@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.fb770705136a

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 (37) hide show
  1. package/dist/bridge/bridge.service.d.ts +3 -1
  2. package/dist/bridge/bridge.service.js +11 -2
  3. package/dist/bridge/bridge.types.d.ts +6 -0
  4. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  5. package/dist/runtime/host-database-capability-boundary.js +1 -0
  6. package/dist/runtime/host-facts.d.ts +35 -0
  7. package/dist/runtime/host-facts.js +95 -0
  8. package/dist/runtime/host-load-sampler.d.ts +83 -0
  9. package/dist/runtime/host-load-sampler.js +164 -0
  10. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  11. package/dist/runtime/host-pressure-stall.js +121 -0
  12. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  13. package/dist/runtime/host-runtime-contract.js +2 -0
  14. package/dist/session/phase-completion.artifacts.js +4 -0
  15. package/dist/session/pre-publication-process.js +2 -1
  16. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  17. package/dist/session/pre-publication-skipped-tests.js +109 -0
  18. package/dist/session/pre-publication-validation.js +23 -4
  19. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  20. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  21. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  22. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  23. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  24. package/dist/session/provider-cli/provider-cli.process.js +120 -28
  25. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  26. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  27. package/dist/session/provider-cli/provider-cli.service.js +105 -19
  28. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  29. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  30. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  31. package/dist/session/provider-cli/provider-output-state.js +9 -0
  32. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  33. package/dist/session/publishable-worktree-changes.js +193 -0
  34. package/dist/session/session.types.js +12 -0
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/package.json +1 -1
@@ -392,6 +392,13 @@ Architect revision context:
392
392
  - Reviewer feedback: ${dispatch.architectRevision.feedback}
393
393
  Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
394
394
  }
395
+ /**
396
+ * Headless providers must not end a turn to wait: Forge stops the provider shortly after
397
+ * a turn ends, and nothing started in the background reports back.
398
+ */
399
+ export function providerTurnEndRule(completionStep) {
400
+ return `Ending your turn ends this run. Forge runs you headless and stops the provider process shortly after a turn ends, together with any managed command it is still running. Background tasks, Monitor, \`run_in_background\` shells and other watchers never report back after that. Do not end your turn to wait for anything: block on \`forge.wait_managed_command\` until it returns a terminal receipt (call it again while \`command_continues=true\`), then ${completionStep} in the same turn.`;
401
+ }
395
402
  export function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
396
403
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
397
404
 
@@ -403,6 +410,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
403
410
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
404
411
 
405
412
  ${completionPromptForPhase(phase)}
413
+ ${providerTurnEndRule("call the completion tool")}
406
414
 
407
415
  Finish with a concise summary of changed files and verification after calling the completion tool.`;
408
416
  }
@@ -417,6 +425,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
417
425
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
418
426
 
419
427
  ${completionPromptForDevelopCycle(phase)}
428
+ ${providerTurnEndRule("call the current phase's completion tool")}
420
429
 
421
430
  Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
422
431
  }
@@ -431,6 +440,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
431
440
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
432
441
 
433
442
  ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
443
+ ${providerTurnEndRule("call the current Debug gate's completion tool")}
434
444
 
435
445
  Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
436
446
  }
@@ -587,6 +597,7 @@ Report in-scope defects as actionable findings with repro steps, expected/actual
587
597
  Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item. If a broad regression command fails only on a surface outside both the current diff and acceptance criteria, reproduce that failure with a focused command. The regression gate may pass only when the current item has independent passing evidence and the failed command is preserved with classification out_of_scope_failure, candidate_bug_id, scope_evidence, acceptance_criteria_independent: true, repro_command, and a non-zero repro_exit_code. Never use this classification for an unexplained failure, a runner/environment failure, or a failure that can affect the current item.
588
598
 
589
599
  ${completionPromptForQaCycle("qa_plan", artifactRoot)}
600
+ ${providerTurnEndRule("call the next QA gate's completion tool, through forge.complete_qa_verdict,")}
590
601
 
591
602
  Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
592
603
  }
@@ -607,6 +618,8 @@ export function buildConflictResolvePrompt(dispatch, branchName) {
607
618
  The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
608
619
  Fetch origin, merge ${targetBranch} into ${branchName} with --no-commit, resolve conflicts conservatively, and run relevant validation when practical.
609
620
  Leave every repair change uncommitted and unpushed. Forge Bridge owns the sole final commit and compare-and-swap push after validation passes.
621
+ 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.
622
+ 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.
610
623
  Keep the original work item intent intact:
611
624
  - Work item: ${dispatch.workItem.id}
612
625
  - Title: ${dispatch.workItem.title}
@@ -644,6 +657,7 @@ Forge prepared two required inputs before this agent started:
644
657
  Read both first. The readiness contract supplies attempt-scoped E2E URLs, Playwright/browser readiness, runnable local preflight commands, and provider-only spec patterns. Run every listed local preflight. Do not override the readiness environment or bypass its provider-only exclusions: those specs require infrastructure unavailable inside this managed attempt. Record each applicable provider-only step and the provider check that supplies its proof, and leave provider CI authoritative without weakening its coverage.
645
658
 
646
659
  After repair and validation, call forge.complete_ci_repair with the complete structured handoff. Forge Bridge will validate it and will not commit, push, or report success until that gate passes. If the tool rejects the payload, correct the exact missing evidence it reports and call it again.
660
+ ${providerTurnEndRule("call forge.complete_ci_repair")}
647
661
 
648
662
  Keep the original work item intent intact:
649
663
  - Work item: ${dispatch.workItem.id}
@@ -695,6 +709,7 @@ Before handing a changed diff back for publication:
695
709
  4. Fix validation failures locally before requesting publication. Preserve acceptance criteria and assertions; do not skip tests, weaken checks, change retry budgets, or edit the trusted validation contract to get green. A tier that is still running has not failed to finish: Forge terminates a hung command at its runner-owned limit, which the receipt reports as timeout_ms (${managedMaximumCommandTimeoutMs / 60_000} minutes for dotnet_affected, ${managedQuickTierTimeoutMs / 60_000} minutes for Unit and Contract, ${managedLongTierTimeoutMs / 60_000} minutes for one shard of another tier, and more for an all-shard run, scaled to its shard waves), and its receipt then reports timed_out. Never stop waiting, or record needs_rework, because a required tier is still running. Record a blocker only when infrastructure is unavailable; when a required check ends with a terminal timed_out, timeout_termination_failed, or runner_error receipt that a rerun cannot clear; when a receipt's elapsed time stops rising across waits; or when a real failure cannot be fixed after diagnosis. Then record the exact blocker and preserve the diff without claiming validation passed.
696
710
  5. Inspect the final diff after all fixes and generated-file changes, run git diff --check, and rerun checks affected by any subsequent edit. Record commands, the affected-test selection it printed, exit statuses, and terminal evidence paths in the completion evidence. Finalize changed_files from that final diff, not an earlier repair draft.
697
711
  Only after applicable local validation passes, call forge.complete_comment_repair with the exact head, issue key, finding identities, and evidence. Legitimate no-code rejection or already-addressed outcomes are successful dispositions and do not require an empty commit or unrelated test suites; provide evidence for each disposition.
712
+ ${providerTurnEndRule("call forge.complete_comment_repair")}
698
713
  Forge Bridge owns any commit and compare-and-swap push after its independent pre-publication gate succeeds, then selectively resolves only review threads dispositioned fixed, already_addressed, or server-verified accepted_transfer while all fences still match. The accepted-transfer receipt remains in durable repair evidence and source/target scope; Forge does not post a provider reply automatically. A local pass is not a GitHub CI pass: provider-only checks remain pending until CI runs on the pushed head. Do not request another review yourself; Forge owns the green-CI-before-review sequence.
699
714
  Keep the original work item intent intact:
700
715
  - Work item: ${dispatch.workItem.id}
@@ -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);
@@ -1438,6 +1517,7 @@ export class ProcessBackedProviderCliService {
1438
1517
  args: command.args,
1439
1518
  cwd: worktree.worktreePath,
1440
1519
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1520
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1441
1521
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1442
1522
  }, {
1443
1523
  onStarted: async () => {
@@ -1449,6 +1529,8 @@ export class ProcessBackedProviderCliService {
1449
1529
  eventType: "provider_cli_started",
1450
1530
  });
1451
1531
  },
1532
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1533
+ onGenerationStart: toolHeartbeat.startGeneration,
1452
1534
  onStdoutLine: async (line) => {
1453
1535
  await toolHeartbeat.consume(line);
1454
1536
  },
@@ -1470,6 +1552,7 @@ export class ProcessBackedProviderCliService {
1470
1552
  await cleanupCompletionTools(completionTools, context.emit);
1471
1553
  }
1472
1554
  }
1555
+ options.lastRun.result = result;
1473
1556
  if (result.exitCode !== 0)
1474
1557
  throw providerCliExitFailure(command.command, result);
1475
1558
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1555,6 +1638,7 @@ export class ProcessBackedProviderCliService {
1555
1638
  args: command.args,
1556
1639
  cwd: worktree.worktreePath,
1557
1640
  env: environment,
1641
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1558
1642
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1559
1643
  }, {
1560
1644
  onStarted: async () => {
@@ -1566,6 +1650,8 @@ export class ProcessBackedProviderCliService {
1566
1650
  });
1567
1651
  providerStarted = true;
1568
1652
  },
1653
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1654
+ onGenerationStart: toolHeartbeat.startGeneration,
1569
1655
  onStdoutLine: async (line) => {
1570
1656
  await toolHeartbeat.consume(line);
1571
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) {
@@ -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[]>;