@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.8f4846c6e7a9

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 (89) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +73 -8
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cli/cli.service.js +3 -1
  12. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  13. package/dist/runtime/attempt-process-supervisor.js +50 -0
  14. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  15. package/dist/runtime/host-database-capability-boundary.js +1 -0
  16. package/dist/runtime/host-facts.d.ts +35 -0
  17. package/dist/runtime/host-facts.js +95 -0
  18. package/dist/runtime/host-load-admission.d.ts +52 -0
  19. package/dist/runtime/host-load-admission.js +84 -0
  20. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  21. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  22. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  23. package/dist/runtime/host-load-governor-config.js +46 -0
  24. package/dist/runtime/host-load-governor.d.ts +123 -0
  25. package/dist/runtime/host-load-governor.js +415 -0
  26. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  27. package/dist/runtime/host-load-ledger-lock.js +185 -0
  28. package/dist/runtime/host-load-sampler.d.ts +121 -0
  29. package/dist/runtime/host-load-sampler.js +224 -0
  30. package/dist/runtime/host-load-step-class.d.ts +33 -0
  31. package/dist/runtime/host-load-step-class.js +46 -0
  32. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  33. package/dist/runtime/host-load-token-ledger.js +345 -0
  34. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  35. package/dist/runtime/host-pressure-stall.js +168 -0
  36. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  37. package/dist/runtime/host-runtime-contract.js +6 -1
  38. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  39. package/dist/runtime/host-runtime-lease.js +82 -11
  40. package/dist/runtime/host-runtime-promotion.js +12 -0
  41. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  42. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  43. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  44. package/dist/runtime/host-runtime-requirements.js +117 -0
  45. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  46. package/dist/runtime/managed-command-teardown.js +607 -0
  47. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  48. package/dist/runtime/playwright-browser-cache.js +227 -0
  49. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  50. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  51. package/dist/session/managed-attempt-tools.d.ts +25 -0
  52. package/dist/session/managed-attempt-tools.js +212 -15
  53. package/dist/session/managed-build-coordinator.d.ts +1 -1
  54. package/dist/session/managed-build-coordinator.js +4 -1
  55. package/dist/session/phase-completion.artifacts.js +4 -0
  56. package/dist/session/phase-completion.runtime.js +22 -17
  57. package/dist/session/pre-publication-host-load.d.ts +27 -0
  58. package/dist/session/pre-publication-host-load.js +96 -0
  59. package/dist/session/pre-publication-process.d.ts +20 -0
  60. package/dist/session/pre-publication-process.js +97 -0
  61. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  62. package/dist/session/pre-publication-skipped-tests.js +109 -0
  63. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  64. package/dist/session/pre-publication-step-execution.js +49 -0
  65. package/dist/session/pre-publication-validation.d.ts +9 -9
  66. package/dist/session/pre-publication-validation.js +44 -112
  67. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  68. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  69. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  70. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  71. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  72. package/dist/session/provider-cli/provider-cli.process.js +297 -23
  73. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  74. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  75. package/dist/session/provider-cli/provider-cli.service.js +126 -26
  76. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  77. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  78. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  79. package/dist/session/provider-cli/provider-output-state.js +9 -0
  80. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  81. package/dist/session/publishable-worktree-changes.js +193 -0
  82. package/dist/session/session.base.d.ts +3 -0
  83. package/dist/session/session.service.d.ts +2 -0
  84. package/dist/session/session.service.js +5 -0
  85. package/dist/session/session.types.d.ts +3 -0
  86. package/dist/session/session.types.js +14 -2
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/package.json +1 -1
@@ -10,12 +10,19 @@ 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
16
17
  // only needs a bounded diagnostic tail for failure classification.
17
18
  export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
18
19
  const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
20
+ // A provider that keeps starting turns after its first successful one (background-task
21
+ // notifications) is still stopped once this much time without supervised work in flight
22
+ // has passed since that first success.
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;
19
26
  const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
20
27
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
21
28
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -44,6 +51,7 @@ export class CodexModelsCacheRecoveringProcessRunner {
44
51
  const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
45
52
  if (!recovered || signal?.aborted)
46
53
  return first;
54
+ handlers?.onGenerationStart?.();
47
55
  return await this.inner.run(request, handlers, signal);
48
56
  }
49
57
  }
@@ -66,7 +74,10 @@ export class CodexResumeRecoveringProcessRunner {
66
74
  return first;
67
75
  }
68
76
  const fallback = codexFreshTurnRequest(request);
69
- 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);
70
81
  }
71
82
  }
72
83
  function isRecoverableCodexResumeFailure(command, result) {
@@ -104,7 +115,8 @@ function codexFreshTurnRequest(request) {
104
115
  const cd = args.splice(cdIndex, 2);
105
116
  args.splice(args.length - 1, 0, ...cd);
106
117
  }
107
- return { ...request, args };
118
+ // The fallback starts a fresh thread, so it has no replayed turn to discount.
119
+ return { ...request, args, resumesProviderThread: false };
108
120
  }
109
121
  function isCodexCommand(command) {
110
122
  return path.parse(command).name.toLowerCase() === "codex";
@@ -313,22 +325,45 @@ function setEnvironmentValueIfMissing(env, name, value) {
313
325
  }
314
326
  export class StreamingProviderProcessRunner {
315
327
  terminalExitGraceMs;
316
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS) {
328
+ terminalSuccessCeilingMs;
329
+ terminalWorkPollMs;
330
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
317
331
  this.terminalExitGraceMs = terminalExitGraceMs;
332
+ this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
333
+ this.terminalWorkPollMs = terminalWorkPollMs;
318
334
  }
319
335
  async run(request, handlers = {}, signal) {
320
336
  assertHostDatabaseCapabilityBoundary();
337
+ // Every child this runner launches is a new generation, including supervisor retries.
338
+ handlers.onGenerationStart?.();
321
339
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
322
340
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
323
341
  // An unsupervised Unix provider still gets a dedicated process group so a
324
342
  // cancellation can stop descendants instead of only the CLI root.
325
343
  const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
344
+ const childEnvironment = buildProviderChildEnvironment(request.env);
345
+ // A piped prompt must reach the provider promptly (Claude Code abandons a
346
+ // silent stdin after ~3s), but the provider must not run before Forge has
347
+ // recorded its start. Off Windows, hold the launch behind a start gate in
348
+ // the same process: the prompt is written immediately and buffers in the
349
+ // pipe, and the gate execs the provider only once onStarted succeeds.
350
+ const startGated = process.platform !== "win32"
351
+ && supervisedLaunch?.strategy !== "windows_job_object"
352
+ && request.stdin !== undefined
353
+ && fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
354
+ && isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
355
+ const spawnLaunch = startGated
356
+ ? buildUnixProviderStartGateLaunch(launch.command, launch.args)
357
+ : launch;
326
358
  return await new Promise((resolve, reject) => {
327
359
  const rootCreatedAt = new Date().toISOString();
328
- const child = spawn(launch.command, launch.args, {
360
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
361
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
329
362
  cwd: request.cwd,
330
- env: buildProviderChildEnvironment(request.env),
331
- stdio: [request.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
363
+ env: childEnvironment,
364
+ stdio: startGated
365
+ ? [stdinMode, "pipe", "pipe", "pipe"]
366
+ : [stdinMode, "pipe", "pipe"],
332
367
  windowsHide: true,
333
368
  detached: launch.detached,
334
369
  });
@@ -352,14 +387,24 @@ export class StreamingProviderProcessRunner {
352
387
  let settled = false;
353
388
  let closed = false;
354
389
  let cancellationRequested = false;
390
+ let cancelledBeforeClose = false;
355
391
  let terminalTerminationStarted = false;
356
- let terminalExitTimer = 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;
402
+ let latestTurnFailed = false;
357
403
  let readiness = null;
358
404
  const cleanup = () => {
359
- if (terminalExitTimer) {
360
- clearTimeout(terminalExitTimer);
361
- terminalExitTimer = null;
362
- }
405
+ stopTerminalWorkTimer();
406
+ graceIdleMs = null;
407
+ ceilingIdleMs = null;
363
408
  signal?.removeEventListener("abort", abort);
364
409
  };
365
410
  const fail = (error) => {
@@ -373,6 +418,8 @@ export class StreamingProviderProcessRunner {
373
418
  void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
374
419
  };
375
420
  const abort = () => {
421
+ if (!closed)
422
+ cancelledBeforeClose = true;
376
423
  cancellationRequested = true;
377
424
  // Cancellation is not a launch failure when the supervised tree can be
378
425
  // proven stopped. Let the close handler settle the command after exact
@@ -386,6 +433,27 @@ export class StreamingProviderProcessRunner {
386
433
  signal?.addEventListener("abort", abort, { once: true });
387
434
  }
388
435
  child.on("error", fail);
436
+ const startGrant = startGated ? child.stdio[3] : null;
437
+ if (startGated && !startGrant) {
438
+ fail(new Error("Provider start-grant stream was not piped."));
439
+ return;
440
+ }
441
+ startGrant?.on("error", error => {
442
+ // A broken grant pipe means the gate already exited (terminated before
443
+ // its grant, or it died on its own). Its close event carries the real
444
+ // exit status, so an EPIPE here must not replace that result.
445
+ if (isBrokenPipeError(error))
446
+ return;
447
+ fail(error);
448
+ });
449
+ const grantUnixProviderStart = () => {
450
+ if (!startGrant)
451
+ return;
452
+ // Never release a provider whose launch was cancelled or already failed.
453
+ if (closed || settled || cancellationRequested || signal?.aborted)
454
+ return;
455
+ startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
456
+ };
389
457
  child.once("spawn", () => {
390
458
  readiness = (async () => {
391
459
  const providerReady = supervisedLaunch?.strategy === "windows_job_object"
@@ -398,6 +466,9 @@ export class StreamingProviderProcessRunner {
398
466
  if (supervisedLaunch?.strategy === "windows_job_object") {
399
467
  grantWindowsProviderStart(supervisedLaunch);
400
468
  }
469
+ else if (startGated) {
470
+ grantUnixProviderStart();
471
+ }
401
472
  })();
402
473
  void readiness.catch(error => {
403
474
  if (!closed && !signal?.aborted)
@@ -413,15 +484,20 @@ export class StreamingProviderProcessRunner {
413
484
  return;
414
485
  }
415
486
  child.stdin.on("error", (error) => {
487
+ // A prompt still buffered when Forge stops the process (cancellation,
488
+ // or a refused start grant) cannot be delivered; that broken pipe is
489
+ // not a failure. Any other stdin error still is.
490
+ if ((cancellationRequested || termination) && isBrokenPipeError(error))
491
+ return;
416
492
  void terminate();
417
493
  fail(error);
418
494
  });
419
495
  child.stdin.end(request.stdin, "utf8");
420
496
  };
421
497
  if (request.stdin !== undefined) {
422
- if (supervisedLaunch?.strategy === "windows_job_object") {
423
- // The outer supervisor must receive stdin before it can launch the
424
- // inner provider. Its start-grant file prevents prompt delivery.
498
+ if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
499
+ // The outer supervisor / Unix start gate must receive stdin before it
500
+ // can launch the provider. Its start grant fences prompt processing.
425
501
  writeProviderInput();
426
502
  }
427
503
  else {
@@ -430,19 +506,110 @@ export class StreamingProviderProcessRunner {
430
506
  });
431
507
  }
432
508
  }
509
+ const finishAfterTerminalSuccess = (reason) => {
510
+ if (closed || settled || cancellationRequested || terminalTerminationStarted)
511
+ return;
512
+ terminalTerminationStarted = true;
513
+ terminalStopReason = reason;
514
+ stopTerminalWorkTimer();
515
+ void terminate().catch(fail);
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
+ };
577
+ const armTerminalExit = () => {
578
+ terminalSuccessCount += 1;
579
+ graceIdleMs = 0;
580
+ // Later turns may postpone the grace period, but never past this ceiling.
581
+ ceilingIdleMs ??= 0;
582
+ startTerminalWorkTimer();
583
+ };
433
584
  const readers = [
434
585
  readProcessLines(childStdout, (line) => {
435
586
  if (request.captureOutput !== false)
436
587
  stdout.appendLine(line);
437
588
  const handled = handlers.onStdoutLine?.(line);
438
- if (!terminalExitTimer && isProviderTerminalSuccess(line)) {
439
- terminalExitTimer = setTimeout(() => {
440
- if (closed || settled || cancellationRequested)
441
- return;
442
- terminalTerminationStarted = true;
443
- void terminate().catch(fail);
444
- }, this.terminalExitGraceMs);
445
- terminalExitTimer.unref?.();
589
+ if (!terminalTerminationStarted) {
590
+ if (isProviderTerminalSuccess(line)) {
591
+ latestTurnFailed = false;
592
+ armTerminalExit();
593
+ }
594
+ else if (isProviderTerminalFailure(line)) {
595
+ // A later turn that fails reports its failure even after an earlier success.
596
+ latestTurnFailed = true;
597
+ }
598
+ else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
599
+ // A terminal event ends a turn, not necessarily the provider. Claude Code
600
+ // stays resident while background tasks it started are pending and begins a
601
+ // new turn when one reports. A provider that is working again is not finished;
602
+ // the grace period restarts at its next terminal event.
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
+ }
612
+ }
446
613
  }
447
614
  return handled;
448
615
  }),
@@ -489,16 +656,65 @@ export class StreamingProviderProcessRunner {
489
656
  // that event, terminate the supervised tree after a short grace
490
657
  // period and preserve the successful handoff so the existing
491
658
  // artifact, commit, and publication gates can run.
492
- exitCode: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
659
+ // A provider stopped after a successful turn keeps that success. Whenever the
660
+ // most recent turn failed, the run fails, however the process ended.
661
+ exitCode: latestTurnFailed
662
+ ? code && code !== 0 ? code : 1
663
+ : terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
493
664
  stdout: stdout.toString(),
494
665
  stderr: stderr.toString(),
495
666
  ...(memory ?? {}),
667
+ ...(cancelledBeforeClose ? { cancelled: true } : {}),
668
+ ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
496
669
  });
497
670
  }).catch(fail);
498
671
  });
499
672
  });
500
673
  }
501
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
+ }
686
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
687
+ function isProviderTurnActivity(line) {
688
+ const trimmed = line.trim();
689
+ if (!trimmed.startsWith("{"))
690
+ return false;
691
+ try {
692
+ const event = JSON.parse(trimmed);
693
+ return event.type === "assistant"
694
+ || event.type === "user"
695
+ || (event.type === "system" && event.subtype === "init")
696
+ || event.type === "turn.started"
697
+ || event.type === "item.started";
698
+ }
699
+ catch {
700
+ return false;
701
+ }
702
+ }
703
+ function isProviderTerminalFailure(line) {
704
+ const trimmed = line.trim();
705
+ if (!trimmed.startsWith("{"))
706
+ return false;
707
+ try {
708
+ const event = JSON.parse(trimmed);
709
+ // The same events the output parsers report as provider errors.
710
+ return event.type === "turn.failed"
711
+ || event.type === "error"
712
+ || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
713
+ }
714
+ catch {
715
+ return false;
716
+ }
717
+ }
502
718
  function isProviderTerminalSuccess(line) {
503
719
  const trimmed = line.trim();
504
720
  if (!trimmed.startsWith("{"))
@@ -682,6 +898,64 @@ async function resolveProviderProcessLaunch(command, args) {
682
898
  ?? resolvePackageManagerDirectLaunch(resolved, args)
683
899
  ?? buildWindowsLaunchCommand(resolved, args);
684
900
  }
901
+ const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
902
+ const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
903
+ export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
904
+ /**
905
+ * Blocks on fd 3 until the bridge writes the exact grant line, then replaces
906
+ * itself with the provider (`exec`), so the supervised root PID, process group
907
+ * and birth identity stay the provider's. The provider command and arguments
908
+ * are passed positionally and expanded only as "$@"; nothing is interpolated
909
+ * into the script. EOF, a read error, or any other content on fd 3 exits
910
+ * without running the provider. fd 3 is closed before exec so the provider and
911
+ * its descendants never inherit the grant channel. stdin is not touched, so
912
+ * the prompt stays buffered in its pipe for the provider.
913
+ */
914
+ const UNIX_PROVIDER_START_GATE_SCRIPT = [
915
+ "IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
916
+ `[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
917
+ "exec \"$@\" 3<&-",
918
+ ].join("\n");
919
+ export function buildUnixProviderStartGateLaunch(command, args) {
920
+ return {
921
+ command: UNIX_PROVIDER_START_GATE_SHELL,
922
+ args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
923
+ };
924
+ }
925
+ /**
926
+ * Mirrors the executable lookup the gate's `exec` will perform. A command that
927
+ * cannot be found is spawned directly instead so it keeps failing as a spawn
928
+ * ENOENT before any start is recorded; nothing can run in that case. The check
929
+ * is advisory: if the executable disappears between this lookup and the gated
930
+ * `exec`, the gate exits 127 with the shell's "not found" message after the
931
+ * start was recorded, which surfaces as an ordinary provider failure.
932
+ */
933
+ function isUnixExecutableAvailable(command, pathValue, cwd) {
934
+ if (!command || command.startsWith("-"))
935
+ return false;
936
+ const candidates = command.includes("/")
937
+ ? [path.resolve(cwd, command)]
938
+ : pathValue === undefined
939
+ ? null
940
+ : pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
941
+ if (candidates === null)
942
+ return true;
943
+ return candidates.some(candidate => {
944
+ try {
945
+ if (!fs.statSync(candidate).isFile())
946
+ return false;
947
+ fs.accessSync(candidate, fs.constants.X_OK);
948
+ return true;
949
+ }
950
+ catch {
951
+ return false;
952
+ }
953
+ });
954
+ }
955
+ function isBrokenPipeError(error) {
956
+ const code = error?.code;
957
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
958
+ }
685
959
  function grantWindowsProviderStart(launch) {
686
960
  if (!launch.startGrantPath) {
687
961
  throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
@@ -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}