@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 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.
@@ -10,6 +10,7 @@ import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunc
10
10
  import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
11
11
  import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
12
  import { ForgeFailureError } from "../session.types.js";
13
+ import { hasNonterminalManagedCommand } from "./provider-in-flight-work.js";
13
14
  const execFileAsync = promisify(execFile);
14
15
  // Provider processes can emit many gigabytes over a long-running session. The
15
16
  // line handlers stream that output to Forge as it arrives; the completed result
@@ -17,8 +18,11 @@ const execFileAsync = promisify(execFile);
17
18
  export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
18
19
  const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
19
20
  // A provider that keeps starting turns after its first successful one (background-task
20
- // notifications) is still stopped this long after that first success.
21
+ // notifications) is still stopped once this much time without supervised work in flight
22
+ // has passed since that first success.
21
23
  const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
24
+ // How often the end-of-turn timers re-check whether supervised work is still in flight.
25
+ const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
22
26
  const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
23
27
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
24
28
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -47,6 +51,7 @@ export class CodexModelsCacheRecoveringProcessRunner {
47
51
  const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
48
52
  if (!recovered || signal?.aborted)
49
53
  return first;
54
+ handlers?.onGenerationStart?.();
50
55
  return await this.inner.run(request, handlers, signal);
51
56
  }
52
57
  }
@@ -69,7 +74,10 @@ export class CodexResumeRecoveringProcessRunner {
69
74
  return first;
70
75
  }
71
76
  const fallback = codexFreshTurnRequest(request);
72
- return fallback ? await this.inner.run(fallback, handlers, signal) : first;
77
+ if (!fallback)
78
+ return first;
79
+ handlers?.onGenerationStart?.();
80
+ return await this.inner.run(fallback, handlers, signal);
73
81
  }
74
82
  }
75
83
  function isRecoverableCodexResumeFailure(command, result) {
@@ -107,7 +115,8 @@ function codexFreshTurnRequest(request) {
107
115
  const cd = args.splice(cdIndex, 2);
108
116
  args.splice(args.length - 1, 0, ...cd);
109
117
  }
110
- return { ...request, args };
118
+ // The fallback starts a fresh thread, so it has no replayed turn to discount.
119
+ return { ...request, args, resumesProviderThread: false };
111
120
  }
112
121
  function isCodexCommand(command) {
113
122
  return path.parse(command).name.toLowerCase() === "codex";
@@ -317,12 +326,16 @@ function setEnvironmentValueIfMissing(env, name, value) {
317
326
  export class StreamingProviderProcessRunner {
318
327
  terminalExitGraceMs;
319
328
  terminalSuccessCeilingMs;
320
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS) {
329
+ terminalWorkPollMs;
330
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
321
331
  this.terminalExitGraceMs = terminalExitGraceMs;
322
332
  this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
333
+ this.terminalWorkPollMs = terminalWorkPollMs;
323
334
  }
324
335
  async run(request, handlers = {}, signal) {
325
336
  assertHostDatabaseCapabilityBoundary();
337
+ // Every child this runner launches is a new generation, including supervisor retries.
338
+ handlers.onGenerationStart?.();
326
339
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
327
340
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
328
341
  // An unsupervised Unix provider still gets a dedicated process group so a
@@ -376,19 +389,22 @@ export class StreamingProviderProcessRunner {
376
389
  let cancellationRequested = false;
377
390
  let cancelledBeforeClose = false;
378
391
  let terminalTerminationStarted = false;
379
- let terminalExitTimer = null;
380
- let terminalCeilingTimer = null;
392
+ let terminalStopReason = null;
393
+ // Idle time (no supervised work in flight) accrued against the end-of-turn grace and
394
+ // the success ceiling; null while that timer is not armed.
395
+ let graceIdleMs = null;
396
+ let ceilingIdleMs = null;
397
+ let terminalSuccessCount = 0;
398
+ let replayedTurnCeilingSkipped = false;
399
+ let terminalWorkTimer = null;
400
+ let terminalWorkTickAt = 0;
401
+ let terminalWorkTickRunning = false;
381
402
  let latestTurnFailed = false;
382
403
  let readiness = null;
383
404
  const cleanup = () => {
384
- if (terminalExitTimer) {
385
- clearTimeout(terminalExitTimer);
386
- terminalExitTimer = null;
387
- }
388
- if (terminalCeilingTimer) {
389
- clearTimeout(terminalCeilingTimer);
390
- terminalCeilingTimer = null;
391
- }
405
+ stopTerminalWorkTimer();
406
+ graceIdleMs = null;
407
+ ceilingIdleMs = null;
392
408
  signal?.removeEventListener("abort", abort);
393
409
  };
394
410
  const fail = (error) => {
@@ -490,22 +506,80 @@ export class StreamingProviderProcessRunner {
490
506
  });
491
507
  }
492
508
  }
493
- const finishAfterTerminalSuccess = () => {
509
+ const finishAfterTerminalSuccess = (reason) => {
494
510
  if (closed || settled || cancellationRequested || terminalTerminationStarted)
495
511
  return;
496
512
  terminalTerminationStarted = true;
513
+ terminalStopReason = reason;
514
+ stopTerminalWorkTimer();
497
515
  void terminate().catch(fail);
498
516
  };
517
+ const workInFlight = async () => {
518
+ try {
519
+ if (handlers.isToolCallInFlight?.())
520
+ return true;
521
+ }
522
+ catch {
523
+ // A failing probe must not keep the provider open or stop it early on its own.
524
+ }
525
+ return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
526
+ };
527
+ // The grace and the ceiling only count time in which no supervised work is in flight:
528
+ // a provider waiting on an MCP tool call or on a managed command it started is not
529
+ // finished, even when its turn has ended. The grace restarts once that work is done.
530
+ const terminalWorkTick = async () => {
531
+ if (terminalWorkTickRunning)
532
+ return;
533
+ terminalWorkTickRunning = true;
534
+ try {
535
+ const inFlight = await workInFlight();
536
+ const now = performance.now();
537
+ const elapsed = Math.max(0, now - terminalWorkTickAt);
538
+ terminalWorkTickAt = now;
539
+ if (closed || settled || terminalTerminationStarted)
540
+ return;
541
+ if (inFlight) {
542
+ if (graceIdleMs !== null)
543
+ graceIdleMs = 0;
544
+ return;
545
+ }
546
+ if (graceIdleMs !== null)
547
+ graceIdleMs += elapsed;
548
+ if (ceilingIdleMs !== null)
549
+ ceilingIdleMs += elapsed;
550
+ if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
551
+ finishAfterTerminalSuccess("turn_exit_grace");
552
+ }
553
+ else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
554
+ finishAfterTerminalSuccess("success_ceiling");
555
+ }
556
+ }
557
+ finally {
558
+ terminalWorkTickRunning = false;
559
+ if (graceIdleMs === null && ceilingIdleMs === null)
560
+ stopTerminalWorkTimer();
561
+ }
562
+ };
563
+ function stopTerminalWorkTimer() {
564
+ if (terminalWorkTimer) {
565
+ clearInterval(terminalWorkTimer);
566
+ terminalWorkTimer = null;
567
+ }
568
+ }
569
+ const startTerminalWorkTimer = () => {
570
+ if (terminalWorkTimer)
571
+ return;
572
+ terminalWorkTickAt = performance.now();
573
+ const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
574
+ terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
575
+ terminalWorkTimer.unref?.();
576
+ };
499
577
  const armTerminalExit = () => {
500
- if (terminalExitTimer)
501
- clearTimeout(terminalExitTimer);
502
- terminalExitTimer = setTimeout(finishAfterTerminalSuccess, this.terminalExitGraceMs);
503
- terminalExitTimer.unref?.();
578
+ terminalSuccessCount += 1;
579
+ graceIdleMs = 0;
504
580
  // Later turns may postpone the grace period, but never past this ceiling.
505
- if (!terminalCeilingTimer) {
506
- terminalCeilingTimer = setTimeout(finishAfterTerminalSuccess, this.terminalSuccessCeilingMs);
507
- terminalCeilingTimer.unref?.();
508
- }
581
+ ceilingIdleMs ??= 0;
582
+ startTerminalWorkTimer();
509
583
  };
510
584
  const readers = [
511
585
  readProcessLines(childStdout, (line) => {
@@ -521,14 +595,20 @@ export class StreamingProviderProcessRunner {
521
595
  // A later turn that fails reports its failure even after an earlier success.
522
596
  latestTurnFailed = true;
523
597
  }
524
- else if (terminalExitTimer && isProviderTurnActivity(line)) {
598
+ else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
525
599
  // A terminal event ends a turn, not necessarily the provider. Claude Code
526
600
  // stays resident while background tasks it started are pending and begins a
527
- // new turn when one reports (and a resumed session can replay a queued
528
- // notification turn first). A provider that is working again is not finished;
601
+ // new turn when one reports. A provider that is working again is not finished;
529
602
  // the grace period restarts at its next terminal event.
530
- clearTimeout(terminalExitTimer);
531
- terminalExitTimer = null;
603
+ graceIdleMs = null;
604
+ // A resumed session can replay a queued notification turn before the
605
+ // prompt's own turn. The replayed turn must not consume the ceiling, or the
606
+ // resumed agent is stopped mid-work, but the prompt's turn still needs a
607
+ // watchdog: restart the ceiling from here instead of dropping it.
608
+ if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
609
+ replayedTurnCeilingSkipped = true;
610
+ ceilingIdleMs = 0;
611
+ }
532
612
  }
533
613
  }
534
614
  return handled;
@@ -585,12 +665,24 @@ export class StreamingProviderProcessRunner {
585
665
  stderr: stderr.toString(),
586
666
  ...(memory ?? {}),
587
667
  ...(cancelledBeforeClose ? { cancelled: true } : {}),
668
+ ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
588
669
  });
589
670
  }).catch(fail);
590
671
  });
591
672
  });
592
673
  }
593
674
  }
675
+ /**
676
+ * The typed failure for a provider run that ended without calling its required Forge
677
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
678
+ * is not mistaken for an agent that simply ended its turn.
679
+ */
680
+ export function providerCompletionToolMissingFailure(message, result) {
681
+ if (result?.terminalStopReason === "success_ceiling") {
682
+ return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
683
+ }
684
+ return new ForgeFailureError("provider_completion_tool_missing", message);
685
+ }
594
686
  /** A stream event that shows the provider is working on a turn: model output or a tool result. */
595
687
  function isProviderTurnActivity(line) {
596
688
  const trimmed = line.trim();
@@ -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
  }
@@ -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}
@@ -10,7 +10,7 @@ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtif
10
10
  import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
11
11
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
12
12
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
13
- import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
13
+ import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
14
14
  import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
15
15
  import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
16
16
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
@@ -472,10 +472,17 @@ class ProviderToolActivityHeartbeat {
472
472
  emit;
473
473
  intervalMs;
474
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();
475
479
  constructor(outputState, emit, intervalMs) {
476
480
  this.outputState = outputState;
477
481
  this.emit = emit;
478
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();
479
486
  }
480
487
  async consume(line) {
481
488
  const events = this.outputState.consume(line);
@@ -629,6 +636,7 @@ export class ProcessBackedProviderCliService {
629
636
  args: command.args,
630
637
  cwd: worktree.worktreePath,
631
638
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
639
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
632
640
  stdin: pipePromptToStdin ? providerPrompt : undefined
633
641
  }, {
634
642
  onStarted: async () => {
@@ -639,6 +647,8 @@ export class ProcessBackedProviderCliService {
639
647
  eventType: "provider_cli_started"
640
648
  });
641
649
  },
650
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
651
+ onGenerationStart: toolHeartbeat.startGeneration,
642
652
  onStdoutLine: async (line) => {
643
653
  await toolHeartbeat.consume(line);
644
654
  }
@@ -688,7 +698,7 @@ export class ProcessBackedProviderCliService {
688
698
  await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
689
699
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
690
700
  if (!proposalArtifact) {
691
- 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);
692
702
  }
693
703
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
694
704
  const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
@@ -711,7 +721,7 @@ export class ProcessBackedProviderCliService {
711
721
  await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
712
722
  const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
713
723
  if (!proposalArtifact) {
714
- 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);
715
725
  }
716
726
  const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
717
727
  const draftJson = proposal["draft_json"];
@@ -798,6 +808,7 @@ export class ProcessBackedProviderCliService {
798
808
  args: command.args,
799
809
  cwd: worktree.worktreePath,
800
810
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
811
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
801
812
  stdin: pipePromptToStdin ? providerPrompt : undefined
802
813
  }, {
803
814
  onStarted: async () => {
@@ -808,6 +819,8 @@ export class ProcessBackedProviderCliService {
808
819
  eventType: "provider_cli_started"
809
820
  });
810
821
  },
822
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
823
+ onGenerationStart: toolHeartbeat.startGeneration,
811
824
  onStdoutLine: async (line) => {
812
825
  await toolHeartbeat.consume(line);
813
826
  }
@@ -849,7 +862,7 @@ export class ProcessBackedProviderCliService {
849
862
  eventType: "worktree_branch_pushed"
850
863
  });
851
864
  }
852
- 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);
853
866
  for (const artifact of completionArtifacts) {
854
867
  if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
855
868
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
@@ -936,6 +949,7 @@ export class ProcessBackedProviderCliService {
936
949
  args: command.args,
937
950
  cwd: worktree.worktreePath,
938
951
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
952
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
939
953
  stdin: pipePromptToStdin ? providerPrompt : undefined
940
954
  }, {
941
955
  onStarted: async () => {
@@ -946,6 +960,8 @@ export class ProcessBackedProviderCliService {
946
960
  eventType: "provider_cli_started"
947
961
  });
948
962
  },
963
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
964
+ onGenerationStart: toolHeartbeat.startGeneration,
949
965
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
950
966
  }, context.signal);
951
967
  }
@@ -966,7 +982,7 @@ export class ProcessBackedProviderCliService {
966
982
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
967
983
  const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
968
984
  if (!architectArtifact) {
969
- 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);
970
986
  }
971
987
  if (!liveArchitectEvents.hasEmitted()) {
972
988
  await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
@@ -1040,6 +1056,7 @@ export class ProcessBackedProviderCliService {
1040
1056
  args: command.args,
1041
1057
  cwd: worktree.worktreePath,
1042
1058
  env: providerProcessEnv(dispatch, context.runtimeEnvironment),
1059
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1043
1060
  stdin: pipePromptToStdin ? providerPrompt : undefined
1044
1061
  }, {
1045
1062
  onStarted: async () => {
@@ -1050,6 +1067,8 @@ export class ProcessBackedProviderCliService {
1050
1067
  eventType: "provider_cli_started"
1051
1068
  });
1052
1069
  },
1070
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1071
+ onGenerationStart: toolHeartbeat.startGeneration,
1053
1072
  onStdoutLine: async (line) => await toolHeartbeat.consume(line)
1054
1073
  }, context.signal);
1055
1074
  }
@@ -1069,17 +1088,19 @@ export class ProcessBackedProviderCliService {
1069
1088
  eventType: "provider_cli_completed"
1070
1089
  });
1071
1090
  await emitProviderUsageEvent(context.emit, dispatch, outputState);
1091
+ const lastRun = { result };
1072
1092
  let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
1073
1093
  if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
1074
1094
  // A headless provider that ends its turn to "wait for a background watcher"
1075
1095
  // exits for good. Resume the same thread instead of failing the session.
1076
- qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
1096
+ qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
1077
1097
  }
1078
1098
  if (!qaArtifact) {
1079
1099
  const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
1080
- throw new Error(verdictOnly
1081
- ? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
1082
- : "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);
1083
1104
  }
1084
1105
  await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
1085
1106
  if (!liveQaEvents.hasEmitted()) {
@@ -1192,6 +1213,7 @@ export class ProcessBackedProviderCliService {
1192
1213
  args: command.args,
1193
1214
  cwd: worktree.worktreePath,
1194
1215
  env: providerProcessEnv(dispatch, repairEnvironment),
1216
+ resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
1195
1217
  stdin: pipePromptToStdin ? providerPrompt : undefined
1196
1218
  }, {
1197
1219
  onStarted: async () => {
@@ -1203,6 +1225,8 @@ export class ProcessBackedProviderCliService {
1203
1225
  });
1204
1226
  providerStarted = true;
1205
1227
  },
1228
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1229
+ onGenerationStart: toolHeartbeat.startGeneration,
1206
1230
  onStdoutLine: async (line) => {
1207
1231
  await toolHeartbeat.consume(line);
1208
1232
  }
@@ -1237,7 +1261,7 @@ export class ProcessBackedProviderCliService {
1237
1261
  if (repairChecks) {
1238
1262
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
1239
1263
  if (!repairArtifact) {
1240
- 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);
1241
1265
  }
1242
1266
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1243
1267
  throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
@@ -1245,16 +1269,18 @@ export class ProcessBackedProviderCliService {
1245
1269
  }
1246
1270
  if (addressComments) {
1247
1271
  repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
1272
+ const lastRun = { result };
1248
1273
  if (!repairArtifact) {
1249
1274
  repairArtifact = await this.recoverMissingCommentRepairCompletion({
1250
1275
  context,
1251
1276
  repairEnvironment,
1252
1277
  outputState,
1253
1278
  preparedHeadSha,
1279
+ lastRun,
1254
1280
  });
1255
1281
  }
1256
1282
  if (!repairArtifact) {
1257
- 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);
1258
1284
  }
1259
1285
  if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
1260
1286
  throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
@@ -1381,13 +1407,19 @@ export class ProcessBackedProviderCliService {
1381
1407
  args: command.args,
1382
1408
  cwd: worktree.worktreePath,
1383
1409
  env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
1410
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1384
1411
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1385
- }, { 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);
1386
1417
  }
1387
1418
  finally {
1388
1419
  toolHeartbeat.stop();
1389
1420
  await cleanupCompletionTools(completionTools, context.emit);
1390
1421
  }
1422
+ options.lastRun.result = result;
1391
1423
  if (result.exitCode !== 0)
1392
1424
  throw providerCliExitFailure(command.command, result);
1393
1425
  const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
@@ -1485,6 +1517,7 @@ export class ProcessBackedProviderCliService {
1485
1517
  args: command.args,
1486
1518
  cwd: worktree.worktreePath,
1487
1519
  env: providerProcessEnv(recoveryDispatch, repairEnvironment),
1520
+ resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
1488
1521
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1489
1522
  }, {
1490
1523
  onStarted: async () => {
@@ -1496,6 +1529,8 @@ export class ProcessBackedProviderCliService {
1496
1529
  eventType: "provider_cli_started",
1497
1530
  });
1498
1531
  },
1532
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1533
+ onGenerationStart: toolHeartbeat.startGeneration,
1499
1534
  onStdoutLine: async (line) => {
1500
1535
  await toolHeartbeat.consume(line);
1501
1536
  },
@@ -1517,6 +1552,7 @@ export class ProcessBackedProviderCliService {
1517
1552
  await cleanupCompletionTools(completionTools, context.emit);
1518
1553
  }
1519
1554
  }
1555
+ options.lastRun.result = result;
1520
1556
  if (result.exitCode !== 0)
1521
1557
  throw providerCliExitFailure(command.command, result);
1522
1558
  const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
@@ -1602,6 +1638,7 @@ export class ProcessBackedProviderCliService {
1602
1638
  args: command.args,
1603
1639
  cwd: worktree.worktreePath,
1604
1640
  env: environment,
1641
+ resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
1605
1642
  stdin: pipePromptToStdin ? providerPrompt : undefined,
1606
1643
  }, {
1607
1644
  onStarted: async () => {
@@ -1613,6 +1650,8 @@ export class ProcessBackedProviderCliService {
1613
1650
  });
1614
1651
  providerStarted = true;
1615
1652
  },
1653
+ isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
1654
+ onGenerationStart: toolHeartbeat.startGeneration,
1616
1655
  onStdoutLine: async (line) => {
1617
1656
  await toolHeartbeat.consume(line);
1618
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
+ }