@loucompanion/forge-bridge 0.1.4-dev.9ddc336f8a9d → 0.1.4-dev.a5a3a7ab2f02

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 (142) hide show
  1. package/README.md +35 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +281 -11
  57. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  58. package/dist/runtime/host-runtime-promotion.js +48 -0
  59. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  60. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  61. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  62. package/dist/runtime/host-runtime-requirements.js +117 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  64. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  65. package/dist/runtime/runner-settings.d.ts +100 -0
  66. package/dist/runtime/runner-settings.js +214 -0
  67. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  68. package/dist/sandbox/host-capacity-broker.js +315 -0
  69. package/dist/sandbox/runtime.d.ts +10 -1
  70. package/dist/sandbox/runtime.js +45 -2
  71. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  72. package/dist/sandbox/sandbox-cgroups.js +42 -0
  73. package/dist/session/managed-attempt-tools.d.ts +2 -0
  74. package/dist/session/managed-attempt-tools.js +156 -37
  75. package/dist/session/managed-command-host-load.d.ts +45 -0
  76. package/dist/session/managed-command-host-load.js +82 -0
  77. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  78. package/dist/session/mcp-argument-coercion.js +121 -0
  79. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  80. package/dist/session/phase-completion.artifacts.js +98 -25
  81. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  82. package/dist/session/phase-completion.command-validation.js +77 -0
  83. package/dist/session/phase-completion.d.ts +4 -0
  84. package/dist/session/phase-completion.helpers.js +13 -12
  85. package/dist/session/phase-completion.js +4 -0
  86. package/dist/session/phase-completion.prompts.js +6 -1
  87. package/dist/session/phase-completion.runtime.d.ts +5 -3
  88. package/dist/session/phase-completion.runtime.js +49 -19
  89. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  90. package/dist/session/phase-completion.schema-parts.js +188 -0
  91. package/dist/session/phase-completion.schemas.d.ts +3 -3
  92. package/dist/session/phase-completion.schemas.js +184 -209
  93. package/dist/session/phase-completion.validation.d.ts +2 -3
  94. package/dist/session/phase-completion.validation.js +46 -92
  95. package/dist/session/pre-publication-host-load.d.ts +27 -0
  96. package/dist/session/pre-publication-host-load.js +111 -0
  97. package/dist/session/pre-publication-process.d.ts +3 -0
  98. package/dist/session/pre-publication-process.js +23 -11
  99. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  100. package/dist/session/pre-publication-step-execution.js +49 -0
  101. package/dist/session/pre-publication-validation.d.ts +9 -9
  102. package/dist/session/pre-publication-validation.js +21 -55
  103. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  104. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  105. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  106. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  107. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  108. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  109. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  110. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  111. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  112. package/dist/session/provider-cli/provider-cli.service.js +237 -33
  113. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  114. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  115. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  116. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  117. package/dist/session/provider-cli/provider-output-state.js +9 -0
  118. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  119. package/dist/session/publishable-worktree-changes.js +193 -0
  120. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  121. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  122. package/dist/session/session.base.d.ts +9 -1
  123. package/dist/session/session.service.d.ts +9 -2
  124. package/dist/session/session.service.js +120 -5
  125. package/dist/session/session.types.d.ts +3 -0
  126. package/dist/session/session.types.js +15 -3
  127. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  128. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  129. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  130. package/dist/shared/process/host-process-supervisor.js +1 -1
  131. package/dist/shared/process/process-tree.d.ts +52 -0
  132. package/dist/shared/process/process-tree.js +144 -0
  133. package/dist/shared/process/process.d.ts +67 -0
  134. package/dist/shared/process/process.js +213 -11
  135. package/dist/version.d.ts +1 -1
  136. package/dist/version.js +1 -1
  137. package/dist/worktree/dependency-warmer.d.ts +25 -0
  138. package/dist/worktree/dependency-warmer.js +46 -10
  139. package/dist/worktree/worktree.service.d.ts +10 -1
  140. package/dist/worktree/worktree.service.js +42 -2
  141. package/dist/worktree/worktree.types.d.ts +7 -0
  142. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { type LaunchCommand } from "../../shared/process/windows-launch.js";
2
+ import { ForgeFailureError } from "../session.types.js";
2
3
  export declare const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS: number;
3
4
  export type ProviderCliCommand = LaunchCommand;
4
5
  export interface ProviderProcessRunRequest {
@@ -14,7 +15,15 @@ export interface ProviderProcessRunRequest {
14
15
  * supervisor and is never forwarded to the child process.
15
16
  */
16
17
  readonly failureRedactionValues?: readonly string[];
18
+ /**
19
+ * The run resumes an existing provider thread. Such a run can replay a queued
20
+ * notification turn before the prompt's turn, and that replayed turn must not
21
+ * start the success ceiling.
22
+ */
23
+ readonly resumesProviderThread?: boolean;
17
24
  }
25
+ /** Why Forge stopped a provider that was still resident after a successful turn. */
26
+ export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling";
18
27
  export interface ProviderProcessRunResult {
19
28
  readonly exitCode: number;
20
29
  readonly stdout: string;
@@ -25,6 +34,8 @@ export interface ProviderProcessRunResult {
25
34
  readonly memoryObservedAt?: string;
26
35
  /** Present when the caller's cancellation stopped the process before it exited on its own. */
27
36
  readonly cancelled?: true;
37
+ /** Present when Forge stopped a provider that stayed resident after a successful turn. */
38
+ readonly terminalStopReason?: ProviderTerminalStopReason;
28
39
  }
29
40
  export interface ProviderProcessRunner {
30
41
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
@@ -33,6 +44,19 @@ export interface ProviderProcessHandlers {
33
44
  onStarted?(): Promise<void> | void;
34
45
  onStdoutLine?(line: string): Promise<void> | void;
35
46
  onStderrLine?(line: string): Promise<void> | void;
47
+ /**
48
+ * True while the provider has a tool call (such as an MCP tool call) in flight. While it
49
+ * is, or while an attempt-owned managed command is non-terminal, Forge suspends the
50
+ * end-of-turn exit grace and the success ceiling.
51
+ */
52
+ isToolCallInFlight?(): boolean;
53
+ /**
54
+ * Called before each provider generation (child process) starts, including every
55
+ * relaunch a recovery wrapper or supervisor makes with the same handlers. Per-generation
56
+ * state, such as tool calls in flight, must be reset here: a generation that exited mid
57
+ * call never reports that call's completion.
58
+ */
59
+ onGenerationStart?(): void;
36
60
  }
37
61
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
38
62
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -73,9 +97,16 @@ export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Reco
73
97
  export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
74
98
  private readonly terminalExitGraceMs;
75
99
  private readonly terminalSuccessCeilingMs;
76
- constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number);
100
+ private readonly terminalWorkPollMs;
101
+ constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
77
102
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
78
103
  }
104
+ /**
105
+ * The typed failure for a provider run that ended without calling its required Forge
106
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
107
+ * is not mistaken for an agent that simply ended its turn.
108
+ */
109
+ export declare function providerCompletionToolMissingFailure(message: string, result?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): ForgeFailureError;
79
110
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
80
111
  export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
81
112
  export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
@@ -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
@@ -366,7 +379,7 @@ export class StreamingProviderProcessRunner {
366
379
  const childStderr = child.stderr;
367
380
  if (!childStdout || !childStderr) {
368
381
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
369
- void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "Provider launch failed and its process tree could not be proven stopped.")));
382
+ void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "host_process_supervisor_termination_failed: Provider launch failed and its process tree could not be proven stopped.")));
370
383
  return;
371
384
  }
372
385
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -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) => {
@@ -399,7 +415,7 @@ export class StreamingProviderProcessRunner {
399
415
  cleanup();
400
416
  // Do not release the caller's reservation/worktree/port ownership until
401
417
  // descendant termination has completed (or failed with explicit proof).
402
- void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
418
+ void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "host_process_supervisor_termination_failed: Provider process failed and its process tree could not be proven stopped.")));
403
419
  };
404
420
  const abort = () => {
405
421
  if (!closed)
@@ -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;
@@ -278,7 +278,10 @@ function buildRuntimeContextPrompt(dispatch, prompt, runtimeEnvironment) {
278
278
  ? "- `FORGE_HOST_CONCURRENCY=host_parallel_safe` means Forge verified this contract's assigned-port probe and gave this attempt independent ports, paths, and process supervisors. Do not share or discover another attempt's runtime resources."
279
279
  : "- `FORGE_HOST_CONCURRENCY=host_serial_only` means Forge holds the runner-local project singleton named by `FORGE_SINGLETON_KEYS`; do not bypass or release it yourself.";
280
280
  const playwright = runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
281
- ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly."
281
+ ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly. Run `playwright test --config <absolute value of FORGE_PLAYWRIGHT_CONFIG>` from the Playwright project directory through `forge.start_managed_command` (in Forge: command `pnpm`, args `[\"--dir\", \"tests/e2e\", \"exec\", \"playwright\", \"test\", \"--config\", \"<path>\"]`), and append spec file paths such as `specs/<name>.spec.ts` to run only the specs you are working on. Repository wrappers that start their own disposable stack, such as Forge's `pnpm --dir tests/e2e test`, refuse to run inside a managed attempt; Forge-owned pre-publication still runs the full suite."
282
+ : "";
283
+ const stackUnavailable = runtimeEnvironment?.FORGE_RUNTIME_STACK === "unavailable"
284
+ ? "\n- `FORGE_RUNTIME_STACK=unavailable` means Forge's restart of this attempt's application stack failed, so no attempt-owned API, web, or Playwright URLs are supplied for this turn. Do not reuse URLs or ports from an earlier turn or start the stack yourself; fix the source so the restart succeeds. Forge restarts the stack and reruns validation after this turn."
282
285
  : "";
283
286
  return `${prompt.trimEnd()}
284
287
 
@@ -292,7 +295,7 @@ ${concurrency}
292
295
  - If a tool creates \`TestResults\`, \`test-results\`, or \`playwright-report\` beneath source, use \`forge.reset_generated_outputs\` to quarantine only those untracked generated directories. Do not issue a recursive delete.
293
296
  - Use the attempt-scoped \`FORGE_TMPDIR\`, \`FORGE_LOG_DIR\`, \`FORGE_CACHE_DIR\`, \`FORGE_BROWSER_PROFILE_DIR\`, and \`FORGE_TEST_OUTPUT_DIR\` paths instead of shared host paths.
294
297
  - Use supplied \`FORGE_*\` URLs, ports, and paths. Do not search for a free port, kill a process occupying one, or reuse an existing dev server, browser profile, database, container, network, or volume.
295
- - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}`;
298
+ - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}${stackUnavailable}`;
296
299
  }
297
300
  return `${prompt.trimEnd()}
298
301
 
@@ -392,6 +395,13 @@ Architect revision context:
392
395
  - Reviewer feedback: ${dispatch.architectRevision.feedback}
393
396
  Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
394
397
  }
398
+ /**
399
+ * Headless providers must not end a turn to wait: Forge stops the provider shortly after
400
+ * a turn ends, and nothing started in the background reports back.
401
+ */
402
+ export function providerTurnEndRule(completionStep) {
403
+ 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.`;
404
+ }
395
405
  export function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
396
406
  return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
397
407
 
@@ -403,6 +413,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
403
413
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
404
414
 
405
415
  ${completionPromptForPhase(phase)}
416
+ ${providerTurnEndRule("call the completion tool")}
406
417
 
407
418
  Finish with a concise summary of changed files and verification after calling the completion tool.`;
408
419
  }
@@ -417,6 +428,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
417
428
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
418
429
 
419
430
  ${completionPromptForDevelopCycle(phase)}
431
+ ${providerTurnEndRule("call the current phase's completion tool")}
420
432
 
421
433
  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
434
  }
@@ -431,6 +443,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
431
443
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
432
444
 
433
445
  ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
446
+ ${providerTurnEndRule("call the current Debug gate's completion tool")}
434
447
 
435
448
  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
449
  }
@@ -587,6 +600,7 @@ Report in-scope defects as actionable findings with repro steps, expected/actual
587
600
  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
601
 
589
602
  ${completionPromptForQaCycle("qa_plan", artifactRoot)}
603
+ ${providerTurnEndRule("call the next QA gate's completion tool, through forge.complete_qa_verdict,")}
590
604
 
591
605
  Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
592
606
  }
@@ -607,6 +621,8 @@ export function buildConflictResolvePrompt(dispatch, branchName) {
607
621
  The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
608
622
  Fetch origin, merge ${targetBranch} into ${branchName} with --no-commit, resolve conflicts conservatively, and run relevant validation when practical.
609
623
  Leave every repair change uncommitted and unpushed. Forge Bridge owns the sole final commit and compare-and-swap push after validation passes.
624
+ 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.
625
+ 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
626
  Keep the original work item intent intact:
611
627
  - Work item: ${dispatch.workItem.id}
612
628
  - Title: ${dispatch.workItem.title}
@@ -644,6 +660,7 @@ Forge prepared two required inputs before this agent started:
644
660
  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
661
 
646
662
  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.
663
+ ${providerTurnEndRule("call forge.complete_ci_repair")}
647
664
 
648
665
  Keep the original work item intent intact:
649
666
  - Work item: ${dispatch.workItem.id}
@@ -695,6 +712,7 @@ Before handing a changed diff back for publication:
695
712
  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
713
  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
714
  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.
715
+ ${providerTurnEndRule("call forge.complete_comment_repair")}
698
716
  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
717
  Keep the original work item intent intact:
700
718
  - Work item: ${dispatch.workItem.id}
@@ -67,4 +67,10 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
67
67
  private recoverMissingQaCompletion;
68
68
  private recoverMissingCommentRepairCompletion;
69
69
  private validatePrePublicationWithRecovery;
70
+ /**
71
+ * Restarts the attempt's runtime stack when the workspace changed since it was
72
+ * launched, before a validation pass runs against it. A build of the changed
73
+ * source that fails is a validation failure the bounded repair turn can fix.
74
+ */
75
+ private refreshPrePublicationRuntime;
70
76
  }