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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +41 -3
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. package/package.json +1 -1
@@ -0,0 +1,91 @@
1
+ import { failureFactsForCode, failureResult, } from "./session.types.js";
2
+ /**
3
+ * Where a Forge PR review may run. A review reads pull request code an author controls, and the only
4
+ * operating-system isolation this bridge enforces is its Docker sandbox: a container with no git
5
+ * credential, no remote and no host home directory. On a plain host the provider runs as the
6
+ * bridge's user, beside that user's git credentials and provider sign-in, and the review guardrails
7
+ * (credential-free git environment, tool deny rules, command shims, the post-run ref and remote-head
8
+ * checks) are defence in depth, not a boundary. So a review placed on the host is refused before any
9
+ * provider starts unless the runner's owner opted in with `allowUnsandboxedPrReview: true` in
10
+ * bridge.json, accepting that risk.
11
+ */
12
+ export const prReviewUnsandboxedHostCode = "pr_review.unsandboxed_host";
13
+ /**
14
+ * A review placed in this bridge's Docker sandbox for a project whose sandbox contract it cannot read or build:
15
+ * refused before any provider starts, and never retried on this runner (a capacity wait would only expire).
16
+ */
17
+ export const prReviewSandboxUnavailableCode = "pr_review.sandbox_unavailable";
18
+ /** The execution facility a runner advertises when its owner opted in to host-placed reviews. */
19
+ export const prReviewUnsandboxedHostFacility = "pr_review_unsandboxed_host";
20
+ /** The warning a host-placed review carries when the runner's owner opted in. */
21
+ export const prReviewUnsandboxedHostWarningEvent = "pr_review_unsandboxed_host_warning";
22
+ /** A dispatch for the review-only pr_review session, by role, lane or cycle kind. */
23
+ export function isPrReviewDispatch(dispatch) {
24
+ return [dispatch.execution.role, dispatch.execution.lane, dispatch.cycleRun.kind]
25
+ .some((value) => (value ?? "").trim().toLowerCase() === "pr_review");
26
+ }
27
+ /** The pull request head a review dispatch reads, lowercased, or null for any other dispatch. */
28
+ export function prReviewDispatchHeadSha(dispatch) {
29
+ if (!isPrReviewDispatch(dispatch)) {
30
+ return null;
31
+ }
32
+ return (dispatch.prReview?.headSha || dispatch.pullRequest?.headSha || "").trim().toLowerCase() || null;
33
+ }
34
+ function placedInDocker(dispatch) {
35
+ return dispatch.sandbox?.executionMode === "docker";
36
+ }
37
+ /** Why this bridge refuses the dispatch, or null: a review placed outside Docker without the opt-in. */
38
+ export function prReviewPlacementRefusal(dispatch, allowUnsandboxedPrReview) {
39
+ if (!isPrReviewDispatch(dispatch) || placedInDocker(dispatch) || allowUnsandboxedPrReview === true) {
40
+ return null;
41
+ }
42
+ return `${prReviewUnsandboxedHostCode}: this Forge PR review was placed on the bridge host, where the provider would read `
43
+ + "author-controlled pull request code with the bridge user's credentials in reach. This bridge runs reviews only in its "
44
+ + "Docker sandbox. Its owner can accept the risk with \"allowUnsandboxedPrReview\": true in bridge.json.";
45
+ }
46
+ /** The warning for a review that runs on the host because the runner's owner opted in, or null. */
47
+ export function prReviewUnsandboxedHostWarning(dispatch, allowUnsandboxedPrReview) {
48
+ if (!isPrReviewDispatch(dispatch) || placedInDocker(dispatch) || allowUnsandboxedPrReview !== true) {
49
+ return null;
50
+ }
51
+ return "Warning: this Forge PR review ran on the bridge host without OS-level isolation, because the runner's owner set "
52
+ + "\"allowUnsandboxedPrReview\": true in bridge.json. The provider read author-controlled code with the bridge user's "
53
+ + "credentials in reach; only Forge's review guardrails stood between them.";
54
+ }
55
+ /** The terminal failure for a refused review (see {@link prReviewPlacementRefusal}), or null. */
56
+ export function prReviewPlacementRefusalResult(dispatch, allowUnsandboxedPrReview) {
57
+ const refusal = prReviewPlacementRefusal(dispatch, allowUnsandboxedPrReview);
58
+ return refusal
59
+ ? failureResult(refusal, [{ role: "runner", kind: "error", content: refusal, eventType: prReviewUnsandboxedHostCode }], failureFactsForCode(prReviewUnsandboxedHostCode))
60
+ : null;
61
+ }
62
+ /**
63
+ * Set by the server-local runner on a run-once whose Forge PR review it admitted on its host (in its container
64
+ * sandbox, or because the runner opted in to host reviews). Nothing else sets it.
65
+ */
66
+ export const prReviewHostAdmittedEnv = "FORGE_PR_REVIEW_HOST_ADMITTED";
67
+ /**
68
+ * forge-bridge run-once (which the server-local runner launches): a Forge PR review placed outside Docker runs
69
+ * only when the server-local runner admitted it on this host; any other is refused before a provider starts.
70
+ */
71
+ export async function runOnceWithReviewPlacement(dispatch, run, env = process.env) {
72
+ return prReviewPlacementRefusalResult(dispatch, env[prReviewHostAdmittedEnv] === "1") ?? await run(dispatch);
73
+ }
74
+ /** The execution facilities that tell Forge this runner's owner opted in to host-placed reviews. */
75
+ export function prReviewExecutionFacilities(allowUnsandboxedPrReview) {
76
+ return allowUnsandboxedPrReview === true ? [prReviewUnsandboxedHostFacility] : [];
77
+ }
78
+ /**
79
+ * Runs the dispatch; a review that runs on the host by the owner's opt-in is logged, announced as a
80
+ * session event and reported in the result summary as a warning.
81
+ */
82
+ export async function runWithUnsandboxedReviewWarning(dispatch, allowUnsandboxedPrReview, sink, log, run) {
83
+ const warning = prReviewUnsandboxedHostWarning(dispatch, allowUnsandboxedPrReview);
84
+ if (!warning) {
85
+ return await run();
86
+ }
87
+ log(warning);
88
+ await sink.emit({ role: "runner", kind: "checkpoint", content: warning, eventType: prReviewUnsandboxedHostWarningEvent });
89
+ const result = await run();
90
+ return { ...result, summary: `${result.summary} ${warning}` };
91
+ }
@@ -0,0 +1,62 @@
1
+ import { type RunnerDispatchEvent } from "./session.types.js";
2
+ export { findUnreferencedNewExports } from "./unreferenced-exports.js";
3
+ export type ChangeSetGit = (args: readonly string[]) => Promise<{
4
+ exitCode: number;
5
+ stdout?: string;
6
+ stderr?: string;
7
+ }>;
8
+ /**
9
+ * Git reads history as it was committed. The agent could otherwise plant a replace ref
10
+ * (`git replace <target tip> <fake>`) or a graft that rewrites what the merge parent's tree is and
11
+ * whose ancestor it is. The bridge's own git calls in the pass, and the affected .NET run that measures
12
+ * against these revisions, run with it (the sandbox import does the same, sandbox/runtime.ts). Other
13
+ * check steps do not: their suites may make replace refs or grafts of their own in throwaway repos. An empty graft file is no grafts; /dev/null is one on every
14
+ * platform Git runs on (Git for Windows maps it to NUL), and nothing can be written into it.
15
+ */
16
+ export declare const historyIntegrityEnvironment: Readonly<Record<string, string>>;
17
+ /**
18
+ * The pass's change set: the verified merge parent it measures against (null when the attempt makes no
19
+ * merge, or merges something its target branch's CI did not validate), and the changed paths that select
20
+ * its checks. Emits whether and how a merge scoped the pass.
21
+ */
22
+ export declare function passChangeSet(git: ChangeSetGit, execution: {
23
+ readonly baselineRevision?: string;
24
+ readonly targetBranch?: string;
25
+ } | undefined, emit?: (event: RunnerDispatchEvent) => Promise<void>): Promise<{
26
+ readonly mergeParent: string | null;
27
+ readonly changedPaths: readonly string[];
28
+ }>;
29
+ /**
30
+ * The other parent of a merge the attempt makes: MERGE_HEAD while a merge is in progress, or the second
31
+ * parent of a merge commit HEAD made since the dispatch baseline. Null when the attempt makes no merge,
32
+ * including a merge commit that was already HEAD at dispatch.
33
+ */
34
+ export declare function attemptMergeParent(git: ChangeSetGit, baselineRevision: string | undefined): Promise<string | null>;
35
+ /** A merge parent the pass may scope to, or why it may not. */
36
+ export type MergeScope = {
37
+ readonly mergeParent: string;
38
+ readonly targetRef: string;
39
+ } | {
40
+ readonly mergeParent: null;
41
+ readonly unscopedReason: string;
42
+ };
43
+ /**
44
+ * Scopes the pass to a merge parent only when the target branch's CI validated it: the parent is the
45
+ * target's tip on origin, or an ancestor of it. The agent controls the merge and every local ref (it can
46
+ * rewrite refs/remotes/origin/<target>, which a host worktree shares with the main repository), so the
47
+ * bridge fetches the target into a ref of its own for this pass and deletes it afterwards. A parent
48
+ * anywhere else (a scratch branch holding the attempt's own work), or a fetch that fails (a Docker
49
+ * sandbox workspace has no origin), scopes nothing.
50
+ */
51
+ export declare function verifiedMergeScope(git: ChangeSetGit, mergeParent: string, targetBranch: string | undefined, validationRef?: string): Promise<MergeScope>;
52
+ /**
53
+ * The paths the attempt changed: uncommitted, committed since the baseline, and untracked. With a
54
+ * verified merge parent, what the merged head changes over that parent, and the untracked paths.
55
+ */
56
+ export declare function changedPathInventory(git: ChangeSetGit, baselineRevision: string | undefined, mergeParent: string | null): Promise<readonly string[]>;
57
+ /**
58
+ * The step environment the affected .NET tests read (scripts/run-affected-dotnet-tests.mjs): the dispatch
59
+ * baseline, and the verified merge parent they measure against instead when there is one. The validator
60
+ * adds historyIntegrityEnvironment to that check's steps only.
61
+ */
62
+ export declare function validationRevisionEnvironment(baselineRevision: string | undefined, mergeParent: string | null): Readonly<Record<string, string>>;
@@ -0,0 +1,166 @@
1
+ // What a pre-publication pass validates: the paths the attempt changed, which select the CI parity
2
+ // checks, and the revisions the affected .NET tests measure against. When the attempt makes a merge
3
+ // (a conflict repair merging the target branch in) and the merge's other parent is on the target
4
+ // branch, the pass measures the merged head against that parent, as CI measures a pull request
5
+ // against its base: what the target branch brought matches it and was validated by its CI, while the
6
+ // Story's own changes and every conflict resolution that is not the target's version still count.
7
+ // The merged head's integration is CI's job on the pushed head.
8
+ import { randomUUID } from "node:crypto";
9
+ import { validationEvent } from "./pre-publication-pass.js";
10
+ import { ForgeFailureError } from "./session.types.js";
11
+ // The new exports of the same change; the pass checks them alongside the changed paths.
12
+ export { findUnreferencedNewExports } from "./unreferenced-exports.js";
13
+ /**
14
+ * Git reads history as it was committed. The agent could otherwise plant a replace ref
15
+ * (`git replace <target tip> <fake>`) or a graft that rewrites what the merge parent's tree is and
16
+ * whose ancestor it is. The bridge's own git calls in the pass, and the affected .NET run that measures
17
+ * against these revisions, run with it (the sandbox import does the same, sandbox/runtime.ts). Other
18
+ * check steps do not: their suites may make replace refs or grafts of their own in throwaway repos. An empty graft file is no grafts; /dev/null is one on every
19
+ * platform Git runs on (Git for Windows maps it to NUL), and nothing can be written into it.
20
+ */
21
+ export const historyIntegrityEnvironment = {
22
+ GIT_NO_REPLACE_OBJECTS: "1",
23
+ GIT_GRAFT_FILE: "/dev/null",
24
+ };
25
+ const commitSha = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/iu;
26
+ // A branch name the bridge can fetch by refspec; anything else scopes nothing.
27
+ const branchName = /^(?!-)(?!.*\.\.)[A-Za-z0-9._/-]+$/u;
28
+ /**
29
+ * The pass's change set: the verified merge parent it measures against (null when the attempt makes no
30
+ * merge, or merges something its target branch's CI did not validate), and the changed paths that select
31
+ * its checks. Emits whether and how a merge scoped the pass.
32
+ */
33
+ export async function passChangeSet(git, execution, emit) {
34
+ const attempted = await attemptMergeParent(git, execution?.baselineRevision);
35
+ const scope = attempted === null ? null : await verifiedMergeScope(git, attempted, execution?.targetBranch);
36
+ if (scope !== null && scope.mergeParent === null) {
37
+ await emit?.(validationEvent("prepublication_validation_merge_unscoped", "validation-contract", `This attempt merges ${attempted}, but ${scope.unscopedReason}: every path the attempt changed selects checks.`, { mergeParent: attempted, reason: scope.unscopedReason }));
38
+ }
39
+ const mergeParent = scope?.mergeParent ?? null;
40
+ const changedPaths = await changedPathInventory(git, execution?.baselineRevision, mergeParent);
41
+ if (scope !== null && scope.mergeParent !== null) {
42
+ // A merged head that matches the parent selects nothing; say so rather than pass silently.
43
+ await emit?.(changedPaths.length === 0
44
+ ? validationEvent("prepublication_validation_merge_scope_empty", "validation-contract", `This attempt merges ${scope.mergeParent} from ${scope.targetRef}, and its merged head matches it: no check is selected; CI validates the merged head.`, { severity: "warning", mergeParent: scope.mergeParent, targetRef: scope.targetRef })
45
+ : validationEvent("prepublication_validation_merge_scoped", "validation-contract", `This attempt merges ${scope.mergeParent} from ${scope.targetRef}: checks are selected by the ${changedPaths.length} path(s) the merged head changes over it; CI validates the merged head.`, { mergeParent: scope.mergeParent, targetRef: scope.targetRef }));
46
+ }
47
+ return { mergeParent, changedPaths };
48
+ }
49
+ /**
50
+ * The other parent of a merge the attempt makes: MERGE_HEAD while a merge is in progress, or the second
51
+ * parent of a merge commit HEAD made since the dispatch baseline. Null when the attempt makes no merge,
52
+ * including a merge commit that was already HEAD at dispatch.
53
+ */
54
+ export async function attemptMergeParent(git, baselineRevision) {
55
+ const merging = await resolveCommit(git, "MERGE_HEAD");
56
+ if (merging)
57
+ return merging;
58
+ const baseline = baselineRevision?.trim();
59
+ if (!baseline)
60
+ return null;
61
+ const secondParent = await resolveCommit(git, "HEAD^2");
62
+ if (!secondParent)
63
+ return null;
64
+ const head = await resolveCommit(git, "HEAD");
65
+ const base = await resolveCommit(git, baseline);
66
+ return head !== null && base !== null && head !== base ? secondParent : null;
67
+ }
68
+ /**
69
+ * Scopes the pass to a merge parent only when the target branch's CI validated it: the parent is the
70
+ * target's tip on origin, or an ancestor of it. The agent controls the merge and every local ref (it can
71
+ * rewrite refs/remotes/origin/<target>, which a host worktree shares with the main repository), so the
72
+ * bridge fetches the target into a ref of its own for this pass and deletes it afterwards. A parent
73
+ * anywhere else (a scratch branch holding the attempt's own work), or a fetch that fails (a Docker
74
+ * sandbox workspace has no origin), scopes nothing.
75
+ */
76
+ export async function verifiedMergeScope(git, mergeParent, targetBranch, validationRef = `refs/forge/validation-target/${randomUUID()}`) {
77
+ const target = targetBranch?.trim() ?? "";
78
+ if (!target)
79
+ return { mergeParent: null, unscopedReason: "the dispatch names no target branch" };
80
+ if (commitSha.test(target))
81
+ return await scopeToTip(git, mergeParent, target, target);
82
+ const branch = target.replace(/^refs\/heads\//u, "");
83
+ if (!branchName.test(branch))
84
+ return { mergeParent: null, unscopedReason: `target branch ${target} is not a branch name` };
85
+ const targetRef = `origin/${branch}`;
86
+ try {
87
+ // An empty --refmap keeps the fetch from also moving refs/remotes/origin/<target>: it writes only its
88
+ // own ref. The fetch is inside the try, so an aborted fetch that already wrote the ref still deletes it.
89
+ const fetched = await git(["fetch", "--no-tags", "--no-write-fetch-head", "--refmap=", "--quiet", "origin",
90
+ `+refs/heads/${branch}:${validationRef}`]);
91
+ if (fetched.exitCode !== 0)
92
+ return { mergeParent: null, unscopedReason: `the bridge could not fetch ${branch} from origin` };
93
+ return await scopeToTip(git, mergeParent, validationRef, targetRef);
94
+ }
95
+ finally {
96
+ // Forge leaves nothing behind: the ref is this pass's alone.
97
+ await git(["update-ref", "-d", validationRef]);
98
+ }
99
+ }
100
+ async function scopeToTip(git, mergeParent, revision, targetRef) {
101
+ const tip = await resolveCommit(git, revision);
102
+ if (tip === null)
103
+ return { mergeParent: null, unscopedReason: `${targetRef} is not in this checkout` };
104
+ if (tip === mergeParent)
105
+ return { mergeParent, targetRef };
106
+ const ancestor = await git(["merge-base", "--is-ancestor", mergeParent, tip]);
107
+ return ancestor.exitCode === 0
108
+ ? { mergeParent, targetRef }
109
+ : { mergeParent: null, unscopedReason: `${mergeParent} is not on ${targetRef}` };
110
+ }
111
+ /**
112
+ * The paths the attempt changed: uncommitted, committed since the baseline, and untracked. With a
113
+ * verified merge parent, what the merged head changes over that parent, and the untracked paths.
114
+ */
115
+ export async function changedPathInventory(git, baselineRevision, mergeParent) {
116
+ const baseline = mergeParent === null ? baselineRevision?.trim() : undefined;
117
+ const paths = new Set();
118
+ if (mergeParent !== null) {
119
+ // Renames count as a deletion plus an addition, so both sides of one count.
120
+ for (const line of await gitLines(git, ["diff", "--name-only", "--no-renames", mergeParent, "--"]))
121
+ paths.add(normalizedPath(line));
122
+ }
123
+ else {
124
+ for (const line of await gitLines(git, ["diff", "--name-only", "HEAD", "--"]))
125
+ paths.add(normalizedPath(line));
126
+ }
127
+ if (baseline) {
128
+ for (const line of await gitLines(git, ["diff", "--name-only", `${baseline}..HEAD`, "--"]))
129
+ paths.add(normalizedPath(line));
130
+ }
131
+ for (const line of await gitLines(git, ["status", "--porcelain=v1", "--untracked-files=all"])) {
132
+ // Against a merge parent, the tracked paths are already measured; only the untracked ones add.
133
+ if (mergeParent !== null && !line.startsWith("??"))
134
+ continue;
135
+ paths.add(normalizedPath(line.slice(3).split(" -> ").at(-1) ?? ""));
136
+ }
137
+ paths.delete("");
138
+ return [...paths];
139
+ }
140
+ /**
141
+ * The step environment the affected .NET tests read (scripts/run-affected-dotnet-tests.mjs): the dispatch
142
+ * baseline, and the verified merge parent they measure against instead when there is one. The validator
143
+ * adds historyIntegrityEnvironment to that check's steps only.
144
+ */
145
+ export function validationRevisionEnvironment(baselineRevision, mergeParent) {
146
+ const baseline = baselineRevision?.trim();
147
+ return {
148
+ ...(baseline ? { FORGE_VALIDATION_BASE_REVISION: baseline } : {}),
149
+ ...(mergeParent ? { FORGE_VALIDATION_MERGE_PARENT_REVISION: mergeParent } : {}),
150
+ };
151
+ }
152
+ async function resolveCommit(git, revision) {
153
+ const result = await git(["rev-parse", "-q", "--verify", `${revision}^{commit}`]);
154
+ const sha = `${result.stdout ?? ""}`.trim();
155
+ return result.exitCode === 0 && commitSha.test(sha) ? sha.toLowerCase() : null;
156
+ }
157
+ async function gitLines(git, args) {
158
+ const result = await git(args);
159
+ if (result.exitCode !== 0) {
160
+ throw new ForgeFailureError("prepublication_validation_failed", `prepublication_validation_failed: unable to inventory changed paths: ${result.stderr ?? result.stdout ?? "git failed"}`, "bridge");
161
+ }
162
+ return `${result.stdout ?? ""}`.split(/\r?\n/u).filter(Boolean);
163
+ }
164
+ function normalizedPath(raw) {
165
+ return raw.trim().replaceAll("\\", "/");
166
+ }
@@ -1,7 +1,7 @@
1
1
  import { monotonicNowMs } from "../shared/time/monotonic.js";
2
2
  import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
3
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
4
- import { retentionFor, returnHostLoadToken } from "../runtime/host-load-step-run.js";
4
+ import { orderedWaitReports, retentionFor, returnHostLoadToken } from "../runtime/host-load-step-run.js";
5
5
  import { classifyValidationStep } from "../runtime/host-load-step-class.js";
6
6
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
7
7
  /**
@@ -23,6 +23,8 @@ export async function runHostGovernedValidationStep(gate, step, run) {
23
23
  await step.emit?.({ role: "runner", kind, content, eventType, data: JSON.stringify({ ...base, ...data }) })
24
24
  .catch(() => undefined);
25
25
  };
26
+ // Every waiting event lands before the admitted or failed one that follows it.
27
+ const reports = orderedWaitReports(async (decision) => await emit("prepublication_host_capacity_waiting", `Pre-publication step '${step.checkId}' (${stepClass}) is waiting for host capacity: ${decision.detail}`, { status: "waiting_for_host_capacity", reason: decision.reason, cpuCores: cost.cpuCores, memoryBytes: cost.memoryBytes }));
26
28
  let admission;
27
29
  try {
28
30
  admission = await gate.acquire({
@@ -31,12 +33,11 @@ export async function runHostGovernedValidationStep(gate, step, run) {
31
33
  cost,
32
34
  dispatchAttemptId: step.owner?.dispatchAttemptId ?? null,
33
35
  priority: step.owner?.priority ?? "foreground",
34
- }, {
35
- signal: step.signal,
36
- onWaiting: async (decision) => await emit("prepublication_host_capacity_waiting", `Pre-publication step '${step.checkId}' (${stepClass}) is waiting for host capacity: ${decision.detail}`, { status: "waiting_for_host_capacity", reason: decision.reason, cpuCores: cost.cpuCores, memoryBytes: cost.memoryBytes }),
37
- });
36
+ }, { signal: step.signal, onWaiting: reports.onWaiting });
37
+ await reports.drained();
38
38
  }
39
39
  catch (error) {
40
+ await reports.drained();
40
41
  if (error instanceof HostCapacityTimeoutError) {
41
42
  await emit("prepublication_host_capacity_timeout", error.message, { status: "host_capacity_timeout", host_load_wait_ms: Math.round(error.waitMs) }, "error");
42
43
  }
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
4
- import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
4
+ import { withHostTestParallelism, withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
5
5
  import { isSubPath } from "../shared/path/path.js";
6
6
  import { NodeProcessRunner, ProcessTreeTerminationError } from "../shared/process/process.js";
7
7
  import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
@@ -65,7 +65,8 @@ export function prePublicationChildEnvironment(environment) {
65
65
  }
66
66
  // A validation step must not join the host ledger (it would queue behind its own token)
67
67
  // or the sandbox broker, whether the variable is inherited or passed in explicitly.
68
- return withoutHostLoadGovernorVariables({ ...child, ...environment });
68
+ // A heavy step that shares the host with other heavy steps sizes its test parallelism for its share.
69
+ return withHostTestParallelism(withoutHostLoadGovernorVariables({ ...child, ...environment }));
69
70
  }
70
71
  /**
71
72
  * Corepack picks the pnpm version from the nearest package.json `packageManager`
@@ -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). */
@@ -79,7 +81,6 @@ export declare class PrePublicationValidator {
79
81
  private ensureDockerPrerequisite;
80
82
  private throwIfPrerequisiteWasLost;
81
83
  private checkTestOnlyExports;
82
- private changedPaths;
83
84
  private assertContractMatchesDispatchBaseline;
84
85
  /** The approved contract of the branch an in-progress merge brings in (MERGE_HEAD), else null. */
85
86
  private mergedInContractDigest;
@@ -11,9 +11,11 @@ import { redactText } from "../shared/redaction/redaction.js";
11
11
  import { PrePublicationPass, PrePublicationValidationError, SkippedTestTally, skippedCheckEvent, validationEvent, } from "./pre-publication-pass.js";
12
12
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
13
13
  import { ProcessTreeTerminationError } from "../shared/process/process.js";
14
- import { findUnreferencedNewExports } from "./unreferenced-exports.js";
14
+ import { findUnreferencedNewExports, historyIntegrityEnvironment, passChangeSet, validationRevisionEnvironment, } from "./pre-publication-change-set.js";
15
15
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
16
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";
17
19
  const requiredCheckIds = new Set([
18
20
  "file-size-inventory",
19
21
  "owned-suite-registration",
@@ -24,8 +26,11 @@ const requiredCheckIds = new Set([
24
26
  "playwright-e2e",
25
27
  "github-provider-policy",
26
28
  ]);
27
- // Every gate profile runs the affected .NET tests; only CI runs the whole tiers (decision 0017).
28
- 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";
29
34
  // Only comment repair ran the affected tests; the other profiles ran Unit, Contract and
30
35
  // Infrastructure whole. Story branches cut before decision 0017 still carry it.
31
36
  const commentRepairOnlyAffectedContractDigest = "378c767c7977c850140ffb19d69db41da62d0187c37a33828d6cda8803a61c83";
@@ -34,10 +39,12 @@ const wholeTierCommentRepairContractDigest = "024de3648c907db9c0eab13def9a4f91e8
34
39
  // Contracts that declare the comment-repair-dotnet-regression check.
35
40
  const commentRepairRegressionContractDigests = new Set([
36
41
  currentApprovedContractDigest,
42
+ infrastructureFallbackContractDigest,
37
43
  commentRepairOnlyAffectedContractDigest,
38
44
  wholeTierCommentRepairContractDigest,
39
45
  ]);
40
46
  const compatibleApprovedContractDigests = new Set([
47
+ infrastructureFallbackContractDigest,
41
48
  commentRepairOnlyAffectedContractDigest,
42
49
  wholeTierCommentRepairContractDigest,
43
50
  // Preserve dispatches pinned before comment repair gained all .NET regression tiers.
@@ -123,7 +130,7 @@ export class PrePublicationValidator {
123
130
  if (checksExports) {
124
131
  const legacy = await prepareValidationExecution(execution);
125
132
  try {
126
- await this.checkTestOnlyExports(pass, worktreePath, emit, signal, legacy.execution);
133
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, withHistoryIntegrity(legacy.execution));
127
134
  }
128
135
  finally {
129
136
  await legacy.cleanup();
@@ -134,20 +141,23 @@ export class PrePublicationValidator {
134
141
  }
135
142
  const scoped = await prepareValidationExecution(execution);
136
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);
137
146
  if (checksExports)
138
- await this.checkTestOnlyExports(pass, worktreePath, emit, signal, scoped.execution);
147
+ await this.checkTestOnlyExports(pass, worktreePath, emit, signal, historyExecution);
139
148
  const contractDigest = validationContractDigest(contract);
140
- await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, scoped.execution);
149
+ await this.assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, historyExecution);
141
150
  if (contractDigest !== currentApprovedContractDigest) {
142
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}.`));
143
152
  }
144
- 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);
145
155
  const run = {
146
156
  worktreePath,
147
157
  capabilities,
148
158
  emit,
149
159
  signal,
150
- execution: withValidationBaseRevision(scoped.execution),
160
+ execution: withValidationRevisions(scoped.execution, mergeParent),
151
161
  postgresAdminConnection: scoped.postgresAdminConnection,
152
162
  };
153
163
  return await this.runChecks(applicableChecks(contract, profile, changedPaths), run, pass);
@@ -194,7 +204,10 @@ export class PrePublicationValidator {
194
204
  }
195
205
  const granted = await this.ensurePrerequisite(check, run.execution?.environment, run.postgresAdminConnection, run.emit);
196
206
  try {
197
- return await this.runCheckSteps({ ...run, check, postgresAdminConnection: granted ?? run.postgresAdminConnection });
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 });
198
211
  }
199
212
  finally {
200
213
  await releaseCheckPostgres(check.id, granted, run.emit);
@@ -335,28 +348,6 @@ export class PrePublicationValidator {
335
348
  await emit?.(validationEvent("prepublication_validation_failed", "unreferenced-exports", `New code is tested but never called: ${detail}`));
336
349
  pass.record({ checkId: "unreferenced-exports", exitCode: 1, command: "git", args: ["grep"], detail });
337
350
  }
338
- async changedPaths(worktreePath, signal, execution) {
339
- const baselineRevision = execution?.baselineRevision?.trim();
340
- const requests = [
341
- ["diff", "--name-only", "HEAD", "--"],
342
- ...(baselineRevision ? [["diff", "--name-only", `${baselineRevision}..HEAD`, "--"]] : []),
343
- ["status", "--porcelain=v1", "--untracked-files=all"],
344
- ];
345
- const paths = new Set();
346
- for (const args of requests) {
347
- const result = await this.runCommand("git", args, worktreePath, signal, execution);
348
- if (result.exitCode !== 0) {
349
- throw new ForgeFailureError("prepublication_validation_failed", `prepublication_validation_failed: unable to inventory changed paths: ${result.stderr ?? result.stdout ?? "git failed"}`, "bridge");
350
- }
351
- for (const line of `${result.stdout ?? ""}`.split(/\r?\n/u).filter(Boolean)) {
352
- const raw = args[0] === "status" ? line.slice(3).split(" -> ").at(-1) ?? "" : line;
353
- const normalized = raw.trim().replaceAll("\\", "/");
354
- if (normalized)
355
- paths.add(normalized);
356
- }
357
- }
358
- return [...paths];
359
- }
360
351
  async assertContractMatchesDispatchBaseline(worktreePath, contractDigest, signal, execution) {
361
352
  const baselineRevision = execution?.baselineRevision?.trim();
362
353
  if (!baselineRevision)
@@ -647,12 +638,16 @@ export async function loadValidationContract(worktreePath) {
647
638
  }
648
639
  return contract;
649
640
  }
650
- /** The affected .NET tests measure the attempt's change against its dispatch baseline (run-affected-dotnet-tests.mjs). */
651
- function withValidationBaseRevision(execution) {
652
- const baseline = execution?.baselineRevision?.trim();
653
- 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)
654
645
  return execution;
655
- 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 } };
656
651
  }
657
652
  function validationContractDigest(contract) {
658
653
  return createHash("sha256")
@@ -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,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>;