From 541c9c5ec255f7401cccc420b19ab0d8e41fcd3f Mon Sep 17 00:00:00 2001 From: Danathar Date: Thu, 5 Nov 2026 16:36:37 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20fix(automerge):=20an=20appro?= =?UTF-8?q?ving=20review=20counts=20only=20for=20the=20content=20it=20appr?= =?UTF-8?q?oved?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitHub moves an existing review onto a later merge of the base, so commit_id == head does not prove the head was approved: projectbluefin/utah#1078's review submitted 2026-11-04 01:17Z is reported on 9d8ceab (made 2026-11-05 19:50Z) and released the workflow-path fence. - reviewReachesHead: submitted_at >= head commit date, or head is a chain of diff-preserving base merges (any author, BaseMergeParent) back to the approved commit or one no newer than the review; memoised per review/head. - the fence comment says "carried over a base merge ... (PR diff unchanged)". - an approval on the previous head answers requires_human after such a merge. - 085 What to do no longer asks for an approval already recorded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- changelog.d/fixed-owner-approval-carryover.md | 1 + src/docs/hive-merge.md | 18 ++- ...automerge_contributor_workflow_approval.go | 23 ++- ...erge_contributor_workflow_approval_test.go | 2 +- .../automerge_human_changes_requested.go | 13 +- .../github/automerge/automerge_review_gate.go | 12 +- .../automerge_review_head_binding.go | 135 ++++++++++++++++ .../automerge_review_head_binding_test.go | 148 ++++++++++++++++++ src/pkg/github/automerge/automerge_sweep.go | 3 + .../automerge/automerge_sweep_guards_test.go | 4 + src/pkg/github/pr_decision_base_refresh.go | 36 +++++ .../github/pr_decision_base_refresh_test.go | 30 ++++ src/pkg/stagelabels/human.go | 9 +- src/pkg/stagelabels/human_test.go | 32 ++++ 14 files changed, 450 insertions(+), 16 deletions(-) create mode 100644 changelog.d/fixed-owner-approval-carryover.md create mode 100644 src/pkg/github/automerge/automerge_review_head_binding.go create mode 100644 src/pkg/github/automerge/automerge_review_head_binding_test.go diff --git a/changelog.d/fixed-owner-approval-carryover.md b/changelog.d/fixed-owner-approval-carryover.md new file mode 100644 index 0000000000..d9fa85435a --- /dev/null +++ b/changelog.d/fixed-owner-approval-carryover.md @@ -0,0 +1 @@ +- An owner's approving review counts for a PR head only when it approved that content. GitHub moves an existing review onto a later merge of the base, so on projectbluefin/utah#1078 a review submitted 2026-11-04 01:17Z was read as approval of 9d8ceab, a commit made the next day, and released the workflow-path fence. Now the review counts when it was submitted at or after the head commit's date, or when the head adds only base merges that leave the PR's diff unchanged; the fence comment then says the approval was carried over a base merge. The same rule lets an approval on the previous head answer `requires_human` after such a merge (it is no longer re-asked), and the 085 **What to do** no longer asks for an approval that is already recorded. diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index e5e95e0c17..4043b48f62 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -960,9 +960,17 @@ A PR merges through this tier only when all of the following hold: has explicitly approved the current head (`owner_approval_releases_workflow_fence`, default `true`, [#14664](https://github.com/hivecommons/hive/issues/14664)). Explicit - approval is a GitHub pull-request review in state `APPROVED` whose commit - is the current head by a login the hive's merger authorizer trusts (the - same bar that releases a `requires_human` verdict), or a dashboard + approval is a GitHub pull-request review in state `APPROVED` that approved + the current head's content, by a login the hive's merger authorizer trusts + (the same bar that releases a `requires_human` verdict). GitHub moves an + existing review's commit onto a later merge of the base, so the review + counts only when it was submitted at or after the head commit's date, or + when the head adds nothing but base merges (by anyone) that leave the PR's + diff unchanged since the commit it approved; the audit comment then says + "carried over a base merge … (PR diff unchanged)" + (projectbluefin/utah#1078). The same rule lets an approval on the previous + head answer the swarm's `requires_human` after such a merge instead of + asking the owner again. The other forms are a dashboard approval (`/hive decision approve`, which posts `/lgtm` + `/approve` attributed to the maintainer and bound to the head) or a trusted merger's own `/hive decision approve` comment posted after the hive first observed @@ -982,7 +990,9 @@ A PR merges through this tier only when all of the following hold: refuses as a reviewer) clears both gates with one command; a decision recorded on the head after the comment stands instead. The audit comment says whether the approval answered the verdict or which command still - does + does. When the approval is already recorded and the PR is parked for + another reason, **What to do** says there is nothing more to approve + instead of asking for it again ([Danathar/zfs-aurora-complex#254](https://github.com/Danathar/zfs-aurora-complex/pull/254)). When released the lane logs `workflow-path fence released by owner approval login=… head=…`, leaves one `` audit diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go index a5a16d08ca..2e5dd99d2e 100644 --- a/src/pkg/github/automerge/automerge_contributor_workflow_approval.go +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval.go @@ -131,7 +131,7 @@ func (c *Engine) workflowFenceReleased(ctx context.Context, displayRepo, owner, } if !hasCommentWithPrefix(comments, workflowApprovalMarker(headSHA)) { c.info("workflow-path fence released by owner approval", "repo", displayRepo, "pr", number, "login", approver, "head", headSHA) - if err := c.commentWorkflowApproval(ctx, owner, repo, number, headSHA, approver, verdictState); err != nil { + if err := c.commentWorkflowApproval(ctx, owner, repo, number, headSHA, approver, verdictState, approval.CarriedOverBaseMerge); err != nil { c.warn("workflow-path fence: could not post audit comment", "repo", displayRepo, "pr", number, "head", headSHA, "error", err) } } @@ -149,6 +149,9 @@ type workflowApproval struct { // AnswersVerdict: the typed comment was recorded as the person's // answer to the reviewer's requires_human question on the head. AnswersVerdict bool + // CarriedOverBaseMerge: the review approved an earlier commit and head + // adds only base merges that leave the PR's diff unchanged. + CarriedOverBaseMerge bool } // recordTypedApprovalDecision records a typed `/hive decision approve` as @@ -226,8 +229,8 @@ func (c *Engine) typedDecisionApprovalAnswer(ctx context.Context, displayRepo, o // bound to headSHA: an APPROVED review on the head first, then an approval // comment (dashboard-posted or typed) among comments bound to it. func (c *Engine) workflowFenceApproval(ctx context.Context, owner, repo string, pr *gh.PullRequest, number int, headSHA string, comments []*gh.IssueComment) (workflowApproval, bool) { - if login, ok := c.latestTrustedHumanApproval(ctx, owner, repo, number, headSHA); ok { - return workflowApproval{Login: login}, true + if login, carried, ok := c.latestTrustedHumanApprovalReach(ctx, owner, repo, number, headSHA); ok { + return workflowApproval{Login: login, CarriedOverBaseMerge: carried}, true } approval, ok := c.latestTrustedCommentApproval(owner, repo, pr, number, headSHA, comments) if !ok { @@ -343,7 +346,7 @@ func workflowApprovalMarker(headSHA string) string { // owner told only "merges once the gates clear" while the verdict still // held the PR waited hours for a merge that never came // (Danathar/zfs-aurora-complex#254). -func workflowApprovalComment(headSHA, approver string, verdictState int) string { +func workflowApprovalComment(headSHA, approver string, verdictState int, carried bool) string { gates := "the hive merges this PR itself once the usual gates (CI, soak, holds, review verdict) are clear." switch verdictState { case workflowApprovalVerdictAnswered: @@ -351,15 +354,21 @@ func workflowApprovalComment(headSHA, approver string, verdictState int) string case workflowApprovalVerdictOpen: gates = "the review swarm's `requires_human` verdict on this head still holds the PR. A trusted merger's `/hive decision approve` reply (or the dashboard's approval) answers it, as does a `/hive approve` reply posted after the verdict; then the hive merges this PR itself once the usual gates (CI, soak, holds) are clear." } + approved := "approved head `" + shortSHA(headSHA) + "`" + if carried { + // The review was on an earlier commit; head only merges the base in + // (reviewReachesHead), so say so rather than claim this head. + approved = "approved this PR's change, carried over a base merge to head `" + shortSHA(headSHA) + "` (PR diff unchanged)" + } return workflowApprovalMarker(headSHA) + " by=" + strings.ToLower(approver) + " -->\n" + - "@" + approver + " approved head `" + shortSHA(headSHA) + "`, which edits CI workflow / action files. That explicit owner approval releases the contributor lane's workflow-path fence: " + gates + " A new push re-arms the fence until the new head is approved again." + "@" + approver + " " + approved + ", which edits CI workflow / action files. That explicit owner approval releases the contributor lane's workflow-path fence: " + gates + " A new push re-arms the fence until the new head is approved again." } // commentWorkflowApproval posts the audit comment once per head: an existing // marker on the PR, or a prior effects claim, suppresses it. -func (c *Engine) commentWorkflowApproval(ctx context.Context, owner, repo string, number int, headSHA, approver string, verdictState int) error { +func (c *Engine) commentWorkflowApproval(ctx context.Context, owner, repo string, number int, headSHA, approver string, verdictState int, carried bool) error { marker := workflowApprovalMarker(headSHA) - body := workflowApprovalComment(headSHA, approver, verdictState) + body := workflowApprovalComment(headSHA, approver, verdictState, carried) _, err := effects.Execute(hgithub.WithRESTCaller(ctx, workflowApprovalRESTCaller), c.mutation, effects.Claim{ Repo: owner + "/" + repo, Kind: effects.KindIssueComment, diff --git a/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go b/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go index 0e39317f16..6528e07401 100644 --- a/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go +++ b/src/pkg/github/automerge/automerge_contributor_workflow_approval_test.go @@ -291,7 +291,7 @@ func TestContributorLaneWorkflowFenceMarkerOncePerHead(t *testing.T) { fx := validContributorFixture() fx.files = workflowPathFiles() fx.reviews = []map[string]any{ownerApprovedReview("clubanderson", "sha7")} - fx.prComments = []map[string]any{{"id": 5, "user": map[string]string{"login": testHiveAppBotLogin}, "body": workflowApprovalComment("sha7", "clubanderson", workflowApprovalVerdictNone)}} + fx.prComments = []map[string]any{{"id": 5, "user": map[string]string{"login": testHiveAppBotLogin}, "body": workflowApprovalComment("sha7", "clubanderson", workflowApprovalVerdictNone, false)}} api := newContributorLaneAPI(t, &fx) defer api.Close() policy := defaultContributorLanePolicy() diff --git a/src/pkg/github/automerge/automerge_human_changes_requested.go b/src/pkg/github/automerge/automerge_human_changes_requested.go index e200e961c1..93f2dd3f72 100644 --- a/src/pkg/github/automerge/automerge_human_changes_requested.go +++ b/src/pkg/github/automerge/automerge_human_changes_requested.go @@ -58,9 +58,17 @@ func (c *Engine) latestTrustedHumanReview(ctx context.Context, owner, repo strin opts.Page = resp.NextPage } c.noteStageReviews(owner, repo, number, seen) + approval := strings.EqualFold(state, "APPROVED") var found *gh.PullRequestReview for login, rv := range latest { - if !strings.EqualFold(rv.GetState(), state) || strings.TrimSpace(rv.GetCommitID()) != strings.TrimSpace(head) { + if !strings.EqualFold(rv.GetState(), state) { + continue + } + // A change request binds to its commit; an approval binds to the + // content it approved, which a base merge carries and a content push + // does not, whatever commit_id GitHub reports + // (automerge_review_head_binding.go). + if !approval && strings.TrimSpace(rv.GetCommitID()) != strings.TrimSpace(head) { continue } if c.isHiveAppReviewAuthor(rv) || strings.HasSuffix(login, "[bot]") { @@ -70,6 +78,9 @@ func (c *Engine) latestTrustedHumanReview(ctx context.Context, owner, repo strin if !configured || !trusted { continue } + if approval && !c.reviewReachesHead(ctx, owner, repo, number, head, rv).ok { + continue + } if found == nil || rv.GetSubmittedAt().After(found.GetSubmittedAt().Time) { found = rv } diff --git a/src/pkg/github/automerge/automerge_review_gate.go b/src/pkg/github/automerge/automerge_review_gate.go index f2227a15a2..2f755e8b6f 100644 --- a/src/pkg/github/automerge/automerge_review_gate.go +++ b/src/pkg/github/automerge/automerge_review_gate.go @@ -312,13 +312,21 @@ func reviewGateRecordLane(lane string) string { } func (c *Engine) latestTrustedHumanApproval(ctx context.Context, owner, repo string, number int, head string) (string, bool) { + login, _, ok := c.latestTrustedHumanApprovalReach(ctx, owner, repo, number, head) + return login, ok +} + +// latestTrustedHumanApprovalReach is latestTrustedHumanApproval plus whether +// the approval reaches head only by being carried over base merges +// (reviewReachesHead), so the fence comment can say so. +func (c *Engine) latestTrustedHumanApprovalReach(ctx context.Context, owner, repo string, number int, head string) (string, bool, bool) { rv, ok := c.latestTrustedHumanReview(ctx, owner, repo, number, head, "APPROVED") if !ok { - return "", false + return "", false, false } login := strings.TrimSpace(hgithub.SafeGetLogin(rv.GetUser())) c.noteStageTrustedHumanApproval(owner, repo, number, head, login) - return login, true + return login, c.reviewReachesHead(ctx, owner, repo, number, head, rv).carried, true } func (c *Engine) trustedHumanApprovalForRequiresHuman(ctx context.Context, owner, repo string, number int, head string, verdict ContributorLaneVerdict) (string, bool) { diff --git a/src/pkg/github/automerge/automerge_review_head_binding.go b/src/pkg/github/automerge/automerge_review_head_binding.go new file mode 100644 index 0000000000..99b7e0cb78 --- /dev/null +++ b/src/pkg/github/automerge/automerge_review_head_binding.go @@ -0,0 +1,135 @@ +package automerge + +// An approving review counts for the head only when it approved that +// content (hivecommons/hive#14664's "a new push re-arms the fence"). +// +// GitHub moves a person's existing review onto a merge of the base into the +// branch: projectbluefin/utah#1078's review submitted 2026-11-04 01:17Z is +// reported on 9d8ceab, a base merge made 2026-11-05 19:50Z, and the hive +// said "@Danathar approved head 9d8ceab" and merged it. Read alone, +// commit_id cannot tell that from an approval of the head. The hive's own +// base refresh does the opposite: the review stays on the old head, and the +// owner's answer to requires_human was asked for again +// (projectbluefin/utah-packages#877). +// +// So a trusted APPROVED review reaches head when either +// - it was submitted at or after the head commit's date, or +// - head is a chain of base merges (BaseMergeParent: the PR's diff +// unchanged, whoever merged) back to the commit the review approved, or +// to a commit no newer than the review. The approval is then "carried +// over a base merge", and the fence comment says so. +// A review with no submitted_at keeps the old commit_id rule. + +import ( + "context" + "strconv" + "strings" + "sync" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" +) + +// approvalCarryMaxHops bounds the base merges walked back from the head. +const approvalCarryMaxHops = 5 + +const approvalReachCacheLimit = 4096 + +// approvalReach is whether a review reaches a head, and whether only by +// being carried over base merges. +type approvalReach struct { + ok, carried bool +} + +type approvalReachCache struct { + mu sync.Mutex + m map[string]approvalReach +} + +func (c *approvalReachCache) get(key string) (approvalReach, bool) { + c.mu.Lock() + defer c.mu.Unlock() + r, ok := c.m[key] + return r, ok +} + +func (c *approvalReachCache) put(key string, r approvalReach) { + c.mu.Lock() + defer c.mu.Unlock() + if c.m == nil || len(c.m) >= approvalReachCacheLimit { + c.m = map[string]approvalReach{} + } + c.m[key] = r +} + +// reviewReachesHead answers for one APPROVED review. The answer for a fixed +// review and head never changes, so it is memoised; a lookup failure is +// not memoised and reads as false (the fence stays, the person is asked). +func (c *Engine) reviewReachesHead(ctx context.Context, owner, repo string, number int, head string, rv *gh.PullRequestReview) approvalReach { + head = strings.TrimSpace(head) + reviewed := strings.TrimSpace(rv.GetCommitID()) + submitted := rv.GetSubmittedAt().Time + if submitted.IsZero() { + return approvalReach{ok: reviewed == head} + } + if c == nil || c.gh == nil || head == "" { + return approvalReach{} + } + key := owner + "/" + repo + "#" + strconv.Itoa(number) + "@" + head + "<-" + strconv.FormatInt(rv.GetID(), 10) + ":" + reviewed + if r, ok := c.approvalReach.get(key); ok { + return r + } + r, known := c.walkApprovalToHead(ctx, owner, repo, number, head, reviewed, submitted) + if known { + c.approvalReach.put(key, r) + } + return r +} + +// walkApprovalToHead does the reads. known is false when GitHub could not be +// read, so the caller does not memoise the answer. +func (c *Engine) walkApprovalToHead(ctx context.Context, owner, repo string, number int, head, reviewed string, submitted time.Time) (approvalReach, bool) { + ctx = hgithub.WithRESTCaller(ctx, "hive:approval_head_binding") + commit, _, err := c.gh.Repositories.GetCommit(ctx, owner, repo, head, nil) + if err != nil || commit == nil { + return approvalReach{}, false + } + if reviewed == head && !submitted.Before(commitDate(commit)) { + return approvalReach{ok: true}, true + } + pr, _, err := c.gh.PullRequests.Get(ctx, owner, repo, number) + if err != nil || pr == nil { + return approvalReach{}, false + } + baseRef := strings.TrimSpace(pr.GetBase().GetRef()) + cur := head + for hop := 0; hop < approvalCarryMaxHops; hop++ { + prev, ok := hgithub.BaseMergeParent(ctx, c.gh.Repositories, owner, repo, baseRef, commit, cur) + if !ok { + return approvalReach{}, true + } + if prev == reviewed { + return approvalReach{ok: true, carried: true}, true + } + if commit, _, err = c.gh.Repositories.GetCommit(ctx, owner, repo, prev, nil); err != nil || commit == nil { + return approvalReach{}, false + } + if reviewed == head && !submitted.Before(commitDate(commit)) { + // GitHub moved the review off this commit onto the merges above. + return approvalReach{ok: true, carried: true}, true + } + cur = prev + } + return approvalReach{}, true +} + +func commitDate(commit *gh.RepositoryCommit) time.Time { + if commit == nil || commit.GetCommit() == nil { + return time.Time{} + } + if d := commit.GetCommit().GetCommitter().GetDate().Time; !d.IsZero() { + return d + } + return commit.GetCommit().GetAuthor().GetDate().Time +} diff --git a/src/pkg/github/automerge/automerge_review_head_binding_test.go b/src/pkg/github/automerge/automerge_review_head_binding_test.go new file mode 100644 index 0000000000..8febae6be6 --- /dev/null +++ b/src/pkg/github/automerge/automerge_review_head_binding_test.go @@ -0,0 +1,148 @@ +package automerge + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// The PR's commit graph for the binding tests. f166 is the content the owner +// approved at 2026-11-04T01:17Z. merge1 merges the base (b2) into it and +// leaves the PR's diff unchanged; content1 is a content commit made after +// the approval; merge2 merges the base into content1. +type bindingGraph struct { + mu sync.Mutex + reviews []map[string]any + calls int +} + +func bindingCommit(sha, date string, parents ...string) map[string]any { + ps := make([]map[string]string, 0, len(parents)) + for _, p := range parents { + ps = append(ps, map[string]string{"sha": p}) + } + return map[string]any{"sha": sha, "parents": ps, "commit": map[string]any{"committer": map[string]string{"date": date}}} +} + +var ( + prDiff = []map[string]any{{"filename": ".github/workflows/ci.yml", "status": "modified", "sha": "blobA", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -1 +1 @@"}} + changedDiff = []map[string]any{{"filename": ".github/workflows/ci.yml", "status": "modified", "sha": "blobB", "additions": 9, "deletions": 1, "changes": 10, "patch": "@@ -1 +9 @@"}} +) + +func newBindingAPI(t *testing.T, g *bindingGraph) *httptest.Server { + t.Helper() + commits := map[string]map[string]any{ + "f166": bindingCommit("f166", "2026-11-02T23:49:05Z", "p0"), + "merge1": bindingCommit("merge1", "2026-11-05T19:50:10Z", "f166", "b2"), + "content1": bindingCommit("content1", "2026-11-05T10:00:00Z", "f166"), + "merge2": bindingCommit("merge2", "2026-11-05T19:50:10Z", "content1", "b2"), + } + compares := map[string]map[string]any{ + "f166": {"merge_base_commit": map[string]string{"sha": "b1"}, "files": prDiff}, + "merge1": {"merge_base_commit": map[string]string{"sha": "b2"}, "files": prDiff}, + "content1": {"merge_base_commit": map[string]string{"sha": "b1"}, "files": changedDiff}, + "merge2": {"merge_base_commit": map[string]string{"sha": "b2"}, "files": changedDiff}, + } + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + g.mu.Lock() + defer g.mu.Unlock() + g.calls++ + w.Header().Set("Content-Type", "application/json") + p := r.URL.Path + switch { + case p == "/repos/acme/widget/pulls/7/reviews": + _ = json.NewEncoder(w).Encode(g.reviews) + case p == "/repos/acme/widget/pulls/7": + _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "base": map[string]string{"ref": "main"}}) + case strings.HasPrefix(p, "/repos/acme/widget/commits/"): + if c, ok := commits[strings.TrimPrefix(p, "/repos/acme/widget/commits/")]; ok { + _ = json.NewEncoder(w).Encode(c) + return + } + w.WriteHeader(http.StatusNotFound) + case strings.HasPrefix(p, "/repos/acme/widget/compare/main..."): + if c, ok := compares[strings.TrimPrefix(p, "/repos/acme/widget/compare/main...")]; ok { + _ = json.NewEncoder(w).Encode(c) + return + } + w.WriteHeader(http.StatusNotFound) + default: + w.WriteHeader(http.StatusNotFound) + } + })) +} + +func ownerReview(commit, submitted string) map[string]any { + r := map[string]any{"id": 11, "state": "APPROVED", "commit_id": commit, "user": map[string]string{"login": "danathar"}} + if submitted != "" { + r["submitted_at"] = submitted + } + return r +} + +// projectbluefin/utah#1078, utah-packages#877, common#1622: a review submitted +// before the head commit existed counts only when the head adds nothing but +// base merges to the content it approved. +func TestApprovalBindsToApprovedContent(t *testing.T) { + const approvedAt = "2026-11-04T01:17:18Z" + for _, tc := range []struct { + name string + review map[string]any + head string + wantOK bool + wantCarried bool + }{ + {name: "submitted after the head commit", review: ownerReview("f166", approvedAt), head: "f166", wantOK: true}, + {name: "GitHub moved it onto a merge-only head", review: ownerReview("merge1", approvedAt), head: "merge1", wantOK: true, wantCarried: true}, + {name: "GitHub moved it onto a head with a content delta", review: ownerReview("merge2", approvedAt), head: "merge2"}, + {name: "on the previous head, base merge since", review: ownerReview("f166", approvedAt), head: "merge1", wantOK: true, wantCarried: true}, + {name: "on the previous head, content push since", review: ownerReview("f166", approvedAt), head: "content1"}, + {name: "on the previous head, content then base merge", review: ownerReview("f166", approvedAt), head: "merge2"}, + {name: "no submitted_at keeps the commit_id rule", review: ownerReview("merge2", ""), head: "merge2", wantOK: true}, + } { + t.Run(tc.name, func(t *testing.T) { + g := &bindingGraph{reviews: []map[string]any{tc.review}} + api := newBindingAPI(t, g) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + c.SetMergerAuthorizer(func(login string) bool { return strings.EqualFold(login, "danathar") }) + login, carried, ok := c.latestTrustedHumanApprovalReach(context.Background(), "acme", "widget", 7, tc.head) + if ok != tc.wantOK || carried != tc.wantCarried { + t.Fatalf("approval = %q carried=%v ok=%v, want ok=%v carried=%v", login, carried, ok, tc.wantOK, tc.wantCarried) + } + }) + } +} + +// The answer for a fixed review and head is read from GitHub once. +func TestApprovalBindingIsMemoised(t *testing.T) { + g := &bindingGraph{reviews: []map[string]any{ownerReview("merge1", "2026-11-04T01:17:18Z")}} + api := newBindingAPI(t, g) + defer api.Close() + c := newAutoMergeSweepClient(api.URL) + c.SetMergerAuthorizer(func(login string) bool { return strings.EqualFold(login, "danathar") }) + c.latestTrustedHumanApprovalReach(context.Background(), "acme", "widget", 7, "merge1") + g.mu.Lock() + first := g.calls + g.mu.Unlock() + c.latestTrustedHumanApprovalReach(context.Background(), "acme", "widget", 7, "merge1") + g.mu.Lock() + defer g.mu.Unlock() + if second := g.calls - first; second != 1 { + t.Fatalf("second lookup made %d calls, want 1 (the review list only)", second) + } +} + +func TestWorkflowApprovalCommentSaysCarried(t *testing.T) { + carried := workflowApprovalComment("9d8ceabe7d2a", "Danathar", workflowApprovalVerdictNone, true) + if !strings.Contains(carried, "carried over a base merge") || !strings.Contains(carried, "PR diff unchanged") || strings.Contains(carried, "approved head `") { + t.Fatalf("carried comment:\n%s", carried) + } + if plain := workflowApprovalComment("9d8ceabe7d2a", "Danathar", workflowApprovalVerdictNone, false); !strings.Contains(plain, "approved head `9d8ceabe7d2a`") || strings.Contains(plain, "carried") { + t.Fatalf("plain comment:\n%s", plain) + } +} diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 9e984cc24b..05cc237a09 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -349,6 +349,9 @@ type Engine struct { // baseRefresh memoises whether a PR head is the hive's own base refresh // of the head a decision was recorded on (automerge_decision_carry.go). baseRefresh hgithub.BaseRefreshChecker + // approvalReach memoises whether a trusted approving review reaches a + // head (automerge_review_head_binding.go). + approvalReach approvalReachCache humanMergePathsMu sync.RWMutex humanMergePaths func(repo string) []string diff --git a/src/pkg/github/automerge/automerge_sweep_guards_test.go b/src/pkg/github/automerge/automerge_sweep_guards_test.go index 580425d17e..78fe0a4c4b 100644 --- a/src/pkg/github/automerge/automerge_sweep_guards_test.go +++ b/src/pkg/github/automerge/automerge_sweep_guards_test.go @@ -190,6 +190,10 @@ func newSelfSweepGuardAPI(t *testing.T, fx selfSweepFixture) *httptest.Server { json.NewEncoder(w).Encode(map[string]any{"merged": fx.mergeApplied, "sha": "merge7"}) case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/rules/branches/"): json.NewEncoder(w).Encode([]any{}) // no rulesets + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/commits/sha7": + // The head commit predates every fixture review, so an approval + // on sha7 binds to it (automerge_review_head_binding.go). + json.NewEncoder(w).Encode(map[string]any{"sha": "sha7", "parents": []map[string]string{{"sha": "sha6"}}, "commit": map[string]any{"committer": map[string]string{"date": "2026-10-01T00:00:00Z"}}}) default: t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) } diff --git a/src/pkg/github/pr_decision_base_refresh.go b/src/pkg/github/pr_decision_base_refresh.go index 0d43c6ea53..6a2e58922f 100644 --- a/src/pkg/github/pr_decision_base_refresh.go +++ b/src/pkg/github/pr_decision_base_refresh.go @@ -158,6 +158,42 @@ func mergeIsBaseRefreshOf(ctx context.Context, api BaseRefreshRepos, owner, repo return sameChangedFiles(oldFiles, newFiles) } +// BaseMergeParent reports the PR-side parent of commit (the commit at +// newHead) when it is a merge of baseRef into that parent which leaves the +// PR's three-dot diff against baseRef unchanged, whoever made the merge: +// the other parent is the merge-base with baseRef, and the changed files +// match file for file. It is mergeIsBaseRefreshOf without the App-author +// rule, for questions about content rather than about who pushed: GitHub +// moves a person's approving review onto such a merge (projectbluefin/utah#1078: +// a review submitted 2026-11-04 01:17Z is reported on a merge made +// 2026-11-05 19:50Z). Lookup failures are false. +func BaseMergeParent(ctx context.Context, api BaseRefreshRepos, owner, repo, baseRef string, commit *gh.RepositoryCommit, newHead string) (string, bool) { + baseRef, newHead = strings.TrimSpace(baseRef), strings.TrimSpace(newHead) + if api == nil || commit == nil || len(commit.Parents) != baseRefreshMergeParents || baseRef == "" || newHead == "" { + return "", false + } + first, second := strings.TrimSpace(commit.Parents[0].GetSHA()), strings.TrimSpace(commit.Parents[1].GetSHA()) + newCmp, newFiles, err := compareAllFiles(ctx, api, owner, repo, baseRef, newHead) + if err != nil || newCmp == nil { + return "", false + } + prev := "" + switch strings.TrimSpace(newCmp.GetMergeBaseCommit().GetSHA()) { + case second: + prev = first + case first: + prev = second + } + if prev == "" || prev == newHead { + return "", false + } + _, oldFiles, err := compareAllFiles(ctx, api, owner, repo, baseRef, prev) + if err != nil || !sameChangedFiles(oldFiles, newFiles) { + return "", false + } + return prev, true +} + // compareAllFiles walks every page of the three-dot compare base...head. func compareAllFiles(ctx context.Context, api BaseRefreshRepos, owner, repo, base, head string) (*gh.CommitsComparison, []*gh.CommitFile, error) { opts := &gh.ListOptions{PerPage: 100} diff --git a/src/pkg/github/pr_decision_base_refresh_test.go b/src/pkg/github/pr_decision_base_refresh_test.go index 582b0840c1..2f1b28cae0 100644 --- a/src/pkg/github/pr_decision_base_refresh_test.go +++ b/src/pkg/github/pr_decision_base_refresh_test.go @@ -325,3 +325,33 @@ func TestSameChangedFilesIgnoresOrderButNotContent(t *testing.T) { t.Fatal("App attribution must match the login case-insensitively, [bot] suffix aside, and nobody else") } } + +// BaseMergeParent accepts a diff-preserving base merge whoever made it +// (projectbluefin/utah#1078's 9d8ceab was a web merge by the owner), and +// refuses one that changes the PR's diff or is not a base merge. +func TestBaseMergeParentAnyAuthor(t *testing.T) { + files := []*gh.CommitFile{refreshFile("ci.yml", "blobA", "@@")} + api := &fakeBaseRefreshRepos{ + commits: map[string]*gh.RepositoryCommit{ + "merge": refreshCommit("merge", "Danathar", "head", "base2"), + "changed": refreshCommit("changed", "Danathar", "head", "base2"), + "single": refreshCommit("single", "Danathar", "head"), + }, + compares: map[string]*gh.CommitsComparison{ + "main...head": refreshCompare("base1", files...), + "main...merge": refreshCompare("base2", files...), + "main...changed": refreshCompare("base2", refreshFile("ci.yml", "blobB", "@@ changed")), + "main...single": refreshCompare("base1", files...), + }, + } + ctx := context.Background() + if prev, ok := BaseMergeParent(ctx, api, "o", "r", "main", api.commits["merge"], "merge"); !ok || prev != "head" { + t.Fatalf("diff-preserving merge by a person: prev=%q ok=%v", prev, ok) + } + if _, ok := BaseMergeParent(ctx, api, "o", "r", "main", api.commits["changed"], "changed"); ok { + t.Fatal("a merge that changes the PR's diff must not count") + } + if _, ok := BaseMergeParent(ctx, api, "o", "r", "main", api.commits["single"], "single"); ok { + t.Fatal("a single-parent commit is not a base merge") + } +} diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 167f89023f..ac4434afb7 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -871,7 +871,14 @@ func DecisionActions(r Route) string { } var steps []string head := "`" + ShortSHA(r.Head) + "`" - if r.ManualMerge { + if approver := strings.TrimPrefix(strings.TrimSpace(r.HumanApprover), "@"); approver != "" && (r.ManualMerge || r.Verdict == VerdictRequiresHuman) { + // The approval this step would ask for is already recorded on the + // head: it released the fence and answered requires_human, so the + // park is for another reason (projectbluefin/utah#1078 kept asking + // "a trusted merger approves this head" next to "approved by + // @Danathar"). Say it is done; the reasons name what is left. + steps = append(steps, "nothing more to approve: @"+approver+" approved this head ("+head+"); resolve the other reasons listed above") + } else if r.ManualMerge { // Only `/hive decision approve` (typed or from the dashboard) and // an Approve review release the fence; `/hive approve` never does // (hivecommons/hive#14672). The first two also answer a diff --git a/src/pkg/stagelabels/human_test.go b/src/pkg/stagelabels/human_test.go index c0c60094f7..7ce1b092f9 100644 --- a/src/pkg/stagelabels/human_test.go +++ b/src/pkg/stagelabels/human_test.go @@ -876,3 +876,35 @@ func TestAlreadyLandedAuthorReason(t *testing.T) { t.Fatalf("unknown = %q", got) } } + +// projectbluefin/utah#1078 (2026-11-04 01:41Z): the head line said "approved +// by @Danathar" while the actions still asked a trusted merger to approve +// that head. With the approval recorded, the actions say it is done and +// leave the other reasons (here the fork's update-branch refusal) to act on. +func TestDecisionActionsDoNotReaskARecordedApproval(t *testing.T) { + e := readyEvidence() + e.Verdict = VerdictRequiresHuman + e.ManualMerge = true + e.ApprovalReleasesFence = true + e.Sentinel = true + r := RouteHuman(e) + r.HumanApprover = "Danathar" + got := DecisionActions(r) + if strings.Contains(got, "a trusted merger approves this head") || strings.Contains(got, "approve this head") { + t.Fatalf("actions re-ask a recorded approval:\n%s", got) + } + for _, want := range []string{"nothing more to approve: @Danathar approved this head (`abc1234`)", "resolve the sentinel alert"} { + if !strings.Contains(got, want) { + t.Fatalf("actions missing %q:\n%s", want, got) + } + } + + // requires_human alone, approver recorded: no approval ask either. + rh := readyEvidence() + rh.Verdict = VerdictRequiresHuman + rr := RouteHuman(rh) + rr.Stage, rr.HumanApprover = NeedsDecision, "@Danathar" + if got := DecisionActions(rr); strings.Contains(got, "approves this head") || !strings.Contains(got, "@Danathar approved this head") { + t.Fatalf("requires_human actions = %q", got) + } +} From 671a78337ed79c2a612a138f6128973365b32766 Mon Sep 17 00:00:00 2001 From: Danathar Date: Thu, 5 Nov 2026 17:07:27 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20fix(automerge):=20a=20review?= =?UTF-8?q?=20GitHub=20reports=20on=20a=20non-merge=20head=20counts=20what?= =?UTF-8?q?ever=20the=20commit=20date?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewer finding 2 on #16817: walkApprovalToHead required submitted_at >= the head commit's date even when commit_id == head and the head is not a merge, so a pusher clock a few minutes fast refused a real approval of that exact head (and memoised the miss). GitHub only moves a review onto a merge, so a review it reports on a non-merge head approved that head. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- src/pkg/github/automerge/automerge_review_head_binding.go | 8 ++++++-- .../automerge/automerge_review_head_binding_test.go | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/pkg/github/automerge/automerge_review_head_binding.go b/src/pkg/github/automerge/automerge_review_head_binding.go index 99b7e0cb78..a0b3ed715e 100644 --- a/src/pkg/github/automerge/automerge_review_head_binding.go +++ b/src/pkg/github/automerge/automerge_review_head_binding.go @@ -13,7 +13,8 @@ package automerge // (projectbluefin/utah-packages#877). // // So a trusted APPROVED review reaches head when either -// - it was submitted at or after the head commit's date, or +// - GitHub reports it on head and head is not a merge, or it was +// submitted at or after the head commit's date, or // - head is a chain of base merges (BaseMergeParent: the PR's diff // unchanged, whoever merged) back to the commit the review approved, or // to a commit no newer than the review. The approval is then "carried @@ -95,7 +96,10 @@ func (c *Engine) walkApprovalToHead(ctx context.Context, owner, repo string, num if err != nil || commit == nil { return approvalReach{}, false } - if reviewed == head && !submitted.Before(commitDate(commit)) { + if reviewed == head && (len(commit.Parents) < 2 || !submitted.Before(commitDate(commit))) { + // GitHub moves a review only onto a merge, so a review it reports on + // a non-merge head approved that head, whatever the pusher's clock + // wrote as its date. return approvalReach{ok: true}, true } pr, _, err := c.gh.PullRequests.Get(ctx, owner, repo, number) diff --git a/src/pkg/github/automerge/automerge_review_head_binding_test.go b/src/pkg/github/automerge/automerge_review_head_binding_test.go index 8febae6be6..f84c139604 100644 --- a/src/pkg/github/automerge/automerge_review_head_binding_test.go +++ b/src/pkg/github/automerge/automerge_review_head_binding_test.go @@ -97,6 +97,7 @@ func TestApprovalBindsToApprovedContent(t *testing.T) { wantCarried bool }{ {name: "submitted after the head commit", review: ownerReview("f166", approvedAt), head: "f166", wantOK: true}, + {name: "non-merge head dated after the review (pusher clock ahead)", review: ownerReview("f166", "2026-11-02T23:40:00Z"), head: "f166", wantOK: true}, {name: "GitHub moved it onto a merge-only head", review: ownerReview("merge1", approvedAt), head: "merge1", wantOK: true, wantCarried: true}, {name: "GitHub moved it onto a head with a content delta", review: ownerReview("merge2", approvedAt), head: "merge2"}, {name: "on the previous head, base merge since", review: ownerReview("f166", approvedAt), head: "merge1", wantOK: true, wantCarried: true},