@loucompanion/forge-bridge 0.1.4-dev.494233aa2e50 → 0.1.4-dev.60e18c3cfec6

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 (141) hide show
  1. package/README.md +35 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +279 -10
  57. package/dist/runtime/host-runtime-promotion.js +12 -0
  58. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  59. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  60. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  61. package/dist/runtime/host-runtime-requirements.js +117 -0
  62. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  64. package/dist/runtime/runner-settings.d.ts +100 -0
  65. package/dist/runtime/runner-settings.js +214 -0
  66. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  67. package/dist/sandbox/host-capacity-broker.js +315 -0
  68. package/dist/sandbox/runtime.d.ts +10 -1
  69. package/dist/sandbox/runtime.js +45 -2
  70. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  71. package/dist/sandbox/sandbox-cgroups.js +42 -0
  72. package/dist/session/managed-attempt-tools.d.ts +2 -0
  73. package/dist/session/managed-attempt-tools.js +156 -37
  74. package/dist/session/managed-command-host-load.d.ts +45 -0
  75. package/dist/session/managed-command-host-load.js +82 -0
  76. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  77. package/dist/session/mcp-argument-coercion.js +121 -0
  78. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  79. package/dist/session/phase-completion.artifacts.js +94 -25
  80. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  81. package/dist/session/phase-completion.command-validation.js +77 -0
  82. package/dist/session/phase-completion.d.ts +4 -0
  83. package/dist/session/phase-completion.helpers.js +13 -12
  84. package/dist/session/phase-completion.js +4 -0
  85. package/dist/session/phase-completion.prompts.js +6 -1
  86. package/dist/session/phase-completion.runtime.d.ts +5 -3
  87. package/dist/session/phase-completion.runtime.js +49 -19
  88. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  89. package/dist/session/phase-completion.schema-parts.js +188 -0
  90. package/dist/session/phase-completion.schemas.d.ts +3 -3
  91. package/dist/session/phase-completion.schemas.js +184 -209
  92. package/dist/session/phase-completion.validation.d.ts +2 -3
  93. package/dist/session/phase-completion.validation.js +46 -92
  94. package/dist/session/pre-publication-host-load.d.ts +27 -0
  95. package/dist/session/pre-publication-host-load.js +111 -0
  96. package/dist/session/pre-publication-process.d.ts +3 -0
  97. package/dist/session/pre-publication-process.js +23 -11
  98. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  99. package/dist/session/pre-publication-step-execution.js +49 -0
  100. package/dist/session/pre-publication-validation.d.ts +9 -9
  101. package/dist/session/pre-publication-validation.js +21 -55
  102. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  103. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  104. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  105. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  106. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  107. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  108. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  109. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  110. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  111. package/dist/session/provider-cli/provider-cli.service.js +183 -26
  112. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  113. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  114. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  115. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  116. package/dist/session/provider-cli/provider-output-state.js +9 -0
  117. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  118. package/dist/session/publishable-worktree-changes.js +21 -5
  119. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  120. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  121. package/dist/session/session.base.d.ts +9 -1
  122. package/dist/session/session.service.d.ts +9 -2
  123. package/dist/session/session.service.js +120 -5
  124. package/dist/session/session.types.d.ts +3 -0
  125. package/dist/session/session.types.js +12 -3
  126. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  127. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  128. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  129. package/dist/shared/process/host-process-supervisor.js +1 -1
  130. package/dist/shared/process/process-tree.d.ts +52 -0
  131. package/dist/shared/process/process-tree.js +144 -0
  132. package/dist/shared/process/process.d.ts +67 -0
  133. package/dist/shared/process/process.js +213 -11
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. package/dist/worktree/dependency-warmer.d.ts +25 -0
  137. package/dist/worktree/dependency-warmer.js +46 -10
  138. package/dist/worktree/worktree.service.d.ts +10 -1
  139. package/dist/worktree/worktree.service.js +42 -2
  140. package/dist/worktree/worktree.types.d.ts +7 -0
  141. package/package.json +1 -1
@@ -2,6 +2,9 @@ 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";
@@ -10,7 +13,7 @@ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtif
10
13
  import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
11
14
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
12
15
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
13
- import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
16
+ import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
14
17
  import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
15
18
  import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
16
19
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
@@ -213,16 +216,20 @@ function providerOwnsBranchPublication(context) {
213
216
  return context.dispatch.sandbox?.executionMode !== "docker";
214
217
  }
215
218
  function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
219
+ const hostLoadOwner = {
220
+ dispatchAttemptId: context.dispatch.sandbox?.dispatchAttemptId ?? null,
221
+ priority: runtimeAdmissionPriority(context.dispatch),
222
+ };
216
223
  if (context.processRunner)
217
- return { baselineRevision, environment, processRunner: context.processRunner };
224
+ return { baselineRevision, environment, processRunner: context.processRunner, hostLoadOwner };
218
225
  if (context.dispatch.sandbox?.executionMode !== "docker")
219
- return { baselineRevision, environment };
226
+ return { baselineRevision, environment, hostLoadOwner };
220
227
  const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
221
228
  const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
222
229
  if (observedSandboxId !== expectedSandboxId) {
223
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");
224
231
  }
225
- return { baselineRevision, environment, processRunner: defaultRunner };
232
+ return { baselineRevision, environment, processRunner: defaultRunner, hostLoadOwner };
226
233
  }
227
234
  function remoteTrackingRefspec(branchName) {
228
235
  return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
@@ -432,7 +439,8 @@ export class ManagedVerificationProgressEmitter {
432
439
  }
433
440
  }
434
441
  function isManagedVerificationNonterminal(status) {
435
- 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";
436
444
  }
437
445
  async function parseManagedVerificationSnapshot(receiptPath) {
438
446
  try {
@@ -472,10 +480,17 @@ class ProviderToolActivityHeartbeat {
472
480
  emit;
473
481
  intervalMs;
474
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();
475
487
  constructor(outputState, emit, intervalMs) {
476
488
  this.outputState = outputState;
477
489
  this.emit = emit;
478
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();
479
494
  }
480
495
  async consume(line) {
481
496
  const events = this.outputState.consume(line);
@@ -557,7 +572,12 @@ export class ProcessBackedProviderCliService {
557
572
  providerToolHeartbeatIntervalMs;
558
573
  publicationCoordinator;
559
574
  prePublicationValidator;
560
- 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())) {
561
581
  this.processRunner = processRunner;
562
582
  this.git = git;
563
583
  this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
@@ -576,7 +596,7 @@ export class ProcessBackedProviderCliService {
576
596
  await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
577
597
  const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
578
598
  const decomposeDraft = isDecomposeDraftDispatch(dispatch);
579
- 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 });
580
600
  const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
581
601
  const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
582
602
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -629,6 +649,7 @@ export class ProcessBackedProviderCliService {
629
649
  args: command.args,
630
650
  cwd: worktree.worktreePath,
631
651
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
652
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
632
653
  stdin: pipePromptToStdin ? providerPrompt : undefined
633
654
  }, {
634
655
  onStarted: async () => {
@@ -639,6 +660,8 @@ export class ProcessBackedProviderCliService {
639
660
  eventType: "provider_cli_started"
640
661
  });
641
662
  },
663
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
664
+ onGenerationStart: toolHeartbeat.startGeneration,
642
665
  onStdoutLine: async (line) => {
643
666
  await toolHeartbeat.consume(line);
644
667
  }
@@ -688,7 +711,7 @@ export class ProcessBackedProviderCliService {
688
711
  await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
689
712
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
690
713
  if (!proposalArtifact) {
691
- 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);
692
715
  }
693
716
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
694
717
  const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
@@ -711,7 +734,7 @@ export class ProcessBackedProviderCliService {
711
734
  await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
712
735
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
713
736
  if (!proposalArtifact) {
714
- 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);
715
738
  }
716
739
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
717
740
  const draftJson = proposal["draft_json"];
@@ -756,7 +779,7 @@ export class ProcessBackedProviderCliService {
756
779
  const specPath = path.join(metadataRoot, "spec.md");
757
780
  await fs.writeFile(specPath, specBody, "utf8");
758
781
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
759
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
782
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
760
783
  const implementationPrompt = debugCycle
761
784
  ? buildDebugCyclePrompt(dispatch, phase)
762
785
  : developCycle
@@ -798,6 +821,7 @@ export class ProcessBackedProviderCliService {
798
821
  args: command.args,
799
822
  cwd: worktree.worktreePath,
800
823
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
824
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
801
825
  stdin: pipePromptToStdin ? providerPrompt : undefined
802
826
  }, {
803
827
  onStarted: async () => {
@@ -808,6 +832,8 @@ export class ProcessBackedProviderCliService {
808
832
  eventType: "provider_cli_started"
809
833
  });
810
834
  },
835
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
836
+ onGenerationStart: toolHeartbeat.startGeneration,
811
837
  onStdoutLine: async (line) => {
812
838
  await toolHeartbeat.consume(line);
813
839
  }
@@ -849,7 +875,7 @@ export class ProcessBackedProviderCliService {
849
875
  eventType: "worktree_branch_pushed"
850
876
  });
851
877
  }
852
- 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);
853
879
  for (const artifact of completionArtifacts) {
854
880
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
855
881
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -901,7 +927,7 @@ export class ProcessBackedProviderCliService {
901
927
  const specPath = path.join(metadataRoot, "spec.md");
902
928
  await fs.writeFile(specPath, specBody, "utf8");
903
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");
904
- 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 });
905
931
  const architectPrompt = buildArchitectPrompt(dispatch);
906
932
  const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
907
933
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -936,6 +962,7 @@ export class ProcessBackedProviderCliService {
936
962
  args: command.args,
937
963
  cwd: worktree.worktreePath,
938
964
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
965
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
939
966
  stdin: pipePromptToStdin ? providerPrompt : undefined
940
967
  }, {
941
968
  onStarted: async () => {
@@ -946,6 +973,8 @@ export class ProcessBackedProviderCliService {
946
973
  eventType: "provider_cli_started"
947
974
  });
948
975
  },
976
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
977
+ onGenerationStart: toolHeartbeat.startGeneration,
949
978
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
950
979
  }, context.signal);
951
980
  }
@@ -966,7 +995,7 @@ export class ProcessBackedProviderCliService {
966
995
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
967
996
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
968
997
  if (!architectArtifact) {
969
- 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);
970
999
  }
971
1000
  if (!liveArchitectEvents.hasEmitted()) {
972
1001
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -1003,7 +1032,7 @@ export class ProcessBackedProviderCliService {
1003
1032
  const specPath = path.join(metadataRoot, "spec.md");
1004
1033
  await fs.writeFile(specPath, specBody, "utf8");
1005
1034
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
1006
- 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 });
1007
1036
  const qaPrompt = buildQaPrompt(dispatch, specBody);
1008
1037
  const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
1009
1038
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -1040,6 +1069,7 @@ export class ProcessBackedProviderCliService {
1040
1069
  args: command.args,
1041
1070
  cwd: worktree.worktreePath,
1042
1071
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1072
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1043
1073
  stdin: pipePromptToStdin ? providerPrompt : undefined
1044
1074
  }, {
1045
1075
  onStarted: async () => {
@@ -1050,6 +1080,8 @@ export class ProcessBackedProviderCliService {
1050
1080
  eventType: "provider_cli_started"
1051
1081
  });
1052
1082
  },
1083
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1084
+ onGenerationStart: toolHeartbeat.startGeneration,
1053
1085
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1054
1086
  }, context.signal);
1055
1087
  }
@@ -1069,17 +1101,19 @@ export class ProcessBackedProviderCliService {
1069
1101
  eventType: "provider_cli_completed"
1070
1102
  });
1071
1103
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
1104
+ const lastRun = { result };
1072
1105
  let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1073
1106
  if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1074
1107
  // A headless provider that ends its turn to "wait for a background watcher"
1075
1108
  // exits for good. Resume the same thread instead of failing the session.
1076
- qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
1109
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1077
1110
  }
1078
1111
  if (!qaArtifact) {
1079
1112
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
1080
- throw new Error(verdictOnly
1081
- ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
1082
- : "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);
1083
1117
  }
1084
1118
  await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1085
1119
  if (!liveQaEvents.hasEmitted()) {
@@ -1118,6 +1152,7 @@ export class ProcessBackedProviderCliService {
1118
1152
  const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
1119
1153
  let repairSpec = null;
1120
1154
  let repairEnvironment = context.runtimeEnvironment;
1155
+ let ciRepairSpecPath = null;
1121
1156
  let completionTools = null;
1122
1157
  if (repairChecks) {
1123
1158
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -1128,6 +1163,7 @@ export class ProcessBackedProviderCliService {
1128
1163
  }
1129
1164
  const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
1130
1165
  const specPath = path.join(metadataRoot, "spec.md");
1166
+ ciRepairSpecPath = specPath;
1131
1167
  await fs.writeFile(specPath, specBody, "utf8");
1132
1168
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
1133
1169
  repairSpec = {
@@ -1139,7 +1175,9 @@ export class ProcessBackedProviderCliService {
1139
1175
  };
1140
1176
  const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
1141
1177
  repairEnvironment = readiness.environment;
1142
- 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
+ });
1143
1181
  await context.emit({
1144
1182
  role: "runner",
1145
1183
  kind: "checkpoint",
@@ -1154,7 +1192,9 @@ export class ProcessBackedProviderCliService {
1154
1192
  });
1155
1193
  }
1156
1194
  if (addressComments) {
1157
- 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
+ });
1158
1198
  await context.emit({
1159
1199
  role: "runner",
1160
1200
  kind: "checkpoint",
@@ -1192,6 +1232,7 @@ export class ProcessBackedProviderCliService {
1192
1232
  args: command.args,
1193
1233
  cwd: worktree.worktreePath,
1194
1234
  env: providerProcessEnv(dispatch, repairEnvironment),
1235
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1195
1236
  stdin: pipePromptToStdin ? providerPrompt : undefined
1196
1237
  }, {
1197
1238
  onStarted: async () => {
@@ -1203,6 +1244,8 @@ export class ProcessBackedProviderCliService {
1203
1244
  });
1204
1245
  providerStarted = true;
1205
1246
  },
1247
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1248
+ onGenerationStart: toolHeartbeat.startGeneration,
1206
1249
  onStdoutLine: async (line) => {
1207
1250
  await toolHeartbeat.consume(line);
1208
1251
  }
@@ -1237,7 +1280,7 @@ export class ProcessBackedProviderCliService {
1237
1280
  if (repairChecks) {
1238
1281
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1239
1282
  if (!repairArtifact) {
1240
- 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);
1241
1284
  }
1242
1285
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1243
1286
  throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
@@ -1245,16 +1288,18 @@ export class ProcessBackedProviderCliService {
1245
1288
  }
1246
1289
  if (addressComments) {
1247
1290
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1291
+ const lastRun = { result };
1248
1292
  if (!repairArtifact) {
1249
1293
  repairArtifact = await this.recoverMissingCommentRepairCompletion({
1250
1294
  context,
1251
1295
  repairEnvironment,
1252
1296
  outputState,
1253
1297
  preparedHeadSha,
1298
+ lastRun,
1254
1299
  });
1255
1300
  }
1256
1301
  if (!repairArtifact) {
1257
- 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);
1258
1303
  }
1259
1304
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1260
1305
  throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
@@ -1273,6 +1318,7 @@ export class ProcessBackedProviderCliService {
1273
1318
  : addressComments
1274
1319
  ? "comment_repair"
1275
1320
  : "conflict_repair";
1321
+ const readinessSpecPath = ciRepairSpecPath;
1276
1322
  await this.validatePrePublicationWithRecovery({
1277
1323
  context,
1278
1324
  validationProfile,
@@ -1280,6 +1326,10 @@ export class ProcessBackedProviderCliService {
1280
1326
  outputState,
1281
1327
  preparedHeadSha,
1282
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
+ } : {}),
1283
1333
  });
1284
1334
  const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1285
1335
  const stagedChangedFiles = stagedChangeSet.publishable;
@@ -1358,6 +1408,7 @@ export class ProcessBackedProviderCliService {
1358
1408
  worktree,
1359
1409
  phase: "qa",
1360
1410
  runtimeEnvironment: context.runtimeEnvironment,
1411
+ hostLoadEnvironment: context.hostLoadEnvironment,
1361
1412
  });
1362
1413
  const command = buildProviderCliCommand(recoveryDispatch, {
1363
1414
  worktreePath: worktree.worktreePath,
@@ -1381,13 +1432,19 @@ export class ProcessBackedProviderCliService {
1381
1432
  args: command.args,
1382
1433
  cwd: worktree.worktreePath,
1383
1434
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1435
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1384
1436
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1385
- }, { 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);
1386
1442
  }
1387
1443
  finally {
1388
1444
  toolHeartbeat.stop();
1389
1445
  await cleanupCompletionTools(completionTools, context.emit);
1390
1446
  }
1447
+ options.lastRun.result = result;
1391
1448
  if (result.exitCode !== 0)
1392
1449
  throw providerCliExitFailure(command.command, result);
1393
1450
  const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
@@ -1461,6 +1518,7 @@ export class ProcessBackedProviderCliService {
1461
1518
  worktree,
1462
1519
  phase: "comment_repair",
1463
1520
  runtimeEnvironment: repairEnvironment,
1521
+ hostLoadEnvironment: context.hostLoadEnvironment,
1464
1522
  });
1465
1523
  const command = buildProviderCliCommand(recoveryDispatch, {
1466
1524
  worktreePath: worktree.worktreePath,
@@ -1485,6 +1543,7 @@ export class ProcessBackedProviderCliService {
1485
1543
  args: command.args,
1486
1544
  cwd: worktree.worktreePath,
1487
1545
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1546
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1488
1547
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1489
1548
  }, {
1490
1549
  onStarted: async () => {
@@ -1496,6 +1555,8 @@ export class ProcessBackedProviderCliService {
1496
1555
  eventType: "provider_cli_started",
1497
1556
  });
1498
1557
  },
1558
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1559
+ onGenerationStart: toolHeartbeat.startGeneration,
1499
1560
  onStdoutLine: async (line) => {
1500
1561
  await toolHeartbeat.consume(line);
1501
1562
  },
@@ -1517,6 +1578,7 @@ export class ProcessBackedProviderCliService {
1517
1578
  await cleanupCompletionTools(completionTools, context.emit);
1518
1579
  }
1519
1580
  }
1581
+ options.lastRun.result = result;
1520
1582
  if (result.exitCode !== 0)
1521
1583
  throw providerCliExitFailure(command.command, result);
1522
1584
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1536,13 +1598,23 @@ export class ProcessBackedProviderCliService {
1536
1598
  return artifact;
1537
1599
  }
1538
1600
  async validatePrePublicationWithRecovery(options) {
1539
- const { context, validationProfile, repairEnvironment, outputState, preparedHeadSha, repairScope } = options;
1601
+ const { context, validationProfile, outputState, preparedHeadSha, repairScope } = options;
1540
1602
  const { dispatch, worktree } = context;
1541
1603
  const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
1542
- const environment = providerProcessEnv(dispatch, repairEnvironment);
1543
- 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);
1544
1608
  for (let repairTurn = 0;; repairTurn += 1) {
1545
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
+ }
1546
1618
  await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
1547
1619
  if (repairTurn > 0) {
1548
1620
  await context.emit({
@@ -1558,6 +1630,17 @@ export class ProcessBackedProviderCliService {
1558
1630
  catch (error) {
1559
1631
  if (!(error instanceof PrePublicationValidationError))
1560
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
+ }
1561
1644
  if (repairTurn >= maxPrePublicationRepairTurns) {
1562
1645
  await context.emit({
1563
1646
  role: "runner",
@@ -1602,6 +1685,7 @@ export class ProcessBackedProviderCliService {
1602
1685
  args: command.args,
1603
1686
  cwd: worktree.worktreePath,
1604
1687
  env: environment,
1688
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1605
1689
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1606
1690
  }, {
1607
1691
  onStarted: async () => {
@@ -1613,6 +1697,8 @@ export class ProcessBackedProviderCliService {
1613
1697
  });
1614
1698
  providerStarted = true;
1615
1699
  },
1700
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1701
+ onGenerationStart: toolHeartbeat.startGeneration,
1616
1702
  onStdoutLine: async (line) => {
1617
1703
  await toolHeartbeat.consume(line);
1618
1704
  },
@@ -1638,6 +1724,77 @@ export class ProcessBackedProviderCliService {
1638
1724
  }
1639
1725
  }
1640
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;
1641
1798
  }
1642
1799
  function buildPrePublicationRepairPrompt(error, repairTurn, repairScope) {
1643
1800
  const invocation = [error.command, ...error.args].join(" ");
@@ -1,18 +1,48 @@
1
1
  import type { RunOnceDispatchPacket, RunnerDispatchArtifact, RunnerDispatchEvent, RunnerDispatchSpec } from "../session.types.js";
2
2
  import type { WorktreeHandle } from "../../worktree/worktree.types.js";
3
3
  import type { ProviderProcessRunner } from "./provider-cli.process.js";
4
+ /**
5
+ * Why the attempt's runtime stack restarted before a validation pass. The first cause that applies:
6
+ * a previous restart did not complete; the workspace state could not be compared with the stack's
7
+ * (either reading was unavailable); or the workspace changed since the stack was launched.
8
+ */
9
+ export type RuntimeRestartReason = "previous_restart_incomplete" | "fingerprint_unavailable" | "workspace_changed";
10
+ export interface RuntimeEnvironmentRefresh {
11
+ /** The restarted stack's runtime environment. */
12
+ readonly environment: Readonly<Record<string, string>>;
13
+ readonly reason: RuntimeRestartReason;
14
+ /** What changed in the workspace since the stack was launched, when both states could be read. */
15
+ readonly changes: readonly string[];
16
+ }
4
17
  export interface ProviderCliRunContext {
5
18
  readonly dispatch: RunOnceDispatchPacket;
6
19
  readonly worktree: WorktreeHandle;
7
20
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
21
+ /** Host load governor variables for the completion MCP server only (decision 0013). */
22
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
8
23
  readonly processRunner?: ProviderProcessRunner;
9
24
  readonly signal?: AbortSignal;
25
+ /**
26
+ * Restarts the attempt's host runtime stack when the workspace changed since it was
27
+ * launched (an uncommitted edit, an in-progress merge), so validation and repair
28
+ * turns run against the current source. Resolves to the refreshed runtime
29
+ * environment and why the stack restarted, or null when the stack is current or
30
+ * there is no configured project.
31
+ */
32
+ refreshRuntimeEnvironment?(signal?: AbortSignal): Promise<RuntimeEnvironmentRefresh | null>;
33
+ /**
34
+ * The runtime environment keys that name the configured project's live stack (its URLs and
35
+ * ports). A failed restart withholds them from the repair turn, since the stack is down.
36
+ */
37
+ readonly runtimeStackEnvironmentKeys?: readonly string[];
10
38
  emit(event: RunnerDispatchEvent): Promise<void>;
11
39
  }
12
40
  export interface ProviderCliDraftContext {
13
41
  readonly dispatch: RunOnceDispatchPacket;
14
42
  readonly worktree: WorktreeHandle;
15
43
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
44
+ /** Host load governor variables for the completion MCP server only (decision 0013). */
45
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
16
46
  readonly processRunner?: ProviderProcessRunner;
17
47
  readonly signal?: AbortSignal;
18
48
  emit(event: RunnerDispatchEvent): Promise<void>;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * True while an attempt-owned managed command (a receipt under
3
+ * `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
4
+ * Unreadable or stale receipts do not count.
5
+ */
6
+ export declare function hasNonterminalManagedCommand(logDirectory: string | undefined, nowMs?: number): Promise<boolean>;
@@ -0,0 +1,47 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ const nonterminalManagedCommandStatuses = new Set(["starting", "running", "waiting_for_build_slot"]);
4
+ // A running receipt is rewritten every 5 s. One that has not changed for a minute
5
+ // belongs to a command whose supervisor is gone, so it no longer holds the provider open.
6
+ const runningReceiptStaleMs = 60_000;
7
+ // Starting and queued receipts are written once. They hold the provider open for at most
8
+ // the command's own timeout (the managed-command maximum when absent) plus a margin.
9
+ const maximumManagedCommandTimeoutMs = 2 * 60 * 60_000;
10
+ const queuedReceiptMarginMs = 60_000;
11
+ /**
12
+ * True while an attempt-owned managed command (a receipt under
13
+ * `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
14
+ * Unreadable or stale receipts do not count.
15
+ */
16
+ export async function hasNonterminalManagedCommand(logDirectory, nowMs = Date.now()) {
17
+ if (!logDirectory?.trim())
18
+ return false;
19
+ const directory = path.join(logDirectory, "managed-commands");
20
+ const names = await fs.readdir(directory).catch(() => []);
21
+ for (const name of names) {
22
+ if (!name.endsWith(".receipt.json"))
23
+ continue;
24
+ if (await receiptHoldsProvider(path.join(directory, name), nowMs))
25
+ return true;
26
+ }
27
+ return false;
28
+ }
29
+ async function receiptHoldsProvider(receiptPath, nowMs) {
30
+ try {
31
+ const [stat, content] = await Promise.all([fs.stat(receiptPath), fs.readFile(receiptPath, "utf8")]);
32
+ const receipt = JSON.parse(content);
33
+ const status = typeof receipt.status === "string" ? receipt.status : "";
34
+ if (!nonterminalManagedCommandStatuses.has(status))
35
+ return false;
36
+ const ageMs = nowMs - stat.mtimeMs;
37
+ if (status === "running")
38
+ return ageMs <= runningReceiptStaleMs;
39
+ const timeoutMs = typeof receipt.timeout_ms === "number" && Number.isFinite(receipt.timeout_ms)
40
+ ? receipt.timeout_ms
41
+ : maximumManagedCommandTimeoutMs;
42
+ return ageMs <= timeoutMs + queuedReceiptMarginMs;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }