@loucompanion/forge-bridge 0.1.4-dev.41da3780c451 → 0.1.4-dev.4677bbd22f17

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 (58) hide show
  1. package/README.md +3 -3
  2. package/dist/bridge/bridge.service.d.ts +12 -1
  3. package/dist/bridge/bridge.service.js +51 -5
  4. package/dist/bridge/bridge.types.d.ts +6 -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/cli/cli.help.js +2 -2
  8. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  9. package/dist/runtime/attempt-process-supervisor.js +74 -1
  10. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  11. package/dist/runtime/host-database-capability-boundary.js +1 -0
  12. package/dist/runtime/host-facts.d.ts +35 -0
  13. package/dist/runtime/host-facts.js +95 -0
  14. package/dist/runtime/host-load-sampler.d.ts +83 -0
  15. package/dist/runtime/host-load-sampler.js +164 -0
  16. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  17. package/dist/runtime/host-pressure-stall.js +121 -0
  18. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  19. package/dist/runtime/host-runtime-contract.js +2 -0
  20. package/dist/runtime/host-runtime-lease.js +55 -9
  21. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  22. package/dist/runtime/managed-command-teardown.js +607 -0
  23. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  24. package/dist/runtime/playwright-browser-cache.js +227 -0
  25. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  26. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  27. package/dist/session/managed-attempt-tools.d.ts +25 -0
  28. package/dist/session/managed-attempt-tools.js +212 -15
  29. package/dist/session/managed-build-coordinator.d.ts +1 -1
  30. package/dist/session/managed-build-coordinator.js +4 -1
  31. package/dist/session/phase-completion.artifacts.js +4 -0
  32. package/dist/session/phase-completion.runtime.js +22 -17
  33. package/dist/session/pre-publication-process.d.ts +20 -0
  34. package/dist/session/pre-publication-process.js +97 -0
  35. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  36. package/dist/session/pre-publication-skipped-tests.js +109 -0
  37. package/dist/session/pre-publication-validation.js +27 -57
  38. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  39. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  40. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  41. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  42. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  43. package/dist/session/provider-cli/provider-cli.process.js +297 -23
  44. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  45. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  46. package/dist/session/provider-cli/provider-cli.service.js +112 -22
  47. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  48. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  49. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  50. package/dist/session/provider-cli/provider-output-state.js +9 -0
  51. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  52. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  53. package/dist/session/publishable-worktree-changes.js +193 -0
  54. package/dist/session/session.types.js +12 -0
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/dist/worktree/dependency-warmer.js +74 -0
  58. package/package.json +1 -1
@@ -6,10 +6,11 @@ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-inject
6
6
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
7
7
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
8
8
  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";
9
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
10
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
10
11
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
11
12
  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";
13
+ import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
13
14
  import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
14
15
  import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
15
16
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
@@ -68,12 +69,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
68
69
  const claimed = [...new Set(claimedChangedFiles)].sort();
69
70
  const actual = [...new Set(normalizedActual)].sort();
70
71
  if (hasFixedDisposition && actual.length === 0) {
71
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
72
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
72
73
  }
73
74
  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.");
75
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
76
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
75
77
  }
76
78
  }
79
+ /**
80
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
81
+ * published commit; otherwise the thread would be resolved without its fix. That covers
82
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
83
+ */
84
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
85
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
86
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
87
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
88
+ ]));
89
+ const payload = JSON.parse(artifact.verdictJson);
90
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
+ const fixed = dispositions.flatMap(value => {
92
+ const record = value;
93
+ if (record.disposition !== "fixed")
94
+ return [];
95
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
96
+ const findingPath = findingPaths.get(identity);
97
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
98
+ });
99
+ if (fixed.length === 0)
100
+ return;
101
+ const unpublished = new Set([
102
+ ...changeSet.excluded.map(normalizeChangedFilePath),
103
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
104
+ ]);
105
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
106
+ if (dropped.length > 0) {
107
+ 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.`);
108
+ }
109
+ }
110
+ function commentRepairChangedFilesMismatch(message) {
111
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
112
+ }
113
+ function formatChangedFilesDelta(missing, unexpected) {
114
+ const parts = [
115
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
116
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
117
+ ].filter(Boolean);
118
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
119
+ }
77
120
  async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
78
121
  const payload = JSON.parse(artifact.verdictJson);
79
122
  const claimedRecords = Array.isArray(payload.changed_files)
@@ -90,11 +133,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
90
133
  const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
134
  const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
92
135
  if (hasFixedDisposition && authoritativePaths.length === 0) {
93
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
136
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
94
137
  }
95
138
  for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
96
139
  if (baselinePath && !authoritative.has(baselinePath)) {
97
- throw new Error(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
140
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
98
141
  }
99
142
  }
100
143
  payload.changed_files = authoritativePaths.map(filePath => {
@@ -429,10 +472,17 @@ class ProviderToolActivityHeartbeat {
429
472
  emit;
430
473
  intervalMs;
431
474
  timer = null;
475
+ /** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
476
+ isToolCallInFlight = () => this.outputState.hasActiveToolCall;
477
+ /** Forgets tool calls a previous generation left open; called before every relaunch. */
478
+ startGeneration = () => this.outputState.resetActiveToolCalls();
432
479
  constructor(outputState, emit, intervalMs) {
433
480
  this.outputState = outputState;
434
481
  this.emit = emit;
435
482
  this.intervalMs = intervalMs;
483
+ // Each heartbeat watches one provider generation. Calls an earlier generation left
484
+ // open died with it; inheriting them would hold the new generation's timers forever.
485
+ this.outputState.resetActiveToolCalls();
436
486
  }
437
487
  async consume(line) {
438
488
  const events = this.outputState.consume(line);
@@ -586,6 +636,7 @@ export class ProcessBackedProviderCliService {
586
636
  args: command.args,
587
637
  cwd: worktree.worktreePath,
588
638
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
639
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
589
640
  stdin: pipePromptToStdin ? providerPrompt : undefined
590
641
  }, {
591
642
  onStarted: async () => {
@@ -596,6 +647,8 @@ export class ProcessBackedProviderCliService {
596
647
  eventType: "provider_cli_started"
597
648
  });
598
649
  },
650
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
651
+ onGenerationStart: toolHeartbeat.startGeneration,
599
652
  onStdoutLine: async (line) => {
600
653
  await toolHeartbeat.consume(line);
601
654
  }
@@ -645,7 +698,7 @@ export class ProcessBackedProviderCliService {
645
698
  await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
646
699
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
647
700
  if (!proposalArtifact) {
648
- throw new Error("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.");
701
+ throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
649
702
  }
650
703
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
651
704
  const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
@@ -668,7 +721,7 @@ export class ProcessBackedProviderCliService {
668
721
  await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
669
722
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
670
723
  if (!proposalArtifact) {
671
- throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
724
+ throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
672
725
  }
673
726
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
674
727
  const draftJson = proposal["draft_json"];
@@ -755,6 +808,7 @@ export class ProcessBackedProviderCliService {
755
808
  args: command.args,
756
809
  cwd: worktree.worktreePath,
757
810
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
811
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
758
812
  stdin: pipePromptToStdin ? providerPrompt : undefined
759
813
  }, {
760
814
  onStarted: async () => {
@@ -765,6 +819,8 @@ export class ProcessBackedProviderCliService {
765
819
  eventType: "provider_cli_started"
766
820
  });
767
821
  },
822
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
823
+ onGenerationStart: toolHeartbeat.startGeneration,
768
824
  onStdoutLine: async (line) => {
769
825
  await toolHeartbeat.consume(line);
770
826
  }
@@ -806,7 +862,7 @@ export class ProcessBackedProviderCliService {
806
862
  eventType: "worktree_branch_pushed"
807
863
  });
808
864
  }
809
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
865
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
810
866
  for (const artifact of completionArtifacts) {
811
867
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
812
868
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -893,6 +949,7 @@ export class ProcessBackedProviderCliService {
893
949
  args: command.args,
894
950
  cwd: worktree.worktreePath,
895
951
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
952
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
896
953
  stdin: pipePromptToStdin ? providerPrompt : undefined
897
954
  }, {
898
955
  onStarted: async () => {
@@ -903,6 +960,8 @@ export class ProcessBackedProviderCliService {
903
960
  eventType: "provider_cli_started"
904
961
  });
905
962
  },
963
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
964
+ onGenerationStart: toolHeartbeat.startGeneration,
906
965
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
907
966
  }, context.signal);
908
967
  }
@@ -923,7 +982,7 @@ export class ProcessBackedProviderCliService {
923
982
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
924
983
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
925
984
  if (!architectArtifact) {
926
- throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
985
+ throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
927
986
  }
928
987
  if (!liveArchitectEvents.hasEmitted()) {
929
988
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -997,6 +1056,7 @@ export class ProcessBackedProviderCliService {
997
1056
  args: command.args,
998
1057
  cwd: worktree.worktreePath,
999
1058
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1059
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1000
1060
  stdin: pipePromptToStdin ? providerPrompt : undefined
1001
1061
  }, {
1002
1062
  onStarted: async () => {
@@ -1007,6 +1067,8 @@ export class ProcessBackedProviderCliService {
1007
1067
  eventType: "provider_cli_started"
1008
1068
  });
1009
1069
  },
1070
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1071
+ onGenerationStart: toolHeartbeat.startGeneration,
1010
1072
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1011
1073
  }, context.signal);
1012
1074
  }
@@ -1026,17 +1088,19 @@ export class ProcessBackedProviderCliService {
1026
1088
  eventType: "provider_cli_completed"
1027
1089
  });
1028
1090
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
1091
+ const lastRun = { result };
1029
1092
  let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1030
1093
  if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1031
1094
  // A headless provider that ends its turn to "wait for a background watcher"
1032
1095
  // exits for good. Resume the same thread instead of failing the session.
1033
- qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
1096
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1034
1097
  }
1035
1098
  if (!qaArtifact) {
1036
1099
  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.");
1100
+ if (verdictOnly) {
1101
+ throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
1102
+ }
1103
+ throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
1040
1104
  }
1041
1105
  await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1042
1106
  if (!liveQaEvents.hasEmitted()) {
@@ -1149,6 +1213,7 @@ export class ProcessBackedProviderCliService {
1149
1213
  args: command.args,
1150
1214
  cwd: worktree.worktreePath,
1151
1215
  env: providerProcessEnv(dispatch, repairEnvironment),
1216
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1152
1217
  stdin: pipePromptToStdin ? providerPrompt : undefined
1153
1218
  }, {
1154
1219
  onStarted: async () => {
@@ -1160,6 +1225,8 @@ export class ProcessBackedProviderCliService {
1160
1225
  });
1161
1226
  providerStarted = true;
1162
1227
  },
1228
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1229
+ onGenerationStart: toolHeartbeat.startGeneration,
1163
1230
  onStdoutLine: async (line) => {
1164
1231
  await toolHeartbeat.consume(line);
1165
1232
  }
@@ -1194,7 +1261,7 @@ export class ProcessBackedProviderCliService {
1194
1261
  if (repairChecks) {
1195
1262
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1196
1263
  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.");
1264
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
1198
1265
  }
1199
1266
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1200
1267
  throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
@@ -1202,16 +1269,18 @@ export class ProcessBackedProviderCliService {
1202
1269
  }
1203
1270
  if (addressComments) {
1204
1271
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1272
+ const lastRun = { result };
1205
1273
  if (!repairArtifact) {
1206
1274
  repairArtifact = await this.recoverMissingCommentRepairCompletion({
1207
1275
  context,
1208
1276
  repairEnvironment,
1209
1277
  outputState,
1210
1278
  preparedHeadSha,
1279
+ lastRun,
1211
1280
  });
1212
1281
  }
1213
1282
  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.");
1283
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
1215
1284
  }
1216
1285
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1217
1286
  throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
@@ -1220,7 +1289,9 @@ export class ProcessBackedProviderCliService {
1220
1289
  }
1221
1290
  let commentRepairBaselineChangedFiles = null;
1222
1291
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1292
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1293
+ commentRepairBaselineChangedFiles = baseline.publishable;
1294
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1295
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1296
  }
1226
1297
  const validationProfile = repairChecks
@@ -1236,8 +1307,10 @@ export class ProcessBackedProviderCliService {
1236
1307
  preparedHeadSha,
1237
1308
  repairScope: "pull_request",
1238
1309
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1310
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1311
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1312
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1313
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1314
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1315
  }
1243
1316
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1334,13 +1407,19 @@ export class ProcessBackedProviderCliService {
1334
1407
  args: command.args,
1335
1408
  cwd: worktree.worktreePath,
1336
1409
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1410
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1337
1411
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1338
- }, { onStdoutLine: async (line) => await toolHeartbeat.consume(line) }, context.signal);
1412
+ }, {
1413
+ onStdoutLine: async (line) => await toolHeartbeat.consume(line),
1414
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1415
+ onGenerationStart: toolHeartbeat.startGeneration,
1416
+ }, context.signal);
1339
1417
  }
1340
1418
  finally {
1341
1419
  toolHeartbeat.stop();
1342
1420
  await cleanupCompletionTools(completionTools, context.emit);
1343
1421
  }
1422
+ options.lastRun.result = result;
1344
1423
  if (result.exitCode !== 0)
1345
1424
  throw providerCliExitFailure(command.command, result);
1346
1425
  const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
@@ -1397,10 +1476,14 @@ export class ProcessBackedProviderCliService {
1397
1476
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1477
  };
1399
1478
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1479
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1480
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1481
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1482
  "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.",
1483
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1484
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1485
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1486
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1487
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1488
  ].join(" ");
1406
1489
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -1434,6 +1517,7 @@ export class ProcessBackedProviderCliService {
1434
1517
  args: command.args,
1435
1518
  cwd: worktree.worktreePath,
1436
1519
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1520
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1437
1521
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1438
1522
  }, {
1439
1523
  onStarted: async () => {
@@ -1445,6 +1529,8 @@ export class ProcessBackedProviderCliService {
1445
1529
  eventType: "provider_cli_started",
1446
1530
  });
1447
1531
  },
1532
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1533
+ onGenerationStart: toolHeartbeat.startGeneration,
1448
1534
  onStdoutLine: async (line) => {
1449
1535
  await toolHeartbeat.consume(line);
1450
1536
  },
@@ -1466,6 +1552,7 @@ export class ProcessBackedProviderCliService {
1466
1552
  await cleanupCompletionTools(completionTools, context.emit);
1467
1553
  }
1468
1554
  }
1555
+ options.lastRun.result = result;
1469
1556
  if (result.exitCode !== 0)
1470
1557
  throw providerCliExitFailure(command.command, result);
1471
1558
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1551,6 +1638,7 @@ export class ProcessBackedProviderCliService {
1551
1638
  args: command.args,
1552
1639
  cwd: worktree.worktreePath,
1553
1640
  env: environment,
1641
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1554
1642
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1555
1643
  }, {
1556
1644
  onStarted: async () => {
@@ -1562,6 +1650,8 @@ export class ProcessBackedProviderCliService {
1562
1650
  });
1563
1651
  providerStarted = true;
1564
1652
  },
1653
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1654
+ onGenerationStart: toolHeartbeat.startGeneration,
1565
1655
  onStdoutLine: async (line) => {
1566
1656
  await toolHeartbeat.consume(line);
1567
1657
  },
@@ -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) {
@@ -4,7 +4,8 @@ export type InputTokenSemantics = "includes_cached_input" | "excludes_cache_toke
4
4
  export declare const PROVIDER_USAGE_SCHEMA_VERSION = 1;
5
5
  /**
6
6
  * Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
7
- * here; the API recomputes cost from these tokens x model rates (ADR-0006).
7
+ * here; the API recomputes cost from these tokens x model rates (legacy
8
+ * ADR-0006, .forge-designer/decisions/legacy/0006-cost-capture.md).
8
9
  */
9
10
  export interface ProviderUsage {
10
11
  /** Normalized total input. Cached input is a subset, never an additive peer. */
@@ -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[]>;