@loucompanion/forge-bridge 0.1.4-dev.9e8a5b93cbcb → 0.1.4-dev.a690038a6849

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 (52) hide show
  1. package/dist/bridge/bridge.service.d.ts +12 -1
  2. package/dist/bridge/bridge.service.js +51 -5
  3. package/dist/bridge/bridge.types.d.ts +6 -0
  4. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  5. package/dist/bridge/dispatch-result-outbox.js +31 -6
  6. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  7. package/dist/runtime/attempt-process-supervisor.js +50 -0
  8. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  9. package/dist/runtime/host-database-capability-boundary.js +1 -0
  10. package/dist/runtime/host-facts.d.ts +35 -0
  11. package/dist/runtime/host-facts.js +95 -0
  12. package/dist/runtime/host-load-sampler.d.ts +83 -0
  13. package/dist/runtime/host-load-sampler.js +164 -0
  14. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  15. package/dist/runtime/host-pressure-stall.js +121 -0
  16. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  17. package/dist/runtime/host-runtime-contract.js +2 -0
  18. package/dist/runtime/host-runtime-lease.js +55 -9
  19. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  20. package/dist/runtime/managed-command-teardown.js +607 -0
  21. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  22. package/dist/runtime/playwright-browser-cache.js +227 -0
  23. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  24. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  25. package/dist/session/managed-attempt-tools.d.ts +25 -0
  26. package/dist/session/managed-attempt-tools.js +212 -15
  27. package/dist/session/managed-build-coordinator.d.ts +1 -1
  28. package/dist/session/managed-build-coordinator.js +4 -1
  29. package/dist/session/phase-completion.artifacts.js +4 -0
  30. package/dist/session/phase-completion.runtime.js +22 -17
  31. package/dist/session/pre-publication-process.d.ts +20 -0
  32. package/dist/session/pre-publication-process.js +97 -0
  33. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  34. package/dist/session/pre-publication-skipped-tests.js +109 -0
  35. package/dist/session/pre-publication-validation.js +27 -57
  36. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  37. package/dist/session/provider-cli/provider-cli.artifacts.js +7 -13
  38. package/dist/session/provider-cli/provider-cli.process.d.ts +28 -1
  39. package/dist/session/provider-cli/provider-cli.process.js +177 -15
  40. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  41. package/dist/session/provider-cli/provider-cli.prompts.js +13 -0
  42. package/dist/session/provider-cli/provider-cli.service.js +99 -22
  43. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  44. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  45. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  46. package/dist/session/provider-cli/provider-output-state.js +9 -0
  47. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  48. package/dist/session/publishable-worktree-changes.js +177 -0
  49. package/dist/session/session.types.js +9 -0
  50. package/dist/version.d.ts +1 -1
  51. package/dist/version.js +1 -1
  52. package/package.json +1 -1
@@ -35,6 +35,11 @@ export declare function buildArchitectPrompt(dispatch: RunOnceDispatchPacket): s
35
35
  export declare function architectDependencyInstruction(dispatch: RunOnceDispatchPacket): string;
36
36
  export declare function designerRefInstruction(dispatch: RunOnceDispatchPacket): string;
37
37
  export declare function architectRevisionInstruction(dispatch: RunOnceDispatchPacket): string;
38
+ /**
39
+ * Headless providers must not end a turn to wait: Forge stops the provider shortly after
40
+ * a turn ends, and nothing started in the background reports back.
41
+ */
42
+ export declare function providerTurnEndRule(completionStep: string): string;
38
43
  export declare function buildImplementationPrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
39
44
  export declare function buildDevelopCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
40
45
  export declare function buildDebugCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
@@ -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
  }
@@ -644,6 +655,7 @@ Forge prepared two required inputs before this agent started:
644
655
  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
656
 
646
657
  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.
658
+ ${providerTurnEndRule("call forge.complete_ci_repair")}
647
659
 
648
660
  Keep the original work item intent intact:
649
661
  - Work item: ${dispatch.workItem.id}
@@ -695,6 +707,7 @@ Before handing a changed diff back for publication:
695
707
  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
708
  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
709
  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.
710
+ ${providerTurnEndRule("call forge.complete_comment_repair")}
698
711
  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
712
  Keep the original work item intent intact:
700
713
  - 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,15 @@ 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;
432
477
  constructor(outputState, emit, intervalMs) {
433
478
  this.outputState = outputState;
434
479
  this.emit = emit;
435
480
  this.intervalMs = intervalMs;
481
+ // Each heartbeat watches one provider generation. Calls an earlier generation left
482
+ // open died with it; inheriting them would hold the new generation's timers forever.
483
+ this.outputState.resetActiveToolCalls();
436
484
  }
437
485
  async consume(line) {
438
486
  const events = this.outputState.consume(line);
@@ -586,6 +634,7 @@ export class ProcessBackedProviderCliService {
586
634
  args: command.args,
587
635
  cwd: worktree.worktreePath,
588
636
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
637
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
589
638
  stdin: pipePromptToStdin ? providerPrompt : undefined
590
639
  }, {
591
640
  onStarted: async () => {
@@ -596,6 +645,7 @@ export class ProcessBackedProviderCliService {
596
645
  eventType: "provider_cli_started"
597
646
  });
598
647
  },
648
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
599
649
  onStdoutLine: async (line) => {
600
650
  await toolHeartbeat.consume(line);
601
651
  }
@@ -645,7 +695,7 @@ export class ProcessBackedProviderCliService {
645
695
  await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
646
696
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
647
697
  if (!proposalArtifact) {
648
- throw new Error("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.");
698
+ throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
649
699
  }
650
700
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
651
701
  const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
@@ -668,7 +718,7 @@ export class ProcessBackedProviderCliService {
668
718
  await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
669
719
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
670
720
  if (!proposalArtifact) {
671
- throw new Error("Provider CLI Draft completed but did not call forge.complete_draft_proposal.");
721
+ throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
672
722
  }
673
723
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
674
724
  const draftJson = proposal["draft_json"];
@@ -755,6 +805,7 @@ export class ProcessBackedProviderCliService {
755
805
  args: command.args,
756
806
  cwd: worktree.worktreePath,
757
807
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
808
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
758
809
  stdin: pipePromptToStdin ? providerPrompt : undefined
759
810
  }, {
760
811
  onStarted: async () => {
@@ -765,6 +816,7 @@ export class ProcessBackedProviderCliService {
765
816
  eventType: "provider_cli_started"
766
817
  });
767
818
  },
819
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
768
820
  onStdoutLine: async (line) => {
769
821
  await toolHeartbeat.consume(line);
770
822
  }
@@ -806,7 +858,7 @@ export class ProcessBackedProviderCliService {
806
858
  eventType: "worktree_branch_pushed"
807
859
  });
808
860
  }
809
- const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
861
+ const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
810
862
  for (const artifact of completionArtifacts) {
811
863
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
812
864
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -893,6 +945,7 @@ export class ProcessBackedProviderCliService {
893
945
  args: command.args,
894
946
  cwd: worktree.worktreePath,
895
947
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
948
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
896
949
  stdin: pipePromptToStdin ? providerPrompt : undefined
897
950
  }, {
898
951
  onStarted: async () => {
@@ -903,6 +956,7 @@ export class ProcessBackedProviderCliService {
903
956
  eventType: "provider_cli_started"
904
957
  });
905
958
  },
959
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
906
960
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
907
961
  }, context.signal);
908
962
  }
@@ -923,7 +977,7 @@ export class ProcessBackedProviderCliService {
923
977
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
924
978
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
925
979
  if (!architectArtifact) {
926
- throw new Error("Provider CLI Architect completed but did not call the Forge Architect completion tool.");
980
+ throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
927
981
  }
928
982
  if (!liveArchitectEvents.hasEmitted()) {
929
983
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -997,6 +1051,7 @@ export class ProcessBackedProviderCliService {
997
1051
  args: command.args,
998
1052
  cwd: worktree.worktreePath,
999
1053
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1054
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1000
1055
  stdin: pipePromptToStdin ? providerPrompt : undefined
1001
1056
  }, {
1002
1057
  onStarted: async () => {
@@ -1007,6 +1062,7 @@ export class ProcessBackedProviderCliService {
1007
1062
  eventType: "provider_cli_started"
1008
1063
  });
1009
1064
  },
1065
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1010
1066
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1011
1067
  }, context.signal);
1012
1068
  }
@@ -1026,17 +1082,19 @@ export class ProcessBackedProviderCliService {
1026
1082
  eventType: "provider_cli_completed"
1027
1083
  });
1028
1084
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
1085
+ const lastRun = { result };
1029
1086
  let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1030
1087
  if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1031
1088
  // A headless provider that ends its turn to "wait for a background watcher"
1032
1089
  // exits for good. Resume the same thread instead of failing the session.
1033
- qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
1090
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1034
1091
  }
1035
1092
  if (!qaArtifact) {
1036
1093
  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.");
1094
+ if (verdictOnly) {
1095
+ throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
1096
+ }
1097
+ throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
1040
1098
  }
1041
1099
  await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1042
1100
  if (!liveQaEvents.hasEmitted()) {
@@ -1149,6 +1207,7 @@ export class ProcessBackedProviderCliService {
1149
1207
  args: command.args,
1150
1208
  cwd: worktree.worktreePath,
1151
1209
  env: providerProcessEnv(dispatch, repairEnvironment),
1210
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1152
1211
  stdin: pipePromptToStdin ? providerPrompt : undefined
1153
1212
  }, {
1154
1213
  onStarted: async () => {
@@ -1160,6 +1219,7 @@ export class ProcessBackedProviderCliService {
1160
1219
  });
1161
1220
  providerStarted = true;
1162
1221
  },
1222
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1163
1223
  onStdoutLine: async (line) => {
1164
1224
  await toolHeartbeat.consume(line);
1165
1225
  }
@@ -1194,7 +1254,7 @@ export class ProcessBackedProviderCliService {
1194
1254
  if (repairChecks) {
1195
1255
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1196
1256
  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.");
1257
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
1198
1258
  }
1199
1259
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1200
1260
  throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
@@ -1202,16 +1262,18 @@ export class ProcessBackedProviderCliService {
1202
1262
  }
1203
1263
  if (addressComments) {
1204
1264
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1265
+ const lastRun = { result };
1205
1266
  if (!repairArtifact) {
1206
1267
  repairArtifact = await this.recoverMissingCommentRepairCompletion({
1207
1268
  context,
1208
1269
  repairEnvironment,
1209
1270
  outputState,
1210
1271
  preparedHeadSha,
1272
+ lastRun,
1211
1273
  });
1212
1274
  }
1213
1275
  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.");
1276
+ throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
1215
1277
  }
1216
1278
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1217
1279
  throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
@@ -1220,7 +1282,9 @@ export class ProcessBackedProviderCliService {
1220
1282
  }
1221
1283
  let commentRepairBaselineChangedFiles = null;
1222
1284
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1285
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1286
+ commentRepairBaselineChangedFiles = baseline.publishable;
1287
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1288
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1289
  }
1226
1290
  const validationProfile = repairChecks
@@ -1236,8 +1300,10 @@ export class ProcessBackedProviderCliService {
1236
1300
  preparedHeadSha,
1237
1301
  repairScope: "pull_request",
1238
1302
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1303
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1304
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1305
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1306
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1307
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1308
  }
1243
1309
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1334,13 +1400,15 @@ export class ProcessBackedProviderCliService {
1334
1400
  args: command.args,
1335
1401
  cwd: worktree.worktreePath,
1336
1402
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1403
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1337
1404
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1338
- }, { onStdoutLine: async (line) => await toolHeartbeat.consume(line) }, context.signal);
1405
+ }, { onStdoutLine: async (line) => await toolHeartbeat.consume(line), isToolCallInFlight: toolHeartbeat.isToolCallInFlight }, context.signal);
1339
1406
  }
1340
1407
  finally {
1341
1408
  toolHeartbeat.stop();
1342
1409
  await cleanupCompletionTools(completionTools, context.emit);
1343
1410
  }
1411
+ options.lastRun.result = result;
1344
1412
  if (result.exitCode !== 0)
1345
1413
  throw providerCliExitFailure(command.command, result);
1346
1414
  const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
@@ -1397,10 +1465,14 @@ export class ProcessBackedProviderCliService {
1397
1465
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1466
  };
1399
1467
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1468
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1469
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1470
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1471
  "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.",
1472
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1473
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1474
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1475
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1476
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1477
  ].join(" ");
1406
1478
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -1434,6 +1506,7 @@ export class ProcessBackedProviderCliService {
1434
1506
  args: command.args,
1435
1507
  cwd: worktree.worktreePath,
1436
1508
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1509
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1437
1510
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1438
1511
  }, {
1439
1512
  onStarted: async () => {
@@ -1445,6 +1518,7 @@ export class ProcessBackedProviderCliService {
1445
1518
  eventType: "provider_cli_started",
1446
1519
  });
1447
1520
  },
1521
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1448
1522
  onStdoutLine: async (line) => {
1449
1523
  await toolHeartbeat.consume(line);
1450
1524
  },
@@ -1466,6 +1540,7 @@ export class ProcessBackedProviderCliService {
1466
1540
  await cleanupCompletionTools(completionTools, context.emit);
1467
1541
  }
1468
1542
  }
1543
+ options.lastRun.result = result;
1469
1544
  if (result.exitCode !== 0)
1470
1545
  throw providerCliExitFailure(command.command, result);
1471
1546
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1551,6 +1626,7 @@ export class ProcessBackedProviderCliService {
1551
1626
  args: command.args,
1552
1627
  cwd: worktree.worktreePath,
1553
1628
  env: environment,
1629
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1554
1630
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1555
1631
  }, {
1556
1632
  onStarted: async () => {
@@ -1562,6 +1638,7 @@ export class ProcessBackedProviderCliService {
1562
1638
  });
1563
1639
  providerStarted = true;
1564
1640
  },
1641
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1565
1642
  onStdoutLine: async (line) => {
1566
1643
  await toolHeartbeat.consume(line);
1567
1644
  },
@@ -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,45 @@
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
+ /** Stages every publishable worktree change in the real index and returns both sets. */
20
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
21
+ /**
22
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
23
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
24
+ * `worktreePath` is not the root of a git worktree.
25
+ */
26
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
27
+ /** Compares claimed `changed_files` paths with the publishable diff. */
28
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
29
+ readonly missing: readonly string[];
30
+ readonly unexpected: readonly string[];
31
+ };
32
+ export declare function normalizeChangedFilePath(value: string): string;
33
+ /**
34
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
35
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
36
+ * in the same turn instead of failing at publication.
37
+ */
38
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
39
+ /**
40
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
41
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
42
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
43
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
44
+ */
45
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;