@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.1a5cf93b48a1

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 (267) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +11 -0
  11. package/dist/bridge/bridge-state-io.js +50 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +92 -14
  18. package/dist/bridge/bridge.service.js +446 -380
  19. package/dist/bridge/bridge.types.d.ts +21 -0
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  56. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  57. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  58. package/dist/runtime/attempt-process-supervisor.js +12 -6
  59. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  60. package/dist/runtime/docker-engine-probe.js +7 -0
  61. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  62. package/dist/runtime/dotnet-build-outputs.js +402 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  65. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  66. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  67. package/dist/runtime/host-facts.d.ts +2 -1
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +75 -2
  85. package/dist/runtime/host-load-sampler.js +142 -8
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  99. package/dist/runtime/host-pressure-stall.js +48 -1
  100. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  101. package/dist/runtime/host-runtime-contract.js +33 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  103. package/dist/runtime/host-runtime-lease.js +408 -294
  104. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  105. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  106. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  107. package/dist/runtime/host-runtime-promotion.js +355 -14
  108. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  109. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  110. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  111. package/dist/runtime/host-runtime-requirements.js +117 -0
  112. package/dist/runtime/managed-command-teardown.js +5 -16
  113. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  114. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  115. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  116. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  117. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  118. package/dist/runtime/prepared-runtime-identity.js +130 -9
  119. package/dist/runtime/prepared-runtime-readiness.d.ts +13 -1
  120. package/dist/runtime/prepared-runtime-readiness.js +63 -16
  121. package/dist/runtime/runner-settings.d.ts +104 -0
  122. package/dist/runtime/runner-settings.js +236 -0
  123. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  124. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  125. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  126. package/dist/sandbox/host-capacity-broker.js +336 -0
  127. package/dist/sandbox/managed-branch.d.ts +13 -0
  128. package/dist/sandbox/managed-branch.js +90 -0
  129. package/dist/sandbox/provider-auth/codex.js +11 -11
  130. package/dist/sandbox/runtime.d.ts +10 -1
  131. package/dist/sandbox/runtime.js +47 -8
  132. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  133. package/dist/sandbox/sandbox-cgroups.js +42 -0
  134. package/dist/session/architect-waits.d.ts +2 -0
  135. package/dist/session/architect-waits.js +138 -0
  136. package/dist/session/managed-attempt-tools.d.ts +2 -7
  137. package/dist/session/managed-attempt-tools.js +207 -121
  138. package/dist/session/managed-build-coordinator.d.ts +16 -0
  139. package/dist/session/managed-build-coordinator.js +10 -0
  140. package/dist/session/managed-build-receipt.d.ts +5 -0
  141. package/dist/session/managed-build-receipt.js +8 -3
  142. package/dist/session/managed-command-host-load.d.ts +47 -0
  143. package/dist/session/managed-command-host-load.js +83 -0
  144. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  145. package/dist/session/mcp-argument-coercion.js +121 -0
  146. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  147. package/dist/session/phase-completion.artifacts.js +96 -26
  148. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  149. package/dist/session/phase-completion.command-validation.js +77 -0
  150. package/dist/session/phase-completion.d.ts +12 -0
  151. package/dist/session/phase-completion.helpers.js +13 -12
  152. package/dist/session/phase-completion.js +5 -0
  153. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  154. package/dist/session/phase-completion.mcp-args.js +156 -0
  155. package/dist/session/phase-completion.prompts.js +6 -1
  156. package/dist/session/phase-completion.runtime.d.ts +5 -11
  157. package/dist/session/phase-completion.runtime.js +91 -215
  158. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  159. package/dist/session/phase-completion.schema-parts.js +188 -0
  160. package/dist/session/phase-completion.schemas.d.ts +3 -3
  161. package/dist/session/phase-completion.schemas.js +208 -231
  162. package/dist/session/phase-completion.validation.d.ts +2 -3
  163. package/dist/session/phase-completion.validation.js +49 -93
  164. package/dist/session/pre-publication-host-load.d.ts +27 -0
  165. package/dist/session/pre-publication-host-load.js +111 -0
  166. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  167. package/dist/session/pre-publication-native-postgres.js +111 -0
  168. package/dist/session/pre-publication-pass.d.ts +61 -0
  169. package/dist/session/pre-publication-pass.js +148 -0
  170. package/dist/session/pre-publication-process.d.ts +3 -0
  171. package/dist/session/pre-publication-process.js +31 -19
  172. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  173. package/dist/session/pre-publication-step-execution.js +50 -0
  174. package/dist/session/pre-publication-validation.d.ts +37 -21
  175. package/dist/session/pre-publication-validation.js +221 -182
  176. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  177. package/dist/session/provider-cli/claude-background-work.js +181 -0
  178. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  179. package/dist/session/provider-cli/host-build-lock.js +30 -0
  180. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  181. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  182. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  183. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  184. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  185. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  186. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  187. package/dist/session/provider-cli/provider-cli.merge-integrity.js +28 -8
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  189. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  191. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  192. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  193. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  194. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  195. package/dist/session/provider-cli/provider-cli.service.js +98 -173
  196. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  197. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  198. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  199. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  200. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  201. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  202. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  203. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  204. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  205. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  206. package/dist/session/provider-cli/provider-output-state.js +6 -0
  207. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  208. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  209. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  210. package/dist/session/qa-sidecar-validation.js +28 -0
  211. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  212. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  213. package/dist/session/session-redaction.js +31 -181
  214. package/dist/session/session.base.d.ts +9 -1
  215. package/dist/session/session.service.d.ts +15 -2
  216. package/dist/session/session.service.js +246 -88
  217. package/dist/session/session.types.d.ts +4 -0
  218. package/dist/session/session.types.js +7 -7
  219. package/dist/session/sidecar-json-shape.d.ts +31 -0
  220. package/dist/session/sidecar-json-shape.js +217 -0
  221. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  222. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  223. package/dist/shared/fs/file-identity.d.ts +10 -0
  224. package/dist/shared/fs/file-identity.js +15 -0
  225. package/dist/shared/fs/replace-file.d.ts +7 -0
  226. package/dist/shared/fs/replace-file.js +33 -0
  227. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  228. package/dist/shared/process/host-process-recovery.js +23 -3
  229. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  230. package/dist/shared/process/host-process-supervisor.js +67 -15
  231. package/dist/shared/process/process-tree.d.ts +52 -0
  232. package/dist/shared/process/process-tree.js +144 -0
  233. package/dist/shared/process/process.d.ts +67 -0
  234. package/dist/shared/process/process.js +213 -11
  235. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  236. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  237. package/dist/shared/process/windows-launch.d.ts +18 -0
  238. package/dist/shared/process/windows-launch.js +68 -0
  239. package/dist/shared/provider-capabilities.js +14 -7
  240. package/dist/version.d.ts +1 -1
  241. package/dist/version.js +1 -1
  242. package/dist/worktree/dependency-warmer.d.ts +25 -0
  243. package/dist/worktree/dependency-warmer.js +46 -10
  244. package/dist/worktree/orphan-relink.d.ts +19 -0
  245. package/dist/worktree/orphan-relink.js +106 -0
  246. package/dist/worktree/wip-git.d.ts +42 -0
  247. package/dist/worktree/wip-git.js +139 -0
  248. package/dist/worktree/wip-refs.d.ts +77 -0
  249. package/dist/worktree/wip-refs.js +146 -0
  250. package/dist/worktree/wip-restore.d.ts +46 -0
  251. package/dist/worktree/wip-restore.js +280 -0
  252. package/dist/worktree/wip-snapshot.d.ts +53 -0
  253. package/dist/worktree/wip-snapshot.js +270 -0
  254. package/dist/worktree/worktree-inputs.d.ts +8 -0
  255. package/dist/worktree/worktree-inputs.js +134 -0
  256. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  257. package/dist/worktree/worktree-origin-sync.js +128 -0
  258. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  259. package/dist/worktree/worktree-wip-events.js +115 -0
  260. package/dist/worktree/worktree-wip.d.ts +51 -0
  261. package/dist/worktree/worktree-wip.js +190 -0
  262. package/dist/worktree/worktree.base.d.ts +7 -1
  263. package/dist/worktree/worktree.service.d.ts +36 -5
  264. package/dist/worktree/worktree.service.js +126 -155
  265. package/dist/worktree/worktree.types.d.ts +42 -0
  266. package/package.json +2 -2
  267. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -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,9 +73,11 @@ 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
- let started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
80
+ const started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
67
81
  runtimeStarted = true;
68
82
  const discovery = started.runtimeContract.discovery;
69
83
  if (!hostRuntimeParallelEligible(started.runtimeContract)) {
@@ -71,28 +85,14 @@ 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(),
77
92
  };
78
93
  }
79
94
  else {
80
- assertReadinessProbeStartupBudget(request.expiresAt);
81
- started = await this.hostRuntime.startConfiguredProject(request.requestId, request.fencingToken, signal);
82
- const requiredPorts = configuredLaunchPortNames(started.runtimeContract);
83
- const verifiedPorts = started.lease.resources.ports.map(port => port.name);
84
- const verified = requiredPorts.length > 0 && requiredPorts.every(name => verifiedPorts.includes(name));
85
- result = verified
86
- ? {
87
- status: "parallel_ready",
88
- runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
89
- runtimeContractSource: started.runtimeContract.source,
90
- reasonCode: null,
91
- reasonMessage: null,
92
- qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
93
- checkedAt: new Date().toISOString(),
94
- }
95
- : failedProbe("host_runtime_probe_unverified", "The application did not prove ownership and readiness on every Forge-assigned port.");
95
+ result = await this.probeConfiguredProject(this.hostRuntime, request, started, signal);
96
96
  }
97
97
  }
98
98
  catch (error) {
@@ -174,6 +174,7 @@ export class BridgeSessionService {
174
174
  let worktree = null;
175
175
  let hostSingletonKeys = null;
176
176
  let hostLease = null;
177
+ let succeeded = false;
177
178
  try {
178
179
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
179
180
  const capacity = this.hostRuntime.snapshot?.() ?? null;
@@ -248,7 +249,10 @@ export class BridgeSessionService {
248
249
  qaRework: dispatch.qaRework,
249
250
  warmPathOverrides: dispatch.warmPathOverrides,
250
251
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
251
- preserveExistingState: Boolean(dispatch.session.resumedFromSessionId)
252
+ preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
253
+ sessionId: dispatch.session.id,
254
+ ...preparedAttemptOwner(dispatch),
255
+ signal,
252
256
  });
253
257
  }
254
258
  catch (error) {
@@ -264,6 +268,7 @@ export class BridgeSessionService {
264
268
  : `Prepared worktree ${worktree.branchName}.`,
265
269
  eventType: dispatch.session.resumedFromSessionId ? "worktree_reattached" : "worktree_prepared"
266
270
  });
271
+ await emitWorktreePreparedEvents(worktree, emit);
267
272
  if ((worktree.hydratedPriorPhaseArtifactCount ?? 0) > 0) {
268
273
  await emit({
269
274
  role: "runner",
@@ -326,7 +331,100 @@ export class BridgeSessionService {
326
331
  });
327
332
  }
328
333
  }
334
+ // The stack was built and launched from this workspace state. Pre-publication
335
+ // validation restarts it when the provider has changed the source since.
336
+ let refreshRuntimeEnvironment;
337
+ const hostRuntime = this.hostRuntime;
338
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
339
+ && hostLease.executionClass === "managed_runtime"
340
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
341
+ const worktreePath = worktree.worktreePath;
342
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
343
+ const fencingToken = dispatch.lease.fencingToken;
344
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
345
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
346
+ .catch(() => null);
347
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
348
+ let restartPending = false;
349
+ refreshRuntimeEnvironment = async (refreshSignal) => {
350
+ // A late violation stopped the stack: fail this validation pass rather than run it against closed ports.
351
+ this.throwIfAbortedOrIsolationViolated(undefined, dispatch, hostLease);
352
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
353
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
354
+ return null;
355
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
356
+ // only when both states were read: an unreadable baseline is not a workspace change.
357
+ const comparable = launchFingerprint !== null && current !== null;
358
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
359
+ const causes = [
360
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
361
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
362
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
363
+ ];
364
+ const reason = causes[0] ?? "workspace_changed";
365
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
366
+ await emitLifecycle({
367
+ role: "runner",
368
+ kind: "checkpoint",
369
+ content: reason === "workspace_changed"
370
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
371
+ : reason === "previous_restart_incomplete"
372
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
373
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
374
+ eventType: "host_runtime_restart_started",
375
+ data: JSON.stringify({
376
+ reason,
377
+ causes,
378
+ changes,
379
+ head_sha: current?.headSha ?? null,
380
+ merge_in_progress: Boolean(current?.mergeHead),
381
+ }),
382
+ });
383
+ restartPending = true;
384
+ let restarted;
385
+ try {
386
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
387
+ await emitLifecycle({
388
+ role: "runner",
389
+ kind: "checkpoint",
390
+ content: checkpoint.message,
391
+ eventType: checkpoint.code,
392
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
393
+ });
394
+ });
395
+ }
396
+ catch (error) {
397
+ await emitLifecycle({
398
+ role: "runner",
399
+ kind: "error",
400
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
401
+ eventType: "host_runtime_restart_failed",
402
+ data: JSON.stringify({ reason, causes, changes }),
403
+ }).catch(() => undefined);
404
+ throw error;
405
+ }
406
+ hostLease = restarted;
407
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
408
+ // keep the pre-restart reading, which is null when it could not be collected; a null
409
+ // baseline never matches, so every later pass would restart and rotate ports again.
410
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
411
+ restartPending = false;
412
+ await emitLifecycle({
413
+ role: "runner",
414
+ kind: "checkpoint",
415
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
416
+ eventType: "host_runtime_restarted",
417
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
418
+ });
419
+ return { environment: restarted.environment, reason, changes };
420
+ };
421
+ }
329
422
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
423
+ const providerEnvironment = {
424
+ runtimeEnvironment: hostLease?.environment,
425
+ // Only the completion MCP server gets these: its managed commands share the host ledger.
426
+ hostLoadEnvironment: hostLease ? this.hostRuntime?.hostLoadChildEnvironment?.() : undefined,
427
+ };
330
428
  if (dispatch.draft) {
331
429
  throwIfAborted(signal);
332
430
  const processRunner = hostLease && dispatch.sandbox
@@ -335,22 +433,23 @@ export class BridgeSessionService {
335
433
  const run = await this.providerCli.runDraft({
336
434
  dispatch: providerDispatch,
337
435
  worktree,
338
- runtimeEnvironment: hostLease?.environment,
436
+ ...providerEnvironment,
339
437
  processRunner,
340
438
  emit,
341
439
  signal
342
440
  });
343
- throwIfAborted(signal);
441
+ this.throwIfAbortedOrIsolationViolated(signal, dispatch, hostLease);
344
442
  const draftArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
345
- return redactRunOnceResultPacket({
346
- schemaVersion: 2,
347
- exitCode: 0,
348
- summary: run.summary,
443
+ // Redaction can throw (a secret in a structural field); only a returned result is a success.
444
+ const draftResult = redactRunOnceResultPacket({
445
+ schemaVersion: 2, exitCode: 0, summary: run.summary,
349
446
  events,
350
447
  spec: run.spec ?? null,
351
448
  artifact: run.artifact ?? null,
352
449
  artifacts: draftArtifacts
353
450
  }, redactionSecrets);
451
+ succeeded = true;
452
+ return draftResult;
354
453
  }
355
454
  throwIfAborted(signal);
356
455
  const lane = dispatch.execution.lane.trim().toLowerCase();
@@ -363,10 +462,13 @@ export class BridgeSessionService {
363
462
  const context = {
364
463
  dispatch: providerDispatch,
365
464
  worktree,
366
- runtimeEnvironment: hostLease?.environment,
465
+ ...providerEnvironment,
367
466
  processRunner: hostLease && dispatch.sandbox
368
467
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
369
468
  : undefined,
469
+ ...(refreshRuntimeEnvironment && hostLease
470
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
471
+ : {}),
370
472
  emit,
371
473
  signal
372
474
  };
@@ -391,12 +493,10 @@ export class BridgeSessionService {
391
493
  }
392
494
  throw error;
393
495
  }
394
- throwIfAborted(signal);
496
+ this.throwIfAbortedOrIsolationViolated(signal, dispatch, hostLease);
395
497
  const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
396
- return redactRunOnceResultPacket({
397
- schemaVersion: 2,
398
- exitCode: 0,
399
- summary: run.summary,
498
+ const result = redactRunOnceResultPacket({
499
+ schemaVersion: 2, exitCode: 0, summary: run.summary,
400
500
  resultCommitSha: run.resultCommitSha ?? null,
401
501
  publishedCommitSha: run.publishedCommitSha ?? null,
402
502
  events,
@@ -404,72 +504,102 @@ export class BridgeSessionService {
404
504
  artifact: run.artifact ?? null,
405
505
  artifacts: phaseArtifacts
406
506
  }, redactionSecrets);
507
+ succeeded = true;
508
+ return result;
407
509
  }
408
510
  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();
511
+ await this.releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle);
512
+ if (worktree) {
513
+ await settleWorktree(this.worktrees, worktree, sessionWipOutcome(signal, events, succeeded), signal, emitLifecycle);
514
+ }
515
+ }
516
+ }
517
+ /** Launches a parallel-eligible probe's project, unless its contract is quarantined and so could never earn proof. */
518
+ async probeConfiguredProject(hostRuntime, request, started, signal) {
519
+ if (await hostRuntime.promotionQuarantined?.(request.repoId, hostRuntimeContractFingerprint(started.runtimeContract))) {
520
+ // Not launched; the server retries on its backoff, and the check passes once the quarantine expires.
521
+ return failedProbe("host_runtime_isolation_quarantined", "The runtime contract is quarantined after a recent isolation violation, so it was not probed; its runs stay serialized.");
522
+ }
523
+ assertReadinessProbeStartupBudget(request.expiresAt);
524
+ let isolationDetail = null;
525
+ const launched = await hostRuntime.startConfiguredProject(request.requestId, request.fencingToken, signal, async (checkpoint) => {
526
+ if (checkpoint.code === "host_runtime_isolation_serialized")
527
+ isolationDetail = checkpoint.message;
528
+ });
529
+ return configuredProbeResult(launched, isolationDetail);
530
+ }
531
+ /** A late isolation violation stopped the attempt's project in the background: fail rather than report success. */
532
+ throwIfAbortedOrIsolationViolated(signal, dispatch, hostLease) {
533
+ throwIfAborted(signal);
534
+ const violation = hostLease && dispatch.sandbox
535
+ ? this.hostRuntime?.isolationViolation?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken)
536
+ : null;
537
+ if (violation)
538
+ throw violation;
539
+ }
540
+ /** Reports the provider's peak memory and releases the attempt's host runtime lease. */
541
+ async releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle) {
542
+ if (hostLease && dispatch.sandbox) {
543
+ const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
544
+ if (providerMemory) {
430
545
  await emitLifecycle({
431
546
  role: "runner",
432
547
  kind: "checkpoint",
433
- content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
434
- eventType: "sandbox_teardown_started",
435
- occurredAt: teardownAt,
548
+ content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
549
+ eventType: "sandbox_peak_memory_observed",
550
+ occurredAt: providerMemory.observedAt,
551
+ data: JSON.stringify({
552
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
553
+ sampleCount: providerMemory.sampleCount,
554
+ source: providerMemory.source,
555
+ containers: [{
556
+ role: "agent",
557
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
558
+ }],
559
+ }),
436
560
  }).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) {
561
+ }
562
+ const teardownAt = new Date().toISOString();
563
+ await emitLifecycle({
564
+ role: "runner",
565
+ kind: "checkpoint",
566
+ content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
567
+ eventType: "sandbox_teardown_started",
568
+ occurredAt: teardownAt,
569
+ }).catch(() => undefined);
570
+ try {
571
+ const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
572
+ if (!released) {
459
573
  await emitLifecycle({
460
574
  role: "runner",
461
575
  kind: "error",
462
- content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
576
+ content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
463
577
  eventType: "teardown_failed",
464
578
  occurredAt: new Date().toISOString(),
465
579
  }).catch(() => undefined);
466
580
  }
581
+ else {
582
+ await emitLifecycle({
583
+ role: "runner",
584
+ kind: "checkpoint",
585
+ content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
586
+ eventType: "sandbox_teardown_completed",
587
+ occurredAt: released.releasedAt,
588
+ }).catch(() => undefined);
589
+ }
467
590
  }
468
- if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
469
- await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
591
+ catch (error) {
592
+ await emitLifecycle({
593
+ role: "runner",
594
+ kind: "error",
595
+ content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
596
+ eventType: "teardown_failed",
597
+ occurredAt: new Date().toISOString(),
598
+ }).catch(() => undefined);
470
599
  }
471
- if (worktree && !isPauseCancellation(signal))
472
- await this.worktrees.release(worktree);
600
+ }
601
+ if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
602
+ await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
473
603
  }
474
604
  }
475
605
  }
@@ -479,10 +609,6 @@ function failureMessage(error) {
479
609
  function formatMemoryBytes(bytes) {
480
610
  return `${(bytes / (1024 ** 2)).toFixed(bytes >= 1024 ** 3 ? 0 : 1)} MiB`;
481
611
  }
482
- function isPauseCancellation(signal) {
483
- return signal?.aborted === true
484
- && String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
485
- }
486
612
  function readinessProbeDispatch(request) {
487
613
  return {
488
614
  schemaVersion: 2,
@@ -562,6 +688,31 @@ function readinessProbeDispatch(request) {
562
688
  artifacts: [],
563
689
  };
564
690
  }
691
+ /**
692
+ * A probe is parallel_ready only when every configured port proved readiness and the launch earned the
693
+ * parallel promotion, which an isolation violation or a quarantined contract withholds while it runs.
694
+ */
695
+ function configuredProbeResult(started, isolationDetail) {
696
+ const requiredPorts = configuredLaunchPortNames(started.runtimeContract);
697
+ const verifiedPorts = started.lease.resources.ports.map(port => port.name);
698
+ if (requiredPorts.length === 0 || !requiredPorts.every(name => verifiedPorts.includes(name))) {
699
+ return failedProbe("host_runtime_probe_unverified", "The application did not prove ownership and readiness on every Forge-assigned port.");
700
+ }
701
+ if (started.environment.FORGE_HOST_CONCURRENCY !== "host_parallel_safe") {
702
+ return failedProbe("host_runtime_isolation_violation", isolationDetail
703
+ ?? "The application served every Forge-assigned port, but did not earn parallel-safety proof for this runtime contract.");
704
+ }
705
+ return {
706
+ status: "parallel_ready",
707
+ runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
708
+ runtimeContractSource: started.runtimeContract.source,
709
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
710
+ reasonCode: null,
711
+ reasonMessage: null,
712
+ qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
713
+ checkedAt: new Date().toISOString(),
714
+ };
715
+ }
565
716
  function failedProbe(reasonCode, reasonMessage) {
566
717
  return { status: "failed", reasonCode, reasonMessage, checkedAt: new Date().toISOString() };
567
718
  }
@@ -622,6 +773,13 @@ function throwIfAborted(signal) {
622
773
  throw new Error(String(signal.reason ?? "Dispatch cancelled."));
623
774
  }
624
775
  }
776
+ /** The dispatch attempt a worktree is prepared for: Forge's attempt for its WIP refs, and whose host load it reserves. */
777
+ function preparedAttemptOwner(dispatch) {
778
+ return {
779
+ wipAttempt: dispatch.wipAttempt ?? null,
780
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: runtimeAdmissionPriority(dispatch) },
781
+ };
782
+ }
625
783
  function validateApiKeySecretGrant(dispatch) {
626
784
  if (!dispatch.execution.requiresApiKeySecretGrant) {
627
785
  return;
@@ -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;
@@ -10,6 +11,7 @@ export interface RunOnceDispatchPacket {
10
11
  readonly runtimeIntent: DispatchRuntimeIntent;
11
12
  readonly serverLocal: DispatchServerLocalConfig;
12
13
  readonly sandbox?: DispatchSandboxContext | null;
14
+ readonly wipAttempt?: number | null;
13
15
  readonly pullRequest?: DispatchPullRequestContext | null;
14
16
  readonly apiKeySecretGrant?: ApiKeySecretGrant | null;
15
17
  readonly apiKeySecretGrantHandle?: ApiKeySecretGrantHandle | null;
@@ -546,6 +548,8 @@ export interface HostRuntimeReadinessProbeResult {
546
548
  readonly status: "parallel_ready" | "serialized" | "failed";
547
549
  readonly runtimeContractFingerprint?: string | null;
548
550
  readonly runtimeContractSource?: string | null;
551
+ /** Requirements declared by the probed contract (decision 0013); null when none. */
552
+ readonly runtimeRequirements?: HostRuntimeRequirements | null;
549
553
  readonly reasonCode?: string | null;
550
554
  readonly reasonMessage?: string | null;
551
555
  readonly qaAppLaunchTarget?: HostRuntimeReadinessQaLaunchTarget | null;
@@ -28,6 +28,7 @@ export function parseRunOnceDispatchPacket(value) {
28
28
  runtimeIntent: parseRuntimeIntent(packet.runtimeIntent),
29
29
  serverLocal: parseServerLocal(packet.serverLocal),
30
30
  sandbox: parseSandbox(packet.sandbox, schemaVersion),
31
+ wipAttempt: optionalNonNegativeInteger(packet, "wipAttempt"),
31
32
  pullRequest: parsePullRequest(packet.pullRequest),
32
33
  apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant),
33
34
  apiKeySecretGrantHandle: parseApiKeySecretGrantHandle(packet.apiKeySecretGrantHandle),
@@ -469,19 +470,19 @@ function unvalidatedFailureFactsForCode(code, source) {
469
470
  if (code === "bridge.unavailable") {
470
471
  return facts(code, "transport", "offer", source, "retryable", "retry_dispatch");
471
472
  }
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)) {
473
+ 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
474
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
474
475
  }
475
476
  if (["bridge.lease_retry_exhausted", "bridge.capacity_wait_exhausted"].includes(code)) {
476
477
  return facts(code, "resource", "offer", source, "non_retryable", "inspect_failure");
477
478
  }
478
- if (["prepublication_infrastructure_failed", "prepublication_capability_unavailable"].includes(code)) {
479
+ if (["prepublication_infrastructure_failed", "prepublication_capability_unavailable", "host_capacity_timeout", "host_capacity_token_fenced", "host_capacity_ledger_unavailable"].includes(code)) {
479
480
  return facts(code, "resource", "validation", source, "retryable", "retry_with_policy");
480
481
  }
481
482
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
482
483
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
484
  }
484
- if (code === "comment_repair_changed_files_mismatch") {
485
+ if (["comment_repair_changed_files_mismatch", "runner_result_sidecar_malformed"].includes(code)) {
485
486
  return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
487
  }
487
488
  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)) {
@@ -496,7 +497,7 @@ function unvalidatedFailureFactsForCode(code, source) {
496
497
  if (code === "provider_configuration_invalid") {
497
498
  return facts(code, "provider", "prepare", source, "non_retryable", "fix_environment");
498
499
  }
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_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
500
+ 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)) {
500
501
  return facts(code, "resource", "prepare", source, "retryable", "retry_dispatch");
501
502
  }
502
503
  if (code === "host_runtime_project_start_failed") {
@@ -525,7 +526,7 @@ function unvalidatedFailureFactsForCode(code, source) {
525
526
  if (code === "provider_completion_tool_missing") {
526
527
  return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
527
528
  }
528
- if (code === "provider_terminated_at_turn_ceiling") {
529
+ if (["provider_terminated_at_turn_ceiling", "provider_turn_ended_with_background_work"].includes(code)) {
529
530
  return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
530
531
  }
531
532
  if (code === "provider_context_window_exhausted") {
@@ -1373,9 +1374,8 @@ function optionalPositiveInteger(source, key) {
1373
1374
  }
1374
1375
  function optionalNonNegativeInteger(source, key) {
1375
1376
  const value = source[key];
1376
- if (value === undefined || value === null) {
1377
+ if (value === undefined || value === null)
1377
1378
  return null;
1378
- }
1379
1379
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1380
1380
  throw new Error(`${key} must be a non-negative integer when provided.`);
1381
1381
  }
@@ -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;