@loucompanion/forge-bridge 0.1.4-dev.028808a841c8 → 0.1.4-dev.138b79c6feb3

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 (119) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +2 -0
  3. package/dist/bridge/bridge.service.js +30 -5
  4. package/dist/bridge/bridge.types.d.ts +5 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +72 -109
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  13. package/dist/cleanup/forge-owned-paths.js +53 -0
  14. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  15. package/dist/cleanup/host-runtime-ledger.js +109 -0
  16. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  17. package/dist/cleanup/managed-branch-sweep.js +111 -0
  18. package/dist/cli/cli.service.js +10 -2
  19. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  20. package/dist/runtime/host-load-admission.d.ts +52 -0
  21. package/dist/runtime/host-load-admission.js +84 -0
  22. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  23. package/dist/runtime/host-load-child-environment.js +65 -0
  24. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  25. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  26. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  27. package/dist/runtime/host-load-governor-config.js +46 -0
  28. package/dist/runtime/host-load-governor.d.ts +172 -0
  29. package/dist/runtime/host-load-governor.js +519 -0
  30. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  31. package/dist/runtime/host-load-ledger-lock.js +185 -0
  32. package/dist/runtime/host-load-sampler.d.ts +43 -0
  33. package/dist/runtime/host-load-sampler.js +74 -6
  34. package/dist/runtime/host-load-step-class.d.ts +68 -0
  35. package/dist/runtime/host-load-step-class.js +106 -0
  36. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  37. package/dist/runtime/host-load-step-reaper.js +95 -0
  38. package/dist/runtime/host-load-step-run.d.ts +73 -0
  39. package/dist/runtime/host-load-step-run.js +102 -0
  40. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  41. package/dist/runtime/host-load-token-ledger.js +421 -0
  42. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  43. package/dist/runtime/host-pressure-stall.js +48 -1
  44. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  45. package/dist/runtime/host-runtime-contract.js +4 -1
  46. package/dist/runtime/host-runtime-lease.d.ts +47 -3
  47. package/dist/runtime/host-runtime-lease.js +215 -5
  48. package/dist/runtime/host-runtime-promotion.js +12 -0
  49. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  50. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  51. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  52. package/dist/runtime/host-runtime-requirements.js +117 -0
  53. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  54. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  55. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  56. package/dist/sandbox/host-capacity-broker.js +315 -0
  57. package/dist/sandbox/runtime.d.ts +10 -1
  58. package/dist/sandbox/runtime.js +45 -2
  59. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  60. package/dist/sandbox/sandbox-cgroups.js +42 -0
  61. package/dist/session/managed-attempt-tools.d.ts +2 -0
  62. package/dist/session/managed-attempt-tools.js +156 -37
  63. package/dist/session/managed-command-host-load.d.ts +45 -0
  64. package/dist/session/managed-command-host-load.js +82 -0
  65. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  66. package/dist/session/mcp-argument-coercion.js +121 -0
  67. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  68. package/dist/session/phase-completion.artifacts.js +94 -25
  69. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  70. package/dist/session/phase-completion.command-validation.js +77 -0
  71. package/dist/session/phase-completion.d.ts +4 -0
  72. package/dist/session/phase-completion.helpers.js +13 -12
  73. package/dist/session/phase-completion.js +4 -0
  74. package/dist/session/phase-completion.prompts.js +6 -1
  75. package/dist/session/phase-completion.runtime.d.ts +5 -3
  76. package/dist/session/phase-completion.runtime.js +49 -19
  77. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  78. package/dist/session/phase-completion.schema-parts.js +188 -0
  79. package/dist/session/phase-completion.schemas.d.ts +3 -3
  80. package/dist/session/phase-completion.schemas.js +184 -209
  81. package/dist/session/phase-completion.validation.d.ts +2 -3
  82. package/dist/session/phase-completion.validation.js +46 -92
  83. package/dist/session/pre-publication-host-load.d.ts +27 -0
  84. package/dist/session/pre-publication-host-load.js +111 -0
  85. package/dist/session/pre-publication-process.d.ts +3 -0
  86. package/dist/session/pre-publication-process.js +23 -11
  87. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  88. package/dist/session/pre-publication-step-execution.js +49 -0
  89. package/dist/session/pre-publication-validation.d.ts +9 -9
  90. package/dist/session/pre-publication-validation.js +21 -55
  91. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  92. package/dist/session/provider-cli/provider-cli.process.js +15 -7
  93. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  94. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  95. package/dist/session/provider-cli/provider-cli.service.js +146 -15
  96. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  97. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  98. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  99. package/dist/session/session.base.d.ts +3 -0
  100. package/dist/session/session.service.d.ts +5 -1
  101. package/dist/session/session.service.js +114 -5
  102. package/dist/session/session.types.d.ts +3 -0
  103. package/dist/session/session.types.js +3 -3
  104. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  105. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  106. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  107. package/dist/shared/process/host-process-supervisor.js +1 -1
  108. package/dist/shared/process/process-tree.d.ts +52 -0
  109. package/dist/shared/process/process-tree.js +144 -0
  110. package/dist/shared/process/process.d.ts +67 -0
  111. package/dist/shared/process/process.js +213 -11
  112. package/dist/version.d.ts +1 -1
  113. package/dist/version.js +1 -1
  114. package/dist/worktree/dependency-warmer.d.ts +25 -0
  115. package/dist/worktree/dependency-warmer.js +46 -10
  116. package/dist/worktree/worktree.service.d.ts +10 -1
  117. package/dist/worktree/worktree.service.js +42 -2
  118. package/dist/worktree/worktree.types.d.ts +7 -0
  119. package/package.json +1 -1
@@ -3,11 +3,13 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
5
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
6
- import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
6
+ import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
7
+ import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
7
8
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
8
9
  import { redactText } from "../shared/redaction/redaction.js";
9
10
  import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
10
11
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
+ import { ProcessTreeTerminationError } from "../shared/process/process.js";
11
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
12
14
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
13
15
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
@@ -84,10 +86,12 @@ export class PrePublicationValidator {
84
86
  commands;
85
87
  dockerEngineProbe;
86
88
  nativeTestPostgresFallback;
87
- constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null) {
89
+ hostLoad;
90
+ constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
88
91
  this.commands = commands;
89
92
  this.dockerEngineProbe = dockerEngineProbe;
90
93
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
94
+ this.hostLoad = hostLoad;
91
95
  }
92
96
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
93
97
  const checksExports = profile === "implementation" || profile === "comment_repair";
@@ -130,11 +134,11 @@ export class PrePublicationValidator {
130
134
  let skipped = { count: 0, reasons: [] };
131
135
  for (const step of check.steps) {
132
136
  const stepStartedMs = Date.now() - 1000;
133
- let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
137
+ let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
134
138
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
135
139
  if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
136
140
  await emit?.(validationEvent("prepublication_validation_timeout_confirmation_started", check.id, "The full client test step reported only Vitest timeouts; confirming once with the same command and attempt environment."));
137
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
141
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
138
142
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
139
143
  await emit?.(validationEvent(result.exitCode === 0
140
144
  ? "prepublication_validation_timeout_confirmation_passed"
@@ -144,7 +148,7 @@ export class PrePublicationValidator {
144
148
  }
145
149
  if (isTransientBridgeCleanupFailure(check.id, step, result)) {
146
150
  await emit?.(validationEvent("prepublication_validation_cleanup_confirmation_started", check.id, "The Bridge suite hit the known Windows temporary-worktree cleanup race; confirming once with the same command and attempt environment."));
147
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
151
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
148
152
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
149
153
  await emit?.(validationEvent(result.exitCode === 0
150
154
  ? "prepublication_validation_cleanup_confirmation_passed"
@@ -154,7 +158,7 @@ export class PrePublicationValidator {
154
158
  }
155
159
  if (isTransientShellInfrastructureFailure(result)) {
156
160
  await emit?.(validationEvent("prepublication_infrastructure_confirmation_started", check.id, "The validation shell reported a known host-runtime failure; confirming once with the same command and attempt environment."));
157
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
161
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
158
162
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
159
163
  const infrastructureFailed = isTransientShellInfrastructureFailure(result);
160
164
  await emit?.(validationEvent(infrastructureFailed
@@ -213,7 +217,7 @@ export class PrePublicationValidator {
213
217
  const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
214
218
  if (!snapshot.available) {
215
219
  const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
216
- const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check)
220
+ const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
217
221
  ? this.nativeTestPostgresFallback()
218
222
  : null;
219
223
  if (fallback) {
@@ -299,8 +303,14 @@ export class PrePublicationValidator {
299
303
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
300
304
  }
301
305
  }
302
- async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection) {
306
+ async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
303
307
  const invocation = managedAttemptInvocation(checkId, step, execution?.environment);
308
+ // Every launch, including confirmation reruns, is admitted by the host load governor first.
309
+ return await runHostGovernedValidationStep(this.hostLoad, {
310
+ checkId, command: invocation.command, args: invocation.args, owner: execution?.hostLoadOwner, signal, emit,
311
+ }, async (stepSignal) => await this.launchStep(checkId, step, invocation, cwd, stepSignal, execution, postgresAdminConnection));
312
+ }
313
+ async launchStep(checkId, step, invocation, cwd, signal, execution, postgresAdminConnection) {
304
314
  const stepExecution = validationExecutionForStep(checkId, step, execution, postgresAdminConnection);
305
315
  const before = await readValidationFiles(cwd, step.assertUnchangedPaths ?? []);
306
316
  const result = await this.runCommand(invocation.command, invocation.args, cwd, signal, stepExecution);
@@ -345,57 +355,13 @@ export class PrePublicationValidator {
345
355
  };
346
356
  }
347
357
  catch (error) {
358
+ // Carries the check its host capacity token waits on; it names only the executable.
359
+ if (error instanceof ProcessTreeTerminationError)
360
+ throw error;
348
361
  throw sanitizeFailureError(error, exactSecrets);
349
362
  }
350
363
  }
351
364
  }
352
- function managedAttemptInvocation(checkId, step, environment) {
353
- const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
354
- const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
355
- || Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
356
- if (checkId !== "playwright-e2e" || !attemptOwned) {
357
- return step;
358
- }
359
- if (!playwrightConfig) {
360
- throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
361
- }
362
- return {
363
- command: "pnpm",
364
- args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
365
- };
366
- }
367
- const nativeFallbackCheckIds = new Set([
368
- "owned-suite-registration",
369
- "dotnet-build-and-unit",
370
- "comment-repair-dotnet-regression",
371
- ]);
372
- const nativeFallbackDotnetTierScripts = [
373
- "scripts/run-dotnet-test-tier.ps1",
374
- "scripts/run-dotnet-test-tier-set.ps1",
375
- "scripts/run-affected-dotnet-tests.mjs",
376
- ];
377
- function supportsNativeTestPostgresFallback(check) {
378
- return nativeFallbackCheckIds.has(check.id);
379
- }
380
- function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
381
- // The connection only exists when Docker is unavailable and the operator
382
- // provisioned a dedicated native test cluster. Only the runner-authored
383
- // .NET test tiers and the suite-identity check receive it; build, client,
384
- // Bridge, and E2E steps never do.
385
- if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
386
- return execution;
387
- const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
388
- .some(script => argument.replaceAll("\\", "/").endsWith(script)));
389
- if (checkId !== "owned-suite-registration" && !runsDotnetTier)
390
- return execution;
391
- return {
392
- ...execution,
393
- environment: {
394
- ...execution?.environment,
395
- ...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
396
- },
397
- };
398
- }
399
365
  function environmentValue(environment, name) {
400
366
  return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
401
367
  ? environment?.[name]?.trim() ?? ""
@@ -50,6 +50,13 @@ export interface ProviderProcessHandlers {
50
50
  * end-of-turn exit grace and the success ceiling.
51
51
  */
52
52
  isToolCallInFlight?(): boolean;
53
+ /**
54
+ * Called before each provider generation (child process) starts, including every
55
+ * relaunch a recovery wrapper or supervisor makes with the same handlers. Per-generation
56
+ * state, such as tool calls in flight, must be reset here: a generation that exited mid
57
+ * call never reports that call's completion.
58
+ */
59
+ onGenerationStart?(): void;
53
60
  }
54
61
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
55
62
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -51,6 +51,7 @@ export class CodexModelsCacheRecoveringProcessRunner {
51
51
  const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
52
52
  if (!recovered || signal?.aborted)
53
53
  return first;
54
+ handlers?.onGenerationStart?.();
54
55
  return await this.inner.run(request, handlers, signal);
55
56
  }
56
57
  }
@@ -73,7 +74,10 @@ export class CodexResumeRecoveringProcessRunner {
73
74
  return first;
74
75
  }
75
76
  const fallback = codexFreshTurnRequest(request);
76
- return fallback ? await this.inner.run(fallback, handlers, signal) : first;
77
+ if (!fallback)
78
+ return first;
79
+ handlers?.onGenerationStart?.();
80
+ return await this.inner.run(fallback, handlers, signal);
77
81
  }
78
82
  }
79
83
  function isRecoverableCodexResumeFailure(command, result) {
@@ -111,7 +115,8 @@ function codexFreshTurnRequest(request) {
111
115
  const cd = args.splice(cdIndex, 2);
112
116
  args.splice(args.length - 1, 0, ...cd);
113
117
  }
114
- return { ...request, args };
118
+ // The fallback starts a fresh thread, so it has no replayed turn to discount.
119
+ return { ...request, args, resumesProviderThread: false };
115
120
  }
116
121
  function isCodexCommand(command) {
117
122
  return path.parse(command).name.toLowerCase() === "codex";
@@ -329,6 +334,8 @@ export class StreamingProviderProcessRunner {
329
334
  }
330
335
  async run(request, handlers = {}, signal) {
331
336
  assertHostDatabaseCapabilityBoundary();
337
+ // Every child this runner launches is a new generation, including supervisor retries.
338
+ handlers.onGenerationStart?.();
332
339
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
333
340
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
334
341
  // An unsupervised Unix provider still gets a dedicated process group so a
@@ -372,7 +379,7 @@ export class StreamingProviderProcessRunner {
372
379
  const childStderr = child.stderr;
373
380
  if (!childStdout || !childStderr) {
374
381
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
375
- void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "Provider launch failed and its process tree could not be proven stopped.")));
382
+ void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "host_process_supervisor_termination_failed: Provider launch failed and its process tree could not be proven stopped.")));
376
383
  return;
377
384
  }
378
385
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -408,7 +415,7 @@ export class StreamingProviderProcessRunner {
408
415
  cleanup();
409
416
  // Do not release the caller's reservation/worktree/port ownership until
410
417
  // descendant termination has completed (or failed with explicit proof).
411
- void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
418
+ void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "host_process_supervisor_termination_failed: Provider process failed and its process tree could not be proven stopped.")));
412
419
  };
413
420
  const abort = () => {
414
421
  if (!closed)
@@ -595,11 +602,12 @@ export class StreamingProviderProcessRunner {
595
602
  // the grace period restarts at its next terminal event.
596
603
  graceIdleMs = null;
597
604
  // A resumed session can replay a queued notification turn before the
598
- // prompt's own turn. That replayed turn must not start the ceiling, or the
599
- // resumed agent is stopped mid-work; the prompt's turn arms it instead.
605
+ // prompt's own turn. The replayed turn must not consume the ceiling, or the
606
+ // resumed agent is stopped mid-work, but the prompt's turn still needs a
607
+ // watchdog: restart the ceiling from here instead of dropping it.
600
608
  if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
601
609
  replayedTurnCeilingSkipped = true;
602
- ceilingIdleMs = null;
610
+ ceilingIdleMs = 0;
603
611
  }
604
612
  }
605
613
  }
@@ -278,7 +278,10 @@ function buildRuntimeContextPrompt(dispatch, prompt, runtimeEnvironment) {
278
278
  ? "- `FORGE_HOST_CONCURRENCY=host_parallel_safe` means Forge verified this contract's assigned-port probe and gave this attempt independent ports, paths, and process supervisors. Do not share or discover another attempt's runtime resources."
279
279
  : "- `FORGE_HOST_CONCURRENCY=host_serial_only` means Forge holds the runner-local project singleton named by `FORGE_SINGLETON_KEYS`; do not bypass or release it yourself.";
280
280
  const playwright = runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
281
- ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly."
281
+ ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly. Run `playwright test --config <absolute value of FORGE_PLAYWRIGHT_CONFIG>` from the Playwright project directory through `forge.start_managed_command` (in Forge: command `pnpm`, args `[\"--dir\", \"tests/e2e\", \"exec\", \"playwright\", \"test\", \"--config\", \"<path>\"]`), and append spec file paths such as `specs/<name>.spec.ts` to run only the specs you are working on. Repository wrappers that start their own disposable stack, such as Forge's `pnpm --dir tests/e2e test`, refuse to run inside a managed attempt; Forge-owned pre-publication still runs the full suite."
282
+ : "";
283
+ const stackUnavailable = runtimeEnvironment?.FORGE_RUNTIME_STACK === "unavailable"
284
+ ? "\n- `FORGE_RUNTIME_STACK=unavailable` means Forge's restart of this attempt's application stack failed, so no attempt-owned API, web, or Playwright URLs are supplied for this turn. Do not reuse URLs or ports from an earlier turn or start the stack yourself; fix the source so the restart succeeds. Forge restarts the stack and reruns validation after this turn."
282
285
  : "";
283
286
  return `${prompt.trimEnd()}
284
287
 
@@ -292,7 +295,7 @@ ${concurrency}
292
295
  - If a tool creates \`TestResults\`, \`test-results\`, or \`playwright-report\` beneath source, use \`forge.reset_generated_outputs\` to quarantine only those untracked generated directories. Do not issue a recursive delete.
293
296
  - Use the attempt-scoped \`FORGE_TMPDIR\`, \`FORGE_LOG_DIR\`, \`FORGE_CACHE_DIR\`, \`FORGE_BROWSER_PROFILE_DIR\`, and \`FORGE_TEST_OUTPUT_DIR\` paths instead of shared host paths.
294
297
  - Use supplied \`FORGE_*\` URLs, ports, and paths. Do not search for a free port, kill a process occupying one, or reuse an existing dev server, browser profile, database, container, network, or volume.
295
- - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}`;
298
+ - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}${stackUnavailable}`;
296
299
  }
297
300
  return `${prompt.trimEnd()}
298
301
 
@@ -67,4 +67,10 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
67
67
  private recoverMissingQaCompletion;
68
68
  private recoverMissingCommentRepairCompletion;
69
69
  private validatePrePublicationWithRecovery;
70
+ /**
71
+ * Restarts the attempt's runtime stack when the workspace changed since it was
72
+ * launched, before a validation pass runs against it. A build of the changed
73
+ * source that fails is a validation failure the bounded repair turn can fix.
74
+ */
75
+ private refreshPrePublicationRuntime;
70
76
  }
@@ -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";
@@ -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 {
@@ -474,6 +482,8 @@ class ProviderToolActivityHeartbeat {
474
482
  timer = null;
475
483
  /** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
476
484
  isToolCallInFlight = () => this.outputState.hasActiveToolCall;
485
+ /** Forgets tool calls a previous generation left open; called before every relaunch. */
486
+ startGeneration = () => this.outputState.resetActiveToolCalls();
477
487
  constructor(outputState, emit, intervalMs) {
478
488
  this.outputState = outputState;
479
489
  this.emit = emit;
@@ -562,7 +572,12 @@ export class ProcessBackedProviderCliService {
562
572
  providerToolHeartbeatIntervalMs;
563
573
  publicationCoordinator;
564
574
  prePublicationValidator;
565
- 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())) {
566
581
  this.processRunner = processRunner;
567
582
  this.git = git;
568
583
  this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
@@ -581,7 +596,7 @@ export class ProcessBackedProviderCliService {
581
596
  await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
582
597
  const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
583
598
  const decomposeDraft = isDecomposeDraftDispatch(dispatch);
584
- 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 });
585
600
  const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
586
601
  const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
587
602
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -646,6 +661,7 @@ export class ProcessBackedProviderCliService {
646
661
  });
647
662
  },
648
663
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
664
+ onGenerationStart: toolHeartbeat.startGeneration,
649
665
  onStdoutLine: async (line) => {
650
666
  await toolHeartbeat.consume(line);
651
667
  }
@@ -763,7 +779,7 @@ export class ProcessBackedProviderCliService {
763
779
  const specPath = path.join(metadataRoot, "spec.md");
764
780
  await fs.writeFile(specPath, specBody, "utf8");
765
781
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
766
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
782
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
767
783
  const implementationPrompt = debugCycle
768
784
  ? buildDebugCyclePrompt(dispatch, phase)
769
785
  : developCycle
@@ -817,6 +833,7 @@ export class ProcessBackedProviderCliService {
817
833
  });
818
834
  },
819
835
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
836
+ onGenerationStart: toolHeartbeat.startGeneration,
820
837
  onStdoutLine: async (line) => {
821
838
  await toolHeartbeat.consume(line);
822
839
  }
@@ -910,7 +927,7 @@ export class ProcessBackedProviderCliService {
910
927
  const specPath = path.join(metadataRoot, "spec.md");
911
928
  await fs.writeFile(specPath, specBody, "utf8");
912
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");
913
- 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 });
914
931
  const architectPrompt = buildArchitectPrompt(dispatch);
915
932
  const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
916
933
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -957,6 +974,7 @@ export class ProcessBackedProviderCliService {
957
974
  });
958
975
  },
959
976
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
977
+ onGenerationStart: toolHeartbeat.startGeneration,
960
978
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
961
979
  }, context.signal);
962
980
  }
@@ -1014,7 +1032,7 @@ export class ProcessBackedProviderCliService {
1014
1032
  const specPath = path.join(metadataRoot, "spec.md");
1015
1033
  await fs.writeFile(specPath, specBody, "utf8");
1016
1034
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
1017
- 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 });
1018
1036
  const qaPrompt = buildQaPrompt(dispatch, specBody);
1019
1037
  const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
1020
1038
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -1063,6 +1081,7 @@ export class ProcessBackedProviderCliService {
1063
1081
  });
1064
1082
  },
1065
1083
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1084
+ onGenerationStart: toolHeartbeat.startGeneration,
1066
1085
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1067
1086
  }, context.signal);
1068
1087
  }
@@ -1133,6 +1152,7 @@ export class ProcessBackedProviderCliService {
1133
1152
  const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
1134
1153
  let repairSpec = null;
1135
1154
  let repairEnvironment = context.runtimeEnvironment;
1155
+ let ciRepairSpecPath = null;
1136
1156
  let completionTools = null;
1137
1157
  if (repairChecks) {
1138
1158
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -1143,6 +1163,7 @@ export class ProcessBackedProviderCliService {
1143
1163
  }
1144
1164
  const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
1145
1165
  const specPath = path.join(metadataRoot, "spec.md");
1166
+ ciRepairSpecPath = specPath;
1146
1167
  await fs.writeFile(specPath, specBody, "utf8");
1147
1168
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
1148
1169
  repairSpec = {
@@ -1154,7 +1175,9 @@ export class ProcessBackedProviderCliService {
1154
1175
  };
1155
1176
  const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
1156
1177
  repairEnvironment = readiness.environment;
1157
- 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
+ });
1158
1181
  await context.emit({
1159
1182
  role: "runner",
1160
1183
  kind: "checkpoint",
@@ -1169,7 +1192,9 @@ export class ProcessBackedProviderCliService {
1169
1192
  });
1170
1193
  }
1171
1194
  if (addressComments) {
1172
- 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
+ });
1173
1198
  await context.emit({
1174
1199
  role: "runner",
1175
1200
  kind: "checkpoint",
@@ -1220,6 +1245,7 @@ export class ProcessBackedProviderCliService {
1220
1245
  providerStarted = true;
1221
1246
  },
1222
1247
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1248
+ onGenerationStart: toolHeartbeat.startGeneration,
1223
1249
  onStdoutLine: async (line) => {
1224
1250
  await toolHeartbeat.consume(line);
1225
1251
  }
@@ -1292,6 +1318,7 @@ export class ProcessBackedProviderCliService {
1292
1318
  : addressComments
1293
1319
  ? "comment_repair"
1294
1320
  : "conflict_repair";
1321
+ const readinessSpecPath = ciRepairSpecPath;
1295
1322
  await this.validatePrePublicationWithRecovery({
1296
1323
  context,
1297
1324
  validationProfile,
@@ -1299,6 +1326,10 @@ export class ProcessBackedProviderCliService {
1299
1326
  outputState,
1300
1327
  preparedHeadSha,
1301
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
+ } : {}),
1302
1333
  });
1303
1334
  const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1304
1335
  const stagedChangedFiles = stagedChangeSet.publishable;
@@ -1377,6 +1408,7 @@ export class ProcessBackedProviderCliService {
1377
1408
  worktree,
1378
1409
  phase: "qa",
1379
1410
  runtimeEnvironment: context.runtimeEnvironment,
1411
+ hostLoadEnvironment: context.hostLoadEnvironment,
1380
1412
  });
1381
1413
  const command = buildProviderCliCommand(recoveryDispatch, {
1382
1414
  worktreePath: worktree.worktreePath,
@@ -1402,7 +1434,11 @@ export class ProcessBackedProviderCliService {
1402
1434
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1403
1435
  resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1404
1436
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1405
- }, { onStdoutLine: async (line) => await toolHeartbeat.consume(line), isToolCallInFlight: toolHeartbeat.isToolCallInFlight }, context.signal);
1437
+ }, {
1438
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line),
1439
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1440
+ onGenerationStart: toolHeartbeat.startGeneration,
1441
+ }, context.signal);
1406
1442
  }
1407
1443
  finally {
1408
1444
  toolHeartbeat.stop();
@@ -1482,6 +1518,7 @@ export class ProcessBackedProviderCliService {
1482
1518
  worktree,
1483
1519
  phase: "comment_repair",
1484
1520
  runtimeEnvironment: repairEnvironment,
1521
+ hostLoadEnvironment: context.hostLoadEnvironment,
1485
1522
  });
1486
1523
  const command = buildProviderCliCommand(recoveryDispatch, {
1487
1524
  worktreePath: worktree.worktreePath,
@@ -1519,6 +1556,7 @@ export class ProcessBackedProviderCliService {
1519
1556
  });
1520
1557
  },
1521
1558
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1559
+ onGenerationStart: toolHeartbeat.startGeneration,
1522
1560
  onStdoutLine: async (line) => {
1523
1561
  await toolHeartbeat.consume(line);
1524
1562
  },
@@ -1560,13 +1598,23 @@ export class ProcessBackedProviderCliService {
1560
1598
  return artifact;
1561
1599
  }
1562
1600
  async validatePrePublicationWithRecovery(options) {
1563
- const { context, validationProfile, repairEnvironment, outputState, preparedHeadSha, repairScope } = options;
1601
+ const { context, validationProfile, outputState, preparedHeadSha, repairScope } = options;
1564
1602
  const { dispatch, worktree } = context;
1565
1603
  const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
1566
- const environment = providerProcessEnv(dispatch, repairEnvironment);
1567
- 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);
1568
1608
  for (let repairTurn = 0;; repairTurn += 1) {
1569
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
+ }
1570
1618
  await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
1571
1619
  if (repairTurn > 0) {
1572
1620
  await context.emit({
@@ -1582,6 +1630,17 @@ export class ProcessBackedProviderCliService {
1582
1630
  catch (error) {
1583
1631
  if (!(error instanceof PrePublicationValidationError))
1584
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
+ }
1585
1644
  if (repairTurn >= maxPrePublicationRepairTurns) {
1586
1645
  await context.emit({
1587
1646
  role: "runner",
@@ -1639,6 +1698,7 @@ export class ProcessBackedProviderCliService {
1639
1698
  providerStarted = true;
1640
1699
  },
1641
1700
  isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1701
+ onGenerationStart: toolHeartbeat.startGeneration,
1642
1702
  onStdoutLine: async (line) => {
1643
1703
  await toolHeartbeat.consume(line);
1644
1704
  },
@@ -1664,6 +1724,77 @@ export class ProcessBackedProviderCliService {
1664
1724
  }
1665
1725
  }
1666
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;
1667
1798
  }
1668
1799
  function buildPrePublicationRepairPrompt(error, repairTurn, repairScope) {
1669
1800
  const invocation = [error.command, ...error.args].join(" ");