@loucompanion/forge-bridge 0.2.1-dev.573a8a5fa582 → 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 (121) hide show
  1. package/README.md +38 -2
  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 +62 -92
  6. package/dist/bridge/bridge.types.d.ts +6 -0
  7. package/dist/bridge/default-session-service.d.ts +13 -0
  8. package/dist/bridge/default-session-service.js +22 -0
  9. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  10. package/dist/bridge/dispatch-offer-policy.js +58 -0
  11. package/dist/cleanup/cleanup-wip.js +3 -3
  12. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  13. package/dist/cleanup/forge-owned-paths.js +9 -0
  14. package/dist/cli/cli.help.js +1 -1
  15. package/dist/cli/cli.service.js +3 -3
  16. package/dist/cli/local-config.d.ts +2 -0
  17. package/dist/cli/local-config.js +3 -0
  18. package/dist/runtime/host-load-capacity.d.ts +198 -0
  19. package/dist/runtime/host-load-capacity.js +353 -0
  20. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  21. package/dist/runtime/host-load-child-environment.js +35 -1
  22. package/dist/runtime/host-load-governor-config.d.ts +23 -2
  23. package/dist/runtime/host-load-governor-config.js +20 -2
  24. package/dist/runtime/host-load-governor.d.ts +81 -1
  25. package/dist/runtime/host-load-governor.js +184 -15
  26. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  27. package/dist/runtime/host-load-live-test-slots.js +193 -0
  28. package/dist/runtime/host-load-sampler.d.ts +17 -0
  29. package/dist/runtime/host-load-sampler.js +24 -0
  30. package/dist/runtime/host-load-step-run.d.ts +37 -3
  31. package/dist/runtime/host-load-step-run.js +63 -7
  32. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  33. package/dist/runtime/host-load-test-slot.js +19 -7
  34. package/dist/sandbox/runtime.d.ts +1 -2
  35. package/dist/sandbox/runtime.js +7 -13
  36. package/dist/sandbox/sandbox-input.d.ts +22 -0
  37. package/dist/sandbox/sandbox-input.js +49 -0
  38. package/dist/sandbox/workspace.service.js +15 -2
  39. package/dist/session/managed-attempt-tools.js +6 -29
  40. package/dist/session/managed-build-receipt.d.ts +3 -1
  41. package/dist/session/managed-build-receipt.js +5 -2
  42. package/dist/session/managed-command-environment.d.ts +8 -0
  43. package/dist/session/managed-command-environment.js +28 -0
  44. package/dist/session/managed-command-host-load.d.ts +10 -5
  45. package/dist/session/managed-command-host-load.js +18 -14
  46. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  47. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  48. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  49. package/dist/session/phase-completion.artifacts.js +63 -165
  50. package/dist/session/phase-completion.d.ts +25 -2
  51. package/dist/session/phase-completion.helpers.js +5 -53
  52. package/dist/session/phase-completion.js +15 -32
  53. package/dist/session/phase-completion.mcp-args.js +69 -2
  54. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  55. package/dist/session/phase-completion.phase-aliases.js +43 -0
  56. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  57. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  58. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  59. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  60. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  61. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  62. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  63. package/dist/session/phase-completion.pr-review.js +294 -0
  64. package/dist/session/phase-completion.prompts.d.ts +1 -1
  65. package/dist/session/phase-completion.prompts.js +14 -0
  66. package/dist/session/phase-completion.runtime.js +9 -3
  67. package/dist/session/phase-completion.schemas.js +12 -2
  68. package/dist/session/phase-completion.validation.d.ts +1 -0
  69. package/dist/session/phase-completion.validation.js +9 -1
  70. package/dist/session/pr-review-diff-base.d.ts +18 -0
  71. package/dist/session/pr-review-diff-base.js +45 -0
  72. package/dist/session/pr-review-placement.d.ts +50 -0
  73. package/dist/session/pr-review-placement.js +91 -0
  74. package/dist/session/pre-publication-change-set.d.ts +62 -0
  75. package/dist/session/pre-publication-change-set.js +166 -0
  76. package/dist/session/pre-publication-host-load.js +6 -5
  77. package/dist/session/pre-publication-process.js +3 -2
  78. package/dist/session/pre-publication-validation.d.ts +2 -1
  79. package/dist/session/pre-publication-validation.js +31 -36
  80. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  81. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  82. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  83. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  84. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  85. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  86. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  87. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  88. package/dist/session/provider-cli/pre-publication-repair.js +7 -3
  89. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  90. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  91. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  92. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  93. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  94. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -13
  95. package/dist/session/provider-cli/provider-cli.prompts.js +123 -107
  96. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  97. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  98. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  99. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  100. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  101. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  102. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  103. package/dist/session/provider-cli/provider-cli.service.js +24 -139
  104. package/dist/session/sandbox-host-capacity-gate.js +28 -6
  105. package/dist/session/session.parse-helpers.d.ts +10 -0
  106. package/dist/session/session.parse-helpers.js +84 -0
  107. package/dist/session/session.runtime-refresh.d.ts +46 -0
  108. package/dist/session/session.runtime-refresh.js +116 -0
  109. package/dist/session/session.service.d.ts +2 -1
  110. package/dist/session/session.service.js +40 -95
  111. package/dist/session/session.types.d.ts +4 -0
  112. package/dist/session/session.types.js +7 -77
  113. package/dist/session/session.types.pr-review.d.ts +59 -0
  114. package/dist/session/session.types.pr-review.js +53 -0
  115. package/dist/version.d.ts +1 -1
  116. package/dist/version.js +1 -1
  117. package/dist/worktree/artifact-injector.js +24 -0
  118. package/dist/worktree/worktree.service.d.ts +22 -0
  119. package/dist/worktree/worktree.service.js +116 -12
  120. package/dist/worktree/worktree.types.d.ts +7 -0
  121. package/package.json +1 -1
package/README.md CHANGED
@@ -162,8 +162,28 @@ managed commands and dependency installs never wait for it. A waiting step repor
162
162
  (`prepublication_host_capacity_waiting`, `host_runtime_build_waiting_for_host_capacity`, or
163
163
  `host_load_wait_detail` on a managed command's receipt), and its own timeout starts only once it runs.
164
164
  A holder that crashes or stalls keeps the slot only until the host load ledger takes its token back (its
165
- process tree stopped, its lease fenced, or attempt teardown). `FORGE_HOST_LOAD_TEST_SLOTS` sets how many
166
- run at once (default 1; `0` turns the slot off).
165
+ process tree stopped, its lease fenced, or attempt teardown).
166
+
167
+ How many run at once is sized from the host, with nothing to set: `min(floor((CPUs - reserve) / 6),
168
+ floor((memory - reserve) / 4 GiB))`, from 1 to 4, where the reserve kept for the system and the person using
169
+ the machine is a quarter of the CPUs (at least 2) and a quarter of the memory (at least 4 GiB). One heavy step
170
+ is planned at 6 cores and 4 GiB: a Forge .NET suite averages about 1.6 cores with peaks well above, and about
171
+ 2.2 GB for the test host and its PostgreSQL. A 24-CPU, 64 GB host runs 3; an 8-CPU, 16 GB or a 4-CPU, 8 GB host
172
+ runs 1. A bridge under a CPU quota or memory limit (a systemd unit, a container, a pod) is sized within it.
173
+ While the bridge runs, the count drops when other work on the machine needs it (two readings in a
174
+ row, about 10 seconds) and comes back one slot at a time after the host has stayed clear for 2 minutes;
175
+ running steps are never stopped. Each reading is judged with the heavy steps running when it was taken, so
176
+ suites that have since finished are not other work. Without a measured Forge share (Windows, or no
177
+ dedicated cgroup), CPU never lowers the count while a heavy step runs (one build can use every core), and
178
+ each running step is taken to use at least its planned memory. On macOS, whose free-memory figure leaves
179
+ out inactive and purgeable memory, memory readings are not used. The bridge and every completion MCP
180
+ server admit against the lowest count any of them has in force; a lowered count lapses 90 seconds after
181
+ its governor stops reading the host, and is ignored once its process exits. With more than one slot, each step gets
182
+ `FORGE_TEST_MAX_PARALLEL_CLASSES` for its share of the
183
+ machine unless it is already set. The bridge logs the count and how it was chosen at startup (`Host test
184
+ slots: …`), and a waiting step says when the count is lowered and why. `FORGE_HOST_LOAD_TEST_SLOTS` is the
185
+ operator's override (`0` turns the slot off; live adjustment only lowers it), and
186
+ `FORGE_HOST_LOAD_LIVE_SLOTS=off` turns live adjustment off.
167
187
 
168
188
  Yield this machine to foreground work (for example while gaming) from the host itself:
169
189
 
@@ -335,6 +355,22 @@ Before selecting `sandbox_required`, save the full approved 40- or 64-character
335
355
 
336
356
  Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Settings › Runners. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
337
357
 
358
+ ### Forge PR reviews run only in the Docker sandbox
359
+
360
+ A Forge PR review reads code its author controls, so it runs only where the bridge isolates it, and today that means the Docker sandbox. Forge decides where a review runs before it offers it to any runner. It places the review in a runner's Docker sandbox when that sandbox can take it, and gives it no publication grant. The sandbox can take it when the project runs in a sandbox (`sandbox_preferred` or `sandbox_required`, so it has the `.forge/forge.sandbox.yml` contract the container is built from; a `host_allowed` project never ran in one, and most have no contract) and the provider can reach its API from it. Either the project's network policy allows the provider's hosts (`public_allowlist`), or the runner approves open public networking (`forge-bridge sandbox on --allow-open-public`), which a review outside `sandbox_required` then uses. The container gets the dispatched head as a bundle with no remote, no git credential and no GitHub token. The review diffs against the merge base of the pull request's base and head, which is always in that bundle; the bridge resolves it with its own git, fetching the base by SHA when needed. Codex runs a review with `danger-full-access` in the container, as every other Docker lane does, because its own Linux sandbox cannot be relied on inside the hardened container; the container is the boundary. On a host, Codex runs a review `read-only`. The bridge does not set up Claude Code's own OS sandbox. If a bridge cannot build the sandbox for a review it was offered anyway, it refuses with the non-retryable `pr_review.sandbox_unavailable`, and Forge does not offer that head to the same runner again.
361
+
362
+ On a plain host the provider runs as your user, next to your git credential store, your GitHub CLI login and every file in your home directory. The review guardrails still apply: the git and `gh` environment, the tool deny list, and the checks that the worktree, the local refs and the pull request branch on `origin` haven't changed. They are defence in depth, though, not a boundary. A push to another remote, or anything read and sent elsewhere, would go unnoticed. So a bridge refuses a review placed on its host with the non-retryable `pr_review.unsandboxed_host` before any provider starts. Forge does not offer that head to the same runner again.
363
+
364
+ If no runner can take the review in its sandbox and none has opted in (below), Forge doesn't run it. The pull request's Forge review status becomes `unavailable`, the timeline records `pr_review.no_isolated_runner`, and the bounded review wait releases the head the same way it releases any review that can't run.
365
+
366
+ To accept unsandboxed reviews on a machine anyway, set this in its `bridge.json` and restart the bridge:
367
+
368
+ ```json
369
+ { "allowUnsandboxedPrReview": true }
370
+ ```
371
+
372
+ The setting defaults to `false` and has no environment override. With it set, the bridge advertises the `pr_review_unsandboxed_host` facility, and Forge places a review on that host when its Docker sandbox can't take it and the project's policy lets work run on the host. The server's Local Runner has no Docker sandbox: it runs a review only in its container sandbox or when it advertises the same facility, and refuses any other review with `pr_review.unsandboxed_host`, as `forge-bridge run-once` does. Each such review logs a warning, emits a `pr_review_unsandboxed_host_warning` event and notes the warning in its session result. Turn it on only on a machine whose credentials and files you are willing to expose to the code under review, such as a disposable VM or a host with no credentials worth stealing.
373
+
338
374
  The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Settings › Runners before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Settings › Runners also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
339
375
 
340
376
  Every attempt-owned container (including short-lived initialization helpers), network, and volume carries `dev.forge.resource-lease-id` equal to the dispatch execution lease. Ledger schema v2 persists the same `resourceLeaseId`; teardown compares the complete expected label set, and orphan reaping fails closed unless the managed, resource-lease, execution-lease, attempt, runner, runner-instance, and fencing identities are all present and consistent.
@@ -6,6 +6,10 @@
6
6
  export declare function writeJsonFileAtomically(target: string, value: unknown): Promise<void>;
7
7
  /** True when a process with this id exists. EPERM means it exists but belongs to someone else. */
8
8
  export declare function isProcessAlive(pid: number): boolean;
9
- /** Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is open. */
10
- export declare function withFsRetry<T>(operation: () => Promise<T>, attempts?: number): Promise<T>;
9
+ /**
10
+ * Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is
11
+ * open. The backoff is jittered so a writer does not keep landing in lockstep with polling
12
+ * readers, and the budget runs on the monotonic clock so a faked `Date` cannot stretch it.
13
+ */
14
+ export declare function withFsRetry<T>(operation: () => Promise<T>, budgetMs?: number): Promise<T>;
11
15
  export declare function errorCode(error: unknown): string;
@@ -32,16 +32,34 @@ export function isProcessAlive(pid) {
32
32
  return errorCode(error) === "EPERM";
33
33
  }
34
34
  }
35
- /** Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is open. */
36
- export async function withFsRetry(operation, attempts = 8) {
35
+ /**
36
+ * How long an fs call keeps retrying while Windows refuses it. Windows cannot rename over
37
+ * or delete a file that any handle has open, and a reader of a large file holds it open
38
+ * across several chunked reads: on a Windows 11 host, three readers polling a 2 MB state
39
+ * file every few milliseconds kept a rename refused for up to ~0.6 s, past the old ~0.4 s
40
+ * budget. Two seconds rides that out and stays well inside the state file's staleness window.
41
+ */
42
+ const fsRetryBudgetMs = 2_000;
43
+ /** A backstop on top of the time budget. */
44
+ const fsRetryMaxAttempts = 100;
45
+ /**
46
+ * Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is
47
+ * open. The backoff is jittered so a writer does not keep landing in lockstep with polling
48
+ * readers, and the budget runs on the monotonic clock so a faked `Date` cannot stretch it.
49
+ */
50
+ export async function withFsRetry(operation, budgetMs = fsRetryBudgetMs) {
51
+ const deadline = performance.now() + budgetMs;
37
52
  for (let attempt = 1;; attempt += 1) {
38
53
  try {
39
54
  return await operation();
40
55
  }
41
56
  catch (error) {
42
- if (attempt >= attempts || !retryableFsCodes.has(errorCode(error)))
57
+ if (attempt >= fsRetryMaxAttempts || !retryableFsCodes.has(errorCode(error)))
58
+ throw error;
59
+ const delayMs = Math.min(100, 10 * attempt) * (0.5 + Math.random());
60
+ if (performance.now() + delayMs > deadline)
43
61
  throw error;
44
- await new Promise(resolve => setTimeout(resolve, 15 * attempt));
62
+ await new Promise(resolve => setTimeout(resolve, delayMs));
45
63
  }
46
64
  }
47
65
  }
@@ -79,7 +79,11 @@ export declare class ForgeBridgeService implements BridgeService {
79
79
  private hostRequirementFacts;
80
80
  private readonly recoveredHostAttempts;
81
81
  private hostCapabilitiesDetected;
82
+ /** The default session service's host load governor, for the startup capacity log line. */
83
+ private readonly hostLoadGovernor;
82
84
  constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
85
+ /** Once per bridge process: host capabilities, and how many heavy steps this host runs at once, and why. */
86
+ private detectHostCapabilities;
83
87
  connectOnce(): Promise<void>;
84
88
  private rememberRecoveredHostAttempts;
85
89
  private recoveredHostAttemptsForHello;
@@ -165,6 +169,12 @@ export declare class ForgeBridgeService implements BridgeService {
165
169
  private redeemPublishGrant;
166
170
  private handleLeaseUpdate;
167
171
  private sendOfferDecision;
172
+ /**
173
+ * The terminal result for a dispatch this runner refuses before any worktree or provider exists: the host
174
+ * database capability boundary, a missing required facility, or a Forge PR review outside the Docker sandbox
175
+ * without the owner's opt-in. Null when it may run.
176
+ */
177
+ private refusalBeforeRun;
168
178
  private parseDispatchOrReport;
169
179
  private parseChatTurnOrReport;
170
180
  private handleCancel;
@@ -1,4 +1,3 @@
1
- import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
2
1
  import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
3
2
  import fs from "node:fs";
4
3
  import path from "node:path";
@@ -7,14 +6,14 @@ import os from "node:os";
7
6
  import { defaultForgeBridgeConfig } from "../config.js";
8
7
  import { bridgeChatCapabilityFor, defaultSandboxProfiles, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
8
  import { redactText } from "../shared/redaction/redaction.js";
10
- import { BridgeSessionService } from "../session/session.service.js";
11
- import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
9
+ import { formatProviderCliCommandForCheckpoint, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
10
  import { assertChatTurnFinished, buildChatProviderCommand, chatTurnGiphyFramesMethod, lookAtChatGiphyFrames, materializeChatTurnMetadata, } from "./bridge-chat-provider-command.js";
13
11
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
14
12
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
15
- import { PrePublicationValidator } from "../session/pre-publication-validation.js";
13
+ import { describeHostTestSlotCapacity } from "../runtime/host-load-governor.js";
16
14
  import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
17
- import { hostCapacityLimitDefaults, HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
15
+ import { createDefaultSessionService } from "./default-session-service.js";
16
+ import { hostCapacityLimitDefaults, } from "../runtime/host-runtime-lease.js";
18
17
  import { computeEffectiveRunnerSettings, describeRunnerSettings, parseRunnerSettingsDocument, runnerSettingsInForce, runnerYieldingMessage, sameRunnerSettingsReport, } from "../runtime/runner-settings.js";
19
18
  import { resetHostLoadRuntimeSettings, writeHostLoadRuntimeSettings } from "../runtime/host-load-runtime-settings.js";
20
19
  import { readLocalYieldFlag } from "./local-yield-flag.js";
@@ -22,12 +21,7 @@ import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBo
22
21
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
23
22
  import { buildMemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
24
23
  import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
25
- import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
26
- import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
27
24
  import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
28
- import { GitWorktreeService } from "../worktree/worktree.service.js";
29
- import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
30
- import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
31
25
  import { failureFactsForCode, failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
32
26
  import { forgeBridgeVersion } from "../version.js";
33
27
  import { canRunDockerMaintenance, DockerPreflight } from "../sandbox/preflight.js";
@@ -39,6 +33,7 @@ import { HostLoadSampler } from "../runtime/host-load-sampler.js";
39
33
  import { deferredReadinessResult, FileReadinessResultOutbox, readinessDeferralReason, } from "./readiness-result-outbox.js";
40
34
  import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
41
35
  import { BridgeStatePublisher } from "./bridge-state-file.js";
36
+ import { offerPolicyRefusal, prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning, sandboxProfileRefusalCode, unmetHostRuntimeRequirements, } from "./dispatch-offer-policy.js";
42
37
  import { BridgeInFlightRegistry, describeInFlightIds, inFlightIdsFrom, readinessInFlightEntries, reservationInFlightEntries, safeLogLabel, sessionInFlightEntries, } from "./in-flight-registry.js";
43
38
  import { canReserveSandboxResources, defaultSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, sumSandboxResources, zeroSandboxResources, } from "./sandbox-resource-accounting.js";
44
39
  export { canReserveSandboxResources, resolveDynamicSandboxResources, resolveSandboxResourcesFromRepo, sandboxCapacityFailureMessage, sandboxMemoryCommitmentCapacity, };
@@ -129,6 +124,8 @@ export class ForgeBridgeService {
129
124
  // leaves those attempts on Forge's conservative unknown-outcome path.
130
125
  recoveredHostAttempts = new Map();
131
126
  hostCapabilitiesDetected = false;
127
+ /** The default session service's host load governor, for the startup capacity log line. */
128
+ hostLoadGovernor;
132
129
  constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
133
130
  // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
134
131
  hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
@@ -170,6 +167,7 @@ export class ForgeBridgeService {
170
167
  });
171
168
  const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
172
169
  this.sessions = sessions ?? defaultSessions.sessions;
170
+ this.hostLoadGovernor = defaultSessions?.hostLoadGovernor ?? null;
173
171
  // Docker sandboxes ask the same host load governor for their validation tokens.
174
172
  this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
175
173
  this.sandboxResourceResolver = sandboxResourceResolver
@@ -185,6 +183,13 @@ export class ForgeBridgeService {
185
183
  ...readinessInFlightEntries(this.activeReadinessProbes),
186
184
  ]);
187
185
  }
186
+ /** Once per bridge process: host capabilities, and how many heavy steps this host runs at once, and why. */
187
+ async detectHostCapabilities() {
188
+ this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
189
+ this.hostCapabilitiesDetected = true;
190
+ if (this.hostLoadGovernor?.enabled)
191
+ logBridgeStatus(describeHostTestSlotCapacity(this.hostLoadGovernor.testSlotCapacity()));
192
+ }
188
193
  async connectOnce() {
189
194
  if (this.revokedReason !== null) {
190
195
  throw new BridgeRevokedError(this.revokedReason);
@@ -210,10 +215,8 @@ export class ForgeBridgeService {
210
215
  }
211
216
  }
212
217
  await this.dockerEngineProbe.refresh(true);
213
- if (!this.hostCapabilitiesDetected) {
214
- this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
215
- this.hostCapabilitiesDetected = true;
216
- }
218
+ if (!this.hostCapabilitiesDetected)
219
+ await this.detectHostCapabilities();
217
220
  // Static host facts and the first load sample ride on Hello; the sampler
218
221
  // keeps refreshing its cached snapshot for later heartbeats.
219
222
  await this.hostLoad.start().catch(() => undefined);
@@ -886,37 +889,16 @@ export class ForgeBridgeService {
886
889
  this.releaseReservedDispatchHandoff(reservationHandoff);
887
890
  return;
888
891
  }
889
- if (this.enforceHostDatabaseCapabilityBoundary) {
890
- try {
891
- assertHostDatabaseCapabilityBoundary();
892
- }
893
- catch (error) {
894
- const message = errorMessage(error);
895
- await this.sendResult(dispatch, failureResult(message, [{
896
- role: "runner",
897
- kind: "error",
898
- content: message,
899
- eventType: "host_database_capability_forbidden",
900
- }], failureFactsFromError(error, { source: "bridge" }))).catch(() => undefined);
901
- this.releaseReservedDispatchHandoff(reservationHandoff);
902
- return;
903
- }
904
- }
905
- let capabilityFailure;
892
+ let refusal;
906
893
  try {
907
- capabilityFailure = await this.requiredCapabilityFailure(dispatch);
894
+ refusal = await this.refusalBeforeRun(dispatch);
908
895
  }
909
896
  catch (error) {
910
897
  this.releaseReservedDispatchHandoff(reservationHandoff);
911
898
  throw error;
912
899
  }
913
- if (capabilityFailure) {
914
- await this.sendResult(dispatch, failureResult(capabilityFailure, [{
915
- role: "runner",
916
- kind: "error",
917
- content: capabilityFailure,
918
- eventType: "docker_engine_unavailable",
919
- }], failureFactsForCode("docker_engine_unavailable"))).catch(() => undefined);
900
+ if (refusal) {
901
+ await this.sendResult(dispatch, refusal).catch(() => undefined);
920
902
  this.releaseReservedDispatchHandoff(reservationHandoff);
921
903
  return;
922
904
  }
@@ -1046,9 +1028,9 @@ export class ForgeBridgeService {
1046
1028
  this.inFlight.notePhase(dispatch.lease.id, "run_once");
1047
1029
  logBridgeStatus(`Run-once started (${docker ? "Docker sandbox" : "host"}, ${safeLogLabel(dispatch.execution.role)}): ${ids}.`);
1048
1030
  try {
1049
- const result = docker
1050
- ? await this.sandboxRuntime.runOnce(dispatch, sink, signal)
1051
- : await this.sessions.runOnce(dispatch, sink, signal);
1031
+ const result = await runWithUnsandboxedReviewWarning(dispatch, this.config.allowUnsandboxedPrReview, sink, (warning) => logBridgeStatus(`${warning} ${ids}.`), () => docker
1032
+ ? this.sandboxRuntime.runOnce(dispatch, sink, signal)
1033
+ : this.sessions.runOnce(dispatch, sink, signal));
1052
1034
  if (docker) {
1053
1035
  await this.flushCleanupReports().catch(() => undefined);
1054
1036
  }
@@ -1165,21 +1147,11 @@ export class ForgeBridgeService {
1165
1147
  await this.sendOfferDecision(dispatch, false, preflight?.unavailableCode ?? "docker_unavailable", preflight?.unavailableReason ?? "Docker sandbox preflight is unavailable.");
1166
1148
  return;
1167
1149
  }
1168
- const networkFailure = sandboxNetworkPolicyFailure(dispatch, this.config);
1169
- if (networkFailure) {
1170
- await this.sendOfferDecision(dispatch, false, "policy_mismatch", networkFailure);
1171
- return;
1172
- }
1173
- const providerNetworkFailure = sandboxProviderNetworkFailure(dispatch, this.config);
1174
- if (providerNetworkFailure) {
1175
- await this.sendOfferDecision(dispatch, false, "provider_network_policy_denied", providerNetworkFailure);
1176
- return;
1177
- }
1178
- const authFailure = sandboxAuthFailure(dispatch, this.config);
1179
- if (authFailure) {
1180
- await this.sendOfferDecision(dispatch, false, "sandbox_auth_unavailable", authFailure);
1181
- return;
1182
- }
1150
+ }
1151
+ const policyRefusal = offerPolicyRefusal(dispatch, this.config, () => sandboxAuthFailure(dispatch, this.config));
1152
+ if (policyRefusal) {
1153
+ await this.sendOfferDecision(dispatch, false, policyRefusal.code, policyRefusal.message);
1154
+ return;
1183
1155
  }
1184
1156
  let requestedResources = sandbox.requestedResources;
1185
1157
  let sandboxConfigCommitSha = sandbox.sandboxConfigCommitSha ?? null;
@@ -1191,7 +1163,7 @@ export class ForgeBridgeService {
1191
1163
  sandboxConfigCommitSha = profile.sandboxConfigCommitSha;
1192
1164
  }
1193
1165
  catch (error) {
1194
- await this.sendOfferDecision(dispatch, false, "sandbox_capacity_profile_unavailable", error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1166
+ await this.sendOfferDecision(dispatch, false, sandboxProfileRefusalCode(dispatch), error instanceof Error ? error.message : "The immutable sandbox contract could not be profiled for admission.");
1195
1167
  return;
1196
1168
  }
1197
1169
  }
@@ -1425,6 +1397,37 @@ export class ForgeBridgeService {
1425
1397
  logBridgeStatus(`Offer accepted: ${describeInFlightIds(inFlightIdsFrom(dispatch))}; reserved until ${payload.reservedUntil}.`);
1426
1398
  await this.invokeAck("OfferDecision", payload);
1427
1399
  }
1400
+ /**
1401
+ * The terminal result for a dispatch this runner refuses before any worktree or provider exists: the host
1402
+ * database capability boundary, a missing required facility, or a Forge PR review outside the Docker sandbox
1403
+ * without the owner's opt-in. Null when it may run.
1404
+ */
1405
+ async refusalBeforeRun(dispatch) {
1406
+ if (this.enforceHostDatabaseCapabilityBoundary) {
1407
+ try {
1408
+ assertHostDatabaseCapabilityBoundary();
1409
+ }
1410
+ catch (error) {
1411
+ const message = errorMessage(error);
1412
+ return failureResult(message, [{
1413
+ role: "runner",
1414
+ kind: "error",
1415
+ content: message,
1416
+ eventType: "host_database_capability_forbidden",
1417
+ }], failureFactsFromError(error, { source: "bridge" }));
1418
+ }
1419
+ }
1420
+ const capabilityFailure = await this.requiredCapabilityFailure(dispatch);
1421
+ if (capabilityFailure) {
1422
+ return failureResult(capabilityFailure, [{
1423
+ role: "runner",
1424
+ kind: "error",
1425
+ content: capabilityFailure,
1426
+ eventType: "docker_engine_unavailable",
1427
+ }], failureFactsForCode("docker_engine_unavailable"));
1428
+ }
1429
+ return prReviewPlacementRefusalResult(dispatch, this.config.allowUnsandboxedPrReview);
1430
+ }
1428
1431
  async parseDispatchOrReport(rawDispatch) {
1429
1432
  try {
1430
1433
  return parseRunOnceDispatchPacket(rawDispatch);
@@ -2046,7 +2049,7 @@ export class ForgeBridgeService {
2046
2049
  sandboxProfiles: this.config.sandboxProfiles,
2047
2050
  runnerInstanceId: this.config.runnerInstanceId,
2048
2051
  trustDomainId: this.config.trustDomainId,
2049
- executionFacilities: dockerEngine?.available ? ["docker_engine"] : [],
2052
+ executionFacilities: [...(dockerEngine?.available ? ["docker_engine"] : []), ...prReviewExecutionFacilities(this.config.allowUnsandboxedPrReview)],
2050
2053
  dockerEngine,
2051
2054
  toolchains: {
2052
2055
  ...this.hostCapabilities.toolchains,
@@ -2299,14 +2302,6 @@ function isProviderStorageUnavailable(error) {
2299
2302
  function isBridgeCallbackTimeout(error) {
2300
2303
  return errorMessage(error).startsWith("bridge_callback_timeout:");
2301
2304
  }
2302
- function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
2303
- const rawProcessRunner = new StreamingProviderProcessRunner();
2304
- const processSupervisors = new AttemptProcessSupervisorRegistry();
2305
- const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
2306
- const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
2307
- const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
2308
- return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
2309
- }
2310
2305
  export class SignalRBridgeConnectionFactory {
2311
2306
  create(config) {
2312
2307
  return new SignalRBridgeConnection(config);
@@ -2871,21 +2866,6 @@ function containsIgnoreCase(values, value) {
2871
2866
  export function canReapManagedSandboxes(preflight) {
2872
2867
  return canRunDockerMaintenance(preflight);
2873
2868
  }
2874
- function sandboxNetworkPolicyFailure(dispatch, config) {
2875
- const sandbox = dispatch.sandbox;
2876
- if (!sandbox)
2877
- return "Protocol-v2 sandbox context is missing.";
2878
- if (sandbox.networkPolicy.mode === "open_public"
2879
- && (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
2880
- return "open_public sandbox networking is not permitted by this runner policy.";
2881
- }
2882
- if (sandbox.networkPolicy.mode === "public_allowlist"
2883
- && sandbox.networkPolicy.allowedHosts.length > 0
2884
- && process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
2885
- return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
2886
- }
2887
- return null;
2888
- }
2889
2869
  export function dockerEngineRequirementFailure(requiredCapabilities, executionMode, capability) {
2890
2870
  if (!requiredCapabilities.includes("docker_engine"))
2891
2871
  return null;
@@ -2922,16 +2902,6 @@ function parseReadinessProbe(value) {
2922
2902
  }
2923
2903
  return request;
2924
2904
  }
2925
- function sandboxProviderNetworkFailure(dispatch, config) {
2926
- const sandbox = dispatch.sandbox;
2927
- if (!sandbox || sandbox.networkPolicy.mode !== "offline")
2928
- return null;
2929
- const provider = dispatch.execution.provider.trim().toLowerCase();
2930
- const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
2931
- if (!isNetworkProvider)
2932
- return null;
2933
- return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
2934
- }
2935
2905
  function sandboxAuthFailure(dispatch, config) {
2936
2906
  const unsupported = sandboxProviderAuthUnavailableMessage(dispatch.execution.provider, dispatch.execution.authKind);
2937
2907
  if (unsupported) {
@@ -23,6 +23,12 @@ export interface BridgeServiceConfig {
23
23
  readonly sandboxPidCapacity: number;
24
24
  readonly dockerEnabled: boolean;
25
25
  readonly allowOpenPublicSandbox: boolean;
26
+ /**
27
+ * The runner owner accepts Forge PR reviews placed on this host, outside the Docker sandbox, where the
28
+ * provider reads author-controlled code with this user's credentials in reach. Default false: such a
29
+ * review is refused (pr-review-placement.ts).
30
+ */
31
+ readonly allowUnsandboxedPrReview?: boolean;
26
32
  readonly sandboxPublicationMode?: "bridge_push" | "shared_filesystem";
27
33
  readonly dockerExecutable: string;
28
34
  readonly dockerContext: string;
@@ -0,0 +1,13 @@
1
+ import type { SessionService } from "../session/session.base.js";
2
+ import type { HostLoadGovernor } from "../runtime/host-load-governor.js";
3
+ import type { HostLoadSource } from "../runtime/host-load-sampler.js";
4
+ import type { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
5
+ /**
6
+ * The session service a bridge builds when none is injected, wired to one host load governor
7
+ * (the host runtime's): worktree builds, pre-publication validation and host runtimes all ask
8
+ * it for capacity. The governor is returned too, for the bridge's startup capacity log line.
9
+ */
10
+ export declare function createDefaultSessionService(sandboxStateRoot: string, sandboxExecutionRoot: string, dockerEngineProbe: DockerEngineProbe, hostLoad: HostLoadSource): {
11
+ readonly sessions: SessionService;
12
+ readonly hostLoadGovernor: HostLoadGovernor;
13
+ };
@@ -0,0 +1,22 @@
1
+ import { BridgeSessionService } from "../session/session.service.js";
2
+ import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
3
+ import { PrePublicationValidator } from "../session/pre-publication-validation.js";
4
+ import { HostRuntimeLeaseManager } from "../runtime/host-runtime-lease.js";
5
+ import { createNativeTestClusterDatabaseBroker } from "../runtime/attempt-database-broker.js";
6
+ import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
7
+ import { GitWorktreeService } from "../worktree/worktree.service.js";
8
+ import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
9
+ import { AttemptCoordinatedProviderProcessRunner, AttemptProcessSupervisorRegistry, } from "../runtime/attempt-process-supervisor-registry.js";
10
+ /**
11
+ * The session service a bridge builds when none is injected, wired to one host load governor
12
+ * (the host runtime's): worktree builds, pre-publication validation and host runtimes all ask
13
+ * it for capacity. The governor is returned too, for the bridge's startup capacity log line.
14
+ */
15
+ export function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
16
+ const rawProcessRunner = new StreamingProviderProcessRunner();
17
+ const processSupervisors = new AttemptProcessSupervisorRegistry();
18
+ const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
19
+ const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
20
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
21
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
22
+ }
@@ -0,0 +1,22 @@
1
+ export { unmetHostRuntimeRequirements, type HostRequirementFacts } from "../runtime/host-runtime-requirements-check.js";
2
+ export { prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning } from "../session/pr-review-placement.js";
3
+ import type { RunOnceDispatchPacket } from "../session/session.types.js";
4
+ import type { BridgeServiceConfig } from "./bridge.types.js";
5
+ export interface OfferRefusal {
6
+ readonly code: string;
7
+ readonly message: string;
8
+ }
9
+ /**
10
+ * Why this runner refuses an offer on policy, after its Docker preflight passed: a Forge PR review placed
11
+ * outside the Docker sandbox without the owner's opt-in, then, for a Docker offer, its network policy, the
12
+ * provider's need for a network, and the provider's auth (`authFailure`). Null when it may take the offer.
13
+ */
14
+ export declare function offerPolicyRefusal(dispatch: RunOnceDispatchPacket, config: BridgeServiceConfig, authFailure: () => string | null): OfferRefusal | null;
15
+ /**
16
+ * The code a Docker offer is refused with when its sandbox contract cannot be profiled: a capacity wait for
17
+ * ordinary work, but for a Forge PR review the non-retryable refusal Forge remembers for this runner and head.
18
+ */
19
+ export declare function sandboxProfileRefusalCode(dispatch: RunOnceDispatchPacket): string;
20
+ /** Why this runner refuses a Docker offer under its network policy, or null. */
21
+ export declare function sandboxNetworkPolicyFailure(dispatch: RunOnceDispatchPacket, config: BridgeServiceConfig): string | null;
22
+ export declare function sandboxProviderNetworkFailure(dispatch: RunOnceDispatchPacket, config: BridgeServiceConfig): string | null;
@@ -0,0 +1,58 @@
1
+ // What a runner checks before it takes a dispatch: the host runtime requirements, a Docker offer's network
2
+ // policy, and where a Forge PR review may run (pr-review-placement.ts).
3
+ export { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
4
+ export { prReviewExecutionFacilities, prReviewPlacementRefusalResult, runWithUnsandboxedReviewWarning } from "../session/pr-review-placement.js";
5
+ import { isPrReviewDispatch, prReviewPlacementRefusalResult, prReviewSandboxUnavailableCode } from "../session/pr-review-placement.js";
6
+ /**
7
+ * Why this runner refuses an offer on policy, after its Docker preflight passed: a Forge PR review placed
8
+ * outside the Docker sandbox without the owner's opt-in, then, for a Docker offer, its network policy, the
9
+ * provider's need for a network, and the provider's auth (`authFailure`). Null when it may take the offer.
10
+ */
11
+ export function offerPolicyRefusal(dispatch, config, authFailure) {
12
+ const review = prReviewPlacementRefusalResult(dispatch, config.allowUnsandboxedPrReview)?.failure;
13
+ if (review)
14
+ return { code: review.code, message: review.message };
15
+ if (dispatch.sandbox?.executionMode !== "docker")
16
+ return null;
17
+ const network = sandboxNetworkPolicyFailure(dispatch, config);
18
+ if (network)
19
+ return { code: "policy_mismatch", message: network };
20
+ const providerNetwork = sandboxProviderNetworkFailure(dispatch, config);
21
+ if (providerNetwork)
22
+ return { code: "provider_network_policy_denied", message: providerNetwork };
23
+ const auth = authFailure();
24
+ return auth ? { code: "sandbox_auth_unavailable", message: auth } : null;
25
+ }
26
+ /**
27
+ * The code a Docker offer is refused with when its sandbox contract cannot be profiled: a capacity wait for
28
+ * ordinary work, but for a Forge PR review the non-retryable refusal Forge remembers for this runner and head.
29
+ */
30
+ export function sandboxProfileRefusalCode(dispatch) {
31
+ return isPrReviewDispatch(dispatch) ? prReviewSandboxUnavailableCode : "sandbox_capacity_profile_unavailable";
32
+ }
33
+ /** Why this runner refuses a Docker offer under its network policy, or null. */
34
+ export function sandboxNetworkPolicyFailure(dispatch, config) {
35
+ const sandbox = dispatch.sandbox;
36
+ if (!sandbox)
37
+ return "Protocol-v2 sandbox context is missing.";
38
+ if (sandbox.networkPolicy.mode === "open_public"
39
+ && (sandbox.executionPolicy === "sandbox_required" || !config.allowOpenPublicSandbox)) {
40
+ return "open_public sandbox networking is not permitted by this runner policy.";
41
+ }
42
+ if (sandbox.networkPolicy.mode === "public_allowlist"
43
+ && sandbox.networkPolicy.allowedHosts.length > 0
44
+ && process.env.FORGE_SANDBOX_EGRESS_ENFORCED !== "true") {
45
+ return "public_allowlist requires an operator-enforced Forge egress proxy or firewall.";
46
+ }
47
+ return null;
48
+ }
49
+ export function sandboxProviderNetworkFailure(dispatch, config) {
50
+ const sandbox = dispatch.sandbox;
51
+ if (!sandbox || sandbox.networkPolicy.mode !== "offline")
52
+ return null;
53
+ const provider = dispatch.execution.provider.trim().toLowerCase();
54
+ const isNetworkProvider = config.cliProviders.some(candidate => candidate.trim().toLowerCase() === provider);
55
+ if (!isNetworkProvider)
56
+ return null;
57
+ return `Provider ${dispatch.execution.provider} requires outbound network access, but this Docker attempt uses the offline network policy.`;
58
+ }
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { preserveWorktreeWip } from "../worktree/wip-snapshot.js";
3
- import { isRuntimeReadinessName } from "./forge-owned-paths.js";
3
+ import { isPrReviewWorktreeKey, isRuntimeReadinessName } from "./forge-owned-paths.js";
4
4
  import { isForgeManagedWorkBranch } from "./managed-branch-sweep.js";
5
5
  // Cleanup removes stale Forge worktrees: folders whose Git registration is gone (or prunable) and
6
6
  // that no lease owns. Such a folder can still hold a session's uncommitted work (the #558 loss:
@@ -10,8 +10,8 @@ const releaseSuffix = /\.forge-release-[0-9a-f-]{36}$/u;
10
10
  /** Saves a stale candidate's uncommitted work. Never throws: a failure means "keep the folder". */
11
11
  export async function saveStaleWorktreeWork(git, repoPath, worktreeRoot, candidate) {
12
12
  const branchName = candidateBranch(worktreeRoot, candidate);
13
- // A readiness probe never runs an agent: there is no work of anyone's in it.
14
- if (isRuntimeReadinessName(branchName))
13
+ // A readiness probe never runs an agent, and a review only reads: there is no work of anyone's in either.
14
+ if (isRuntimeReadinessName(branchName) || isPrReviewWorktreeKey(branchName))
15
15
  return { status: "exempt" };
16
16
  try {
17
17
  const result = await snapshotCandidate(git, repoPath, candidate, branchName);
@@ -6,4 +6,6 @@ export declare function isForgeOwnedWorktreePath(relativePath: string, separator
6
6
  export declare function isForgeWorktreeContainer(relativePath: string, separator?: PathSeparator): boolean;
7
7
  /** True for a readiness probe's exact folder or branch name: runtime-readiness-<UUID>. */
8
8
  export declare function isRuntimeReadinessName(name: string): boolean;
9
+ /** True for a Forge PR review's worktree key, pr-review/<12 hex>-<12 hex>: nothing in it is anyone's work. */
10
+ export declare function isPrReviewWorktreeKey(name: string): boolean;
9
11
  export {};
@@ -4,6 +4,8 @@
4
4
  // <kind>/<12 hex> a work item (story, task, bug, feature, work_order) or
5
5
  // its Architect phase (architect)
6
6
  // decompose/<feature|work_order>/<12 hex> a decompose session
7
+ // pr-review/<12 hex>-<12 hex> a Forge PR review of one head (work item, head SHA); it is
8
+ // detached and review-only, so it holds nothing to save
7
9
  // runtime-readiness-<UUID> a runtime readiness probe (session.service.ts)
8
10
  // draft-<32 hex> a drafting session (DraftingService on the server)
9
11
  // A release that couldn't finish deleting can leave `<one of those>.forge-release-<UUID>` beside it.
@@ -16,10 +18,12 @@ const releaseSuffix = `(?:\\.forge-release-${uuid})?`;
16
18
  const forgeOwnedWorktreePathPattern = new RegExp("^(?:"
17
19
  + `(?:story|task|bug|feature|work_order|architect)/${hex12}`
18
20
  + `|decompose/(?:feature|work_order)/${hex12}`
21
+ + `|pr-review/${hex12}-${hex12}`
19
22
  + `|runtime-readiness-${uuid}`
20
23
  + "|draft-[0-9a-f]{32}"
21
24
  + `)${releaseSuffix}$`);
22
25
  const runtimeReadinessNamePattern = new RegExp(`^runtime-readiness-${uuid}$`);
26
+ const prReviewWorktreeKeyPattern = new RegExp(`^pr-review/${hex12}-${hex12}$`);
23
27
  // Folders that only group Forge's worktrees; cleanup may look inside them but never removes them.
24
28
  const forgeWorktreeContainers = new Set([
25
29
  "story",
@@ -31,6 +35,7 @@ const forgeWorktreeContainers = new Set([
31
35
  "decompose",
32
36
  "decompose/feature",
33
37
  "decompose/work_order",
38
+ "pr-review",
34
39
  ]);
35
40
  // Split only on the separators the filesystem itself uses. On POSIX a backslash is an ordinary
36
41
  // filename character, so a folder a person named `story\0123456789ab` must not read as Forge's
@@ -51,3 +56,7 @@ export function isForgeWorktreeContainer(relativePath, separator = path.sep) {
51
56
  export function isRuntimeReadinessName(name) {
52
57
  return runtimeReadinessNamePattern.test(name);
53
58
  }
59
+ /** True for a Forge PR review's worktree key, pr-review/<12 hex>-<12 hex>: nothing in it is anyone's work. */
60
+ export function isPrReviewWorktreeKey(name) {
61
+ return prReviewWorktreeKeyPattern.test(name);
62
+ }