feat: resolve conflicts in editable fork PRs
This commit is contained in:
1 parent
3a0e0fb0b6
commit
0e914c6bc6
7 files changed
+127
-22
No files matched your search
@@ -207,7 +207,7 @@ jobs:
|
||||
ref: main
|
||||
path: ghbot-runtime
|
||||
- name: Check out current PR source for agent tasks
|
||||
if: ${{ inputs.event_name == 'issue_comment' || (inputs.event_name == 'pull_request_target' && inputs.event_action != 'closed' && inputs.auto_resolve_conflicts == 'true' && inputs.pull_head_repository == format('{0}/{1}', inputs.repository_owner, inputs.repository_name)) }}
|
||||
if: ${{ inputs.event_name == 'issue_comment' || (inputs.event_name == 'pull_request_target' && inputs.event_action != 'closed' && inputs.auto_resolve_conflicts == 'true') }}
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ inputs.repository_owner }}/${{ inputs.repository_name }}
|
||||
|
||||
+2
-2
@@ -126,7 +126,7 @@ prompt 还会收到由宿主通过 GitHub 验证的请求者上下文:评论
|
||||
|
||||
具有 `write`、`maintain` 或 `admin` 权限的协作者也可以评论精确命令 `/conflict`,显式要求执行同一套受保护的冲突修复。即使 `AUTO_RESOLVE_CONFLICTS=false`,该命令也可以运行;它不要求先有一次通过的审核,因为修复提交 push 后一定会对新 head 重新完整审核,修复动作本身不会直接批准合并。
|
||||
|
||||
仅处理当前 head 未变化且 PR 分支位于同一仓库的情况;外部 fork、旧 head、非冲突状态和未通过审核的 PR 都会跳过。ghbot 在宿主生成本地 merge,再把无 `.git`、无凭据的净化快照交给 goose。goose 可以修改直接冲突文件,也可以在兼容性确有需要时调整相关调用方、类型、测试、lockfile、配置或文档;受保护的 Agent 配置和凭证路径会被拒绝。
|
||||
仅处理当前 head 未变化且可写的 PR 分支。同仓库分支可直接写入;外部 fork 只有贡献者启用 **Allow edits from maintainers** 才可处理,并使用绑定已审核 head SHA 的 `--force-with-lease` 推送,因此贡献者新提交的 commit 不会被覆盖。旧 head、非冲突状态、关闭 maintainer edits 和未通过审核的 PR 都会跳过。ghbot 在宿主生成本地 merge,再把无 `.git`、无凭据的净化快照交给 goose。goose 可以修改直接冲突文件,也可以在兼容性确有需要时调整相关调用方、类型、测试、lockfile、配置或文档;受保护的 Agent 配置和凭证路径会被拒绝。
|
||||
|
||||
应用改动后,ghbot 检查未合并路径和 `git diff --check`。第二次隔离 goose 会审核完整 staged diff,并在配置后运行可信的 `CONFLICT_TEST_COMMAND`。只有第二次确认明确返回 `safeToCommit=true`,且远端 PR head 仍与审核 SHA 相同,才会创建普通 merge commit 并 push;绝不 force-push。新 commit 会触发 `synchronize` 并重新完整审核,不会把修复前的结论直接当作批准。
|
||||
|
||||
@@ -218,7 +218,7 @@ secrets:
|
||||
/conflict
|
||||
```
|
||||
|
||||
只有当 GitHub 报告当前开放 PR 存在冲突,且 head 分支属于同一个仓库时才会尝试修复。机器人不会向外部 fork push。它会运行与自动修复相同的可信验证命令和第二次 goose 最终确认;两者成功且远端 head 未变化时才会创建普通 commit 并 push。
|
||||
只有当 GitHub 报告当前开放 PR 存在冲突且 head 可写时才会尝试修复。外部 fork 必须开启 **Allow edits from maintainers**,并通过绑定已审核 SHA 的 force-with-lease 安全更新贡献者分支。它会运行与自动修复相同的可信验证命令和第二次 goose 最终确认;两者成功且远端 head 未变化时才会创建 commit 并 push。
|
||||
|
||||
## 本地开发
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ Set `AUTO_RESOLVE_CONFLICTS=true` to allow goose to repair a PR that passed revi
|
||||
|
||||
A collaborator with `write`, `maintain`, or `admin` permission can also explicitly request the same guarded repair by posting the exact command `/conflict`. This manual command works even when `AUTO_RESOLVE_CONFLICTS=false`; it does not require an earlier passing review because the resulting commit always triggers a new complete review before any merge decision.
|
||||
|
||||
Conflict repair applies only to a current-head PR branch in the same repository. External forks, stale heads, non-dirty states, and failed reviews are skipped. ghbot creates the merge locally, gives goose a sanitized credential-free snapshot, and allows it to change direct conflict files plus related callers, types, tests, lockfiles, configuration, or documentation when necessary for compatibility. Protected agent/configuration and credential paths are rejected.
|
||||
Conflict repair applies to a current, writable PR head. Same-repository branches are writable directly; external forks are eligible only when the contributor enabled **Allow edits from maintainers**. Fork pushes use an explicit `--force-with-lease` tied to the reviewed head SHA, so a newly pushed contributor commit is never overwritten. Stale heads, non-dirty states, disabled maintainer edits, and failed reviews are skipped. ghbot creates the merge locally, gives goose a sanitized credential-free snapshot, and allows it to change direct conflict files plus related callers, types, tests, lockfiles, configuration, or documentation when necessary for compatibility. Protected agent/configuration and credential paths are rejected.
|
||||
|
||||
After applying the proposed files, ghbot verifies there are no unmerged paths and runs `git diff --check`. A second isolated goose pass reviews the complete staged diff and, when configured, runs the trusted `CONFLICT_TEST_COMMAND`. The result is committed and pushed only when that final pass returns `safeToCommit=true` and the remote PR head still matches the reviewed SHA. ghbot never force-pushes. The new commit triggers a fresh `synchronize` review; the old decision is not reused as approval.
|
||||
|
||||
@@ -208,7 +208,7 @@ An eligible repository user can comment the exact command:
|
||||
/conflict
|
||||
```
|
||||
|
||||
The bot attempts conflict repair only when GitHub reports the current open PR as conflicted and its head branch belongs to the same repository. External forks are never pushed. It runs the same configured validation and separate final goose confirmation used by automatic repair, then pushes a normal commit only if both succeed and the head has not changed.
|
||||
The bot attempts conflict repair only when GitHub reports the current open PR as conflicted and the head is writable. External forks require **Allow edits from maintainers**; their resolved head is pushed with a force lease pinned to the reviewed SHA. It runs the same configured validation and separate final goose confirmation used by automatic repair, then pushes only if both succeed and the head has not changed.
|
||||
|
||||
## Local development
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ export type ConflictResolutionEligibility = {
|
||||
mergeableState: string;
|
||||
baseRepository: string;
|
||||
headRepository: string | null;
|
||||
maintainerCanModify: boolean;
|
||||
expectedHeadSha: string;
|
||||
currentHeadSha: string;
|
||||
};
|
||||
@@ -43,7 +44,8 @@ export function canAutoResolveConflicts(input: ConflictResolutionEligibility): b
|
||||
input.reviewPassed &&
|
||||
input.mergeable === false &&
|
||||
input.mergeableState === "dirty" &&
|
||||
input.headRepository === input.baseRepository &&
|
||||
input.headRepository !== null &&
|
||||
(input.headRepository === input.baseRepository || input.maintainerCanModify) &&
|
||||
input.currentHeadSha === input.expectedHeadSha
|
||||
);
|
||||
}
|
||||
@@ -58,15 +60,25 @@ export async function resolvePullRequestConflicts(
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
headRepository: string | null;
|
||||
maintainerCanModify: boolean;
|
||||
worktree: string;
|
||||
gitToken: string;
|
||||
repositoryKnowledge?: string;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
if (params.headRepository !== `${params.owner}/${params.repo}`) {
|
||||
const baseRepository = `${params.owner}/${params.repo}`;
|
||||
if (!params.headRepository) {
|
||||
logger.info(
|
||||
{ owner: params.owner, repo: params.repo, pullNumber: params.pullNumber },
|
||||
"Skipping automatic conflict resolution for an external fork."
|
||||
"Skipping conflict resolution because the PR head repository is unavailable."
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const externalFork = params.headRepository !== baseRepository;
|
||||
if (externalFork && !params.maintainerCanModify) {
|
||||
logger.info(
|
||||
{ owner: params.owner, repo: params.repo, pullNumber: params.pullNumber },
|
||||
"Skipping conflict resolution because the external contributor disabled maintainer edits."
|
||||
);
|
||||
return false;
|
||||
}
|
||||
@@ -206,7 +218,12 @@ export async function resolvePullRequestConflicts(
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber
|
||||
});
|
||||
if (currentPullRequest.state !== "open" || currentPullRequest.head.sha !== params.expectedHeadSha) {
|
||||
if (
|
||||
currentPullRequest.state !== "open" ||
|
||||
currentPullRequest.head.sha !== params.expectedHeadSha ||
|
||||
currentPullRequest.head.repo?.full_name !== params.headRepository ||
|
||||
(externalFork && !currentPullRequest.maintainer_can_modify)
|
||||
) {
|
||||
logger.info(
|
||||
{
|
||||
owner: params.owner,
|
||||
@@ -214,9 +231,11 @@ export async function resolvePullRequestConflicts(
|
||||
pullNumber: params.pullNumber,
|
||||
expectedHead: params.expectedHeadSha,
|
||||
currentHead: currentPullRequest.head.sha,
|
||||
currentState: currentPullRequest.state
|
||||
currentState: currentPullRequest.state,
|
||||
currentHeadRepository: currentPullRequest.head.repo?.full_name,
|
||||
maintainerCanModify: currentPullRequest.maintainer_can_modify
|
||||
},
|
||||
"Discarding conflict resolution because the pull request changed before push."
|
||||
"Discarding conflict resolution because the pull request or maintainer-edit permission changed before push."
|
||||
);
|
||||
await runCommand("git", ["merge", "--abort"], worktree, gitEnv);
|
||||
return false;
|
||||
@@ -239,12 +258,12 @@ export async function resolvePullRequestConflicts(
|
||||
worktree,
|
||||
gitEnv
|
||||
);
|
||||
await runCommand(
|
||||
"git",
|
||||
["push", "origin", `HEAD:refs/heads/${params.headBranch}`],
|
||||
worktree,
|
||||
gitEnv
|
||||
);
|
||||
await runCommand("git", buildConflictPushArgs({
|
||||
baseRepository,
|
||||
headRepository: params.headRepository,
|
||||
headBranch: params.headBranch,
|
||||
expectedHeadSha: params.expectedHeadSha
|
||||
}), worktree, gitEnv);
|
||||
return true;
|
||||
} catch (error) {
|
||||
await runCommand("git", ["merge", "--abort"], worktree, gitEnv).catch(() => undefined);
|
||||
@@ -257,6 +276,54 @@ export async function resolvePullRequestConflicts(
|
||||
}
|
||||
}
|
||||
|
||||
export function buildConflictPushArgs(params: {
|
||||
baseRepository: string;
|
||||
headRepository: string;
|
||||
headBranch: string;
|
||||
expectedHeadSha: string;
|
||||
}): string[] {
|
||||
if (!isSafeGitHubRepository(params.headRepository)) {
|
||||
throw new Error(`Unsafe PR head repository: ${params.headRepository}`);
|
||||
}
|
||||
if (!isSafeGitBranch(params.headBranch)) {
|
||||
throw new Error(`Unsafe PR head branch: ${params.headBranch}`);
|
||||
}
|
||||
if (!/^[0-9a-f]{40,64}$/i.test(params.expectedHeadSha)) {
|
||||
throw new Error("Expected PR head SHA must contain 40-64 hexadecimal characters.");
|
||||
}
|
||||
|
||||
const headRef = `refs/heads/${params.headBranch}`;
|
||||
if (params.headRepository === params.baseRepository) {
|
||||
return ["push", "origin", `HEAD:${headRef}`];
|
||||
}
|
||||
|
||||
return [
|
||||
"push",
|
||||
`--force-with-lease=${headRef}:${params.expectedHeadSha}`,
|
||||
`https://github.com/${params.headRepository}.git`,
|
||||
`HEAD:${headRef}`
|
||||
];
|
||||
}
|
||||
|
||||
function isSafeGitHubRepository(value: string): boolean {
|
||||
return value.split("/").length === 2 && value.split("/").every((part) => (
|
||||
part !== "." && part !== ".." && /^[A-Za-z0-9_.-]+$/.test(part)
|
||||
));
|
||||
}
|
||||
|
||||
function isSafeGitBranch(value: string): boolean {
|
||||
return (
|
||||
value.length > 0 &&
|
||||
!value.startsWith("-") &&
|
||||
!value.startsWith("/") &&
|
||||
!value.endsWith("/") &&
|
||||
!value.endsWith(".") &&
|
||||
!value.includes("..") &&
|
||||
!value.includes("@{") &&
|
||||
!/[\u0000-\u0020~^:?*[\\]/.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
function buildConflictPrompt(
|
||||
params: { baseBranch: string; headBranch: string; pullNumber: number },
|
||||
conflictFiles: string[]
|
||||
|
||||
@@ -172,6 +172,7 @@ export async function processPullRequest(
|
||||
mergeableState: mergeablePullRequest.mergeable_state,
|
||||
baseRepository: `${owner}/${repo}`,
|
||||
headRepository: pullRequest.head.repo?.full_name ?? null,
|
||||
maintainerCanModify: pullRequest.maintainer_can_modify ?? false,
|
||||
expectedHeadSha: pullRequest.head.sha,
|
||||
currentHeadSha: currentPullRequest.head.sha
|
||||
});
|
||||
@@ -192,6 +193,7 @@ export async function processPullRequest(
|
||||
baseBranch: pullRequest.base.ref,
|
||||
headBranch: pullRequest.head.ref,
|
||||
headRepository: pullRequest.head.repo?.full_name ?? null,
|
||||
maintainerCanModify: pullRequest.maintainer_can_modify ?? false,
|
||||
worktree,
|
||||
gitToken,
|
||||
repositoryKnowledge
|
||||
@@ -669,12 +671,13 @@ export async function processConflictComment(
|
||||
mergeableState: mergeablePullRequest.mergeable_state,
|
||||
baseRepository: `${params.owner}/${params.repo}`,
|
||||
headRepository: pullRequest.head.repo?.full_name ?? null,
|
||||
maintainerCanModify: pullRequest.maintainer_can_modify ?? false,
|
||||
expectedHeadSha: pullRequest.head.sha,
|
||||
currentHeadSha: mergeablePullRequest.head.sha
|
||||
});
|
||||
if (!eligible) {
|
||||
const reason = pullRequest.head.repo?.full_name !== `${params.owner}/${params.repo}`
|
||||
? "The PR comes from an external fork, and ghbot never pushes conflict-resolution commits to contributor forks."
|
||||
const reason = pullRequest.head.repo?.full_name !== `${params.owner}/${params.repo}` && !pullRequest.maintainer_can_modify
|
||||
? "The PR comes from an external fork whose contributor has disabled maintainer edits. Enable ‘Allow edits from maintainers’, then run /conflict again."
|
||||
: mergeablePullRequest.mergeable_state !== "dirty"
|
||||
? `GitHub does not currently report a merge conflict (mergeable=${mergeablePullRequest.mergeable}, mergeable_state=${mergeablePullRequest.mergeable_state}).`
|
||||
: "The PR head changed while conflict eligibility was being checked. Run /conflict again on the latest head.";
|
||||
@@ -704,6 +707,7 @@ export async function processConflictComment(
|
||||
baseBranch: pullRequest.base.ref,
|
||||
headBranch: pullRequest.head.ref,
|
||||
headRepository: pullRequest.head.repo?.full_name ?? null,
|
||||
maintainerCanModify: pullRequest.maintainer_can_modify ?? false,
|
||||
worktree,
|
||||
gitToken: params.gitToken,
|
||||
repositoryKnowledge
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildConflictPushArgs,
|
||||
canAutoResolveConflicts,
|
||||
diffSnapshotInventories
|
||||
} from "../src/review/conflictResolver.js";
|
||||
@@ -12,19 +13,51 @@ const eligible = {
|
||||
mergeableState: "dirty",
|
||||
baseRepository: "forumlify/public",
|
||||
headRepository: "forumlify/public",
|
||||
maintainerCanModify: false,
|
||||
expectedHeadSha: "abc",
|
||||
currentHeadSha: "abc"
|
||||
} as const;
|
||||
|
||||
test("only a passing conflicted same-repository current head is eligible", () => {
|
||||
test("only a passing conflicted writable current head is eligible", () => {
|
||||
assert.equal(canAutoResolveConflicts(eligible), true);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, reviewPassed: false }), false);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, mergeable: true, mergeableState: "clean" }), false);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, headRepository: "contributor/fork" }), false);
|
||||
assert.equal(canAutoResolveConflicts({
|
||||
...eligible,
|
||||
headRepository: "contributor/fork",
|
||||
maintainerCanModify: true
|
||||
}), true);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, currentHeadSha: "new-head" }), false);
|
||||
assert.equal(canAutoResolveConflicts({ ...eligible, enabled: false }), false);
|
||||
});
|
||||
|
||||
test("external fork conflict pushes use a head-SHA force lease", () => {
|
||||
assert.deepEqual(buildConflictPushArgs({
|
||||
baseRepository: "forumlify/public",
|
||||
headRepository: "contributor/forumlify",
|
||||
headBranch: "fix/conflicts",
|
||||
expectedHeadSha: "a".repeat(40)
|
||||
}), [
|
||||
"push",
|
||||
`--force-with-lease=refs/heads/fix/conflicts:${"a".repeat(40)}`,
|
||||
"https://github.com/contributor/forumlify.git",
|
||||
"HEAD:refs/heads/fix/conflicts"
|
||||
]);
|
||||
assert.deepEqual(buildConflictPushArgs({
|
||||
baseRepository: "forumlify/public",
|
||||
headRepository: "forumlify/public",
|
||||
headBranch: "fix/conflicts",
|
||||
expectedHeadSha: "b".repeat(40)
|
||||
}), ["push", "origin", "HEAD:refs/heads/fix/conflicts"]);
|
||||
assert.throws(() => buildConflictPushArgs({
|
||||
baseRepository: "forumlify/public",
|
||||
headRepository: "contributor/forumlify",
|
||||
headBranch: "bad:branch",
|
||||
expectedHeadSha: "c".repeat(40)
|
||||
}), /Unsafe PR head branch/);
|
||||
});
|
||||
|
||||
test("snapshot inventory detects related file additions, changes, and deletions", () => {
|
||||
const before = new Map([
|
||||
["conflicted.ts", { hash: "old", size: 10 }],
|
||||
|
||||
@@ -2,10 +2,11 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
|
||||
test("pull_request_target checks out a PR worktree only for same-repository heads", async () => {
|
||||
test("conflict repair checks out fork heads without persisting GitHub credentials", async () => {
|
||||
const workflow = await fs.readFile(".github/workflows/review-reusable.yml", "utf8");
|
||||
const caller = await fs.readFile(".github/workflows/review.yml", "utf8");
|
||||
assert.match(workflow, /pull_head_repository == format\('\{0\}\/\{1\}'/);
|
||||
assert.match(workflow, /inputs\.auto_resolve_conflicts == 'true'/);
|
||||
assert.doesNotMatch(workflow, /pull_head_repository == format\('\{0\}\/\{1\}'/);
|
||||
assert.doesNotMatch(workflow, /allow-unsafe-pr-checkout:\s*true/);
|
||||
assert.match(workflow, /GHBOT_GOOSE_BINARY:\s*\$\{\{ runner\.temp \}\}\/goose\/bin\/goose/);
|
||||
assert.match(caller, /pull_head_repository:\s*\$\{\{ github\.event\.pull_request\.head\.repo\.full_name \|\| '' \}\}/);
|
||||
|
||||
Reference in new issue
Block a user