@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.7171bf414613

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 (152) hide show
  1. package/README.md +41 -3
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. package/package.json +1 -1
@@ -0,0 +1,46 @@
1
+ import type { RuntimeEnvironmentRefresh } from "./provider-cli/provider-cli.types.js";
2
+ import type { RunOnceDispatchPacket, RunnerDispatchEvent } from "./session.types.js";
3
+ import type { HostRuntimeLeaseRuntime, HostRuntimeLeaseStart } from "../runtime/host-runtime-lease.js";
4
+ import { readWorkspaceRuntimeFingerprint, type WorkspaceRuntimeFingerprintReader } from "./workspace-runtime-fingerprint.js";
5
+ export { readWorkspaceRuntimeFingerprint, type WorkspaceRuntimeFingerprintReader };
6
+ export interface RuntimeEnvironmentRefreshInput {
7
+ readonly worktreePath: string;
8
+ readonly dispatchAttemptId: string;
9
+ readonly fencingToken: string;
10
+ readonly restartConfiguredProject: NonNullable<HostRuntimeLeaseRuntime["restartConfiguredProject"]>;
11
+ readonly readFingerprint: WorkspaceRuntimeFingerprintReader;
12
+ readonly emitLifecycle: (event: RunnerDispatchEvent) => Promise<void>;
13
+ readonly signal?: AbortSignal;
14
+ /** Throws when the attempt was aborted or a late isolation violation stopped its stack. */
15
+ readonly assertRunning?: () => void;
16
+ /** Called with the restarted lease so the caller keeps serving the current stack. */
17
+ readonly onRestarted: (restarted: HostRuntimeLeaseStart) => void;
18
+ /**
19
+ * True while the first start of the stack is deferred (re-apply conflicts): the stack has never run,
20
+ * so the first pass starts it. Cleared after a successful restart.
21
+ */
22
+ readonly startDeferred?: boolean;
23
+ }
24
+ /**
25
+ * Builds the pre-publication hook that restarts the attempt runtime stack when the provider has
26
+ * changed the workspace since the stack was launched. The stack was built and launched from the
27
+ * workspace state read here.
28
+ */
29
+ export declare function createRuntimeEnvironmentRefresh(input: RuntimeEnvironmentRefreshInput): Promise<(refreshSignal?: AbortSignal) => Promise<RuntimeEnvironmentRefresh | null>>;
30
+ export interface ConfiguredRuntimeRefreshInput {
31
+ readonly hostLease: HostRuntimeLeaseStart | null;
32
+ readonly dispatch: RunOnceDispatchPacket;
33
+ readonly hostRuntime: HostRuntimeLeaseRuntime | undefined;
34
+ readonly worktreePath: string;
35
+ readonly readFingerprint: WorkspaceRuntimeFingerprintReader;
36
+ readonly emitLifecycle: (event: RunnerDispatchEvent) => Promise<void>;
37
+ readonly signal?: AbortSignal;
38
+ readonly assertRunning?: () => void;
39
+ readonly onRestarted: (restarted: HostRuntimeLeaseStart) => void;
40
+ readonly startDeferred?: boolean;
41
+ }
42
+ /**
43
+ * The refresh hook for a managed runtime lease with configured launch ports, or undefined when the
44
+ * attempt has no restartable project stack.
45
+ */
46
+ export declare function createConfiguredRuntimeRefresh(input: ConfiguredRuntimeRefreshInput): Promise<((refreshSignal?: AbortSignal) => Promise<RuntimeEnvironmentRefresh | null>) | undefined>;
@@ -0,0 +1,116 @@
1
+ import { configuredLaunchPortNames } from "../runtime/host-runtime-promotion.js";
2
+ import { hostRuntimeEventResources } from "../runtime/host-runtime-lease.js";
3
+ import { runtimeRestartStartedMessage } from "./session-host-project.js";
4
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
5
+ // Re-exported so the session service reaches the workspace fingerprint reader through this module.
6
+ export { readWorkspaceRuntimeFingerprint };
7
+ function failureMessage(error) {
8
+ return error instanceof Error ? error.message : String(error);
9
+ }
10
+ /**
11
+ * Builds the pre-publication hook that restarts the attempt runtime stack when the provider has
12
+ * changed the workspace since the stack was launched. The stack was built and launched from the
13
+ * workspace state read here.
14
+ */
15
+ export async function createRuntimeEnvironmentRefresh(input) {
16
+ const { worktreePath, dispatchAttemptId, fencingToken, restartConfiguredProject, readFingerprint, emitLifecycle, signal, assertRunning, onRestarted } = input;
17
+ let launchFingerprint = await readFingerprint(worktreePath)
18
+ .catch(() => null);
19
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
20
+ let restartPending = false;
21
+ // Set until the deferred first start (re-apply conflicts) succeeds: the stack has never run.
22
+ let startDeferred = input.startDeferred ?? false;
23
+ return async (refreshSignal) => {
24
+ // A late violation stopped the stack: fail this validation pass rather than run it against closed ports.
25
+ assertRunning?.();
26
+ const current = await readFingerprint(worktreePath).catch(() => null);
27
+ if (!restartPending && !startDeferred && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
28
+ return null;
29
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
30
+ // only when both states were read: an unreadable baseline is not a workspace change.
31
+ const comparable = launchFingerprint !== null && current !== null;
32
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
33
+ const causes = [
34
+ ...(startDeferred ? ["deferred_start"] : []),
35
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
36
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
37
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
38
+ ];
39
+ const reason = causes[0] ?? "workspace_changed";
40
+ await emitLifecycle({
41
+ role: "runner",
42
+ kind: "checkpoint",
43
+ content: runtimeRestartStartedMessage(reason, changes),
44
+ eventType: "host_runtime_restart_started",
45
+ data: JSON.stringify({
46
+ reason,
47
+ causes,
48
+ changes,
49
+ head_sha: current?.headSha ?? null,
50
+ merge_in_progress: Boolean(current?.mergeHead),
51
+ }),
52
+ });
53
+ restartPending = true;
54
+ let restarted;
55
+ try {
56
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
57
+ await emitLifecycle({
58
+ role: "runner",
59
+ kind: "checkpoint",
60
+ content: checkpoint.message,
61
+ eventType: checkpoint.code,
62
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
63
+ });
64
+ });
65
+ }
66
+ catch (error) {
67
+ await emitLifecycle({
68
+ role: "runner",
69
+ kind: "error",
70
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
71
+ eventType: "host_runtime_restart_failed",
72
+ data: JSON.stringify({ reason, causes, changes }),
73
+ }).catch(() => undefined);
74
+ throw error;
75
+ }
76
+ onRestarted(restarted);
77
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
78
+ // keep the pre-restart reading, which is null when it could not be collected; a null
79
+ // baseline never matches, so every later pass would restart and rotate ports again.
80
+ launchFingerprint = await readFingerprint(worktreePath).catch(() => current);
81
+ restartPending = false;
82
+ startDeferred = false;
83
+ await emitLifecycle({
84
+ role: "runner",
85
+ kind: "checkpoint",
86
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
87
+ eventType: "host_runtime_restarted",
88
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
89
+ });
90
+ return { environment: restarted.environment, reason, changes };
91
+ };
92
+ }
93
+ /**
94
+ * The refresh hook for a managed runtime lease with configured launch ports, or undefined when the
95
+ * attempt has no restartable project stack.
96
+ */
97
+ export async function createConfiguredRuntimeRefresh(input) {
98
+ const { hostLease, dispatch, hostRuntime } = input;
99
+ if (!hostLease || !dispatch.sandbox || !hostRuntime?.restartConfiguredProject
100
+ || hostLease.executionClass !== "managed_runtime"
101
+ || configuredLaunchPortNames(hostLease.runtimeContract).length === 0) {
102
+ return undefined;
103
+ }
104
+ return await createRuntimeEnvironmentRefresh({
105
+ worktreePath: input.worktreePath,
106
+ dispatchAttemptId: dispatch.sandbox.dispatchAttemptId,
107
+ fencingToken: dispatch.lease.fencingToken,
108
+ restartConfiguredProject: hostRuntime.restartConfiguredProject.bind(hostRuntime),
109
+ readFingerprint: input.readFingerprint,
110
+ emitLifecycle: input.emitLifecycle,
111
+ signal: input.signal,
112
+ assertRunning: input.assertRunning,
113
+ onRestarted: input.onRestarted,
114
+ startDeferred: input.startDeferred
115
+ });
116
+ }
@@ -1,3 +1,4 @@
1
+ export { runOnceWithReviewPlacement } from "./pr-review-placement.js";
1
2
  import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
2
3
  import type { ProviderCliService } from "./provider-cli/provider-cli.base.js";
3
4
  import type { SessionEventSink, SessionService } from "./session.base.js";
@@ -5,7 +6,7 @@ import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult,
5
6
  import type { WorktreeService } from "../worktree/worktree.base.js";
6
7
  import { type HostCapacityLimits, type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
7
8
  import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
8
- import { type WorkspaceRuntimeFingerprintReader } from "./workspace-runtime-fingerprint.js";
9
+ import { type WorkspaceRuntimeFingerprintReader } from "./session.runtime-refresh.js";
9
10
  export declare class BridgeSessionService implements SessionService {
10
11
  private readonly worktrees;
11
12
  private readonly providerCli;
@@ -1,12 +1,15 @@
1
+ // forge-bridge run-once's review placement guard (pr-review-placement.ts).
2
+ export { runOnceWithReviewPlacement } from "./pr-review-placement.js";
1
3
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-redaction.js";
2
4
  import { randomUUID } from "node:crypto";
3
5
  import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
4
6
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
- import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree } from "../worktree/worktree.service.js";
7
+ import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree, } from "../worktree/worktree.service.js";
6
8
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
9
  import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
10
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
- import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
11
+ import { managedQaLaunchTarget, startOrDeferConfiguredProject, withMaterializedManagedQaTarget, } from "./session-host-project.js";
12
+ import { createConfiguredRuntimeRefresh, readWorkspaceRuntimeFingerprint, } from "./session.runtime-refresh.js";
10
13
  const minimumReadinessProbeStartupBudgetMs = 150_000;
11
14
  export class BridgeSessionService {
12
15
  worktrees;
@@ -250,11 +253,10 @@ export class BridgeSessionService {
250
253
  warmPathOverrides: dispatch.warmPathOverrides,
251
254
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
252
255
  preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
256
+ // A review reads the exact pull request head, detached; it never works on a lease branch.
257
+ detachedHeadSha: prReviewHeadSha(dispatch),
253
258
  sessionId: dispatch.session.id,
254
- hostLoadOwner: {
255
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
256
- priority: runtimeAdmissionPriority(dispatch),
257
- },
259
+ ...preparedAttemptOwner(dispatch),
258
260
  signal,
259
261
  });
260
262
  }
@@ -283,6 +285,10 @@ export class BridgeSessionService {
283
285
  if (worktree.dependencyWarm) {
284
286
  await emitDependencyWarmEvents(worktree.dependencyWarm, emit);
285
287
  }
288
+ // Conflicts a WIP re-apply left for the agent (deferredProjectStartEvent): the project stack
289
+ // is not started on them, and the prompt names them.
290
+ const reapplyConflicts = worktree.reapplyConflicts;
291
+ let projectStartDeferred = false;
286
292
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
287
293
  hostLease = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal, async (checkpoint) => {
288
294
  const observation = waitObservation(checkpoint.code);
@@ -313,116 +319,25 @@ export class BridgeSessionService {
313
319
  remediation: "Enable Run in Docker in Project Settings.",
314
320
  }),
315
321
  });
316
- const unconfiguredPortCount = hostLease.lease.resources.ports.length;
317
- hostLease = await this.hostRuntime.startConfiguredProject(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken, signal, async (checkpoint) => {
318
- await emitLifecycle({
319
- role: "runner",
320
- kind: "checkpoint",
321
- content: checkpoint.message,
322
- eventType: checkpoint.code,
323
- data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
324
- });
325
- });
326
- if (hostLease.lease.resources.ports.length > unconfiguredPortCount) {
327
- const assigned = hostLease.lease.resources.ports.at(-1);
328
- await emitLifecycle({
329
- role: "runner",
330
- kind: "checkpoint",
331
- content: `Verified supervised project runtime ${assigned.name} on ${assigned.hostIp}:${assigned.hostPort}.`,
332
- eventType: "host_runtime_project_ready",
333
- data: JSON.stringify(hostRuntimeEventResources(hostLease.lease, hostLease.runtimeContract, hostLease.executionClass)),
334
- });
335
- }
322
+ ({ hostLease, deferred: projectStartDeferred } = await startOrDeferConfiguredProject(this.hostRuntime, hostLease, dispatch, reapplyConflicts, signal, emitLifecycle));
336
323
  }
337
324
  // The stack was built and launched from this workspace state. Pre-publication
338
325
  // validation restarts it when the provider has changed the source since.
339
- let refreshRuntimeEnvironment;
340
- const hostRuntime = this.hostRuntime;
341
- if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
342
- && hostLease.executionClass === "managed_runtime"
343
- && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
344
- const worktreePath = worktree.worktreePath;
345
- const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
346
- const fencingToken = dispatch.lease.fencingToken;
347
- const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
348
- let launchFingerprint = await this.workspaceFingerprint(worktreePath)
349
- .catch(() => null);
350
- // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
351
- let restartPending = false;
352
- refreshRuntimeEnvironment = async (refreshSignal) => {
353
- // A late violation stopped the stack: fail this validation pass rather than run it against closed ports.
354
- this.throwIfAbortedOrIsolationViolated(undefined, dispatch, hostLease);
355
- const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
356
- if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
357
- return null;
358
- // Every cause that applies is reported; `reason` is the first of them. Changes are named
359
- // only when both states were read: an unreadable baseline is not a workspace change.
360
- const comparable = launchFingerprint !== null && current !== null;
361
- const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
362
- const causes = [
363
- ...(restartPending ? ["previous_restart_incomplete"] : []),
364
- ...(comparable ? [] : ["fingerprint_unavailable"]),
365
- ...(changes.length > 0 ? ["workspace_changed"] : []),
366
- ];
367
- const reason = causes[0] ?? "workspace_changed";
368
- const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
369
- await emitLifecycle({
370
- role: "runner",
371
- kind: "checkpoint",
372
- content: reason === "workspace_changed"
373
- ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
374
- : reason === "previous_restart_incomplete"
375
- ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
376
- : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
377
- eventType: "host_runtime_restart_started",
378
- data: JSON.stringify({
379
- reason,
380
- causes,
381
- changes,
382
- head_sha: current?.headSha ?? null,
383
- merge_in_progress: Boolean(current?.mergeHead),
384
- }),
385
- });
386
- restartPending = true;
387
- let restarted;
388
- try {
389
- restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
390
- await emitLifecycle({
391
- role: "runner",
392
- kind: "checkpoint",
393
- content: checkpoint.message,
394
- eventType: checkpoint.code,
395
- data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
396
- });
397
- });
398
- }
399
- catch (error) {
400
- await emitLifecycle({
401
- role: "runner",
402
- kind: "error",
403
- content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
404
- eventType: "host_runtime_restart_failed",
405
- data: JSON.stringify({ reason, causes, changes }),
406
- }).catch(() => undefined);
407
- throw error;
408
- }
326
+ const refreshRuntimeEnvironment = await createConfiguredRuntimeRefresh({
327
+ hostLease,
328
+ dispatch,
329
+ hostRuntime: this.hostRuntime,
330
+ worktreePath: worktree.worktreePath,
331
+ readFingerprint: this.workspaceFingerprint,
332
+ emitLifecycle,
333
+ signal,
334
+ assertRunning: () => this.throwIfAbortedOrIsolationViolated(undefined, dispatch, hostLease),
335
+ onRestarted: restarted => {
409
336
  hostLease = restarted;
410
- // The restarted stack serves the workspace as it is now. Read that state again rather than
411
- // keep the pre-restart reading, which is null when it could not be collected; a null
412
- // baseline never matches, so every later pass would restart and rotate ports again.
413
- launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
414
- restartPending = false;
415
- await emitLifecycle({
416
- role: "runner",
417
- kind: "checkpoint",
418
- content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
419
- eventType: "host_runtime_restarted",
420
- data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
421
- });
422
- return { environment: restarted.environment, reason, changes };
423
- };
424
- }
425
- providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
337
+ },
338
+ startDeferred: projectStartDeferred
339
+ });
340
+ providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease, projectStartDeferred);
426
341
  const providerEnvironment = {
427
342
  runtimeEnvironment: hostLease?.environment,
428
343
  // Only the completion MCP server gets these: its managed commands share the host ledger.
@@ -462,6 +377,7 @@ export class BridgeSessionService {
462
377
  const isArchitect = role === "architect" || lane === "architect" || cycleKind === "architect";
463
378
  const isCiRepair = role === "ci_repair" || lane === "ci_repair" || cycleKind === "pr_checks";
464
379
  const isConflictResolve = role === "conflict_resolve" || lane === "conflict_resolve";
380
+ const isPrReview = role === "pr_review" || lane === "pr_review" || cycleKind === "pr_review";
465
381
  const context = {
466
382
  dispatch: providerDispatch,
467
383
  worktree,
@@ -472,20 +388,24 @@ export class BridgeSessionService {
472
388
  ...(refreshRuntimeEnvironment && hostLease
473
389
  ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
474
390
  : {}),
391
+ reapplyConflicts,
392
+ projectStartDeferred,
475
393
  emit,
476
394
  signal
477
395
  };
478
396
  let run;
479
397
  try {
480
- run = isQa
481
- ? await this.providerCli.runQa(context)
482
- : isArchitect
483
- ? await this.providerCli.runArchitect(context)
484
- : isCiRepair
485
- ? await this.providerCli.runCiRepair(context)
486
- : isConflictResolve
487
- ? await this.providerCli.runConflictResolve(context)
488
- : await this.providerCli.runImplementation(context);
398
+ run = isPrReview
399
+ ? await this.providerCli.runPrReview(context)
400
+ : isQa
401
+ ? await this.providerCli.runQa(context)
402
+ : isArchitect
403
+ ? await this.providerCli.runArchitect(context)
404
+ : isCiRepair
405
+ ? await this.providerCli.runCiRepair(context)
406
+ : isConflictResolve
407
+ ? await this.providerCli.runConflictResolve(context)
408
+ : await this.providerCli.runImplementation(context);
489
409
  }
490
410
  catch (error) {
491
411
  const message = failureMessage(error);
@@ -606,6 +526,15 @@ export class BridgeSessionService {
606
526
  }
607
527
  }
608
528
  }
529
+ function prReviewHeadSha(dispatch) {
530
+ const lane = dispatch.execution.lane.trim().toLowerCase();
531
+ const role = dispatch.execution.role.trim().toLowerCase();
532
+ const kind = dispatch.cycleRun.kind.trim().toLowerCase();
533
+ if (role !== "pr_review" && lane !== "pr_review" && kind !== "pr_review") {
534
+ return null;
535
+ }
536
+ return (dispatch.prReview?.headSha || dispatch.pullRequest?.headSha || "").trim() || null;
537
+ }
609
538
  function failureMessage(error) {
610
539
  return error instanceof Error ? error.message : String(error);
611
540
  }
@@ -725,43 +654,6 @@ function assertReadinessProbeStartupBudget(expiresAt) {
725
654
  throw new Error("host_runtime_probe_deadline_insufficient: readiness admission completed too close to the probe deadline; Forge released the reservation before launching the application.");
726
655
  }
727
656
  }
728
- function managedQaLaunchTarget(runtimeContract) {
729
- const playwright = runtimeContract.contract.runtime.playwright;
730
- if (!playwright)
731
- return null;
732
- const port = runtimeContract.contract.runtime.ports.find(candidate => candidate.name === playwright.baseUrlPort);
733
- return port?.launch && port.baseUrlEnv && port.format
734
- ? { managedRuntimePort: port.name, routes: ["/"] }
735
- : null;
736
- }
737
- function withMaterializedManagedQaTarget(dispatch, hostLease) {
738
- const target = dispatch.qaBrowser?.launchTarget;
739
- const portName = target?.managed_runtime_port?.trim().toLowerCase();
740
- if (!target || !portName)
741
- return dispatch;
742
- if (!hostLease) {
743
- throw new Error("qa_managed_runtime_unavailable: Browser QA requires the verified managed host runtime selected during readiness.");
744
- }
745
- const normalizedName = portName.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
746
- const url = hostLease.environment[`FORGE_${normalizedName}_URL`];
747
- if (!url) {
748
- throw new Error(`qa_managed_runtime_unavailable: verified runtime port '${portName}' was not launched for this attempt.`);
749
- }
750
- return {
751
- ...dispatch,
752
- qaBrowser: dispatch.qaBrowser ? {
753
- ...dispatch.qaBrowser,
754
- launchTarget: {
755
- ...target,
756
- url: target.url ?? url,
757
- ready_url: target.ready_url ?? url,
758
- notes: [target.notes, "Forge launched and verified this URL inside the current fenced attempt."]
759
- .filter(Boolean)
760
- .join(" "),
761
- },
762
- } : dispatch.qaBrowser,
763
- };
764
- }
765
657
  function probeFailureCode(error) {
766
658
  const message = error instanceof Error ? error.message : String(error);
767
659
  const candidate = message.split(":", 1)[0]?.trim().toLowerCase() ?? "";
@@ -776,6 +668,13 @@ function throwIfAborted(signal) {
776
668
  throw new Error(String(signal.reason ?? "Dispatch cancelled."));
777
669
  }
778
670
  }
671
+ /** The dispatch attempt a worktree is prepared for: Forge's attempt for its WIP refs, and whose host load it reserves. */
672
+ function preparedAttemptOwner(dispatch) {
673
+ return {
674
+ wipAttempt: dispatch.wipAttempt ?? null,
675
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: runtimeAdmissionPriority(dispatch) },
676
+ };
677
+ }
779
678
  function validateApiKeySecretGrant(dispatch) {
780
679
  if (!dispatch.execution.requiresApiKeySecretGrant) {
781
680
  return;
@@ -1,4 +1,6 @@
1
1
  import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
2
+ import { type DispatchPrReviewContext } from "./session.types.pr-review.js";
3
+ export type { DispatchPrReviewContext, DispatchPrReviewPriorReview, DispatchPrReviewThread, DispatchPrReviewThreadComment } from "./session.types.pr-review.js";
2
4
  export interface RunOnceDispatchPacket {
3
5
  readonly schemaVersion: 1 | 2;
4
6
  readonly userId: string;
@@ -11,7 +13,10 @@ export interface RunOnceDispatchPacket {
11
13
  readonly runtimeIntent: DispatchRuntimeIntent;
12
14
  readonly serverLocal: DispatchServerLocalConfig;
13
15
  readonly sandbox?: DispatchSandboxContext | null;
16
+ readonly wipAttempt?: number | null;
14
17
  readonly pullRequest?: DispatchPullRequestContext | null;
18
+ /** Review-only context for the pr_review lane: the head to review and the Story spec text. */
19
+ readonly prReview?: DispatchPrReviewContext | null;
15
20
  readonly apiKeySecretGrant?: ApiKeySecretGrant | null;
16
21
  readonly apiKeySecretGrantHandle?: ApiKeySecretGrantHandle | null;
17
22
  readonly artifacts: readonly DispatchResolvedArtifact[];
@@ -1,5 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { redactText } from "../shared/redaction/redaction.js";
3
+ import { asObject, requiredString, optionalString, requiredBoolean, optionalBoolean, optionalPositiveInteger, optionalNonNegativeInteger, requiredNumber, boundedInteger } from "./session.parse-helpers.js";
4
+ import { parsePrReview } from "./session.types.pr-review.js";
3
5
  export class ForgeFailureError extends Error {
4
6
  failureCode;
5
7
  failureSource;
@@ -28,7 +30,9 @@ export function parseRunOnceDispatchPacket(value) {
28
30
  runtimeIntent: parseRuntimeIntent(packet.runtimeIntent),
29
31
  serverLocal: parseServerLocal(packet.serverLocal),
30
32
  sandbox: parseSandbox(packet.sandbox, schemaVersion),
33
+ wipAttempt: optionalNonNegativeInteger(packet, "wipAttempt"),
31
34
  pullRequest: parsePullRequest(packet.pullRequest),
35
+ prReview: parsePrReview(packet.prReview),
32
36
  apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant),
33
37
  apiKeySecretGrantHandle: parseApiKeySecretGrantHandle(packet.apiKeySecretGrantHandle),
34
38
  artifacts: parseArtifacts(packet.artifacts),
@@ -538,6 +542,9 @@ function unvalidatedFailureFactsForCode(code, source) {
538
542
  if (stableFailureFamilyCodes.has(code) && (code.startsWith("teardown") || code.startsWith("reaper"))) {
539
543
  return facts(code, "transport", "teardown", source, "retryable", "retry_with_policy");
540
544
  }
545
+ if (["pr_review.unsandboxed_host", "pr_review.sandbox_unavailable"].includes(code)) {
546
+ return facts(code, "domain", "offer", source, "non_retryable", "fix_environment");
547
+ }
541
548
  if (["invalid_dispatch"].includes(code)) {
542
549
  return facts(code, "domain", "offer", source, "non_retryable", "fix_input");
543
550
  }
@@ -551,10 +558,7 @@ function unvalidatedFailureFactsForCode(code, source) {
551
558
  ].includes(code)) {
552
559
  return facts(code, "domain", "prepare", source, "non_retryable", "reauthenticate");
553
560
  }
554
- if (code === "sandbox_idle_timeout") {
555
- return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
556
- }
557
- if (code === "sandbox_wall_timeout") {
561
+ if (["sandbox_idle_timeout", "sandbox_wall_timeout"].includes(code)) {
558
562
  return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
559
563
  }
560
564
  if (["sandbox_oom_killed", "sandbox_pid_exhausted", "sandbox_file_descriptor_exhausted", "sandbox_storage_exhausted"].includes(code)) {
@@ -1321,77 +1325,3 @@ function parsePriorPhaseArtifacts(value) {
1321
1325
  };
1322
1326
  });
1323
1327
  }
1324
- function asObject(value, label) {
1325
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1326
- throw new Error(`${label} must be an object.`);
1327
- }
1328
- return value;
1329
- }
1330
- function requiredString(source, key) {
1331
- const value = source[key];
1332
- if (typeof value !== "string" || value.trim().length === 0) {
1333
- throw new Error(`${key} must be a non-empty string.`);
1334
- }
1335
- return value;
1336
- }
1337
- function optionalString(source, key) {
1338
- const value = source[key];
1339
- if (value === undefined || value === null) {
1340
- return null;
1341
- }
1342
- if (typeof value !== "string") {
1343
- throw new Error(`${key} must be a string when provided.`);
1344
- }
1345
- return value;
1346
- }
1347
- function requiredBoolean(source, key) {
1348
- const value = source[key];
1349
- if (typeof value !== "boolean") {
1350
- throw new Error(`${key} must be a boolean.`);
1351
- }
1352
- return value;
1353
- }
1354
- function optionalBoolean(source, key) {
1355
- const value = source[key];
1356
- if (value === undefined || value === null) {
1357
- return null;
1358
- }
1359
- if (typeof value !== "boolean") {
1360
- throw new Error(`${key} must be a boolean when provided.`);
1361
- }
1362
- return value;
1363
- }
1364
- function optionalPositiveInteger(source, key) {
1365
- const value = source[key];
1366
- if (value === undefined || value === null) {
1367
- return null;
1368
- }
1369
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
1370
- throw new Error(`${key} must be a positive integer when provided.`);
1371
- }
1372
- return value;
1373
- }
1374
- function optionalNonNegativeInteger(source, key) {
1375
- const value = source[key];
1376
- if (value === undefined || value === null) {
1377
- return null;
1378
- }
1379
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1380
- throw new Error(`${key} must be a non-negative integer when provided.`);
1381
- }
1382
- return value;
1383
- }
1384
- function requiredNumber(source, key) {
1385
- const value = source[key];
1386
- if (typeof value !== "number" || !Number.isFinite(value)) {
1387
- throw new Error(`${key} must be a finite number.`);
1388
- }
1389
- return value;
1390
- }
1391
- function boundedInteger(source, key, minimum, maximum) {
1392
- const value = requiredNumber(source, key);
1393
- if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1394
- throw new Error(`${key} must be an integer from ${minimum} through ${maximum}.`);
1395
- }
1396
- return value;
1397
- }