@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
@@ -76,6 +76,17 @@ export interface HostCpuAttribution {
76
76
  /** The governor's view: the load sample plus the CPU attribution from the same window. */
77
77
  export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
78
78
  cpuAttribution?(): HostCpuAttribution | null;
79
+ /**
80
+ * The CPU attribution of each sample in recent(), oldest first, matched by sampledAt. It
81
+ * counts the Docker sandbox cgroups as Forge's own, which the snapshots' ownCgroup does not.
82
+ */
83
+ recentCpuAttributions?(): readonly HostCpuAttribution[];
84
+ /**
85
+ * When a sample in recent() was taken on the sampler's monotonic clock (ms), matched by
86
+ * sampledAt; null for one it does not know. Readings are ordered and timed by it, so a
87
+ * wall-clock step (NTP, resume) cannot reorder them.
88
+ */
89
+ sampleMonotonicMs?(sampledAt: string): number | null;
79
90
  /**
80
91
  * Free memory under the tightest cgroup `memory.max` on the bridge's path
81
92
  * (null when none is set), from the latest sample. The governor budgets
@@ -115,6 +126,10 @@ export declare class HostLoadSampler implements HostLoadSource {
115
126
  private hostFacts;
116
127
  private latest;
117
128
  private readonly history;
129
+ private readonly attributionHistory;
130
+ /** Each kept sample's monotonic time, by sampledAt (insertion order is sample order). */
131
+ private readonly monotonicStamps;
132
+ private readMonotonicMs;
118
133
  private cpuMark;
119
134
  private hostCpuMark;
120
135
  private latestCpuAttribution;
@@ -129,6 +144,8 @@ export declare class HostLoadSampler implements HostLoadSource {
129
144
  cpuAttribution(): HostCpuAttribution | null;
130
145
  cgroupMemoryHeadroomBytes(): number | null;
131
146
  recent(): readonly HostLoadSnapshot[];
147
+ recentCpuAttributions(): readonly HostCpuAttribution[];
148
+ sampleMonotonicMs(sampledAt: string): number | null;
132
149
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
133
150
  start(): Promise<void>;
134
151
  stop(): void;
@@ -25,6 +25,10 @@ export class HostLoadSampler {
25
25
  hostFacts = null;
26
26
  latest = null;
27
27
  history = [];
28
+ attributionHistory = [];
29
+ /** Each kept sample's monotonic time, by sampledAt (insertion order is sample order). */
30
+ monotonicStamps = new Map();
31
+ readMonotonicMs = 0;
28
32
  cpuMark = null;
29
33
  hostCpuMark = null;
30
34
  latestCpuAttribution = null;
@@ -61,6 +65,12 @@ export class HostLoadSampler {
61
65
  recent() {
62
66
  return [...this.history];
63
67
  }
68
+ recentCpuAttributions() {
69
+ return [...this.attributionHistory];
70
+ }
71
+ sampleMonotonicMs(sampledAt) {
72
+ return this.monotonicStamps.get(sampledAt) ?? null;
73
+ }
64
74
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
65
75
  start() {
66
76
  if (this.timer)
@@ -88,6 +98,19 @@ export class HostLoadSampler {
88
98
  this.history.push(snapshot);
89
99
  if (this.history.length > retainedSampleCount)
90
100
  this.history.splice(0, this.history.length - retainedSampleCount);
101
+ this.monotonicStamps.set(snapshot.sampledAt, this.readMonotonicMs);
102
+ for (const stamp of this.monotonicStamps.keys()) {
103
+ if (this.monotonicStamps.size <= retainedSampleCount)
104
+ break;
105
+ this.monotonicStamps.delete(stamp);
106
+ }
107
+ const attribution = this.latestCpuAttribution;
108
+ if (attribution?.sampledAt === snapshot.sampledAt) {
109
+ this.attributionHistory.push(attribution);
110
+ if (this.attributionHistory.length > retainedSampleCount) {
111
+ this.attributionHistory.splice(0, this.attributionHistory.length - retainedSampleCount);
112
+ }
113
+ }
91
114
  return snapshot;
92
115
  })
93
116
  .finally(() => {
@@ -111,6 +134,7 @@ export class HostLoadSampler {
111
134
  async readSnapshot() {
112
135
  const sampledAtMs = this.now();
113
136
  const monotonicMs = this.monotonicNow();
137
+ this.readMonotonicMs = monotonicMs;
114
138
  if (this.environment.platform === "win32")
115
139
  return this.readWindowsSnapshot(sampledAtMs, monotonicMs);
116
140
  const linux = this.environment.platform === "linux";
@@ -1,5 +1,5 @@
1
1
  import type { HostLoadAdmissionDecision } from "./host-load-admission.js";
2
- import type { HostLoadAdmission, HostLoadStepGate } from "./host-load-governor.js";
2
+ import { type HostLoadAdmission, type HostLoadStepGate } from "./host-load-governor.js";
3
3
  import type { HostLoadStepProcess } from "./host-load-step-reaper.js";
4
4
  import type { HostLoadStepClassification } from "./host-load-step-class.js";
5
5
  import type { HostLoadTokenPriority } from "./host-load-token-ledger.js";
@@ -10,8 +10,8 @@ export interface HostGovernedStep {
10
10
  readonly dispatchAttemptId: string | null;
11
11
  readonly priority: HostLoadTokenPriority;
12
12
  readonly signal?: AbortSignal;
13
- /** Called once, when the step first has to wait for capacity. */
14
- readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
13
+ /** Called when the step first has to wait for capacity, and again whenever that wait changes. */
14
+ readonly onWaiting?: (decision: HostLoadAdmissionDecision, fence: WaitReportFence) => void | Promise<void>;
15
15
  /**
16
16
  * The step records its own fenced outcome (a managed command's receipt). Otherwise a
17
17
  * step whose token was reclaimed while it ran fails with host_capacity_token_fenced.
@@ -53,6 +53,40 @@ export declare function retentionFor(error: unknown): HostLoadRetention | null;
53
53
  * is returned when `run` settles, whether it succeeded, failed or was stopped.
54
54
  */
55
55
  export declare function runHostGovernedStep<T>(gate: HostLoadStepGate | undefined, step: HostGovernedStep, run: (hostLoadWaitMs: HostLoadWait, control: HostLoadStepControl) => Promise<T>): Promise<T>;
56
+ /** A step's wait reports, run in order; see orderedWaitReports. */
57
+ export interface OrderedWaitReports {
58
+ readonly onWaiting: ((decision: HostLoadAdmissionDecision) => void) | undefined;
59
+ /**
60
+ * Resolves once every report made so far has landed, or after the governor's drain bound
61
+ * (afterNotified) at the latest. Either way the reports are then closed: one still queued, or
62
+ * made later, is dropped as stale and never runs, and one still running can no longer commit
63
+ * (WaitReportFence). A commit already under way is awaited, so it lands before what follows.
64
+ */
65
+ drained(): Promise<void>;
66
+ }
67
+ /**
68
+ * Handed to each wait report. The bound in `drained` stops waiting for a report, not the report
69
+ * itself, so a slow write that finally succeeds would land after the step's own state. A report
70
+ * that replaces durable state (a receipt) makes that last replace through `commit`: it then runs
71
+ * only while the reports are open, and never after the step's state is written.
72
+ */
73
+ export interface WaitReportFence {
74
+ /** False once the reports are closed. */
75
+ readonly current: boolean;
76
+ /** Runs `replace` only while the reports are open; false when it was skipped as stale. */
77
+ commit(replace: () => Promise<void>): Promise<boolean>;
78
+ }
79
+ /**
80
+ * Runs a step's wait reports one at a time, in the order they were made, and hands the governor a
81
+ * callback that returns at once. The governor waits only a few seconds for a report (afterNotified),
82
+ * so a report it waited on could still land after the step's admitted or failed state. The step
83
+ * awaits `drained` before writing that state instead, so a late "waiting" can never replace it.
84
+ * `drained` keeps the governor's bound, so a report that never settles (a stuck checkpoint or
85
+ * event) cannot hold the step's admission, or its failure, back for longer than that. A report
86
+ * still running after the bound can no longer replace a receipt (WaitReportFence.commit); an
87
+ * appended event it already sent stays in the log as history of the wait, which it was.
88
+ */
89
+ export declare function orderedWaitReports(report: ((decision: HostLoadAdmissionDecision, fence: WaitReportFence) => void | Promise<void>) | undefined): OrderedWaitReports;
56
90
  /**
57
91
  * Returns a step's token, unless part of its process tree could not be proven
58
92
  * gone: the token (and its cost) is then kept until the tree is.
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { isProcessTreeTerminationUnproven, ProcessTreeTerminationError } from "../shared/process/process.js";
3
+ import { afterNotified } from "./host-load-governor.js";
3
4
  /**
4
5
  * The retention a step's failure calls for: a tree that could not be proven gone,
5
6
  * whether the runner said so with its own check (ProcessTreeTerminationError) or a
@@ -21,13 +22,21 @@ export function retentionFor(error) {
21
22
  export async function runHostGovernedStep(gate, step, run) {
22
23
  if (!gate?.enabled)
23
24
  return await run(null, {});
24
- const admission = await gate.acquire({
25
- stepClass: step.classification.stepClass,
26
- label: step.label,
27
- cost: step.classification.cost,
28
- dispatchAttemptId: step.dispatchAttemptId,
29
- priority: step.priority,
30
- }, { signal: step.signal, onWaiting: step.onWaiting });
25
+ const reports = orderedWaitReports(step.onWaiting);
26
+ let admission;
27
+ try {
28
+ admission = await gate.acquire({
29
+ stepClass: step.classification.stepClass,
30
+ label: step.label,
31
+ cost: step.classification.cost,
32
+ dispatchAttemptId: step.dispatchAttemptId,
33
+ priority: step.priority,
34
+ }, { signal: step.signal, onWaiting: reports.onWaiting });
35
+ }
36
+ finally {
37
+ // Every wait report lands before the step's own outcome (its launch, or why it was never admitted).
38
+ await reports.drained();
39
+ }
31
40
  let retention = null;
32
41
  try {
33
42
  let outcome;
@@ -55,6 +64,53 @@ export async function runHostGovernedStep(gate, step, run) {
55
64
  await returnHostLoadToken(admission, retention, step.onReleaseFailed);
56
65
  }
57
66
  }
67
+ /**
68
+ * Runs a step's wait reports one at a time, in the order they were made, and hands the governor a
69
+ * callback that returns at once. The governor waits only a few seconds for a report (afterNotified),
70
+ * so a report it waited on could still land after the step's admitted or failed state. The step
71
+ * awaits `drained` before writing that state instead, so a late "waiting" can never replace it.
72
+ * `drained` keeps the governor's bound, so a report that never settles (a stuck checkpoint or
73
+ * event) cannot hold the step's admission, or its failure, back for longer than that. A report
74
+ * still running after the bound can no longer replace a receipt (WaitReportFence.commit); an
75
+ * appended event it already sent stays in the log as history of the wait, which it was.
76
+ */
77
+ export function orderedWaitReports(report) {
78
+ let chain = Promise.resolve();
79
+ let closed = false;
80
+ let committing = Promise.resolve();
81
+ const fence = {
82
+ get current() { return !closed; },
83
+ commit: async (replace) => {
84
+ if (closed)
85
+ return false;
86
+ // Started while open: `drained` waits for it, so it cannot land after the step's state.
87
+ const replaced = replace();
88
+ committing = replaced.catch(() => undefined);
89
+ await replaced;
90
+ return true;
91
+ },
92
+ };
93
+ return {
94
+ onWaiting: report ? decision => {
95
+ if (closed)
96
+ return;
97
+ chain = chain.then(async () => { if (!closed)
98
+ await report(decision, fence); }).catch(() => undefined);
99
+ } : undefined,
100
+ drained: async () => {
101
+ // Once closed nothing new runs or commits: a report still in flight was already given its bound.
102
+ if (closed)
103
+ return;
104
+ try {
105
+ await afterNotified(chain);
106
+ }
107
+ finally {
108
+ closed = true;
109
+ }
110
+ await committing;
111
+ },
112
+ };
113
+ }
58
114
  /**
59
115
  * Returns a step's token, unless part of its process tree could not be proven
60
116
  * gone: the token (and its cost) is then kept until the tree is.
@@ -28,7 +28,10 @@ export interface HostTestSlotInput {
28
28
  readonly queue: readonly HostTestSlotTicketRequest[];
29
29
  /** Every live token on the host; fenced and degraded ones still hold their slot. */
30
30
  readonly tokens: readonly HostLoadToken[];
31
+ /** The count in force: the configured count, or lower while other work needs the host. */
31
32
  readonly testSlots: number;
33
+ /** Why testSlots is below the configured count (host-load-capacity.ts); empty or absent when it is not. */
34
+ readonly testSlotsDetail?: string;
32
35
  readonly nowMs: number;
33
36
  readonly antiStarvationMs: number;
34
37
  }
@@ -48,22 +48,41 @@ export function decideHostTestSlot(input) {
48
48
  return { ...reserved, admitted, reason: "admitted_test_slot", detail: "The host test slot is free." };
49
49
  }
50
50
  const heldBy = holders.length > 0
51
- ? `held by ${holders.map(describeHolder).join("; ")}`
51
+ ? `held by ${holders.map(token => describeHolder(token, input.ticket.dispatchAttemptId)).join("; ")}`
52
52
  : "the steps ahead of this one take it first";
53
53
  return {
54
54
  ...reserved,
55
55
  admitted,
56
56
  reason: "host_test_slot",
57
- detail: `Waiting for the host test slot (${input.testSlots} at once): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
57
+ detail: `Waiting for the host test slot (${input.testSlots} at once${input.testSlotsDetail ? `, ${input.testSlotsDetail}` : ""}): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
58
+ // Only a running, healthy holder is progress. With no holder the steps ahead are waiting too (for
59
+ // the budget, say), and that wait must count as stalled, not reset the clock.
60
+ progressing: holders.length > 0 && holders.every(healthyHolder),
58
61
  };
59
62
  }
60
- function describeHolder(token) {
63
+ /** A holder whose step is still running under a live, renewed lease; the ledger reclaims the rest. */
64
+ function healthyHolder(token) {
65
+ return !token.degradedAt && !token.fencedAt && !token.retainedAt;
66
+ }
67
+ /**
68
+ * Names the holder for the waiting step's agent: whose step it is and since when. A step
69
+ * label alone reads like the agent's own: an agent that saw "held by dotnet_api_component"
70
+ * took another session's live test run for its own finished one and gave up the wait.
71
+ */
72
+ function describeHolder(token, waiterAttemptId) {
61
73
  const attempt = token.dispatchAttemptId ? `, attempt ${token.dispatchAttemptId}` : "";
74
+ const whose = !token.dispatchAttemptId ? ""
75
+ : token.dispatchAttemptId === waiterAttemptId ? ", this session's own step" : ", another session's step";
76
+ const admittedAtMs = Date.parse(token.admittedAt);
77
+ const since = Number.isFinite(admittedAtMs)
78
+ ? ` since ${new Date(admittedAtMs).toISOString().replace(/\.\d{3}Z$/u, "Z")}`
79
+ : "";
62
80
  const state = token.degradedAt
63
- ? ", whose owner is gone; it is returned once its processes are stopped"
64
- : token.fencedAt ? ", which is past its lease"
65
- : token.retainedAt ? ", whose processes could not be proven stopped; it is returned at attempt teardown" : "";
66
- return `${token.label} (${token.stepClass}${attempt}${state})`;
81
+ ? `, held${since}; its owner is gone, and it is returned once its processes are stopped`
82
+ : token.fencedAt ? `, held${since} and past its lease`
83
+ : token.retainedAt ? `, held${since}; its processes could not be proven stopped, and it is returned at attempt teardown`
84
+ : `, still running${since}`;
85
+ return `${token.label} (${token.stepClass}${attempt}${whose}${state})`;
67
86
  }
68
87
  /** A ticket read back from the ledger; a malformed one is dropped, never trusted. */
69
88
  export function validHostTestSlotTicket(value) {
@@ -5,6 +5,8 @@ import { isAlias, parseDocument, visit } from "yaml";
5
5
  import { readCanonicalSourceFile } from "./canonical-source-file.js";
6
6
  import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
7
7
  import { parseHostRuntimeRequirements } from "./host-runtime-requirements.js";
8
+ // A contract a WIP re-apply left conflicted runs as committed until the agent resolves it (see wip-git.ts).
9
+ import { committedWhileReapplyConflicted } from "../worktree/wip-git.js";
8
10
  export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
9
11
  export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
10
12
  export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
@@ -68,10 +70,10 @@ export async function loadHostRuntimeContract(worktreePath, snapshot, directoryS
68
70
  return await discoverHostRuntimeContract(worktreePath, snapshot, directorySnapshot);
69
71
  throw error;
70
72
  }
71
- return {
72
- contract: validateHostRuntimeContract(source.toString("utf8")),
73
- source: "project",
74
- };
73
+ const text = await committedWhileReapplyConflicted(worktreePath, hostRuntimeContractPath, source.toString("utf8"));
74
+ if (text === null)
75
+ return await discoverHostRuntimeContract(worktreePath, snapshot, directorySnapshot);
76
+ return { contract: validateHostRuntimeContract(text), source: "project" };
75
77
  }
76
78
  async function discoverHostRuntimeContract(worktreePath, snapshot, directorySnapshot) {
77
79
  const root = path.resolve(worktreePath);
@@ -33,10 +33,20 @@ export declare class PreparedRuntimeReadiness {
33
33
  private drain;
34
34
  private scheduleDeadline;
35
35
  private check;
36
+ /**
37
+ * The identity when the worktree needs no probe, or null to probe it. Recorded proof for the same
38
+ * isolation inputs already covers it: a re-apply conflict changes source, not those inputs, and the
39
+ * stack it defers starts at validation from the agent's resolved source, as any edited source does.
40
+ * Without proof, nothing is probed (no exclusive admission, no stack launch) when no proof could be
41
+ * recorded: a quarantined contract, or restored work with unresolved re-apply conflicts, which
42
+ * cannot build and which the agent resolves first (deferredProjectStartEvent in
43
+ * worktree-wip-events.ts). Those runs take exclusive admission.
44
+ */
45
+ private settledWithoutProbe;
36
46
  /**
37
47
  * A probe whose repository was revoked while it ran (its own violation or a sibling's), or whose
38
- * contract is quarantined, records no proof. The agent's admission then finds none and runs under
39
- * exclusive admission.
48
+ * contract is quarantined, or whose worktree still has unresolved WIP re-apply conflicts, records
49
+ * no proof. The agent's admission then finds none and runs under exclusive admission.
40
50
  */
41
51
  private unproven;
42
52
  }
@@ -4,6 +4,7 @@ import { ForgeFailureError } from "../session/session.types.js";
4
4
  import { loadHostRuntimeContract } from "./host-runtime-contract.js";
5
5
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible } from "./host-runtime-promotion.js";
6
6
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
7
+ import { unresolvedReapplyConflicts, WipGit } from "../worktree/wip-git.js";
7
8
  /** Foreground barrier: prepare a wave, verify its exact runtimes, then release agents. */
8
9
  export class PreparedRuntimeReadiness {
9
10
  runtime;
@@ -170,11 +171,9 @@ export class PreparedRuntimeReadiness {
170
171
  if (hostRuntimeContractFingerprint(contract) !== identity.runtimeContractFingerprint) {
171
172
  throw new Error("host_runtime_prepared_source_changed: runtime contract changed while capturing its source identity.");
172
173
  }
173
- if (await this.store.load(dispatch.repo.id, identity))
174
- return identity;
175
- // A quarantined contract cannot record proof: skip the exclusive admission and the stack launch.
176
- if (await this.store.quarantined(dispatch.repo.id, identity.runtimeContractFingerprint))
177
- return await this.unproven(entry, identity, checkpoint, true);
174
+ const settled = await this.settledWithoutProbe(entry, identity, worktree, checkpoint);
175
+ if (settled)
176
+ return settled;
178
177
  await checkpoint?.({ code: "host_runtime_prepared_probe_started", expiresAt: entry.expiresAt,
179
178
  message: `Verifying prepared runtime ${identity.inputCommitSha.slice(0, 12)} before agent admission; project-default readiness is not a substitute.` });
180
179
  const probeId = randomUUID();
@@ -246,20 +245,45 @@ export class PreparedRuntimeReadiness {
246
245
  message: `Prepared runtime ${identity.inputCommitSha.slice(0, 12)} passed isolation verification; its proof is retained for every head with the same isolation inputs.` });
247
246
  return identity;
248
247
  }
248
+ /**
249
+ * The identity when the worktree needs no probe, or null to probe it. Recorded proof for the same
250
+ * isolation inputs already covers it: a re-apply conflict changes source, not those inputs, and the
251
+ * stack it defers starts at validation from the agent's resolved source, as any edited source does.
252
+ * Without proof, nothing is probed (no exclusive admission, no stack launch) when no proof could be
253
+ * recorded: a quarantined contract, or restored work with unresolved re-apply conflicts, which
254
+ * cannot build and which the agent resolves first (deferredProjectStartEvent in
255
+ * worktree-wip-events.ts). Those runs take exclusive admission.
256
+ */
257
+ async settledWithoutProbe(entry, identity, worktree, checkpoint) {
258
+ const repoId = entry.dispatch.repo.id;
259
+ if (await this.store.load(repoId, identity))
260
+ return identity;
261
+ if (await this.store.quarantined(repoId, identity.runtimeContractFingerprint)) {
262
+ return await this.unproven(entry, identity, checkpoint, "quarantined");
263
+ }
264
+ // An unreadable conflict state is not probed either: the stack may not build.
265
+ const conflicted = await unresolvedReapplyConflicts(new WipGit(), worktree)
266
+ .then(conflicts => conflicts.length > 0 ? "reapply_conflicts" : null, () => "reapply_conflicts_unreadable");
267
+ return conflicted ? await this.unproven(entry, identity, checkpoint, conflicted) : null;
268
+ }
249
269
  /**
250
270
  * A probe whose repository was revoked while it ran (its own violation or a sibling's), or whose
251
- * contract is quarantined, records no proof. The agent's admission then finds none and runs under
252
- * exclusive admission.
271
+ * contract is quarantined, or whose worktree still has unresolved WIP re-apply conflicts, records
272
+ * no proof. The agent's admission then finds none and runs under exclusive admission.
253
273
  */
254
- async unproven(entry, identity, checkpoint, quarantined = false) {
255
- const reason = quarantined
256
- ? "its runtime contract is quarantined after a recent isolation violation, so it was not probed"
257
- : "the repository's promotion was revoked during the probe";
274
+ async unproven(entry, identity, checkpoint, cause = "revoked") {
275
+ const reason = unprovenReasons[cause];
258
276
  await checkpoint?.({ code: "host_runtime_prepared_probe_completed", expiresAt: entry.expiresAt,
259
277
  message: `Prepared runtime ${identity.inputCommitSha.slice(0, 12)} did not prove isolation (${reason}); its runs are serialized.` });
260
278
  return identity;
261
279
  }
262
280
  }
281
+ const unprovenReasons = {
282
+ revoked: "the repository's promotion was revoked during the probe",
283
+ quarantined: "its runtime contract is quarantined after a recent isolation violation, so it was not probed",
284
+ reapply_conflicts: "its worktree has unresolved conflicts from re-applied saved work, which the agent resolves first, so it was not probed",
285
+ reapply_conflicts_unreadable: "its worktree's record of conflicts from re-applied saved work could not be read, so it was not probed",
286
+ };
263
287
  const preparedHeadPollIntervalMs = 1_000;
264
288
  async function monitorPreparedHead(worktree, expectedCommitSha, preparationController, stopSignal) {
265
289
  const git = new GitClient();
@@ -2,6 +2,7 @@ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
2
2
  import type { SessionEventSink } from "../session/session.base.js";
3
3
  import { type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
4
4
  import type { SandboxService, ValidatedSandboxContract } from "./sandbox.types.js";
5
+ export { selectSandboxInputRefs } from "./sandbox-input.js";
5
6
  import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
6
7
  import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
7
8
  export interface SandboxRuntime {
@@ -169,7 +170,6 @@ export declare function selectSandboxConfigRefs(executionPolicy: string, configu
169
170
  readonly refs: readonly string[];
170
171
  readonly approvedSha: string | null;
171
172
  };
172
- export declare function selectSandboxInputRefs(worktreeKey: string, baseBranch: string): readonly string[];
173
173
  export declare function sandboxTimeLimits(environment?: NodeJS.ProcessEnv): {
174
174
  readonly hardWallMs: number;
175
175
  readonly idleMs: number;
@@ -308,4 +308,3 @@ export declare function classifySandboxResourceFailure(value: string): {
308
308
  readonly code: string;
309
309
  readonly message: string;
310
310
  } | null;
311
- export {};
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
5
5
  import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
6
6
  import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
7
7
  import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
- import { advanceCheckedOutBranch } from "./managed-branch.js";
8
+ import { advanceCheckedOutBranch, resolveReviewDiffBase, resolveSandboxInputCommit, reviewOnlySandboxOutput, sandboxPublicationAllowed, withReviewDiffBase } from "./sandbox-input.js";
9
+ export { selectSandboxInputRefs } from "./sandbox-input.js";
9
10
  import { createLeaseUpdate } from "./lease-watchdog.js";
10
11
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
11
12
  import { SandboxEventBudget } from "./event-budget.js";
@@ -111,7 +112,7 @@ export class DockerSandboxRuntime {
111
112
  const securityOptions = resolveSandboxSecurityOptions(dispatch.sandbox.executionPolicy);
112
113
  const builtImage = await this.buildImage(prepared.contextRoot, prepared.contextDigest, dispatch.repo.name, validated, upstreamImages, dispatch.sandbox.executionPolicy, sink, runtimeSignal);
113
114
  const imageDigest = builtImage.imageDigest;
114
- const runtimeDispatch = withSandboxMetadata(dispatch, prepared.inputCommitSha, prepared.configCommitSha, validated.digest, imageDigest);
115
+ const runtimeDispatch = withReviewDiffBase(withSandboxMetadata(dispatch, prepared.inputCommitSha, prepared.configCommitSha, validated.digest, imageDigest), prepared.reviewDiffBase);
115
116
  const providerAuthAdapter = sandboxProviderAuthAdapterFor(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
116
117
  const providerAuthUnavailable = sandboxProviderAuthUnavailableMessage(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
117
118
  if (providerAuthUnavailable) {
@@ -170,7 +171,7 @@ export class DockerSandboxRuntime {
170
171
  const brokered = this.hostLoadGate?.enabled === true;
171
172
  const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
172
173
  const createArgs = brokered
173
- ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
174
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxTotalWaitMs)
174
175
  : workerArgs;
175
176
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
176
177
  const containerId = dockerObjectId(createdContainer.stdout, "container");
@@ -276,7 +277,7 @@ export class DockerSandboxRuntime {
276
277
  await this.docker(["cp", `${containerId}:/control/output/.`, path.join(attemptRoot, "output")], 60_000);
277
278
  let output;
278
279
  try {
279
- output = await validateOutput(attemptRoot, runtimeDispatch);
280
+ output = reviewOnlySandboxOutput(runtimeDispatch, await validateOutput(attemptRoot, runtimeDispatch));
280
281
  }
281
282
  catch (error) {
282
283
  if (start.exitCode !== 0 && isMissingSandboxManifest(error)) {
@@ -285,7 +286,7 @@ export class DockerSandboxRuntime {
285
286
  throw error;
286
287
  }
287
288
  await git.importResult(runtimeDispatch, output, () => assertSandboxImportCurrent(active, this.active.get(active.dispatchAttemptId), controller.signal));
288
- if (runtimeDispatch.sandbox.publicationMode === "bridge_push") {
289
+ if (sandboxPublicationAllowed(runtimeDispatch)) {
289
290
  const handle = runtimeDispatch.sandbox.publishGrantHandle;
290
291
  if (!handle || !output.manifest.resultCommitSha || !this.publicationGrantRedeemer) {
291
292
  throw trustedSandboxFailure("sandbox_output_publish_forbidden", "bridge publication grant redemption is unavailable.");
@@ -1166,7 +1167,7 @@ class HostGit {
1166
1167
  async prepareLocked(dispatch, attemptRoot) {
1167
1168
  const baseBranch = dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch;
1168
1169
  await this.git(["fetch", "--prune", "origin"], 5 * 60_000).catch(() => null);
1169
- const inputCommitSha = await this.resolveFirst([...selectSandboxInputRefs(dispatch.lease.worktreeKey, baseBranch)]);
1170
+ const [inputCommitSha, reviewDiffBase] = [await resolveSandboxInputCommit(dispatch, baseBranch, (refs) => this.resolveFirst(refs), (args) => this.git(args, 5 * 60_000)), await resolveReviewDiffBase(dispatch, async (args) => (await this.git(args, 5 * 60_000)).stdout)];
1170
1171
  const configSelection = selectSandboxConfigRefs(dispatch.sandbox.executionPolicy, dispatch.sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
1171
1172
  const configCommitSha = await this.resolveFirst([...configSelection.refs]);
1172
1173
  const approvedConfigSha = configSelection.approvedSha;
@@ -1190,7 +1191,7 @@ class HostGit {
1190
1191
  await fs.mkdir(contextRoot, { recursive: true });
1191
1192
  await requireSandboxProcess({ command: "tar", args: ["-xf", contextArchive, "-C", contextRoot], timeoutMs: 5 * 60_000, maxOutputBytes: 1024 * 1024 });
1192
1193
  const contextDigest = createHash("sha256").update(await fs.readFile(contextArchive)).digest("hex");
1193
- return { inputCommitSha, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1194
+ return { inputCommitSha, reviewDiffBase, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1194
1195
  }
1195
1196
  async importResult(dispatch, output, assertCurrent) {
1196
1197
  await this.coordinator.withLock(this.repoPath, () => this.importResultLocked(dispatch, output, assertCurrent));
@@ -1421,13 +1422,6 @@ export function selectSandboxConfigRefs(executionPolicy, configuredSha, defaultB
1421
1422
  ? { refs: [approvedSha], approvedSha }
1422
1423
  : { refs: [`refs/heads/${defaultBranch}`, `refs/remotes/origin/${defaultBranch}`], approvedSha: null };
1423
1424
  }
1424
- export function selectSandboxInputRefs(worktreeKey, baseBranch) {
1425
- return [
1426
- `refs/heads/${worktreeKey}`,
1427
- `refs/heads/${baseBranch}`,
1428
- `refs/remotes/origin/${baseBranch}`
1429
- ];
1430
- }
1431
1425
  export function sandboxTimeLimits(environment = process.env) {
1432
1426
  const hardWallSeconds = boundedInteger(environment.FORGE_SANDBOX_HARD_WALL_SECONDS, 8 * 60 * 60, 60, 8 * 60 * 60);
1433
1427
  const idleSeconds = boundedInteger(environment.FORGE_SANDBOX_IDLE_SECONDS, 10 * 60, 60, hardWallSeconds);
@@ -0,0 +1,22 @@
1
+ export { advanceCheckedOutBranch } from "./managed-branch.js";
2
+ export { resolveReviewDiffBase, withReviewDiffBase } from "../session/pr-review-diff-base.js";
3
+ import { type RunOnceDispatchPacket } from "../session/session.types.js";
4
+ export declare function selectSandboxInputRefs(worktreeKey: string, baseBranch: string): readonly string[];
5
+ /**
6
+ * The commit a Docker attempt starts from. A Forge PR review reads exactly the dispatched pull request
7
+ * head, fetched from origin by its SHA when the host checkout doesn't have it yet; every other attempt
8
+ * starts from its managed branch or its base. Never a branch name for a review: the head is a full SHA.
9
+ */
10
+ export declare function resolveSandboxInputCommit(dispatch: RunOnceDispatchPacket, baseBranch: string, resolveFirst: (refs: string[]) => Promise<string>, fetchFromOrigin: (args: readonly string[]) => Promise<unknown>): Promise<string>;
11
+ /**
12
+ * A review publishes nothing: whatever the container's HEAD is, the attempt has no result commit, so the
13
+ * host neither imports a bundle into a branch nor pushes one.
14
+ */
15
+ export declare function reviewOnlySandboxOutput<T extends {
16
+ readonly bundlePath: string | null;
17
+ readonly manifest: {
18
+ readonly resultCommitSha: string | null;
19
+ };
20
+ }>(dispatch: RunOnceDispatchPacket, output: T): T;
21
+ /** Whether the host may publish this attempt's result: never for a review, whatever mode it was offered. */
22
+ export declare function sandboxPublicationAllowed(dispatch: RunOnceDispatchPacket): boolean;
@@ -0,0 +1,49 @@
1
+ // The host side of a sandbox attempt's git state: the commit it starts from, whether its result comes back
2
+ // and is published, and how an imported result moves its managed branch (managed-branch.ts).
3
+ export { advanceCheckedOutBranch } from "./managed-branch.js";
4
+ // A review's diff base is in its bundle: the merge base is an ancestor of the head the bundle carries.
5
+ export { resolveReviewDiffBase, withReviewDiffBase } from "../session/pr-review-diff-base.js";
6
+ import { prReviewDispatchHeadSha } from "../session/pr-review-placement.js";
7
+ import { ForgeFailureError } from "../session/session.types.js";
8
+ export function selectSandboxInputRefs(worktreeKey, baseBranch) {
9
+ return [
10
+ `refs/heads/${worktreeKey}`,
11
+ `refs/heads/${baseBranch}`,
12
+ `refs/remotes/origin/${baseBranch}`
13
+ ];
14
+ }
15
+ /**
16
+ * The commit a Docker attempt starts from. A Forge PR review reads exactly the dispatched pull request
17
+ * head, fetched from origin by its SHA when the host checkout doesn't have it yet; every other attempt
18
+ * starts from its managed branch or its base. Never a branch name for a review: the head is a full SHA.
19
+ */
20
+ export async function resolveSandboxInputCommit(dispatch, baseBranch, resolveFirst, fetchFromOrigin) {
21
+ const reviewHead = prReviewDispatchHeadSha(dispatch);
22
+ if (!reviewHead) {
23
+ return await resolveFirst([...selectSandboxInputRefs(dispatch.lease.worktreeKey, baseBranch)]);
24
+ }
25
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(reviewHead)) {
26
+ throw new ForgeFailureError("sandbox_input_failed", "sandbox_input_failed: the pull request review head is not a full Git object id.", "sandbox");
27
+ }
28
+ const resolved = await resolveFirst([reviewHead]).catch(async () => {
29
+ await fetchFromOrigin(["fetch", "--no-tags", "--no-write-fetch-head", "origin", reviewHead]).catch(() => undefined);
30
+ return await resolveFirst([reviewHead]);
31
+ });
32
+ if (resolved.toLowerCase() !== reviewHead) {
33
+ throw new ForgeFailureError("sandbox_input_failed", "sandbox_input_failed: the resolved review input is not the dispatched pull request head.", "sandbox");
34
+ }
35
+ return resolved;
36
+ }
37
+ /**
38
+ * A review publishes nothing: whatever the container's HEAD is, the attempt has no result commit, so the
39
+ * host neither imports a bundle into a branch nor pushes one.
40
+ */
41
+ export function reviewOnlySandboxOutput(dispatch, output) {
42
+ return prReviewDispatchHeadSha(dispatch) === null
43
+ ? output
44
+ : { ...output, bundlePath: null, manifest: { ...output.manifest, resultCommitSha: null } };
45
+ }
46
+ /** Whether the host may publish this attempt's result: never for a review, whatever mode it was offered. */
47
+ export function sandboxPublicationAllowed(dispatch) {
48
+ return dispatch.sandbox?.publicationMode === "bridge_push" && prReviewDispatchHeadSha(dispatch) === null;
49
+ }
@@ -33,7 +33,19 @@ export class SandboxWorkspaceService {
33
33
  if (actualSha.toLowerCase() !== this.inputCommitSha.toLowerCase())
34
34
  throw new Error("Imported bundle does not contain the exact recorded input commit.");
35
35
  const branchName = normalizeBranchName(request.worktreeKey, `forge/${request.workItem.id.replace(/-/g, "")}`);
36
- await this.git.run(this.workspace, ["checkout", "-B", branchName, this.inputCommitSha]);
36
+ const reviewHeadSha = request.detachedHeadSha?.trim().toLowerCase();
37
+ if (reviewHeadSha) {
38
+ // A review reads exactly the dispatched pull request head, detached; the bundle must carry it.
39
+ if (reviewHeadSha !== this.inputCommitSha.toLowerCase())
40
+ throw new Error("Sandbox input commit is not the review head.");
41
+ await this.git.run(this.workspace, ["checkout", "--detach", this.inputCommitSha]);
42
+ const detachedHead = (await this.git.run(this.workspace, ["rev-parse", "HEAD"])).trim().toLowerCase();
43
+ if (detachedHead !== reviewHeadSha)
44
+ throw new Error("Sandbox review worktree is not at the review head.");
45
+ }
46
+ else {
47
+ await this.git.run(this.workspace, ["checkout", "-B", branchName, this.inputCommitSha]);
48
+ }
37
49
  await this.git.run(this.workspace, ["config", "user.email", "forge-agent@forge.local"]);
38
50
  await this.git.run(this.workspace, ["config", "user.name", "Forge Agent"]);
39
51
  await this.git.run(this.workspace, ["config", "core.hooksPath", "/dev/null"]);
@@ -54,7 +66,8 @@ export class SandboxWorkspaceService {
54
66
  branchName,
55
67
  baseBranch: request.baseBranch,
56
68
  cleanupWorktrees: false,
57
- hydratedPriorPhaseArtifactCount
69
+ hydratedPriorPhaseArtifactCount,
70
+ ...(reviewHeadSha ? { detachedHeadSha: reviewHeadSha } : {})
58
71
  };
59
72
  }
60
73
  async release(_handle) {