From 6bb50e7ccd27c952e5de831767e36ffd4af027e1 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 18:10:15 -0400 Subject: [PATCH 01/10] =?UTF-8?q?=F0=9F=90=9B=20Activity=20Monitor:=20Reba?= =?UTF-8?q?se,=20then=20merge=20as=20maintainer;=20autonomous=20rebase-res?= =?UTF-8?q?olve=20with=20loop=20guard;=20approve=20on=20a=20dirty=20PR=20q?= =?UTF-8?q?ueues=20the=20rebase;=20dismiss=20self-inflicted=20changes=5Fre?= =?UTF-8?q?quested?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Squashed and rebased onto v5 after #15087 and #15074 landed. Fixes #15103 Signed-off-by: Andrew Anderson --- changelog.d/fixed-rebase-then-merge.md | 3 + src/cmd/hive/adopted_pr_fixer_test.go | 82 +++ src/cmd/hive/merge_eligibility.go | 106 +++- src/cmd/hive/merge_relay_lane_gate_test.go | 18 + src/docs/dashboard-sections.md | 4 +- src/docs/operator-reference.md | 57 ++- src/pkg/dashboard/api_repo_item_decision.go | 87 +++- .../dashboard/api_repo_item_decision_test.go | 9 + .../dashboard/rebase_merge_followthrough.go | 378 ++++++++++++++ .../rebase_merge_followthrough_test.go | 327 ++++++++++++ src/pkg/dashboard/server.go | 5 + src/pkg/dashboard/stage_tracker.go | 10 + src/pkg/dashboard/stage_tracker_cues_test.go | 1 + src/pkg/dashboard/stage_tracker_decision.go | 43 +- .../stage_tracker_merge_gate_test.go | 18 + .../stage_tracker_row_actions_test.go | 109 ++++ src/pkg/dashboard/static/index.html | 63 ++- src/pkg/github/automerge/automerge_sweep.go | 15 +- .../automerge_sweep_trusted_author_test.go | 25 +- src/pkg/github/issue_unpark_command.go | 3 + src/pkg/github/pr_merge_state.go | 138 ++++++ src/pkg/github/pr_unpark_decision.go | 28 ++ src/pkg/github/pr_unpark_decision_test.go | 53 ++ src/pkg/rebasemerge/attempts.go | 194 ++++++++ src/pkg/rebasemerge/rebasemerge.go | 467 ++++++++++++++++++ src/pkg/rebasemerge/rebasemerge_test.go | 210 ++++++++ src/pkg/review/human_change_request.go | 35 ++ src/pkg/scheduler/fork_aware_queue_test.go | 20 + src/pkg/scheduler/policy_overlays.go | 34 ++ 29 files changed, 2511 insertions(+), 31 deletions(-) create mode 100644 changelog.d/fixed-rebase-then-merge.md create mode 100644 src/pkg/dashboard/rebase_merge_followthrough.go create mode 100644 src/pkg/dashboard/rebase_merge_followthrough_test.go create mode 100644 src/pkg/github/pr_merge_state.go create mode 100644 src/pkg/rebasemerge/attempts.go create mode 100644 src/pkg/rebasemerge/rebasemerge.go create mode 100644 src/pkg/rebasemerge/rebasemerge_test.go diff --git a/changelog.d/fixed-rebase-then-merge.md b/changelog.d/fixed-rebase-then-merge.md new file mode 100644 index 0000000000..f85d30c53b --- /dev/null +++ b/changelog.d/fixed-rebase-then-merge.md @@ -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 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 ([#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)). diff --git a/src/cmd/hive/adopted_pr_fixer_test.go b/src/cmd/hive/adopted_pr_fixer_test.go index 71fcfe666f..6f311de2f7 100644 --- a/src/cmd/hive/adopted_pr_fixer_test.go +++ b/src/cmd/hive/adopted_pr_fixer_test.go @@ -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" ) @@ -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) + } +} diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index a6c5872a48..3bcb7de810 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -16,6 +16,7 @@ import ( "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" ) @@ -602,6 +603,15 @@ func classifyMergeEligibility(pr github.PullRequest, held bool, fullRepo string, 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 @@ -610,10 +620,6 @@ func classifyMergeEligibility(pr github.PullRequest, held bool, fullRepo string, 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), "" } @@ -815,6 +821,32 @@ func hiveAuthoredPR(pr github.PullRequest) bool { return strings.HasPrefix(author, "app/") } +// rebaseAttempts is the conflict loop-guard ledger; tests swap it. +var rebaseAttempts = rebasemerge.SharedAttempts + +// 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 @@ -1001,6 +1033,16 @@ func writeMergeEligible(actionable *github.ActionableResult, hold github.HoldRes // 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 @@ -1097,6 +1139,16 @@ func writeMergeEligible(actionable *github.ActionableResult, hold github.HoldRes } 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 { @@ -1140,6 +1192,10 @@ func writeMergeEligible(actionable *github.ActionableResult, hold github.HoldRes 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 @@ -1149,13 +1205,40 @@ func writeMergeEligible(actionable *github.ActionableResult, hold github.HoldRes 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 := "" @@ -1165,8 +1248,11 @@ func writeMergeEligible(actionable *github.ActionableResult, hold github.HoldRes 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 diff --git a/src/cmd/hive/merge_relay_lane_gate_test.go b/src/cmd/hive/merge_relay_lane_gate_test.go index c7ab00d694..5601640c3d 100644 --- a/src/cmd/hive/merge_relay_lane_gate_test.go +++ b/src/cmd/hive/merge_relay_lane_gate_test.go @@ -103,6 +103,24 @@ func TestClassifyMergeEligibility_ParkedRedPRStaysFailing(t *testing.T) { } } +// A parked CONFLICTING PR is still its fixer's to rebase: the conflict +// classification sits before the park (hivecommons/hive#14822 sat 14h at +// 085 behind v5 with no lane owning the rebase). +func TestClassifyMergeEligibility_ParkedConflictingPRStaysConflict(t *testing.T) { + pr := github.PullRequest{ + Number: 14822, Repo: "hive", Author: "thatguywob", CIStatus: "success", + Mergeable: github.MergeableNo, MergeableState: "dirty", + Labels: []string{github.PRNeedsDecisionStageLabel, "needs-rebase"}, + } + bucket, verdict, _ := classifyMergeEligibility(pr, false, "hivecommons/hive", mergeGates{}) + if bucket != mergeBucketConflict { + t.Fatalf("bucket = %d, want conflict (verdict %+v)", bucket, verdict) + } + if verdict.State != github.MergeVerdictBlocked { + t.Fatalf("state = %q, want blocked", verdict.State) + } +} + func TestNeedsDecisionParkLabel(t *testing.T) { if got := needsDecisionParkLabel([]string{"stage/060-reviewed", " Stage/085-Needs-Decision "}); got != "stage/085-needs-decision" { t.Fatalf("got %q", got) diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 0dc6e1c4dc..4c41570036 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -752,7 +752,9 @@ No glyph on a chevron or pill rotates (owner, 2026-10-28: "i dont like the statu | State the pill shows | Lead actions in ⋯ and in the popover (consequence) | |---|---| | PR at 090 *Ready for human merge* (untrusted author, workflow files, manual-merge path, branch protection…) | **Approve & merge as maintainer** (merges #N into *base* now via hive's identity, attributed to you — a comment on the PR names you, the audit log records `repo_item_decision_merge`, `source: dashboard`) · **Approve — let hive merge** (records your approval as the owner decision — an APPROVE review and the automerge label; the hive's merge sweep merges it on its next pass once CI is green and the head has soaked) · Give direction (hive-authored PRs only) · Close as superseded · Close as won't fix · Hold. Both merge actions need the merger or owner role and confirm first (with *Don't ask again*); the toast reads *merged* / *queued for merge*; the badge records `merge-now` / `queue-merge`. **Let hive decide** is here too (third): on a 090 PR it never runs the policy — the hive answers at once through the no-effect toast, *I can't merge this: author @Karibhou is untrusted on hotshot — …*, with *Approve & merge as maintainer · Approve — let hive merge* as buttons and the 👥 Contributors fix in the next line. **Either Approve is the trust override for that head** ([#15136](https://github.com/hivecommons/hive/issues/15136); owner, 2026-10-29: "I approved these and then they went to adopted…"): the stage record gets `admitted_by: operator-approval:`, the contributor lane merges the head as-is after checks and soak, and the adoption engine refuses to adopt or supersede it while the admission stands (the row reads *not adopted: a maintainer approved this head; the hive merges it as-is*; the 090 tooltip and popover say *Approved by @you as the owner decision…* and the second Approve greys out). When the record's commit check found commits without a `Signed-off-by`, the popover's blocker line and both Approve confirms say so **before** acting (*2 of 3 commits have no Signed-off-by, so a required DCO check refuses the merge*) and a third lead action appears, **Re-author as hive PR** — the explicit, separate choice: the hive re-homes the commits on a signed-off hive branch and opens a superseding PR; nothing is merged as-is. It is greyed with the reason on a person's PR. Renderer test: `TestStageTrackerReauthorAndApprovalCaveats`. | -| PR at 085 *Needs human decision* | Let hive decide · Approve · Give direction · Close as superseded · Close as won't fix · Hold (unchanged). | +| PR at 085 *Needs human decision* | Let hive decide · Approve · Give direction · Close as superseded · Close as won't fix · Hold (unchanged). When the row also wears **needs rebase**, **Rebase, then merge as maintainer** sits right after Approve (below). | +| PR at 085 or 090 that also wears **needs rebase** (behind or conflicting with its base) | **Rebase, then merge as maintainer** replaces *Approve & merge as maintainer* — a plain merge would be a GitHub 405 — with the consequence *hive rebases #N onto base, waits for CI, then merges it with your approval on record; you'll get a toast when it lands or if the rebase conflicts*. The click records your approval first (/lgtm + /approve in your name), arms a follow-through, and kicks the rebase (GitHub update-branch for the hive's own PR when it is merely behind; otherwise the fixer lane, which now owns a parked PR with an armed follow-through); the endpoint answers `202 rebase-queued` and the toast reads *rebase queued, merge to follow*. The row then reads **Rebasing → merge queued (approved by @you)** with the working cue, *Rebased → waiting for CI, then merge* once the head moves, and the normal merge-gate pills after that. On green the hive merges the rebased head with your approval attributed; on a conflict (or CI red, or no rebase within 2 h) the action settles as *failed* with the conflicting files and two ways out — **Adopt into fresh branch** · **Close as superseded** — on the row's badge and in a note on the PR. The ledger's `last_operator_action.followed[]` carries each step (`approval-recorded` → `rebase-kicked` → `rebased` → `ci-green` → `merged`, or `failed`). ([#14822](https://github.com/hivecommons/hive/issues/14822)) | +| PR (hive-authored or a trusted author's) that is **conflicting** with its base | No click needed: the fixer lane rebases it on the hive's behalf, and the gate pill reads **Rebasing · attempt n/2** (spinning) — each fixer push that GitHub still reports dirty is the next attempt. After two the hive stops: the pill reads **Rebase failed · 2/2 — needs a person** and the row's menu still offers *Adopt into fresh branch* / *Close as superseded*. A merely `behind` PR gets GitHub's update-branch from its merge lane even while it wears prow's stale needs-rebase label. **Approve** on such a PR records the approval and opens the rebase episode in your 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, never "the merge gate takes it from here"; the *Approving…* cue clears the moment the decision records. ([#15103](https://github.com/hivecommons/hive/issues/15103)) | | Issue at 045 *Needs decision* (direction) | Let hive decide · Give direction · Approve direction · Send back to the hive · Hold (unchanged). | | Human-authored PR at 071 *Needs author* / 072 *Returned to contributor* | Let hive decide · Close as superseded · Close as won't fix · Hold — the hive never rewrites a person's PR, so the choice is wait or close. (A hive-authored PR there carries *Adopt now* when adoption applies.) | | `needs-human` label set by a person or the hive (any stage) | **Resolve — lift needs-human** (removes the label; on a PR also leaves the hive's /lgtm + /approve, on an issue a `/hive approve`) · Let hive decide · Hold. | diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 04fc06043e..4ea4f338d4 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -472,6 +472,7 @@ verified owner or an authorized user with the `merger` role: | Decision | What it does | Audit / ledger | |---|---|---| | `merge-now` — *Approve & merge as maintainer* | Comments on the PR that @you merged it from the dashboard, then merges it at once through the hive's GitHub App (`MergePRVia`, audit path `dashboard`). Refused when the PR is merged or closed, or when you are its author. | `repo_item_decision_merge`; `last_operator_action.action: merge-now`; toast *merged*. | +| `merge-now` on a PR whose `mergeable_state` is `dirty` or `behind` — *Rebase, then merge as maintainer* | Never a GitHub 405. Records your approval first (/lgtm + /approve naming you), arms a rebase-then-merge follow-through (`/data/rebase-merge-followups.json`), kicks the rebase (update-branch on the hive's own PR when only behind; otherwise the fixer lane, which owns a parked PR with an armed follow-through), and answers `202 rebase-queued`. A 2-minute ticker then reads the PR: `mergeable_state: clean` on the rebased head → merges it with your approval attributed; still `dirty` after 2 h, CI red, or no rebase within the deadline → `failed` with the conflicting files and the options *Adopt into fresh branch* / *Close as superseded* (also left as a note on the PR). Refused on a fork whose author has not allowed maintainer edits (`head-not-pushable`). | `repo_item_decision_merge` with `status: rebase-queued`; `last_operator_action.action: merge-now`, outcome `pending` → `applied` / `failed`, `followed[]` steps `approval-recorded`, `rebase-kicked`, `rebased`, `ci-green`, `merged` / `failed`; row `rebase_merge.state`; toast *rebase queued, merge to follow*. | | `queue-merge` — *Approve — let hive merge* | Leaves an `APPROVED` review in your name with a note, adds the automerge label, and leaves the merge to the App self-merge sweep, which merges on its next pass once CI is green and the head has soaked. Refused on your own PR. | `repo_item_decision_queue_merge`; `last_operator_action.action: queue-merge`; toast *queued for merge*. | **Approve is the trust override for that head @@ -514,7 +515,61 @@ A sentinel alert, your own PR, a writer without the `merger` role on a good head, adoption turned off, or any other 090 reason keep the plain-words no-effect answer with the two merge buttons. -Neither merge action widens who the lanes trust: to stop a contributor's PRs parking at 090 + +Two related repairs ride with the rebase-then-merge action +([#14822](https://github.com/hivecommons/hive/issues/14822)). The fixer +router now classifies a conflicting (`mergeable_state: dirty`) PR *before* +skipping rows parked at 085 *Needs human decision*, and a PR with an armed +follow-through is routed as pushable (like an in-place adoption), so a +parked PR that falls behind its base is no longer owned by no lane. And on +each unpark sweep the hive dismisses, with an Info log line +`dismissed self-inflicted changes_requested: source comment is hive's own /hive decision`, +any recorded changes-requested whose source comment is the hive's own +delegated `/hive decision` — the self-inflicted verdict the guard in +[#15063](https://github.com/hivecommons/hive/pull/15063) now prevents but +which older records still carried. + +**Autonomous rebase-resolve** ([#15103](https://github.com/hivecommons/hive/issues/15103)). +No merge lane ever rebased a conflicting PR: the self and trusted-author +lanes stopped at `label:needs-rebase` before reaching the update-branch call, +and the fixer router only listed hive-authored or adopted PRs as rebase +work — so a PR the operator opened under their own identity through a +session agent sat `dirty` with nobody kicked to fix it. Now: + +- **`behind` (clean update):** prow's `needs-rebase` label no longer blocks + the self or trusted-author lane when GitHub says `mergeable_state: behind` + — the lane's update-branch runs and clears the label. +- **`dirty` (real conflict):** the fixer router lists a trusted author's PR + (`auto_merge.trusted_authors` enabled, repo allowed, author at the required + role, head pushable, no exclude label) as rebase work alongside the hive's + own and adopted PRs. The kick says + *rebase-resolve (attempt n/2): `gh pr checkout`, `git rebase origin/`, + resolve, re-run build and tests, `git push --force-with-lease` to the PR's + OWN branch; do not open a new PR*. Loop guard: `/data/rebase-attempts.json` + counts distinct dirty heads per PR — the first dirty head is attempt 1, a + fixer push that is still dirty is attempt 2, a third dirty head is + exhausted: the router stops listing the PR (Warn log + `rebase attempts exhausted; leaving the conflict to a person`) and the row's + gate pill reads **Rebase failed · 2/2 — needs a person**. While it runs the + pill reads **Rebasing · attempt n/2** with the working cue; the episode + clears as soon as the PR is no longer conflicting. The row payload carries + `rebase: {attempt, max, exhausted, head, text}`. +- **Approve on a PR that is behind or conflicting** no longer promises that + "the merge gate takes it from here" (the gate skips `conflicting` for + good). The approval is recorded, the rebase episode opens in your name + (`requested_by`, which admits the PR to the fixer router whoever opened it, + as long as the hive can push to it; a hive-authored PR that is merely + `behind` gets update-branch on the spot), 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, the response carries + `rebase: {attempt, max, …}`, and the row's *Approving…* cue clears as soon + as the decision records. +- **Rebase, then merge as maintainer** uses the same task: a rebased head that + is still dirty goes back to *Rebasing* (step `still-conflicting`, the 2 h + rebase clock restarting) while attempts remain, and settles *failed* with + the conflicting files once the guard is exhausted. + +Neither widens who the lanes trust: to stop a contributor's PRs parking at 090 give them the `trusted` / `merger` tier under 👥 Contributors (`auto_merge.contributor_lane.require_tiers`), add them as a repository collaborator, or list them under `dashboard.authorized_users` with the diff --git a/src/pkg/dashboard/api_repo_item_decision.go b/src/pkg/dashboard/api_repo_item_decision.go index 3785ac8f3e..ccccc7979b 100644 --- a/src/pkg/dashboard/api_repo_item_decision.go +++ b/src/pkg/dashboard/api_repo_item_decision.go @@ -13,6 +13,7 @@ import ( "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/delegatedecision" ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/rebasemerge" "github.com/hivecommons/hive/pkg/review" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -183,6 +184,10 @@ type repoItemDecisionResponse struct { // the hive bot is not an approver, so they would only draw another // "NOT APPROVED" (dibs#510). The approval itself is still recorded. CommandsSkipped string `json:"commands_skipped,omitempty"` + // Rebase is set when an approval landed on a PR that is behind or + // conflicting with its base: the rebase episode the approval opened + // (hivecommons/hive#15103), so the row reads "Rebasing · attempt n/2". + Rebase *StageTrackerRebase `json:"rebase,omitempty"` } // admitPullRequestHead records user's Approve as the trust override for @@ -535,6 +540,20 @@ func (s *Server) handlePullRequestMergeDecision(ctx context.Context, w http.Resp Result: repoItemDecisionResult(repoFull, number, "pr", decision, comment, "", label, nil)}) return } + // A head GitHub reports behind or conflicting cannot merge (405): the + // same click becomes "Rebase, then merge as maintainer" — approval on + // record, rebase kicked, merge on green (hivecommons/hive#14822). + if ms, err := gh.GetPRMergeState(ctx, repoFull, number); err == nil && ms.NeedsRebase() { + s.armRebaseThenMerge(ctx, w, repoFull, number, user, comment, ms) + return + } else if err == nil && rebaseMergeStore().Armed(repoFull, number) { + // The rebase landed but the follow-through has not merged yet: the + // follow-through owns the merge; do not race it. + prev, _ := rebaseMergeStore().Get(repoFull, number) + jsonStatusResponse(w, http.StatusAccepted, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: repoItemStatusRebaseQd, Head: prev.ApprovedHead, + Result: rebaseMergeQueuedResult(prev, true)}) + return + } if err := gh.CreateIssueComment(ctx, repoFull, number, renderRepoItemDecisionMergeComment(user, comment)); err != nil { jsonError(w, "posting merge note: "+err.Error(), http.StatusBadGateway) return @@ -657,13 +676,73 @@ func (s *Server) handlePullRequestDecision(ctx context.Context, w http.ResponseW } } s.audit.LogRecord(user, action, auditDetail("repo", repoFull, "number", numStr, "type", "pr", "head", head, "decision", comment, "released", strings.Join(released, ","), "stage", stage, "admitted_by", admitted, "commands_skipped", commandsSkipped, "to_contributor", toContributor), "", repoFull, number) + result := repoItemDecisionResultWith(repoFull, number, "pr", decision, comment, "", "", repoItemApproveFacts{ + User: user, Released: released, Stage: stage, SentinelOpen: sentinelOpen, SentinelLabel: s.sentinelLabel(), SoakMinutes: s.approveSoakMinutes(admitted != ""), Prow: prow, CommandsSkipped: commandsSkipped != "", ToContributor: toContributor, + }) + var rebase *StageTrackerRebase + if decision == repoItemDecisionApprove { + // An approval on a PR that is behind or conflicting does not + // reach the merge gate (it skips `conflicting` for good): say so, + // and ask the fixer for the rebase now instead of promising the + // gate "takes it from here" (hivecommons/hive#15103). + if ms, err := gh.GetPRMergeState(ctx, repoFull, number); err == nil && ms.NeedsRebase() { + rebase = s.queueRebaseOnApprove(ctx, repoFull, number, user, nonEmptyString(head, ms.HeadSHA), ms) + approveNeedsRebaseResult(result, number, ms, rebase) + } + } // The row's park was just answered: serve the re-derived stage on the // next tracker read instead of the cached 085. s.invalidateStageTrackerForWebhook() - jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, Head: head, AdmittedBy: admitted, CommandsSkipped: commandsSkipped, - Result: repoItemDecisionResultWith(repoFull, number, "pr", decision, comment, "", "", repoItemApproveFacts{ - User: user, Released: released, Stage: stage, SentinelOpen: sentinelOpen, SentinelLabel: s.sentinelLabel(), SoakMinutes: s.approveSoakMinutes(admitted != ""), Prow: prow, CommandsSkipped: commandsSkipped != "", ToContributor: toContributor, - })}) + jsonResponse(w, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: decision, Status: status, Released: released, Stage: stage, Head: head, AdmittedBy: admitted, CommandsSkipped: commandsSkipped, Rebase: rebase, + Result: result}) +} + +// queueRebaseOnApprove opens the rebase episode for an approved PR that +// needs one: GitHub's update-branch on the spot for the hive's own PR that +// is merely behind, otherwise the fixer's rebase-resolve task on the next +// router pass (the episode carries the operator as requester so the router +// lists the PR whoever opened it, as long as the hive can push to it). +func (s *Server) queueRebaseOnApprove(ctx context.Context, repoFull string, number int, user, head string, ms ghpkg.PRMergeState) *StageTrackerRebase { + gh := s.deps.GHClient + now := rebaseMergeNow() + a := rebaseAttemptsStore().Request(repoFull, number, head, user, now) + how := "fixer rebase-resolve (next router pass)" + if gh.IsHiveAuthorLogin(ms.Author) && !ms.Conflicting() { + if err := gh.UpdateBranch(ctx, repoFull, number); err == nil { + how = "update-branch" + } else if s.logger != nil { + s.logger.Warn("approve: update-branch failed; leaving the rebase to the fixer", "repo", repoFull, "number", number, "error", err) + } + } + if s.logger != nil { + s.logger.Info("approve on a PR that needs a rebase: rebase queued", "repo", repoFull, "number", number, "actor", user, "head", head, "base", ms.BaseRef, "mergeable_state", ms.MergeableState, "attempt", a.Count(), "max", rebasemerge.MaxRebaseAttempts, "kick", how) + } + return &StageTrackerRebase{Attempt: min(max(a.Count(), 1), rebasemerge.MaxRebaseAttempts), Max: rebasemerge.MaxRebaseAttempts, Exhausted: a.Exhausted(), Head: rebaseMergeShortSHA(a.Head()), Text: rebasemerge.AttemptText(a)} +} + +// approveNeedsRebaseResult rewrites the approve toast for a PR that is +// behind or conflicting: what the approval did, what the hive does next, +// and the one-click upgrade to "Rebase, then merge as maintainer". +func approveNeedsRebaseResult(out *RowActionResult, number int, ms ghpkg.PRMergeState, rebase *StageTrackerRebase) { + base := nonEmptyString(ms.BaseRef, "its base branch") + attempt := "" + if rebase != nil && !rebase.Exhausted { + attempt = fmt.Sprintf(" (attempt %d/%d)", rebase.Attempt, rebase.Max) + } + if ms.Conflicting() { + out.Outcome = fmt.Sprintf("Approved — #%d conflicts with %s; hive will rebase it next pass%s.", number, base, attempt) + } else { + out.Outcome = fmt.Sprintf("Approved — #%d is behind %s; hive is updating the branch%s.", number, base, attempt) + } + if rebase != nil && rebase.Exhausted { + out.Outcome = fmt.Sprintf("Approved — #%d conflicts with %s and hive's %d rebase attempts are used up; a person has to resolve it.", number, base, rebase.Max) + out.Next = "Resolve the conflict on the branch yourself, or adopt it into a fresh branch / close it as superseded from the row menu." + return + } + out.Next = "The merge gate skips a conflicting PR, so your approval alone would not land it. Once the rebased head is green the gate takes it — or have hive merge it for you right after the rebase:" + opt := decisionOption(decisionActionMergeNow, rebaseMergeFollowThroughLabel, true, "") + opt.Consequence = rebaseMergeFollowThroughConsequence(number, ms.BaseRef) + out.Options = []StageTrackerDecisionOption{opt} } // repoItemApprovalReleased names what a PR approval released, for the diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 1fd737ec8e..bffc6b7263 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -35,11 +35,16 @@ type repoItemDecisionMock struct { // prNoCI shape the head's combined status when the state alone does not // settle CI (e.g. "blocked"). prMergeState string + updates int prRedCI bool prNoCI bool // priorComments are the comment bodies GET /comments lists (a prior // delegated decision makes a repeat click a no-op). priorComments []string + // merges records PUT /pulls/8/merge bodies; reviews the POST /reviews + // bodies (merge-now / queue-merge, hivecommons/hive#15078). + merges []map[string]any + reviews []map[string]any // supersederState / supersederMerged shape GET pulls/90, the hive copy // an adoption marker on #8 may name (hivecommons/hive#15052); "" is 404. supersederState string @@ -105,6 +110,10 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { prLabels = append(prLabels, map[string]string{"name": label}) } _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "labels": prLabels, "user": author, "mergeable": true, "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}, "base": map[string]any{"ref": "main"}}) + case r.Method == http.MethodPut && strings.HasSuffix(path, "/pulls/8/update-branch"): + m.updates++ + w.WriteHeader(http.StatusAccepted) + _, _ = io.WriteString(w, `{"message":"Updating pull request branch."}`) case r.Method == http.MethodPut && strings.HasSuffix(path, "/pulls/8/merge"): var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) diff --git a/src/pkg/dashboard/rebase_merge_followthrough.go b/src/pkg/dashboard/rebase_merge_followthrough.go new file mode 100644 index 0000000000..0472e36584 --- /dev/null +++ b/src/pkg/dashboard/rebase_merge_followthrough.go @@ -0,0 +1,378 @@ +package dashboard + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/rebasemerge" +) + +// "Rebase, then merge as maintainer" (hivecommons/hive: #14822 sat 14h at +// 085 behind v5 and "Approve & merge as maintainer" on it would have been a +// GitHub 405). When the operator's merge-now lands on a PR GitHub reports +// behind or dirty, the dashboard records the approval, arms a follow-through +// in pkg/rebasemerge and answers 202 rebase-queued. The hive's merge- +// eligibility router then routes the PR to its fixer whoever authored it +// (an armed PR is routed like an in-place adoption), a hive-authored PR that +// is merely behind gets GitHub's update-branch straight away, and the +// ticker below watches the new head: green → merge with the approval on +// record, conflict / red / timeout → the action fails with the conflicting +// files and the two ways out. + +const ( + rowActionRebaseQueued = "rebase-queued" + repoItemStatusRebaseQd = "rebase-queued" + // rebaseMergeTickInterval is how often the follow-through polls GitHub + // for every live PR; a PR event refetch does not drive it, so this is + // the latency ceiling between "green" and "merged". + rebaseMergeTickInterval = 2 * time.Minute + rebaseMergeFollowedMax = 6 +) + +// rebaseMergeStore is the follow-through store (swapped in tests). +var rebaseMergeStore = func() *rebasemerge.Store { return rebasemerge.Shared() } + +// rebaseAttemptsStore is the fixer's rebase loop-guard ledger (the router +// in cmd/hive writes it); tests swap it. +var rebaseAttemptsStore = func() *rebasemerge.Attempts { return rebasemerge.SharedAttempts() } + +// rebaseMergeNow is the clock (swapped in tests). +var rebaseMergeNow = time.Now + +// rebaseMergeFollowThroughLabel / Consequence are the option text the +// decision menu shows instead of "Approve & merge as maintainer" when the +// PR needs a rebase first. +const rebaseMergeFollowThroughLabel = "Rebase, then merge as maintainer" + +func rebaseMergeFollowThroughConsequence(number int, base string) string { + return fmt.Sprintf("hive rebases #%d onto %s, waits for CI, then merges it with your approval on record; you'll get a toast when it lands or if the rebase conflicts", number, nonEmptyString(base, "its base branch")) +} + +func nonEmptyString(s, fallback string) string { + if strings.TrimSpace(s) == "" { + return fallback + } + return s +} + +// armRebaseThenMerge is the merge-now branch for a PR that needs a rebase. +// Order matters: the approval is posted first (the durable record the +// merge carries), then the follow-through is armed, then the rebase is +// kicked. +func (s *Server) armRebaseThenMerge(ctx context.Context, w http.ResponseWriter, repoFull string, number int, user, comment string, st ghpkg.PRMergeState) { + gh := s.deps.GHClient + now := rebaseMergeNow() + hiveAuthored := gh.IsHiveAuthorLogin(st.Author) + if !hiveAuthored && !st.PushReachable() { + f := rebasemerge.Arm(repoFull, number, user, st.BaseRef, st.HeadSHA, false, now) + f.FailNow(now, rebasemerge.FailNotReachable, nil) + // A 200 with a refused result, not an error: the toast shows the + // reason and the two ways out instead of "HTTP 409". + jsonStatusResponse(w, http.StatusOK, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: repoItemDecisionMergeNow, Status: rowActionRefused, Head: st.HeadSHA, + Result: rebaseMergeFailedResult(f)}) + return + } + event, err := gh.RecordOperatorPullRequestApprovalWith(ctx, repoFull, number, user, ghpkg.PullRequestApprovalOptions{ + HumanChangeRequests: repoItemDecisionChangeRequests(), + LiftNeedsHuman: true, + SentinelLabel: s.sentinelLabel(), + }) + if err != nil { + jsonError(w, "recording your approval: "+err.Error(), http.StatusBadGateway) + return + } + f := rebasemerge.Arm(repoFull, number, user, st.BaseRef, nonEmptyString(event.HeadSHA, st.HeadSHA), hiveAuthored, now) + if err := rebaseMergeStore().Put(f); err != nil { + if errors.Is(err, rebasemerge.ErrAlreadyArmed) { + prev, _ := rebaseMergeStore().Get(repoFull, number) + jsonStatusResponse(w, http.StatusAccepted, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: repoItemDecisionMergeNow, Status: repoItemStatusRebaseQd, Head: prev.ApprovedHead, + Result: rebaseMergeQueuedResult(prev, true)}) + return + } + jsonError(w, "arming the rebase-then-merge follow-through: "+err.Error(), http.StatusInternalServerError) + return + } + if err := gh.CreateIssueComment(ctx, repoFull, number, renderRebaseThenMergeComment(user, comment, number, st.BaseRef)); err != nil && s.logger != nil { + s.logger.Warn("rebase-then-merge: posting note failed", "repo", repoFull, "number", number, "error", err) + } + how := "fixer rebase (merge-eligibility conflict route)" + if hiveAuthored && !st.Conflicting() { + // Behind, not conflicting: GitHub's own update-branch is the whole + // rebase for the hive's own PR. + if err := gh.UpdateBranch(ctx, repoFull, number); err == nil { + how = "update-branch" + } else if s.logger != nil { + s.logger.Warn("rebase-then-merge: update-branch failed; leaving the rebase to the fixer", "repo", repoFull, "number", number, "error", err) + } + } + f.Kicked(now, how) + _ = rebaseMergeStore().Update(f) + s.audit.LogRecord(user, auditRepoItemDecisionMerge, auditDetail("repo", repoFull, "number", strconv.Itoa(number), "type", "pr", "head", f.ApprovedHead, "author", st.Author, "base", st.BaseRef, "status", repoItemStatusRebaseQd, "mergeable_state", st.MergeableState, "kick", how), "", repoFull, number) + if s.logger != nil { + s.logger.Info("rebase-then-merge armed", "repo", repoFull, "number", number, "actor", user, "head", f.ApprovedHead, "base", st.BaseRef, "mergeable_state", st.MergeableState, "kick", how) + } + s.invalidateStageTrackerForWebhook() + jsonStatusResponse(w, http.StatusAccepted, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: repoItemDecisionMergeNow, Status: repoItemStatusRebaseQd, Head: f.ApprovedHead, + Released: repoItemApprovalReleased(event), Stage: event.Stage, Result: rebaseMergeQueuedResult(f, false)}) +} + +func rebaseMergeQueuedResult(f rebasemerge.FollowThrough, already bool) *RowActionResult { + out := &RowActionResult{Action: rowActionRebaseQueued, Target: rowActionTarget(f.Repo, rowActionTargetPR, f.Number)} + base := nonEmptyString(f.Base, "its base branch") + if already { + out.Outcome = fmt.Sprintf("Already queued: @%s's approval is on record and the hive is rebasing #%d onto %s.", f.Actor, f.Number, base) + } else { + out.Outcome = fmt.Sprintf("Your approval is on record; the hive is rebasing #%d onto %s.", f.Number, base) + } + out.Next = "Once CI is green on the rebased head the hive merges it with your approval attributed; you'll get a toast when it lands or if the rebase conflicts." + return out +} + +func rebaseMergeFailedResult(f rebasemerge.FollowThrough) *RowActionResult { + out := &RowActionResult{Action: rowActionRefused, Target: rowActionTarget(f.Repo, rowActionTargetPR, f.Number), Outcome: f.FailureText(), Why: f.FailReason} + out.Next = "Pick a way out: adopt the commits into a fresh branch, or close it as superseded." + out.Options = rebaseMergeFailureOptions(f) + return out +} + +func rebaseMergeFailureOptions(f rebasemerge.FollowThrough) []StageTrackerDecisionOption { + var out []StageTrackerDecisionOption + for _, id := range f.Options { + switch id { + case rebasemerge.OptionAdoptFresh: + out = append(out, decisionOption(decisionActionAdopt, rebasemerge.OptionAdoptFreshLabel, true, "")) + case rebasemerge.OptionCloseSuperseded: + out = append(out, decisionOption(decisionActionCloseSuperseded, rebasemerge.OptionCloseSupersLabel, true, "")) + } + } + return out +} + +func renderRebaseThenMergeComment(user, comment string, number int, base string) string { + body := fmt.Sprintf("Rebase, then merge as maintainer — @%s approved #%d from the Hive dashboard; the hive rebases it onto `%s`, waits for CI, then merges it with that approval on record.", strings.TrimSpace(user), number, nonEmptyString(base, "its base branch")) + if c := strings.TrimSpace(comment); c != "" { + body += "\n\n> " + strings.ReplaceAll(c, "\n", "\n> ") + } + return body +} + +func renderRebaseThenMergeFailedComment(f rebasemerge.FollowThrough) string { + body := "Rebase, then merge as maintainer did not land: " + f.FailureText() + if len(f.ConflictFiles) > 0 { + body += "\n\nFiles to resolve:\n" + for _, file := range f.ConflictFiles { + body += "- `" + file + "`\n" + } + } + body += fmt.Sprintf("\n@%s: from the dashboard row, **%s** or **%s**.", f.Actor, rebasemerge.OptionAdoptFreshLabel, rebasemerge.OptionCloseSupersLabel) + return body +} + +// StartRebaseMergeFollowThrough runs the ticker until ctx ends. +func (s *Server) StartRebaseMergeFollowThrough(ctx context.Context) { + go func() { + t := time.NewTicker(rebaseMergeTickInterval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + s.tickRebaseMerge(ctx) + } + } + }() +} + +// tickRebaseMerge drives every live follow-through one observation forward. +func (s *Server) tickRebaseMerge(ctx context.Context) { + if s == nil || s.deps == nil || s.deps.GHClient == nil { + return + } + gh := s.deps.GHClient + store := rebaseMergeStore() + for _, f := range store.Live() { + st, err := gh.GetPRMergeState(ctx, f.Repo, f.Number) + if err != nil { + if s.logger != nil { + s.logger.Warn("rebase-then-merge: reading PR failed", "repo", f.Repo, "number", f.Number, "error", err) + } + continue + } + s.driveRebaseMerge(ctx, store, f, st) + } +} + +// driveRebaseMerge folds one PR read into its follow-through and performs +// the action the state machine asks for. +func (s *Server) driveRebaseMerge(ctx context.Context, store *rebasemerge.Store, f rebasemerge.FollowThrough, st ghpkg.PRMergeState) { + gh := s.deps.GHClient + now := rebaseMergeNow() + obs := rebasemerge.Observation{Now: now, Head: st.HeadSHA, State: st.State, Merged: st.Merged, MergeableState: st.MergeableState, CIRed: st.CIRed} + if st.Conflicting() { + if files, err := gh.PRConflictCandidates(ctx, f.Repo, st.BaseRef, st.HeadSHA); err == nil { + obs.ConflictFiles = files + } + if attempts := rebaseAttemptsStore(); attempts != nil { + if a, ok := attempts.Get(f.Repo, f.Number); ok { + obs.RebaseAttempt, obs.RebaseExhausted = a.Count(), a.Exhausted() + } + } + } + action := rebasemerge.Advance(&f, obs, rebasemerge.Deadlines{}) + switch action { + case rebasemerge.ActionMerge: + head := nonEmptyString(f.RebasedHead, f.ApprovedHead) + res, err := gh.MergePRVia(ctx, f.Repo, f.Number, "", head, ghpkg.PRAuditPathDashboard) + switch { + case err != nil: + f.FailNow(now, "merge-refused: "+err.Error(), nil) + case !res.Merged: + f.FailNow(now, "merge-refused: "+strings.TrimSpace(res.Message), nil) + default: + f.Merged(now, res.SHA) + } + } + _ = store.Update(f) + s.settleRebaseMergeLedger(ctx, f) + if !f.Live() { + s.invalidateStageTrackerForWebhook() + } + if s.logger != nil { + s.logger.Info("rebase-then-merge advanced", "repo", f.Repo, "number", f.Number, "state", f.State, "head", st.HeadSHA, "mergeable_state", st.MergeableState, "action", string(action), "fail_reason", f.FailReason) + } +} + +// settleRebaseMergeLedger closes the operator's pending merge-now record +// when the follow-through ends, and leaves the failure note on the PR. +func (s *Server) settleRebaseMergeLedger(ctx context.Context, f rebasemerge.FollowThrough) { + switch f.State { + case rebasemerge.StateMerged: + _, _ = s.operatorActions().Settle(f.Repo, f.Number, operatorActionMergeNow, operatorActionOutcomeApplied, "merged "+rebaseMergeShortSHA(f.MergeSHA)+" after rebase") + case rebasemerge.StateFailed: + _, _ = s.operatorActions().Settle(f.Repo, f.Number, operatorActionMergeNow, operatorActionOutcomeFailed, f.FailureText()) + if f.FailReason != rebasemerge.FailClosed && s.deps != nil && s.deps.GHClient != nil { + if err := s.deps.GHClient.CreateIssueComment(ctx, f.Repo, f.Number, renderRebaseThenMergeFailedComment(f)); err != nil && s.logger != nil { + s.logger.Warn("rebase-then-merge: posting failure note failed", "repo", f.Repo, "number", f.Number, "error", err) + } + } + } +} + +func rebaseMergeShortSHA(sha string) string { + if len(sha) > 7 { + return sha[:7] + } + return sha +} + +// rebaseMergeFollowedHops renders the follow-through's steps as ledger hops +// (Number 0, Slug = step) so last_operator_action.followed[] tells the +// trail: approval recorded → rebase kicked → rebased → CI green → merged. +func rebaseMergeFollowedHops(f rebasemerge.FollowThrough) []StageTrackerHop { + out := make([]StageTrackerHop, 0, len(f.Steps)) + for _, st := range f.Steps { + out = append(out, StageTrackerHop{Slug: st.Step, Reason: st.Detail, At: st.At}) + } + if len(out) > rebaseMergeFollowedMax { + out = out[len(out)-rebaseMergeFollowedMax:] + } + return out +} + +// StageTrackerRebaseMerge is the row's view of a live or just-settled +// follow-through. +type StageTrackerRebaseMerge struct { + State string `json:"state"` + Actor string `json:"actor"` + Base string `json:"base,omitempty"` + // Text is the row caption while it runs: "Rebasing → merge queued + // (approved by @you)". + Text string `json:"text"` + FailReason string `json:"fail_reason,omitempty"` + ConflictFiles []string `json:"conflict_files,omitempty"` + ArmedAt string `json:"armed_at"` +} + +// stageTrackerRebaseMergeText is the row caption for a follow-through. +func stageTrackerRebaseMergeText(f rebasemerge.FollowThrough) string { + by := "approved by @" + f.Actor + switch f.State { + case rebasemerge.StateApproved, rebasemerge.StateRebasing: + return "Rebasing → merge queued (" + by + ")" + case rebasemerge.StateCIPending: + return "Rebased → waiting for CI, then merge (" + by + ")" + case rebasemerge.StateMerged: + return "Merged after rebase (" + by + ")" + case rebasemerge.StateFailed: + return "Rebase-then-merge failed: " + f.FailureText() + } + return "" +} + +// StageTrackerRebase is the row's view of the fixer's autonomous +// rebase-resolve loop guard on a conflicting PR (hivecommons/hive#15103): +// "Rebasing · attempt 1/2", or "Rebase failed · 2/2 — needs a person". +type StageTrackerRebase struct { + Attempt int `json:"attempt"` + Max int `json:"max"` + Exhausted bool `json:"exhausted"` + Head string `json:"head,omitempty"` + Text string `json:"text"` +} + +// applyRebaseAttempts stamps rebase onto PR rows with an open conflict +// episode in the fixer's attempts ledger. +func applyRebaseAttempts(items []StageTrackerItem) { + attempts := rebaseAttemptsStore() + if attempts == nil { + return + } + for i := range items { + it := &items[i] + if it.Kind != "pr" { + continue + } + a, ok := attempts.Get(it.Repo, it.Number) + if !ok { + continue + } + it.Rebase = &StageTrackerRebase{Attempt: min(max(a.Count(), 1), rebasemerge.MaxRebaseAttempts), Max: rebasemerge.MaxRebaseAttempts, Exhausted: a.Exhausted(), Head: rebaseMergeShortSHA(a.Head()), Text: rebasemerge.AttemptText(a)} + } +} + +// applyRebaseMergeFollowThrough stamps rebase_merge onto rows with a live +// follow-through (or one settled within the hour, so the toast's target +// row can still say what happened) and folds its steps into the ledger's +// followed[]. +func (s *Server) applyRebaseMergeFollowThrough(items []StageTrackerItem, now time.Time) { + store := rebaseMergeStore() + if store == nil { + return + } + for i := range items { + it := &items[i] + if it.Kind != "pr" { + continue + } + f, ok := store.Get(it.Repo, it.Number) + if !ok || (!f.Live() && now.Sub(f.UpdatedAt) > time.Hour) { + continue + } + it.RebaseMerge = &StageTrackerRebaseMerge{State: f.State, Actor: f.Actor, Base: f.Base, Text: stageTrackerRebaseMergeText(f), FailReason: f.FailReason, ConflictFiles: f.ConflictFiles, ArmedAt: f.ArmedAt.UTC().Format(time.RFC3339)} + if f.Live() { + // The row reads the follow-through while it runs; the lane's + // own caption ("Needs human decision") is what it replaces. + it.Caption = it.RebaseMerge.Text + } + if it.LastOperatorAction != nil && it.LastOperatorAction.Action == operatorActionMergeNow && !it.LastOperatorAction.At.After(f.ArmedAt.Add(time.Minute)) { + it.LastOperatorAction.Followed = append(rebaseMergeFollowedHops(f), it.LastOperatorAction.Followed...) + } + } +} diff --git a/src/pkg/dashboard/rebase_merge_followthrough_test.go b/src/pkg/dashboard/rebase_merge_followthrough_test.go new file mode 100644 index 0000000000..c75771d1e9 --- /dev/null +++ b/src/pkg/dashboard/rebase_merge_followthrough_test.go @@ -0,0 +1,327 @@ +package dashboard + +import ( + "context" + "encoding/json" + "net/http" + "path/filepath" + "strings" + "testing" + "time" + + ghpkg "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/rebasemerge" +) + +func useRebaseAttemptsStore(t *testing.T) *rebasemerge.Attempts { + t.Helper() + store := rebasemerge.NewAttempts("") + prev := rebaseAttemptsStore + rebaseAttemptsStore = func() *rebasemerge.Attempts { return store } + t.Cleanup(func() { rebaseAttemptsStore = prev }) + return store +} + +func useRebaseMergeStore(t *testing.T) *rebasemerge.Store { + t.Helper() + store := rebasemerge.NewStore(filepath.Join(t.TempDir(), "rm.json")) + prev := rebaseMergeStore + rebaseMergeStore = func() *rebasemerge.Store { return store } + t.Cleanup(func() { rebaseMergeStore = prev }) + return store +} + +// "Approve & merge as maintainer" on a PR GitHub reports dirty is not a +// 405: the approval is recorded first (/lgtm + /approve), the +// follow-through is armed, the rebase note is left, nothing is merged, and +// the answer is 202 rebase-queued (hivecommons/hive#14822). +func TestRepoItemDecisionMergeNowOnDirtyPRArmsRebaseThenMerge(t *testing.T) { + store := useRebaseMergeStore(t) + mock := &repoItemDecisionMock{prForeign: true, prMergeState: "dirty", prLabels: []string{"stage/085-needs-decision", "needs-rebase"}} + srv := newRepoItemDecisionServer(t, mock) + + w := postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"merge-now","type":"pr","comment":"ship it"}`) + if w.Code != http.StatusAccepted { + t.Fatalf("merge-now on dirty: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != repoItemStatusRebaseQd || resp.Head != "feedfacefeedfacefeedfacefeedfacefeedface" { + t.Fatalf("response = %+v", resp) + } + if resp.Result == nil || resp.Result.Action != rowActionRebaseQueued || !strings.Contains(resp.Result.Outcome, "approval is on record") || !strings.Contains(resp.Result.Outcome, "rebasing #8 onto main") { + t.Fatalf("result = %+v", resp.Result) + } + if len(mock.merges) != 0 { + t.Fatalf("nothing merges on a dirty head: %v", mock.merges) + } + if len(mock.comments) < 3 || !strings.HasPrefix(mock.comments[0], "/lgtm\n") || !strings.HasPrefix(mock.comments[1], "/approve\n") || !strings.Contains(mock.comments[2], "Rebase, then merge as maintainer — @writer approved #8") || !strings.Contains(mock.comments[2], "> ship it") { + t.Fatalf("comments = %q", mock.comments) + } + f, ok := store.Get("testorg/testrepo", 8) + if !ok || f.State != rebasemerge.StateRebasing || f.Actor != "writer" || f.Base != "main" || f.ApprovedHead != "feedfacefeedfacefeedfacefeedfacefeedface" { + t.Fatalf("follow-through = %+v (ok=%v)", f, ok) + } + if len(f.Steps) != 2 || f.Steps[0].Step != rebasemerge.StepApprovalRecorded || f.Steps[1].Step != rebasemerge.StepRebaseKicked { + t.Fatalf("steps = %+v", f.Steps) + } + if f.HiveAuthored { + t.Fatal("a contributor PR must not read as hive-authored") + } + // A second click while it runs is a no-op that says so. + w = postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"merge-now","type":"pr"}`) + if w.Code != http.StatusAccepted || !strings.Contains(w.Body.String(), "Already queued") { + t.Fatalf("repeat: code=%d body=%s", w.Code, w.Body.String()) + } +} + +// The driver: a rebased head that GitHub reports clean merges with the +// approval on record and settles the ledger; a dirty head past the deadline +// fails with the files and the two options, and the PR gets the note. +func TestDriveRebaseMergeGreenMergesAndConflictFails(t *testing.T) { + store := useRebaseMergeStore(t) + mock := &repoItemDecisionMock{prForeign: true} + srv := newRepoItemDecisionServer(t, mock) + srv.operatorActionStore = newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json")) + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + prevNow := rebaseMergeNow + rebaseMergeNow = func() time.Time { return now } + t.Cleanup(func() { rebaseMergeNow = prevNow }) + + f := rebasemerge.Arm("testorg/testrepo", 8, "writer", "main", "feedfacefeedfacefeedfacefeedfacefeedface", false, now) + f.Kicked(now, "fixer") + if err := store.Put(f); err != nil { + t.Fatal(err) + } + _ = srv.operatorActions().Record("testorg/testrepo", 8, OperatorAction{Action: operatorActionMergeNow, Actor: "writer", At: now, Outcome: operatorActionOutcomePending, Detail: repoItemStatusRebaseQd, Stage: 85}) + + // New head, CI pending: no merge yet. + now = now.Add(5 * time.Minute) + srv.driveRebaseMerge(context.Background(), store, f, ghpkg.PRMergeState{State: "open", HeadSHA: "0123456789abcdef0123456789abcdef01234567", BaseRef: "main", MergeableState: "blocked"}) + f, _ = store.Get("testorg/testrepo", 8) + if f.State != rebasemerge.StateCIPending || len(mock.merges) != 0 { + t.Fatalf("after rebase: state=%q merges=%v", f.State, mock.merges) + } + // Clean: merge pinned to the rebased head. + now = now.Add(5 * time.Minute) + srv.driveRebaseMerge(context.Background(), store, f, ghpkg.PRMergeState{State: "open", HeadSHA: "0123456789abcdef0123456789abcdef01234567", BaseRef: "main", MergeableState: "clean"}) + f, _ = store.Get("testorg/testrepo", 8) + if f.State != rebasemerge.StateMerged || f.MergeSHA != "0ddba11" { + t.Fatalf("after clean: %+v", f) + } + if len(mock.merges) != 1 || mock.merges[0]["sha"] != "0123456789abcdef0123456789abcdef01234567" { + t.Fatalf("merge must pin the rebased head: %v", mock.merges) + } + acts := srv.operatorActions().List("testorg/testrepo", 8) + if len(acts) != 1 || acts[0].Outcome != operatorActionOutcomeApplied || !strings.Contains(acts[0].Detail, "merged 0ddba11 after rebase") { + t.Fatalf("ledger = %+v", acts) + } + + // Conflict path on another follow-through. + g := rebasemerge.Arm("testorg/testrepo", 9, "writer", "main", "feedfacefeedfacefeedfacefeedfacefeedface", true, now) + g.Kicked(now, "fixer") + _ = store.Put(g) + _ = srv.operatorActions().Record("testorg/testrepo", 9, OperatorAction{Action: operatorActionMergeNow, Actor: "writer", At: now, Outcome: operatorActionOutcomePending, Stage: 85}) + before := len(mock.comments) + now = now.Add(rebasemerge.DefaultRebaseDeadline) + srv.driveRebaseMerge(context.Background(), store, g, ghpkg.PRMergeState{State: "open", HeadSHA: "feedfacefeedfacefeedfacefeedfacefeedface", BaseRef: "main", MergeableState: "dirty"}) + g, _ = store.Get("testorg/testrepo", 9) + if g.State != rebasemerge.StateFailed || g.FailReason != rebasemerge.FailConflict || len(g.Options) != 2 { + t.Fatalf("conflict: %+v", g) + } + acts = srv.operatorActions().List("testorg/testrepo", 9) + if len(acts) != 1 || acts[0].Outcome != operatorActionOutcomeFailed || !strings.Contains(acts[0].Detail, "conflicts") { + t.Fatalf("ledger = %+v", acts) + } + if len(mock.comments) != before+1 || !strings.Contains(mock.comments[before], "did not land") || !strings.Contains(mock.comments[before], rebasemerge.OptionAdoptFreshLabel) || !strings.Contains(mock.comments[before], rebasemerge.OptionCloseSupersLabel) { + t.Fatalf("failure note = %q", mock.comments[before:]) + } + res := rebaseMergeFailedResult(g) + if res.Action != rowActionRefused || len(res.Options) != 2 || res.Options[0].Action != decisionActionAdopt || res.Options[1].Action != decisionActionCloseSuperseded { + t.Fatalf("failed result = %+v", res) + } +} + +// The row: while the follow-through runs the caption reads "Rebasing → +// merge queued (approved by @you)" and the ledger's followed[] carries the +// steps; the menu offers "Rebase, then merge as maintainer" at 085 and in +// place of merge-now at 090 when the row needs a rebase. +func TestRebaseMergeRowCaptionFollowedAndOptions(t *testing.T) { + store := useRebaseMergeStore(t) + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := rebasemerge.Arm("hivecommons/hive", 14822, "clubanderson", "v5", "b0f5f80", false, now) + f.Kicked(now.Add(time.Second), "fixer") + _ = store.Put(f) + srv := &Server{} + items := []StageTrackerItem{{Repo: "hivecommons/hive", Number: 14822, Kind: "pr", Stage: 85, Caption: "Needs human decision", Modifiers: []string{modNeedsRebase}, + LastOperatorAction: &StageTrackerOperatorAction{Action: operatorActionMergeNow, Actor: "clubanderson", At: now, Followed: []StageTrackerHop{{Number: 85, Slug: "needs-decision", At: now.Add(time.Hour)}}}}} + srv.applyRebaseMergeFollowThrough(items, now.Add(time.Minute)) + it := items[0] + if it.RebaseMerge == nil || it.RebaseMerge.State != rebasemerge.StateRebasing || it.Caption != "Rebasing → merge queued (approved by @clubanderson)" { + t.Fatalf("row = %+v caption=%q", it.RebaseMerge, it.Caption) + } + followed := it.LastOperatorAction.Followed + if len(followed) != 3 || followed[0].Slug != rebasemerge.StepApprovalRecorded || followed[1].Slug != rebasemerge.StepRebaseKicked || followed[2].Number != 85 { + t.Fatalf("followed = %+v", followed) + } + + // 085 options: Let hive decide, Approve, Rebase-then-merge, … + d := decisionForPR(it, nil, "", false) + if len(d.Options) < 3 || d.Options[2].Action != decisionActionMergeNow || d.Options[2].Label != rebaseMergeFollowThroughLabel || !strings.Contains(d.Options[2].Consequence, "rebases #14822 onto its base branch") { + t.Fatalf("085 options = %+v", d.Options) + } + // Without needs-rebase the 085 menu is unchanged. + plain := decisionForPR(StageTrackerItem{Repo: "o/r", Number: 1, Kind: "pr", Stage: 85}, nil, "", false) + for _, o := range plain.Options { + if o.Action == decisionActionMergeNow { + t.Fatalf("merge-now offered at 085 without needs-rebase: %+v", plain.Options) + } + } + // 090 relabel. + hm := decisionForHumanMerge(StageTrackerItem{Repo: "o/r", Number: 7, Kind: "pr", Stage: 90, BaseRef: "v5", Labels: []string{"needs-rebase"}}, false) + if hm.Options[0].Action != decisionActionMergeNow || hm.Options[0].Label != rebaseMergeFollowThroughLabel || hm.Options[0].Consequence != rebaseMergeFollowThroughConsequence(7, "v5") { + t.Fatalf("090 option = %+v", hm.Options[0]) + } + hmPlain := decisionForHumanMerge(StageTrackerItem{Repo: "o/r", Number: 7, Kind: "pr", Stage: 90, BaseRef: "v5"}, false) + if hmPlain.Options[0].Label != "Approve & merge as maintainer" { + t.Fatalf("090 plain option = %+v", hmPlain.Options[0]) + } + // Settled: the caption is the lane's again; a stale record is dropped. + f.Merged(now.Add(2*time.Minute), "abc") + _ = store.Update(f) + items[0].Caption = "Merged" + srv.applyRebaseMergeFollowThrough(items, now.Add(3*time.Minute)) + if items[0].Caption != "Merged" || items[0].RebaseMerge == nil || items[0].RebaseMerge.State != rebasemerge.StateMerged { + t.Fatalf("settled row = %+v caption=%q", items[0].RebaseMerge, items[0].Caption) + } + items[0].RebaseMerge = nil + srv.applyRebaseMergeFollowThrough(items, now.Add(3*time.Hour)) + if items[0].RebaseMerge != nil { + t.Fatalf("stale settled record still on the row: %+v", items[0].RebaseMerge) + } +} + +// hivecommons/hive#15103: the fixer's rebase loop guard shows on the row +// ("Rebasing · attempt n/2", then "needs a person"), and a follow-through +// whose rebased head is still dirty retries while attempts remain and +// fails with the conflict once they are exhausted. +func TestRebaseAttemptsPillAndFollowThroughExhaustion(t *testing.T) { + attempts := useRebaseAttemptsStore(t) + store := useRebaseMergeStore(t) + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + rebaseMergeNow = func() time.Time { return now } + t.Cleanup(func() { rebaseMergeNow = time.Now }) + + items := []StageTrackerItem{{Repo: "hivecommons/hive", Number: 15087, Kind: "pr", Stage: 90, Modifiers: []string{modNeedsRebase}}, {Repo: "hivecommons/hive", Number: 1, Kind: "pr", Stage: 90}} + applyRebaseAttempts(items) + if items[0].Rebase != nil || items[1].Rebase != nil { + t.Fatalf("no episode, no pill: %+v %+v", items[0].Rebase, items[1].Rebase) + } + attempts.Observe("hivecommons/hive", 15087, "aaa1111aaa1111", now) + applyRebaseAttempts(items) + if r := items[0].Rebase; r == nil || r.Attempt != 1 || r.Max != 2 || r.Exhausted || r.Head != "aaa1111" || r.Text != "Rebasing · attempt 1/2" { + t.Fatalf("attempt 1 pill = %+v", r) + } + attempts.Observe("hivecommons/hive", 15087, "bbb2222", now) + attempts.Observe("hivecommons/hive", 15087, "ccc3333", now) + applyRebaseAttempts(items) + if r := items[0].Rebase; r == nil || !r.Exhausted || r.Attempt != 2 || r.Text != "Rebase failed · 2/2 — needs a person" { + t.Fatalf("exhausted pill = %+v", r) + } + + // Follow-through on the same PR: still dirty after the fixer's first + // push → back to rebasing; exhausted → failed with the files. + mock := &repoItemDecisionMock{} + srv := newRepoItemDecisionServer(t, mock) + srv.operatorActionStore = newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json")) + attempts.Clear("hivecommons/hive", 15087) + attempts.Observe("hivecommons/hive", 15087, "aaa1111", now) + f := rebasemerge.Arm("hivecommons/hive", 15087, "clubanderson", "v5", "aaa1111", false, now) + f.Kicked(now, "scanner") + _ = store.Put(f) + now = now.Add(time.Minute) + attempts.Observe("hivecommons/hive", 15087, "bbb2222", now) + srv.driveRebaseMerge(context.Background(), store, f, ghpkg.PRMergeState{State: "open", HeadSHA: "bbb2222", BaseRef: "v5", MergeableState: "dirty"}) + f, _ = store.Get("hivecommons/hive", 15087) + if f.State != rebasemerge.StateRebasing || f.Steps[len(f.Steps)-1].Step != rebasemerge.StepStillConflicting { + t.Fatalf("after first still-dirty head: %+v", f) + } + now = now.Add(time.Minute) + attempts.Observe("hivecommons/hive", 15087, "ccc3333", now) + srv.driveRebaseMerge(context.Background(), store, f, ghpkg.PRMergeState{State: "open", HeadSHA: "ccc3333", BaseRef: "v5", MergeableState: "dirty"}) + f, _ = store.Get("hivecommons/hive", 15087) + if f.State != rebasemerge.StateFailed || f.FailReason != rebasemerge.FailConflict || len(f.Options) != 2 { + t.Fatalf("after exhausting attempts: %+v", f) + } +} + +// Approve on a PR GitHub reports dirty (hivecommons/hive#15103, live +// 17:59): the toast must not promise the merge gate "takes it from here" +// (it skips a conflicting PR for good). The approval is recorded, the +// fixer's rebase episode opens in the operator's name (attempt 1/2) so +// the row reads "Rebasing · attempt 1/2", and the toast offers "Rebase, +// then merge as maintainer". A hive-authored PR that is merely behind +// gets update-branch on the spot. +func TestRepoItemDecisionApproveOnDirtyPRQueuesRebase(t *testing.T) { + attempts := useRebaseAttemptsStore(t) + mock := &repoItemDecisionMock{prForeign: true, prMergeState: "dirty", prLabels: []string{"stage/085-needs-decision", "needs-rebase"}} + srv := newRepoItemDecisionServer(t, mock) + + w := postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"approve","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("approve on dirty: code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Status != "approval-commented" || resp.Rebase == nil || resp.Rebase.Attempt != 1 || resp.Rebase.Max != 2 || resp.Rebase.Text != "Rebasing · attempt 1/2" { + t.Fatalf("response = %+v rebase=%+v", resp, resp.Rebase) + } + if len(mock.comments) < 2 || !strings.HasPrefix(mock.comments[0], "/lgtm\n") || !strings.HasPrefix(mock.comments[1], "/approve\n") { + t.Fatalf("the approval is recorded first: %q", mock.comments) + } + res := resp.Result + if res == nil || res.Action != rowActionApproved || res.Outcome != "Approved — #8 conflicts with main; hive will rebase it next pass (attempt 1/2)." { + t.Fatalf("result = %+v", res) + } + if strings.Contains(res.Next, "takes it from here;") || !strings.Contains(res.Next, "skips a conflicting PR") { + t.Fatalf("next = %q", res.Next) + } + if len(res.Options) != 1 || res.Options[0].Action != decisionActionMergeNow || res.Options[0].Label != rebaseMergeFollowThroughLabel || res.Options[0].Consequence != rebaseMergeFollowThroughConsequence(8, "main") { + t.Fatalf("options = %+v", res.Options) + } + a, ok := attempts.Get("testorg/testrepo", 8) + if !ok || a.RequestedBy != "writer" || a.Count() != 1 || a.Head() != "feedfacefeedfacefeedfacefeedfacefeedface" { + t.Fatalf("episode = %+v ok=%v", a, ok) + } + if mock.updates != 0 { + t.Fatalf("a dirty head gets no update-branch: %d", mock.updates) + } + items := []StageTrackerItem{{Repo: "testorg/testrepo", Number: 8, Kind: "pr", Stage: 85}} + applyRebaseAttempts(items) + if items[0].Rebase == nil || items[0].Rebase.Text != "Rebasing · attempt 1/2" { + t.Fatalf("row = %+v", items[0].Rebase) + } + + // Hive's own PR, merely behind: update-branch now, and the toast says so. + mock2 := &repoItemDecisionMock{prMergeState: "behind", prLabels: []string{"stage/085-needs-decision", "needs-rebase"}} + srv2 := newRepoItemDecisionServer(t, mock2) + w = postRepoItemDecisionAs(t, srv2, 8, "writer", "merger", `{"decision":"approve","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("approve on behind: code=%d body=%s", w.Code, w.Body.String()) + } + resp = repoItemDecisionResponse{} + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if mock2.updates != 1 || resp.Result == nil || !strings.Contains(resp.Result.Outcome, "is behind main; hive is updating the branch") { + t.Fatalf("behind: updates=%d result=%+v", mock2.updates, resp.Result) + } + + // Clean: the plain approve toast is unchanged. + mock3 := &repoItemDecisionMock{prForeign: true, prLabels: []string{"stage/085-needs-decision"}} + srv3 := newRepoItemDecisionServer(t, mock3) + w = postRepoItemDecisionAs(t, srv3, 8, "writer", "merger", `{"decision":"approve","type":"pr"}`) + resp = repoItemDecisionResponse{} + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if w.Code != http.StatusOK || resp.Rebase != nil || resp.Result == nil || len(resp.Result.Options) != 0 || !strings.Contains(resp.Result.Next, "takes it from here") { + t.Fatalf("clean approve: code=%d resp=%+v", w.Code, resp.Result) + } +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index a030161790..d410d0c0f3 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -1697,6 +1697,11 @@ func (s *Server) Start() error { costTicker := time.NewTicker(costHistoryMinIntervalMs * time.Millisecond) defer costTicker.Stop() go s.runCostSampler(costTicker.C) + // The operator's "Rebase, then merge as maintainer" follow-throughs + // (rebase_merge_followthrough.go) poll from here. + followCtx, cancelFollow := context.WithCancel(context.Background()) + defer cancelFollow() + s.StartRebaseMergeFollowThrough(followCtx) return srv.Serve(ln) } diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 4f9719d9db..947910d00a 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -349,6 +349,14 @@ type StageTrackerItem struct { // window, at 060/080/095: when it started, when it ends, the window // and the head it was measured on. The SPA counts it down in place. Soak *StageTrackerSoak `json:"soak,omitempty"` + // RebaseMerge is set while an operator's "Rebase, then merge as + // maintainer" follow-through runs on the PR (or just settled): its + // state and the row caption to show in place of the lane's. + RebaseMerge *StageTrackerRebaseMerge `json:"rebase_merge,omitempty"` + // Rebase is set on a conflicting PR the fixer is rebasing on the hive's + // behalf: which attempt of the loop guard this is, or that the hive + // ran out and a person must resolve it. + Rebase *StageTrackerRebase `json:"rebase,omitempty"` // SentinelAlert is true on a PR the suspicious-activity sentinel flagged: // it wears the configured alert label (sentinel.label, default // sentinel-alert) or the review evidence bundle for its current head @@ -2242,6 +2250,8 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto stageTrackerMergeTrainPostPass(resp.Items) s.applyOperatorActions(resp.Items, now) s.applyDecidedProjection(resp.Items, now) + applyRebaseAttempts(resp.Items) + s.applyRebaseMergeFollowThrough(resp.Items, now) resp.NeedsHuman, resp.OnHold = stageTrackerHumanCounts(resp.Items) stageTrackerResolveLinkedPRs(resp.Items, prOpen) stageTrackerMarkClosedBy(resp.Items, s.mergedLedger().ClosedBy) diff --git a/src/pkg/dashboard/stage_tracker_cues_test.go b/src/pkg/dashboard/stage_tracker_cues_test.go index 1e2081ea48..c1c58a565b 100644 --- a/src/pkg/dashboard/stage_tracker_cues_test.go +++ b/src/pkg/dashboard/stage_tracker_cues_test.go @@ -22,6 +22,7 @@ func stageTrackerCuesJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerWorkers"), jsFunc(t, html, "stageTrackerWorkerKey"), jsFunc(t, html, "stageTrackerWorkingOn"), + jsFunc(t, html, "stageTrackerRebaseMergeLive"), jsFunc(t, html, "stageTrackerCueLead"), jsFunc(t, html, "stageTrackerAgoText"), jsFunc(t, html, "stageTrackerCueClasses"), diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 10cbdfd2c4..307b2532af 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -280,8 +280,7 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision if held { d.Blocker += " " + decisionHeldBlocker(it.Hold) } - mergeNow := decisionOption(decisionActionMergeNow, "Approve & merge as maintainer", !held, "Release the hold first") - mergeNow.Consequence = "merges " + ref + " into " + into + " now via hive's identity, attributed to you" + mergeNow := decisionMergeNowOption(it, held) queue := decisionOption(decisionActionQueueMerge, "Approve — let hive merge", !held, "Release the hold first") queue.Consequence = "records your approval as the trust override for this head; the hive's merge sweep merges " + ref + " as-is on its next pass once CI is green and the head has soaked, and does not adopt it" if admitter != "" && !held { @@ -353,6 +352,40 @@ func decisionReauthorOption(it StageTrackerItem, ref string, held bool) StageTra return o } +// decisionMergeNowOption is "Approve & merge as maintainer", or — when the +// row wears needs-rebase, so a plain merge would be a GitHub 405 — "Rebase, +// then merge as maintainer": the same click records the approval, has the +// hive rebase the PR, and merges it on green (hivecommons/hive#14822). +func decisionMergeNowOption(it StageTrackerItem, held bool) StageTrackerDecisionOption { + ref := "#" + strconv.Itoa(it.Number) + into := strings.TrimSpace(it.BaseRef) + if into == "" { + into = "its base branch" + } + if stageTrackerNeedsRebase(it) { + opt := decisionOption(decisionActionMergeNow, rebaseMergeFollowThroughLabel, !held, "Release the hold first") + opt.Consequence = rebaseMergeFollowThroughConsequence(it.Number, strings.TrimSpace(it.BaseRef)) + return opt + } + opt := decisionOption(decisionActionMergeNow, "Approve & merge as maintainer", !held, "Release the hold first") + opt.Consequence = "merges " + ref + " into " + into + " now via hive's identity, attributed to you" + return opt +} + +// stageTrackerNeedsRebase: the row wears needs-rebase (modifier or label), +// or a rebase-then-merge follow-through is already running on it. +func stageTrackerNeedsRebase(it StageTrackerItem) bool { + if slices.Contains(it.Modifiers, modNeedsRebase) { + return true + } + for _, l := range it.Labels { + if strings.EqualFold(strings.TrimSpace(l), "needs-rebase") { + return true + } + } + return it.RebaseMerge != nil && it.RebaseMerge.State != "" && it.RebaseMerge.State != "merged" && it.RebaseMerge.State != "failed" +} + // decisionForUnauthorized: a row wearing hive:unauthorized outside 085 — // the hive's GitHub App lacks the permission for its next step, so a // person takes that step on GitHub (approve the held workflow runs, merge @@ -682,6 +715,12 @@ func decisionForPR(it StageTrackerItem, verdict *review.Aggregate, sentinelLabel decisionOption(decisionActionCloseWontfix, "Close as won't fix", true, ""), decisionHoldOption(held), } + // A PR parked here that also needs a rebase has no lane rebasing it + // until a person speaks (hivecommons/hive#14822): offer the maintainer + // merge with the rebase folded in, right after Approve. + if stageTrackerNeedsRebase(it) && !sentinel { + d.Options = slices.Insert(d.Options, 2, decisionMergeNowOption(it, held)) + } if selfHold != nil { // Release leads: it is the one action that answers the question. d.Options = append([]StageTrackerDecisionOption{decisionHoldOption(true)}, d.Options[:len(d.Options)-1]...) diff --git a/src/pkg/dashboard/stage_tracker_merge_gate_test.go b/src/pkg/dashboard/stage_tracker_merge_gate_test.go index bf2ee4faba..76ba1d7a7c 100644 --- a/src/pkg/dashboard/stage_tracker_merge_gate_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_gate_test.go @@ -260,6 +260,24 @@ stageTrackerGateCountdownSync(el, now + 30000); assert.deepStrictEqual([n1.textContent, n2.textContent], ['· next sweep in 12s', '· 8m left']); stageTrackerGateCountdownSync(el, now + 500000); assert.deepStrictEqual([n1.textContent, n2.textContent], ['· sweep due now', '· soak window complete']); + +// hivecommons/hive#15103: the fixer's rebase loop guard is the pill while +// the hive rebases a conflicting PR, spinning on attempt n/2 and asking +// for a person once exhausted; a live rebase-then-merge follow-through +// keeps its own caption instead. +const rebasing = { stage: 90, number: 15087, rebase: { attempt: 1, max: 2, exhausted: false, head: 'aaa1111', text: 'Rebasing · attempt 1/2' } }; +const rbi = stageTrackerMergeGateInfo(rebasing, now); +assert.deepStrictEqual([rbi.state, rbi.word, rbi.detail, rbi.cue], ['rebasing', 'Rebasing · attempt 1/2', '', 'running']); +assert.ok(rbi.tip.includes('attempt 1 of 2'), rbi.tip); +assert.ok(stageTrackerGateCueHtml(rebasing, now).includes('cue-spin'), 'rebasing spins'); +const exhausted = { stage: 90, rebase: { attempt: 2, max: 2, exhausted: true, head: 'ccc3333', text: 'Rebase failed · 2/2 — needs a person' } }; +const exi = stageTrackerMergeGateInfo(exhausted, now); +assert.deepStrictEqual([exi.state, exi.word, exi.cue], ['rebase-failed', 'Rebase failed · 2/2 — needs a person', 'waiting']); +assert.ok(exi.tip.includes('2 times') && exi.tip.includes('ccc3333') && exi.tip.includes('Adopt into fresh branch'), exi.tip); +assert.ok(stageTrackerMergeGateWordHtml(exhausted, now).includes('Rebase failed · 2/2 — needs a person')); +const withFollowThrough = { stage: 90, rebase: rebasing.rebase, rebase_merge: { state: 'rebasing' } }; +assert.strictEqual(stageTrackerMergeGateInfo(withFollowThrough, now), null, 'a live follow-through owns the row caption'); +assert.strictEqual(stageTrackerMergeGateInfo({ stage: 90, rebase: rebasing.rebase, rebase_merge: { state: 'failed' } }, now).state, 'rebasing', 'a settled follow-through hands the pill back'); console.log('merge-gate helpers ok'); `) } diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 7ef1d63d17..95da9a1899 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -113,6 +113,10 @@ func stageTrackerRowActionsPreamble(t *testing.T, html string) string { jsConstLine(t, html, "STAGE_TRACKER_RESULT_TOAST_MAX"), jsConstLine(t, html, "STAGE_TRACKER_ACTING_MAX_MS"), jsConstBlock(t, html, "STAGE_TRACKER_ACTING_CAPTIONS"), + jsConstLine(t, html, "STAGE_TRACKER_REBASE_MERGE_LABEL"), + jsConstLine(t, html, "STAGE_TRACKER_ACTION_REBASE_QUEUED"), + jsFunc(t, html, "stageTrackerNeedsRebase"), + jsFunc(t, html, "stageTrackerRebaseMergeLive"), jsConstBlock(t, html, "STAGE_TRACKER_ACTION_WORDS"), "var _stageTrackerResultToasts = []; var _stageTrackerPending = [];", jsFunc(t, html, "stageTrackerActingCaption"), @@ -1150,6 +1154,14 @@ assert.ok(!acting('o/r/issue#7'), 'a no-op or an error clears at once'); assert.strictEqual(del.toast.text.outcome, "Hive decided on o/r#14947: adopted (the author's clanker hasn't been connected since the nudge)", del.toast.text.outcome); assert.deepStrictEqual(del.pending[0].keys, ['o/r/pr#14947', 'o/r/issue#14938']); assert.ok(acting('o/r/issue#14938') && acting('o/r/pr#14947')); + // An approval is recorded when the server answers: "Approving…" clears + // at once instead of lingering beside the ✓ (hivecommons/hive#15103). + stageTrackerClearPending(del.pending[0]); + global.fetch = async () => ({ ok: true, status: 200, json: async () => ({ result: { action: 'approved', target: { repo: 'o/r', kind: 'pr', number: 14947, url: 'u947' }, outcome: 'Approved — #14947 conflicts with v5; hive will rebase it next pass (attempt 1/2).', next: 'n', options: [{ action: 'decide:merge-now', label: 'Rebase, then merge as maintainer', enabled: true }] } }) }); + stageTrackerSetConfirmSkip('decide:approve', true); + const ap = await runRowAction('decide:approve', Object.assign({ repo: 'o/r', kind: 'pr' }, nested)); + assert.ok(!acting('o/r/pr#14947'), 'approved: the acting caption clears once the decision records'); + assert.strictEqual(ap.toast.text.options.length, 1, 'the approve toast carries the rebase-then-merge button'); })().catch(e => { console.error(e); process.exit(1); }); `) } @@ -1375,5 +1387,102 @@ assert.strictEqual(stageTrackerDCOCaveat([]), ''); await stageTrackerActionPayload([{ ...pr317, dco_unsigned: 0 }], 'decide:merge-now'); assert.ok(!dialogs[0].cfg.message.includes('Signed-off-by'), dialogs[0].cfg.message); })().catch(e => { console.error(e); process.exit(1); }); +} + +// TestStageTrackerRebaseThenMergeRow: a PR that needs a rebase offers +// "Rebase, then merge as maintainer" in place of (090) or next to (085) +// the plain maintainer merge; the acting caption, the 202 rebase-queued +// toast, the cue-working glow while the follow-through runs, and the +// ledger trail's step lines all read as the operator was promised +// (hivecommons/hive#14822). +func TestStageTrackerRebaseThenMergeRow(t *testing.T) { + html := indexHTML(t) + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+"\n"+stageTrackerCuesJS(t, html)+stageTrackerActedJS(t, html)+"\n"+jsFunc(t, html, "agentNowClockTime")+` +const ids = as => as.map(a => a.id); +const merger = { user: true, canHold: true, canHuman: true }; +const rebaseOpt = { action: 'decide:merge-now', label: STAGE_TRACKER_REBASE_MERGE_LABEL, enabled: true, + consequence: "hive rebases #14822 onto v5, waits for CI, then merges it with your approval on record; you'll get a toast when it lands or if the rebase conflicts" }; +const pr = { repo: 'hivecommons/hive', kind: 'pr', number: 14822, title: 'fix: preserve owner intent through PR decision paths', url: 'u', author: 'thatguywob', author_kind: 'clanker', base_ref: 'v5', + stage: 85, caption: 'Needs human decision', modifiers: ['needs-decision', 'needs-rebase'], + decision_needed: { question: 'q', options: [ + { action: 'decide:delegate', label: 'Let hive decide', enabled: true }, + { action: 'decide:approve', label: 'Approve', enabled: true }, + rebaseOpt, + { action: 'decide:close-superseded', label: 'Close as superseded', enabled: true }, + { action: 'hold', label: 'Hold', enabled: true } ] } }; + +assert.strictEqual(stageTrackerNeedsRebase(pr), true); +assert.strictEqual(stageTrackerNeedsRebase({ ...pr, modifiers: ['needs-decision'] }), false); +assert.strictEqual(stageTrackerNeedsRebase({ ...pr, modifiers: [], labels: ['Needs-Rebase'] }), true, 'the label counts too'); +assert.strictEqual(stageTrackerNeedsRebase({ ...pr, modifiers: [], rebase_merge: { state: 'rebasing' } }), true, 'a live follow-through counts'); +assert.strictEqual(stageTrackerNeedsRebase({ ...pr, modifiers: [], rebase_merge: { state: 'merged' } }), false); + +// 085 menu: the relabelled merge leads; the 085 menu without needs-rebase is untouched. +let as = stageTrackerRowActions(pr, merger); +assert.strictEqual(as[0].id, 'decide:merge-now'); assert.strictEqual(as[0].label, STAGE_TRACKER_REBASE_MERGE_LABEL); +assert.ok(as[0].hint.startsWith('hive rebases #14822 onto v5'), 'consequence rides as the hint: ' + as[0].hint); +assert.ok(as[0].enabled && as[0].lead); +const menu = stageTrackerMenuHtml(as, 'hivecommons/hive#14822'); +assert.ok(menu.includes('Rebase, then merge as maintainer'), menu); +assert.ok(menu.indexOf('data-ham-act="decide:merge-now"') < menu.indexOf('data-ham-act="decide"'), 'the rebase-merge leads the Decide… group'); +const req = stageTrackerActionRequest(pr, 'decide:merge-now', {}); +assert.strictEqual(req.url, '/api/repos/hivecommons/hive/items/14822/decision'); +assert.deepStrictEqual(req.body, { decision: 'merge-now', comment: '', type: 'pr' }, 'the same decision wire: the server folds the rebase in'); + +// Acting caption and the action word for the 202. +assert.strictEqual(stageTrackerActingCaption('decide:merge-now', pr), 'Rebasing, then merging…'); +assert.strictEqual(stageTrackerActingCaption('decide:merge-now', { ...pr, modifiers: [] }), 'Merging…'); +assert.strictEqual(STAGE_TRACKER_ACTION_WORDS[STAGE_TRACKER_ACTION_REBASE_QUEUED], 'rebase queued, merge to follow'); + +// The toast for the 202 names the rebase-merge, not a plain merge. +const result = { action: STAGE_TRACKER_ACTION_REBASE_QUEUED, target: { repo: 'hivecommons/hive', kind: 'pr', number: 14822, url: 'u' }, + outcome: 'Your approval is on record; the hive is rebasing #14822 onto v5.', next: 'Once CI is green on the rebased head the hive merges it with your approval attributed; you\'ll get a toast when it lands or if the rebase conflicts.' }; +const text = stageTrackerResultText(result, pr, { id: 'decide:merge-now' }); +const flat = typeof text === 'string' ? text : JSON.stringify(text); +assert.ok(flat.includes('Rebase, then merge as maintainer on hivecommons/hive#14822'), flat); +assert.ok(flat.includes('rebasing #14822 onto v5'), flat); + +// A refused follow-through (conflict) carries its two ways out. +const failed = { action: 'refused', why: 'rebase-conflict', target: result.target, outcome: 'Rebase conflicts in .github/workflows/v2-ci.yml.', + options: [{ action: 'decide:adopt', label: 'Adopt into fresh branch', enabled: true }, { action: 'decide:close-superseded', label: 'Close as superseded', enabled: true }] }; +const failedText = stageTrackerResultText(failed, pr, { id: 'decide:merge-now' }); +const failedFlat = typeof failedText === 'string' ? failedText : JSON.stringify(failedText); +assert.ok(failedFlat.includes('v2-ci.yml'), failedFlat); + +// The row while it runs: cue-working, caption from the server, state +// signature changes with the follow-through state. +const running = { ...pr, caption: 'Rebasing → merge queued (approved by @clubanderson)', rebase_merge: { state: 'rebasing', actor: 'clubanderson', base: 'v5', text: 'Rebasing → merge queued (approved by @clubanderson)' } }; +assert.strictEqual(stageTrackerRebaseMergeLive(running), true); +assert.strictEqual(stageTrackerRebaseMergeLive(pr), false); +assert.ok(stageTrackerCueClasses(running, { workers: {} }).includes('cue-working'), 'the working cue while the hive rebases'); +assert.ok(!stageTrackerCueClasses(pr, { workers: {} }).includes('cue-working')); +assert.notStrictEqual(stageTrackerItemState(running), stageTrackerItemState({ ...running, rebase_merge: { state: 'ci-pending' } }), 'the acting row sees the state move'); + +// The ledger trail: step hops without a stage number read as plain steps. +const now = Date.parse('2026-10-29T10:00:00Z'); +const at = m => new Date(now - m * 60000).toISOString(); +const acted = { ...running, last_operator_action: { action: 'merge-now', actor: 'clubanderson', at: at(5), outcome: 'pending', detail: 'rebase-queued', stage_at: 85, + followed: [{ number: 0, slug: 'approval-recorded', at: at(5) }, { number: 0, slug: 'rebase-kicked', at: at(4), reason: 'fixer' }] } }; +const tip = stageTrackerActedTip(acted, now); +assert.ok(tip.includes('rebasing, then merging…'), tip); +assert.ok(tip.includes('Then the hive recorded your approval'), tip); +assert.ok(tip.includes('Then the hive started the rebase — fixer'), tip); + +// Approve on a dirty PR (hivecommons/hive#15103): the toast tells the +// truth (the gate skips a conflicting PR), carries the one-click upgrade +// to rebase-then-merge, and the row's state signature moves with the +// fixer's attempt so "Approving…" does not wait on the gate. +const approvedDirty = { action: 'approved', target: result.target, + outcome: 'Approved — #14822 conflicts with v5; hive will rebase it next pass (attempt 1/2).', + next: 'The merge gate skips a conflicting PR, so your approval alone would not land it. Once the rebased head is green the gate takes it — or have hive merge it for you right after the rebase:', + options: [{ action: 'decide:merge-now', label: STAGE_TRACKER_REBASE_MERGE_LABEL, enabled: true, consequence: 'hive rebases #14822 onto v5, waits for CI, then merges it with your approval on record' }] }; +const apText = stageTrackerResultText(approvedDirty, pr, { id: 'decide:approve' }); +assert.strictEqual(apText.type, 'success'); +assert.ok(apText.outcome.includes('hive will rebase it next pass (attempt 1/2)'), apText.outcome); +assert.strictEqual(apText.options.length, 1, 'the approve toast offers the rebase-then-merge button'); +assert.strictEqual(apText.options[0].label, 'Rebase, then merge as maintainer'); +const plainApproved = stageTrackerResultText({ action: 'approved', target: result.target, outcome: '/lgtm + /approve posted.', next: 'The merge gate takes it from here; the dashboard merges nothing.' }, pr, { id: 'decide:approve' }); +assert.strictEqual(plainApproved.options.length, 0, 'a plain approval has no buttons'); +assert.notStrictEqual(stageTrackerItemState(pr), stageTrackerItemState({ ...pr, rebase: { attempt: 1, max: 2, text: 'Rebasing · attempt 1/2' } }), 'the fixer attempt moves the row state'); `) } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index de52fdf798..617595a367 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14628,6 +14628,15 @@

Where to get help

// cue — 'running' (sweep on it now) | 'waiting' | 'soaking' | 'merging' | '' // until — ms epoch the detail counts down to (0 when none) function stageTrackerMergeGateInfo(item, nowMs) { + const rb = item && item.rebase; + if (rb && rb.text && !(item.rebase_merge && item.rebase_merge.state && item.rebase_merge.state !== 'failed' && item.rebase_merge.state !== 'merged')) { + // The fixer's autonomous rebase-resolve loop guard: "Rebasing · + // attempt 1/2" spins; past the cap the row asks for a person. + const tip = rb.exhausted + ? 'hive rebased this PR ' + rb.max + ' times and GitHub still reports conflicts' + (rb.head ? ' on ' + rb.head : '') + '. A person has to resolve it (or Adopt into fresh branch / Close as superseded from the row menu).' + : "hive's fixer is rebasing this PR onto its base branch and resolving conflicts (attempt " + rb.attempt + ' of ' + rb.max + '). A pushed head that is still conflicting is the next attempt.'; + return { state: rb.exhausted ? 'rebase-failed' : 'rebasing', word: rb.text, detail: '', tip, cue: rb.exhausted ? 'waiting' : 'running', until: 0 }; + } const cover = stageTrackerCoveringPR(item); const src = cover && cover.merge_gate && cover.merge_gate.state ? cover : item; const state = stageTrackerMergeGateStateOf(src); @@ -15737,6 +15746,23 @@

Where to get help

'merge-now': 'Approve & merge as maintainer', 'queue-merge': 'Approve — let hive merge', adopt: 'Adopt', 'adopt-now': 'Adopt now', reroute: 'Reroute to another clanker', }; + // "Rebase, then merge as maintainer" is merge-now on a row that needs a + // rebase (hivecommons/hive#14822): the server relabels the option and + // answers 202 rebase-queued; the follow-through's steps come back in + // last_operator_action.followed[] as hops without a stage number. + const STAGE_TRACKER_REBASE_MERGE_LABEL = 'Rebase, then merge as maintainer'; + const STAGE_TRACKER_ACTION_REBASE_QUEUED = 'rebase-queued'; + function stageTrackerNeedsRebase(item) { + if (!item) return false; + if ((Array.isArray(item.modifiers) ? item.modifiers : []).indexOf('needs-rebase') >= 0) return true; + if ((Array.isArray(item.labels) ? item.labels : []).some(l => String(l).toLowerCase() === 'needs-rebase')) return true; + const rm = item.rebase_merge; + return !!(rm && rm.state && rm.state !== 'merged' && rm.state !== 'failed'); + } + function stageTrackerRebaseMergeLive(item) { + const rm = item && item.rebase_merge; + return !!(rm && (rm.state === 'approved' || rm.state === 'rebasing' || rm.state === 'ci-pending')); + } const STAGE_TRACKER_ACTED_STATES = ['waiting', 'addressed', 'stuck', 'pending', 'failed', 'executing', 'blocked']; const STAGE_TRACKER_ACTED_FILTERS = ['any', 'awaiting', 'acted', 'stuck']; const STAGE_TRACKER_ACTED_STUCK_DEFAULT_S = 30 * 60; @@ -15784,7 +15810,7 @@

Where to get help

case 'applied': return 'done' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'no-op': return 'nothing changed' + (action.detail ? ': ' + stageTrackerActedPlain(action.detail) : ''); case 'failed': return 'failed' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); - case 'pending': return 'the hive is deciding…'; + case 'pending': return action.action === 'merge-now' ? 'rebasing, then merging…' : 'the hive is deciding…'; case 'executing': return (action.detail ? stageTrackerActedPlain(action.detail) : 'decided — the hive is carrying it out…'); case 'no-effect': return "hasn't taken effect" + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); case 'blocked': return 'blocked' + (action.detail ? ' — ' + stageTrackerActedPlain(action.detail) : ''); @@ -15814,6 +15840,8 @@

Where to get help

held: 'put on hold', released: 'hold released', 'already accepted': 'it was already accepted', + 'approval-recorded': 'recorded your approval', 'rebase-kicked': 'started the rebase', rebased: 'rebased it onto the base branch', 'ci-green': 'saw CI go green', merged: 'merged it', + 'rebase-conflict': 'the rebase conflicts', 'ci-red': 'CI went red on the rebased head', 'rebase-timeout': 'the rebase did not land in time', 'head-not-pushable': 'the hive cannot push to this fork', }; function stageTrackerActedPlain(text) { const t = String(text || '').trim(); @@ -15874,7 +15902,8 @@

Where to get help

const followed = Array.isArray(a.followed) ? a.followed : []; followed.slice(-3).forEach(h => { const hopMs = Date.parse(h.at || '') || nowMs; - lines.push('Then the hive ' + (h.regressed ? 'sent it back to ' : 'moved it to ') + stageTrackerActedStageName(h.number) + (h.reason ? ' — ' + stageTrackerActedPlain(h.reason) : '') + ' · ' + stageTrackerActedAgo(nowMs - hopMs) + '.'); + if (!(Number(h.number) > 0) && h.slug) lines.push('Then the hive ' + stageTrackerActedPlain(h.slug) + (h.reason ? ' — ' + h.reason : '') + ' · ' + stageTrackerActedAgo(nowMs - hopMs) + '.'); + else lines.push('Then the hive ' + (h.regressed ? 'sent it back to ' : 'moved it to ') + stageTrackerActedStageName(h.number) + (h.reason ? ' — ' + stageTrackerActedPlain(h.reason) : '') + ' · ' + stageTrackerActedAgo(nowMs - hopMs) + '.'); }); if (src.count > 1) lines.push((src.count - 1) + ' earlier action' + (src.count > 2 ? 's' : '') + ' on this item.'); return lines.join('\n'); @@ -16357,7 +16386,7 @@

Where to get help

// setback while it has fallen back. function stageTrackerCueClasses(item, ctx) { const out = []; - if (stageTrackerWorkingOn(item, ctx && ctx.workers)) out.push('cue-working'); + if (stageTrackerWorkingOn(item, ctx && ctx.workers) || stageTrackerRebaseMergeLive(item)) out.push('cue-working'); const mods = Array.isArray(item && item.modifiers) ? item.modifiers : []; if (mods.indexOf('regressed') >= 0) out.push('cue-setback'); // cue-merged is set by celebrateRow for the moment a merge lands, not @@ -18759,7 +18788,7 @@

All labels

// The clicked row and the item acted on (a nested PR for an issue // row's decision) both read "acting…" from the first byte sent. const keys = stageTrackerPendingKeys(it, rows); - const pend = stageTrackerSetPending(keys, stageTrackerActingCaption(id)); + const pend = stageTrackerSetPending(keys, stageTrackerActingCaption(id, it)); pending.push(pend); try { const r = await fetch(req.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(req.body) }); @@ -18780,7 +18809,11 @@

All labels

results.push({ item: it, ok: true, data, result }); // No change → nothing to wait for; otherwise the row keeps // acting until the tracker reports the target's new state. - if (result.action === STAGE_TRACKER_ACTION_NOOP || result.action === STAGE_TRACKER_ACTION_NO_EFFECT) stageTrackerClearPending(pend); + // An approval is recorded the moment the server answers; the + // row's next state (the gate, or "Rebasing · attempt n/2") is + // the tracker's to show, so "Approving…" must not linger beside + // the ✓ waiting for it (#15103). + if (result.action === STAGE_TRACKER_ACTION_NOOP || result.action === STAGE_TRACKER_ACTION_NO_EFFECT || result.action === 'refused' || result.action === 'approved') stageTrackerClearPending(pend); else { if (typeof stageTrackerDecidePending === 'function') stageTrackerDecidePending(pend, result, stageTrackerItemByKey(_stageTracker, stageTrackerTargetKey(result.target))); stageTrackerArmPending(pend, result.target); } if (result.action !== STAGE_TRACKER_ACTION_NOOP && result.action !== STAGE_TRACKER_ACTION_NO_EFFECT && typeof stageTrackerNoteOwnerEvent === 'function') stageTrackerNoteOwnerEvent(stageTrackerTargetKey(result.target) || stageTrackerItemKey(it), STAGE_TRACKER_ACTION_WORDS[result.action] || stageTrackerActionLabel(id)); if (items.length <= STAGE_TRACKER_RESULT_TOAST_MAX) toasts.push(stageTrackerResultToast(result, it, { id, rowRef: stageTrackerRefOf(it) })); @@ -19019,6 +19052,9 @@

All labels

} case 'decide:merge-now': { const base = items.map(it => it.base_ref || '').filter(Boolean)[0] || 'its base branch'; + if (items.some(stageTrackerNeedsRebase)) { + return (await stageTrackerAsk(id, 'confirm', { title: STAGE_TRACKER_REBASE_MERGE_LABEL, message: preface + refs + ' is behind ' + base + ' (needs a rebase), so GitHub would refuse a plain merge. Record your approval as ' + who + ' and have the hive rebase it onto ' + base + ', wait for CI, then merge it with your approval on record? You get a toast when it lands or if the rebase conflicts.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve & rebase-merge', danger: true })) ? {} : null; + } return (await stageTrackerAsk(id, 'confirm', { title: 'Approve & merge as maintainer', message: preface + 'Merge ' + refs + ' into ' + base + ' now via hive\'s identity, attributed to ' + who + '? The merge gate parked it for a human because its author is not a trusted merger on this repo; this is you taking that call. The head you see is the head that merges — a push in between makes GitHub refuse.' + stageTrackerDCOCaveat(items), confirmLabel: 'Approve & merge', danger: true })) ? {} : null; } case 'decide:queue-merge': @@ -19097,15 +19133,18 @@

All labels

}; const STAGE_TRACKER_ACTION_WORDS = { adopted: 'adopted', approved: 'approved', recommended: 'recommendation only', closed: 'closed', directed: 'direction recorded', refused: 'refused', 'decided-each': 'decided per PR', - merged: 'merged', 'queued-for-merge': 'queued for merge', + merged: 'merged', 'queued-for-merge': 'queued for merge', [STAGE_TRACKER_ACTION_REBASE_QUEUED]: 'rebase queued, merge to follow', held: 'held', released: 'hold released', rescanned: 'rescanned', 'triage-accepted': 'triage accepted', 'needs-human': 'marked needs-human', rerouted: 'rerouted', [STAGE_TRACKER_ACTION_NOOP]: 'no change', [STAGE_TRACKER_ACTION_NO_EFFECT]: "decided, but it hasn't taken effect", }; - function stageTrackerActingCaption(id) { return STAGE_TRACKER_ACTING_CAPTIONS[stageTrackerActionBase(id)] || 'acting…'; } + function stageTrackerActingCaption(id, item) { + if (id === 'decide:merge-now' && item && stageTrackerNeedsRebase(item)) return 'Rebasing, then merging…'; + return STAGE_TRACKER_ACTING_CAPTIONS[stageTrackerActionBase(id)] || 'acting…'; + } // Pure: the state signature a toast / acting row waits to see change. function stageTrackerItemState(it) { if (!it) return ''; - return String(Number(it.stage) || 0) + '|' + (it.stage_slug || '') + '|' + (it.caption || '') + '|' + (Array.isArray(it.modifiers) ? it.modifiers.slice().sort().join(',') : ''); + return String(Number(it.stage) || 0) + '|' + (it.stage_slug || '') + '|' + (it.caption || '') + '|' + (Array.isArray(it.modifiers) ? it.modifiers.slice().sort().join(',') : '') + (it.rebase_merge && it.rebase_merge.state ? '|rm:' + it.rebase_merge.state : '') + (it.rebase && it.rebase.text ? '|rb:' + it.rebase.text : ''); } function stageTrackerTargetKey(target) { return target && target.number ? stageTrackerItemKey({ repo: target.repo, kind: target.kind === 'pr' ? 'pr' : 'issue', number: target.number }) : ''; @@ -19144,6 +19183,7 @@

All labels

const hiveDecided = !error && (result.rule || result.action === 'recommended' || (result.action === 'adopted' && ctx.id !== 'decide:adopt-now')); if (error) head = stageTrackerActionLabel(ctx.id || '') + ' failed on ' + rowRef + toward; else if (hiveDecided) head = 'Hive decided on ' + rowRef + toward; + else if (result.action === STAGE_TRACKER_ACTION_REBASE_QUEUED || (ctx.id === 'decide:merge-now' && stageTrackerNeedsRebase(item))) head = STAGE_TRACKER_REBASE_MERGE_LABEL + ' on ' + rowRef + toward; else head = stageTrackerActionLabel(ctx.id || '') + ' on ' + rowRef + toward; const word = error ? '' : (STAGE_TRACKER_ACTION_WORDS[result.action] || result.action || ''); // The rule in plain words from the glossary, never the bare slug. @@ -19157,8 +19197,11 @@

All labels

if (hiveDecided && !noop && !noEffect && outcome) { const lead = outcome; outcome = head; head = lead; } const warn = stageTrackerResultWarn(result, item); const posted = Array.isArray(result.posted) ? result.posted.filter(p => typeof p === 'string' && p.trim()).map(p => p.replace(/`/g, '')) : []; - const options = noEffect && Array.isArray(result.options) ? result.options.filter(o => o && o.action && o.label) : []; - return { head, outcome, next: local(result.next || ''), warn, posted: posted.length ? 'Posted: ' + posted.join(' · ') : '', options, why: noEffect ? stageTrackerPlainWords(result.why || 'no-effect', true) : '', type: error ? 'error' : (noEffect ? 'warning' : (noop ? 'info' : 'success')), url: t.url || item.url || '', linkText: 'Open ' + (t.kind === 'pr' ? 'PR' : 'issue') + ' #' + (t.number || item.number) }; + const refused = result.action === 'refused'; + // Options ride a no-effect / refused result, and an approval on a PR + // that needs a rebase ("Rebase, then merge as maintainer"). + const options = (noEffect || refused || result.action === 'approved') && Array.isArray(result.options) ? result.options.filter(o => o && o.action && o.label) : []; + return { head, outcome, next: local(result.next || ''), warn, posted: posted.length ? 'Posted: ' + posted.join(' · ') : '', options, why: noEffect ? stageTrackerPlainWords(result.why || 'no-effect', true) : '', type: error ? 'error' : (noEffect || refused ? 'warning' : (noop ? 'info' : 'success')), url: t.url || item.url || '', linkText: 'Open ' + (t.kind === 'pr' ? 'PR' : 'issue') + ' #' + (t.number || item.number) }; } // Pure: the ⚠ sentinel paragraph a result toast carries. The row's // alert is what the action started from, so it is repeated only while diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 9abe407460..e6ae827ba5 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -1229,6 +1229,15 @@ func (c *Engine) SweepSelfAuthoredAutoMerges(ctx context.Context, opts AutoMerge // prMergeableStateConflicting reads GitHub's conflict flag off a single-PR // GET payload. +// staleNeedsRebaseLabel: prow's needs-rebase label lags GitHub's +// mergeable_state. When GitHub says the branch is merely "behind" (clean +// update), the label must not block the lane — the lane's UpdateBranch is +// exactly what clears it, and before hivecommons/hive#15103 no lane ever +// reached that call under the label. +func staleNeedsRebaseLabel(blocked string, pr *gh.PullRequest) bool { + return blocked == "label:needs-rebase" && strings.EqualFold(strings.TrimSpace(pr.GetMergeableState()), "behind") +} + func prMergeableStateConflicting(pr *gh.PullRequest) bool { state := strings.ToLower(strings.TrimSpace(pr.GetMergeableState())) return state == "dirty" || state == "conflicting" @@ -1741,7 +1750,9 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, } } } - if blocked != "" { + // A needs-rebase label left on a head GitHub now reports merely behind + // is stale: the gate still sees a mergeable PR (hivecommons/hive#15103). + if blocked != "" && !staleNeedsRebaseLabel(blocked, pr) { return AutoMergeSweepEvent{}, blocked, nil } if c.transport.IsExemptLabels(selfLabels) { @@ -2130,7 +2141,7 @@ func (c *Engine) prefilterTrustedAuthorPR(pr *gh.PullRequest, policy TrustedAuth return "draft" } labels := labelNames(pr.Labels) - if blocked := c.labelBlockReason(labels, true); blocked != "" { + if blocked := c.labelBlockReason(labels, true); blocked != "" && !staleNeedsRebaseLabel(blocked, pr) { return blocked } if excluded := policy.excludedLabel(labels); excluded != "" { diff --git a/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go b/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go index cf80f63e5d..e9f15d7934 100644 --- a/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go +++ b/src/pkg/github/automerge/automerge_sweep_trusted_author_test.go @@ -34,6 +34,7 @@ type trustedSweepFixture struct { comments int updates int updateStatus int + labels []string } func newTrustedSweepAPI(t *testing.T, fx *trustedSweepFixture) *httptest.Server { @@ -61,7 +62,7 @@ func newTrustedSweepAPI(t *testing.T, fx *trustedSweepFixture) *httptest.Server "user": map[string]string{"login": author}, "head": map[string]any{"sha": sha, "repo": map[string]string{"full_name": headRepo}}, "base": map[string]any{"repo": map[string]string{"full_name": "acme/widget"}}, - "labels": []map[string]string{}, + "labels": prLabelObjects(fx.labels), } } switch { @@ -192,6 +193,20 @@ func TestTrySweepTrustedAuthorPRFailClosedBranches(t *testing.T) { wantReason: "check-pending", wantUpdates: 1, }, + { + // hivecommons/hive#15103: prow's needs-rebase label lags; when + // GitHub says "behind" the label must not stop the UpdateBranch + // that clears it. + name: "stale needs-rebase label with behind still updates branch", + fx: trustedSweepFixture{mergeableState: "behind", labels: []string{"needs-rebase"}}, + wantReason: "check-pending", + wantUpdates: 1, + }, + { + name: "needs-rebase label with dirty is left to the fixer", + fx: trustedSweepFixture{mergeableState: "dirty", labels: []string{"needs-rebase"}}, + wantReason: "label:needs-rebase", + }, { name: "required checks expected updates branch", fx: trustedSweepFixture{mergeStatus: http.StatusMethodNotAllowed, mergeMessage: `2 of 3 required status checks are expected.`}, @@ -507,3 +522,11 @@ func TestTrustedAuthorSweepRunsReviewGate(t *testing.T) { }) } } + +func prLabelObjects(names []string) []map[string]string { + out := make([]map[string]string, 0, len(names)) + for _, n := range names { + out = append(out, map[string]string{"name": n}) + } + return out +} diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index a9af3ba2ef..b86f233d74 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -278,6 +278,9 @@ func (c *Client) SweepIssueUnparkCommands(ctx context.Context, opts IssueUnparkS maxActions = DefaultIssueUnparkSweepMaxActions } result := &IssueUnparkSweepResult{} + if opts.HumanChangeRequests != nil { + c.ReconcileSelfDecisionChangeRequests(opts.HumanChangeRequests) + } cutoff := time.Now().Add(-unparkCommandScanWindow) for _, repo := range c.getRepos() { diff --git a/src/pkg/github/pr_merge_state.go b/src/pkg/github/pr_merge_state.go new file mode 100644 index 0000000000..3573ce3c91 --- /dev/null +++ b/src/pkg/github/pr_merge_state.go @@ -0,0 +1,138 @@ +package github + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// PRMergeState is a fresh (uncached) read of what the dashboard's +// rebase-then-merge follow-through needs to decide its next move: the head, +// GitHub's mergeability verdict, whether the hive can push to the head, +// and whether CI on the head is red. +type PRMergeState struct { + State string + Merged bool + MergedAt time.Time + HeadSHA string + HeadRef string + BaseRef string + Author string + MergeableState string + FromFork bool + MaintainerCanModify bool + // CIRed is true when a check or status on HeadSHA concluded red. + CIRed bool + // RedChecks names them. + RedChecks []string +} + +// NeedsRebase reports a head GitHub will not merge as it stands: behind +// its base or conflicting with it. "unknown" (GitHub still computing) +// counts as not-needing so a stale read never turns a plain merge into a +// rebase. +func (s PRMergeState) NeedsRebase() bool { + switch strings.ToLower(strings.TrimSpace(s.MergeableState)) { + case "dirty", "behind": + return true + } + return false +} + +// Conflicting is the dirty case: a plain update-branch will not do. +func (s PRMergeState) Conflicting() bool { + return strings.EqualFold(strings.TrimSpace(s.MergeableState), "dirty") +} + +// PushReachable reports whether the hive's token can push to the head. +func (s PRMergeState) PushReachable() bool { + return !s.FromFork || s.MaintainerCanModify +} + +// GetPRMergeState reads the PR fresh (no detail cache: the follow-through +// acts on what it sees) and, when the PR is open, folds in its head's +// check summary. +func (c *Client) GetPRMergeState(ctx context.Context, repo string, number int) (PRMergeState, error) { + if c == nil || c.client == nil { + return PRMergeState{}, ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + pr, _, err := c.client.PullRequests.Get(WithRESTCaller(ctx, "hive:rebase_merge_state"), owner, repoName, number) + if err != nil { + return PRMergeState{}, fmt.Errorf("reading PR %s#%d: %w", repo, number, err) + } + c.storePRDetail(owner+"/"+repoName, number, pr) + st := PRMergeState{ + State: pr.GetState(), Merged: pr.GetMerged() || !pr.GetMergedAt().IsZero(), + HeadSHA: pr.GetHead().GetSHA(), HeadRef: pr.GetHead().GetRef(), BaseRef: prBaseRef(pr), + Author: pr.GetUser().GetLogin(), MergeableState: pr.GetMergeableState(), + MaintainerCanModify: pr.GetMaintainerCanModify(), + } + if !pr.GetMergedAt().IsZero() { + st.MergedAt = pr.GetMergedAt().Time + } + if head, base := pr.GetHead().GetRepo(), pr.GetBase().GetRepo(); head != nil && base != nil && head.GetFullName() != "" && base.GetFullName() != "" { + st.FromFork = !strings.EqualFold(head.GetFullName(), base.GetFullName()) + } + if strings.EqualFold(st.State, "open") && st.HeadSHA != "" { + if sum, err := SummarizeCommitChecks(ctx, c.client, owner, repoName, st.HeadSHA); err == nil && len(sum.Red) > 0 { + st.CIRed = true + st.RedChecks = sum.Red + } + } + return st, nil +} + +// PRConflictCandidates names the files a PR changed that its base also +// changed since their merge base: the files a rebase will have to resolve. +// GitHub does not report conflicting paths, so this is the honest +// approximation from two compares (base...head for the PR's side, +// head...base for what moved under it). Errors are returned; an empty list +// means the compares agree nothing overlaps. +func (c *Client) PRConflictCandidates(ctx context.Context, repo, base, head string) ([]string, error) { + if c == nil || c.client == nil { + return nil, ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + prFiles, err := c.compareFiles(ctx, owner, repoName, base, head) + if err != nil { + return nil, err + } + baseFiles, err := c.compareFiles(ctx, owner, repoName, head, base) + if err != nil { + return nil, err + } + var out []string + for f := range prFiles { + if baseFiles[f] { + out = append(out, f) + } + } + slices.Sort(out) + return out, nil +} + +func (c *Client) compareFiles(ctx context.Context, owner, repo, base, head string) (map[string]bool, error) { + out := map[string]bool{} + opts := &gh.ListOptions{PerPage: 100} + for { + cmp, resp, err := c.client.Repositories.CompareCommits(WithRESTCaller(ctx, "hive:rebase_merge_conflicts"), owner, repo, base, head, opts) + if err != nil { + return nil, fmt.Errorf("comparing %s/%s %s...%s: %w", owner, repo, base, head, err) + } + for _, f := range cmp.Files { + if name := f.GetFilename(); name != "" { + out[name] = true + } + } + if resp == nil || resp.NextPage == 0 || len(cmp.Files) == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} diff --git a/src/pkg/github/pr_unpark_decision.go b/src/pkg/github/pr_unpark_decision.go index f7a48dff35..3ee06ed152 100644 --- a/src/pkg/github/pr_unpark_decision.go +++ b/src/pkg/github/pr_unpark_decision.go @@ -141,6 +141,34 @@ func isHiveSelfDecisionComment(body string) bool { return delegatedecision.IsDelegatedComment(body) } +// ReconcileSelfDecisionChangeRequests is the reconcile pass behind the +// guard above (run at the start of every un-park sweep; idempotent, so +// after the first pass it finds nothing): a changes_requested recorded from a `/hive decision` +// comment the hive itself posted (the delegate's marker in the body, or +// the hive's own login as actor) predates the guard and still blocks the +// head it was meant to advance. It is dismissed with a log line naming the +// PR and head; a store without Dismiss is left alone. Returns what came +// off. +func (c *Client) ReconcileSelfDecisionChangeRequests(store review.HumanChangeRequestStore) []review.HumanChangeRequest { + d, ok := store.(review.HumanChangeRequestDismisser) + if !ok || d == nil { + return nil + } + removed := d.Dismiss(func(r review.HumanChangeRequest) bool { + if r.Source != review.HumanChangeRequestSourceDecision || r.Kind == review.HumanChangeRequestKindApprove { + return false + } + return isHiveSelfDecisionComment(r.Body) || (c != nil && c.IsHiveAuthorLogin(r.Actor)) + }) + if c != nil && c.logger != nil { + for _, r := range removed { + c.logger.Info("dismissed self-inflicted changes_requested: source comment is hive's own /hive decision", + "repo", r.Repo, "number", r.Number, "head", r.HeadSHA, "actor", r.Actor, "comment_id", r.SourceID) + } + } + return removed +} + // prDecisionMode is what a `/hive decision` on a PR asks for. type prDecisionMode string diff --git a/src/pkg/github/pr_unpark_decision_test.go b/src/pkg/github/pr_unpark_decision_test.go index a1d536b96b..ba68ea151d 100644 --- a/src/pkg/github/pr_unpark_decision_test.go +++ b/src/pkg/github/pr_unpark_decision_test.go @@ -581,3 +581,56 @@ func TestDecisionApprovalFirstWord(t *testing.T) { } } } + +// A changes_requested recorded from the hive's own `/hive decision` comment +// (before the self-decision guard existed) is dismissed on the next sweep; +// a reviewer's real decision and an approval are left standing +// (hivecommons/hive#14822). +func TestReconcileSelfDecisionChangeRequestsDismissesHiveOwnDecisions(t *testing.T) { + c, _ := newUnparkPRClient(t, nil, nil) + store := review.NewHumanChangeRequests("") + self := review.HumanChangeRequest{Repo: "org/repo", Number: 14822, HeadSHA: liveDecisionHead, Source: review.HumanChangeRequestSourceDecision, SourceID: 1, + Actor: "clubanderson", Body: delegatedecision.MarkerPrefix + " rule=contributor-offline -->\n/hive decision supersede now", Kind: review.HumanChangeRequestKindChanges} + byBot := review.HumanChangeRequest{Repo: "org/repo", Number: 2, HeadSHA: "aaaa", Source: review.HumanChangeRequestSourceDecision, SourceID: 2, Actor: "hive[bot]", Body: "/hive decision rework", Kind: review.HumanChangeRequestKindChanges} + human := review.HumanChangeRequest{Repo: "org/repo", Number: 3, HeadSHA: "bbbb", Source: review.HumanChangeRequestSourceDecision, SourceID: 3, Actor: "clubanderson", Body: "/hive decision split the PR", Kind: review.HumanChangeRequestKindChanges} + reviewReq := review.HumanChangeRequest{Repo: "org/repo", Number: 4, HeadSHA: "cccc", Source: review.HumanChangeRequestSourceReview, SourceID: 4, Actor: "hive[bot]", Body: delegatedecision.MarkerPrefix + " -->", Kind: review.HumanChangeRequestKindChanges} + approve := review.HumanChangeRequest{Repo: "org/repo", Number: 5, HeadSHA: "dddd", Source: review.HumanChangeRequestSourceDecision, SourceID: 5, Actor: "hive[bot]", Body: "/hive approve", Kind: review.HumanChangeRequestKindApprove} + for _, r := range []review.HumanChangeRequest{self, byBot, human, reviewReq, approve} { + if err := store.Record(r); err != nil { + t.Fatal(err) + } + } + removed := c.ReconcileSelfDecisionChangeRequests(store) + if len(removed) != 2 { + t.Fatalf("removed %d, want 2: %+v", len(removed), removed) + } + if _, ok := store.For("org/repo", 14822, liveDecisionHead); ok { + t.Fatal("self-inflicted decision still recorded") + } + if _, ok := store.For("org/repo", 2, "aaaa"); ok { + t.Fatal("hive-login decision still recorded") + } + for _, keep := range []review.HumanChangeRequest{human, reviewReq, approve} { + if _, ok := store.For(keep.Repo, keep.Number, keep.HeadSHA); !ok { + t.Fatalf("%s#%d dismissed, want kept", keep.Repo, keep.Number) + } + } + // Idempotent: the second pass finds nothing. + if again := c.ReconcileSelfDecisionChangeRequests(store); len(again) != 0 { + t.Fatalf("second pass removed %+v", again) + } + if got := c.ReconcileSelfDecisionChangeRequests(reviewOnlyStore{inner: store}); got != nil { + t.Fatalf("store without Dismiss: %+v", got) + } +} + +// reviewOnlyStore hides Dismiss. +type reviewOnlyStore struct{ inner *review.HumanChangeRequests } + +func (s reviewOnlyStore) Record(r review.HumanChangeRequest) error { return s.inner.Record(r) } +func (s reviewOnlyStore) For(repo string, n int, head string) (review.HumanChangeRequest, bool) { + return s.inner.For(repo, n, head) +} +func (s reviewOnlyStore) Forget(repo string, n int, source string, sourceID int64) error { + return s.inner.Forget(repo, n, source, sourceID) +} diff --git a/src/pkg/rebasemerge/attempts.go b/src/pkg/rebasemerge/attempts.go new file mode 100644 index 0000000000..6568b20688 --- /dev/null +++ b/src/pkg/rebasemerge/attempts.go @@ -0,0 +1,194 @@ +package rebasemerge + +import ( + "encoding/json" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +// MaxRebaseAttempts is the loop guard on the autonomous rebase-resolve +// task: a PR gets this many fixer rebases per conflict episode. Each +// attempt is a new head the fixer pushed that GitHub still reports dirty; +// past the cap the hive stops re-kicking and the row asks for a person +// (hivecommons/hive#14822, #15103). +const MaxRebaseAttempts = 2 + +// AttemptsPath is where the per-PR attempt ledger lives in the pod. +var AttemptsPath = "/data/rebase-attempts.json" + +// Attempt is one PR's conflict episode: the dirty heads seen, oldest +// first. The first dirty head is attempt 1 (the fixer's first task); a +// pushed head that is still dirty is the next attempt; past +// MaxRebaseAttempts dirty heads the episode is exhausted. A PR that stops +// conflicting ends its episode (Clear) so a later conflict starts fresh. +type Attempt struct { + Repo string `json:"repo"` + Number int `json:"number"` + Heads []string `json:"heads"` + // RequestedBy is the operator whose approval (or merge-now) asked for + // the rebase from the dashboard, so the fixer router lists the PR even + // when neither the hive nor a trusted author opened it. + RequestedBy string `json:"requested_by,omitempty"` + StartedAt time.Time `json:"started_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// Count is the attempt number the current head represents (1-based). +func (a Attempt) Count() int { return len(a.Heads) } + +// Exhausted: more dirty heads than the cap allows rebases. +func (a Attempt) Exhausted() bool { return len(a.Heads) > MaxRebaseAttempts } + +// Head is the newest dirty head seen. +func (a Attempt) Head() string { + if len(a.Heads) == 0 { + return "" + } + return a.Heads[len(a.Heads)-1] +} + +// Attempts is the persisted attempt ledger. +type Attempts struct { + mu sync.Mutex + path string + loaded bool + items map[string]Attempt +} + +// NewAttempts returns a ledger at path ("" keeps it in memory). +func NewAttempts(path string) *Attempts { + return &Attempts{path: path, items: map[string]Attempt{}} +} + +var ( + sharedAttemptsOnce sync.Once + sharedAttempts *Attempts +) + +// SharedAttempts is the process-wide ledger at AttemptsPath. +func SharedAttempts() *Attempts { + sharedAttemptsOnce.Do(func() { sharedAttempts = NewAttempts(AttemptsPath) }) + return sharedAttempts +} + +func (s *Attempts) load() { + if s.loaded { + return + } + s.loaded = true + if s.path == "" { + return + } + data, err := os.ReadFile(s.path) + if err != nil { + return + } + var items map[string]Attempt + if json.Unmarshal(data, &items) == nil && items != nil { + s.items = items + } +} + +func (s *Attempts) persist() { + if s.path == "" { + return + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return + } + data, err := json.MarshalIndent(s.items, "", " ") + if err != nil { + return + } + tmp := s.path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return + } + _ = os.Rename(tmp, s.path) +} + +// Observe records that head is conflicting on repo#number now and returns +// the episode. The same head observed again is the same attempt; a new +// head is the next one. +func (s *Attempts) Observe(repo string, number int, head string, now time.Time) Attempt { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + key := Key(repo, number) + a, ok := s.items[key] + head = strings.TrimSpace(head) + if !ok { + a = Attempt{Repo: repo, Number: number, StartedAt: now} + } + if head != "" && (len(a.Heads) == 0 || a.Heads[len(a.Heads)-1] != head) { + a.Heads = append(a.Heads, head) + a.UpdatedAt = now + s.items[key] = a + s.persist() + } else if !ok { + a.UpdatedAt = now + s.items[key] = a + s.persist() + } + return a +} + +// Request opens (or joins) the episode for repo#number on behalf of an +// operator: the dashboard's approve / merge-now on a conflicting PR asks +// the fixer to rebase it on the next router pass. +func (s *Attempts) Request(repo string, number int, head, actor string, now time.Time) Attempt { + a := s.Observe(repo, number, head, now) + actor = strings.TrimSpace(actor) + if actor == "" || a.RequestedBy == actor { + return a + } + s.mu.Lock() + defer s.mu.Unlock() + key := Key(repo, number) + a = s.items[key] + a.RequestedBy = actor + a.UpdatedAt = now + s.items[key] = a + s.persist() + return a +} + +// Get returns the episode for repo#number, if one is open. +func (s *Attempts) Get(repo string, number int) (Attempt, bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + a, ok := s.items[Key(repo, number)] + return a, ok +} + +// Clear ends the episode: the PR is no longer conflicting (rebased, +// merged or closed). +func (s *Attempts) Clear(repo string, number int) { + s.mu.Lock() + defer s.mu.Unlock() + s.load() + key := Key(repo, number) + if _, ok := s.items[key]; !ok { + return + } + delete(s.items, key) + s.persist() +} + +// AttemptText is the row pill: "Rebasing · attempt 1/2", or +// "Rebase failed · 2/2 — needs a person" once exhausted. +func AttemptText(a Attempt) string { + if a.Exhausted() { + return "Rebase failed · " + strconv.Itoa(MaxRebaseAttempts) + "/" + strconv.Itoa(MaxRebaseAttempts) + " — needs a person" + } + n := a.Count() + if n < 1 { + n = 1 + } + return "Rebasing · attempt " + strconv.Itoa(n) + "/" + strconv.Itoa(MaxRebaseAttempts) +} diff --git a/src/pkg/rebasemerge/rebasemerge.go b/src/pkg/rebasemerge/rebasemerge.go new file mode 100644 index 0000000000..af1f431769 --- /dev/null +++ b/src/pkg/rebasemerge/rebasemerge.go @@ -0,0 +1,467 @@ +// Package rebasemerge is the "Rebase, then merge as maintainer" follow-through +// (hivecommons/hive: #14822 sat 14h at 085 behind v5 with no lane owning the +// rebase, and "Approve & merge as maintainer" on a dirty PR would have been a +// GitHub 405). An operator's merge-now on a PR that is behind or conflicting +// records the approval first, arms a follow-through here, and the hive does +// the rest: a fixer rebases the branch (the merge-eligibility router admits +// an armed PR to its conflict route whoever authored it), the dashboard's +// ticker watches the new head, merges it on green with the approval on +// record, or fails the action with the conflicting files and the two ways +// out (adopt into a fresh branch / close as superseded). +// +// The state machine is pure (Advance) so it can be tested without GitHub; +// the store is shared between the dashboard (arms, drives) and cmd/hive +// (routes the rebase). +package rebasemerge + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "time" +) + +// StatePath is where the shared store persists; /data is the hive's volume. +var StatePath = "/data/rebase-merge-followups.json" + +// States of a follow-through, in order. +const ( + // StateApproved: the operator's approval is on record; the rebase kick + // has not been observed as a new head yet. + StateApproved = "approved" + // StateRebasing: a fixer owns the rebase (the PR is in the conflict + // route); still the head the operator approved. + StateRebasing = "rebasing" + // StateCIPending: a new head landed (the rebase); waiting for GitHub to + // report it clean. + StateCIPending = "ci-pending" + StateMerged = "merged" + StateFailed = "failed" +) + +// Steps recorded on the follow-through (and mirrored into the operator +// ledger's followed[]). +const ( + StepApprovalRecorded = "approval-recorded" + StepRebaseKicked = "rebase-kicked" + StepRebased = "rebased" + StepStillConflicting = "still-conflicting" + StepCIGreen = "ci-green" + StepMerged = "merged" + StepFailed = "failed" +) + +// Failure reasons. +const ( + FailConflict = "rebase-conflict" + FailCIRed = "ci-red" + FailTimeout = "rebase-timeout" + FailClosed = "pr-closed" + FailNotReachable = "head-not-pushable" +) + +// Options the failed outcome offers (decision action ids the SPA knows). +const ( + OptionAdoptFresh = "decide:adopt" + OptionCloseSuperseded = "decide:close-superseded" + OptionAdoptFreshLabel = "Adopt into fresh branch" + OptionCloseSupersLabel = "Close as superseded" +) + +// Default timing. RebaseDeadline bounds how long a kicked rebase may sit +// without a new head; CIDeadline bounds how long the rebased head may sit +// not-clean before the follow-through gives up. +const ( + DefaultRebaseDeadline = 2 * time.Hour + DefaultCIDeadline = 3 * time.Hour +) + +// Step is one recorded move of the follow-through. +type Step struct { + At time.Time `json:"at"` + Step string `json:"step"` + Detail string `json:"detail,omitempty"` +} + +// FollowThrough is one armed rebase-then-merge. +type FollowThrough struct { + Repo string `json:"repo"` + Number int `json:"number"` + // Actor is the operator whose approval is on record; Base the branch + // the PR is rebased onto. + Actor string `json:"actor"` + Base string `json:"base,omitempty"` + // ApprovedHead is the head the operator approved; RebasedHead the head + // the rebase produced (set once observed). HiveAuthored says whether + // the PR is the hive's own (the self lane rebases) or a contributor's + // (push-reachable fixer). + ApprovedHead string `json:"approved_head"` + RebasedHead string `json:"rebased_head,omitempty"` + HiveAuthored bool `json:"hive_authored,omitempty"` + State string `json:"state"` + ArmedAt time.Time `json:"armed_at"` + UpdatedAt time.Time `json:"updated_at"` + Steps []Step `json:"steps,omitempty"` + // FailReason / ConflictFiles / Options describe a failed outcome. + FailReason string `json:"fail_reason,omitempty"` + ConflictFiles []string `json:"conflict_files,omitempty"` + Options []string `json:"options,omitempty"` + MergeSHA string `json:"merge_sha,omitempty"` +} + +// Live reports whether the follow-through still wants the hive's work. +func (f FollowThrough) Live() bool { + return f.State == StateApproved || f.State == StateRebasing || f.State == StateCIPending +} + +// Observation is what one poll of GitHub saw. +type Observation struct { + Now time.Time + Head string + State string // open / closed + Merged bool + MergeableState string // clean / unstable / blocked / dirty / behind / unknown + // CIRed is true when a required check on Head failed. + CIRed bool + // ConflictFiles are the files changed on both sides since the merge + // base, when the poller worked them out. + ConflictFiles []string + // RebaseAttempt / RebaseExhausted mirror the fixer loop guard + // (Attempts): which rebase-resolve attempt the current dirty head is, + // and whether the hive has run out. A rebased head that is still dirty + // goes back to rebasing while attempts remain; once exhausted it fails + // with the conflict for a person. + RebaseAttempt int + RebaseExhausted bool +} + +// Action is what the driver must do after Advance. +type Action string + +const ( + ActionNone Action = "" + ActionMerge Action = "merge" + ActionFail Action = "fail" +) + +// Deadlines bounds the follow-through. +type Deadlines struct { + Rebase time.Duration + CI time.Duration +} + +func (d Deadlines) orDefault() Deadlines { + if d.Rebase <= 0 { + d.Rebase = DefaultRebaseDeadline + } + if d.CI <= 0 { + d.CI = DefaultCIDeadline + } + return d +} + +func (f *FollowThrough) step(now time.Time, step, detail string) { + f.Steps = append(f.Steps, Step{At: now, Step: step, Detail: detail}) + f.UpdatedAt = now +} + +// rebaseSince is when the current rebase wait started: arming, or the +// last time a rebased head came back still conflicting. +func (f *FollowThrough) rebaseSince() time.Time { + since := f.ArmedAt + for _, st := range f.Steps { + if st.Step == StepStillConflicting && st.At.After(since) { + since = st.At + } + } + return since +} + +func (f *FollowThrough) fail(now time.Time, reason string, files []string) { + f.State = StateFailed + f.FailReason = reason + f.ConflictFiles = slices.Clone(files) + f.Options = []string{OptionAdoptFresh, OptionCloseSuperseded} + f.step(now, StepFailed, reason) +} + +// Arm builds a fresh follow-through with the approval recorded as its first +// step: the approval is the durable record, everything after is the hive's. +func Arm(repo string, number int, actor, base, head string, hiveAuthored bool, now time.Time) FollowThrough { + f := FollowThrough{Repo: repo, Number: number, Actor: actor, Base: base, ApprovedHead: head, HiveAuthored: hiveAuthored, State: StateApproved, ArmedAt: now, UpdatedAt: now} + f.step(now, StepApprovalRecorded, "approved by @"+actor+" on "+short(head)) + return f +} + +// Kicked records that the rebase is in a fixer's hands. +func (f *FollowThrough) Kicked(now time.Time, how string) { + if f.State != StateApproved { + return + } + f.State = StateRebasing + f.step(now, StepRebaseKicked, how) +} + +// Advance folds one observation into the follow-through and says what the +// driver does next. It is pure: no GitHub calls, no clock reads. +// +// approved/rebasing + new head → ci-pending (step rebased) +// ci-pending + clean → merge (step ci-green) +// any live + dirty past rebase deadline → fail rebase-conflict (files) +// any live + CI red on the rebased head → fail ci-red +// ci-pending past CI deadline → fail rebase-timeout +// closed / merged elsewhere → merged | failed pr-closed +func Advance(f *FollowThrough, obs Observation, d Deadlines) Action { + if f == nil || !f.Live() { + return ActionNone + } + d = d.orDefault() + now := obs.Now + if obs.Merged { + f.State = StateMerged + f.step(now, StepMerged, "merged outside the follow-through") + return ActionNone + } + if obs.State != "" && !strings.EqualFold(obs.State, "open") { + f.fail(now, FailClosed, nil) + return ActionFail + } + head := strings.TrimSpace(obs.Head) + if head != "" && head != f.ApprovedHead && head != f.RebasedHead { + f.RebasedHead = head + f.State = StateCIPending + f.step(now, StepRebased, "new head "+short(head)+" onto "+f.Base) + } + ms := strings.ToLower(strings.TrimSpace(obs.MergeableState)) + switch f.State { + case StateApproved, StateRebasing: + if ms == "clean" { + // The approved head became mergeable without a rebase (the + // label was stale, or base moved back under it). + f.step(now, StepCIGreen, "GitHub reports "+short(f.ApprovedHead)+" clean") + return ActionMerge + } + if ms == "dirty" && (obs.RebaseExhausted || now.Sub(f.rebaseSince()) >= d.Rebase) { + f.fail(now, FailConflict, obs.ConflictFiles) + return ActionFail + } + if ms != "dirty" && now.Sub(f.rebaseSince()) >= d.Rebase { + f.fail(now, FailTimeout, nil) + return ActionFail + } + case StateCIPending: + if obs.CIRed { + f.fail(now, FailCIRed, nil) + return ActionFail + } + if ms == "dirty" { + // The base moved again under the rebased head (or the fixer's + // resolution did not take). While the loop guard allows it the + // fixer gets another go; past it the conflict is a person's. + if obs.RebaseExhausted { + f.fail(now, FailConflict, obs.ConflictFiles) + return ActionFail + } + f.State = StateRebasing + f.step(now, StepStillConflicting, "head "+short(f.RebasedHead)+" still conflicting — rebase attempt "+strconv.Itoa(max(obs.RebaseAttempt, 1))+"/"+strconv.Itoa(MaxRebaseAttempts)) + return ActionNone + } + if ms == "clean" { + f.step(now, StepCIGreen, "GitHub reports "+short(f.RebasedHead)+" clean") + return ActionMerge + } + if now.Sub(f.UpdatedAt) >= d.CI { + f.fail(now, FailTimeout, nil) + return ActionFail + } + } + return ActionNone +} + +// Merged records the merge the driver performed. +func (f *FollowThrough) Merged(now time.Time, sha string) { + f.State = StateMerged + f.MergeSHA = sha + f.step(now, StepMerged, "merged "+short(sha)+" with @"+f.Actor+"'s approval on record") +} + +// FailNow fails the follow-through from the driver (a merge call that GitHub +// refused, a head nobody can push). +func (f *FollowThrough) FailNow(now time.Time, reason string, files []string) { + f.fail(now, reason, files) +} + +// FailureText is the one-line toast for a failed follow-through. +func (f FollowThrough) FailureText() string { + switch f.FailReason { + case FailConflict: + msg := fmt.Sprintf("Rebase of #%d onto %s conflicts", f.Number, nonEmpty(f.Base, "its base")) + if len(f.ConflictFiles) > 0 { + msg += " in " + strings.Join(f.ConflictFiles, ", ") + } + return msg + "." + case FailCIRed: + return fmt.Sprintf("CI went red on the rebased head of #%d; nothing merged.", f.Number) + case FailTimeout: + return fmt.Sprintf("The rebase of #%d did not land in time; nothing merged.", f.Number) + case FailClosed: + return fmt.Sprintf("#%d was closed before the hive could merge it.", f.Number) + case FailNotReachable: + return fmt.Sprintf("The hive cannot push to #%d's head (fork without maintainer edits).", f.Number) + } + return fmt.Sprintf("Rebase-then-merge of #%d failed: %s.", f.Number, f.FailReason) +} + +// Store is the persisted set of follow-throughs keyed by repo#number. +type Store struct { + mu sync.Mutex + path string + loaded bool + items map[string]FollowThrough +} + +// NewStore returns a store at path ("" keeps it in memory). +func NewStore(path string) *Store { + return &Store{path: path, items: map[string]FollowThrough{}} +} + +var ( + sharedOnce sync.Once + shared *Store +) + +// Shared is the process-wide store at StatePath. +func Shared() *Store { + sharedOnce.Do(func() { shared = NewStore(StatePath) }) + return shared +} + +// Key is the store key for repo#number. +func Key(repo string, number int) string { + return strings.ToLower(strings.TrimSpace(repo)) + "#" + strconv.Itoa(number) +} + +func (s *Store) load() { + if s.loaded { + return + } + s.loaded = true + if s.path == "" { + return + } + data, err := os.ReadFile(s.path) + if err != nil { + return + } + var items map[string]FollowThrough + if json.Unmarshal(data, &items) == nil && items != nil { + s.items = items + } +} + +func (s *Store) persist() error { + if s.path == "" { + return nil + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + return err + } + data, err := json.MarshalIndent(s.items, "", " ") + if err != nil { + return err + } + tmp := s.path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, s.path) +} + +// ErrAlreadyArmed is returned by Put for a live follow-through on the key. +var ErrAlreadyArmed = errors.New("rebase-then-merge already armed") + +// Put stores f, refusing to replace a live follow-through on the same PR. +func (s *Store) Put(f FollowThrough) error { + if s == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + key := Key(f.Repo, f.Number) + if prev, ok := s.items[key]; ok && prev.Live() && prev.ArmedAt != f.ArmedAt { + return ErrAlreadyArmed + } + s.items[key] = f + return s.persist() +} + +// Update replaces f unconditionally (the driver advancing it). +func (s *Store) Update(f FollowThrough) error { + if s == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + s.items[Key(f.Repo, f.Number)] = f + return s.persist() +} + +// Get returns the follow-through on repo#number. +func (s *Store) Get(repo string, number int) (FollowThrough, bool) { + if s == nil { + return FollowThrough{}, false + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + f, ok := s.items[Key(repo, number)] + return f, ok +} + +// Armed reports a live follow-through on repo#number: the hive owns this +// PR's rebase whoever authored it. +func (s *Store) Armed(repo string, number int) bool { + f, ok := s.Get(repo, number) + return ok && f.Live() +} + +// Live lists every live follow-through, oldest armed first. +func (s *Store) Live() []FollowThrough { + if s == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + var out []FollowThrough + for _, f := range s.items { + if f.Live() { + out = append(out, f) + } + } + slices.SortFunc(out, func(a, b FollowThrough) int { return a.ArmedAt.Compare(b.ArmedAt) }) + return out +} + +func short(sha string) string { + sha = strings.TrimSpace(sha) + if len(sha) > 7 { + return sha[:7] + } + return sha +} + +func nonEmpty(s, fallback string) string { + if strings.TrimSpace(s) == "" { + return fallback + } + return s +} diff --git a/src/pkg/rebasemerge/rebasemerge_test.go b/src/pkg/rebasemerge/rebasemerge_test.go new file mode 100644 index 0000000000..874184cbb9 --- /dev/null +++ b/src/pkg/rebasemerge/rebasemerge_test.go @@ -0,0 +1,210 @@ +package rebasemerge + +import ( + "path/filepath" + "testing" + "time" +) + +func TestArmRecordsApprovalFirst(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("hivecommons/hive", 14822, "clubanderson", "v5", "b0f5f80aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false, now) + if f.State != StateApproved || !f.Live() { + t.Fatalf("state=%q live=%v, want approved/live", f.State, f.Live()) + } + if len(f.Steps) != 1 || f.Steps[0].Step != StepApprovalRecorded || f.Steps[0].Detail != "approved by @clubanderson on b0f5f80" { + t.Fatalf("first step = %+v, want approval-recorded", f.Steps) + } + f.Kicked(now.Add(time.Second), "fixer") + if f.State != StateRebasing || f.Steps[1].Step != StepRebaseKicked { + t.Fatalf("after kick: %+v", f) + } +} + +func TestAdvanceGreenMerges(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 1, "op", "v5", "aaaa111", true, now) + f.Kicked(now, "update-branch") + // Still the approved head, dirty, inside the deadline: wait. + if a := Advance(&f, Observation{Now: now.Add(time.Minute), Head: "aaaa111", State: "open", MergeableState: "dirty"}, Deadlines{}); a != ActionNone || f.State != StateRebasing { + t.Fatalf("waiting: action=%q state=%q", a, f.State) + } + // The rebase lands: new head, CI pending. + if a := Advance(&f, Observation{Now: now.Add(2 * time.Minute), Head: "bbbb222", State: "open", MergeableState: "blocked"}, Deadlines{}); a != ActionNone || f.State != StateCIPending || f.RebasedHead != "bbbb222" { + t.Fatalf("rebased: action=%q state=%q head=%q", a, f.State, f.RebasedHead) + } + // Green → merge. + if a := Advance(&f, Observation{Now: now.Add(10 * time.Minute), Head: "bbbb222", State: "open", MergeableState: "clean"}, Deadlines{}); a != ActionMerge { + t.Fatalf("clean: action=%q", a) + } + f.Merged(now.Add(11*time.Minute), "cccc333") + if f.State != StateMerged || f.Live() { + t.Fatalf("merged: %+v", f) + } + want := []string{StepApprovalRecorded, StepRebaseKicked, StepRebased, StepCIGreen, StepMerged} + if len(f.Steps) != len(want) { + t.Fatalf("steps=%+v", f.Steps) + } + for i, s := range want { + if f.Steps[i].Step != s { + t.Fatalf("step %d = %q, want %q", i, f.Steps[i].Step, s) + } + } +} + +func TestAdvanceConflictFailsWithFilesAndOptions(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 2, "op", "v5", "aaaa111", false, now) + f.Kicked(now, "fixer") + obs := Observation{Now: now.Add(DefaultRebaseDeadline), Head: "aaaa111", State: "open", MergeableState: "dirty", ConflictFiles: []string{"a.go", "b.go"}} + if a := Advance(&f, obs, Deadlines{}); a != ActionFail { + t.Fatalf("action=%q", a) + } + if f.State != StateFailed || f.FailReason != FailConflict || len(f.ConflictFiles) != 2 { + t.Fatalf("failed: %+v", f) + } + if len(f.Options) != 2 || f.Options[0] != OptionAdoptFresh || f.Options[1] != OptionCloseSuperseded { + t.Fatalf("options=%v", f.Options) + } + if got := f.FailureText(); got != "Rebase of #2 onto v5 conflicts in a.go, b.go." { + t.Fatalf("text=%q", got) + } + // A rebased head that goes dirty again fails as a conflict once the + // fixer's attempts are exhausted. + g := Arm("o/r", 3, "op", "v5", "aaaa111", false, now) + Advance(&g, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "blocked"}, Deadlines{}) + if a := Advance(&g, Observation{Now: now.Add(2 * time.Minute), Head: "bbbb222", State: "open", MergeableState: "dirty", RebaseExhausted: true}, Deadlines{}); a != ActionFail || g.FailReason != FailConflict { + t.Fatalf("re-dirty: action=%q reason=%q", a, g.FailReason) + } +} + +// The loop guard inside the follow-through: a rebased head still dirty +// goes back to rebasing while attempts remain (and the rebase clock +// restarts), then fails for a person when the guard says exhausted. +func TestAdvanceStillConflictingRetriesWithinLoopGuard(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 6, "op", "v5", "aaaa111", true, now) + f.Kicked(now, "scanner") + Advance(&f, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "unknown"}, Deadlines{}) + if f.State != StateCIPending { + t.Fatalf("state after push = %q", f.State) + } + a := Advance(&f, Observation{Now: now.Add(2 * time.Minute), Head: "bbbb222", State: "open", MergeableState: "dirty", RebaseAttempt: 2}, Deadlines{}) + if a != ActionNone || f.State != StateRebasing { + t.Fatalf("still dirty with attempts left: action=%q state=%q", a, f.State) + } + last := f.Steps[len(f.Steps)-1] + if last.Step != StepStillConflicting || last.Detail != "head bbbb222 still conflicting — rebase attempt 2/2" { + t.Fatalf("step = %+v", last) + } + // The rebase deadline counts from the retry, not from arming. + at := now.Add(2*time.Minute + DefaultRebaseDeadline - time.Second) + if a := Advance(&f, Observation{Now: at, Head: "bbbb222", State: "open", MergeableState: "dirty", RebaseAttempt: 2}, Deadlines{}); a != ActionNone || f.State != StateRebasing { + t.Fatalf("within the restarted deadline: action=%q state=%q", a, f.State) + } + // Second fixer head lands and is clean: merge. + Advance(&f, Observation{Now: at.Add(time.Second), Head: "cccc333", State: "open", MergeableState: "blocked"}, Deadlines{}) + if a := Advance(&f, Observation{Now: at.Add(2 * time.Second), Head: "cccc333", State: "open", MergeableState: "clean"}, Deadlines{}); a != ActionMerge { + t.Fatalf("clean rebased head: action=%q", a) + } + // Exhausted while waiting in rebasing fails at once with the files. + g := Arm("o/r", 7, "op", "v5", "aaaa111", true, now) + if a := Advance(&g, Observation{Now: now.Add(time.Minute), Head: "aaaa111", State: "open", MergeableState: "dirty", RebaseExhausted: true, ConflictFiles: []string{"x.go"}}, Deadlines{}); a != ActionFail || g.FailReason != FailConflict || len(g.ConflictFiles) != 1 { + t.Fatalf("exhausted: action=%q %+v", a, g) + } +} + +func TestAdvanceCIRedTimeoutAndClosed(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 4, "op", "v5", "aaaa111", true, now) + Advance(&f, Observation{Now: now, Head: "bbbb222", State: "open", MergeableState: "unstable"}, Deadlines{}) + if a := Advance(&f, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "unstable", CIRed: true}, Deadlines{}); a != ActionFail || f.FailReason != FailCIRed { + t.Fatalf("ci red: action=%q reason=%q", a, f.FailReason) + } + g := Arm("o/r", 5, "op", "v5", "aaaa111", true, now) + Advance(&g, Observation{Now: now, Head: "bbbb222", State: "open", MergeableState: "blocked"}, Deadlines{}) + if a := Advance(&g, Observation{Now: now.Add(DefaultCIDeadline), Head: "bbbb222", State: "open", MergeableState: "blocked"}, Deadlines{}); a != ActionFail || g.FailReason != FailTimeout { + t.Fatalf("timeout: action=%q reason=%q", a, g.FailReason) + } + h := Arm("o/r", 6, "op", "v5", "aaaa111", true, now) + if a := Advance(&h, Observation{Now: now, Head: "aaaa111", State: "closed"}, Deadlines{}); a != ActionFail || h.FailReason != FailClosed { + t.Fatalf("closed: action=%q reason=%q", a, h.FailReason) + } + m := Arm("o/r", 7, "op", "v5", "aaaa111", true, now) + if a := Advance(&m, Observation{Now: now, Head: "aaaa111", State: "closed", Merged: true}, Deadlines{}); a != ActionNone || m.State != StateMerged { + t.Fatalf("merged elsewhere: action=%q state=%q", a, m.State) + } + // A settled follow-through ignores further observations. + if a := Advance(&m, Observation{Now: now, Head: "zzz", State: "open", MergeableState: "clean"}, Deadlines{}); a != ActionNone { + t.Fatalf("settled: action=%q", a) + } +} + +func TestAdvanceCleanWithoutRebaseMerges(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 8, "op", "v5", "aaaa111", true, now) + if a := Advance(&f, Observation{Now: now, Head: "aaaa111", State: "open", MergeableState: "clean"}, Deadlines{}); a != ActionMerge { + t.Fatalf("stale needs-rebase: action=%q", a) + } +} + +func TestStorePersistsAndRefusesDoubleArm(t *testing.T) { + path := filepath.Join(t.TempDir(), "f.json") + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + st := NewStore(path) + f := Arm("O/R", 9, "op", "v5", "aaaa111", true, now) + if err := st.Put(f); err != nil { + t.Fatal(err) + } + if !st.Armed("o/r", 9) { + t.Fatal("not armed after Put") + } + if err := st.Put(Arm("o/r", 9, "other", "v5", "aaaa111", true, now.Add(time.Minute))); err != ErrAlreadyArmed { + t.Fatalf("double arm err=%v", err) + } + f.Merged(now.Add(time.Hour), "cccc") + if err := st.Update(f); err != nil { + t.Fatal(err) + } + st2 := NewStore(path) + got, ok := st2.Get("o/r", 9) + if !ok || got.State != StateMerged || st2.Armed("o/r", 9) || len(st2.Live()) != 0 { + t.Fatalf("reloaded: ok=%v %+v live=%d", ok, got, len(st2.Live())) + } + // A settled record may be re-armed. + if err := st2.Put(Arm("o/r", 9, "op", "v5", "dddd", true, now.Add(2*time.Hour))); err != nil { + t.Fatalf("re-arm: %v", err) + } +} + +// The loop guard: the first dirty head is attempt 1, each new dirty head +// the next, the third is exhausted; a PR that stops conflicting starts +// over; the ledger survives a reload. +func TestAttemptsLoopGuard(t *testing.T) { + path := filepath.Join(t.TempDir(), "attempts.json") + s := NewAttempts(path) + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + a := s.Observe("o/r", 1, "aaa", now) + if a.Count() != 1 || a.Exhausted() || AttemptText(a) != "Rebasing · attempt 1/2" { + t.Fatalf("first head: %+v %q", a, AttemptText(a)) + } + if a = s.Observe("o/r", 1, "aaa", now.Add(time.Minute)); a.Count() != 1 { + t.Fatalf("same head is the same attempt: %+v", a) + } + if a = s.Observe("o/r", 1, "bbb", now.Add(2*time.Minute)); a.Count() != 2 || a.Exhausted() || AttemptText(a) != "Rebasing · attempt 2/2" { + t.Fatalf("second head: %+v", a) + } + if a = s.Observe("o/r", 1, "ccc", now.Add(3*time.Minute)); !a.Exhausted() || AttemptText(a) != "Rebase failed · 2/2 — needs a person" || a.Head() != "ccc" { + t.Fatalf("third head: %+v %q", a, AttemptText(a)) + } + if got, ok := NewAttempts(path).Get("o/r", 1); !ok || got.Count() != 3 { + t.Fatalf("reload: %+v ok=%v", got, ok) + } + s.Clear("o/r", 1) + if _, ok := s.Get("o/r", 1); ok { + t.Fatal("cleared episode still present") + } + if a = s.Observe("o/r", 1, "ddd", now.Add(time.Hour)); a.Count() != 1 { + t.Fatalf("a new episode starts at 1: %+v", a) + } +} diff --git a/src/pkg/review/human_change_request.go b/src/pkg/review/human_change_request.go index 2427b3f918..a09835932a 100644 --- a/src/pkg/review/human_change_request.go +++ b/src/pkg/review/human_change_request.go @@ -277,6 +277,41 @@ func (s *HumanChangeRequests) Lookup(repo string, number int, source string, sou return HumanChangeRequest{}, false } +// Dismiss removes every request match reports true for and returns the +// removed entries (nil when none). It is the one-time reconcile's lever: +// a changes_requested whose source is the hive's own `/hive decision` +// comment (recorded before the self-decision guard existed, +// hivecommons/hive#14822) comes off the head it was blocking. +func (s *HumanChangeRequests) Dismiss(match func(HumanChangeRequest) bool) []HumanChangeRequest { + if s == nil || match == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + s.load() + var removed []HumanChangeRequest + kept := s.items[:0] + for _, item := range s.items { + if match(item) { + removed = append(removed, item) + continue + } + kept = append(kept, item) + } + if len(removed) == 0 { + return nil + } + s.items = kept + _ = s.persist() + return removed +} + +// HumanChangeRequestDismisser is the optional store capability the +// self-decision reconcile needs. +type HumanChangeRequestDismisser interface { + Dismiss(match func(HumanChangeRequest) bool) []HumanChangeRequest +} + // Len is the number of recorded requests across all PRs and heads. func (s *HumanChangeRequests) Len() int { if s == nil { diff --git a/src/pkg/scheduler/fork_aware_queue_test.go b/src/pkg/scheduler/fork_aware_queue_test.go index cf21f19af5..9ecc7be187 100644 --- a/src/pkg/scheduler/fork_aware_queue_test.go +++ b/src/pkg/scheduler/fork_aware_queue_test.go @@ -234,3 +234,23 @@ func TestFormatRedPRFixData_AdoptedPRListedNonAdoptedForkIsNot(t *testing.T) { t.Errorf("non-adopted fork PR listed as push work:\n%s", out) } } + +// hivecommons/hive#15103: the conflict kick tells the fixer how to +// rebase-resolve, which attempt this is, and when the hive stops. +func TestRebaseResolveInstructions(t *testing.T) { + first := rebaseResolveInstructions("v5", 1, 2, false) + for _, want := range []string{"attempt 1/2", "git rebase origin/v5", "--force-with-lease", "OWN branch", "Do not open a new PR"} { + if !strings.Contains(first, want) { + t.Fatalf("first attempt missing %q: %s", want, first) + } + } + if strings.Contains(first, "Last attempt") || strings.Contains(first, "trusted author") { + t.Fatalf("first attempt over-explains: %s", first) + } + last := rebaseResolveInstructions("", 2, 2, true) + for _, want := range []string{"attempt 2/2", "git rebase the base branch", "Last attempt", "trusted author's PR"} { + if !strings.Contains(last, want) { + t.Fatalf("last attempt missing %q: %s", want, last) + } + } +} diff --git a/src/pkg/scheduler/policy_overlays.go b/src/pkg/scheduler/policy_overlays.go index 1049435c87..4fde5f7697 100644 --- a/src/pkg/scheduler/policy_overlays.go +++ b/src/pkg/scheduler/policy_overlays.go @@ -240,6 +240,10 @@ func formatRedPRFixData(data []byte, agent string) string { DeferredIncident int `json:"deferred_incident"` BaseRedChecks []string `json:"base_red_checks"` BaseRed bool `json:"base_red"` + RebaseAttempt int `json:"rebase_attempt"` + RebaseMax int `json:"rebase_attempts_max"` + BaseRef string `json:"base_ref"` + TrustedAuthor bool `json:"trusted_author"` } var payload struct { Items []ciFailingRow `json:"ci_failing"` @@ -337,6 +341,7 @@ func formatRedPRFixData(data []byte, agent string) string { state = "dirty" } b.WriteString(" conflict: mergeable_state=" + state + " — merge the base branch or rebase the PR branch\n") + b.WriteString(" " + rebaseResolveInstructions(pr.BaseRef, pr.RebaseAttempt, pr.RebaseMax, pr.TrustedAuthor) + "\n") if from := strings.TrimSpace(pr.ReroutedFrom); from != "" { b.WriteString(" rerouted from paused/unavailable lane: " + from + "\n") } @@ -688,3 +693,32 @@ const adoptedSentinelNote = "sentinel-alert: repair CI / rebase as usual, but do // pending `tide` or a missing lgtm is never the hive's blocker below stage // 080 (hivecommons/hive#12858). const adoptedPRStatusRule = " ADOPTED BRANCH: when needs-rebase/conflicting, fetch the contributor's actual fork branch and the PR base, rebase onto the base, preserve original authors and Signed-off-by trailers (never --reset-author), and push back to that fork with --force-with-lease against the observed head. Stop if the contributor moved it; never overwrite their new work. Sign only your own new commits.\n STATUS RULE: green CI is not done on a 074 PR. Read the stage comment/lane reason: an open review-swarm finding (reviewer-verdict:changes_requested) is YOUR blocker — fix it and let the swarm re-review. Never report \"only tide remains\" or \"needs maintainer lgtm/approve\" unless the stage label is already >= stage/080; below that, a pending tide check means the lane has not admitted the head yet, not that a person owes an approval.\n" + +// rebaseResolveInstructions is the fixer's rebase-resolve task for a +// conflicting PR (hivecommons/hive#15103): rebase onto the base branch, +// resolve, force-with-lease to the PR's own branch, never open a new PR. +// attempt/max is the loop guard the fixer sees so it knows a second dirty +// head ends the hive's attempts. +func rebaseResolveInstructions(baseRef string, attempt, max int, trustedAuthor bool) string { + base := strings.TrimSpace(baseRef) + if base == "" { + base = "the base branch" + } else { + base = "origin/" + base + } + if attempt < 1 { + attempt = 1 + } + if max < attempt { + max = attempt + } + var b strings.Builder + fmt.Fprintf(&b, "rebase-resolve (attempt %d/%d): `gh pr checkout`, `git rebase %s`, resolve every conflict keeping both sides' intent, re-run the build and tests, then `git push --force-with-lease` to the PR's OWN branch. Do not open a new PR; do not squash away the author's commits.", attempt, max, base) + if trustedAuthor { + b.WriteString(" This is a trusted author's PR the hive carries on their behalf — keep their authorship and sign-off intact.") + } + if attempt >= max { + b.WriteString(" Last attempt: if the head is still conflicting after this push the hive stops and asks a person.") + } + return b.String() +} From a765696df940eb02a5d0cc6bf32c2b0dce4b20d6 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 19:04:30 -0400 Subject: [PATCH 02/10] test: fix fixtures after the v5 rebase (mock fields, failingEntry rebase fields, import ratchet, window shim) Signed-off-by: Andrew Anderson --- src/cmd/hive/merge_eligible_buckets_test.go | 40 ++++++++++--------- .../testutil/dashboard_import_allowlist.txt | 1 + .../dashboard/api_repo_item_decision_test.go | 4 -- .../stage_tracker_row_actions_test.go | 1 + 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/src/cmd/hive/merge_eligible_buckets_test.go b/src/cmd/hive/merge_eligible_buckets_test.go index b391ea74a1..ad596963ad 100644 --- a/src/cmd/hive/merge_eligible_buckets_test.go +++ b/src/cmd/hive/merge_eligible_buckets_test.go @@ -34,24 +34,28 @@ type eligibleEntry struct { } type failingEntry struct { - Number int `json:"number"` - Repo string `json:"repo"` - Agent string `json:"agent"` - HeadSHA string `json:"head_sha"` - FailingChecks []string `json:"failing_checks"` - Excerpt string `json:"excerpt"` - Escalated bool `json:"escalated"` - HeadRef string `json:"head_ref"` - HeadRepo string `json:"head_repo"` - FromFork bool `json:"from_fork"` - ReachableAction string `json:"reachable_action"` - Held bool `json:"held"` - Adopted bool `json:"adopted"` - SentinelAlert bool `json:"sentinel_alert"` - MergeableState string `json:"mergeable_state"` - Conflict bool `json:"conflict"` - ReroutedFrom string `json:"rerouted_from"` - DeferredIncident int `json:"deferred_incident"` + Number int `json:"number"` + Repo string `json:"repo"` + Agent string `json:"agent"` + HeadSHA string `json:"head_sha"` + FailingChecks []string `json:"failing_checks"` + Excerpt string `json:"excerpt"` + Escalated bool `json:"escalated"` + HeadRef string `json:"head_ref"` + HeadRepo string `json:"head_repo"` + FromFork bool `json:"from_fork"` + ReachableAction string `json:"reachable_action"` + Held bool `json:"held"` + Adopted bool `json:"adopted"` + SentinelAlert bool `json:"sentinel_alert"` + MergeableState string `json:"mergeable_state"` + Conflict bool `json:"conflict"` + ReroutedFrom string `json:"rerouted_from"` + DeferredIncident int `json:"deferred_incident"` + RebaseAttempt int `json:"rebase_attempt"` + RebaseAttemptsMax int `json:"rebase_attempts_max"` + BaseRef string `json:"base_ref"` + TrustedAuthor bool `json:"trusted_author"` } type mergeEligibleInputs struct { diff --git a/src/internal/testutil/dashboard_import_allowlist.txt b/src/internal/testutil/dashboard_import_allowlist.txt index 604d2e9faa..faa4df977e 100644 --- a/src/internal/testutil/dashboard_import_allowlist.txt +++ b/src/internal/testutil/dashboard_import_allowlist.txt @@ -51,6 +51,7 @@ github.com/hivecommons/hive/pkg/nous 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/releasenotes github.com/hivecommons/hive/pkg/resolve github.com/hivecommons/hive/pkg/retro diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index bffc6b7263..677544e698 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -49,10 +49,6 @@ type repoItemDecisionMock struct { // an adoption marker on #8 may name (hivecommons/hive#15052); "" is 404. supersederState string supersederMerged bool - // merges records PUT /pulls/8/merge bodies; reviews the POST /reviews - // bodies (merge-now / queue-merge, hivecommons/hive#15078). - merges []map[string]any - reviews []map[string]any // timeline is what GET /issues/N/timeline answers (nil = empty): the // re-park read of hivecommons/hive#15021. timeline []map[string]any diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 95da9a1899..491588576d 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -1398,6 +1398,7 @@ assert.strictEqual(stageTrackerDCOCaveat([]), ''); func TestStageTrackerRebaseThenMergeRow(t *testing.T) { html := indexHTML(t) runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+"\n"+stageTrackerCuesJS(t, html)+stageTrackerActedJS(t, html)+"\n"+jsFunc(t, html, "agentNowClockTime")+` +global.window = { _hiveUser: 'clubanderson' }; const ids = as => as.map(a => a.id); const merger = { user: true, canHold: true, canHuman: true }; const rebaseOpt = { action: 'decide:merge-now', label: STAGE_TRACKER_REBASE_MERGE_LABEL, enabled: true, From bfe7d4506b356671e7a0ce6f2e5253af01af055a Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 19:23:42 -0400 Subject: [PATCH 03/10] test: lift pkg/rebasemerge coverage above its floor; drop an ineffectual assignment Signed-off-by: Andrew Anderson --- src/pkg/dashboard/stage_tracker_decision.go | 4 - src/pkg/rebasemerge/rebasemerge_test.go | 122 ++++++++++++++++++++ 2 files changed, 122 insertions(+), 4 deletions(-) diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 307b2532af..b27338d36f 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -250,10 +250,6 @@ func decisionForHumanMerge(it StageTrackerItem, held bool) *StageTrackerDecision word = "policy" } ref := "#" + strconv.Itoa(it.Number) - into := strings.TrimSpace(it.BaseRef) - if into == "" { - into = "its base branch" - } why := stageTrackerUntrustedAuthorWhy(base, it.Author) if why == "" { why = decisionPlainReason(base) diff --git a/src/pkg/rebasemerge/rebasemerge_test.go b/src/pkg/rebasemerge/rebasemerge_test.go index 874184cbb9..41ef16844c 100644 --- a/src/pkg/rebasemerge/rebasemerge_test.go +++ b/src/pkg/rebasemerge/rebasemerge_test.go @@ -1,6 +1,7 @@ package rebasemerge import ( + "os" "path/filepath" "testing" "time" @@ -208,3 +209,124 @@ func TestAttemptsLoopGuard(t *testing.T) { t.Fatalf("a new episode starts at 1: %+v", a) } } + +// Request opens the episode on an operator's behalf (approve / merge-now on +// a dirty PR): the actor is recorded once, a blank actor records nothing, +// and the request rides the same head count as the sweep's Observe. +func TestAttemptsRequestRecordsOperator(t *testing.T) { + path := filepath.Join(t.TempDir(), "attempts.json") + s := NewAttempts(path) + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + a := s.Request("o/r", 2, "aaa", " ", now) + if a.RequestedBy != "" || a.Count() != 1 { + t.Fatalf("blank actor: %+v", a) + } + a = s.Request("o/r", 2, "aaa", "clubanderson", now.Add(time.Minute)) + if a.RequestedBy != "clubanderson" || a.Count() != 1 || !a.UpdatedAt.Equal(now.Add(time.Minute)) { + t.Fatalf("request: %+v", a) + } + if a = s.Request("o/r", 2, "aaa", "clubanderson", now.Add(2*time.Minute)); !a.UpdatedAt.Equal(now.Add(time.Minute)) { + t.Fatalf("same actor again must not rewrite the episode: %+v", a) + } + if a = s.Request("o/r", 2, "bbb", "other", now.Add(3*time.Minute)); a.RequestedBy != "other" || a.Count() != 2 { + t.Fatalf("new actor on a new head: %+v", a) + } + if got, ok := NewAttempts(path).Get("o/r", 2); !ok || got.RequestedBy != "other" || got.Head() != "bbb" { + t.Fatalf("reload: %+v ok=%v", got, ok) + } + // An empty episode has no head and still reads as attempt 1. + if (Attempt{}).Head() != "" || AttemptText(Attempt{}) != "Rebasing · attempt 1/2" { + t.Fatalf("zero attempt: %q", AttemptText(Attempt{})) + } + // In-memory ledgers never touch disk; a Clear on nothing is a no-op. + mem := NewAttempts("") + mem.Clear("o/r", 99) + if _, ok := mem.Get("o/r", 99); ok { + t.Fatal("phantom episode") + } + if mem.Observe("o/r", 3, "x", now).Count() != 1 { + t.Fatal("in-memory observe") + } +} + +// The process-wide singletons point at the configured /data paths and are +// stable across calls. +func TestSharedSingletons(t *testing.T) { + if Shared() != Shared() || Shared() == nil { + t.Fatal("Shared store is not a singleton") + } + if SharedAttempts() != SharedAttempts() || SharedAttempts() == nil { + t.Fatal("SharedAttempts is not a singleton") + } + var nilStore *Store + if nilStore.Armed("o/r", 1) || nilStore.Live() != nil || nilStore.Put(FollowThrough{}) != nil || nilStore.Update(FollowThrough{}) != nil { + t.Fatal("nil store must be inert") + } +} + +// FailNow is the driver's own failure (a refused merge, an unreachable +// head); FailureText reads each reason in plain words; Kicked is a no-op +// once the follow-through has left the approved state. +func TestFailNowAndFailureText(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 5, "op", "v5", "aaaa111", false, now) + f.FailNow(now.Add(time.Minute), FailNotReachable, nil) + if f.State != StateFailed || f.FailReason != FailNotReachable || f.Live() { + t.Fatalf("FailNow: %+v", f) + } + f.Kicked(now.Add(2*time.Minute), "fixer") + if f.State != StateFailed { + t.Fatalf("Kicked after failure moved state: %+v", f) + } + cases := map[string]string{ + FailNotReachable: "The hive cannot push to #5's head (fork without maintainer edits).", + FailCIRed: "CI went red on the rebased head of #5; nothing merged.", + FailTimeout: "The rebase of #5 did not land in time; nothing merged.", + FailClosed: "#5 was closed before the hive could merge it.", + FailConflict: "Rebase of #5 onto v5 conflicts in a.go, b.go.", + "odd": "Rebase-then-merge of #5 failed: odd.", + } + for reason, want := range cases { + g := f + g.FailReason = reason + g.ConflictFiles = []string{"a.go", "b.go"} + if got := g.FailureText(); got != want { + t.Errorf("%s: %q, want %q", reason, got, want) + } + } + g := f + g.FailReason, g.Base, g.ConflictFiles = FailConflict, "", nil + if got := g.FailureText(); got != "Rebase of #5 onto its base conflicts." { + t.Errorf("conflict without files/base: %q", got) + } +} + +// Persistence failures are reported, not hidden: a store whose path cannot +// be created returns the error from Put, and a corrupt file loads as empty. +func TestStoreAndAttemptsPersistenceEdges(t *testing.T) { + dir := t.TempDir() + blocker := filepath.Join(dir, "file") + if err := os.WriteFile(blocker, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + st := NewStore(filepath.Join(blocker, "sub", "f.json")) + if err := st.Put(Arm("o/r", 1, "op", "v5", "aaa", true, now)); err == nil { + t.Fatal("Put under a file-as-directory must fail") + } + // The attempts ledger swallows the same failure and stays usable. + at := NewAttempts(filepath.Join(blocker, "sub", "a.json")) + if at.Observe("o/r", 1, "aaa", now).Count() != 1 { + t.Fatal("attempts observe under a bad path") + } + corrupt := filepath.Join(dir, "corrupt.json") + if err := os.WriteFile(corrupt, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + if got := NewStore(corrupt).Live(); len(got) != 0 { + t.Fatalf("corrupt store loaded %d items", len(got)) + } + if _, ok := NewAttempts(corrupt).Get("o/r", 1); ok { + t.Fatal("corrupt attempts loaded an episode") + } +} From f7330d24b8a8e41751e83293e160e1e69f5f331d Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 19:45:45 -0400 Subject: [PATCH 04/10] test: compare the shared singletons through named values (staticcheck SA4000) Signed-off-by: Andrew Anderson --- src/pkg/rebasemerge/rebasemerge_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/pkg/rebasemerge/rebasemerge_test.go b/src/pkg/rebasemerge/rebasemerge_test.go index 41ef16844c..a0614a84cc 100644 --- a/src/pkg/rebasemerge/rebasemerge_test.go +++ b/src/pkg/rebasemerge/rebasemerge_test.go @@ -252,10 +252,12 @@ func TestAttemptsRequestRecordsOperator(t *testing.T) { // The process-wide singletons point at the configured /data paths and are // stable across calls. func TestSharedSingletons(t *testing.T) { - if Shared() != Shared() || Shared() == nil { + first, second := Shared(), Shared() + if first == nil || first != second { t.Fatal("Shared store is not a singleton") } - if SharedAttempts() != SharedAttempts() || SharedAttempts() == nil { + a1, a2 := SharedAttempts(), SharedAttempts() + if a1 == nil || a1 != a2 { t.Fatal("SharedAttempts is not a singleton") } var nilStore *Store From 4e1c4bebea707874c3a2fafea9c384da9c4a85f6 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 21:25:38 -0400 Subject: [PATCH 05/10] security: rebase-then-merge fails closed on a head the hive did not produce; document the new API shapes The approval is bound to the head the operator read. A contributor PR whose head moves after the click now counts as rebased only when GitHub reports the hive (App bot or pane identity) as the commit's author or committer; any other head settles the follow-through as failed (foreign-head) with nothing merged, a note on the PR, and 'Approve the new head & merge' as the way out. api-reference.md gains the 202 rebase-queued answer, the rebase response field, and the rebase_merge / rebase row fields. Signed-off-by: Andrew Anderson --- changelog.d/fixed-rebase-then-merge.md | 2 +- src/docs/api-reference.md | 4 +- src/docs/dashboard-sections.md | 2 +- src/docs/operator-reference.md | 2 +- .../dashboard/api_repo_item_decision_test.go | 14 ++++++ .../dashboard/rebase_merge_followthrough.go | 24 ++++++++++ .../rebase_merge_followthrough_test.go | 46 ++++++++++++++++++- .../stage_tracker_row_actions_test.go | 1 + src/pkg/dashboard/static/index.html | 2 +- src/pkg/github/pr_merge_state.go | 26 +++++++++++ src/pkg/rebasemerge/rebasemerge.go | 36 +++++++++++++-- src/pkg/rebasemerge/rebasemerge_test.go | 38 ++++++++++++++- 12 files changed, 183 insertions(+), 14 deletions(-) diff --git a/changelog.d/fixed-rebase-then-merge.md b/changelog.d/fixed-rebase-then-merge.md index f85d30c53b..5a07ac1c5a 100644 --- a/changelog.d/fixed-rebase-then-merge.md +++ b/changelog.d/fixed-rebase-then-merge.md @@ -1,3 +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 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)). +- 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 ([#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)). diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index a55f14e805..3691dd24aa 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -283,9 +283,9 @@ Read the result from `GET /api/kick/{agent}/status`, which returns `status` of ` | `GET` | `/api/repos/{owner}/{repo}/hold-permission` | Dashboard auth/session | Reports whether the signed-in user can toggle hold chips for a repository card. Owners are allowed; otherwise the server checks GitHub `repos/{owner}/{repo}/collaborators/{user}/permission` and briefly caches the effective permission | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_hold.go` | -| `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | +| `GET` | `/api/repos/{owner}/{repo}/items/{number}` | Dashboard session | Per-item detail for the activity monitor's decision badge: `{repo, number, stage, stage_slug, operator_actions[], operator_action_count, last_operator_action}`. `operator_actions[]` is the server-side ledger of every row action submitted from the dashboard (hold/release, decision, decide-delegated, send-to-human, accept-triage — recorded by `recordOperatorAction` around those routes) as `{action, actor, at, note, target, outcome: pending|applied|no-op|failed, detail, head_sha, stage}`; `last_operator_action` adds the derived `state` (`waiting|addressed|stuck|pending|failed`), `stuck_after_seconds` and `followed[]` (the stage hops after the action). The same `last_operator_action` / `operator_action_count` ride every stage-tracker row and linked PR. Persisted in `/data/operator-actions.json`; `HIVE_OPERATOR_ACTION_STUCK_AFTER` (default `30m`) sets the stuck window. Rows also carry `rebase_merge: {state: approved|rebasing|ci-pending|merged|failed, actor, base, text, fail_reason, conflict_files[], armed_at}` while a *Rebase, then merge as maintainer* follow-through is live or just settled (persisted in `/data/rebase-merge-followups.json`; `fail_reason: foreign-head` when the head moved after the approval by someone other than the hive, so nothing merged), and `rebase: {attempt, max, exhausted, head, text}` on a conflicting PR the fixer is rebasing under the two-attempt loop guard (`/data/rebase-attempts.json`). | `pkg/dashboard/api.go`, `pkg/dashboard/operator_actions.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/hold` | Owner or repo write/maintain/admin | Add or remove a dashboard hold chip for an issue or PR. Body `{"held": true}` adds the hive's exact-match canonical `hive-pause/` label; `{"held": false}` removes exactly the labels causing the hold (`hive-pause/` and/or generic hold labels) and never removes `hive/` provenance. Every toggle writes an audit-log entry; the #8851 upgrade migration writes `/data/hive-hold-migration-.json` with audit-backed, provenance-only, and ambiguous legacy `hive/` classifications. | `pkg/dashboard/api.go:337`, `pkg/dashboard/api_repo_hold.go` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458"}`. On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. Never merges. Every decision writes an audit-log entry (`repo_item_decision_*`). | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_item_decision.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/decision` | Owner or repo write/maintain/admin, signed-in GitHub user | Record an operator decision from the activity monitor's row menu / selection bar. Body `{"decision": "approve"|"direction"|"close-superseded"|"close-wontfix"|"adopt"|"reroute"|"re-author"|"merge-now"|"queue-merge", "comment": "…", "type": "issue"|"pr", "superseded_by": "#458", "force": true, "to": ""|"any"}` (`force` only with `adopt`, `to` only with `reroute`; an unknown `decision` is a 400). On an issue parked at 045, `approve`/`direction` act exactly as a maintainer's `/hive approve` / `/hive decision ` comment would (labels, `approved-direction`, stage-engine Unparked fact, reply comment naming the operator). On a PR parked at 085 (`type: "pr"`), `approve` posts the `/lgtm` and `/approve` commands as two comments attributed to the operator, records the approval against the head as the human answer to a `requires_human` / decision-requested verdict (the lanes and the stage engine honour it like a trusted merger's Approve review), lifts `needs-human`, clears the sentinel label and acknowledges the bundle's sentinel findings for that head, re-derives the stage and drops the tracker cache — the response adds `released` (`approval-recorded`, `needs-human`, `sentinel-label`, `sentinel-acknowledged`) and `stage`; the merge gate decides from there (no review as the operator, no merge) — and `direction` records the text as a human change request against the head — the `/hive decision` fix lane — on a hive-authored PR, and on a contributor's clanker PR (`author/clanker` / hive attribution markers) where the text is posted to the contributor's hive and the PR moves to `stage/072-returned-to-contributor` (`status: "direction-returned-to-contributor"`); a person's PR, which no hive can carry direction to, answers 409. The close variants post a comment naming the operator (and the superseding PR when `superseded_by` is given) and close the item as not planned. `adopt` and `re-author` require `type: "pr"` and queue adoption via the `adoption/supersede` label (409 unless `governor.labels.stage.adoption` is enabled). `adopt` with `"force": true` is *Adopt now* ([#15038](https://github.com/hivecommons/hive/issues/15038)): it bypasses the author's presence, the grace window and `maintainer_policy`, marks the stage record and nudges the automerge sweep so the adoption engine supersedes the head at once (responds `status: "already-adopted"` when nothing is left to do; 400 on the hive's own PR). `reroute` (`type: "pr"`, `"to": ""|"any"`) hands the PR's follow-up work to another online clanker through the contributor fix queue, posts a `` note and arms a pickup timer that falls back to Adopt now after `governor.reroute.pickup_timeout`; answers `status: "rerouted"`, 409 when no clanker is online or adoption is disabled. On a PR at 090, `merge-now` (*Approve & merge as maintainer*) posts an attributed comment and merges immediately through the hive's GitHub App, returning `status: "merged"`; `queue-merge` (*Approve — let hive merge*) records an approval attributed to the operator and applies the automerge label, returning `status: "queued-for-merge"` for the hive's merge sweep once CI is green and the head has soaked. Both require `type: "pr"` and a verified owner or `merger` role in addition to the route's repo permission check; both refuse closed/merged PRs and the operator's own PR. `merge-now` on a PR whose `mergeable_state` is `dirty`/`behind` instead answers `202` with `status: "rebase-queued"` (approval recorded, rebase kicked, merge follows via the follow-through once the hive's own rebase is green; a head pushed by anyone else fails the follow-through closed; `head-not-pushable` refusal on a fork without maintainer edits). `approve` on such a PR adds `rebase: {attempt, max, exhausted, head, text}` for the rebase episode it opened. Every decision writes an audit-log entry (`repo_item_decision_*`, e.g. `repo_item_decision_adopt_now`, `repo_item_decision_reroute`). | `pkg/dashboard/api.go:338`, `pkg/dashboard/api_repo_item_decision.go` | | `POST` / `GET` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated` | Same as `…/hold` (owner or repo write), signed-in GitHub user; `decisions.delegate.enabled` (403 when off) | *Let hive decide*: enqueue a delegated-decision job in which the hive decides the parked item itself as the owner's delegate under `pkg/delegatedecision.PolicyText` and records it as a human decision (`/hive decision` comment with the `` marker, park labels off, `triage/accepted`, queue approval on a PR head). Body `{"type": "issue"|"pr", "reason", "caption", "sentinel_reason"}`. `POST` answers 202 with the job (`{id, status: "running"|"done"|"failed", decision: {verdict, rule, text, rationale, actions, keeps_park}, notes, error}`); 409 with the running job while one is in flight; `GET` reads it. Rails: never merges, refuses items wearing `hold`, never grants secrets/permissions (`needs-owner` + `hold` instead), recommends only on hive policy/governance questions (keeps 085). Audited as `repo_item_decision_delegated[_failed]`. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:329`, `pkg/dashboard/api_repo_item_decide_delegated.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, summary, why, consequences[], alternatives[], writes: false, prior, notes}` — *Hive would: re-author #15029 as a hive PR with the same commits and merge it; #15029 will be closed as superseded. Why: author @Karibhou is untrusted and their clanker is offline.* The confirm popover shows **Let hive do that** / **Approve & merge as-is** / **Cancel**; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. See [dashboard-sections.md](dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:533`, `pkg/dashboard/api_repo_item_accept_triage.go` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 4c41570036..732129f71f 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -753,7 +753,7 @@ No glyph on a chevron or pill rotates (owner, 2026-10-28: "i dont like the statu |---|---| | PR at 090 *Ready for human merge* (untrusted author, workflow files, manual-merge path, branch protection…) | **Approve & merge as maintainer** (merges #N into *base* now via hive's identity, attributed to you — a comment on the PR names you, the audit log records `repo_item_decision_merge`, `source: dashboard`) · **Approve — let hive merge** (records your approval as the owner decision — an APPROVE review and the automerge label; the hive's merge sweep merges it on its next pass once CI is green and the head has soaked) · Give direction (hive-authored PRs only) · Close as superseded · Close as won't fix · Hold. Both merge actions need the merger or owner role and confirm first (with *Don't ask again*); the toast reads *merged* / *queued for merge*; the badge records `merge-now` / `queue-merge`. **Let hive decide** is here too (third): on a 090 PR it never runs the policy — the hive answers at once through the no-effect toast, *I can't merge this: author @Karibhou is untrusted on hotshot — …*, with *Approve & merge as maintainer · Approve — let hive merge* as buttons and the 👥 Contributors fix in the next line. **Either Approve is the trust override for that head** ([#15136](https://github.com/hivecommons/hive/issues/15136); owner, 2026-10-29: "I approved these and then they went to adopted…"): the stage record gets `admitted_by: operator-approval:`, the contributor lane merges the head as-is after checks and soak, and the adoption engine refuses to adopt or supersede it while the admission stands (the row reads *not adopted: a maintainer approved this head; the hive merges it as-is*; the 090 tooltip and popover say *Approved by @you as the owner decision…* and the second Approve greys out). When the record's commit check found commits without a `Signed-off-by`, the popover's blocker line and both Approve confirms say so **before** acting (*2 of 3 commits have no Signed-off-by, so a required DCO check refuses the merge*) and a third lead action appears, **Re-author as hive PR** — the explicit, separate choice: the hive re-homes the commits on a signed-off hive branch and opens a superseding PR; nothing is merged as-is. It is greyed with the reason on a person's PR. Renderer test: `TestStageTrackerReauthorAndApprovalCaveats`. | | PR at 085 *Needs human decision* | Let hive decide · Approve · Give direction · Close as superseded · Close as won't fix · Hold (unchanged). When the row also wears **needs rebase**, **Rebase, then merge as maintainer** sits right after Approve (below). | -| PR at 085 or 090 that also wears **needs rebase** (behind or conflicting with its base) | **Rebase, then merge as maintainer** replaces *Approve & merge as maintainer* — a plain merge would be a GitHub 405 — with the consequence *hive rebases #N onto base, waits for CI, then merges it with your approval on record; you'll get a toast when it lands or if the rebase conflicts*. The click records your approval first (/lgtm + /approve in your name), arms a follow-through, and kicks the rebase (GitHub update-branch for the hive's own PR when it is merely behind; otherwise the fixer lane, which now owns a parked PR with an armed follow-through); the endpoint answers `202 rebase-queued` and the toast reads *rebase queued, merge to follow*. The row then reads **Rebasing → merge queued (approved by @you)** with the working cue, *Rebased → waiting for CI, then merge* once the head moves, and the normal merge-gate pills after that. On green the hive merges the rebased head with your approval attributed; on a conflict (or CI red, or no rebase within 2 h) the action settles as *failed* with the conflicting files and two ways out — **Adopt into fresh branch** · **Close as superseded** — on the row's badge and in a note on the PR. The ledger's `last_operator_action.followed[]` carries each step (`approval-recorded` → `rebase-kicked` → `rebased` → `ci-green` → `merged`, or `failed`). ([#14822](https://github.com/hivecommons/hive/issues/14822)) | +| PR at 085 or 090 that also wears **needs rebase** (behind or conflicting with its base) | **Rebase, then merge as maintainer** replaces *Approve & merge as maintainer* — a plain merge would be a GitHub 405 — with the consequence *hive rebases #N onto base, waits for CI, then merges it with your approval on record; you'll get a toast when it lands or if the rebase conflicts*. The click records your approval first (/lgtm + /approve in your name), arms a follow-through, and kicks the rebase (GitHub update-branch for the hive's own PR when it is merely behind; otherwise the fixer lane, which now owns a parked PR with an armed follow-through); the endpoint answers `202 rebase-queued` and the toast reads *rebase queued, merge to follow*. The row then reads **Rebasing → merge queued (approved by @you)** with the working cue, *Rebased → waiting for CI, then merge* once the head moves, and the normal merge-gate pills after that. On green the hive merges the rebased head with your approval attributed — only a head the hive itself produced counts as the rebase; a head someone else pushes after your click settles the action as *failed* (*the head moved after your approval*) with **Approve the new head & merge** · **Close as superseded** as the ways out, nothing merged. On a conflict (or CI red, or no rebase within 2 h) the action settles as *failed* with the conflicting files and two ways out — **Adopt into fresh branch** · **Close as superseded** — on the row's badge and in a note on the PR. The ledger's `last_operator_action.followed[]` carries each step (`approval-recorded` → `rebase-kicked` → `rebased` → `ci-green` → `merged`, or `failed`). ([#14822](https://github.com/hivecommons/hive/issues/14822)) | | PR (hive-authored or a trusted author's) that is **conflicting** with its base | No click needed: the fixer lane rebases it on the hive's behalf, and the gate pill reads **Rebasing · attempt n/2** (spinning) — each fixer push that GitHub still reports dirty is the next attempt. After two the hive stops: the pill reads **Rebase failed · 2/2 — needs a person** and the row's menu still offers *Adopt into fresh branch* / *Close as superseded*. A merely `behind` PR gets GitHub's update-branch from its merge lane even while it wears prow's stale needs-rebase label. **Approve** on such a PR records the approval and opens the rebase episode in your 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, never "the merge gate takes it from here"; the *Approving…* cue clears the moment the decision records. ([#15103](https://github.com/hivecommons/hive/issues/15103)) | | Issue at 045 *Needs decision* (direction) | Let hive decide · Give direction · Approve direction · Send back to the hive · Hold (unchanged). | | Human-authored PR at 071 *Needs author* / 072 *Returned to contributor* | Let hive decide · Close as superseded · Close as won't fix · Hold — the hive never rewrites a person's PR, so the choice is wait or close. (A hive-authored PR there carries *Adopt now* when adoption applies.) | diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 4ea4f338d4..8f25a8ce18 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -472,7 +472,7 @@ verified owner or an authorized user with the `merger` role: | Decision | What it does | Audit / ledger | |---|---|---| | `merge-now` — *Approve & merge as maintainer* | Comments on the PR that @you merged it from the dashboard, then merges it at once through the hive's GitHub App (`MergePRVia`, audit path `dashboard`). Refused when the PR is merged or closed, or when you are its author. | `repo_item_decision_merge`; `last_operator_action.action: merge-now`; toast *merged*. | -| `merge-now` on a PR whose `mergeable_state` is `dirty` or `behind` — *Rebase, then merge as maintainer* | Never a GitHub 405. Records your approval first (/lgtm + /approve naming you), arms a rebase-then-merge follow-through (`/data/rebase-merge-followups.json`), kicks the rebase (update-branch on the hive's own PR when only behind; otherwise the fixer lane, which owns a parked PR with an armed follow-through), and answers `202 rebase-queued`. A 2-minute ticker then reads the PR: `mergeable_state: clean` on the rebased head → merges it with your approval attributed; still `dirty` after 2 h, CI red, or no rebase within the deadline → `failed` with the conflicting files and the options *Adopt into fresh branch* / *Close as superseded* (also left as a note on the PR). Refused on a fork whose author has not allowed maintainer edits (`head-not-pushable`). | `repo_item_decision_merge` with `status: rebase-queued`; `last_operator_action.action: merge-now`, outcome `pending` → `applied` / `failed`, `followed[]` steps `approval-recorded`, `rebase-kicked`, `rebased`, `ci-green`, `merged` / `failed`; row `rebase_merge.state`; toast *rebase queued, merge to follow*. | +| `merge-now` on a PR whose `mergeable_state` is `dirty` or `behind` — *Rebase, then merge as maintainer* | Never a GitHub 405. Records your approval first (/lgtm + /approve naming you), arms a rebase-then-merge follow-through (`/data/rebase-merge-followups.json`), kicks the rebase (update-branch on the hive's own PR when only behind; otherwise the fixer lane, which owns a parked PR with an armed follow-through), and answers `202 rebase-queued`. A 2-minute ticker then reads the PR: `mergeable_state: clean` on the rebased head → merges it with your approval attributed; still `dirty` after 2 h, CI red, or no rebase within the deadline → `failed` with the conflicting files and the options *Adopt into fresh branch* / *Close as superseded* (also left as a note on the PR). Refused on a fork whose author has not allowed maintainer edits (`head-not-pushable`). The approval is bound to the head you read: a new head on a contributor's PR counts as the rebase only when GitHub says the hive committed it (the fixer's rebase or update-branch under the App); a head anyone else pushes after your click settles the follow-through as `failed` (`foreign-head`) with nothing merged, a note on the PR, and *Approve the new head & merge* / *Close as superseded* as the ways out. | `repo_item_decision_merge` with `status: rebase-queued`; `last_operator_action.action: merge-now`, outcome `pending` → `applied` / `failed`, `followed[]` steps `approval-recorded`, `rebase-kicked`, `rebased`, `ci-green`, `merged` / `failed`; row `rebase_merge.state`; toast *rebase queued, merge to follow*. | | `queue-merge` — *Approve — let hive merge* | Leaves an `APPROVED` review in your name with a note, adds the automerge label, and leaves the merge to the App self-merge sweep, which merges on its next pass once CI is green and the head has soaked. Refused on your own PR. | `repo_item_decision_queue_merge`; `last_operator_action.action: queue-merge`; toast *queued for merge*. | **Approve is the trust override for that head diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index 677544e698..c6c061b681 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -52,6 +52,9 @@ type repoItemDecisionMock struct { // timeline is what GET /issues/N/timeline answers (nil = empty): the // re-park read of hivecommons/hive#15021. timeline []map[string]any + // commitBy maps a head SHA to the login GET /commits/{sha} reports as + // its committer; an unlisted SHA reads as a person's push. + commitBy map[string]string } func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { @@ -133,6 +136,17 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { } case r.Method == http.MethodGet && strings.HasSuffix(path, "/commits/feedfacefeedfacefeedfacefeedfacefeedface/check-runs"): _, _ = io.WriteString(w, `{"total_count":0,"check_runs":[]}`) + case r.Method == http.MethodGet && strings.Contains(path, "/commits/") && !strings.HasSuffix(path, "/status") && !strings.HasSuffix(path, "/check-runs"): + sha := path[strings.LastIndex(path, "/")+1:] + login, typ := "someone", "User" + if by, ok := m.commitBy[sha]; ok { + login = by + if strings.HasSuffix(by, "[bot]") { + typ = "Bot" + } + } + who := map[string]any{"login": login, "type": typ} + _ = json.NewEncoder(w).Encode(map[string]any{"sha": sha, "author": who, "committer": who, "commit": map[string]any{"author": map[string]any{"name": login, "email": login + "@example.com"}, "committer": map[string]any{"name": login, "email": login + "@example.com"}}}) case r.Method == http.MethodGet && strings.Contains(path, "/timeline"): if m.timeline == nil { _, _ = io.WriteString(w, `[]`) diff --git a/src/pkg/dashboard/rebase_merge_followthrough.go b/src/pkg/dashboard/rebase_merge_followthrough.go index 0472e36584..8421f3ec94 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough.go +++ b/src/pkg/dashboard/rebase_merge_followthrough.go @@ -137,6 +137,9 @@ func rebaseMergeQueuedResult(f rebasemerge.FollowThrough, already bool) *RowActi func rebaseMergeFailedResult(f rebasemerge.FollowThrough) *RowActionResult { out := &RowActionResult{Action: rowActionRefused, Target: rowActionTarget(f.Repo, rowActionTargetPR, f.Number), Outcome: f.FailureText(), Why: f.FailReason} out.Next = "Pick a way out: adopt the commits into a fresh branch, or close it as superseded." + if f.FailReason == rebasemerge.FailForeignHead { + out.Next = "Read the new head; if it is what you meant to merge, approve it again — or close the PR as superseded." + } out.Options = rebaseMergeFailureOptions(f) return out } @@ -149,6 +152,10 @@ func rebaseMergeFailureOptions(f rebasemerge.FollowThrough) []StageTrackerDecisi out = append(out, decisionOption(decisionActionAdopt, rebasemerge.OptionAdoptFreshLabel, true, "")) case rebasemerge.OptionCloseSuperseded: out = append(out, decisionOption(decisionActionCloseSuperseded, rebasemerge.OptionCloseSupersLabel, true, "")) + case rebasemerge.OptionReapprove: + opt := decisionOption(decisionActionMergeNow, rebasemerge.OptionReapproveLabel, true, "") + opt.Consequence = "records your approval for the head as it is now and has the hive rebase and merge it" + out = append(out, opt) } } return out @@ -170,6 +177,10 @@ func renderRebaseThenMergeFailedComment(f rebasemerge.FollowThrough) string { body += "- `" + file + "`\n" } } + if f.FailReason == rebasemerge.FailForeignHead { + body += fmt.Sprintf("\n@%s: from the dashboard row, **%s** or **%s**.", f.Actor, rebasemerge.OptionReapproveLabel, rebasemerge.OptionCloseSupersLabel) + return body + } body += fmt.Sprintf("\n@%s: from the dashboard row, **%s** or **%s**.", f.Actor, rebasemerge.OptionAdoptFreshLabel, rebasemerge.OptionCloseSupersLabel) return body } @@ -215,6 +226,19 @@ func (s *Server) driveRebaseMerge(ctx context.Context, store *rebasemerge.Store, gh := s.deps.GHClient now := rebaseMergeNow() obs := rebasemerge.Observation{Now: now, Head: st.HeadSHA, State: st.State, Merged: st.Merged, MergeableState: st.MergeableState, CIRed: st.CIRed} + if head := strings.TrimSpace(st.HeadSHA); head != "" && head != f.ApprovedHead && head != f.RebasedHead && !f.HiveAuthored && !st.Merged { + // The approval was bound to ApprovedHead. Before the new head can + // count as "the rebase", make sure the hive produced it; a read + // error leaves the decision to the next tick rather than guessing. + byHive, err := gh.CommitByHive(ctx, f.Repo, head) + if err != nil { + if s.logger != nil { + s.logger.Warn("rebase-then-merge: cannot tell who pushed the new head; waiting", "repo", f.Repo, "number", f.Number, "head", head, "error", err) + } + return + } + obs.HeadByHive = byHive + } if st.Conflicting() { if files, err := gh.PRConflictCandidates(ctx, f.Repo, st.BaseRef, st.HeadSHA); err == nil { obs.ConflictFiles = files diff --git a/src/pkg/dashboard/rebase_merge_followthrough_test.go b/src/pkg/dashboard/rebase_merge_followthrough_test.go index c75771d1e9..70264f82b4 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough_test.go +++ b/src/pkg/dashboard/rebase_merge_followthrough_test.go @@ -80,7 +80,7 @@ func TestRepoItemDecisionMergeNowOnDirtyPRArmsRebaseThenMerge(t *testing.T) { // fails with the files and the two options, and the PR gets the note. func TestDriveRebaseMergeGreenMergesAndConflictFails(t *testing.T) { store := useRebaseMergeStore(t) - mock := &repoItemDecisionMock{prForeign: true} + mock := &repoItemDecisionMock{prForeign: true, commitBy: map[string]string{"0123456789abcdef0123456789abcdef01234567": "hive[bot]"}} srv := newRepoItemDecisionServer(t, mock) srv.operatorActionStore = newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json")) now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) @@ -231,7 +231,7 @@ func TestRebaseAttemptsPillAndFollowThroughExhaustion(t *testing.T) { // Follow-through on the same PR: still dirty after the fixer's first // push → back to rebasing; exhausted → failed with the files. - mock := &repoItemDecisionMock{} + mock := &repoItemDecisionMock{commitBy: map[string]string{"bbb2222": "hive[bot]", "ccc3333": "hive[bot]"}} srv := newRepoItemDecisionServer(t, mock) srv.operatorActionStore = newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json")) attempts.Clear("hivecommons/hive", 15087) @@ -325,3 +325,45 @@ func TestRepoItemDecisionApproveOnDirtyPRQueuesRebase(t *testing.T) { t.Fatalf("clean approve: code=%d resp=%+v", w.Code, resp.Result) } } + +// The approval is bound to the head the operator read. When a contributor +// PR's head moves and GitHub says the hive did not commit it, the +// follow-through fails closed — nothing merges, the ledger says why, the +// note on the PR asks for a fresh approval — and the row's way out is to +// approve the new head (hivecommons/hive#15104 security review). +func TestDriveRebaseMergeForeignHeadFailsClosed(t *testing.T) { + store := useRebaseMergeStore(t) + mock := &repoItemDecisionMock{prForeign: true} + srv := newRepoItemDecisionServer(t, mock) + srv.operatorActionStore = newOperatorActionStore(filepath.Join(t.TempDir(), "ops.json")) + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + prevNow := rebaseMergeNow + rebaseMergeNow = func() time.Time { return now } + t.Cleanup(func() { rebaseMergeNow = prevNow }) + + f := rebasemerge.Arm("testorg/testrepo", 8, "writer", "main", "feedfacefeedfacefeedfacefeedfacefeedface", false, now) + f.Kicked(now, "fixer") + _ = store.Put(f) + _ = srv.operatorActions().Record("testorg/testrepo", 8, OperatorAction{Action: operatorActionMergeNow, Actor: "writer", At: now, Outcome: operatorActionOutcomePending, Detail: repoItemStatusRebaseQd, Stage: 85}) + + now = now.Add(5 * time.Minute) + srv.driveRebaseMerge(context.Background(), store, f, ghpkg.PRMergeState{State: "open", HeadSHA: "0123456789abcdef0123456789abcdef01234567", BaseRef: "main", MergeableState: "clean"}) + f, _ = store.Get("testorg/testrepo", 8) + if f.State != rebasemerge.StateFailed || f.FailReason != rebasemerge.FailForeignHead || f.ForeignHead != "0123456789abcdef0123456789abcdef01234567" { + t.Fatalf("foreign head: %+v", f) + } + if len(mock.merges) != 0 { + t.Fatalf("a head the hive did not produce must not merge: %v", mock.merges) + } + acts := srv.operatorActions().List("testorg/testrepo", 8) + if len(acts) != 1 || acts[0].Outcome != operatorActionOutcomeFailed || !strings.Contains(acts[0].Detail, "someone pushed 0123456") { + t.Fatalf("ledger = %+v", acts) + } + if len(mock.comments) != 1 || !strings.Contains(mock.comments[0], "approve it again") || !strings.Contains(mock.comments[0], rebasemerge.OptionReapproveLabel) || strings.Contains(mock.comments[0], rebasemerge.OptionAdoptFreshLabel) { + t.Fatalf("failure note = %q", mock.comments) + } + res := rebaseMergeFailedResult(f) + if res.Action != rowActionRefused || res.Why != rebasemerge.FailForeignHead || len(res.Options) != 2 || res.Options[0].Action != decisionActionMergeNow || res.Options[1].Action != decisionActionCloseSuperseded { + t.Fatalf("failed result = %+v", res) + } +} diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 491588576d..1c24371113 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -1387,6 +1387,7 @@ assert.strictEqual(stageTrackerDCOCaveat([]), ''); await stageTrackerActionPayload([{ ...pr317, dco_unsigned: 0 }], 'decide:merge-now'); assert.ok(!dialogs[0].cfg.message.includes('Signed-off-by'), dialogs[0].cfg.message); })().catch(e => { console.error(e); process.exit(1); }); +`) } // TestStageTrackerRebaseThenMergeRow: a PR that needs a rebase offers diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 617595a367..93ff33c15e 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -15841,7 +15841,7 @@

Where to get help

released: 'hold released', 'already accepted': 'it was already accepted', 'approval-recorded': 'recorded your approval', 'rebase-kicked': 'started the rebase', rebased: 'rebased it onto the base branch', 'ci-green': 'saw CI go green', merged: 'merged it', - 'rebase-conflict': 'the rebase conflicts', 'ci-red': 'CI went red on the rebased head', 'rebase-timeout': 'the rebase did not land in time', 'head-not-pushable': 'the hive cannot push to this fork', + 'rebase-conflict': 'the rebase conflicts', 'ci-red': 'CI went red on the rebased head', 'rebase-timeout': 'the rebase did not land in time', 'head-not-pushable': 'the hive cannot push to this fork', 'foreign-head': 'the head moved after your approval, pushed by someone other than the hive', }; function stageTrackerActedPlain(text) { const t = String(text || '').trim(); diff --git a/src/pkg/github/pr_merge_state.go b/src/pkg/github/pr_merge_state.go index 3573ce3c91..1c465e49e9 100644 --- a/src/pkg/github/pr_merge_state.go +++ b/src/pkg/github/pr_merge_state.go @@ -2,6 +2,7 @@ package github import ( "context" + "errors" "fmt" "slices" "strings" @@ -87,6 +88,31 @@ func (c *Client) GetPRMergeState(ctx context.Context, repo string, number int) ( return st, nil } +// CommitByHive reports whether the commit at sha is the hive's own work: +// its author or committer resolves to the App bot (by login or noreply +// address) or to an address in the pane identity domain — the fixer's +// rebase or GitHub's update-branch under the App. A head a person pushed +// after a rebase-then-merge approval is new content the approval never +// covered, so the follow-through fails closed on it (hivecommons/hive#15104). +func (c *Client) CommitByHive(ctx context.Context, repo, sha string) (bool, error) { + if c == nil || c.client == nil { + return false, ErrNoGitHubClient + } + sha = strings.TrimSpace(sha) + if sha == "" { + return false, errors.New("commit by hive: empty SHA") + } + owner, repoName := c.splitRepo(repo) + rc, _, err := c.client.Repositories.GetCommit(WithRESTCaller(ctx, "hive:rebase_merge_head_identity"), owner, repoName, sha, nil) + if err != nil { + return false, fmt.Errorf("reading %s/%s@%s: %w", owner, repoName, shortSHA(sha), err) + } + if c.hiveCommitIdentity(safeGetLogin(rc.GetCommitter()), rc.GetCommit().GetCommitter().GetEmail()) { + return true, nil + } + return c.hiveCommitIdentity(safeGetLogin(rc.GetAuthor()), rc.GetCommit().GetAuthor().GetEmail()), nil +} + // PRConflictCandidates names the files a PR changed that its base also // changed since their merge base: the files a rebase will have to resolve. // GitHub does not report conflicting paths, so this is the honest diff --git a/src/pkg/rebasemerge/rebasemerge.go b/src/pkg/rebasemerge/rebasemerge.go index af1f431769..2df02ce71a 100644 --- a/src/pkg/rebasemerge/rebasemerge.go +++ b/src/pkg/rebasemerge/rebasemerge.go @@ -64,14 +64,21 @@ const ( FailTimeout = "rebase-timeout" FailClosed = "pr-closed" FailNotReachable = "head-not-pushable" + // FailForeignHead: the head moved after the approval, but not by the + // hive — a person pushed new content. The approval was bound to the + // head the operator read, so the follow-through stops instead of + // merging content nobody approved. + FailForeignHead = "foreign-head" ) // Options the failed outcome offers (decision action ids the SPA knows). const ( OptionAdoptFresh = "decide:adopt" OptionCloseSuperseded = "decide:close-superseded" + OptionReapprove = "decide:merge-now" OptionAdoptFreshLabel = "Adopt into fresh branch" OptionCloseSupersLabel = "Close as superseded" + OptionReapproveLabel = "Approve the new head & merge" ) // Default timing. RebaseDeadline bounds how long a kicked rebase may sit @@ -101,8 +108,11 @@ type FollowThrough struct { // the rebase produced (set once observed). HiveAuthored says whether // the PR is the hive's own (the self lane rebases) or a contributor's // (push-reachable fixer). - ApprovedHead string `json:"approved_head"` - RebasedHead string `json:"rebased_head,omitempty"` + ApprovedHead string `json:"approved_head"` + RebasedHead string `json:"rebased_head,omitempty"` + // ForeignHead is the head a person (not the hive) pushed after the + // approval, when that is why the follow-through failed. + ForeignHead string `json:"foreign_head,omitempty"` HiveAuthored bool `json:"hive_authored,omitempty"` State string `json:"state"` ArmedAt time.Time `json:"armed_at"` @@ -122,9 +132,14 @@ func (f FollowThrough) Live() bool { // Observation is what one poll of GitHub saw. type Observation struct { - Now time.Time - Head string - State string // open / closed + Now time.Time + Head string + State string // open / closed + // HeadByHive is true when Head (if it is not the approved head) was + // committed by the hive — the fixer's rebase or GitHub's update-branch + // under the App. A head somebody else pushed after the approval is new + // content, not a rebase, and the follow-through fails closed on it. + HeadByHive bool Merged bool MergeableState string // clean / unstable / blocked / dirty / behind / unknown // CIRed is true when a required check on Head failed. @@ -188,6 +203,9 @@ func (f *FollowThrough) fail(now time.Time, reason string, files []string) { f.FailReason = reason f.ConflictFiles = slices.Clone(files) f.Options = []string{OptionAdoptFresh, OptionCloseSuperseded} + if reason == FailForeignHead { + f.Options = []string{OptionReapprove, OptionCloseSuperseded} + } f.step(now, StepFailed, reason) } @@ -234,6 +252,12 @@ func Advance(f *FollowThrough, obs Observation, d Deadlines) Action { } head := strings.TrimSpace(obs.Head) if head != "" && head != f.ApprovedHead && head != f.RebasedHead { + if !f.HiveAuthored && !obs.HeadByHive { + f.ForeignHead = head + f.fail(now, FailForeignHead, nil) + f.Steps[len(f.Steps)-1].Detail = "head " + short(head) + " was pushed by someone other than the hive; the approval was for " + short(f.ApprovedHead) + return ActionFail + } f.RebasedHead = head f.State = StateCIPending f.step(now, StepRebased, "new head "+short(head)+" onto "+f.Base) @@ -314,6 +338,8 @@ func (f FollowThrough) FailureText() string { return fmt.Sprintf("#%d was closed before the hive could merge it.", f.Number) case FailNotReachable: return fmt.Sprintf("The hive cannot push to #%d's head (fork without maintainer edits).", f.Number) + case FailForeignHead: + return fmt.Sprintf("#%d's head moved after your approval, and not by the hive's rebase: someone pushed %s. Your approval was for %s, so nothing merged; read the new head and approve it again.", f.Number, nonEmpty(short(f.ForeignHead), "a new head"), nonEmpty(short(f.ApprovedHead), "the head you saw")) } return fmt.Sprintf("Rebase-then-merge of #%d failed: %s.", f.Number, f.FailReason) } diff --git a/src/pkg/rebasemerge/rebasemerge_test.go b/src/pkg/rebasemerge/rebasemerge_test.go index a0614a84cc..91bfe644de 100644 --- a/src/pkg/rebasemerge/rebasemerge_test.go +++ b/src/pkg/rebasemerge/rebasemerge_test.go @@ -3,6 +3,7 @@ package rebasemerge import ( "os" "path/filepath" + "strings" "testing" "time" ) @@ -73,7 +74,7 @@ func TestAdvanceConflictFailsWithFilesAndOptions(t *testing.T) { // A rebased head that goes dirty again fails as a conflict once the // fixer's attempts are exhausted. g := Arm("o/r", 3, "op", "v5", "aaaa111", false, now) - Advance(&g, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "blocked"}, Deadlines{}) + Advance(&g, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "blocked", HeadByHive: true}, Deadlines{}) if a := Advance(&g, Observation{Now: now.Add(2 * time.Minute), Head: "bbbb222", State: "open", MergeableState: "dirty", RebaseExhausted: true}, Deadlines{}); a != ActionFail || g.FailReason != FailConflict { t.Fatalf("re-dirty: action=%q reason=%q", a, g.FailReason) } @@ -332,3 +333,38 @@ func TestStoreAndAttemptsPersistenceEdges(t *testing.T) { t.Fatal("corrupt attempts loaded an episode") } } + +// The approval is bound to the head the operator read. A new head on a +// contributor's PR counts as the rebase only when the hive produced it; a +// head somebody else pushed fails closed with "approve the new head" as +// the way out, and nothing merges. The hive's own PR needs no such check. +func TestAdvanceForeignHeadFailsClosed(t *testing.T) { + now := time.Date(2026, 10, 29, 9, 0, 0, 0, time.UTC) + f := Arm("o/r", 4, "op", "v5", "aaaa111", false, now) + f.Kicked(now, "fixer") + if a := Advance(&f, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "clean"}, Deadlines{}); a != ActionFail { + t.Fatalf("foreign head: action=%q", a) + } + if f.State != StateFailed || f.FailReason != FailForeignHead || f.ForeignHead != "bbbb222" || f.RebasedHead != "" { + t.Fatalf("failed: %+v", f) + } + if len(f.Options) != 2 || f.Options[0] != OptionReapprove || f.Options[1] != OptionCloseSuperseded { + t.Fatalf("options=%v", f.Options) + } + if got := f.FailureText(); !strings.Contains(got, "someone pushed bbbb222") || !strings.Contains(got, "approval was for aaaa111") || !strings.Contains(got, "nothing merged") { + t.Fatalf("text=%q", got) + } + if last := f.Steps[len(f.Steps)-1]; last.Step != StepFailed || !strings.Contains(last.Detail, "someone other than the hive") { + t.Fatalf("last step=%+v", last) + } + // The hive's rebase of the same PR is the expected path. + g := Arm("o/r", 5, "op", "v5", "aaaa111", false, now) + if a := Advance(&g, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "blocked", HeadByHive: true}, Deadlines{}); a != ActionNone || g.State != StateCIPending || g.RebasedHead != "bbbb222" { + t.Fatalf("hive head: action=%q state=%q head=%q", a, g.State, g.RebasedHead) + } + // A hive-authored PR: any new head is the hive's own lane at work. + h := Arm("o/r", 6, "op", "v5", "aaaa111", true, now) + if a := Advance(&h, Observation{Now: now.Add(time.Minute), Head: "bbbb222", State: "open", MergeableState: "blocked"}, Deadlines{}); a != ActionNone || h.State != StateCIPending { + t.Fatalf("hive-authored: action=%q state=%q", a, h.State) + } +} From 671fc2ca055e5a54e335782042d3776a35a1c85d Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 21:42:16 -0400 Subject: [PATCH 06/10] merge train: hand a dirty member to the fixer's rebase-resolve episode; the exhausted row's rebase-then-merge option goes live v5 landed the conflict-aware merge train (#15157) with a RebaseResolver hook reserved for this PR and a duplicate rebaseMergeFollowThroughLabel. The hook now opens the shared rebase episode (requested_by: merge-train); the mergeNowWired flag and its disabled reason go, since the option it guarded is wired here. Signed-off-by: Andrew Anderson --- changelog.d/fixed-rebase-then-merge.md | 2 +- src/cmd/hive/main.go | 13 +++++++--- src/cmd/hive/merge_eligibility.go | 5 ++++ src/docs/operator-reference.md | 2 +- .../dashboard/stage_tracker_merge_train.go | 24 ++++--------------- .../stage_tracker_merge_train_test.go | 7 ++---- .../github/automerge/automerge_merge_train.go | 13 +++++----- 7 files changed, 30 insertions(+), 36 deletions(-) diff --git a/changelog.d/fixed-rebase-then-merge.md b/changelog.d/fixed-rebase-then-merge.md index 5a07ac1c5a..febf6fa6e6 100644 --- a/changelog.d/fixed-rebase-then-merge.md +++ b/changelog.d/fixed-rebase-then-merge.md @@ -1,3 +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 ([#15103](https://github.com/hivecommons/hive/issues/15103)). +- 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)). diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 5af466ce29..de6d1cfeb0 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -70,6 +70,7 @@ import ( "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" @@ -2571,9 +2572,15 @@ func (b *boot) bootAgentsWith(deps bootAgentsDeps) { 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 diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 3bcb7de810..b0296fff89 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -824,6 +824,11 @@ func hiveAuthoredPR(pr github.PullRequest) bool { // 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 diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 8f25a8ce18..0f96501bd4 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -431,7 +431,7 @@ advanced into the merge path. | `auto_merge.human_merge_paths` | unset | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge, e.g. `Danathar/goodreads-mcp: [".claude/settings.json", ".claude/hooks/**"]`. Every App merge path honors it: the automerge sweep lanes (App self-merge, trusted-author, label-queued) and the agent merge-request relay refuse a PR that touches a listed path, add `hold`, and post one `` comment naming the path(s); a person must merge it. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). | | `auto_merge.require_current_base` | unset (off) | Repo list (`owner/repo`) whose App self-merge, trusted-author and contributor lanes only merge a head that contains the current base tip. A green head tested against an older base is updated with GitHub update-branch (a merge commit; no author commit is rewritten) and merges once CI is green on the new head, so a semantic conflict with work merged since turns that PR red instead of breaking the base (#13634). Costs one compare call per merge candidate. | | `auto_merge.merge_forward_trusted_human` | unset (off) | Repo list (`owner/repo`) where a `role/trusted` + `author/human` PR on a same-repo branch that GitHub reports as conflicting (`dirty`) gets the base merged into its head as one App-authored, signed-off merge commit via the GitHub merges API (no human commit is rewritten), then merges once CI is green on the new head. A real conflict pushes nothing and posts one `` note naming the files both sides changed. Fork heads are never written. Attempted once per head (#13636). | -| `auto_merge.merge_train.enabled` | `true` | Conflict-aware merge train in every automerge lane (hive, trusted-author, contributor) ([#15117](https://github.com/hivecommons/hive/issues/15117)). Each sweep groups the open approved / mergeable-pending PRs of one repo+base by overlapping changed files (`GET /pulls/{n}/files`, cached per head SHA) and lets ONE front per group merge — the clean-mergeable PR approved earliest — while the others wait at stage/080 with lane reason `merge-train:queued-behind#:/:…` (tracker pill "In merge train · 3rd of 4", never a human stage, never `needs-rebase` as a human flag). The moment the front merges, every sibling whose branch is merely `behind` gets `PUT /pulls/{n}/update-branch`; a `dirty` one is handed to the rebase-resolve hook (the #15104 task; until it lands the dirty PR falls through to the plain `conflicting` path, logged once). A head the lane last saw blocked on its own (red required check, terminal hold, permanent merge refusal) never fronts, and a group whose best member is blocked imposes no ordering (fail-open) — nobody waits behind a PR that is not moving. One INFO line `merge train` per order change, not per cycle. `false` restores independent per-PR evaluation. | +| `auto_merge.merge_train.enabled` | `true` | Conflict-aware merge train in every automerge lane (hive, trusted-author, contributor) ([#15117](https://github.com/hivecommons/hive/issues/15117)). Each sweep groups the open approved / mergeable-pending PRs of one repo+base by overlapping changed files (`GET /pulls/{n}/files`, cached per head SHA) and lets ONE front per group merge — the clean-mergeable PR approved earliest — while the others wait at stage/080 with lane reason `merge-train:queued-behind#:/:…` (tracker pill "In merge train · 3rd of 4", never a human stage, never `needs-rebase` as a human flag). The moment the front merges, every sibling whose branch is merely `behind` gets `PUT /pulls/{n}/update-branch`; a `dirty` one is handed to the fixer's rebase-resolve episode (`requested_by: merge-train`, the shared two-attempt guard of [#15104](https://github.com/hivecommons/hive/pull/15104); the fixer router still requires a head the hive can push to, so a fork without maintainer edits stays on the plain `conflicting` path for a person). A head the lane last saw blocked on its own (red required check, terminal hold, permanent merge refusal) never fronts, and a group whose best member is blocked imposes no ordering (fail-open) — nobody waits behind a PR that is not moving. One INFO line `merge train` per order change, not per cycle. `false` restores independent per-PR evaluation. | | `auto_merge.merge_train.max_rebase_attempts` | `2` | Loop guard: how many rebase-resolve requests the train makes for one PR behind one front. Past it the PR moves to stage/085 with the pill "Needs human decision · rebase failed twice" and the decision option "Rebase, then merge as maintainer". | | `auto_merge.squash_only` | unset (no repo) | Repo list (`owner/repo`) whose branch policy forbids merge commits. Elsewhere, a `role/trusted` PR whose head mixes the contributor's commits with App-linked, App-signed ones (the hive's own in-place adoption fixes), every commit self-signed, is labelled `merge-method/merge` and merged with a merge commit instead of parking at `stage/085` as `adoption-stalled:hive-signoff-attribution`; a listed repo keeps squash-only policy and re-homes an in-place adoption to an App-authored superseder instead (#13975). | | `auto_merge.credit_issue_authors` | `true` | Append `Co-authored-by: ` for the human authors of the issues a PR closes (`Fixes|Closes|Resolves #N`) to the squash (or merge) commit message on every hive-performed merge, so reporters land on the contributor graph when an external clanker fixed their issue. Bots, the PR author and logins already credited on the branch are skipped; the logins are recorded as `issue_authors=` on the merge audit entry and in review evidence. One cached `GET /issues/{n}` per newly referenced issue. `false` leaves GitHub's default squash message untouched (#14581). | diff --git a/src/pkg/dashboard/stage_tracker_merge_train.go b/src/pkg/dashboard/stage_tracker_merge_train.go index 6fa204a18a..7dfa05cd33 100644 --- a/src/pkg/dashboard/stage_tracker_merge_train.go +++ b/src/pkg/dashboard/stage_tracker_merge_train.go @@ -193,9 +193,8 @@ func stageTrackerMergeTrainCaption(reason string) string { // decisionForMergeTrain: the train gave up rebasing this PR after the loop // guard (hivecommons/hive#15117). The lead option is the rebase-then-merge -// follow-through; until that follow-through (hivecommons/hive#15104) is -// wired the option is offered disabled with the honest reason, and the -// row menu's usual decision options remain. +// follow-through (hivecommons/hive#15104): the click records the approval, +// re-opens the rebase episode in the operator's name and merges on green. func decisionForMergeTrain(it StageTrackerItem, held bool) *StageTrackerDecision { mt := it.MergeTrain d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByLane, BlockerReason: it.Reason} @@ -208,25 +207,12 @@ func decisionForMergeTrain(it StageTrackerItem, held bool) *StageTrackerDecision if held { d.Blocker += " " + decisionHeldBlocker(it.Hold) } - mergeWhy := decisionWhyMergeNowUnwired - if held { - mergeWhy = decisionWhyHeld - } + mergeNow := decisionOption(decisionActionMergeNow, rebaseMergeFollowThroughLabel, !held, decisionWhyHeld) + mergeNow.Consequence = rebaseMergeFollowThroughConsequence(it.Number, strings.TrimSpace(it.BaseRef)) d.Options = []StageTrackerDecisionOption{ - decisionOption(decisionActionMergeNow, rebaseMergeFollowThroughLabel, mergeNowWired && !held, mergeWhy), + mergeNow, decisionOption(decisionActionCloseSuperseded, "Close as superseded", !held, decisionWhyHeld), decisionHoldOption(held), } return d } - -// rebaseMergeFollowThroughLabel is the option's wording. -const rebaseMergeFollowThroughLabel = "Rebase, then merge as maintainer" - -// mergeNowWired flips true once decide:merge-now rebases a conflicting head -// before merging (hivecommons/hive#15104). The #15087 handler merges a -// mergeable head only, so on a rebase-exhausted (dirty) PR the option is -// offered disabled with the honest reason. -var mergeNowWired = false - -const decisionWhyMergeNowUnwired = "Rebase-then-merge is not wired in this hive yet (#15104); rebase the branch on GitHub, then approve & merge as maintainer" diff --git a/src/pkg/dashboard/stage_tracker_merge_train_test.go b/src/pkg/dashboard/stage_tracker_merge_train_test.go index c090d65355..b5686f2f4b 100644 --- a/src/pkg/dashboard/stage_tracker_merge_train_test.go +++ b/src/pkg/dashboard/stage_tracker_merge_train_test.go @@ -95,8 +95,8 @@ func TestStageTrackerMergeTrainPayload(t *testing.T) { if d == nil || len(d.Options) == 0 || d.Options[0].Action != decisionActionMergeNow || d.Options[0].Label != rebaseMergeFollowThroughLabel { t.Fatalf("exhausted decision = %+v", d) } - if d.Options[0].Enabled || d.Options[0].ReasonIfDisabled != decisionWhyMergeNowUnwired { - t.Fatalf("merge-now must be offered disabled with the honest reason until #15104 lands: %+v", d.Options[0]) + if !d.Options[0].Enabled || d.Options[0].Consequence != rebaseMergeFollowThroughConsequence(15097, "v5") { + t.Fatalf("merge-now leads as the rebase-then-merge follow-through: %+v", d.Options[0]) } if !strings.Contains(d.Question, "could not rebase this PR onto the merged front #15074 after 2 attempts") { t.Fatalf("question = %q", d.Question) @@ -157,9 +157,6 @@ func TestStageTrackerMergeTrainCaptions(t *testing.T) { var nilItem *StageTrackerItem stageTrackerApplyMergeTrain(nilItem) stageTrackerApplyMergeTrain(&StageTrackerItem{Kind: "issue", Reason: cases[0].reason}) - if mergeNowWired { - t.Fatal("merge-now is not wired until hivecommons/hive#15104 lands") - } } // TestStageTrackerMergeTrainSPA runs the SPA's train helpers under node: diff --git a/src/pkg/github/automerge/automerge_merge_train.go b/src/pkg/github/automerge/automerge_merge_train.go index 2ff376c83e..dbc776af04 100644 --- a/src/pkg/github/automerge/automerge_merge_train.go +++ b/src/pkg/github/automerge/automerge_merge_train.go @@ -66,13 +66,12 @@ type RebaseRequest struct { Lane string } -// RebaseResolver enqueues a rebase-resolve task for a conflicting PR. The -// rebase-then-merge follow-through (hivecommons/hive#15104, pkg/rebasemerge) -// is the intended implementation: cmd/hive adapts its store here so the -// fixer lane rebases the head and the dashboard ticker merges it on green. -// TODO(hivecommons/hive#15104): wire pkg/rebasemerge.Store as the resolver -// once it lands; until then a nil resolver leaves a dirty front on its -// normal `conflicting` path and logs the gap once per PR head. +// RebaseResolver enqueues a rebase-resolve task for a conflicting PR. +// cmd/hive adapts pkg/rebasemerge's attempts ledger here (hivecommons/hive#15104): +// the request opens the fixer's rebase episode and the lane merges the clean +// head on its next pass. A resolver that returns an error, or a nil +// resolver, leaves the dirty PR on its normal `conflicting` path, logged +// once per PR head. type RebaseResolver interface { RequestRebase(ctx context.Context, req RebaseRequest) error } From 00ae7acee32c8f5bc93add2d0a9072bf0d443f9a Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 22:03:25 -0400 Subject: [PATCH 07/10] test: approve toast wording follows #15213 Signed-off-by: Andrew Anderson --- src/pkg/dashboard/rebase_merge_followthrough_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pkg/dashboard/rebase_merge_followthrough_test.go b/src/pkg/dashboard/rebase_merge_followthrough_test.go index 70264f82b4..f4acbcfdd7 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough_test.go +++ b/src/pkg/dashboard/rebase_merge_followthrough_test.go @@ -321,7 +321,7 @@ func TestRepoItemDecisionApproveOnDirtyPRQueuesRebase(t *testing.T) { w = postRepoItemDecisionAs(t, srv3, 8, "writer", "merger", `{"decision":"approve","type":"pr"}`) resp = repoItemDecisionResponse{} _ = json.Unmarshal(w.Body.Bytes(), &resp) - if w.Code != http.StatusOK || resp.Rebase != nil || resp.Result == nil || len(resp.Result.Options) != 0 || !strings.Contains(resp.Result.Next, "takes it from here") { + if w.Code != http.StatusOK || resp.Rebase != nil || resp.Result == nil || len(resp.Result.Options) != 0 || !strings.Contains(resp.Result.Next, "merge sweep merges it") { t.Fatalf("clean approve: code=%d resp=%+v", w.Code, resp.Result) } } From 1a9efd5df5b0eb7f3bd4621e3aad897b8e17a681 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 22:15:08 -0400 Subject: [PATCH 08/10] rebase onto v5: drop duplicate nonEmptyString, lift STAGE_TRACKER_ICONS for the history badge in the rebase-then-merge row test Signed-off-by: Andrew Anderson --- src/pkg/dashboard/rebase_merge_followthrough.go | 7 ------- src/pkg/dashboard/stage_tracker_row_actions_test.go | 2 +- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/pkg/dashboard/rebase_merge_followthrough.go b/src/pkg/dashboard/rebase_merge_followthrough.go index 8421f3ec94..5c821c6415 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough.go +++ b/src/pkg/dashboard/rebase_merge_followthrough.go @@ -54,13 +54,6 @@ func rebaseMergeFollowThroughConsequence(number int, base string) string { return fmt.Sprintf("hive rebases #%d onto %s, waits for CI, then merges it with your approval on record; you'll get a toast when it lands or if the rebase conflicts", number, nonEmptyString(base, "its base branch")) } -func nonEmptyString(s, fallback string) string { - if strings.TrimSpace(s) == "" { - return fallback - } - return s -} - // armRebaseThenMerge is the merge-now branch for a PR that needs a rebase. // Order matters: the approval is posted first (the durable record the // merge carries), then the follow-through is armed, then the rebase is diff --git a/src/pkg/dashboard/stage_tracker_row_actions_test.go b/src/pkg/dashboard/stage_tracker_row_actions_test.go index 1c24371113..56813b7f91 100644 --- a/src/pkg/dashboard/stage_tracker_row_actions_test.go +++ b/src/pkg/dashboard/stage_tracker_row_actions_test.go @@ -1398,7 +1398,7 @@ assert.strictEqual(stageTrackerDCOCaveat([]), ''); // (hivecommons/hive#14822). func TestStageTrackerRebaseThenMergeRow(t *testing.T) { html := indexHTML(t) - runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+"\n"+stageTrackerCuesJS(t, html)+stageTrackerActedJS(t, html)+"\n"+jsFunc(t, html, "agentNowClockTime")+` + runStageTrackerRowActionsScript(t, stageTrackerRowActionsPreamble(t, html)+"\n"+stageTrackerCuesJS(t, html)+jsConstBlock(t, html, "STAGE_TRACKER_ICONS")+"\n"+stageTrackerActedJS(t, html)+"\n"+jsFunc(t, html, "agentNowClockTime")+` global.window = { _hiveUser: 'clubanderson' }; const ids = as => as.map(a => a.id); const merger = { user: true, canHold: true, canHuman: true }; From f7c109fceec091689f3591f629a57dd138c3890f Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 23:56:50 -0400 Subject: [PATCH 09/10] writeback ratchet: baseline the two operator-solicited comments of the rebase-then-merge follow-through Signed-off-by: Andrew Anderson --- src/pkg/dashboard/rebase_merge_followthrough.go | 3 +++ src/pkg/writeback/testdata/direct-writes-baseline.txt | 1 + 2 files changed, 4 insertions(+) diff --git a/src/pkg/dashboard/rebase_merge_followthrough.go b/src/pkg/dashboard/rebase_merge_followthrough.go index 5c821c6415..9048d32c0c 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough.go +++ b/src/pkg/dashboard/rebase_merge_followthrough.go @@ -91,6 +91,8 @@ func (s *Server) armRebaseThenMerge(ctx context.Context, w http.ResponseWriter, jsonError(w, "arming the rebase-then-merge follow-through: "+err.Error(), http.StatusInternalServerError) return } + // Solicited: the operator asked for this from the dashboard, so the + // write-back gate does not apply (pkg/writeback doc; ratchet baseline). if err := gh.CreateIssueComment(ctx, repoFull, number, renderRebaseThenMergeComment(user, comment, number, st.BaseRef)); err != nil && s.logger != nil { s.logger.Warn("rebase-then-merge: posting note failed", "repo", repoFull, "number", number, "error", err) } @@ -274,6 +276,7 @@ func (s *Server) settleRebaseMergeLedger(ctx context.Context, f rebasemerge.Foll _, _ = s.operatorActions().Settle(f.Repo, f.Number, operatorActionMergeNow, operatorActionOutcomeApplied, "merged "+rebaseMergeShortSHA(f.MergeSHA)+" after rebase") case rebasemerge.StateFailed: _, _ = s.operatorActions().Settle(f.Repo, f.Number, operatorActionMergeNow, operatorActionOutcomeFailed, f.FailureText()) + // The outcome note of that same operator request: solicited, ungated. if f.FailReason != rebasemerge.FailClosed && s.deps != nil && s.deps.GHClient != nil { if err := s.deps.GHClient.CreateIssueComment(ctx, f.Repo, f.Number, renderRebaseThenMergeFailedComment(f)); err != nil && s.logger != nil { s.logger.Warn("rebase-then-merge: posting failure note failed", "repo", f.Repo, "number", f.Number, "error", err) diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index d677e9b974..d6f045869d 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -76,6 +76,7 @@ wrap pkg/dashboard/contribute_verdict_settle.go 4 wrap pkg/dashboard/contribute_wrong_base.go 1 wrap pkg/dashboard/plan_handlers.go 2 wrap pkg/dashboard/plan_mirror.go 1 +wrap pkg/dashboard/rebase_merge_followthrough.go 2 wrap pkg/forge/gitea_forge.go 2 wrap pkg/forge/github_forge.go 3 wrap pkg/forge/gitlab_forge.go 2 From 3b401b0fa55784a6dc2f7e83849c67cadb7cac8d Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Thu, 29 Oct 2026 00:09:44 -0400 Subject: [PATCH 10/10] automerge: superseded question precedes the label block (#15278) while a needs-rebase label on a merely-behind head stays stale Signed-off-by: Andrew Anderson --- src/pkg/github/automerge/automerge_sweep_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/pkg/github/automerge/automerge_sweep_test.go b/src/pkg/github/automerge/automerge_sweep_test.go index 308c962160..6ceb5875ce 100644 --- a/src/pkg/github/automerge/automerge_sweep_test.go +++ b/src/pkg/github/automerge/automerge_sweep_test.go @@ -3293,10 +3293,12 @@ func TestSweepSelfAuthoredNeedsRebaseLabelAsksSupersededCloser(t *testing.T) { var merged []int var updates int api := newSelfAuthoredAutoMergeAPI(t, []selfAuthoredPR{{ - number: 15208, - author: testHiveAppBotLogin, - extraLabels: []string{"needs-rebase"}, - mergeableState: "behind", + number: 15208, + author: testHiveAppBotLogin, + extraLabels: []string{"needs-rebase"}, + // dirty, not behind: a needs-rebase label on a merely-behind head is + // stale and the lane updates the branch instead (hivecommons/hive#15103). + mergeableState: "dirty", updateCount: &updates, }}, &merged) defer api.Close()