@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0f07274d438b

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 (260) hide show
  1. package/README.md +128 -4
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -1,7 +1,7 @@
1
1
  import type { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
2
- import type { NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
3
2
  import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
4
3
  import { type PrePublicationHostLoadOwner } from "./pre-publication-host-load.js";
4
+ import { type NativeTestPostgresFallback, type StartEphemeralTestPostgresGrant } from "./pre-publication-native-postgres.js";
5
5
  import { type ValidationStep } from "./pre-publication-step-execution.js";
6
6
  import { PrePublicationValidationError, type PrePublicationCheckFailure } from "./pre-publication-pass.js";
7
7
  import type { ProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
@@ -31,6 +31,8 @@ export interface PrePublicationCommandRunner {
31
31
  }
32
32
  export interface PrePublicationExecutionContext {
33
33
  readonly baselineRevision?: string;
34
+ /** The branch the attempt publishes into; only a merge of it scopes the pass (pre-publication-change-set.ts). */
35
+ readonly targetBranch?: string;
34
36
  readonly environment?: Readonly<Record<string, string>>;
35
37
  readonly processRunner?: ProviderProcessRunner;
36
38
  /** The attempt governed steps reserve host capacity for (decision 0013). */
@@ -56,7 +58,8 @@ export declare class PrePublicationValidator {
56
58
  private readonly dockerEngineProbe?;
57
59
  private readonly nativeTestPostgresFallback;
58
60
  private readonly hostLoad?;
59
- constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null, hostLoad?: HostLoadStepGate | undefined);
61
+ private readonly startEphemeral?;
62
+ constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null, hostLoad?: HostLoadStepGate | undefined, startEphemeral?: StartEphemeralTestPostgresGrant | undefined);
60
63
  /**
61
64
  * Runs one pre-publication pass. A failed check does not end the pass: every remaining check that
62
65
  * can still meaningfully run keeps going, and the pass then throws all of its failures as one
@@ -66,16 +69,18 @@ export declare class PrePublicationValidator {
66
69
  private runChecks;
67
70
  /** Runs one check's steps in order; the first failed step ends the check, since later steps use its output. */
68
71
  private runCheck;
72
+ private runCheckSteps;
69
73
  /** Runs a step, confirming once a failure that matches a known transient pattern. */
70
74
  private runConfirmedStep;
71
75
  private runCheckedStep;
72
76
  private confirmStep;
73
77
  private confirmInfrastructure;
74
- /** Returns the native fallback connection when this check must use it instead of Docker. */
78
+ /** Returns the native cluster grant when this check uses it instead of Docker. */
75
79
  private ensurePrerequisite;
80
+ /** Waits for Docker; returns the native cluster grant when Docker stays down and a cluster is provisioned. */
81
+ private ensureDockerPrerequisite;
76
82
  private throwIfPrerequisiteWasLost;
77
83
  private checkTestOnlyExports;
78
- private changedPaths;
79
84
  private assertContractMatchesDispatchBaseline;
80
85
  /** The approved contract of the branch an in-progress merge brings in (MERGE_HEAD), else null. */
81
86
  private mergedInContractDigest;
@@ -4,15 +4,18 @@ import path from "node:path";
4
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
5
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
6
6
  import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
7
- import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
7
+ import { dockerFreeGrant, dockerUnavailableNativeTestPostgres, isolatedPostgresProvided, preferredNativeTestPostgres, releaseCheckPostgres, } from "./pre-publication-native-postgres.js";
8
+ import { managedAttemptInvocation, validationExecutionForStep, } from "./pre-publication-step-execution.js";
8
9
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
9
10
  import { redactText } from "../shared/redaction/redaction.js";
10
11
  import { PrePublicationPass, PrePublicationValidationError, SkippedTestTally, skippedCheckEvent, validationEvent, } from "./pre-publication-pass.js";
11
12
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
13
  import { ProcessTreeTerminationError } from "../shared/process/process.js";
13
- import { findUnreferencedNewExports } from "./unreferenced-exports.js";
14
+ import { findUnreferencedNewExports, historyIntegrityEnvironment, passChangeSet, validationRevisionEnvironment, } from "./pre-publication-change-set.js";
14
15
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
15
16
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
17
+ // The check whose steps run scripts/run-affected-dotnet-tests.mjs against the pass's revisions.
18
+ const affectedTestsCheckId = "comment-repair-dotnet-regression";
16
19
  const requiredCheckIds = new Set([
17
20
  "file-size-inventory",
18
21
  "owned-suite-registration",
@@ -23,8 +26,11 @@ const requiredCheckIds = new Set([
23
26
  "playwright-e2e",
24
27
  "github-provider-policy",
25
28
  ]);
26
- // Every gate profile runs the affected .NET tests; only CI runs the whole tiers (decision 0017).
27
- const currentApprovedContractDigest = "9cf3a3070de56f3d3bc2c013dfa45b0fd463d257722849087e6743fb9cb1fd0d";
29
+ // Every gate profile runs the affected .NET tests; only CI runs the whole heavier tiers (decision 0017),
30
+ // even when the selection cannot be narrowed (--whole-fallback none).
31
+ const currentApprovedContractDigest = "69dc8a3ac08bdbea938015584eb02bc3e42ef63f3c14a4ec365859a0e77e7909";
32
+ // The gate ran the whole Infrastructure tier when the affected selection could not be narrowed.
33
+ const infrastructureFallbackContractDigest = "9cf3a3070de56f3d3bc2c013dfa45b0fd463d257722849087e6743fb9cb1fd0d";
28
34
  // Only comment repair ran the affected tests; the other profiles ran Unit, Contract and
29
35
  // Infrastructure whole. Story branches cut before decision 0017 still carry it.
30
36
  const commentRepairOnlyAffectedContractDigest = "378c767c7977c850140ffb19d69db41da62d0187c37a33828d6cda8803a61c83";
@@ -33,10 +39,12 @@ const wholeTierCommentRepairContractDigest = "024de3648c907db9c0eab13def9a4f91e8
33
39
  // Contracts that declare the comment-repair-dotnet-regression check.
34
40
  const commentRepairRegressionContractDigests = new Set([
35
41
  currentApprovedContractDigest,
42
+ infrastructureFallbackContractDigest,
36
43
  commentRepairOnlyAffectedContractDigest,
37
44
  wholeTierCommentRepairContractDigest,
38
45
  ]);
39
46
  const compatibleApprovedContractDigests = new Set([
47
+ infrastructureFallbackContractDigest,
40
48
  commentRepairOnlyAffectedContractDigest,
41
49
  wholeTierCommentRepairContractDigest,
42
50
  // Preserve dispatches pinned before comment repair gained all .NET regression tiers.
@@ -100,11 +108,13 @@ export class PrePublicationValidator {
100
108
  dockerEngineProbe;
101
109
  nativeTestPostgresFallback;
102
110
  hostLoad;
103
- constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
111
+ startEphemeral;
112
+ constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad, startEphemeral) {
104
113
  this.commands = commands;
105
114
  this.dockerEngineProbe = dockerEngineProbe;
106
115
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
107
116
  this.hostLoad = hostLoad;
117
+ this.startEphemeral = startEphemeral;
108
118
  }
109
119
  /**
110
120
  * Runs one pre-publication pass. A failed check does not end the pass: every remaining check that
@@ -120,7 +130,7 @@ export class PrePublicationValidator {
120
130
  if (checksExports) {
121
131
  const legacy = await prepareValidationExecution(execution);
122
132
  try {
123
- await this.checkTestOnlyExports(pass, worktreePath, emit, signal, legacy.execution);
133
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, withHistoryIntegrity(legacy.execution));
124
134
  }
125
135
  finally {
126
136
  await legacy.cleanup();
@@ -131,20 +141,23 @@ export class PrePublicationValidator {
131
141
  }
132
142
  const scoped = await prepareValidationExecution(execution);
133
143
  try {
144
+ // The bridge's own git reads history as committed: no replace refs or grafts the agent planted.
145
+ const historyExecution = withHistoryIntegrity(scoped.execution);
134
146
  if (checksExports)
135
- await this.checkTestOnlyExports(pass, worktreePath, emit, signal, scoped.execution);
147
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, historyExecution);
136
148
  const contractDigest = validationContractDigest(contract);
137
- await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, scoped.execution);
149
+ await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, historyExecution);
138
150
  if (contractDigest !== currentApprovedContractDigest) {
139
151
  await emit?.(validationEvent("prepublication_validation_compatible_contract", "validation-contract", `This checkout is pinned to approved compatible CI parity contract ${contractDigest}; the host's current contract is ${currentApprovedContractDigest}.`));
140
152
  }
141
- const changedPaths = await this.changedPaths(worktreePath, signal, scoped.execution);
153
+ const git = (args) => this.runCommand("git", args, worktreePath, signal, historyExecution);
154
+ const { mergeParent, changedPaths } = await passChangeSet(git, scoped.execution, emit);
142
155
  const run = {
143
156
  worktreePath,
144
157
  capabilities,
145
158
  emit,
146
159
  signal,
147
- execution: withValidationBaseRevision(scoped.execution),
160
+ execution: withValidationRevisions(scoped.execution, mergeParent),
148
161
  postgresAdminConnection: scoped.postgresAdminConnection,
149
162
  };
150
163
  return await this.runChecks(applicableChecks(contract, profile, changedPaths), run, pass);
@@ -189,8 +202,19 @@ export class PrePublicationValidator {
189
202
  if (check.requiredCapability && !run.capabilities.has(check.requiredCapability)) {
190
203
  throw new ForgeFailureError("prepublication_capability_unavailable", `prepublication_capability_unavailable: ${check.id} requires ${check.requiredCapability}; publication is holding until a capable runner is available.`, "bridge");
191
204
  }
192
- const postgresAdminConnection = await this.ensurePrerequisite(check, run.execution?.environment, run.postgresAdminConnection, run.emit) ?? run.postgresAdminConnection;
193
- const stepRun = { ...run, check, postgresAdminConnection };
205
+ const granted = await this.ensurePrerequisite(check, run.execution?.environment, run.postgresAdminConnection, run.emit);
206
+ try {
207
+ // Only the affected .NET run measures against the pass's revisions, so only it reads them as committed;
208
+ // other suites may make replace refs or grafts of their own.
209
+ const execution = check.id === affectedTestsCheckId ? withHistoryIntegrity(run.execution) : run.execution;
210
+ return await this.runCheckSteps({ ...run, check, execution, postgresAdminConnection: granted ?? run.postgresAdminConnection });
211
+ }
212
+ finally {
213
+ await releaseCheckPostgres(check.id, granted, run.emit);
214
+ }
215
+ }
216
+ async runCheckSteps(stepRun) {
217
+ const { check, ...run } = stepRun;
194
218
  await run.emit?.(validationEvent("prepublication_validation_started", check.id, `Running pre-publication CI parity check '${check.id}'.`));
195
219
  const skipped = new SkippedTestTally(run.worktreePath, run.execution?.environment);
196
220
  for (const step of check.steps) {
@@ -206,7 +230,11 @@ export class PrePublicationValidator {
206
230
  }
207
231
  await skipped.add(result.args, stepStartedMs);
208
232
  }
209
- await run.emit?.(skipped.passedEvent(check.id, validationExactSecrets(run.execution?.environment)));
233
+ // The check's own grant reaches only its steps' derived environments, so name its secrets too.
234
+ await run.emit?.(skipped.passedEvent(check.id, [
235
+ ...validationExactSecrets(run.execution?.environment),
236
+ ...attemptDatabaseCapabilitySecrets(run.postgresAdminConnection?.connectionString),
237
+ ]));
210
238
  return null;
211
239
  }
212
240
  /** Runs a step, confirming once a failure that matches a known transient pattern. */
@@ -255,7 +283,7 @@ export class PrePublicationValidator {
255
283
  await run.emit?.(validationEvent("prepublication_infrastructure_failed", checkId, `Pre-publication infrastructure for '${checkId}' remained unavailable${detail ? `: ${detail}` : "."}`));
256
284
  throw new PrePublicationInfrastructureError(checkId, result.exitCode, result.command, result.args, detail);
257
285
  }
258
- /** Returns the native fallback connection when this check must use it instead of Docker. */
286
+ /** Returns the native cluster grant when this check uses it instead of Docker. */
259
287
  async ensurePrerequisite(check, environment, postgresAdminConnection, emit) {
260
288
  if (check.requiredPrerequisite === "isolated_postgres"
261
289
  && isolatedPostgresProvided(check.id, environment, postgresAdminConnection)) {
@@ -264,6 +292,11 @@ export class PrePublicationValidator {
264
292
  : `Pre-publication check '${check.id}' is using the configured loopback PostgreSQL test server with per-run owned databases. No Docker daemon is required.`));
265
293
  return undefined;
266
294
  }
295
+ return await preferredNativeTestPostgres(check.id, check.requiredPrerequisite, this.nativeTestPostgresFallback, this.dockerEngineProbe, emit, this.startEphemeral)
296
+ ?? await this.ensureDockerPrerequisite(check, emit);
297
+ }
298
+ /** Waits for Docker; returns the native cluster grant when Docker stays down and a cluster is provisioned. */
299
+ async ensureDockerPrerequisite(check, emit) {
267
300
  if (check.requiredPrerequisite === undefined || !this.dockerEngineProbe)
268
301
  return undefined;
269
302
  const current = this.dockerEngineProbe.current();
@@ -275,12 +308,10 @@ export class PrePublicationValidator {
275
308
  const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
276
309
  if (!snapshot.available) {
277
310
  const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
278
- const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
279
- ? this.nativeTestPostgresFallback()
280
- : null;
311
+ const fallback = dockerUnavailableNativeTestPostgres(check.id, check.requiredPrerequisite, this.nativeTestPostgresFallback);
281
312
  if (fallback) {
282
313
  await emit?.(validationEvent("prepublication_prerequisite_native_fallback", check.id, `${detail}. Pre-publication check '${check.id}' is using the dedicated native PostgreSQL test cluster at ${fallback.endpoint} with per-run owned databases.`));
283
- return fallback.connectionString;
314
+ return fallback;
284
315
  }
285
316
  await emit?.(validationEvent("prepublication_prerequisite_unavailable", check.id, `Pre-publication check '${check.id}' is waiting for Docker infrastructure recovery: ${detail}`));
286
317
  throw new PrePublicationInfrastructureError(check.id, 75, "docker", ["info"], detail);
@@ -292,7 +323,7 @@ export class PrePublicationValidator {
292
323
  if (result.exitCode === 0
293
324
  || check.requiredPrerequisite === undefined
294
325
  || (check.requiredPrerequisite === "isolated_postgres"
295
- && isolatedPostgresProvided(check.id, environment, postgresAdminConnection))
326
+ && isolatedPostgresProvided(check.id, environment, dockerFreeGrant(postgresAdminConnection)))
296
327
  || !this.dockerEngineProbe)
297
328
  return;
298
329
  const snapshot = await this.dockerEngineProbe.refresh(true);
@@ -317,28 +348,6 @@ export class PrePublicationValidator {
317
348
  await emit?.(validationEvent("prepublication_validation_failed", "unreferenced-exports", `New code is tested but never called: ${detail}`));
318
349
  pass.record({ checkId: "unreferenced-exports", exitCode: 1, command: "git", args: ["grep"], detail });
319
350
  }
320
- async changedPaths(worktreePath, signal, execution) {
321
- const baselineRevision = execution?.baselineRevision?.trim();
322
- const requests = [
323
- ["diff", "--name-only", "HEAD", "--"],
324
- ...(baselineRevision ? [["diff", "--name-only", `${baselineRevision}..HEAD`, "--"]] : []),
325
- ["status", "--porcelain=v1", "--untracked-files=all"],
326
- ];
327
- const paths = new Set();
328
- for (const args of requests) {
329
- const result = await this.runCommand("git", args, worktreePath, signal, execution);
330
- if (result.exitCode !== 0) {
331
- throw new ForgeFailureError("prepublication_validation_failed", `prepublication_validation_failed: unable to inventory changed paths: ${result.stderr ?? result.stdout ?? "git failed"}`, "bridge");
332
- }
333
- for (const line of `${result.stdout ?? ""}`.split(/\r?\n/u).filter(Boolean)) {
334
- const raw = args[0] === "status" ? line.slice(3).split(" -> ").at(-1) ?? "" : line;
335
- const normalized = raw.trim().replaceAll("\\", "/");
336
- if (normalized)
337
- paths.add(normalized);
338
- }
339
- }
340
- return [...paths];
341
- }
342
351
  async assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, execution) {
343
352
  const baselineRevision = execution?.baselineRevision?.trim();
344
353
  if (!baselineRevision)
@@ -435,27 +444,11 @@ export class PrePublicationValidator {
435
444
  }
436
445
  }
437
446
  }
438
- function environmentValue(environment, name) {
439
- return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
440
- ? environment?.[name]?.trim() ?? ""
441
- : process.env[name]?.trim() ?? "";
442
- }
443
- function isolatedPostgresProvided(checkId, environment, postgresAdminConnection) {
444
- if (checkId === "playwright-e2e") {
445
- const attemptId = environmentValue(environment, "FORGE_DISPATCH_ATTEMPT_ID");
446
- return (environmentValue(environment, "FORGE_E2E_OWNERSHIP_MODE") === "attempt"
447
- || /^[0-9a-f-]{36}$/iu.test(attemptId))
448
- && /^forge_attempt_[0-9a-f]{32}$/u.test(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_SCHEMA"))
449
- && path.isAbsolute(environmentValue(environment, "FORGE_ATTEMPT_DATABASE_READINESS_PATH"))
450
- // The attempt owns a database only once the Bridge's broker has issued it one.
451
- && environmentValue(environment, attemptDatabaseCapabilityEnvironment).length > 0;
452
- }
453
- return Boolean(postgresAdminConnection);
454
- }
455
447
  function validationExactSecrets(environment) {
456
448
  return [
457
- environment?.[hostRuntimeTestPostgresAdminEnvironment]?.trim() ?? "",
458
- environment?.[hostRuntimeLegacyTestPostgresEnvironment]?.trim() ?? "",
449
+ // The connection strings and their passwords: a test may print either.
450
+ ...attemptDatabaseCapabilitySecrets(environment?.[hostRuntimeTestPostgresAdminEnvironment]),
451
+ ...attemptDatabaseCapabilitySecrets(environment?.[hostRuntimeLegacyTestPostgresEnvironment]),
459
452
  environment?.[hostRuntimeTestPostgresProvisionerEnvironment]?.trim() ?? "",
460
453
  ...attemptDatabaseCapabilitySecrets(environment?.[attemptDatabaseCapabilityEnvironment]),
461
454
  ].filter((value, index, values) => value.length > 0 && values.indexOf(value) === index);
@@ -645,12 +638,16 @@ export async function loadValidationContract(worktreePath) {
645
638
  }
646
639
  return contract;
647
640
  }
648
- /** The affected .NET tests measure the attempt's change against its dispatch baseline (run-affected-dotnet-tests.mjs). */
649
- function withValidationBaseRevision(execution) {
650
- const baseline = execution?.baselineRevision?.trim();
651
- if (!baseline)
641
+ /** The affected .NET tests measure the attempt's change against its dispatch baseline and merge parent (run-affected-dotnet-tests.mjs). */
642
+ function withValidationRevisions(execution, mergeParent) {
643
+ const revisions = validationRevisionEnvironment(execution?.baselineRevision, mergeParent);
644
+ if (Object.keys(revisions).length === 0)
652
645
  return execution;
653
- return { ...execution, environment: { ...execution?.environment, FORGE_VALIDATION_BASE_REVISION: baseline } };
646
+ return { ...execution, environment: { ...execution?.environment, ...revisions } };
647
+ }
648
+ /** The execution with git reading history as committed (historyIntegrityEnvironment). */
649
+ function withHistoryIntegrity(execution) {
650
+ return { ...execution, environment: { ...execution?.environment, ...historyIntegrityEnvironment } };
654
651
  }
655
652
  function validationContractDigest(contract) {
656
653
  return createHash("sha256")
@@ -19,9 +19,10 @@ export declare const claudeHeadlessEnvironment: Readonly<Record<string, string>>
19
19
  export declare const claudeHeadlessDisallowedTools: readonly string[];
20
20
  /**
21
21
  * The Claude Code arguments that apply the restrictions: the tool deny list, and the environment
22
- * again as flag settings, which outrank a user's or repository's settings `env` block.
22
+ * again as flag settings, which outrank a user's or repository's settings `env` block. Other flag
23
+ * settings (`provider-user-config-isolation.ts`) share the one `--settings` value.
23
24
  */
24
- export declare function claudeHeadlessToolArgs(): readonly string[];
25
+ export declare function claudeHeadlessToolArgs(additionalSettings?: Readonly<Record<string, unknown>>): readonly string[];
25
26
  /**
26
27
  * The provider ended its turn while background work it started (a background subagent or
27
28
  * shell, a Monitor watch, a wakeup) was still live. Claude Code withholds the turn's terminal
@@ -40,12 +40,13 @@ export const claudeHeadlessDisallowedTools = Object.freeze([
40
40
  ]);
41
41
  /**
42
42
  * The Claude Code arguments that apply the restrictions: the tool deny list, and the environment
43
- * again as flag settings, which outrank a user's or repository's settings `env` block.
43
+ * again as flag settings, which outrank a user's or repository's settings `env` block. Other flag
44
+ * settings (`provider-user-config-isolation.ts`) share the one `--settings` value.
44
45
  */
45
- export function claudeHeadlessToolArgs() {
46
+ export function claudeHeadlessToolArgs(additionalSettings = {}) {
46
47
  return [
47
48
  "--disallowedTools", claudeHeadlessDisallowedTools.join(","),
48
- "--settings", JSON.stringify({ env: claudeHeadlessEnvironment }),
49
+ "--settings", JSON.stringify({ ...additionalSettings, env: claudeHeadlessEnvironment }),
49
50
  ];
50
51
  }
51
52
  /**
@@ -0,0 +1,7 @@
1
+ import type { RunOnceDispatchPacket } from "../session.types.js";
2
+ /**
3
+ * The branch an attempt publishes into: the pull request's target, else the requested base, else the
4
+ * repository's default branch. The lane prompts name it as the branch to merge or compare with, and the
5
+ * pre-publication gate verifies a merge parent against it, so both read it from here.
6
+ */
7
+ export declare function dispatchTargetBranch(dispatch: RunOnceDispatchPacket): string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The branch an attempt publishes into: the pull request's target, else the requested base, else the
3
+ * repository's default branch. The lane prompts name it as the branch to merge or compare with, and the
4
+ * pre-publication gate verifies a merge parent against it, so both read it from here.
5
+ */
6
+ export function dispatchTargetBranch(dispatch) {
7
+ return dispatch.pullRequest?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
8
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * A runner host can allow only one local .NET build or test at a time across everything that runs
3
+ * on it: Forge agents, the owner's own sessions and their tools. Parallel builds there exhaust
4
+ * memory and break each other's shared test output. The host's owner names the lock wrapper in the
5
+ * bridge's own environment; Forge passes it to every host-mode agent turn and Bridge Chat turn and
6
+ * tells the agent to run its .NET builds and tests through it. The rule reaches agents only from Forge, never from a
7
+ * user-level instruction file (provider-user-config-isolation.ts).
8
+ */
9
+ export declare const hostDotnetBuildLockVariable = "FORGE_HOST_DOTNET_BUILD_LOCK";
10
+ /** The host's .NET build lock wrapper, when the bridge's environment names one. */
11
+ export declare function hostDotnetBuildLock(environment?: NodeJS.ProcessEnv): string | null;
12
+ export declare function hostDotnetBuildLockEnvironment(environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
13
+ /**
14
+ * The runtime-context instruction for a host that names a .NET build lock, or an empty string.
15
+ * Session turns also hear that the commands Forge runs for them are scheduled by Forge; Bridge
16
+ * Chat turns have no Forge tools.
17
+ */
18
+ export declare function hostDotnetBuildLockInstruction(environment?: NodeJS.ProcessEnv, turn?: "session" | "chat"): string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A runner host can allow only one local .NET build or test at a time across everything that runs
3
+ * on it: Forge agents, the owner's own sessions and their tools. Parallel builds there exhaust
4
+ * memory and break each other's shared test output. The host's owner names the lock wrapper in the
5
+ * bridge's own environment; Forge passes it to every host-mode agent turn and Bridge Chat turn and
6
+ * tells the agent to run its .NET builds and tests through it. The rule reaches agents only from Forge, never from a
7
+ * user-level instruction file (provider-user-config-isolation.ts).
8
+ */
9
+ export const hostDotnetBuildLockVariable = "FORGE_HOST_DOTNET_BUILD_LOCK";
10
+ /** The host's .NET build lock wrapper, when the bridge's environment names one. */
11
+ export function hostDotnetBuildLock(environment = process.env) {
12
+ return environment[hostDotnetBuildLockVariable]?.trim() || null;
13
+ }
14
+ export function hostDotnetBuildLockEnvironment(environment = process.env) {
15
+ const lock = hostDotnetBuildLock(environment);
16
+ return lock ? { [hostDotnetBuildLockVariable]: lock } : {};
17
+ }
18
+ /**
19
+ * The runtime-context instruction for a host that names a .NET build lock, or an empty string.
20
+ * Session turns also hear that the commands Forge runs for them are scheduled by Forge; Bridge
21
+ * Chat turns have no Forge tools.
22
+ */
23
+ export function hostDotnetBuildLockInstruction(environment = process.env, turn = "session") {
24
+ if (!hostDotnetBuildLock(environment))
25
+ return "";
26
+ const forgeScheduled = turn === "session"
27
+ ? " Commands Forge runs for you (`forge.start_managed_verification`, pre-publication checks) are scheduled by Forge."
28
+ : "";
29
+ return `\n- This host runs one local .NET build or test at a time. Run every \`dotnet build\` and \`dotnet test\` you start yourself through the host lock in \`${hostDotnetBuildLockVariable}\`, for example \`"$${hostDotnetBuildLockVariable}" dotnet test <project> --filter <tests>\`. It waits while another build or test holds the lock and exits 75 if the wait times out; wait and retry rather than running without it.${forgeScheduled}`;
30
+ }
@@ -0,0 +1,83 @@
1
+ import type { GitClient } from "../../shared/git/git.js";
2
+ /** The failure code of every review session that changed or published something it must not. */
3
+ export declare const prReviewGuardrailViolationCode = "guardrail_violation";
4
+ /**
5
+ * The primary publication control for a review-only session, for every provider: the session's
6
+ * environment holds no way to authenticate to a git host and no way to push. Tool deny rules and
7
+ * command shims are a second layer on top of this one.
8
+ *
9
+ * - git reads an empty global configuration (GIT_CONFIG_GLOBAL) and no system configuration
10
+ * (GIT_CONFIG_NOSYSTEM), so no user- or machine-wide credential helper, `url.insteadOf` or token
11
+ * header applies.
12
+ * - Command-scope configuration (GIT_CONFIG_COUNT) clears `credential.helper` (an empty value resets
13
+ * the helper list, including one from the repository's own config), disables every transport
14
+ * (`protocol.allow=never`) and points each remote's push URL at a transport that does not exist.
15
+ * - The GitHub CLI reads an empty configuration directory (GH_CONFIG_DIR), so it has no stored login.
16
+ * - GitHub tokens, Git Credential Manager settings, askpass programs and SSH agent sockets are removed.
17
+ *
18
+ * HOME is not changed: the provider signs in from its own configuration under it. What the environment
19
+ * cannot take away is anything the bridge user can read: the operating system's credential store
20
+ * (Windows Credential Manager, the macOS keychain), which a session can still reach by naming a helper
21
+ * explicitly (`git -c credential.helper=...`), and credential files under HOME. The tool deny rules
22
+ * refuse the commands they recognise (Claude). After the session, Forge compares the review's local refs
23
+ * and, on a host placement, the pull request branch's head on origin (read with the bridge's own git,
24
+ * outside the session's environment) with their values before it, and fails a session that moved them.
25
+ * A push to another branch or repository, or a credential the session read and sent elsewhere, is not
26
+ * detected. That is why a review runs only in the Docker sandbox unless the runner's owner opted in
27
+ * (session/pr-review-placement.ts): none of this is a boundary on a plain host.
28
+ */
29
+ export interface PrReviewCredentialIsolation {
30
+ readonly directory: string;
31
+ readonly env: Readonly<Record<string, string>>;
32
+ cleanup(): Promise<void>;
33
+ }
34
+ /** A push URL no git transport handles, so a push fails before any network or credential lookup. */
35
+ export declare const prReviewDisabledPushUrl = "forge-review-push-disabled://publication-is-not-allowed";
36
+ export interface PrReviewCredentialIsolationOptions {
37
+ /** Directories git must trust although the global configuration that may have listed them is empty. */
38
+ readonly safeDirectories?: readonly string[];
39
+ /** Remote names whose push URL is disabled. */
40
+ readonly remotes?: readonly string[];
41
+ readonly tempRoot?: string;
42
+ }
43
+ /** The git and gh environment for a review session whose isolation directory is `directory`. */
44
+ export declare function prReviewIsolatedGitEnvironment(directory: string, options?: Pick<PrReviewCredentialIsolationOptions, "safeDirectories" | "remotes">): Readonly<Record<string, string>>;
45
+ /** Creates the empty global git configuration and gh configuration directory for one session. */
46
+ export declare function preparePrReviewCredentialIsolation(options?: PrReviewCredentialIsolationOptions): Promise<PrReviewCredentialIsolation>;
47
+ /** The repository's remote names, read before the session starts. */
48
+ export declare function listRemotes(git: GitClient, worktreePath: string): Promise<readonly string[]>;
49
+ export interface ReviewRefSnapshot {
50
+ readonly refs: ReadonlyMap<string, string>;
51
+ }
52
+ /**
53
+ * The refs a review session could move: the pull request's source branch (local and every
54
+ * remote-tracking copy) and the namespaces only history-rewriting or bookkeeping commands write
55
+ * (notes, replace, stash, bisect, per-worktree refs, filter-branch backups). Other branches and tags
56
+ * are left out on purpose: the repository is shared with Forge's other sessions, whose fetches move
57
+ * them while this review runs.
58
+ */
59
+ export declare function reviewRefPatterns(sourceBranch: string | undefined, remotes: readonly string[]): readonly string[];
60
+ export declare function snapshotReviewRefs(git: GitClient, worktreePath: string, patterns: readonly string[]): Promise<ReviewRefSnapshot>;
61
+ /** Throws `guardrail_violation` when a ref in the review's scope was created, moved or deleted. */
62
+ export declare function assertReviewRefsUnchanged(git: GitClient, worktreePath: string, patterns: readonly string[], baseline: ReviewRefSnapshot): Promise<void>;
63
+ /** The pull request branch's head on origin before the session; null when the review runs in Docker. */
64
+ export interface ReviewRemoteHead {
65
+ readonly branch: string;
66
+ readonly sha: string;
67
+ }
68
+ /**
69
+ * Reads the pull request branch's head on origin with the bridge's own git environment, never the
70
+ * session's. In the Docker sandbox there is nothing to read: the container's workspace has no remote
71
+ * and no credential, so the session has nowhere to push. On a host placement a read that fails, or a
72
+ * dispatch without the branch, fails closed: a moved branch could not be detected.
73
+ */
74
+ export declare function readReviewRemoteHead(git: GitClient, worktreePath: string, dispatch: {
75
+ readonly pullRequest?: {
76
+ readonly sourceBranch?: string;
77
+ } | null;
78
+ readonly sandbox?: {
79
+ readonly executionMode?: string;
80
+ } | null;
81
+ }): Promise<ReviewRemoteHead | null>;
82
+ /** Throws `guardrail_violation` when the pull request branch on origin moved, appeared or vanished during the session. */
83
+ export declare function assertReviewRemoteHeadUnchanged(git: GitClient, worktreePath: string, before: ReviewRemoteHead | null): Promise<void>;
@@ -0,0 +1,144 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { ForgeFailureError } from "../session.types.js";
5
+ /** The failure code of every review session that changed or published something it must not. */
6
+ export const prReviewGuardrailViolationCode = "guardrail_violation";
7
+ /** A push URL no git transport handles, so a push fails before any network or credential lookup. */
8
+ export const prReviewDisabledPushUrl = "forge-review-push-disabled://publication-is-not-allowed";
9
+ /** The git and gh environment for a review session whose isolation directory is `directory`. */
10
+ export function prReviewIsolatedGitEnvironment(directory, options = {}) {
11
+ const entries = [
12
+ ["credential.helper", ""],
13
+ ["credential.interactive", "false"],
14
+ ["protocol.allow", "never"],
15
+ ["http.extraHeader", ""],
16
+ ["core.askPass", ""],
17
+ ...(options.remotes ?? ["origin"]).map((remote) => [`remote.${remote}.pushurl`, prReviewDisabledPushUrl]),
18
+ ...(options.safeDirectories ?? []).map((directory) => ["safe.directory", directory.replaceAll("\\", "/")]),
19
+ ];
20
+ const env = {
21
+ GIT_CONFIG_GLOBAL: path.join(directory, "gitconfig"),
22
+ GIT_CONFIG_NOSYSTEM: "1",
23
+ GIT_CONFIG_COUNT: String(entries.length),
24
+ GIT_TERMINAL_PROMPT: "0",
25
+ GIT_ASKPASS: "",
26
+ SSH_ASKPASS: "",
27
+ GCM_INTERACTIVE: "never",
28
+ GH_CONFIG_DIR: path.join(directory, "gh"),
29
+ GH_PROMPT_DISABLED: "1",
30
+ GH_NO_UPDATE_NOTIFIER: "1",
31
+ };
32
+ entries.forEach(([key, value], index) => {
33
+ env[`GIT_CONFIG_KEY_${index}`] = key;
34
+ env[`GIT_CONFIG_VALUE_${index}`] = value;
35
+ });
36
+ return env;
37
+ }
38
+ /** Creates the empty global git configuration and gh configuration directory for one session. */
39
+ export async function preparePrReviewCredentialIsolation(options = {}) {
40
+ const directory = await fs.mkdtemp(path.join(options.tempRoot ?? os.tmpdir(), "forge-pr-review-git-"));
41
+ try {
42
+ await fs.writeFile(path.join(directory, "gitconfig"), "", "utf8");
43
+ await fs.mkdir(path.join(directory, "gh"));
44
+ }
45
+ catch (error) {
46
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);
47
+ throw error;
48
+ }
49
+ return {
50
+ directory,
51
+ env: prReviewIsolatedGitEnvironment(directory, options),
52
+ cleanup: async () => {
53
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);
54
+ },
55
+ };
56
+ }
57
+ /** The repository's remote names, read before the session starts. */
58
+ export async function listRemotes(git, worktreePath) {
59
+ const output = await git.run(worktreePath, ["remote"]).catch(() => "");
60
+ const remotes = output.split(/\r?\n/u).map((line) => line.trim()).filter((line) => /^[A-Za-z0-9._/-]+$/u.test(line));
61
+ return remotes.length > 0 ? remotes : ["origin"];
62
+ }
63
+ /**
64
+ * The refs a review session could move: the pull request's source branch (local and every
65
+ * remote-tracking copy) and the namespaces only history-rewriting or bookkeeping commands write
66
+ * (notes, replace, stash, bisect, per-worktree refs, filter-branch backups). Other branches and tags
67
+ * are left out on purpose: the repository is shared with Forge's other sessions, whose fetches move
68
+ * them while this review runs.
69
+ */
70
+ export function reviewRefPatterns(sourceBranch, remotes) {
71
+ const branch = sourceBranch?.trim();
72
+ return [
73
+ ...(branch ? [`refs/heads/${branch}`, ...remotes.map((remote) => `refs/remotes/${remote}/${branch}`)] : []),
74
+ "refs/notes",
75
+ "refs/replace",
76
+ "refs/stash",
77
+ "refs/bisect",
78
+ "refs/worktree",
79
+ "refs/original",
80
+ ];
81
+ }
82
+ export async function snapshotReviewRefs(git, worktreePath, patterns) {
83
+ const output = await git.run(worktreePath, ["for-each-ref", "--format=%(refname) %(objectname)", ...patterns]);
84
+ const refs = new Map();
85
+ for (const line of output.split(/\r?\n/u)) {
86
+ const separator = line.lastIndexOf(" ");
87
+ if (separator > 0) {
88
+ refs.set(line.slice(0, separator), line.slice(separator + 1).trim().toLowerCase());
89
+ }
90
+ }
91
+ return { refs };
92
+ }
93
+ /** Throws `guardrail_violation` when a ref in the review's scope was created, moved or deleted. */
94
+ export async function assertReviewRefsUnchanged(git, worktreePath, patterns, baseline) {
95
+ const after = await snapshotReviewRefs(git, worktreePath, patterns);
96
+ const problems = [];
97
+ for (const [ref, sha] of after.refs) {
98
+ const before = baseline.refs.get(ref);
99
+ if (before === undefined)
100
+ problems.push(`${ref} was created`);
101
+ else if (before !== sha)
102
+ problems.push(`${ref} moved from ${before.slice(0, 12)} to ${sha.slice(0, 12)}`);
103
+ }
104
+ for (const ref of baseline.refs.keys()) {
105
+ if (!after.refs.has(ref))
106
+ problems.push(`${ref} was deleted`);
107
+ }
108
+ if (problems.length > 0) {
109
+ throw new ForgeFailureError(prReviewGuardrailViolationCode, `guardrail_violation: the review-only session changed git refs (${problems.slice(0, 10).join("; ")}). Forge discards the review and publishes nothing.`, "bridge");
110
+ }
111
+ }
112
+ /**
113
+ * Reads the pull request branch's head on origin with the bridge's own git environment, never the
114
+ * session's. In the Docker sandbox there is nothing to read: the container's workspace has no remote
115
+ * and no credential, so the session has nowhere to push. On a host placement a read that fails, or a
116
+ * dispatch without the branch, fails closed: a moved branch could not be detected.
117
+ */
118
+ export async function readReviewRemoteHead(git, worktreePath, dispatch) {
119
+ if (dispatch.sandbox?.executionMode === "docker") {
120
+ return null;
121
+ }
122
+ const branch = dispatch.pullRequest?.sourceBranch?.trim() ?? "";
123
+ const unreadable = (detail, cause) => new ForgeFailureError("pr_review_remote_head_unreadable", `pr_review_remote_head_unreadable: ${detail}, so a push from the review could not be detected. Forge did not record the review.`, "bridge", cause === undefined ? undefined : { cause });
124
+ if (!branch) {
125
+ throw unreadable("the review dispatch did not name the pull request branch");
126
+ }
127
+ const output = await git.run(worktreePath, ["ls-remote", "--heads", "origin", `refs/heads/${branch}`])
128
+ .catch((error) => { throw unreadable(`origin could not be read for ${branch}`, error); });
129
+ const sha = output.split(/\r?\n/u)
130
+ .map((line) => line.trim().split(/\s+/u))
131
+ .find(([, ref]) => ref === `refs/heads/${branch}`)?.[0]?.toLowerCase() ?? "";
132
+ return { branch, sha };
133
+ }
134
+ /** Throws `guardrail_violation` when the pull request branch on origin moved, appeared or vanished during the session. */
135
+ export async function assertReviewRemoteHeadUnchanged(git, worktreePath, before) {
136
+ if (!before) {
137
+ return;
138
+ }
139
+ const after = await readReviewRemoteHead(git, worktreePath, { pullRequest: { sourceBranch: before.branch } });
140
+ if (after?.sha !== before.sha) {
141
+ const describe = (sha) => (sha ? sha.slice(0, 12) : "absent");
142
+ throw new ForgeFailureError(prReviewGuardrailViolationCode, `guardrail_violation: the pull request branch ${before.branch} on origin moved from ${describe(before.sha)} to ${describe(after?.sha)} while the review-only session ran. Forge discards the review and publishes nothing.`, "bridge");
143
+ }
144
+ }