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
3 changes: 3 additions & 0 deletions changelog.d/fixed-rebase-then-merge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- The Activity Monitor's "Approve & merge as maintainer" on a PR that needs a rebase (behind or conflicting with its base) becomes **Rebase, then merge as maintainer** instead of failing with a GitHub 405: the click records your approval first, has the hive rebase the PR, waits for CI, then merges it with your approval on record — the row reads *Rebasing → merge queued (approved by @you)*, the ledger's `followed[]` carries each step, and a conflict settles as *failed* with the conflicting files and the options *Adopt into fresh branch* / *Close as superseded*. The approval stays bound to the head you read: only a head the hive itself committed counts as the rebase, and a head anyone else pushes after your click settles the follow-through as *failed* (`foreign-head`) with nothing merged and *Approve the new head & merge* as the way out. The option is also offered at 085 *Needs human decision* when the row wears needs-rebase. The fixer router now classifies a conflicting PR before skipping rows parked at needs-decision and routes a PR with an armed follow-through as pushable, so a parked PR that falls behind is no longer owned by no lane; and the unpark sweep dismisses any recorded changes-requested whose source is the hive's own `/hive decision` comment ([#15103](https://github.com/hivecommons/hive/issues/15103), [#14822](https://github.com/hivecommons/hive/issues/14822)).
- No merge lane ever rebased a conflicting PR — the self and trusted-author lanes stopped at prow's `needs-rebase` label before their update-branch call, and the fixer router only listed hive-authored or adopted PRs as rebase work, so PRs the operator opened under their own identity through session agents sat `dirty` with nobody kicked. Now a `behind` PR gets update-branch from its lane despite the stale label, and a `dirty` PR by the hive or a trusted author is dispatched to the fixer as a rebase-resolve task (rebase onto the base, resolve, force-with-lease to the PR's own branch) with a loop guard of two attempts per conflict episode: the Activity Monitor pill reads **Rebasing · attempt n/2**, then **Rebase failed · 2/2 — needs a person**, and *Rebase, then merge as maintainer* rides the same task; the conflict-aware merge train's rebase hook ([#15117](https://github.com/hivecommons/hive/issues/15117)) now opens that same episode (`requested_by: merge-train`), and its rebase-exhausted row offers *Rebase, then merge as maintainer* live instead of disabled ([#15103](https://github.com/hivecommons/hive/issues/15103)).
- **Approve** on a PR that is behind or conflicting no longer says "the merge gate takes it from here" (the gate skips a conflicting PR for good): the approval is recorded, the fixer's rebase episode opens in the operator's name, the toast reads *Approved — #N conflicts with base; hive will rebase it next pass (attempt 1/2)* with a **Rebase, then merge as maintainer** button, and the row's *Approving…* cue clears as soon as the decision records instead of lingering beside the ✓ ([#15103](https://github.com/hivecommons/hive/issues/15103)).
82 changes: 82 additions & 0 deletions src/cmd/hive/adopted_pr_fixer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"testing"
"time"

"github.com/hivecommons/hive/pkg/config"
"github.com/hivecommons/hive/pkg/github"
"github.com/hivecommons/hive/pkg/rebasemerge"
"github.com/hivecommons/hive/pkg/stagelabels"
)

Expand Down Expand Up @@ -147,3 +149,83 @@ func TestWriteMergeEligible_NonAdoptedContributorPRGetsNoHivePush(t *testing.T)
}
}
}

func useMemoryRebaseAttempts(t *testing.T) *rebasemerge.Attempts {
t.Helper()
store := rebasemerge.NewAttempts("")
prev := rebaseAttempts
rebaseAttempts = func() *rebasemerge.Attempts { return store }
t.Cleanup(func() { rebaseAttempts = prev })
return store
}

func trustedAuthorRebaseConfig() *config.Config {
cfg := &config.Config{}
cfg.Dashboard.AuthorizedUsers = []string{"clubanderson:owner"}
cfg.AutoMerge.TrustedAuthors.Enabled = true
return cfg
}

// hivecommons/hive#15103: a trusted author's PR (the operator's own
// identity, opened through a session agent) that goes dirty is the hive's
// rebase work — the trusted-author lane never rebases, so the fixer router
// must list it. Attempts are capped: the third dirty head stops the kicks.
func TestWriteMergeEligible_TrustedAuthorConflictGetsRebaseKickWithLoopGuard(t *testing.T) {
store := useMemoryRebaseAttempts(t)
cfg := trustedAuthorRebaseConfig()
mk := func(head string) github.PullRequest {
return github.PullRequest{Number: 15087, Repo: "hive", Author: "clubanderson", HeadSHA: head,
HeadRef: "feat/decision-actions", HeadRepo: "hivecommons/hive", BaseRef: "v5",
Mergeable: github.MergeableNo, MergeableState: "dirty", CIStatus: "pending",
Labels: []string{"needs-rebase"}}
}
_, failing := runWriteMergeEligible(t, []github.PullRequest{mk("aaa1111")}, mergeEligibleInputs{org: "hivecommons", cfg: cfg})
if len(failing) != 1 {
t.Fatalf("ci_failing = %+v, want the trusted author's dirty PR listed once", failing)
}
row := failing[0]
if !row.Conflict || !row.TrustedAuthor || row.ReachableAction != github.ReachableActionPush || row.Agent != "scanner" {
t.Errorf("row = %+v, want a trusted-author push conflict row owned by the fallback fixer", row)
}
if row.RebaseAttempt != 1 || row.RebaseAttemptsMax != rebasemerge.MaxRebaseAttempts || row.BaseRef != "v5" {
t.Errorf("row = %+v, want attempt 1/%d onto v5", row, rebasemerge.MaxRebaseAttempts)
}
// The fixer pushed and the head is still dirty: attempt 2 of 2.
_, failing = runWriteMergeEligible(t, []github.PullRequest{mk("bbb2222")}, mergeEligibleInputs{org: "hivecommons", cfg: cfg})
if len(failing) != 1 || failing[0].RebaseAttempt != 2 {
t.Fatalf("second dirty head: ci_failing = %+v, want attempt 2", failing)
}
// A third dirty head is past the cap: no kick, a person's turn.
_, failing = runWriteMergeEligible(t, []github.PullRequest{mk("ccc3333")}, mergeEligibleInputs{org: "hivecommons", cfg: cfg})
if len(failing) != 0 {
t.Fatalf("third dirty head: ci_failing = %+v, want nothing (attempts exhausted)", failing)
}
if a, ok := store.Get("hivecommons/hive", 15087); !ok || !a.Exhausted() {
t.Fatalf("attempts = %+v ok=%v, want an exhausted episode", a, ok)
}
// Once the PR is clean again the episode ends.
clean := mk("ddd4444")
clean.Mergeable, clean.MergeableState, clean.Labels = github.MergeableYes, "clean", nil
runWriteMergeEligible(t, []github.PullRequest{clean}, mergeEligibleInputs{org: "hivecommons", cfg: cfg})
if _, ok := store.Get("hivecommons/hive", 15087); ok {
t.Fatal("episode should be cleared once the PR is no longer conflicting")
}
}

func TestWriteMergeEligible_UntrustedConflictIsNotHiveRebaseWork(t *testing.T) {
useMemoryRebaseAttempts(t)
cfg := trustedAuthorRebaseConfig()
pr := github.PullRequest{Number: 15090, Repo: "hive", Author: "stranger", HeadSHA: "eee5555",
HeadRef: "feat/x", HeadRepo: "hivecommons/hive", BaseRef: "v5",
Mergeable: github.MergeableNo, MergeableState: "dirty", CIStatus: "pending", Labels: []string{"needs-rebase"}}
_, failing := runWriteMergeEligible(t, []github.PullRequest{pr}, mergeEligibleInputs{org: "hivecommons", cfg: cfg})
if len(failing) != 0 {
t.Fatalf("ci_failing = %+v, want nothing for an untrusted author's conflict", failing)
}
cfg.AutoMerge.TrustedAuthors.Enabled = false
pr.Author = "clubanderson"
_, failing = runWriteMergeEligible(t, []github.PullRequest{pr}, mergeEligibleInputs{org: "hivecommons", cfg: cfg})
if len(failing) != 0 {
t.Fatalf("ci_failing = %+v, want nothing when the trusted-author tier is off", failing)
}
}
13 changes: 10 additions & 3 deletions src/cmd/hive/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package main

import (
Expand Down Expand Up @@ -70,6 +70,7 @@
"github.com/hivecommons/hive/pkg/planning"
"github.com/hivecommons/hive/pkg/policies"
"github.com/hivecommons/hive/pkg/promptsrc"
"github.com/hivecommons/hive/pkg/rebasemerge"
"github.com/hivecommons/hive/pkg/retro"
"github.com/hivecommons/hive/pkg/review"
"github.com/hivecommons/hive/pkg/review/autoscale"
Expand Down Expand Up @@ -2571,9 +2572,15 @@
autoMergeOpts.MergeForwardTrustedHuman = func(repo string) bool {
return b.cfg != nil && b.cfg.AutoMerge.MergeForwardTrustedHumanFor(repo)
}
// Merge train (#15117): read live so a reload applies. RebaseResolver
// stays nil until the rebase-then-merge follow-through (#15104) lands
// and is wired here; a conflicting front then keeps its conflicting path.
// Merge train (#15117): read live so a reload applies. A member the
// train could not update-branch is handed to the fixer's rebase-resolve
// episode (#15104): the request admits the PR to the fixer router —
// which still requires a head the hive can push to — under the shared
// two-attempt guard, and the lane merges the clean head on its next pass.
autoMergeOpts.RebaseResolver = automerge.RebaseResolverFunc(func(_ context.Context, req automerge.RebaseRequest) error {
rebasemerge.SharedAttempts().Request(req.Repo, req.Number, req.HeadSHA, mergeTrainRebaseRequester, time.Now())
return nil
})
autoMergeOpts.MergeTrain = func() automerge.MergeTrainPolicy {
if b.cfg == nil {
return automerge.DefaultMergeTrainPolicy
Expand Down
111 changes: 101 additions & 10 deletions src/cmd/hive/merge_eligibility.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package main

import (
Expand All @@ -16,6 +16,7 @@
"github.com/hivecommons/hive/pkg/github"
"github.com/hivecommons/hive/pkg/github/automerge"
"github.com/hivecommons/hive/pkg/intent"
"github.com/hivecommons/hive/pkg/rebasemerge"
"github.com/hivecommons/hive/pkg/review"
"github.com/hivecommons/hive/pkg/stagelabels"
)
Expand Down Expand Up @@ -602,6 +603,15 @@
if held {
return mergeBucketSkip, blockedOrOutstanding("label:hold"), ""
}
// The conflict classification sits BEFORE the needs-decision park for
// the same reason the red one sits before the hold (hivecommons/hive
// #14822 sat 14h at stage/085 behind v5 with nothing rebasing it): a
// parked CONFLICTING PR is still its fixer's to rebase, so the person
// deciding on it decides on a branch that can merge. The park still
// keeps it out of merge-eligible — the conflict bucket never merges.
if conflictMergeState(pr) {
return mergeBucketConflict, github.MergeVerdict{State: github.MergeVerdictBlocked, Reason: notMergeableReason(pr, "")}, ""
}
// A PR parked on a person's decision (stage/085-needs-decision, or the
// issue-side stage/045 spelling a hook may have left on it) is a
// human's to release, so it is never merge-eligible — the relay must
Expand All @@ -610,10 +620,6 @@
if parked := needsDecisionParkLabel(pr.Labels); parked != "" {
return mergeBucketSkip, blockedOrOutstanding("label:" + parked + " — parked on a human decision"), ""
}

if conflictMergeState(pr) {
return mergeBucketConflict, github.MergeVerdict{State: github.MergeVerdictBlocked, Reason: notMergeableReason(pr, "")}, ""
}
if sentinelMergeBlock {
return mergeBucketSkip, blockedOrOutstanding(blockLabelSentinel), ""
}
Expand Down Expand Up @@ -815,6 +821,37 @@
return strings.HasPrefix(author, "app/")
}

// rebaseAttempts is the conflict loop-guard ledger; tests swap it.
var rebaseAttempts = rebasemerge.SharedAttempts

// mergeTrainRebaseRequester is the RequestedBy the merge train writes on a
// rebase episode it opens for a member it could not update-branch
// (hivecommons/hive#15117 → #15104).
const mergeTrainRebaseRequester = "merge-train"

// trustedAuthorRebasePR: a PR by a trusted author (auto_merge.trusted_authors
// would merge it unattended) whose head the hive can push to. Its rebase is
// the hive's: the trusted-author lane never rebases, and the author is a
// person who opened it through the hive and expects the hive to carry it.
func trustedAuthorRebasePR(cfg *config.Config, fullRepo string, pr github.PullRequest) bool {
if cfg == nil || github.ReachableAction(pr) != github.ReachableActionPush {
return false
}
policy := trustedAuthorPolicyFunc(cfg)()
if !policy.Enabled {
return false
}
if len(policy.Repos) > 0 && !policy.Repos[strings.ToLower(strings.TrimSpace(fullRepo))] {
return false
}
for _, l := range pr.Labels {
if policy.ExcludeLabels[strings.ToLower(strings.TrimSpace(l))] {
return false
}
}
return trustedAuthorFunc(cfg)(pr.Author, policy.RequireRole).Allowed
}

func conflictMergeState(pr github.PullRequest) bool {
if hasLabel(pr.Labels, "needs-rebase") {
return true
Expand Down Expand Up @@ -1001,6 +1038,16 @@
// leave the label alone — a maintainer clears the alert before the
// merge. Only adopted rows reach the buckets with it set.
SentinelAlert bool `json:"sentinel_alert,omitempty"`
// RebaseAttempt / RebaseAttemptsMax are the conflict loop guard
// (hivecommons/hive#15103): attempt n of max for this conflict
// episode, where each fixer head still dirty is the next attempt.
// BaseRef names the branch to rebase onto. TrustedAuthor marks a
// trusted author's PR (not hive-authored, not adopted) the hive
// rebases on the author's behalf.
RebaseAttempt int `json:"rebase_attempt,omitempty"`
RebaseAttemptsMax int `json:"rebase_attempts_max,omitempty"`
BaseRef string `json:"base_ref,omitempty"`
TrustedAuthor bool `json:"trusted_author,omitempty"`
// DeferredIncident is the open [shared-ci] incident issue this red
// PR was already deferred to (github.PullRequest.SharedCIIncident,
// hivecommons/hive#10528); only red PRs carry one. It applies to a
Expand Down Expand Up @@ -1097,6 +1144,16 @@
}

adopted := adoptedInPlace(fullRepo, pr.Number)
// An operator's "Rebase, then merge as maintainer" makes the rebase
// the hive's whoever authored the PR: route it like an in-place
// adoption so the fixer gets a push instruction (a fork that
// allows maintainer edits is push-reachable; the dashboard refuses
// to arm one that is not).
rebaseMergeArmed := rebasemerge.Shared().Armed(fullRepo, pr.Number)
if rebaseMergeArmed && !adopted {
adopted = true
logger.Info("rebase-then-merge armed; routing PR to fixer", "repo", fullRepo, "number", pr.Number, "mergeable_state", pr.MergeableState)
}
prGates.adopted = adopted
bucket, verdict, intentReason := classifyMergeEligibility(pr, held, fullRepo, prGates)
if bucket == mergeBucketEligible {
Expand Down Expand Up @@ -1140,6 +1197,10 @@
if adopted {
row.ReachableAction = github.ReachableActionPush
}
if bucket != mergeBucketConflict {
// Not conflicting any more: the rebase episode is over.
rebaseAttempts().Clear(fullRepo, pr.Number)
}
if bucket != mergeBucketFailing && row.Escalated && !holdDriftPRs[key] {
row.Mergeable = mergeableJSON(pr.Mergeable)
row.CIStatus = pr.CIStatus
Expand All @@ -1149,13 +1210,40 @@
case mergeBucketSkip:
continue
case mergeBucketConflict:
if !hiveAuthoredPR(pr) && !adopted {
// Whose rebase is it? The hive's own PR, an adopted one, or —
// hivecommons/hive#15103 — a trusted author's (the operator's
// own identity opening PRs through session agents): the
// trusted-author lane skips those on label:needs-rebase and
// nothing else ever rebased them. Any PR the hive can push to
// and would merge unattended is the hive's to keep mergeable.
trustedRebase := !hiveAuthoredPR(pr) && !adopted && trustedAuthorRebasePR(cfg, fullRepo, pr)
// An operator's approve / merge-now from the dashboard on a
// conflicting PR asks for the rebase outright (the episode
// carries RequestedBy); that admits any PR the hive can push.
requested := false
if prior, ok := rebaseAttempts().Get(fullRepo, pr.Number); ok && prior.RequestedBy != "" && github.ReachableAction(pr) == github.ReachableActionPush {
requested = !hiveAuthoredPR(pr) && !adopted && !trustedRebase
}
if !hiveAuthoredPR(pr) && !adopted && !trustedRebase && !requested {
continue
}
// Loop guard: attempt n of MaxRebaseAttempts per conflict
// episode; a fixer's pushed head that is still dirty is the
// next attempt, and past the cap the hive stops re-kicking.
attempt := rebaseAttempts().Observe(fullRepo, pr.Number, pr.HeadSHA, time.Now())
row.RebaseAttempt = attempt.Count()
row.RebaseAttemptsMax = rebasemerge.MaxRebaseAttempts
row.BaseRef = pr.BaseRef
row.TrustedAuthor = trustedRebase
if attempt.Exhausted() {
logger.Warn("rebase attempts exhausted; leaving the conflict to a person", "repo", fullRepo, "number", pr.Number, "head", pr.HeadSHA, "attempts", attempt.Count()-1, "max", rebasemerge.MaxRebaseAttempts, "mergeable_state", pr.MergeableState)
continue
}
agent := prFixAgent(pr, prAgents[fmt.Sprintf("%s#%d", fullRepo, pr.Number)])
if adopted {
// A contributor's branch name is not a lane; the
// fallback fixer owns adopted PRs.
if adopted || trustedRebase || requested {
// A contributor's (or the owner's) branch name is not a
// lane; the fallback fixer owns adopted, trusted-author
// and operator-requested rebases.
agent = ""
}
reroutedFrom := ""
Expand All @@ -1165,8 +1253,11 @@
row.Conflict = true
row.ReroutedFrom = reroutedFrom
row.DeferredIncident = pr.SharedCIIncident
if adopted {
logger.Info("adopted PR routed to fixer", "repo", fullRepo, "number", pr.Number, "work", "rebase", "mergeable_state", pr.MergeableState, "fixer", agent, "sentinel_alert", row.SentinelAlert)
if trustedRebase || requested {
row.ReachableAction = github.ReachableActionPush
}
if adopted || trustedRebase || requested {
logger.Info("PR routed to fixer for rebase", "repo", fullRepo, "number", pr.Number, "work", "rebase", "adopted", adopted, "trusted_author", trustedRebase, "requested_by", attempt.RequestedBy, "attempt", attempt.Count(), "max", rebasemerge.MaxRebaseAttempts, "mergeable_state", pr.MergeableState, "fixer", agent, "sentinel_alert", row.SentinelAlert)
}
failing = append(failing, row)
continue
Expand Down
Loading
Loading