@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.83728c550770

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 (157) hide show
  1. package/README.md +25 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +84 -2
  4. package/dist/bridge/bridge.service.js +357 -12
  5. package/dist/bridge/bridge.types.d.ts +22 -0
  6. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  7. package/dist/bridge/dispatch-result-outbox.js +31 -6
  8. package/dist/bridge/local-yield-flag.d.ts +6 -0
  9. package/dist/bridge/local-yield-flag.js +34 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  11. package/dist/bridge/runner-host-capabilities.js +4 -0
  12. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  13. package/dist/bridge/test-postgres-capability.js +120 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +18 -0
  24. package/dist/cli/cli.service.d.ts +5 -0
  25. package/dist/cli/cli.service.js +62 -4
  26. package/dist/cli/local-config.d.ts +2 -0
  27. package/dist/cli/local-config.js +7 -1
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  30. package/dist/runtime/attempt-process-supervisor.js +50 -0
  31. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  32. package/dist/runtime/host-database-capability-boundary.js +1 -0
  33. package/dist/runtime/host-facts.d.ts +35 -0
  34. package/dist/runtime/host-facts.js +95 -0
  35. package/dist/runtime/host-load-admission.d.ts +60 -0
  36. package/dist/runtime/host-load-admission.js +99 -0
  37. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  38. package/dist/runtime/host-load-child-environment.js +67 -0
  39. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  40. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  41. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  42. package/dist/runtime/host-load-governor-config.js +76 -0
  43. package/dist/runtime/host-load-governor.d.ts +174 -0
  44. package/dist/runtime/host-load-governor.js +541 -0
  45. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  46. package/dist/runtime/host-load-ledger-lock.js +185 -0
  47. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  48. package/dist/runtime/host-load-runtime-settings.js +78 -0
  49. package/dist/runtime/host-load-sampler.d.ts +126 -0
  50. package/dist/runtime/host-load-sampler.js +232 -0
  51. package/dist/runtime/host-load-step-class.d.ts +68 -0
  52. package/dist/runtime/host-load-step-class.js +106 -0
  53. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  54. package/dist/runtime/host-load-step-reaper.js +95 -0
  55. package/dist/runtime/host-load-step-run.d.ts +73 -0
  56. package/dist/runtime/host-load-step-run.js +102 -0
  57. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  58. package/dist/runtime/host-load-token-ledger.js +421 -0
  59. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  60. package/dist/runtime/host-pressure-stall.js +168 -0
  61. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  62. package/dist/runtime/host-runtime-contract.js +6 -1
  63. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  64. package/dist/runtime/host-runtime-lease.js +334 -19
  65. package/dist/runtime/host-runtime-promotion.js +12 -0
  66. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  67. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  68. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  69. package/dist/runtime/host-runtime-requirements.js +117 -0
  70. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  71. package/dist/runtime/managed-command-teardown.js +607 -0
  72. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  73. package/dist/runtime/playwright-browser-cache.js +227 -0
  74. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  75. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  76. package/dist/runtime/runner-settings.d.ts +100 -0
  77. package/dist/runtime/runner-settings.js +214 -0
  78. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  79. package/dist/sandbox/host-capacity-broker.js +315 -0
  80. package/dist/sandbox/runtime.d.ts +10 -1
  81. package/dist/sandbox/runtime.js +45 -2
  82. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  83. package/dist/sandbox/sandbox-cgroups.js +42 -0
  84. package/dist/session/managed-attempt-tools.d.ts +27 -0
  85. package/dist/session/managed-attempt-tools.js +356 -40
  86. package/dist/session/managed-build-coordinator.d.ts +1 -1
  87. package/dist/session/managed-build-coordinator.js +4 -1
  88. package/dist/session/managed-command-host-load.d.ts +45 -0
  89. package/dist/session/managed-command-host-load.js +82 -0
  90. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  91. package/dist/session/mcp-argument-coercion.js +121 -0
  92. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  93. package/dist/session/phase-completion.artifacts.js +98 -25
  94. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  95. package/dist/session/phase-completion.command-validation.js +77 -0
  96. package/dist/session/phase-completion.d.ts +4 -0
  97. package/dist/session/phase-completion.helpers.js +13 -12
  98. package/dist/session/phase-completion.js +4 -0
  99. package/dist/session/phase-completion.prompts.js +6 -1
  100. package/dist/session/phase-completion.runtime.d.ts +5 -3
  101. package/dist/session/phase-completion.runtime.js +70 -35
  102. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  103. package/dist/session/phase-completion.schema-parts.js +188 -0
  104. package/dist/session/phase-completion.schemas.d.ts +3 -3
  105. package/dist/session/phase-completion.schemas.js +184 -209
  106. package/dist/session/phase-completion.validation.d.ts +2 -3
  107. package/dist/session/phase-completion.validation.js +46 -92
  108. package/dist/session/pre-publication-host-load.d.ts +27 -0
  109. package/dist/session/pre-publication-host-load.js +111 -0
  110. package/dist/session/pre-publication-process.d.ts +23 -0
  111. package/dist/session/pre-publication-process.js +109 -0
  112. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  113. package/dist/session/pre-publication-skipped-tests.js +109 -0
  114. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  115. package/dist/session/pre-publication-step-execution.js +49 -0
  116. package/dist/session/pre-publication-validation.d.ts +9 -9
  117. package/dist/session/pre-publication-validation.js +48 -112
  118. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  119. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  120. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  121. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  122. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  123. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  124. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  125. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  126. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  127. package/dist/session/provider-cli/provider-cli.service.js +244 -36
  128. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  129. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  130. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  131. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  132. package/dist/session/provider-cli/provider-output-state.js +9 -0
  133. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  134. package/dist/session/publishable-worktree-changes.js +193 -0
  135. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  136. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  137. package/dist/session/session.base.d.ts +9 -1
  138. package/dist/session/session.service.d.ts +9 -2
  139. package/dist/session/session.service.js +120 -5
  140. package/dist/session/session.types.d.ts +3 -0
  141. package/dist/session/session.types.js +15 -3
  142. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  143. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  144. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  145. package/dist/shared/process/host-process-supervisor.js +1 -1
  146. package/dist/shared/process/process-tree.d.ts +52 -0
  147. package/dist/shared/process/process-tree.js +144 -0
  148. package/dist/shared/process/process.d.ts +67 -0
  149. package/dist/shared/process/process.js +213 -11
  150. package/dist/version.d.ts +1 -1
  151. package/dist/version.js +1 -1
  152. package/dist/worktree/dependency-warmer.d.ts +25 -0
  153. package/dist/worktree/dependency-warmer.js +46 -10
  154. package/dist/worktree/worktree.service.d.ts +10 -1
  155. package/dist/worktree/worktree.service.js +42 -2
  156. package/dist/worktree/worktree.types.d.ts +7 -0
  157. package/package.json +1 -1
@@ -2,14 +2,18 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { RepositoryCoordinatorLock } from "../../sandbox/repository-lock.js";
4
4
  import { GitClient } from "../../shared/git/git.js";
5
+ import { HostPortCollisionError } from "../../runtime/host-port-broker.js";
6
+ import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
7
+ import { sandboxHostLoadGateFromEnvironment } from "../sandbox-host-capacity-gate.js";
5
8
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
6
9
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
7
10
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
8
11
  import { ForgeFailureError } from "../session.types.js";
9
- import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, stagePublishableWorktreeChanges, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
12
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
13
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
10
14
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
11
15
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
12
- import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
16
+ import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
13
17
  import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
14
18
  import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
15
19
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
@@ -68,12 +72,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
68
72
  const claimed = [...new Set(claimedChangedFiles)].sort();
69
73
  const actual = [...new Set(normalizedActual)].sort();
70
74
  if (hasFixedDisposition && actual.length === 0) {
71
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
75
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
72
76
  }
73
77
  if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
74
- throw new Error("Comment repair changed_files must exactly match the publishable staged source diff.");
78
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
79
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
75
80
  }
76
81
  }
82
+ /**
83
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
84
+ * published commit; otherwise the thread would be resolved without its fix. That covers
85
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
86
+ */
87
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
88
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
89
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
90
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
91
+ ]));
92
+ const payload = JSON.parse(artifact.verdictJson);
93
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
94
+ const fixed = dispositions.flatMap(value => {
95
+ const record = value;
96
+ if (record.disposition !== "fixed")
97
+ return [];
98
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
99
+ const findingPath = findingPaths.get(identity);
100
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
101
+ });
102
+ if (fixed.length === 0)
103
+ return;
104
+ const unpublished = new Set([
105
+ ...changeSet.excluded.map(normalizeChangedFilePath),
106
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
107
+ ]);
108
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
109
+ if (dropped.length > 0) {
110
+ throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
111
+ }
112
+ }
113
+ function commentRepairChangedFilesMismatch(message) {
114
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
115
+ }
116
+ function formatChangedFilesDelta(missing, unexpected) {
117
+ const parts = [
118
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
119
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
120
+ ].filter(Boolean);
121
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
122
+ }
77
123
  async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
78
124
  const payload = JSON.parse(artifact.verdictJson);
79
125
  const claimedRecords = Array.isArray(payload.changed_files)
@@ -90,11 +136,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
90
136
  const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
137
  const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
92
138
  if (hasFixedDisposition && authoritativePaths.length === 0) {
93
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
139
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
94
140
  }
95
141
  for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
96
142
  if (baselinePath && !authoritative.has(baselinePath)) {
97
- throw new Error(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
143
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
98
144
  }
99
145
  }
100
146
  payload.changed_files = authoritativePaths.map(filePath => {
@@ -170,16 +216,20 @@ function providerOwnsBranchPublication(context) {
170
216
  return context.dispatch.sandbox?.executionMode !== "docker";
171
217
  }
172
218
  function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
219
+ const hostLoadOwner = {
220
+ dispatchAttemptId: context.dispatch.sandbox?.dispatchAttemptId ?? null,
221
+ priority: runtimeAdmissionPriority(context.dispatch),
222
+ };
173
223
  if (context.processRunner)
174
- return { baselineRevision, environment, processRunner: context.processRunner };
224
+ return { baselineRevision, environment, processRunner: context.processRunner, hostLoadOwner };
175
225
  if (context.dispatch.sandbox?.executionMode !== "docker")
176
- return { baselineRevision, environment };
226
+ return { baselineRevision, environment, hostLoadOwner };
177
227
  const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
178
228
  const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
179
229
  if (observedSandboxId !== expectedSandboxId) {
180
230
  throw new ForgeFailureError("prepublication_execution_scope_invalid", `prepublication_execution_scope_invalid: Docker attempt ${expectedSandboxId} has no runner proven to execute inside that sandbox.`, "bridge");
181
231
  }
182
- return { baselineRevision, environment, processRunner: defaultRunner };
232
+ return { baselineRevision, environment, processRunner: defaultRunner, hostLoadOwner };
183
233
  }
184
234
  function remoteTrackingRefspec(branchName) {
185
235
  return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
@@ -389,7 +439,8 @@ export class ManagedVerificationProgressEmitter {
389
439
  }
390
440
  }
391
441
  function isManagedVerificationNonterminal(status) {
392
- return status === "starting" || status === "running" || status === "waiting_for_build_slot";
442
+ return status === "starting" || status === "running" || status === "waiting_for_build_slot"
443
+ || status === "waiting_for_host_capacity";
393
444
  }
394
445
  async function parseManagedVerificationSnapshot(receiptPath) {
395
446
  try {
@@ -429,10 +480,17 @@ class ProviderToolActivityHeartbeat {
429
480
  emit;
430
481
  intervalMs;
431
482
  timer = null;
483
+ /** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
484
+ isToolCallInFlight = () => this.outputState.hasActiveToolCall;
485
+ /** Forgets tool calls a previous generation left open; called before every relaunch. */
486
+ startGeneration = () => this.outputState.resetActiveToolCalls();
432
487
  constructor(outputState, emit, intervalMs) {
433
488
  this.outputState = outputState;
434
489
  this.emit = emit;
435
490
  this.intervalMs = intervalMs;
491
+ // Each heartbeat watches one provider generation. Calls an earlier generation left
492
+ // open died with it; inheriting them would hold the new generation's timers forever.
493
+ this.outputState.resetActiveToolCalls();
436
494
  }
437
495
  async consume(line) {
438
496
  const events = this.outputState.consume(line);
@@ -514,7 +572,12 @@ export class ProcessBackedProviderCliService {
514
572
  providerToolHeartbeatIntervalMs;
515
573
  publicationCoordinator;
516
574
  prePublicationValidator;
517
- constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()), prePublicationValidator = new PrePublicationValidator()) {
575
+ constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
576
+ // The Docker sandbox worker (`forge` run-once via ForgeBridgeCliService) builds
577
+ // this default. A container cannot reach the host ledger, so when the host
578
+ // bridge enabled it, its steps ask the bridge for tokens over the sandbox
579
+ // channel (decision 0013); elsewhere the gate is absent and validation is ungated.
580
+ prePublicationValidator = new PrePublicationValidator(undefined, undefined, undefined, sandboxHostLoadGateFromEnvironment())) {
518
581
  this.processRunner = processRunner;
519
582
  this.git = git;
520
583
  this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
@@ -533,7 +596,7 @@ export class ProcessBackedProviderCliService {
533
596
  await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
534
597
  const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
535
598
  const decomposeDraft = isDecomposeDraftDispatch(dispatch);
536
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment });
599
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
537
600
  const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
538
601
  const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
539
602
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -586,6 +649,7 @@ export class ProcessBackedProviderCliService {
586
649
  args: command.args,
587
650
  cwd: worktree.worktreePath,
588
651
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
652
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
589
653
  stdin: pipePromptToStdin ? providerPrompt : undefined
590
654
  }, {
591
655
  onStarted: async () => {
@@ -596,6 +660,8 @@ export class ProcessBackedProviderCliService {
596
660
  eventType: "provider_cli_started"
597
661
  });
598
662
  },
663
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
664
+ onGenerationStart: toolHeartbeat.startGeneration,
599
665
  onStdoutLine: async (line) => {
600
666
  await toolHeartbeat.consume(line);
601
667
  }
@@ -645,7 +711,7 @@ export class ProcessBackedProviderCliService {
645
711
  await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
646
712
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
647
713
  if (!proposalArtifact) {
648
- throw new Error("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.");
714
+ throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
649
715
  }
650
716
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
651
717
  const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
@@ -668,7 +734,7 @@ export class ProcessBackedProviderCliService {
668
734
  await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
669
735
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
670
736
  if (!proposalArtifact) {
671
- throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
737
+ throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
672
738
  }
673
739
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
674
740
  const draftJson = proposal["draft_json"];
@@ -713,7 +779,7 @@ export class ProcessBackedProviderCliService {
713
779
  const specPath = path.join(metadataRoot, "spec.md");
714
780
  await fs.writeFile(specPath, specBody, "utf8");
715
781
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
716
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
782
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
717
783
  const implementationPrompt = debugCycle
718
784
  ? buildDebugCyclePrompt(dispatch, phase)
719
785
  : developCycle
@@ -755,6 +821,7 @@ export class ProcessBackedProviderCliService {
755
821
  args: command.args,
756
822
  cwd: worktree.worktreePath,
757
823
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
824
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
758
825
  stdin: pipePromptToStdin ? providerPrompt : undefined
759
826
  }, {
760
827
  onStarted: async () => {
@@ -765,6 +832,8 @@ export class ProcessBackedProviderCliService {
765
832
  eventType: "provider_cli_started"
766
833
  });
767
834
  },
835
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
836
+ onGenerationStart: toolHeartbeat.startGeneration,
768
837
  onStdoutLine: async (line) => {
769
838
  await toolHeartbeat.consume(line);
770
839
  }
@@ -806,7 +875,7 @@ export class ProcessBackedProviderCliService {
806
875
  eventType: "worktree_branch_pushed"
807
876
  });
808
877
  }
809
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
878
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
810
879
  for (const artifact of completionArtifacts) {
811
880
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
812
881
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -858,7 +927,7 @@ export class ProcessBackedProviderCliService {
858
927
  const specPath = path.join(metadataRoot, "spec.md");
859
928
  await fs.writeFile(specPath, specBody, "utf8");
860
929
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-lane-command" }) + "\n", "utf8");
861
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment });
930
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
862
931
  const architectPrompt = buildArchitectPrompt(dispatch);
863
932
  const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
864
933
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -893,6 +962,7 @@ export class ProcessBackedProviderCliService {
893
962
  args: command.args,
894
963
  cwd: worktree.worktreePath,
895
964
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
965
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
896
966
  stdin: pipePromptToStdin ? providerPrompt : undefined
897
967
  }, {
898
968
  onStarted: async () => {
@@ -903,6 +973,8 @@ export class ProcessBackedProviderCliService {
903
973
  eventType: "provider_cli_started"
904
974
  });
905
975
  },
976
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
977
+ onGenerationStart: toolHeartbeat.startGeneration,
906
978
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
907
979
  }, context.signal);
908
980
  }
@@ -923,7 +995,7 @@ export class ProcessBackedProviderCliService {
923
995
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
924
996
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
925
997
  if (!architectArtifact) {
926
- throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
998
+ throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
927
999
  }
928
1000
  if (!liveArchitectEvents.hasEmitted()) {
929
1001
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -960,7 +1032,7 @@ export class ProcessBackedProviderCliService {
960
1032
  const specPath = path.join(metadataRoot, "spec.md");
961
1033
  await fs.writeFile(specPath, specBody, "utf8");
962
1034
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
963
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment });
1035
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
964
1036
  const qaPrompt = buildQaPrompt(dispatch, specBody);
965
1037
  const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
966
1038
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -997,6 +1069,7 @@ export class ProcessBackedProviderCliService {
997
1069
  args: command.args,
998
1070
  cwd: worktree.worktreePath,
999
1071
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1072
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1000
1073
  stdin: pipePromptToStdin ? providerPrompt : undefined
1001
1074
  }, {
1002
1075
  onStarted: async () => {
@@ -1007,6 +1080,8 @@ export class ProcessBackedProviderCliService {
1007
1080
  eventType: "provider_cli_started"
1008
1081
  });
1009
1082
  },
1083
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1084
+ onGenerationStart: toolHeartbeat.startGeneration,
1010
1085
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1011
1086
  }, context.signal);
1012
1087
  }
@@ -1026,17 +1101,19 @@ export class ProcessBackedProviderCliService {
1026
1101
  eventType: "provider_cli_completed"
1027
1102
  });
1028
1103
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
1104
+ const lastRun = { result };
1029
1105
  let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1030
1106
  if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1031
1107
  // A headless provider that ends its turn to "wait for a background watcher"
1032
1108
  // exits for good. Resume the same thread instead of failing the session.
1033
- qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
1109
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1034
1110
  }
1035
1111
  if (!qaArtifact) {
1036
1112
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
1037
- throw new Error(verdictOnly
1038
- ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
1039
- : "Provider CLI QA completed but did not call the Forge QA completion tool.");
1113
+ if (verdictOnly) {
1114
+ throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
1115
+ }
1116
+ throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
1040
1117
  }
1041
1118
  await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1042
1119
  if (!liveQaEvents.hasEmitted()) {
@@ -1075,6 +1152,7 @@ export class ProcessBackedProviderCliService {
1075
1152
  const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
1076
1153
  let repairSpec = null;
1077
1154
  let repairEnvironment = context.runtimeEnvironment;
1155
+ let ciRepairSpecPath = null;
1078
1156
  let completionTools = null;
1079
1157
  if (repairChecks) {
1080
1158
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -1085,6 +1163,7 @@ export class ProcessBackedProviderCliService {
1085
1163
  }
1086
1164
  const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
1087
1165
  const specPath = path.join(metadataRoot, "spec.md");
1166
+ ciRepairSpecPath = specPath;
1088
1167
  await fs.writeFile(specPath, specBody, "utf8");
1089
1168
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
1090
1169
  repairSpec = {
@@ -1096,7 +1175,9 @@ export class ProcessBackedProviderCliService {
1096
1175
  };
1097
1176
  const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
1098
1177
  repairEnvironment = readiness.environment;
1099
- completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment });
1178
+ completionTools = await prepareCompletionToolRuntime({
1179
+ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
1180
+ });
1100
1181
  await context.emit({
1101
1182
  role: "runner",
1102
1183
  kind: "checkpoint",
@@ -1111,7 +1192,9 @@ export class ProcessBackedProviderCliService {
1111
1192
  });
1112
1193
  }
1113
1194
  if (addressComments) {
1114
- completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment });
1195
+ completionTools = await prepareCompletionToolRuntime({
1196
+ dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
1197
+ });
1115
1198
  await context.emit({
1116
1199
  role: "runner",
1117
1200
  kind: "checkpoint",
@@ -1149,6 +1232,7 @@ export class ProcessBackedProviderCliService {
1149
1232
  args: command.args,
1150
1233
  cwd: worktree.worktreePath,
1151
1234
  env: providerProcessEnv(dispatch, repairEnvironment),
1235
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1152
1236
  stdin: pipePromptToStdin ? providerPrompt : undefined
1153
1237
  }, {
1154
1238
  onStarted: async () => {
@@ -1160,6 +1244,8 @@ export class ProcessBackedProviderCliService {
1160
1244
  });
1161
1245
  providerStarted = true;
1162
1246
  },
1247
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1248
+ onGenerationStart: toolHeartbeat.startGeneration,
1163
1249
  onStdoutLine: async (line) => {
1164
1250
  await toolHeartbeat.consume(line);
1165
1251
  }
@@ -1194,7 +1280,7 @@ export class ProcessBackedProviderCliService {
1194
1280
  if (repairChecks) {
1195
1281
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1196
1282
  if (!repairArtifact) {
1197
- throw new Error("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.");
1283
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
1198
1284
  }
1199
1285
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1200
1286
  throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
@@ -1202,16 +1288,18 @@ export class ProcessBackedProviderCliService {
1202
1288
  }
1203
1289
  if (addressComments) {
1204
1290
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1291
+ const lastRun = { result };
1205
1292
  if (!repairArtifact) {
1206
1293
  repairArtifact = await this.recoverMissingCommentRepairCompletion({
1207
1294
  context,
1208
1295
  repairEnvironment,
1209
1296
  outputState,
1210
1297
  preparedHeadSha,
1298
+ lastRun,
1211
1299
  });
1212
1300
  }
1213
1301
  if (!repairArtifact) {
1214
- throw new Error("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.");
1302
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
1215
1303
  }
1216
1304
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1217
1305
  throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
@@ -1220,7 +1308,9 @@ export class ProcessBackedProviderCliService {
1220
1308
  }
1221
1309
  let commentRepairBaselineChangedFiles = null;
1222
1310
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1311
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1312
+ commentRepairBaselineChangedFiles = baseline.publishable;
1313
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1314
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1315
  }
1226
1316
  const validationProfile = repairChecks
@@ -1228,6 +1318,7 @@ export class ProcessBackedProviderCliService {
1228
1318
  : addressComments
1229
1319
  ? "comment_repair"
1230
1320
  : "conflict_repair";
1321
+ const readinessSpecPath = ciRepairSpecPath;
1231
1322
  await this.validatePrePublicationWithRecovery({
1232
1323
  context,
1233
1324
  validationProfile,
@@ -1235,9 +1326,15 @@ export class ProcessBackedProviderCliService {
1235
1326
  outputState,
1236
1327
  preparedHeadSha,
1237
1328
  repairScope: "pull_request",
1329
+ ...(readinessSpecPath ? {
1330
+ // The readiness manifest records the attempt URLs; a restart must not leave it pointing at the old stack.
1331
+ onRuntimeEnvironmentRefreshed: async (runtimeEnvironment) => (await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, readinessSpecPath, runtimeEnvironment)).environment,
1332
+ } : {}),
1238
1333
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1334
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1335
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1336
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1337
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1338
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1339
  }
1243
1340
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1311,6 +1408,7 @@ export class ProcessBackedProviderCliService {
1311
1408
  worktree,
1312
1409
  phase: "qa",
1313
1410
  runtimeEnvironment: context.runtimeEnvironment,
1411
+ hostLoadEnvironment: context.hostLoadEnvironment,
1314
1412
  });
1315
1413
  const command = buildProviderCliCommand(recoveryDispatch, {
1316
1414
  worktreePath: worktree.worktreePath,
@@ -1334,13 +1432,19 @@ export class ProcessBackedProviderCliService {
1334
1432
  args: command.args,
1335
1433
  cwd: worktree.worktreePath,
1336
1434
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1435
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1337
1436
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1338
- }, { onStdoutLine: async (line) => await toolHeartbeat.consume(line) }, context.signal);
1437
+ }, {
1438
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line),
1439
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1440
+ onGenerationStart: toolHeartbeat.startGeneration,
1441
+ }, context.signal);
1339
1442
  }
1340
1443
  finally {
1341
1444
  toolHeartbeat.stop();
1342
1445
  await cleanupCompletionTools(completionTools, context.emit);
1343
1446
  }
1447
+ options.lastRun.result = result;
1344
1448
  if (result.exitCode !== 0)
1345
1449
  throw providerCliExitFailure(command.command, result);
1346
1450
  const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
@@ -1397,10 +1501,14 @@ export class ProcessBackedProviderCliService {
1397
1501
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1502
  };
1399
1503
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1504
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1505
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1506
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1507
  "Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
1402
- "Review the current diff and the durable review snapshot, preserve the validation evidence already gathered,",
1403
- "then call forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1508
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1509
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1510
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1511
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1512
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1513
  ].join(" ");
1406
1514
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -1410,6 +1518,7 @@ export class ProcessBackedProviderCliService {
1410
1518
  worktree,
1411
1519
  phase: "comment_repair",
1412
1520
  runtimeEnvironment: repairEnvironment,
1521
+ hostLoadEnvironment: context.hostLoadEnvironment,
1413
1522
  });
1414
1523
  const command = buildProviderCliCommand(recoveryDispatch, {
1415
1524
  worktreePath: worktree.worktreePath,
@@ -1434,6 +1543,7 @@ export class ProcessBackedProviderCliService {
1434
1543
  args: command.args,
1435
1544
  cwd: worktree.worktreePath,
1436
1545
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1546
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1437
1547
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1438
1548
  }, {
1439
1549
  onStarted: async () => {
@@ -1445,6 +1555,8 @@ export class ProcessBackedProviderCliService {
1445
1555
  eventType: "provider_cli_started",
1446
1556
  });
1447
1557
  },
1558
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1559
+ onGenerationStart: toolHeartbeat.startGeneration,
1448
1560
  onStdoutLine: async (line) => {
1449
1561
  await toolHeartbeat.consume(line);
1450
1562
  },
@@ -1466,6 +1578,7 @@ export class ProcessBackedProviderCliService {
1466
1578
  await cleanupCompletionTools(completionTools, context.emit);
1467
1579
  }
1468
1580
  }
1581
+ options.lastRun.result = result;
1469
1582
  if (result.exitCode !== 0)
1470
1583
  throw providerCliExitFailure(command.command, result);
1471
1584
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1485,13 +1598,23 @@ export class ProcessBackedProviderCliService {
1485
1598
  return artifact;
1486
1599
  }
1487
1600
  async validatePrePublicationWithRecovery(options) {
1488
- const { context, validationProfile, repairEnvironment, outputState, preparedHeadSha, repairScope } = options;
1601
+ const { context, validationProfile, outputState, preparedHeadSha, repairScope } = options;
1489
1602
  const { dispatch, worktree } = context;
1490
1603
  const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
1491
- const environment = providerProcessEnv(dispatch, repairEnvironment);
1492
- const validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1604
+ // A runtime restart assigns new ports, so every environment derived from it is refreshed with it.
1605
+ let repairEnvironment = options.repairEnvironment;
1606
+ let environment = providerProcessEnv(dispatch, repairEnvironment);
1607
+ let validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1493
1608
  for (let repairTurn = 0;; repairTurn += 1) {
1494
1609
  try {
1610
+ const refreshed = await this.refreshPrePublicationRuntime(context, validationProfile, repairTurn);
1611
+ if (refreshed) {
1612
+ repairEnvironment = options.onRuntimeEnvironmentRefreshed
1613
+ ? await options.onRuntimeEnvironmentRefreshed(refreshed)
1614
+ : refreshed;
1615
+ environment = providerProcessEnv(dispatch, repairEnvironment);
1616
+ validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1617
+ }
1495
1618
  await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
1496
1619
  if (repairTurn > 0) {
1497
1620
  await context.emit({
@@ -1507,6 +1630,17 @@ export class ProcessBackedProviderCliService {
1507
1630
  catch (error) {
1508
1631
  if (!(error instanceof PrePublicationValidationError))
1509
1632
  throw error;
1633
+ if (error.checkId === runtimeRestartCheckId) {
1634
+ // The restart stopped the stack and released its ports before it failed, so the URLs the
1635
+ // repair turn would inherit name ports another attempt may now hold. The turn runs without
1636
+ // them; the next pass restarts the stack and supplies fresh ones.
1637
+ const unavailable = withoutRuntimeStack(repairEnvironment, context.runtimeStackEnvironmentKeys ?? []);
1638
+ repairEnvironment = options.onRuntimeEnvironmentRefreshed
1639
+ ? await options.onRuntimeEnvironmentRefreshed(unavailable)
1640
+ : unavailable;
1641
+ environment = providerProcessEnv(dispatch, repairEnvironment);
1642
+ validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1643
+ }
1510
1644
  if (repairTurn >= maxPrePublicationRepairTurns) {
1511
1645
  await context.emit({
1512
1646
  role: "runner",
@@ -1551,6 +1685,7 @@ export class ProcessBackedProviderCliService {
1551
1685
  args: command.args,
1552
1686
  cwd: worktree.worktreePath,
1553
1687
  env: environment,
1688
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1554
1689
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1555
1690
  }, {
1556
1691
  onStarted: async () => {
@@ -1562,6 +1697,8 @@ export class ProcessBackedProviderCliService {
1562
1697
  });
1563
1698
  providerStarted = true;
1564
1699
  },
1700
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1701
+ onGenerationStart: toolHeartbeat.startGeneration,
1565
1702
  onStdoutLine: async (line) => {
1566
1703
  await toolHeartbeat.consume(line);
1567
1704
  },
@@ -1587,6 +1724,77 @@ export class ProcessBackedProviderCliService {
1587
1724
  }
1588
1725
  }
1589
1726
  }
1727
+ /**
1728
+ * Restarts the attempt's runtime stack when the workspace changed since it was
1729
+ * launched, before a validation pass runs against it. A build of the changed
1730
+ * source that fails is a validation failure the bounded repair turn can fix.
1731
+ */
1732
+ async refreshPrePublicationRuntime(context, validationProfile, repairTurn) {
1733
+ if (!context.refreshRuntimeEnvironment)
1734
+ return null;
1735
+ let refreshed;
1736
+ try {
1737
+ refreshed = await context.refreshRuntimeEnvironment(context.signal);
1738
+ }
1739
+ catch (error) {
1740
+ // A restart that fails to build, start or become ready reflects the changed source, which a
1741
+ // bounded repair turn can fix; the next pass restarts again. Cancellation, a released lease
1742
+ // and a changed runtime contract still end the attempt.
1743
+ if (restartFailureForRepair(error)) {
1744
+ throw new PrePublicationValidationError(runtimeRestartCheckId, 1, "forge-host-runtime-restart", [],
1745
+ // The session's host_runtime_restart_started event records why it restarted.
1746
+ `Forge restarted the attempt runtime stack before validation, and the restart failed: ${error.message}`);
1747
+ }
1748
+ throw error;
1749
+ }
1750
+ if (!refreshed)
1751
+ return null;
1752
+ const { environment: restarted, reason, changes } = refreshed;
1753
+ const apiUrl = restarted.FORGE_E2E_API_URL ?? restarted.FORGE_API_URL ?? null;
1754
+ const webUrl = restarted.FORGE_E2E_WEB_URL ?? restarted.FORGE_WEB_URL ?? restarted.FORGE_PLAYWRIGHT_BASE_URL ?? null;
1755
+ await context.emit({
1756
+ role: "runner",
1757
+ kind: "checkpoint",
1758
+ content: `Restarted the attempt runtime stack before pre-publication validation because ${restartReasonText[reason]}; validation${repairTurn > 0 ? " and repair turns" : ""} now use${apiUrl ? ` API ${apiUrl}` : " the refreshed runtime URLs"}${webUrl ? ` and web ${webUrl}` : ""}.`,
1759
+ eventType: "prepublication_runtime_restarted",
1760
+ data: JSON.stringify({
1761
+ reason,
1762
+ changes,
1763
+ validationProfile,
1764
+ repairTurn,
1765
+ apiUrl,
1766
+ webUrl,
1767
+ }),
1768
+ });
1769
+ return restarted;
1770
+ }
1771
+ }
1772
+ const restartReasonText = {
1773
+ previous_restart_incomplete: "the previous restart did not complete",
1774
+ fingerprint_unavailable: "the workspace state could not be compared with the stack's",
1775
+ workspace_changed: "the workspace changed since it was launched",
1776
+ };
1777
+ const runtimeRestartCheckId = "host-runtime-restart";
1778
+ /** The environment with the runtime stack's URLs and ports withheld and the stack marked unavailable. */
1779
+ function withoutRuntimeStack(environment, stackKeys) {
1780
+ const remaining = { ...(environment ?? {}) };
1781
+ for (const key of stackKeys)
1782
+ delete remaining[key];
1783
+ remaining.FORGE_RUNTIME_STACK = "unavailable";
1784
+ return remaining;
1785
+ }
1786
+ const restartFailuresForRepair = new Set([
1787
+ "host_runtime_project_start_failed",
1788
+ "host_runtime_process_exited",
1789
+ "host_runtime_listener_timeout",
1790
+ "host_runtime_http_readiness_timeout",
1791
+ "host_port_collision",
1792
+ ]);
1793
+ function restartFailureForRepair(error) {
1794
+ if (error instanceof ForgeFailureError)
1795
+ return restartFailuresForRepair.has(error.failureCode);
1796
+ // The port broker throws an untyped collision once its launch retries are exhausted.
1797
+ return error instanceof HostPortCollisionError;
1590
1798
  }
1591
1799
  function buildPrePublicationRepairPrompt(error, repairTurn, repairScope) {
1592
1800
  const invocation = [error.command, ...error.args].join(" ");