diff --git a/changelog.d/fixed-15732-already-landed-any-author.md b/changelog.d/fixed-15732-already-landed-any-author.md new file mode 100644 index 0000000000..b4f3eec537 --- /dev/null +++ b/changelog.d/fixed-15732-already-landed-any-author.md @@ -0,0 +1 @@ +- The already-landed close now covers any author's PR, not only the hive's own: when the diff against the base is empty and a merged PR provably carries the change (the reviewer named it and it is merged, the linked issue was closed by a merged PR, or the head is contained in the base) the PR is closed as superseded with thanks instead of parking at 085 for a person; trusted authors are treated the same, and the "Let hive decide" preview gives the empty diff and the merged landing as its reason rather than the author's trust ([#15732](https://github.com/hivecommons/hive/issues/15732)) diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 778d5ed941..940e2c2fe1 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -916,6 +916,30 @@ closed with the redundant-of note. Only when the verdict names no PR *and* the compare is not empty does the PR fall through to 085 as before ([#15647](https://github.com/hivecommons/hive/pull/15647)). +**Already landed, any author.** That entry was the hive's own: #15544, a +trusted contributor's PR for #15543, was +0/−0 against `v5` because +#15545 (merged) carried the identical change, and the reviewer's "should +decide whether #15544 can be closed as a no-op now that #15545 (merged) +carries this change" still parked it at 085 for nine hours. Whether a +change is already on the base is a measurement, not a trust call, so the +already-landed entry now takes any author's PR when the evidence is +unambiguous: the diff against the current base is empty (no files, or +every file byte-identical on the base tip) **and** the landing is proven +— the PR the reviewer named is merged, the issue this PR closes was +closed by a merged PR, or the compare lists no commits (the head is +contained in the base). "#N (merged)" in the reviewer's words names the +landing PR like "via #N" does. The hive comments "already landed via #N +— closing as superseded; thank you @author", closes the PR through the +supersession-close write-back gate, and logs +`already-landed:` (the caption is the same "already landed +via #N — closing as superseded"). A trusted author is treated exactly +like anyone else. A PR with a real diff, an empty PR whose landing is not +proven, a held or `keep-open` PR, or one a person parked keeps the +reviewer's question as before. The "Let hive decide" preview for such a +PR gives the evidence as its reason — "diff is empty — the change already +landed via #N (merged)" — never the author's standing +([#15732](https://github.com/hivecommons/hive/issues/15732)). + ## Usage ```sh diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated.go b/src/pkg/dashboard/api_repo_item_decide_delegated.go index 84f2ecc4b8..60ae17cc8b 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated.go @@ -640,6 +640,7 @@ func (s *Server) gatherDelegatedInput(ctx context.Context, repoFull string, numb if err := s.gatherDelegatedLadderInput(ctx, repoFull, pr, &in); err != nil { return in, err } + in.DiffEmpty = ghpkg.PRChangedFilesClaimsEmpty(pr) state := strings.ToLower(pr.GetMergeableState()) in.Conflicting = state == "dirty" || (pr.Mergeable != nil && !pr.GetMergeable()) green, err := delegatedHeadCIGreen(ctx, api, owner, repoName, pr, in.Conflicting, state) diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go index 9a882787b7..9d00b666ac 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go @@ -253,6 +253,9 @@ func delegatedPlanInstruction(in delegatedecision.Input, d delegatedecision.Deci // what decided it, otherwise the head's blockers, otherwise the first // clause of the rule's rationale with its issue references removed. func delegatedPlanWhy(in delegatedecision.Input, d delegatedecision.Decision) string { + if why := delegatedPlanLandedWhy(in, d); why != "" { + return why + } var parts []string if in.Kind == delegatedecision.KindPR && !in.TrustedAuthor && !in.HiveAuthored && d.Verdict != delegatedecision.VerdictDirection { who := "the author" @@ -280,6 +283,23 @@ func delegatedPlanWhy(in delegatedecision.Input, d delegatedecision.Decision) st return strings.ToUpper(why[:1]) + why[1:] + "." } +// delegatedPlanLandedWhy is the reason when a merged PR already carries +// the change (hivecommons/hive#15732): the preview for #15544 said "Close +// #15544 as superseded by #15545" and then "Author @Karibhou is untrusted +// and their clanker is offline" — the right action for the wrong reason. +// The evidence is the empty diff and the merged landing; the author's +// standing never enters it. Empty for any other decision. +func delegatedPlanLandedWhy(in delegatedecision.Input, d delegatedecision.Decision) string { + if d.Rule != delegatedecision.RuleAlreadyFixed || in.SupersededBy == nil || in.SupersededBy.PR <= 0 { + return "" + } + landed := "the change already landed via #" + strconv.Itoa(in.SupersededBy.PR) + " (merged)" + if in.DiffEmpty { + return "Diff is empty — " + landed + "." + } + return strings.ToUpper(landed[:1]) + landed[1:] + "." +} + // delegatedPlanBlockers names what keeps a head from merging, in plain // words: "CI is red", "it conflicts with the base branch", "the sign-off // is missing". diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go index bf85be770d..932237f6fa 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan_test.go @@ -217,3 +217,37 @@ func TestOperatorActionFromBodyRecordsChosenButton(t *testing.T) { t.Fatalf("%+v %v", req, ok) } } + +// TestDelegatedPlanWhyAlreadyLandedNamesTheEvidence is +// hivecommons/hive#15732: the preview for #15544 said "Close #15544 as +// superseded by #15545" and then "Author @Karibhou is untrusted and their +// clanker is offline". A close driven by an empty diff and a merged +// landing says so, and never mentions the author's standing. +func TestDelegatedPlanWhyAlreadyLandedNamesTheEvidence(t *testing.T) { + in := delegatedecision.Input{Kind: delegatedecision.KindPR, Number: 15544, Author: "Karibhou", DiffEmpty: true, + SupersededBy: &delegatedecision.MergedCloser{PR: 15545, Issue: 15543}} + d := delegatedecision.Decision{Verdict: delegatedecision.VerdictCloseSuperseded, Rule: delegatedecision.RuleAlreadyFixed, + Actions: []delegatedecision.Action{{Kind: delegatedecision.ActionCloseDuplicate, Target: 15545}}} + if why := delegatedPlanWhy(in, d); why != "Diff is empty — the change already landed via #15545 (merged)." { + t.Fatalf("why %q", why) + } + summary, _ := delegatedPlanWording(in, d) + if summary != "Close #15544 as superseded by #15545." { + t.Fatalf("summary %q", summary) + } + // Trusted or not, offline or not: the reason is the evidence. + in.TrustedAuthor, in.ContributorOnline = true, false + if why := delegatedPlanWhy(in, d); strings.Contains(why, "untrusted") || strings.Contains(why, "offline") { + t.Fatalf("why mentions the author's standing: %q", why) + } + // Without the empty-diff fact the landing alone is the reason. + in.DiffEmpty = false + if why := delegatedPlanWhy(in, d); why != "The change already landed via #15545 (merged)." { + t.Fatalf("why %q", why) + } + // Any other rule keeps the author's standing as the reason. + other := delegatedecision.Input{Kind: delegatedecision.KindPR, Number: 15029, Author: "Karibhou"} + if why := delegatedPlanWhy(other, delegatedecision.Decision{Rule: "contributor-offline"}); why != "Author @Karibhou is untrusted and their clanker is offline." { + t.Fatalf("why %q", why) + } +} diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index cd188f8fa3..742da0c34e 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -235,6 +235,11 @@ type Input struct { // work (its issue is closed by that merge, or that PR declares // `Supersedes #N`); nil when none is known (hivecommons/hive#15289). SupersededBy *MergedCloser + // DiffEmpty: the PR's diff against its base is empty (+0/−0, no + // changed files) — with SupersededBy that is the already-landed case + // (hivecommons/hive#15732), and the preview says so instead of + // talking about the author's trust. + DiffEmpty bool // AuthorTooling: what the author drives (hive / clanker / person); // picks the words a decision uses for them (AuthorWord). AuthorTooling AuthorTooling diff --git a/src/pkg/github/automerge/automerge_stage_human.go b/src/pkg/github/automerge/automerge_stage_human.go index 2b62415978..5548bdd1b0 100644 --- a/src/pkg/github/automerge/automerge_stage_human.go +++ b/src/pkg/github/automerge/automerge_stage_human.go @@ -138,11 +138,18 @@ func (c *Engine) closeSupersededBeforeHumanRoute(ctx context.Context, tracker *S hiveAuthored := (pass != nil && pass.AuthorIsApp) || obs.AuthorKind == authorkind.Hive // A person's hold is that person's decision; the rule keeps held PRs, // so it is not asked. - if !hiveAuthored || c.gh == nil || obs.Hold != nil { + if c.gh == nil || obs.Hold != nil { + return false + } + // Another author's PR is asked only the already-landed question, and + // only when the reviewer raised it (hivecommons/hive#15732): the + // closer then proves the landing before closing. Trust changes nothing. + landedClaimed := obs.Detail.VerdictKnown && alreadyLandedClaimed(obs.Detail.Verdict) + if !hiveAuthored && !landedClaimed { return false } closer, ok := c.transport.(supersededCloserTransport) - if !ok { + if !ok && hiveAuthored { return false } cacheKey := key + "@" + obs.HeadSHA @@ -160,13 +167,16 @@ func (c *Engine) closeSupersededBeforeHumanRoute(ctx context.Context, tracker *S c.warn("stage labels: superseded check could not read the PR", "repo", obs.Display, "pr", obs.Number, "error", err) return false } + if !hiveAuthored { + return c.closeEmptyDiffBeforeHumanRoute(ctx, obs, pr, false, now) + } res, err := closer.CloseSupersededHivePRIfEligible(ctx, obs.Owner+"/"+obs.Repo, pr) if err != nil { c.warn("stage labels: superseded check failed", "repo", obs.Display, "pr", obs.Number, "error", err) return false } if !res.Closed { - if c.closeEmptyDiffBeforeHumanRoute(ctx, obs, pr, now) { + if c.closeEmptyDiffBeforeHumanRoute(ctx, obs, pr, true, now) { return true } c.debug("stage labels: hive PR kept", "repo", obs.Display, "pr", obs.Number, "verdict", res.Verdict, "reason", res.Reason) @@ -186,6 +196,12 @@ func alreadyLandedVerdict(v ContributorLaneVerdict) (landed int, claimed bool) { return review.AlreadyLandedFromVerdict(v.RedundantOf, v.DecisionQuestion, v.HumanSummaries) } +// alreadyLandedClaimed is alreadyLandedVerdict's claimed alone. +func alreadyLandedClaimed(v ContributorLaneVerdict) bool { + _, claimed := alreadyLandedVerdict(v) + return claimed +} + // alreadyLandedCloserTransport is the optional transport hook that closes // a hive-authored PR on the reviewer's already-landed verdict // (hgithub.Client.CloseAlreadyLandedHivePRIfEligible; hivecommons/hive#15647). @@ -207,8 +223,11 @@ type alreadyLandedCloserTransport interface { // freshness guard, files identical on the base tip count as no diff, and // the close settles the adoption's lineage — the original the copy // superseded is closed as superseded by the same landed PR, so the orphan -// recovery does not re-adopt a head the base already has. -func (c *Engine) closeEmptyDiffBeforeHumanRoute(ctx context.Context, obs stageObservation, pr *gh.PullRequest, now time.Time) bool { +// recovery does not re-adopt a head the base already has. That entry is +// open to any author (hivecommons/hive#15732); the closer proves the +// landing. hiveAuthored is false for another author's PR, which the plain +// empty-diff rule never touches. +func (c *Engine) closeEmptyDiffBeforeHumanRoute(ctx context.Context, obs stageObservation, pr *gh.PullRequest, hiveAuthored bool, now time.Time) bool { redundantOf, claimed := 0, false if obs.Detail.VerdictKnown { redundantOf, claimed = alreadyLandedVerdict(obs.Detail.Verdict) @@ -218,6 +237,11 @@ func (c *Engine) closeEmptyDiffBeforeHumanRoute(ctx context.Context, obs stageOb return c.closeAlreadyLandedBeforeHumanRoute(ctx, obs, pr, landedCloser, redundantOf, now) } } + if !hiveAuthored { + // The sweep's empty-diff rule is the hive's own; another author's + // PR closes only on the already-landed entry above. + return false + } closer, ok := c.transport.(emptyDiffCloserTransport) if !ok { return false @@ -254,8 +278,8 @@ func (c *Engine) closeAlreadyLandedBeforeHumanRoute(ctx context.Context, obs sta return false } caption, _ := stagelabels.AlreadyLandedCaption(stagelabels.AlreadyLandedReason(res.RedundantOf)) - c.info("stage labels: hive PR closed as already landed instead of a human decision", - "repo", obs.Display, "pr", obs.Number, "reason", stagelabels.LaneReasonAlreadyLanded, "action", res.Reason, + c.info("stage labels: PR closed as already landed instead of a human decision", + "repo", obs.Display, "pr", obs.Number, "reason", stagelabels.AlreadyLandedAuthorReason(obs.AuthorKind), "action", res.Reason, "redundant_of", res.RedundantOf, "issues_closed", res.IssuesClosed, "supersedes", res.Supersedes, "caption", caption, "lane_reason", obs.LaneReason) c.settleAlreadyLandedLineage(ctx, obs, pr.GetNumber(), res.RedundantOf, res.Supersedes, now) return true diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index c81e4a006e..ffdf7f8079 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -2709,3 +2709,122 @@ func TestApplyStageLabelsHiveAlreadyLandedClosesInsteadOfDecision(t *testing.T) t.Fatal("closed copy still on the store") } } + +// TestApplyStageLabelsAnyAuthorAlreadyLandedClosesInsteadOfDecision is +// hivecommons/hive#15732: #15544 by a trusted contributor, +0/−0 against +// v5 because #15545 (merged) carried the change, parked at 085 for 9h on +// "@clubanderson should decide whether #15544 can be closed as a no-op". +// Any author's PR with an already-landed verdict goes to the closer, which +// proves the landing; it never reaches 085. The hive's own superseded rule +// is not asked for another author's PR. +func TestApplyStageLabelsAnyAuthorAlreadyLandedClosesInsteadOfDecision(t *testing.T) { + const number, landed = 15544, 15545 + cases := []struct { + name string + lane string + role stagelabels.Role + login string + }{ + {"contributor", stageLaneContributor, stagelabels.RoleUntrusted, "karibhou"}, + {"trusted", stageLaneTrusted, stagelabels.RoleTrusted, "karibhou"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + api := &stageAPI{} + api.extra = func(w http.ResponseWriter, r *http.Request) bool { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/15544" { + _ = json.NewEncoder(w).Encode(map[string]any{"number": number, "state": "open", "user": map[string]any{"login": tc.login}, + "head": map[string]any{"sha": "k1", "ref": "fix"}, "base": map[string]any{"ref": "v5"}}) + return true + } + return false + } + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 3, 41, 0, 0, time.UTC)} + e, _, store := newStageEngine(t, srv.URL, clock) + e.trustedAuthorPolicy = func() TrustedAuthorPolicy { return TrustedAuthorPolicy{Enabled: true} } + e.contributorLanePolicy = func() ContributorLanePolicy { return ContributorLanePolicy{} } + stage, ok := e.transport.(stageReconcilerTransport) + if !ok { + t.Fatal("engine transport provides no stage writer") + } + spy := &alreadyLandedCloserSpy{Transport: e.transport, stage: stage, result: hgithub.HiveEmptyDiffClose{Closed: true, Empty: true, RedundantOf: landed, Reason: hgithub.SupersessionActionClosedEmptyDiff}} + e.transport = spy + + pr := stagePR(number) + pr.User = &gh.User{Login: gh.Ptr(tc.login)} + e.recordStage(tc.lane, "acme/widget", "acme", "widget", pr, contributorLaneReasonNoVerdict, false, nil) + e.noteStageRole("acme", "widget", number, tc.role) + e.noteStageVerdict("acme", "widget", number, ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true, + DecisionQuestion: "@clubanderson should decide whether #15544 can be closed as a no-op now that #15545 (merged) carries this change"}) + res, err := e.ApplyStageLabels(context.Background()) + if err != nil { + t.Fatal(err) + } + if res.ClosedSuperseded != 1 { + t.Fatalf("ClosedSuperseded=%d want 1", res.ClosedSuperseded) + } + for _, batch := range api.added { + if slices.Contains(batch, "stage/085-needs-decision") { + t.Fatalf("already-landed %s PR routed to 085: added=%v", tc.name, api.added) + } + } + if !reflect.DeepEqual(spy.landedCalls, []int{number}) || !reflect.DeepEqual(spy.redundantOf, []int{landed}) { + t.Fatalf("already-landed closer calls=%v redundant_of=%v", spy.landedCalls, spy.redundantOf) + } + if len(spy.supersededCalls) != 0 { + t.Fatalf("the hive's own superseded rule asked about a %s PR: %v", tc.name, spy.supersededCalls) + } + if _, ok := store.Get(stageKey("acme", "widget", number)); ok { + t.Fatal("closed PR still on the store") + } + }) + } +} + +// TestApplyStageLabelsAnyAuthorAlreadyLandedKeptStillParks: when the closer +// keeps a contributor PR (a real diff, an unproven landing) the decision +// goes to a person as before. +func TestApplyStageLabelsAnyAuthorAlreadyLandedKeptStillParks(t *testing.T) { + const number = 15544 + api := &stageAPI{} + api.extra = func(w http.ResponseWriter, r *http.Request) bool { + if r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/15544" { + _ = json.NewEncoder(w).Encode(map[string]any{"number": number, "state": "open", "user": map[string]any{"login": "karibhou"}, + "head": map[string]any{"sha": "k1", "ref": "fix"}, "base": map[string]any{"ref": "v5"}}) + return true + } + return false + } + srv := newStageAPI(t, api) + defer srv.Close() + clock := &contributorLaneClock{at: time.Date(2026, 10, 20, 3, 41, 0, 0, time.UTC)} + e, _, _ := newStageEngine(t, srv.URL, clock) + e.trustedAuthorPolicy = func() TrustedAuthorPolicy { return TrustedAuthorPolicy{Enabled: true} } + e.contributorLanePolicy = func() ContributorLanePolicy { return ContributorLanePolicy{} } + stage, _ := e.transport.(stageReconcilerTransport) + spy := &alreadyLandedCloserSpy{Transport: e.transport, stage: stage, result: hgithub.HiveEmptyDiffClose{Verdict: "keep", Reason: "has-diff"}} + e.transport = spy + + pr := stagePR(number) + pr.User = &gh.User{Login: gh.Ptr("karibhou")} + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, contributorLaneReasonNoVerdict, false, nil) + e.noteStageRole("acme", "widget", number, stagelabels.RoleUntrusted) + e.noteStageVerdict("acme", "widget", number, ContributorLaneVerdict{Configured: true, Verdict: "requires_human", DecisionRequested: true, + DecisionQuestion: "@clubanderson should decide whether #15544 can be closed as a no-op now that #15545 (merged) carries this change"}) + res, err := e.ApplyStageLabels(context.Background()) + if err != nil { + t.Fatal(err) + } + if res.ClosedSuperseded != 0 || !reflect.DeepEqual(spy.landedCalls, []int{number}) { + t.Fatalf("ClosedSuperseded=%d landedCalls=%v", res.ClosedSuperseded, spy.landedCalls) + } + parked := false + for _, batch := range api.added { + parked = parked || slices.Contains(batch, "stage/085-needs-decision") + } + if !parked { + t.Fatalf("kept contributor PR must still reach 085: added=%v", api.added) + } +} diff --git a/src/pkg/github/pr_empty_diff_hive_autoclose.go b/src/pkg/github/pr_empty_diff_hive_autoclose.go index 9af329f4e4..ccbc752d1b 100644 --- a/src/pkg/github/pr_empty_diff_hive_autoclose.go +++ b/src/pkg/github/pr_empty_diff_hive_autoclose.go @@ -5,6 +5,7 @@ import ( "fmt" "log/slog" "net/http" + "strconv" "strings" "time" @@ -95,8 +96,14 @@ type HiveEmptyDiffAutoCloseFacts struct { // already carries its change. Enabled bool // HiveAuthored: this hive's App (or a login HiveIdentity matches) - // opened the PR. A person's PR is never closed here. + // opened the PR. A person's PR is closed here only when LandingProven. HiveAuthored bool + // LandingProven (hivecommons/hive#15732): a merged PR is known to carry + // this PR's change — the reviewer named one and it is merged, the issue + // this PR closes was closed by a merged PR, or every commit on the head + // is already on the base. With an empty diff that is unambiguous for + // any author kind; trust changes nothing. + LandingProven bool // Merged / Draft / Held / KeptOpen / ParkedByPerson are the guards every // sweep honours. Merged, Draft, Held, KeptOpen, ParkedByPerson bool @@ -123,9 +130,10 @@ type HiveEmptyDiffAutoCloseFacts struct { } // DecideHiveEmptyDiffAutoClose is the pure rule. It returns "close" when the -// hive's own PR measurably adds nothing to its base, "human" when the PR is -// a person's and empty (the caller leaves the decision prompt in place), or -// "keep" with the guard that held. +// hive's own PR measurably adds nothing to its base — or anyone's PR does +// and a merged landing is proven (hivecommons/hive#15732) — "human" when +// the PR is a person's, empty, and no landing is proven (the caller leaves +// the decision prompt in place), or "keep" with the guard that held. func DecideHiveEmptyDiffAutoClose(f HiveEmptyDiffAutoCloseFacts) (verdict, reason string) { switch { case !f.Enabled: @@ -138,7 +146,7 @@ func DecideHiveEmptyDiffAutoClose(f HiveEmptyDiffAutoCloseFacts) (verdict, reaso return hiveEmptyDiffVerdictKeep, hiveEmptyDiffReasonUnknown case f.DiffFiles > 0 && !f.TreeMatchesBase: return hiveEmptyDiffVerdictKeep, hiveEmptyDiffReasonHasDiff - case !f.HiveAuthored: + case !f.HiveAuthored && !f.LandingProven: return hiveEmptyDiffVerdictHumanNote, hiveEmptyDiffReasonNotHive case f.Held: return hiveEmptyDiffVerdictKeep, hiveEmptyDiffReasonHeld @@ -189,28 +197,53 @@ func PRChangedFilesClaimsEmpty(pr *gh.PullRequest) bool { // was cut short. headAt is the newest commit's committer date when the // compare listed commits; when it listed none the head is already on the // base, so it is the merge base's date. Zero when neither is readable. -func (c *Client) prDiffAgainstBase(ctx context.Context, owner, name string, pr *gh.PullRequest) (files []*gh.CommitFile, headAt time.Time, known bool) { +// headOnBase is true when the compare listed no commits: every commit of +// the head is contained in the base. +func (c *Client) prDiffAgainstBase(ctx context.Context, owner, name string, pr *gh.PullRequest) (files []*gh.CommitFile, headAt time.Time, known, headOnBase bool) { base := strings.TrimSpace(pr.GetBase().GetRef()) head := strings.TrimSpace(pr.GetHead().GetSHA()) if base == "" || head == "" { - return nil, time.Time{}, false + return nil, time.Time{}, false, false } comparison, resp, err := c.client.Repositories.CompareCommits(WithRESTCaller(ctx, "hive:empty_diff_autoclose"), owner, name, base, head, &gh.ListOptions{PerPage: githubCompareFileLimit}) if err != nil || comparison == nil { - return nil, time.Time{}, false + return nil, time.Time{}, false, false } for _, commit := range comparison.Commits { if at := commit.GetCommit().GetCommitter().GetDate().Time; at.After(headAt) { headAt = at } } + headOnBase = len(comparison.Commits) == 0 && comparison.GetMergeBaseCommit() != nil if mb := comparison.GetMergeBaseCommit(); len(comparison.Commits) == 0 && strings.EqualFold(mb.GetSHA(), head) { headAt = mb.GetCommit().GetCommitter().GetDate().Time } if (resp != nil && resp.NextPage != 0) || len(comparison.Files) >= githubCompareFileLimit { - return comparison.Files, headAt, false + return comparison.Files, headAt, false, headOnBase } - return comparison.Files, headAt, true + return comparison.Files, headAt, true, headOnBase +} + +// alreadyLandedProof looks for the merged PR that carries pr's change +// (hivecommons/hive#15732), cheapest evidence first: the PR the reviewer +// named, when it is merged; else the merged PR that closed the issue this +// PR claims (detectSupersessionDetail); else the compare having listed no +// commits (the head is already on the base — no single PR named). landed +// is the PR to credit, 0 when the base itself is the landing. +func (c *Client) alreadyLandedProof(ctx context.Context, owner, name string, pr *gh.PullRequest, redundantOf int, headOnBase bool, identity HiveIdentity, now time.Time) (landed int, proven bool) { + if redundantOf > 0 && redundantOf != pr.GetNumber() { + named, _, err := c.client.PullRequests.Get(WithRESTCaller(ctx, "hive:empty_diff_autoclose"), owner, name, redundantOf) + if err == nil && named != nil && (named.GetMerged() || !named.GetMergedAt().IsZero()) { + return redundantOf, true + } + } + if det, err := c.detectSupersessionDetail(ctx, owner+"/"+name, pr, identity, now); err == nil && det.candidate.Issue > 0 && det.closer.Number > 0 { + return det.closer.Number, true + } + if headOnBase { + return 0, true + } + return 0, false } // prFilesIdenticalOnBase proves an already-landed head: every file the @@ -279,6 +312,13 @@ func (c *Client) CloseEmptyDiffHivePRIfEligible(ctx context.Context, repo string // closing references are closed through CloseIssue's usual gates, and the // originals its body declares it supersedes are reported for the caller's // lineage settlement. Redundancy is measured, never taken from the text. +// +// Any author's PR is closed this way (hivecommons/hive#15732: #15544 by a +// trusted contributor sat at 085 for 9h although #15545 had merged the +// same change) when, besides the empty diff, the landing is proven: the +// named PR is merged, the issue this PR closes was closed by a merged PR, +// or the head's commits are all on the base. A person's empty PR with no +// proven landing keeps the reviewer's question. func (c *Client) CloseAlreadyLandedHivePRIfEligible(ctx context.Context, repo string, pr *gh.PullRequest, redundantOf int) (HiveEmptyDiffClose, error) { return c.closeHiveRedundantPR(ctx, repo, pr, redundantOf, true) } @@ -322,15 +362,16 @@ func (c *Client) closeHiveRedundantPR(ctx context.Context, repo string, pr *gh.P out.Verdict, out.Reason = DecideHiveEmptyDiffAutoClose(facts) return out, nil } - if reviewed && !facts.HiveAuthored { - // A person's PR is never closed on the hive's reading of a - // verdict; no compare is spent on it. + if !reviewed && !facts.HiveAuthored { + // The sweep's empty-diff rule never closes a person's PR; only + // the reviewer's already-landed entry proves a landing. out.Verdict, out.Reason = hiveEmptyDiffVerdictHumanNote, hiveEmptyDiffReasonNotHive return out, nil } + headOnBase := false if !facts.DiffKnown { - files, headAt, known := c.prDiffAgainstBase(ctx, owner, name, pr) - facts.DiffFiles, facts.DiffKnown = len(files), known + files, headAt, known, onBase := c.prDiffAgainstBase(ctx, owner, name, pr) + facts.DiffFiles, facts.DiffKnown, headOnBase = len(files), known, onBase facts.HeadAge = emptyDiffHeadAge(pr, headAt, now) if known && len(files) > 0 && reviewed { match, matchKnown := c.prFilesIdenticalOnBase(ctx, owner, name, strings.TrimSpace(pr.GetBase().GetRef()), files) @@ -338,9 +379,19 @@ func (c *Client) closeHiveRedundantPR(ctx context.Context, repo string, pr *gh.P } } out.Empty = facts.DiffKnown && (facts.DiffFiles == 0 || facts.TreeMatchesBase) - if out.Empty && facts.HiveAuthored { + if out.Empty { facts.ParkedByPerson = c.supersessionNeedsHumanByPerson(ctx, owner, name, pr) } + if out.Empty && !facts.HiveAuthored { + // A person's empty PR closes only on proof that the change + // landed; the compare alone could be a branch mid-push. + landed, proven := c.alreadyLandedProof(ctx, owner, name, pr, redundantOf, headOnBase, identity, now) + facts.LandingProven = proven + if proven && landed > 0 { + redundantOf = landed + out.RedundantOf = landed + } + } out.Verdict, out.Reason = DecideHiveEmptyDiffAutoClose(facts) if out.Verdict != hiveEmptyDiffVerdictClose { return out, nil @@ -355,6 +406,9 @@ func (c *Client) closeHiveRedundantPR(ctx context.Context, repo string, pr *gh.P } closer := supersessionCloser{Repo: repo, Number: redundantOf} why := hiveEmptyDiffCloseReason(redundantOf, shortHeadSHA(pr), strings.TrimSpace(pr.GetBase().GetRef()), facts.TreeMatchesBase) + if !facts.HiveAuthored { + why = alreadyLandedCloseReason(redundantOf, event.Author, shortHeadSHA(pr), strings.TrimSpace(pr.GetBase().GetRef()), facts.TreeMatchesBase) + } if _, err := c.ensureSupersessionComment(ctx, owner, name, pr.GetNumber(), renderEmptyDiffCloseComment(closer, why, facts.TreeMatchesBase)); err != nil { return out, err } @@ -367,13 +421,14 @@ func (c *Client) closeHiveRedundantPR(ctx context.Context, repo string, pr *gh.P } } if c.logger != nil { - c.logger.Info("empty-diff auto-close: closed hive-authored PR with no diff against its base", - slog.String("repo", repo), slog.Int("pr", pr.GetNumber()), slog.Int("redundant_of", redundantOf), slog.String("action", event.Action)) + c.logger.Info("empty-diff auto-close: closed PR with no diff against its base", + slog.String("repo", repo), slog.Int("pr", pr.GetNumber()), slog.Int("redundant_of", redundantOf), slog.String("action", event.Action), + slog.Bool("hive_authored", facts.HiveAuthored), slog.Bool("landing_proven", facts.LandingProven)) } out.Closed = true if reviewed { out.Supersedes = SupersedesDeclared(pr.GetBody()) - out.IssuesClosed = c.closeIssuesAlreadyLanded(ctx, owner, name, pr, redundantOf) + out.IssuesClosed = c.closeIssuesAlreadyLanded(ctx, owner, name, pr, redundantOf, facts.HiveAuthored) } return out, nil } @@ -385,7 +440,7 @@ func (c *Client) closeHiveRedundantPR(ctx context.Context, repo string, pr *gh.P // landed it — only once the close went through, so a refused close leaves // no "done" note on an open issue. Failures are logged, never fatal: the // PR close stands. -func (c *Client) closeIssuesAlreadyLanded(ctx context.Context, owner, name string, pr *gh.PullRequest, redundantOf int) []int { +func (c *Client) closeIssuesAlreadyLanded(ctx context.Context, owner, name string, pr *gh.PullRequest, redundantOf int, hiveAuthored bool) []int { repo := owner + "/" + name var closed []int for _, number := range ClosingIssueRefs(pr.GetBody(), repo) { @@ -406,7 +461,7 @@ func (c *Client) closeIssuesAlreadyLanded(ctx context.Context, owner, name strin continue } closed = append(closed, number) - note := alreadyLandedIssueNote(pr.GetNumber(), redundantOf, strings.TrimSpace(pr.GetBase().GetRef())) + note := alreadyLandedIssueNote(pr.GetNumber(), redundantOf, strings.TrimSpace(pr.GetBase().GetRef()), hiveAuthored) if _, _, err := c.client.Issues.CreateComment(ctx, owner, name, number, &gh.IssueComment{Body: gh.Ptr(note)}); err != nil && c.logger != nil { // writeback:gated c.logger.Warn("already-landed auto-close: issue note failed", slog.String("repo", repo), slog.Int("issue", number), slog.String("error", err.Error())) } @@ -416,11 +471,15 @@ func (c *Client) closeIssuesAlreadyLanded(ctx context.Context, owner, name strin // alreadyLandedIssueNote is the one-line note on an issue closed because // the PR that claimed it was already landed through another PR. -func alreadyLandedIssueNote(pr, redundantOf int, base string) string { +func alreadyLandedIssueNote(pr, redundantOf int, base string, hiveAuthored bool) string { + whose := "#" + strconv.Itoa(pr) + if hiveAuthored { + whose = "its own " + whose + } if redundantOf > 0 { - return fmt.Sprintf("%s #%d -->\nThe hive closed its own #%d as superseded: the change it carried is already on `%s` via #%d, so this issue is done. Reopen if that's wrong.", reviewRedundantOfMarker, redundantOf, pr, base, redundantOf) + return fmt.Sprintf("%s #%d -->\nThe hive closed %s as superseded: the change it carried is already on `%s` via #%d, so this issue is done. Reopen if that's wrong.", reviewRedundantOfMarker, redundantOf, whose, base, redundantOf) } - return fmt.Sprintf("The hive closed its own #%d as superseded: the change it carried is already on `%s`, so this issue is done. Reopen if that's wrong.", pr, base) + return fmt.Sprintf("The hive closed %s as superseded: the change it carried is already on `%s`, so this issue is done. Reopen if that's wrong.", whose, base) } // emptyDiffHeadAge measures from the compare's newest commit (headAt) when @@ -461,6 +520,24 @@ func hiveEmptyDiffCloseReason(redundantOf int, head, base string, treeMatches bo return fmt.Sprintf("Closing this hive-authored PR: head %s is identical to `%s` (%s), so there is nothing left to merge. Reopen if that's wrong.", head, base, proof) } +// alreadyLandedCloseReason is the one-line why of the close comment for a +// PR the hive did not author (hivecommons/hive#15732): the change landed +// via another PR, so the PR is closed as superseded with thanks. +func alreadyLandedCloseReason(redundantOf int, author, head, base string, treeMatches bool) string { + proof := "the compare lists no files" + if treeMatches { + proof = "every file it touches is already byte-identical on the base tip" + } + thanks := "thank you for the work." + if a := strings.TrimSpace(author); a != "" { + thanks = "thank you @" + a + "." + } + if redundantOf > 0 { + return fmt.Sprintf("Already landed via #%d — closing as superseded; %s Head %s is identical to `%s` (%s), so the change this PR carried is already on the base. Reopen if that's wrong.", redundantOf, thanks, head, base, proof) + } + return fmt.Sprintf("Already landed on `%s` — closing as superseded; %s Head %s is identical to the base (%s), so there is nothing left to merge. Reopen if that's wrong.", base, thanks, head, proof) +} + // renderEmptyDiffCloseComment is the close notice, under the supersession // marker so ensureSupersessionComment edits it in place and the // `hive-redundant-of` marker so the dashboard and the dedupe key read the diff --git a/src/pkg/github/pr_empty_diff_hive_autoclose_test.go b/src/pkg/github/pr_empty_diff_hive_autoclose_test.go index de4a71539a..3adfd8da42 100644 --- a/src/pkg/github/pr_empty_diff_hive_autoclose_test.go +++ b/src/pkg/github/pr_empty_diff_hive_autoclose_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "reflect" + "slices" "strings" "sync" "testing" @@ -58,6 +59,23 @@ func TestDecideHiveEmptyDiffAutoClose(t *testing.T) { f.TreeMatchesBase = true f.HiveAuthored = false }), hiveEmptyDiffVerdictHumanNote, hiveEmptyDiffReasonNotHive}, + // hivecommons/hive#15732: a person's empty PR whose landing is + // proven closes like the hive's own; a real diff still keeps it. + {"person's empty PR with a proven landing closes", with(func(f *HiveEmptyDiffAutoCloseFacts) { + f.HiveAuthored = false + f.LandingProven = true + f.ReviewerConfirmed = true + }), hiveEmptyDiffVerdictClose, SupersessionActionClosedEmptyDiff}, + {"person's PR with a real diff keeps even with a landing", with(func(f *HiveEmptyDiffAutoCloseFacts) { + f.HiveAuthored = false + f.LandingProven = true + f.DiffFiles = 1 + }), hiveEmptyDiffVerdictKeep, hiveEmptyDiffReasonHasDiff}, + {"person's proven-landed PR parked by a person keeps", with(func(f *HiveEmptyDiffAutoCloseFacts) { + f.HiveAuthored = false + f.LandingProven = true + f.ParkedByPerson = true + }), hiveEmptyDiffVerdictKeep, hiveEmptyDiffReasonPerson}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -170,7 +188,7 @@ func TestPRDiffAgainstBaseHeadOnBaseUsesMergeBaseDate(t *testing.T) { c := NewClientForTest(ts.URL, "hivecommons", []string{"hive"}, slog.Default()) pr := &gh.PullRequest{Base: &gh.PullRequestBranch{Ref: gh.Ptr("v5")}, Head: &gh.PullRequestBranch{SHA: gh.Ptr("head999")}} - files, headAt, known := c.prDiffAgainstBase(context.Background(), "hivecommons", "hive", pr) + files, headAt, known, _ := c.prDiffAgainstBase(context.Background(), "hivecommons", "hive", pr) if !known || len(files) != 0 { t.Fatalf("diff = %d files, known=%v; want empty and known", len(files), known) } @@ -207,7 +225,7 @@ func TestCloseIssuesAlreadyLandedNotesOnlyClosedIssues(t *testing.T) { c := testClient(t, srv.URL) pr := &gh.PullRequest{Number: gh.Ptr(7), Body: gh.Ptr("Closes #1\nCloses #2"), Base: &gh.PullRequestBranch{Ref: gh.Ptr("v5")}} - got := c.closeIssuesAlreadyLanded(context.Background(), "o", "r", pr, 5) + got := c.closeIssuesAlreadyLanded(context.Background(), "o", "r", pr, 5, true) if !reflect.DeepEqual(got, []int{2}) { t.Fatalf("closed = %v, want [2]", got) } @@ -218,3 +236,149 @@ func TestCloseIssuesAlreadyLandedNotesOnlyClosedIssues(t *testing.T) { t.Fatalf("done notes = %v, want only on the closed issue %v", comments, want) } } + +// alreadyLandedAnyAuthorServer is a GitHub stand-in for the any-author +// already-landed close (hivecommons/hive#15732): PR 15544 by a person, +// compare base...head as given, PR 15545 merged or not. +type alreadyLandedAnyAuthorServer struct { + mu sync.Mutex + compare map[string]any + landedOK bool + closed bool + comments []string + labels []string +} + +func (s *alreadyLandedAnyAuthorServer) handler(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/o/r/compare/"): + _ = json.NewEncoder(w).Encode(s.compare) + case r.Method == http.MethodGet && r.URL.Path == "/repos/o/r/pulls/15545": + pr := map[string]any{"number": 15545, "state": "closed", "user": map[string]any{"login": "clubanderson"}} + if s.landedOK { + pr["merged"] = true + pr["merged_at"] = "2026-10-20T01:00:00Z" + } + _ = json.NewEncoder(w).Encode(pr) + case r.Method == http.MethodGet && r.URL.Path == "/repos/o/r/issues/15544/comments": + _ = json.NewEncoder(w).Encode([]map[string]any{}) + case r.Method == http.MethodPost && r.URL.Path == "/repos/o/r/issues/15544/comments": + var c struct{ Body string } + _ = json.NewDecoder(r.Body).Decode(&c) + s.comments = append(s.comments, c.Body) + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1}) + case r.Method == http.MethodPost && r.URL.Path == "/repos/o/r/issues/15544/labels": + var names []string + _ = json.NewDecoder(r.Body).Decode(&names) + s.labels = append(s.labels, names...) + _ = json.NewEncoder(w).Encode([]map[string]any{}) + case r.Method == http.MethodPatch && r.URL.Path == "/repos/o/r/issues/15544": + s.closed = true + _ = json.NewEncoder(w).Encode(map[string]any{"number": 15544, "state": "closed"}) + case strings.HasPrefix(r.URL.Path, "/repos/o/r/labels"): + _ = json.NewEncoder(w).Encode(map[string]any{"name": SupersededLabel}) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/o/r/contents/"): + _ = json.NewEncoder(w).Encode(map[string]any{"sha": "base-blob", "type": "file"}) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func alreadyLandedContributorPR(login string, changed int) *gh.PullRequest { + return &gh.PullRequest{Number: gh.Ptr(15544), State: gh.Ptr("open"), Title: gh.Ptr("fix: thing"), Body: gh.Ptr("No closing refs."), + User: &gh.User{Login: gh.Ptr(login)}, ChangedFiles: gh.Ptr(changed), Additions: gh.Ptr(0), Deletions: gh.Ptr(0), + Head: &gh.PullRequestBranch{SHA: gh.Ptr("k1k1k1k1k1")}, Base: &gh.PullRequestBranch{Ref: gh.Ptr("v5")}, + CreatedAt: &gh.Timestamp{Time: time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)}} +} + +// TestCloseAlreadyLandedAnyAuthorClosesOnProvenLanding is +// hivecommons/hive#15732: #15544 by a contributor was +0/−0 against v5 +// because #15545 (merged) carried the same change, and sat at 085 for 9h. +// With the empty diff and the named PR merged the hive closes it as +// superseded, thanking the author; trust is not consulted. +func TestCloseAlreadyLandedAnyAuthorClosesOnProvenLanding(t *testing.T) { + for _, login := range []string{"karibhou", "trusted-maintainer"} { + t.Run(login, func(t *testing.T) { + api := &alreadyLandedAnyAuthorServer{landedOK: true, compare: map[string]any{"files": []any{}, "commits": []any{}, "status": "identical"}} + srv := httptest.NewServer(http.HandlerFunc(api.handler)) + defer srv.Close() + c := testClient(t, srv.URL) + res, err := c.CloseAlreadyLandedHivePRIfEligible(context.Background(), "o/r", alreadyLandedContributorPR(login, 0), 15545) + if err != nil { + t.Fatal(err) + } + if !res.Closed || !res.Empty || res.RedundantOf != 15545 || res.Reason != SupersessionActionClosedEmptyDiff { + t.Fatalf("res = %+v, want closed empty redundant_of=15545", res) + } + if !api.closed || !slices.Contains(api.labels, SupersededLabel) { + t.Fatalf("closed=%v labels=%v", api.closed, api.labels) + } + if len(api.comments) != 1 || !strings.Contains(api.comments[0], "Already landed via #15545 — closing as superseded; thank you @"+login+".") || strings.Contains(api.comments[0], "hive-authored") { + t.Fatalf("comment = %q", api.comments) + } + }) + } +} + +// TestCloseAlreadyLandedAnyAuthorKeepsRealDiff: a contributor PR whose +// compare lists a file that differs on the base tip is not closed; the +// reviewer's question stands as before. +func TestCloseAlreadyLandedAnyAuthorKeepsRealDiff(t *testing.T) { + api := &alreadyLandedAnyAuthorServer{landedOK: true, compare: map[string]any{ + "files": []map[string]any{{"filename": "pkg/a.go", "status": "modified", "sha": "head-blob"}}, + "commits": []map[string]any{{"sha": "k1k1k1k1k1"}}, + }} + srv := httptest.NewServer(http.HandlerFunc(api.handler)) + defer srv.Close() + c := testClient(t, srv.URL) + res, err := c.CloseAlreadyLandedHivePRIfEligible(context.Background(), "o/r", alreadyLandedContributorPR("karibhou", 1), 15545) + if err != nil { + t.Fatal(err) + } + if res.Closed || res.Empty || res.Verdict != hiveEmptyDiffVerdictKeep || res.Reason != hiveEmptyDiffReasonHasDiff { + t.Fatalf("res = %+v, want kept has-diff", res) + } + if api.closed || len(api.comments) != 0 { + t.Fatalf("a real diff must not be touched: closed=%v comments=%v", api.closed, api.comments) + } +} + +// TestCloseAlreadyLandedAnyAuthorNeedsProof: an empty contributor PR whose +// named PR is not merged (and whose head is not on the base) keeps the +// reviewer's question — the empty compare alone could be a branch +// mid-push. With the head on the base the proof is the compare itself. +func TestCloseAlreadyLandedAnyAuthorNeedsProof(t *testing.T) { + api := &alreadyLandedAnyAuthorServer{landedOK: false, compare: map[string]any{"files": []any{}, "commits": []map[string]any{{"sha": "k1k1k1k1k1"}}}} + srv := httptest.NewServer(http.HandlerFunc(api.handler)) + defer srv.Close() + c := testClient(t, srv.URL) + res, err := c.CloseAlreadyLandedHivePRIfEligible(context.Background(), "o/r", alreadyLandedContributorPR("karibhou", 0), 15545) + if err != nil { + t.Fatal(err) + } + if res.Closed || !res.Empty || res.Verdict != hiveEmptyDiffVerdictHumanNote || res.Reason != hiveEmptyDiffReasonNotHive { + t.Fatalf("res = %+v, want human/not-hive (unproven landing)", res) + } + + api.mu.Lock() + api.compare = map[string]any{"files": []any{}, "commits": []any{}, "merge_base_commit": map[string]any{"sha": "k1k1k1k1k1"}} + api.mu.Unlock() + res, err = c.CloseAlreadyLandedHivePRIfEligible(context.Background(), "o/r", alreadyLandedContributorPR("karibhou", 0), 0) + if err != nil { + t.Fatal(err) + } + if !res.Closed || res.RedundantOf != 0 || len(api.comments) != 1 || !strings.Contains(api.comments[0], "Already landed on `v5` — closing as superseded; thank you @karibhou.") { + t.Fatalf("res = %+v comments=%q, want closed on head-on-base proof", res, api.comments) + } +} + +func TestAlreadyLandedIssueNoteNamesWhosePR(t *testing.T) { + if got := alreadyLandedIssueNote(15544, 15545, "v5", false); strings.Contains(got, "its own") || !strings.Contains(got, "closed #15544 as superseded") { + t.Fatalf("contributor note = %q", got) + } + if got := alreadyLandedIssueNote(15647, 15506, "v5", true); !strings.Contains(got, "its own #15647") { + t.Fatalf("hive note = %q", got) + } +} diff --git a/src/pkg/review/already_landed.go b/src/pkg/review/already_landed.go index d2c6c8f27d..71201d0e42 100644 --- a/src/pkg/review/already_landed.go +++ b/src/pkg/review/already_landed.go @@ -29,6 +29,11 @@ var ( // landing PR from a lineage mention. alreadyLandedRefRE = regexp.MustCompile(`(?i)\b(via|through|in|by|since|landed in|merged (?:in|as|via|through))\s+(?:[\w.-]+/[\w.-]+)?#(\d+)\b`) alreadyLandedPullURLRE = regexp.MustCompile(`(?i)\b(via|through|in|by|since)\s+https?://[^\s/]+/[\w.-]+/[\w.-]+/pull/(\d+)\b`) + // alreadyLandedMergedRefRE captures "#N (merged)" — the reviewer + // annotating the reference with its state names the landing PR as + // surely as a preposition does (hivecommons/hive#15732: "now that + // #15545 (merged) carries this change"). + alreadyLandedMergedRefRE = regexp.MustCompile(`(?i)(?:[\w.-]+/[\w.-]+)?#(\d+)\s*\((?:already |now )?(?:merged|landed)\)`) ) // AlreadyLandedClaim reports whether any of texts says the change is @@ -78,6 +83,16 @@ func AlreadyLandedPR(redundantOf int, texts ...string) int { } found = n } + for _, m := range alreadyLandedMergedRefRE.FindAllStringSubmatch(t, -1) { + n, err := strconv.Atoi(m[1]) + if err != nil || n <= 0 { + continue + } + if found != 0 && found != n { + return 0 + } + found = n + } } return found } diff --git a/src/pkg/review/already_landed_test.go b/src/pkg/review/already_landed_test.go index 4817af9753..c288c92387 100644 --- a/src/pkg/review/already_landed_test.go +++ b/src/pkg/review/already_landed_test.go @@ -20,6 +20,8 @@ func TestAlreadyLandedPRFromReviewerWording(t *testing.T) { {name: "15648 since", text: alreadyLandedQuestion15648, want: 15341}, {name: "owner/repo ref", text: "This is a no-op: the identical fix merged via hivecommons/hive#15301.", want: 15301}, {name: "pull url", text: "Already landed through https://github.com/hivecommons/hive/pull/15301 — close?", want: 15301}, + // hivecommons/hive#15732: the question that parked #15544. + {name: "15544 merged annotation", text: "@clubanderson should decide whether #15544 can be closed as a no-op now that #15545 (merged) carries this change", want: 15545}, {name: "question mentions a PR but not redundancy", text: "@clubanderson should decide whether the flag introduced in #15506 should default on before this PR merges.", want: 0}, {name: "lineage mention only", text: "@clubanderson should decide whether to close this adoption of #15324 as already landed.", want: 0}, {name: "two different landing refs are ambiguous", text: "Already landed via #15506 and via #15507.", want: 0}, diff --git a/src/pkg/stagelabels/human.go b/src/pkg/stagelabels/human.go index 0ebe26ff0c..906ffce740 100644 --- a/src/pkg/stagelabels/human.go +++ b/src/pkg/stagelabels/human.go @@ -678,3 +678,15 @@ func AlreadyLandedCaption(reason string) (caption string, ok bool) { } return "already landed on the base — closing as superseded", true } + +// AlreadyLandedAuthorReason is the log reason for an already-landed close +// of any author's PR (hivecommons/hive#15732): "already-landed:", +// so a contributor's or trusted author's close reads apart from the +// hive's own (LaneReasonAlreadyLanded). An unknown kind reads "unknown". +func AlreadyLandedAuthorReason(kind authorkind.Kind) string { + k := strings.TrimSpace(string(kind)) + if k == "" { + k = "unknown" + } + return "already-landed:" + k +} diff --git a/src/pkg/stagelabels/human_test.go b/src/pkg/stagelabels/human_test.go index 575813d3ed..a44b46d750 100644 --- a/src/pkg/stagelabels/human_test.go +++ b/src/pkg/stagelabels/human_test.go @@ -718,3 +718,12 @@ func TestAlreadyLandedReasonCaption(t *testing.T) { t.Fatal("other reasons are not already-landed") } } + +func TestAlreadyLandedAuthorReason(t *testing.T) { + if got := AlreadyLandedAuthorReason(authorkind.Human); got != "already-landed:human" { + t.Fatalf("human = %q", got) + } + if got := AlreadyLandedAuthorReason(authorkind.Unknown); got != "already-landed:unknown" { + t.Fatalf("unknown = %q", got) + } +}