Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/fixed-merge-refused-review-change-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Automerge: when GitHub refuses a merge for want of an approving review and a person's change request still stands on the PR, the `stage/085-needs-decision` comment now names the reviewer, the commit they reviewed and what the hive pushed since. It asks them to re-review, or a maintainer to dismiss the review, instead of asking anyone for an Approve over it (projectbluefin/utah-packages#633). PRs without a standing change request keep the same text. The self-authored sweep also re-reads `mergeable_state` right before the merge call and skips a head GitHub now calls conflicting, and a 405 "Pull Request has merge conflicts" from any lane is reported as `conflicting` instead of `merge-failed`.
2 changes: 1 addition & 1 deletion src/docs/labels-and-control-signals/stage-labels.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ used to admit the PR:
| CI red (required or optional) on a **fork** PR while **every** failing check's annotation says the check refuses forks (case-insensitive `fork pull request(s) cannot`, `maintainer must push this branch`, or `cannot publish` together with `fork` — a fork-publication / fork-secrets guard) | `085-needs-decision`, reason `fork-guard:<check>,<check>`: never 070/071/072, never nudged, never adopted (074) — neither the author nor the hive can turn the check green by pushing to the fork. The entry comment names the check and says a maintainer must push the branch to the repository (or approve the run as the repository requires). A same-repo PR with the same message, or a fork PR with any other red check, is handed back as usual ([#14273](https://github.com/hivecommons/hive/issues/14273)) |
| any **non-required** check on the current head is red, whatever the lane's reason (the lane gates on required checks only, so it still soaks and merges; a reader of the rollup sees ✗). Parking modifiers (`hold`, `needs-human`, admission reasons) still win | `070-fixing` / `071-needs-author` / `072-returned-to-contributor` (by author kind), reason `optional-check-failing:<check>` (the nudge lists every red check); never 080 or 100. A red *required* check is the lane's own `required-check-failing:*` → 070/071/072 ([#12538](https://github.com/hivecommons/hive/issues/12538), seen on [#12457](https://github.com/hivecommons/hive/pull/12457)) |
| `label:hold`, `held`, `label:needs-human`, `exempt-label`, `excluded-label:*`, `sentinel`, `human-merge-path*`, `intent-*`, `contributor-lane:workflow-path` / `tests-removed` / `no-reviewer` / `reporter-trust-hold`, `workflow-permission` (GitHub refused update-branch or the merge-forward with a 403 because the base changed `.github/workflows/` and the token the hive used lacks the workflows permission; no token the hive holds can push that update, so it is not sent to 070), `fork-workflow-update` (the same update-branch refusal on a fork head: the App is not installed on the fork, so no grant lets it push there), `linked-issue:hold:#N:<label>` / `linked-issue:needs-decision:#N:<label>` (an open issue the PR closes is held or parked — see [Holding an issue](glossary-and-operations.md#holding-an-issue)) | human hand-off, **decision** cause → routed by the head's evidence (below); lands at `085-needs-decision` when the head is otherwise clean. `contributor-lane:workflow-path` reads "awaiting owner approval": a trusted merger's `APPROVED` review on the current head (or a dashboard `/hive decision approve`) releases the fence and the lane merges the PR itself (`owner_approval_releases_workflow_fence`, [#14664](https://github.com/hivecommons/hive/issues/14664)); only with the toggle off, or when the App lacks `workflows: write` for the merge (`hive:unauthorized`, `merge-workflow-path`), does an approved head park at `090-ready-for-human-merge` for a person's click |
| `merge-refused:review-required` (GitHub answered the merge with 405 "At least N approving review(s) is/are required by reviewers with write access"), `merge-refused:method-not-allowed` (405 "Merge commits / Squash merges / Rebase merges are not allowed on this repository") | human hand-off, **decision** cause, as above: lands at `085-needs-decision` when the head is otherwise clean, and the entry comment names the rule GitHub refused the merge on. Every sweep (self-authored, trusted-author, queued, contributor lane) logs these as skips, not `merge-failed` errors, and stops calling merge: a review refusal is remembered per PR head and re-armed when the head moves, when GitHub's `mergeable_state` for the PR changes (an approving review turns `blocked` into `clean`), or after 30 minutes; a method refusal is remembered per repository and method for 30 minutes. The hive never switches the merge method on its own (a forward merge or a `merge-method/merge` PR must not be squashed), so `method-not-allowed` is a manual-merge park. Any other 405, 409 or 422 is still `merge-failed` |
| `merge-refused:review-required` (GitHub answered the merge with 405 "At least N approving review(s) is/are required by reviewers with write access"), `merge-refused:method-not-allowed` (405 "Merge commits / Squash merges / Rebase merges are not allowed on this repository") | human hand-off, **decision** cause, as above: lands at `085-needs-decision` when the head is otherwise clean, and the entry comment names the rule GitHub refused the merge on. Every sweep (self-authored, trusted-author, queued, contributor lane) logs these as skips, not `merge-failed` errors, and stops calling merge: a review refusal is remembered per PR head and re-armed when the head moves, when GitHub's `mergeable_state` for the PR changes (an approving review turns `blocked` into `clean`), or after 30 minutes; a method refusal is remembered per repository and method for 30 minutes. The hive never switches the merge method on its own (a forward merge or a `merge-method/merge` PR must not be squashed), so `method-not-allowed` is a manual-merge park. When a person's change request still stands on the PR (their latest review is `CHANGES_REQUESTED`, on any head, and it was neither dismissed nor followed by their approval), the `review-required` comment does not ask for an approval over it. It names each reviewer, the commit they reviewed and a compare link to what the hive pushed since, and asks them to re-review, or a maintainer to dismiss the review. GitHub keeps such a review standing across pushes ([projectbluefin/utah-packages#633](https://github.com/projectbluefin/utah-packages/pull/633)). A 405 "Pull Request has merge conflicts" is reported as `conflicting` (070), not `merge-failed`, and the self-authored sweep re-reads `mergeable_state` right before the merge call and skips a head GitHub now calls `dirty`, so it does not call merge on a conflicting PR. Any other 405, 409 or 422 is still `merge-failed` |
| `contributor-lane:no-claim` / `claim-*` / `author-association` / `no-linked-issue`, `untrusted-author-role`, `author-permission-missing` | human hand-off, **trust** cause → routed by the head's evidence (below); lands at `090-ready-for-human-merge` when the head is otherwise clean |
| hand-offs (`not-app-authored`, `trusted-bot-lane`, `trusted-author:app-authored`, `contributor-lane:app-authored`), transient fetch errors | no opinion — the owning lane decides; nothing is written. An App-authored PR is handed off by the trusted-author and contributor-lane tiers under their own reason; the self-authored lane owns it, and its `review-gate:no-review-bundle` is the stage's reason while the swarm has not reviewed the head ([#14482](https://github.com/hivecommons/hive/issues/14482)) |

Expand Down
236 changes: 236 additions & 0 deletions src/pkg/github/automerge/automerge_merge_change_request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
package automerge

import (
"bytes"
"context"
"log/slog"
"net/http"
"strings"
"testing"
"time"

gh "github.com/google/go-github/v72/github"

"github.com/hivecommons/hive/pkg/stageengine/prstage"
"github.com/hivecommons/hive/pkg/stagelabels"
)

const mergeConflictsTestMessage = "Pull Request has merge conflicts"

// projectbluefin/utah-packages#633, 2026-10-31 18:29Z: a pass's first read of
// the PR did not show the conflict, the read right before the merge did, and
// the sweep called PUT /merge anyway (405 "Pull Request has merge
// conflicts"). The re-check now skips it without the call.
func TestSweepSelfAuthoredSkipsAConflictFoundAtTheMergeTimeRead(t *testing.T) {
for _, recheck := range []string{"dirty", "conflicting"} {
t.Run(recheck, func(t *testing.T) {
var merged []int
var attempts int
prs := []selfAuthoredPR{{
number: 90, author: testHiveAppBotLogin, mergeableState: "clean", recheckMergeableState: recheck,
statusState: "success", checkStatus: "completed", checkConclusion: "success", mergeAttempts: &attempts,
}}
api := newSelfAuthoredAutoMergeAPI(t, prs, &merged)
defer api.Close()
var logs bytes.Buffer
c := newAutoMergeSweepClient(api.URL)
c.logger = slog.New(slog.NewTextHandler(&logs, nil))

result, err := c.SweepSelfAuthoredAutoMerges(context.Background(), AutoMergeSweepOptions{})
if err != nil {
t.Fatalf("SweepSelfAuthoredAutoMerges: %v", err)
}
if attempts != 0 || len(merged) != 0 || result.Skipped != 1 {
t.Fatalf("merge attempts = %d, merged = %v, result = %+v; want a skip with no merge call", attempts, merged, result)
}
if !strings.Contains(logs.String(), "reason=conflicting") {
t.Fatalf("logs = %q, want reason=conflicting", logs.String())
}
})
}
}

// A clean head is still merged through the re-check.
func TestSweepSelfAuthoredStillMergesACleanHead(t *testing.T) {
var merged []int
var attempts int
prs := []selfAuthoredPR{{
number: 90, author: testHiveAppBotLogin, mergeableState: "clean",
statusState: "success", checkStatus: "completed", checkConclusion: "success", mergeAttempts: &attempts,
}}
api := newSelfAuthoredAutoMergeAPI(t, prs, &merged)
defer api.Close()
result, err := newAutoMergeSweepClient(api.URL).SweepSelfAuthoredAutoMerges(context.Background(), AutoMergeSweepOptions{})
if err != nil || attempts != 1 || len(merged) != 1 || len(result.Merged) != 1 {
t.Fatalf("attempts = %d, merged = %v, result = %+v, err = %v; want one merge", attempts, merged, result, err)
}
}

// When GitHub only learns of the conflict at the merge call, the 405 is the
// conflict it names, not merge-failed: that reason parked #633 at 080 for a
// pass and logged a WARN.
func TestSweepSelfAuthoredMergeConflict405IsConflicting(t *testing.T) {
var merged []int
var attempts int
prs := []selfAuthoredPR{{
number: 90, author: testHiveAppBotLogin, mergeableState: "clean",
statusState: "success", checkStatus: "completed", checkConclusion: "success",
mergeStatus: http.StatusMethodNotAllowed, mergeMessage: mergeConflictsTestMessage, mergeAttempts: &attempts,
}}
api := newSelfAuthoredAutoMergeAPI(t, prs, &merged)
defer api.Close()
var logs bytes.Buffer
c := newAutoMergeSweepClient(api.URL)
c.logger = slog.New(slog.NewTextHandler(&logs, nil))
if _, err := c.SweepSelfAuthoredAutoMerges(context.Background(), AutoMergeSweepOptions{}); err != nil {
t.Fatalf("SweepSelfAuthoredAutoMerges: %v", err)
}
got := logs.String()
if attempts != 1 || !strings.Contains(got, "reason=conflicting") || strings.Contains(got, "merge-failed") {
t.Fatalf("attempts = %d, logs = %q; want one call reported as conflicting, not merge-failed", attempts, got)
}
}

func TestMergeConflictMergeErrorIsOnlyThe405(t *testing.T) {
resp := func(status int, msg string) error {
return &gh.ErrorResponse{Response: &http.Response{StatusCode: status}, Message: msg}
}
if !mergeConflictMergeError(resp(http.StatusMethodNotAllowed, mergeConflictsTestMessage)) {
t.Fatal("405 merge conflicts not recognised")
}
for _, err := range []error{resp(http.StatusConflict, mergeConflictsTestMessage), resp(http.StatusMethodNotAllowed, reviewRequiredTestMessage), resp(http.StatusMethodNotAllowed, "Pull Request is not mergeable")} {
if mergeConflictMergeError(err) {
t.Fatalf("%v read as a merge conflict", err)
}
}
}

func TestMergeCallConflictingReadsTheBoolOnlyWhileTheStateIsUnknown(t *testing.T) {
for _, tc := range []struct {
state string
mergeable *bool
want bool
}{
{"dirty", gh.Ptr(false), true},
{"dirty", nil, true},
{"unknown", gh.Ptr(false), true},
{"", gh.Ptr(false), true},
{"unknown", nil, false},
{"unknown", gh.Ptr(true), false},
{"clean", gh.Ptr(true), false},
{"blocked", gh.Ptr(false), false},
{"behind", gh.Ptr(false), false},
} {
pr := &gh.PullRequest{MergeableState: gh.Ptr(tc.state), Mergeable: tc.mergeable}
if got := mergeCallConflicting(pr); got != tc.want {
t.Fatalf("state %q mergeable %v: got %v, want %v", tc.state, tc.mergeable, got, tc.want)
}
}
}

// projectbluefin/utah-packages#633: @hanthor asked for changes at 1760767,
// the hive reworked the branch, and GitHub refused the merge for want of an
// approving review. The 085 ask named only the approval. It now names the
// standing change request, links what the hive pushed since and asks the
// reviewer to re-review; without one the text is unchanged.
func TestMergeRefusedReviewAskNamesTheStandingChangeRequest(t *testing.T) {
const reviewed = "1760767603b4d1c6a3f1c6c4bb0ad5c20c7e2a11"
const head = "sha90" // the fixture's head: the hive pushed past the review
reviewURL := "https://github.com/acme/widget/pull/90#pullrequestreview-1"
at := time.Date(2026, 10, 30, 4, 12, 6, 0, time.UTC)
review := func(login, state, commit string, when time.Time) map[string]any {
return map[string]any{
"id": when.Unix(), "user": map[string]string{"login": login}, "state": state,
"commit_id": commit, "submitted_at": when.Format(time.RFC3339), "html_url": reviewURL,
}
}
var merged []int
var attempts int
prs := []selfAuthoredPR{{
number: 90, author: testHiveAppBotLogin, mergeableState: "blocked",
statusState: "success", checkStatus: "completed", checkConclusion: "success",
mergeStatus: http.StatusMethodNotAllowed, mergeMessage: reviewRequiredTestMessage, mergeAttempts: &attempts,
reviews: []map[string]any{
review(testHiveAppBotLogin, "COMMENTED", reviewed, at.Add(-time.Hour)),
review("hanthor", "CHANGES_REQUESTED", reviewed, at),
// A request its reviewer later approved, one dismissed, and a
// bot's: none of them stands.
review("carol", "CHANGES_REQUESTED", reviewed, at.Add(time.Minute)),
review("carol", "APPROVED", "sha90", at.Add(2*time.Minute)),
review("dave", "CHANGES_REQUESTED", reviewed, at.Add(3*time.Minute)),
review("dave", "DISMISSED", reviewed, at.Add(4*time.Minute)),
review("renovate[bot]", "CHANGES_REQUESTED", reviewed, at.Add(5*time.Minute)),
},
}}
api := newSelfAuthoredAutoMergeAPI(t, prs, &merged)
defer api.Close()
c := newAutoMergeSweepClient(api.URL)
c.stageLabelPolicy = func() StageLabelPolicy { return StageLabelPolicy{Enabled: true} }
c.stageTracker = NewStageTracker()
if _, err := c.SweepSelfAuthoredAutoMerges(context.Background(), AutoMergeSweepOptions{}); err != nil {
t.Fatalf("SweepSelfAuthoredAutoMerges: %v", err)
}
if attempts != 1 {
t.Fatalf("merge attempts = %d, want the one refused call", attempts)
}
var obs stageObservation
for _, list := range c.stageTracker.drain() {
for _, o := range list {
if o.Number == 90 && o.Reason == autoMergeReasonMergeRefusedReview {
obs = o
}
}
}
if obs.Number != 90 {
t.Fatal("no merge-refused-review observation recorded for #90")
}
if got := obs.Detail.StandingChangeRequests; len(got) != 1 || got[0].Login != "hanthor" || got[0].CommitID != reviewed {
t.Fatalf("StandingChangeRequests = %+v, want only @hanthor's at %s", got, reviewed)
}

// The 085 text is built from the drained observation.
if obs.HeadSHA != head {
t.Fatalf("observed head = %q, want %q", obs.HeadSHA, head)
}
key := stageKey(obs.Owner, obs.Repo, obs.Number)
e := c.humanEvidence(context.Background(), c.stageTracker, key, obs, stagelabels.CauseDecision, at.Add(48*time.Hour))
for _, want := range []string{
"@hanthor requested changes on 2026-10-30 at `1760767`",
"([review](" + reviewURL + "))",
"the hive has pushed since ([changes since that review](https://github.com/acme/widget/compare/" + reviewed + "..." + head + "))",
"@hanthor, please re-review this head",
"a maintainer can dismiss the review",
} {
if !strings.Contains(e.CauseReason, want) {
t.Fatalf("085 cause = %q\nwant it to contain %q", e.CauseReason, want)
}
}
if strings.Contains(e.CauseReason, "A GitHub **Approve** review on this head") {
t.Fatalf("085 cause still invites an approval over the change request: %q", e.CauseReason)
}
if !strings.Contains(stagelabels.DecisionComment(stagelabels.RouteHuman(e)), "@hanthor, please re-review this head") {
t.Fatal("the decision comment does not carry the re-review ask")
}

// No standing request: the text is exactly today's.
obs.Detail.StandingChangeRequests = nil
plain := c.humanEvidence(context.Background(), c.stageTracker, key, obs, stagelabels.CauseDecision, at)
if plain.CauseReason != decisionCause(autoMergeReasonMergeRefusedReview) {
t.Fatalf("085 cause without a change request = %q, want the unchanged approval ask", plain.CauseReason)
}
}

func TestMergeRefusedReviewChangeRequestCauseShapes(t *testing.T) {
const head = "337fa030b73afe13dd9eb77cb6cadf94dcd63ec5"
if got := mergeRefusedReviewChangeRequestCause(head, nil); got != "" {
t.Fatalf("no requests: %q, want empty", got)
}
onHead := mergeRefusedReviewChangeRequestCause(head, []prstage.ChangeRequestRef{{Login: "hanthor", CommitID: head}})
if !strings.Contains(onHead, "@hanthor requested changes on this head") || strings.Contains(onHead, "pushed since") {
t.Fatalf("request on the head: %q, want no claim that the hive pushed since", onHead)
}
two := mergeRefusedReviewChangeRequestCause(head, []prstage.ChangeRequestRef{{Login: "hanthor", CommitID: "aaaa111"}, {Login: "castrojo", CommitID: "bbbb222"}})
if !strings.Contains(two, "@hanthor and @castrojo, please re-review this head") || strings.Contains(two, "compare/") {
t.Fatalf("two requests without URLs: %q", two)
}
}
21 changes: 21 additions & 0 deletions src/pkg/github/automerge/automerge_merge_refusal.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ const mergeRefusalPruneAt = 1024
// "1 review requesting changes by reviewers with write access.".
var mergeRefusedReviewRE = regexp.MustCompile(`(?i)\d+ approving reviews? (?:is|are) required|\d+ reviews? requesting changes`)

// "Pull Request has merge conflicts": the base and head conflict at the
// time of the call, whatever the PR read before it said.
var mergeConflictRE = regexp.MustCompile(`(?i)pull request has merge conflicts`)

// mergeConflictMergeError reports GitHub's 405 for a merge call on a PR
// that has merge conflicts.
func mergeConflictMergeError(err error) bool {
var ghErr *gh.ErrorResponse
if !errors.As(err, &ghErr) || ghErr.Response == nil || ghErr.Response.StatusCode != http.StatusMethodNotAllowed {
return false
}
return mergeConflictRE.MatchString(ghErr.Message) || mergeConflictRE.MatchString(ghErr.Error())
}

// "Merge commits are not allowed on this repository." and the squash and
// rebase forms.
var mergeRefusedMethodRE = regexp.MustCompile(`(?i)(?:merge commits|squash merges|rebase merges) are not allowed on this repository`)
Expand Down Expand Up @@ -207,6 +221,13 @@ func (c *Engine) refusedMerge(a mergeAttempt, err error) string {
c.noteMergeQueueBase(a.owner, a.repo, a.base)
return autoMergeReasonMergeQueueRequired
}
if mergeConflictMergeError(err) {
// Not remembered: GitHub's mergeable_state says dirty on the next
// read, and the lanes skip on that. Reported as the conflict it is,
// not merge-failed, which parked the PR at 080 for a pass
// (projectbluefin/utah-packages#633).
return "conflicting"
}
reason := mergeRefusalReason(err)
if reason == "" || c == nil {
return reason
Expand Down
Loading
Loading