@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.8f4846c6e7a9

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 (89) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +73 -8
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cli/cli.service.js +3 -1
  12. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  13. package/dist/runtime/attempt-process-supervisor.js +50 -0
  14. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  15. package/dist/runtime/host-database-capability-boundary.js +1 -0
  16. package/dist/runtime/host-facts.d.ts +35 -0
  17. package/dist/runtime/host-facts.js +95 -0
  18. package/dist/runtime/host-load-admission.d.ts +52 -0
  19. package/dist/runtime/host-load-admission.js +84 -0
  20. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  21. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  22. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  23. package/dist/runtime/host-load-governor-config.js +46 -0
  24. package/dist/runtime/host-load-governor.d.ts +123 -0
  25. package/dist/runtime/host-load-governor.js +415 -0
  26. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  27. package/dist/runtime/host-load-ledger-lock.js +185 -0
  28. package/dist/runtime/host-load-sampler.d.ts +121 -0
  29. package/dist/runtime/host-load-sampler.js +224 -0
  30. package/dist/runtime/host-load-step-class.d.ts +33 -0
  31. package/dist/runtime/host-load-step-class.js +46 -0
  32. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  33. package/dist/runtime/host-load-token-ledger.js +345 -0
  34. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  35. package/dist/runtime/host-pressure-stall.js +168 -0
  36. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  37. package/dist/runtime/host-runtime-contract.js +6 -1
  38. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  39. package/dist/runtime/host-runtime-lease.js +82 -11
  40. package/dist/runtime/host-runtime-promotion.js +12 -0
  41. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  42. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  43. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  44. package/dist/runtime/host-runtime-requirements.js +117 -0
  45. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  46. package/dist/runtime/managed-command-teardown.js +607 -0
  47. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  48. package/dist/runtime/playwright-browser-cache.js +227 -0
  49. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  50. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  51. package/dist/session/managed-attempt-tools.d.ts +25 -0
  52. package/dist/session/managed-attempt-tools.js +212 -15
  53. package/dist/session/managed-build-coordinator.d.ts +1 -1
  54. package/dist/session/managed-build-coordinator.js +4 -1
  55. package/dist/session/phase-completion.artifacts.js +4 -0
  56. package/dist/session/phase-completion.runtime.js +22 -17
  57. package/dist/session/pre-publication-host-load.d.ts +27 -0
  58. package/dist/session/pre-publication-host-load.js +96 -0
  59. package/dist/session/pre-publication-process.d.ts +20 -0
  60. package/dist/session/pre-publication-process.js +97 -0
  61. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  62. package/dist/session/pre-publication-skipped-tests.js +109 -0
  63. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  64. package/dist/session/pre-publication-step-execution.js +49 -0
  65. package/dist/session/pre-publication-validation.d.ts +9 -9
  66. package/dist/session/pre-publication-validation.js +44 -112
  67. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  68. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  69. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  70. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  71. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  72. package/dist/session/provider-cli/provider-cli.process.js +297 -23
  73. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  74. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  75. package/dist/session/provider-cli/provider-cli.service.js +126 -26
  76. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  77. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  78. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  79. package/dist/session/provider-cli/provider-output-state.js +9 -0
  80. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  81. package/dist/session/publishable-worktree-changes.js +193 -0
  82. package/dist/session/session.base.d.ts +3 -0
  83. package/dist/session/session.service.d.ts +2 -0
  84. package/dist/session/session.service.js +5 -0
  85. package/dist/session/session.types.d.ts +3 -0
  86. package/dist/session/session.types.js +14 -2
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/package.json +1 -1
@@ -2,14 +2,16 @@ 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 { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
5
6
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
6
7
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
7
8
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
8
9
  import { ForgeFailureError } from "../session.types.js";
9
- import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, stagePublishableWorktreeChanges, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
10
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
11
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
10
12
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
11
13
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
12
- import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
14
+ import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
13
15
  import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
14
16
  import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
15
17
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
@@ -68,12 +70,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
68
70
  const claimed = [...new Set(claimedChangedFiles)].sort();
69
71
  const actual = [...new Set(normalizedActual)].sort();
70
72
  if (hasFixedDisposition && actual.length === 0) {
71
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
73
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
72
74
  }
73
75
  if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
74
- throw new Error("Comment repair changed_files must exactly match the publishable staged source diff.");
76
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
77
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
75
78
  }
76
79
  }
80
+ /**
81
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
82
+ * published commit; otherwise the thread would be resolved without its fix. That covers
83
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
84
+ */
85
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
86
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
87
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
88
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
89
+ ]));
90
+ const payload = JSON.parse(artifact.verdictJson);
91
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
92
+ const fixed = dispositions.flatMap(value => {
93
+ const record = value;
94
+ if (record.disposition !== "fixed")
95
+ return [];
96
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
97
+ const findingPath = findingPaths.get(identity);
98
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
99
+ });
100
+ if (fixed.length === 0)
101
+ return;
102
+ const unpublished = new Set([
103
+ ...changeSet.excluded.map(normalizeChangedFilePath),
104
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
105
+ ]);
106
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
107
+ if (dropped.length > 0) {
108
+ throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
109
+ }
110
+ }
111
+ function commentRepairChangedFilesMismatch(message) {
112
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
113
+ }
114
+ function formatChangedFilesDelta(missing, unexpected) {
115
+ const parts = [
116
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
117
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
118
+ ].filter(Boolean);
119
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
120
+ }
77
121
  async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
78
122
  const payload = JSON.parse(artifact.verdictJson);
79
123
  const claimedRecords = Array.isArray(payload.changed_files)
@@ -90,11 +134,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
90
134
  const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
135
  const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
92
136
  if (hasFixedDisposition && authoritativePaths.length === 0) {
93
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
137
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
94
138
  }
95
139
  for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
96
140
  if (baselinePath && !authoritative.has(baselinePath)) {
97
- throw new Error(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
141
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
98
142
  }
99
143
  }
100
144
  payload.changed_files = authoritativePaths.map(filePath => {
@@ -170,16 +214,20 @@ function providerOwnsBranchPublication(context) {
170
214
  return context.dispatch.sandbox?.executionMode !== "docker";
171
215
  }
172
216
  function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
217
+ const hostLoadOwner = {
218
+ dispatchAttemptId: context.dispatch.sandbox?.dispatchAttemptId ?? null,
219
+ priority: runtimeAdmissionPriority(context.dispatch),
220
+ };
173
221
  if (context.processRunner)
174
- return { baselineRevision, environment, processRunner: context.processRunner };
222
+ return { baselineRevision, environment, processRunner: context.processRunner, hostLoadOwner };
175
223
  if (context.dispatch.sandbox?.executionMode !== "docker")
176
- return { baselineRevision, environment };
224
+ return { baselineRevision, environment, hostLoadOwner };
177
225
  const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
178
226
  const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
179
227
  if (observedSandboxId !== expectedSandboxId) {
180
228
  throw new ForgeFailureError("prepublication_execution_scope_invalid", `prepublication_execution_scope_invalid: Docker attempt ${expectedSandboxId} has no runner proven to execute inside that sandbox.`, "bridge");
181
229
  }
182
- return { baselineRevision, environment, processRunner: defaultRunner };
230
+ return { baselineRevision, environment, processRunner: defaultRunner, hostLoadOwner };
183
231
  }
184
232
  function remoteTrackingRefspec(branchName) {
185
233
  return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
@@ -429,10 +477,17 @@ class ProviderToolActivityHeartbeat {
429
477
  emit;
430
478
  intervalMs;
431
479
  timer = null;
480
+ /** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
481
+ isToolCallInFlight = () => this.outputState.hasActiveToolCall;
482
+ /** Forgets tool calls a previous generation left open; called before every relaunch. */
483
+ startGeneration = () => this.outputState.resetActiveToolCalls();
432
484
  constructor(outputState, emit, intervalMs) {
433
485
  this.outputState = outputState;
434
486
  this.emit = emit;
435
487
  this.intervalMs = intervalMs;
488
+ // Each heartbeat watches one provider generation. Calls an earlier generation left
489
+ // open died with it; inheriting them would hold the new generation's timers forever.
490
+ this.outputState.resetActiveToolCalls();
436
491
  }
437
492
  async consume(line) {
438
493
  const events = this.outputState.consume(line);
@@ -514,7 +569,12 @@ export class ProcessBackedProviderCliService {
514
569
  providerToolHeartbeatIntervalMs;
515
570
  publicationCoordinator;
516
571
  prePublicationValidator;
517
- constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()), prePublicationValidator = new PrePublicationValidator()) {
572
+ constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
573
+ // No host load gate here: the Docker sandbox worker (`forge` run-once via
574
+ // ForgeBridgeCliService) builds this default, and a container cannot reach the
575
+ // host's governor ledger, so Docker-mode validation is not yet governed
576
+ // (decision 0013). Only the host bridge wires HostRuntimeLeaseManager's gate.
577
+ prePublicationValidator = new PrePublicationValidator()) {
518
578
  this.processRunner = processRunner;
519
579
  this.git = git;
520
580
  this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
@@ -586,6 +646,7 @@ export class ProcessBackedProviderCliService {
586
646
  args: command.args,
587
647
  cwd: worktree.worktreePath,
588
648
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
649
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
589
650
  stdin: pipePromptToStdin ? providerPrompt : undefined
590
651
  }, {
591
652
  onStarted: async () => {
@@ -596,6 +657,8 @@ export class ProcessBackedProviderCliService {
596
657
  eventType: "provider_cli_started"
597
658
  });
598
659
  },
660
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
661
+ onGenerationStart: toolHeartbeat.startGeneration,
599
662
  onStdoutLine: async (line) => {
600
663
  await toolHeartbeat.consume(line);
601
664
  }
@@ -645,7 +708,7 @@ export class ProcessBackedProviderCliService {
645
708
  await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
646
709
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
647
710
  if (!proposalArtifact) {
648
- throw new Error("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.");
711
+ throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
649
712
  }
650
713
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
651
714
  const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
@@ -668,7 +731,7 @@ export class ProcessBackedProviderCliService {
668
731
  await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
669
732
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
670
733
  if (!proposalArtifact) {
671
- throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
734
+ throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
672
735
  }
673
736
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
674
737
  const draftJson = proposal["draft_json"];
@@ -755,6 +818,7 @@ export class ProcessBackedProviderCliService {
755
818
  args: command.args,
756
819
  cwd: worktree.worktreePath,
757
820
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
821
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
758
822
  stdin: pipePromptToStdin ? providerPrompt : undefined
759
823
  }, {
760
824
  onStarted: async () => {
@@ -765,6 +829,8 @@ export class ProcessBackedProviderCliService {
765
829
  eventType: "provider_cli_started"
766
830
  });
767
831
  },
832
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
833
+ onGenerationStart: toolHeartbeat.startGeneration,
768
834
  onStdoutLine: async (line) => {
769
835
  await toolHeartbeat.consume(line);
770
836
  }
@@ -806,7 +872,7 @@ export class ProcessBackedProviderCliService {
806
872
  eventType: "worktree_branch_pushed"
807
873
  });
808
874
  }
809
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
875
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
810
876
  for (const artifact of completionArtifacts) {
811
877
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
812
878
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -893,6 +959,7 @@ export class ProcessBackedProviderCliService {
893
959
  args: command.args,
894
960
  cwd: worktree.worktreePath,
895
961
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
962
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
896
963
  stdin: pipePromptToStdin ? providerPrompt : undefined
897
964
  }, {
898
965
  onStarted: async () => {
@@ -903,6 +970,8 @@ export class ProcessBackedProviderCliService {
903
970
  eventType: "provider_cli_started"
904
971
  });
905
972
  },
973
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
974
+ onGenerationStart: toolHeartbeat.startGeneration,
906
975
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
907
976
  }, context.signal);
908
977
  }
@@ -923,7 +992,7 @@ export class ProcessBackedProviderCliService {
923
992
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
924
993
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
925
994
  if (!architectArtifact) {
926
- throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
995
+ throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
927
996
  }
928
997
  if (!liveArchitectEvents.hasEmitted()) {
929
998
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -997,6 +1066,7 @@ export class ProcessBackedProviderCliService {
997
1066
  args: command.args,
998
1067
  cwd: worktree.worktreePath,
999
1068
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1069
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1000
1070
  stdin: pipePromptToStdin ? providerPrompt : undefined
1001
1071
  }, {
1002
1072
  onStarted: async () => {
@@ -1007,6 +1077,8 @@ export class ProcessBackedProviderCliService {
1007
1077
  eventType: "provider_cli_started"
1008
1078
  });
1009
1079
  },
1080
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1081
+ onGenerationStart: toolHeartbeat.startGeneration,
1010
1082
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1011
1083
  }, context.signal);
1012
1084
  }
@@ -1026,17 +1098,19 @@ export class ProcessBackedProviderCliService {
1026
1098
  eventType: "provider_cli_completed"
1027
1099
  });
1028
1100
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
1101
+ const lastRun = { result };
1029
1102
  let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1030
1103
  if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1031
1104
  // A headless provider that ends its turn to "wait for a background watcher"
1032
1105
  // exits for good. Resume the same thread instead of failing the session.
1033
- qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
1106
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1034
1107
  }
1035
1108
  if (!qaArtifact) {
1036
1109
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
1037
- throw new Error(verdictOnly
1038
- ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
1039
- : "Provider CLI QA completed but did not call the Forge QA completion tool.");
1110
+ if (verdictOnly) {
1111
+ throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
1112
+ }
1113
+ throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
1040
1114
  }
1041
1115
  await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1042
1116
  if (!liveQaEvents.hasEmitted()) {
@@ -1149,6 +1223,7 @@ export class ProcessBackedProviderCliService {
1149
1223
  args: command.args,
1150
1224
  cwd: worktree.worktreePath,
1151
1225
  env: providerProcessEnv(dispatch, repairEnvironment),
1226
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1152
1227
  stdin: pipePromptToStdin ? providerPrompt : undefined
1153
1228
  }, {
1154
1229
  onStarted: async () => {
@@ -1160,6 +1235,8 @@ export class ProcessBackedProviderCliService {
1160
1235
  });
1161
1236
  providerStarted = true;
1162
1237
  },
1238
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1239
+ onGenerationStart: toolHeartbeat.startGeneration,
1163
1240
  onStdoutLine: async (line) => {
1164
1241
  await toolHeartbeat.consume(line);
1165
1242
  }
@@ -1194,7 +1271,7 @@ export class ProcessBackedProviderCliService {
1194
1271
  if (repairChecks) {
1195
1272
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1196
1273
  if (!repairArtifact) {
1197
- throw new Error("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.");
1274
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
1198
1275
  }
1199
1276
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1200
1277
  throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
@@ -1202,16 +1279,18 @@ export class ProcessBackedProviderCliService {
1202
1279
  }
1203
1280
  if (addressComments) {
1204
1281
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1282
+ const lastRun = { result };
1205
1283
  if (!repairArtifact) {
1206
1284
  repairArtifact = await this.recoverMissingCommentRepairCompletion({
1207
1285
  context,
1208
1286
  repairEnvironment,
1209
1287
  outputState,
1210
1288
  preparedHeadSha,
1289
+ lastRun,
1211
1290
  });
1212
1291
  }
1213
1292
  if (!repairArtifact) {
1214
- throw new Error("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.");
1293
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
1215
1294
  }
1216
1295
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1217
1296
  throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
@@ -1220,7 +1299,9 @@ export class ProcessBackedProviderCliService {
1220
1299
  }
1221
1300
  let commentRepairBaselineChangedFiles = null;
1222
1301
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1302
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1303
+ commentRepairBaselineChangedFiles = baseline.publishable;
1304
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1305
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1306
  }
1226
1307
  const validationProfile = repairChecks
@@ -1236,8 +1317,10 @@ export class ProcessBackedProviderCliService {
1236
1317
  preparedHeadSha,
1237
1318
  repairScope: "pull_request",
1238
1319
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1320
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1321
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1322
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1323
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1324
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1325
  }
1243
1326
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1334,13 +1417,19 @@ export class ProcessBackedProviderCliService {
1334
1417
  args: command.args,
1335
1418
  cwd: worktree.worktreePath,
1336
1419
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1420
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1337
1421
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1338
- }, { onStdoutLine: async (line) => await toolHeartbeat.consume(line) }, context.signal);
1422
+ }, {
1423
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line),
1424
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1425
+ onGenerationStart: toolHeartbeat.startGeneration,
1426
+ }, context.signal);
1339
1427
  }
1340
1428
  finally {
1341
1429
  toolHeartbeat.stop();
1342
1430
  await cleanupCompletionTools(completionTools, context.emit);
1343
1431
  }
1432
+ options.lastRun.result = result;
1344
1433
  if (result.exitCode !== 0)
1345
1434
  throw providerCliExitFailure(command.command, result);
1346
1435
  const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
@@ -1397,10 +1486,14 @@ export class ProcessBackedProviderCliService {
1397
1486
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1487
  };
1399
1488
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1489
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1490
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1491
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1492
  "Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
1402
- "Review the current diff and the durable review snapshot, preserve the validation evidence already gathered,",
1403
- "then call forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1493
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1494
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1495
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1496
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1497
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1498
  ].join(" ");
1406
1499
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -1434,6 +1527,7 @@ export class ProcessBackedProviderCliService {
1434
1527
  args: command.args,
1435
1528
  cwd: worktree.worktreePath,
1436
1529
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1530
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1437
1531
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1438
1532
  }, {
1439
1533
  onStarted: async () => {
@@ -1445,6 +1539,8 @@ export class ProcessBackedProviderCliService {
1445
1539
  eventType: "provider_cli_started",
1446
1540
  });
1447
1541
  },
1542
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1543
+ onGenerationStart: toolHeartbeat.startGeneration,
1448
1544
  onStdoutLine: async (line) => {
1449
1545
  await toolHeartbeat.consume(line);
1450
1546
  },
@@ -1466,6 +1562,7 @@ export class ProcessBackedProviderCliService {
1466
1562
  await cleanupCompletionTools(completionTools, context.emit);
1467
1563
  }
1468
1564
  }
1565
+ options.lastRun.result = result;
1469
1566
  if (result.exitCode !== 0)
1470
1567
  throw providerCliExitFailure(command.command, result);
1471
1568
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1551,6 +1648,7 @@ export class ProcessBackedProviderCliService {
1551
1648
  args: command.args,
1552
1649
  cwd: worktree.worktreePath,
1553
1650
  env: environment,
1651
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1554
1652
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1555
1653
  }, {
1556
1654
  onStarted: async () => {
@@ -1562,6 +1660,8 @@ export class ProcessBackedProviderCliService {
1562
1660
  });
1563
1661
  providerStarted = true;
1564
1662
  },
1663
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1664
+ onGenerationStart: toolHeartbeat.startGeneration,
1565
1665
  onStdoutLine: async (line) => {
1566
1666
  await toolHeartbeat.consume(line);
1567
1667
  },
@@ -0,0 +1,6 @@
1
+ /**
2
+ * True while an attempt-owned managed command (a receipt under
3
+ * `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
4
+ * Unreadable or stale receipts do not count.
5
+ */
6
+ export declare function hasNonterminalManagedCommand(logDirectory: string | undefined, nowMs?: number): Promise<boolean>;
@@ -0,0 +1,47 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ const nonterminalManagedCommandStatuses = new Set(["starting", "running", "waiting_for_build_slot"]);
4
+ // A running receipt is rewritten every 5 s. One that has not changed for a minute
5
+ // belongs to a command whose supervisor is gone, so it no longer holds the provider open.
6
+ const runningReceiptStaleMs = 60_000;
7
+ // Starting and queued receipts are written once. They hold the provider open for at most
8
+ // the command's own timeout (the managed-command maximum when absent) plus a margin.
9
+ const maximumManagedCommandTimeoutMs = 2 * 60 * 60_000;
10
+ const queuedReceiptMarginMs = 60_000;
11
+ /**
12
+ * True while an attempt-owned managed command (a receipt under
13
+ * `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
14
+ * Unreadable or stale receipts do not count.
15
+ */
16
+ export async function hasNonterminalManagedCommand(logDirectory, nowMs = Date.now()) {
17
+ if (!logDirectory?.trim())
18
+ return false;
19
+ const directory = path.join(logDirectory, "managed-commands");
20
+ const names = await fs.readdir(directory).catch(() => []);
21
+ for (const name of names) {
22
+ if (!name.endsWith(".receipt.json"))
23
+ continue;
24
+ if (await receiptHoldsProvider(path.join(directory, name), nowMs))
25
+ return true;
26
+ }
27
+ return false;
28
+ }
29
+ async function receiptHoldsProvider(receiptPath, nowMs) {
30
+ try {
31
+ const [stat, content] = await Promise.all([fs.stat(receiptPath), fs.readFile(receiptPath, "utf8")]);
32
+ const receipt = JSON.parse(content);
33
+ const status = typeof receipt.status === "string" ? receipt.status : "";
34
+ if (!nonterminalManagedCommandStatuses.has(status))
35
+ return false;
36
+ const ageMs = nowMs - stat.mtimeMs;
37
+ if (status === "running")
38
+ return ageMs <= runningReceiptStaleMs;
39
+ const timeoutMs = typeof receipt.timeout_ms === "number" && Number.isFinite(receipt.timeout_ms)
40
+ ? receipt.timeout_ms
41
+ : maximumManagedCommandTimeoutMs;
42
+ return ageMs <= timeoutMs + queuedReceiptMarginMs;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
@@ -9,6 +9,12 @@ export interface ProviderOutputState {
9
9
  finalMessage: string | null;
10
10
  /** True only while the provider has reported a tool/command start without a matching completion. */
11
11
  readonly hasActiveToolCall: boolean;
12
+ /**
13
+ * Forgets tool calls a previous provider generation started but never completed. A
14
+ * generation that exits mid-call reports no completion, and the next generation must not
15
+ * inherit that call as still in flight.
16
+ */
17
+ resetActiveToolCalls(): void;
12
18
  /** Accumulated provider-reported token usage for this run, or null when none was reported. */
13
19
  readonly usage: ProviderUsage | null;
14
20
  consume(line: string): readonly RunnerDispatchEvent[];
@@ -43,6 +43,9 @@ class CursorStreamJsonState {
43
43
  get hasActiveToolCall() {
44
44
  return this.activeToolCallCount > 0;
45
45
  }
46
+ resetActiveToolCalls() {
47
+ this.activeToolCallCount = 0;
48
+ }
46
49
  consume(line) {
47
50
  const event = parseJsonLine(line);
48
51
  if (!event) {
@@ -264,6 +267,9 @@ class ClaudeStreamJsonState {
264
267
  get hasActiveToolCall() {
265
268
  return this.activeToolUses.size > 0;
266
269
  }
270
+ resetActiveToolCalls() {
271
+ this.activeToolUses.clear();
272
+ }
267
273
  consume(line) {
268
274
  const event = parseJsonLine(line);
269
275
  if (!event) {
@@ -544,6 +550,9 @@ class CodexJsonState {
544
550
  get hasActiveToolCall() {
545
551
  return this.activeToolCallCount > 0;
546
552
  }
553
+ resetActiveToolCalls() {
554
+ this.activeToolCallCount = 0;
555
+ }
547
556
  consume(line) {
548
557
  const event = parseJsonLine(line);
549
558
  if (!event) {
@@ -0,0 +1,54 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type ProcessRunner } from "../shared/process/process.js";
3
+ export interface PublishableWorktreeChangeSet {
4
+ /** Paths staged for publication, as `git diff --cached --name-only` reports them. */
5
+ readonly publishable: readonly string[];
6
+ /** Worktree changes Forge treats as runtime output and leaves unstaged. */
7
+ readonly excluded: readonly string[];
8
+ }
9
+ /**
10
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
11
+ *
12
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
13
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
14
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
15
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
16
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
17
+ */
18
+ export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
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
+ */
29
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
30
+ /**
31
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
32
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
33
+ * `worktreePath` is not the root of a git worktree.
34
+ */
35
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
36
+ /** Compares claimed `changed_files` paths with the publishable diff. */
37
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
38
+ readonly missing: readonly string[];
39
+ readonly unexpected: readonly string[];
40
+ };
41
+ export declare function normalizeChangedFilePath(value: string): string;
42
+ /**
43
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
44
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
45
+ * in the same turn instead of failing at publication.
46
+ */
47
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
48
+ /**
49
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
50
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
51
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
52
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
53
+ */
54
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;