@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c2f22d1dd395

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 (62) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/bridge.service.d.ts +12 -1
  3. package/dist/bridge/bridge.service.js +53 -6
  4. package/dist/bridge/bridge.types.d.ts +6 -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/cli/cli.help.js +2 -2
  8. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  9. package/dist/runtime/attempt-database-broker.js +390 -0
  10. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  11. package/dist/runtime/attempt-process-supervisor.js +77 -3
  12. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  13. package/dist/runtime/host-database-capability-boundary.js +1 -0
  14. package/dist/runtime/host-diagnostics.js +4 -3
  15. package/dist/runtime/host-facts.d.ts +35 -0
  16. package/dist/runtime/host-facts.js +95 -0
  17. package/dist/runtime/host-load-sampler.d.ts +83 -0
  18. package/dist/runtime/host-load-sampler.js +164 -0
  19. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  20. package/dist/runtime/host-pressure-stall.js +121 -0
  21. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  22. package/dist/runtime/host-runtime-contract.js +71 -10
  23. package/dist/runtime/host-runtime-lease.d.ts +4 -2
  24. package/dist/runtime/host-runtime-lease.js +108 -24
  25. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  26. package/dist/runtime/managed-command-teardown.js +607 -0
  27. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  28. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  29. package/dist/runtime/playwright-browser-cache.js +227 -0
  30. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  31. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  32. package/dist/sandbox/repository-lock.js +3 -2
  33. package/dist/sandbox/runtime.js +5 -4
  34. package/dist/session/managed-attempt-tools.d.ts +25 -0
  35. package/dist/session/managed-attempt-tools.js +222 -20
  36. package/dist/session/managed-build-coordinator.d.ts +1 -1
  37. package/dist/session/managed-build-coordinator.js +8 -4
  38. package/dist/session/phase-completion.artifacts.js +4 -0
  39. package/dist/session/phase-completion.runtime.js +30 -18
  40. package/dist/session/pre-publication-process.d.ts +20 -0
  41. package/dist/session/pre-publication-process.js +97 -0
  42. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  43. package/dist/session/pre-publication-skipped-tests.js +109 -0
  44. package/dist/session/pre-publication-validation.js +32 -58
  45. package/dist/session/provider-cli/provider-cli.artifacts.js +2 -9
  46. package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
  47. package/dist/session/provider-cli/provider-cli.process.js +198 -16
  48. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  49. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  50. package/dist/session/provider-cli/provider-cli.service.js +64 -12
  51. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  52. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  53. package/dist/session/publishable-worktree-changes.js +177 -0
  54. package/dist/session/session.types.js +3 -0
  55. package/dist/shared/process/host-process-recovery.js +3 -2
  56. package/dist/shared/process/host-process-supervisor.js +5 -4
  57. package/dist/shared/time/monotonic.d.ts +1 -0
  58. package/dist/shared/time/monotonic.js +8 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/worktree/dependency-warmer.js +74 -0
  62. package/package.json +1 -1
@@ -16,6 +16,9 @@ const execFileAsync = promisify(execFile);
16
16
  // only needs a bounded diagnostic tail for failure classification.
17
17
  export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
18
18
  const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
19
+ // 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
+ const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
19
22
  const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
20
23
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
21
24
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -313,8 +316,10 @@ function setEnvironmentValueIfMissing(env, name, value) {
313
316
  }
314
317
  export class StreamingProviderProcessRunner {
315
318
  terminalExitGraceMs;
316
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS) {
319
+ terminalSuccessCeilingMs;
320
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS) {
317
321
  this.terminalExitGraceMs = terminalExitGraceMs;
322
+ this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
318
323
  }
319
324
  async run(request, handlers = {}, signal) {
320
325
  assertHostDatabaseCapabilityBoundary();
@@ -323,12 +328,29 @@ export class StreamingProviderProcessRunner {
323
328
  // An unsupervised Unix provider still gets a dedicated process group so a
324
329
  // cancellation can stop descendants instead of only the CLI root.
325
330
  const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
331
+ const childEnvironment = buildProviderChildEnvironment(request.env);
332
+ // A piped prompt must reach the provider promptly (Claude Code abandons a
333
+ // silent stdin after ~3s), but the provider must not run before Forge has
334
+ // recorded its start. Off Windows, hold the launch behind a start gate in
335
+ // the same process: the prompt is written immediately and buffers in the
336
+ // pipe, and the gate execs the provider only once onStarted succeeds.
337
+ const startGated = process.platform !== "win32"
338
+ && supervisedLaunch?.strategy !== "windows_job_object"
339
+ && request.stdin !== undefined
340
+ && fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
341
+ && isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
342
+ const spawnLaunch = startGated
343
+ ? buildUnixProviderStartGateLaunch(launch.command, launch.args)
344
+ : launch;
326
345
  return await new Promise((resolve, reject) => {
327
346
  const rootCreatedAt = new Date().toISOString();
328
- const child = spawn(launch.command, launch.args, {
347
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
348
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
329
349
  cwd: request.cwd,
330
- env: buildProviderChildEnvironment(request.env),
331
- stdio: [request.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
350
+ env: childEnvironment,
351
+ stdio: startGated
352
+ ? [stdinMode, "pipe", "pipe", "pipe"]
353
+ : [stdinMode, "pipe", "pipe"],
332
354
  windowsHide: true,
333
355
  detached: launch.detached,
334
356
  });
@@ -352,14 +374,21 @@ export class StreamingProviderProcessRunner {
352
374
  let settled = false;
353
375
  let closed = false;
354
376
  let cancellationRequested = false;
377
+ let cancelledBeforeClose = false;
355
378
  let terminalTerminationStarted = false;
356
379
  let terminalExitTimer = null;
380
+ let terminalCeilingTimer = null;
381
+ let latestTurnFailed = false;
357
382
  let readiness = null;
358
383
  const cleanup = () => {
359
384
  if (terminalExitTimer) {
360
385
  clearTimeout(terminalExitTimer);
361
386
  terminalExitTimer = null;
362
387
  }
388
+ if (terminalCeilingTimer) {
389
+ clearTimeout(terminalCeilingTimer);
390
+ terminalCeilingTimer = null;
391
+ }
363
392
  signal?.removeEventListener("abort", abort);
364
393
  };
365
394
  const fail = (error) => {
@@ -373,6 +402,8 @@ export class StreamingProviderProcessRunner {
373
402
  void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
374
403
  };
375
404
  const abort = () => {
405
+ if (!closed)
406
+ cancelledBeforeClose = true;
376
407
  cancellationRequested = true;
377
408
  // Cancellation is not a launch failure when the supervised tree can be
378
409
  // proven stopped. Let the close handler settle the command after exact
@@ -386,6 +417,27 @@ export class StreamingProviderProcessRunner {
386
417
  signal?.addEventListener("abort", abort, { once: true });
387
418
  }
388
419
  child.on("error", fail);
420
+ const startGrant = startGated ? child.stdio[3] : null;
421
+ if (startGated && !startGrant) {
422
+ fail(new Error("Provider start-grant stream was not piped."));
423
+ return;
424
+ }
425
+ startGrant?.on("error", error => {
426
+ // A broken grant pipe means the gate already exited (terminated before
427
+ // its grant, or it died on its own). Its close event carries the real
428
+ // exit status, so an EPIPE here must not replace that result.
429
+ if (isBrokenPipeError(error))
430
+ return;
431
+ fail(error);
432
+ });
433
+ const grantUnixProviderStart = () => {
434
+ if (!startGrant)
435
+ return;
436
+ // Never release a provider whose launch was cancelled or already failed.
437
+ if (closed || settled || cancellationRequested || signal?.aborted)
438
+ return;
439
+ startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
440
+ };
389
441
  child.once("spawn", () => {
390
442
  readiness = (async () => {
391
443
  const providerReady = supervisedLaunch?.strategy === "windows_job_object"
@@ -398,6 +450,9 @@ export class StreamingProviderProcessRunner {
398
450
  if (supervisedLaunch?.strategy === "windows_job_object") {
399
451
  grantWindowsProviderStart(supervisedLaunch);
400
452
  }
453
+ else if (startGated) {
454
+ grantUnixProviderStart();
455
+ }
401
456
  })();
402
457
  void readiness.catch(error => {
403
458
  if (!closed && !signal?.aborted)
@@ -413,15 +468,20 @@ export class StreamingProviderProcessRunner {
413
468
  return;
414
469
  }
415
470
  child.stdin.on("error", (error) => {
471
+ // A prompt still buffered when Forge stops the process (cancellation,
472
+ // or a refused start grant) cannot be delivered; that broken pipe is
473
+ // not a failure. Any other stdin error still is.
474
+ if ((cancellationRequested || termination) && isBrokenPipeError(error))
475
+ return;
416
476
  void terminate();
417
477
  fail(error);
418
478
  });
419
479
  child.stdin.end(request.stdin, "utf8");
420
480
  };
421
481
  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.
482
+ if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
483
+ // The outer supervisor / Unix start gate must receive stdin before it
484
+ // can launch the provider. Its start grant fences prompt processing.
425
485
  writeProviderInput();
426
486
  }
427
487
  else {
@@ -430,19 +490,46 @@ export class StreamingProviderProcessRunner {
430
490
  });
431
491
  }
432
492
  }
493
+ const finishAfterTerminalSuccess = () => {
494
+ if (closed || settled || cancellationRequested || terminalTerminationStarted)
495
+ return;
496
+ terminalTerminationStarted = true;
497
+ void terminate().catch(fail);
498
+ };
499
+ const armTerminalExit = () => {
500
+ if (terminalExitTimer)
501
+ clearTimeout(terminalExitTimer);
502
+ terminalExitTimer = setTimeout(finishAfterTerminalSuccess, this.terminalExitGraceMs);
503
+ terminalExitTimer.unref?.();
504
+ // 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
+ }
509
+ };
433
510
  const readers = [
434
511
  readProcessLines(childStdout, (line) => {
435
512
  if (request.captureOutput !== false)
436
513
  stdout.appendLine(line);
437
514
  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?.();
515
+ if (!terminalTerminationStarted) {
516
+ if (isProviderTerminalSuccess(line)) {
517
+ latestTurnFailed = false;
518
+ armTerminalExit();
519
+ }
520
+ else if (isProviderTerminalFailure(line)) {
521
+ // A later turn that fails reports its failure even after an earlier success.
522
+ latestTurnFailed = true;
523
+ }
524
+ else if (terminalExitTimer && isProviderTurnActivity(line)) {
525
+ // A terminal event ends a turn, not necessarily the provider. Claude Code
526
+ // 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;
529
+ // the grace period restarts at its next terminal event.
530
+ clearTimeout(terminalExitTimer);
531
+ terminalExitTimer = null;
532
+ }
446
533
  }
447
534
  return handled;
448
535
  }),
@@ -489,16 +576,53 @@ export class StreamingProviderProcessRunner {
489
576
  // that event, terminate the supervised tree after a short grace
490
577
  // period and preserve the successful handoff so the existing
491
578
  // artifact, commit, and publication gates can run.
492
- exitCode: terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
579
+ // A provider stopped after a successful turn keeps that success. Whenever the
580
+ // most recent turn failed, the run fails, however the process ended.
581
+ exitCode: latestTurnFailed
582
+ ? code && code !== 0 ? code : 1
583
+ : terminalTerminationStarted && !cancellationRequested ? 0 : code ?? 1,
493
584
  stdout: stdout.toString(),
494
585
  stderr: stderr.toString(),
495
586
  ...(memory ?? {}),
587
+ ...(cancelledBeforeClose ? { cancelled: true } : {}),
496
588
  });
497
589
  }).catch(fail);
498
590
  });
499
591
  });
500
592
  }
501
593
  }
594
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
595
+ function isProviderTurnActivity(line) {
596
+ const trimmed = line.trim();
597
+ if (!trimmed.startsWith("{"))
598
+ return false;
599
+ try {
600
+ const event = JSON.parse(trimmed);
601
+ return event.type === "assistant"
602
+ || event.type === "user"
603
+ || (event.type === "system" && event.subtype === "init")
604
+ || event.type === "turn.started"
605
+ || event.type === "item.started";
606
+ }
607
+ catch {
608
+ return false;
609
+ }
610
+ }
611
+ function isProviderTerminalFailure(line) {
612
+ const trimmed = line.trim();
613
+ if (!trimmed.startsWith("{"))
614
+ return false;
615
+ try {
616
+ const event = JSON.parse(trimmed);
617
+ // The same events the output parsers report as provider errors.
618
+ return event.type === "turn.failed"
619
+ || event.type === "error"
620
+ || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
621
+ }
622
+ catch {
623
+ return false;
624
+ }
625
+ }
502
626
  function isProviderTerminalSuccess(line) {
503
627
  const trimmed = line.trim();
504
628
  if (!trimmed.startsWith("{"))
@@ -682,6 +806,64 @@ async function resolveProviderProcessLaunch(command, args) {
682
806
  ?? resolvePackageManagerDirectLaunch(resolved, args)
683
807
  ?? buildWindowsLaunchCommand(resolved, args);
684
808
  }
809
+ const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
810
+ const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
811
+ export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
812
+ /**
813
+ * Blocks on fd 3 until the bridge writes the exact grant line, then replaces
814
+ * itself with the provider (`exec`), so the supervised root PID, process group
815
+ * and birth identity stay the provider's. The provider command and arguments
816
+ * are passed positionally and expanded only as "$@"; nothing is interpolated
817
+ * into the script. EOF, a read error, or any other content on fd 3 exits
818
+ * without running the provider. fd 3 is closed before exec so the provider and
819
+ * its descendants never inherit the grant channel. stdin is not touched, so
820
+ * the prompt stays buffered in its pipe for the provider.
821
+ */
822
+ const UNIX_PROVIDER_START_GATE_SCRIPT = [
823
+ "IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
824
+ `[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
825
+ "exec \"$@\" 3<&-",
826
+ ].join("\n");
827
+ export function buildUnixProviderStartGateLaunch(command, args) {
828
+ return {
829
+ command: UNIX_PROVIDER_START_GATE_SHELL,
830
+ args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
831
+ };
832
+ }
833
+ /**
834
+ * Mirrors the executable lookup the gate's `exec` will perform. A command that
835
+ * cannot be found is spawned directly instead so it keeps failing as a spawn
836
+ * ENOENT before any start is recorded; nothing can run in that case. The check
837
+ * is advisory: if the executable disappears between this lookup and the gated
838
+ * `exec`, the gate exits 127 with the shell's "not found" message after the
839
+ * start was recorded, which surfaces as an ordinary provider failure.
840
+ */
841
+ function isUnixExecutableAvailable(command, pathValue, cwd) {
842
+ if (!command || command.startsWith("-"))
843
+ return false;
844
+ const candidates = command.includes("/")
845
+ ? [path.resolve(cwd, command)]
846
+ : pathValue === undefined
847
+ ? null
848
+ : pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
849
+ if (candidates === null)
850
+ return true;
851
+ return candidates.some(candidate => {
852
+ try {
853
+ if (!fs.statSync(candidate).isFile())
854
+ return false;
855
+ fs.accessSync(candidate, fs.constants.X_OK);
856
+ return true;
857
+ }
858
+ catch {
859
+ return false;
860
+ }
861
+ });
862
+ }
863
+ function isBrokenPipeError(error) {
864
+ const code = error?.code;
865
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
866
+ }
685
867
  function grantWindowsProviderStart(launch) {
686
868
  if (!launch.startGrantPath) {
687
869
  throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
@@ -3,6 +3,12 @@ import type { ProviderCliRunContext } from "./provider-cli.types.js";
3
3
  import type { ProviderOutputState } from "./provider-output-state.js";
4
4
  import { type ProviderUsage } from "./provider-usage.js";
5
5
  export declare function providerProcessEnv(dispatch: RunOnceDispatchPacket, runtimeEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
6
+ /**
7
+ * Pre-publication validation runs the attempt's own checks, whose E2E fixtures log in to the
8
+ * brokered attempt database. Unlike the provider's shell, it receives that capability; the
9
+ * validator redacts it from every command's output.
10
+ */
11
+ export declare function prePublicationValidationEnv(dispatch: RunOnceDispatchPacket, runtimeEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
6
12
  export declare function providerRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
7
13
  export declare function providerCredentialEnv(dispatch: RunOnceDispatchPacket): Readonly<Record<string, string>>;
8
14
  /**
@@ -1,3 +1,4 @@
1
+ import { attemptDatabaseCapabilityEnvironment } from "../../runtime/attempt-database-broker.js";
1
2
  import { completionRedactionEnv } from "../phase-completion.js";
2
3
  import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage } from "./provider-usage.js";
3
4
  export function providerProcessEnv(dispatch, runtimeEnvironment) {
@@ -12,6 +13,16 @@ export function providerProcessEnv(dispatch, runtimeEnvironment) {
12
13
  // Bridge environment, including credentials outside the provider contract.
13
14
  return env;
14
15
  }
16
+ /**
17
+ * Pre-publication validation runs the attempt's own checks, whose E2E fixtures log in to the
18
+ * brokered attempt database. Unlike the provider's shell, it receives that capability; the
19
+ * validator redacts it from every command's output.
20
+ */
21
+ export function prePublicationValidationEnv(dispatch, runtimeEnvironment) {
22
+ const env = providerProcessEnv(dispatch, runtimeEnvironment);
23
+ const capability = runtimeEnvironment?.[attemptDatabaseCapabilityEnvironment]?.trim();
24
+ return capability ? { ...env, [attemptDatabaseCapabilityEnvironment]: capability } : env;
25
+ }
15
26
  export function providerRuntimeEnvironment(runtimeEnvironment) {
16
27
  if (!runtimeEnvironment)
17
28
  return {};
@@ -19,6 +30,9 @@ export function providerRuntimeEnvironment(runtimeEnvironment) {
19
30
  const normalized = name.trim().toUpperCase();
20
31
  return normalized !== "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING"
21
32
  && normalized !== "FORGE_TEST_POSTGRES_CONNECTION_STRING"
33
+ // The attempt database login reaches the application runtime, pre-publication checks and
34
+ // managed commands (which redact it); the provider's own shell does not need it.
35
+ && normalized !== "FORGE_ATTEMPT_DATABASE_CAPABILITY"
22
36
  && !normalized.startsWith("CONNECTIONSTRINGS__")
23
37
  && !normalized.startsWith("CONNECTIONSTRINGS:")
24
38
  && !normalized.endsWith("_CONNECTION_STRING");
@@ -6,11 +6,12 @@ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-inject
6
6
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
7
7
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
8
8
  import { ForgeFailureError } from "../session.types.js";
9
- import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, stagePublishableWorktreeChanges, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
9
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
10
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
10
11
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
11
12
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
12
13
  import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
13
- import { emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
14
+ import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
14
15
  import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
15
16
  import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
16
17
  import { assertRepairHeadEpoch } from "./provider-cli.repair-epoch.js";
@@ -68,12 +69,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
68
69
  const claimed = [...new Set(claimedChangedFiles)].sort();
69
70
  const actual = [...new Set(normalizedActual)].sort();
70
71
  if (hasFixedDisposition && actual.length === 0) {
71
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
72
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
72
73
  }
73
74
  if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
74
- throw new Error("Comment repair changed_files must exactly match the publishable staged source diff.");
75
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
76
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
75
77
  }
76
78
  }
79
+ /**
80
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
81
+ * published commit; otherwise the thread would be resolved without its fix. That covers
82
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
83
+ */
84
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
85
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
86
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
87
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
88
+ ]));
89
+ const payload = JSON.parse(artifact.verdictJson);
90
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
+ const fixed = dispositions.flatMap(value => {
92
+ const record = value;
93
+ if (record.disposition !== "fixed")
94
+ return [];
95
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
96
+ const findingPath = findingPaths.get(identity);
97
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
98
+ });
99
+ if (fixed.length === 0)
100
+ return;
101
+ const unpublished = new Set([
102
+ ...changeSet.excluded.map(normalizeChangedFilePath),
103
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
104
+ ]);
105
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
106
+ if (dropped.length > 0) {
107
+ throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
108
+ }
109
+ }
110
+ function commentRepairChangedFilesMismatch(message) {
111
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
112
+ }
113
+ function formatChangedFilesDelta(missing, unexpected) {
114
+ const parts = [
115
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
116
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
117
+ ].filter(Boolean);
118
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
119
+ }
77
120
  async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
78
121
  const payload = JSON.parse(artifact.verdictJson);
79
122
  const claimedRecords = Array.isArray(payload.changed_files)
@@ -90,11 +133,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
90
133
  const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
134
  const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
92
135
  if (hasFixedDisposition && authoritativePaths.length === 0) {
93
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
136
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
94
137
  }
95
138
  for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
96
139
  if (baselinePath && !authoritative.has(baselinePath)) {
97
- throw new Error(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
140
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
98
141
  }
99
142
  }
100
143
  payload.changed_files = authoritativePaths.map(filePath => {
@@ -1220,7 +1263,9 @@ export class ProcessBackedProviderCliService {
1220
1263
  }
1221
1264
  let commentRepairBaselineChangedFiles = null;
1222
1265
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1266
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1267
+ commentRepairBaselineChangedFiles = baseline.publishable;
1268
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1269
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1270
  }
1226
1271
  const validationProfile = repairChecks
@@ -1236,8 +1281,10 @@ export class ProcessBackedProviderCliService {
1236
1281
  preparedHeadSha,
1237
1282
  repairScope: "pull_request",
1238
1283
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1284
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1285
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1286
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1287
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1288
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1289
  }
1243
1290
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1397,10 +1444,14 @@ export class ProcessBackedProviderCliService {
1397
1444
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1445
  };
1399
1446
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1447
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1448
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1449
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1450
  "Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
1402
- "Review the current diff and the durable review snapshot, preserve the validation evidence already gathered,",
1403
- "then call forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1451
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1452
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1453
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1454
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1455
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1456
  ].join(" ");
1406
1457
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -1489,9 +1540,10 @@ export class ProcessBackedProviderCliService {
1489
1540
  const { dispatch, worktree } = context;
1490
1541
  const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
1491
1542
  const environment = providerProcessEnv(dispatch, repairEnvironment);
1543
+ const validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1492
1544
  for (let repairTurn = 0;; repairTurn += 1) {
1493
1545
  try {
1494
- await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, environment, this.processRunner, preparedHeadSha));
1546
+ await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
1495
1547
  if (repairTurn > 0) {
1496
1548
  await context.emit({
1497
1549
  role: "runner",
@@ -4,7 +4,8 @@ export type InputTokenSemantics = "includes_cached_input" | "excludes_cache_toke
4
4
  export declare const PROVIDER_USAGE_SCHEMA_VERSION = 1;
5
5
  /**
6
6
  * Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
7
- * here; the API recomputes cost from these tokens x model rates (ADR-0006).
7
+ * here; the API recomputes cost from these tokens x model rates (legacy
8
+ * ADR-0006, .forge-designer/decisions/legacy/0006-cost-capture.md).
8
9
  */
9
10
  export interface ProviderUsage {
10
11
  /** Normalized total input. Cached input is a subset, never an additive peer. */
@@ -0,0 +1,45 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type ProcessRunner } from "../shared/process/process.js";
3
+ export interface PublishableWorktreeChangeSet {
4
+ /** Paths staged for publication, as `git diff --cached --name-only` reports them. */
5
+ readonly publishable: readonly string[];
6
+ /** Worktree changes Forge treats as runtime output and leaves unstaged. */
7
+ readonly excluded: readonly string[];
8
+ }
9
+ /**
10
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
11
+ *
12
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
13
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
14
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
15
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
16
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
17
+ */
18
+ export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
19
+ /** Stages every publishable worktree change in the real index and returns both sets. */
20
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
21
+ /**
22
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
23
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
24
+ * `worktreePath` is not the root of a git worktree.
25
+ */
26
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
27
+ /** Compares claimed `changed_files` paths with the publishable diff. */
28
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
29
+ readonly missing: readonly string[];
30
+ readonly unexpected: readonly string[];
31
+ };
32
+ export declare function normalizeChangedFilePath(value: string): string;
33
+ /**
34
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
35
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
36
+ * in the same turn instead of failing at publication.
37
+ */
38
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
39
+ /**
40
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
41
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
42
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
43
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
44
+ */
45
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;