@loucompanion/forge-bridge 0.1.4-dev.a690038a6849 → 0.1.4-dev.acacfdecaad2

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 (135) 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.js +15 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  104. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  105. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  106. package/dist/session/provider-cli/provider-cli.process.js +15 -7
  107. package/dist/session/provider-cli/provider-cli.prompts.js +7 -2
  108. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  109. package/dist/session/provider-cli/provider-cli.service.js +146 -15
  110. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  111. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  112. package/dist/session/publishable-worktree-changes.js +21 -5
  113. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  114. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  115. package/dist/session/session.base.d.ts +9 -1
  116. package/dist/session/session.service.d.ts +9 -2
  117. package/dist/session/session.service.js +120 -5
  118. package/dist/session/session.types.d.ts +3 -0
  119. package/dist/session/session.types.js +6 -3
  120. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  121. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  122. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  123. package/dist/shared/process/host-process-supervisor.js +1 -1
  124. package/dist/shared/process/process-tree.d.ts +52 -0
  125. package/dist/shared/process/process-tree.js +144 -0
  126. package/dist/shared/process/process.d.ts +67 -0
  127. package/dist/shared/process/process.js +213 -11
  128. package/dist/version.d.ts +1 -1
  129. package/dist/version.js +1 -1
  130. package/dist/worktree/dependency-warmer.d.ts +25 -0
  131. package/dist/worktree/dependency-warmer.js +46 -10
  132. package/dist/worktree/worktree.service.d.ts +10 -1
  133. package/dist/worktree/worktree.service.js +42 -2
  134. package/dist/worktree/worktree.types.d.ts +7 -0
  135. package/package.json +1 -1
@@ -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
 
@@ -618,6 +621,8 @@ export function buildConflictResolvePrompt(dispatch, branchName) {
618
621
  The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
619
622
  Fetch origin, merge ${targetBranch} into ${branchName} with --no-commit, resolve conflicts conservatively, and run relevant validation when practical.
620
623
  Leave every repair change uncommitted and unpushed. Forge Bridge owns the sole final commit and compare-and-swap push after validation passes.
624
+ Deletions on ${targetBranch} are part of the merge. Never restore a file that ${targetBranch} deleted and ${branchName} never changed, and never revert ${targetBranch} edits to files ${branchName} never changed, including under .forge/. Forge rejects a resolution that does.
625
+ A modify/delete conflict (one side deleted the file, the other changed it) is a real conflict for you to decide: resolve it explicitly with \`git rm <path>\` to accept the deletion or \`git add <path>\` to keep the changed file, and name each such path and your decision in your final summary. A binary conflict has no markers: put the chosen version on disk and \`git add <path>\`. Forge rejects a merge that leaves any of these unresolved or keeps conflict markers.
621
626
  Keep the original work item intent intact:
622
627
  - Work item: ${dispatch.workItem.id}
623
628
  - Title: ${dispatch.workItem.title}
@@ -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(" ");
@@ -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>;
@@ -16,7 +16,16 @@ export interface PublishableWorktreeChangeSet {
16
16
  * `.forge/` file that differs from HEAD is an author edit and must be published.
17
17
  */
18
18
  export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
19
- /** Stages every publishable worktree change in the real index and returns both sets. */
19
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
20
+ export declare function isRuntimeOnlyPath(relativePath: string): boolean;
21
+ /**
22
+ * Stages every publishable worktree change in the real index and returns both sets.
23
+ *
24
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
25
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
26
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
27
+ * restored.
28
+ */
20
29
  export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
21
30
  /**
22
31
  * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { GitClient } from "../shared/git/git.js";
5
5
  import { NodeProcessRunner } from "../shared/process/process.js";
6
+ import { assertNoUnresolvedMergeConflicts, restoreMergeOwnedPaths } from "./provider-cli/provider-cli.merge-integrity.js";
6
7
  /**
7
8
  * Forge runtime output that is never published, whether or not the target repository
8
9
  * tracks other `.forge/` content. Completion artifacts and evidence live here.
@@ -20,7 +21,7 @@ const resetBatchSize = 200;
20
21
  */
21
22
  export function isNonPublishableWorktreeChange(relativePath, status) {
22
23
  const normalized = relativePath.trim().replaceAll("\\", "/");
23
- if (normalized === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalized.startsWith(prefix))) {
24
+ if (isRuntimeOnlyPath(normalized)) {
24
25
  return true;
25
26
  }
26
27
  if (normalized === ".forge" || normalized.startsWith(".forge/")) {
@@ -28,16 +29,31 @@ export function isNonPublishableWorktreeChange(relativePath, status) {
28
29
  }
29
30
  return false;
30
31
  }
31
- /** Stages every publishable worktree change in the real index and returns both sets. */
32
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
33
+ export function isRuntimeOnlyPath(relativePath) {
34
+ const normalizedPath = normalizeChangedFilePath(relativePath);
35
+ return normalizedPath === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalizedPath.startsWith(prefix));
36
+ }
37
+ /**
38
+ * Stages every publishable worktree change in the real index and returns both sets.
39
+ *
40
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
41
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
42
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
43
+ * restored.
44
+ */
32
45
  export async function stagePublishableWorktreeChangeSet(git, worktreePath) {
46
+ await assertNoUnresolvedMergeConflicts(git, worktreePath);
33
47
  await git.run(worktreePath, ["add", "-A"]);
34
- const excluded = (await readStagedChanges(git, worktreePath))
48
+ const excludedChanges = (await readStagedChanges(git, worktreePath))
35
49
  .filter(change => isNonPublishableWorktreeChange(change.path, change.status))
36
50
  .map(change => change.path);
37
- for (let index = 0; index < excluded.length; index += resetBatchSize) {
38
- const batch = excluded.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
51
+ for (let index = 0; index < excludedChanges.length; index += resetBatchSize) {
52
+ const batch = excludedChanges.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
39
53
  await git.run(worktreePath, ["reset", "-q", "--", ...batch]);
40
54
  }
55
+ const restored = new Set(await restoreMergeOwnedPaths(git, worktreePath, excludedChanges.filter(filePath => !isRuntimeOnlyPath(filePath))));
56
+ const excluded = excludedChanges.filter(filePath => !restored.has(filePath));
41
57
  const publishable = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
42
58
  .split(/\r?\n/)
43
59
  .map(line => line.trim())
@@ -0,0 +1,30 @@
1
+ import { type HostLoadAcquireOptions, type HostLoadAdmission, type HostLoadStepGate, type HostLoadStepRequest } from "../runtime/host-load-governor.js";
2
+ export interface SandboxHostCapacityGateOptions {
3
+ readonly write?: (line: string) => void;
4
+ readonly responseRoot?: string;
5
+ readonly pollMs?: number;
6
+ /** Fails closed if the bridge never answers (the host enforces its own maximum wait first). */
7
+ readonly maxWaitMs?: number;
8
+ /** Owner of authentic replies (root in the container; tests use their own uid). */
9
+ readonly trustedOwnerUid?: number;
10
+ }
11
+ export declare class SandboxBrokeredHostLoadGate implements HostLoadStepGate {
12
+ readonly enabled = true;
13
+ private readonly write;
14
+ private readonly responseRoot;
15
+ private readonly pollMs;
16
+ private readonly trustedOwnerUid;
17
+ readonly maxWaitMs: number;
18
+ constructor(options?: SandboxHostCapacityGateOptions);
19
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
20
+ private admission;
21
+ private send;
22
+ }
23
+ /**
24
+ * The brokered gate when the host bridge enabled it for this sandbox. The
25
+ * variable is removed once read, so commands the sandbox runs never inherit it
26
+ * (a nested Forge process must not queue behind its parent's token).
27
+ */
28
+ export declare function sandboxHostLoadGateFromEnvironment(environment?: NodeJS.ProcessEnv): HostLoadStepGate | undefined;
29
+ /** Test support: forgets the cached gate. */
30
+ export declare function resetSandboxHostLoadGateForTesting(): void;