From ca66158021f92461d41d640714bf036a1721e914 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:41:20 -0500 Subject: [PATCH 1/2] fix: stop posting refused @dependabot commands; update or close stale Dependabot PRs Dependabot refuses @dependabot rebase/recreate from the hive App and refuses rebase on a branch someone else pushed to (the NOTICE autofix). The automerge sweep and the scanner prompt no longer post those commands. A behind Dependabot PR is updated with the update-branch API; a conflicting one is left to Dependabot's own rebase unless it was edited by others, in which case it is closed once per head so Dependabot opens a fresh PR. Refs #18441 Co-Authored-By: Claude Opus 5.5 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> --- changelog.d/fixed-stale-dependabot-prs.md | 1 + .../automerge/automerge_current_base_test.go | 5 +- .../automerge/automerge_dependabot_stale.go | 194 ++++++++++++++++ .../automerge_dependabot_stale_test.go | 219 ++++++++++++++++++ .../github/automerge/automerge_held_runs.go | 53 ++--- .../automerge/automerge_held_runs_test.go | 25 +- .../automerge/automerge_sweep_trusted.go | 16 +- src/pkg/scheduler/lane_messages.go | 2 +- .../testdata/direct-writes-baseline.txt | 2 +- 9 files changed, 466 insertions(+), 51 deletions(-) create mode 100644 changelog.d/fixed-stale-dependabot-prs.md create mode 100644 src/pkg/github/automerge/automerge_dependabot_stale.go create mode 100644 src/pkg/github/automerge/automerge_dependabot_stale_test.go diff --git a/changelog.d/fixed-stale-dependabot-prs.md b/changelog.d/fixed-stale-dependabot-prs.md new file mode 100644 index 0000000000..19f38bee12 --- /dev/null +++ b/changelog.d/fixed-stale-dependabot-prs.md @@ -0,0 +1 @@ +- Stale Dependabot PRs no longer get stuck behind refused `@dependabot rebase` comments: the hive never posts Dependabot commands (Dependabot ignores them from the App), updates a merely-behind Dependabot PR with the update-branch API, leaves a conflicting one to Dependabot's own rebase, and closes a conflicting one whose branch someone else pushed to so Dependabot opens a fresh PR (#18441). diff --git a/src/pkg/github/automerge/automerge_current_base_test.go b/src/pkg/github/automerge/automerge_current_base_test.go index c02d0819cf..db046a91d3 100644 --- a/src/pkg/github/automerge/automerge_current_base_test.go +++ b/src/pkg/github/automerge/automerge_current_base_test.go @@ -186,7 +186,8 @@ func currentBaseTestPR(fork bool, headRef, author, mergeableState string) *gh.Pu // committed to it). A repo listed in auto_merge.require_current_base, or a // head GitHub itself reports behind under its up-to-date rule, holds as // "behind" for the bot to rebase; a repo gated only by the hive-wide default -// merges it as tested. An ordinary PR on the same repo is still updated. +// merges it as tested. An ordinary PR on the same repo is still updated, and +// so is a Dependabot PR, which never rebases a merely-behind branch (#18441). func TestCurrentBaseGateLeavesDependencyBotBranchToTheBot(t *testing.T) { const head = "sha-head" cases := []struct { @@ -199,7 +200,7 @@ func TestCurrentBaseGateLeavesDependencyBotBranchToTheBot(t *testing.T) { }{ {name: "renovate bot on a listed repo holds", pr: currentBaseTestPR(false, "renovate/actions-checkout-5.x", "renovate[bot]", "clean"), strict: true, wantStop: true, wantReason: "behind"}, {name: "renovate head ref under another account holds", pr: currentBaseTestPR(false, "renovate/go-deps", "castrojo", "clean"), strict: true, wantStop: true, wantReason: "behind"}, - {name: "dependabot author holds", pr: currentBaseTestPR(false, "dependabot/npm_and_yarn/x", "dependabot[bot]", "clean"), strict: true, wantStop: true, wantReason: "behind"}, + {name: "dependabot author is updated by the App (#18441)", pr: currentBaseTestPR(false, "dependabot/npm_and_yarn/x", "dependabot[bot]", "behind"), strict: true, wantStop: true, wantReason: basePreparationReady, wantUpdates: 1}, {name: "github up-to-date rule holds on a default-gated repo", pr: currentBaseTestPR(false, "renovate/x", "renovate[bot]", "behind"), wantStop: true, wantReason: "behind"}, {name: "default-gated repo merges as tested", pr: currentBaseTestPR(false, "renovate/x", "renovate[bot]", "clean")}, {name: "ordinary PR is still updated", pr: currentBaseTestPR(false, "feature", "alice", "behind"), strict: true, wantStop: true, wantReason: basePreparationReady, wantUpdates: 1}, diff --git a/src/pkg/github/automerge/automerge_dependabot_stale.go b/src/pkg/github/automerge/automerge_dependabot_stale.go new file mode 100644 index 0000000000..3a58809680 --- /dev/null +++ b/src/pkg/github/automerge/automerge_dependabot_stale.go @@ -0,0 +1,194 @@ +package automerge + +// Stale Dependabot PRs (hivecommons/hive#18441). +// +// Dependabot only honours `@dependabot rebase` / `recreate` from users with +// push access, which the hive's GitHub App never is ("Sorry, only users with +// push access can use that command"), and it refuses `rebase` from anyone +// once another identity has pushed to the branch (the NOTICE autofix commit: +// "this PR has been edited by someone other than Dependabot"). Posting either +// command therefore cannot move the PR, and re-posting it every pass is noise. +// The hive never posts them. Instead the trusted-bot lane decides: +// +// - behind (no conflicts): GitHub's update-branch API, which the App can +// call. Dependabot, unlike Renovate, does not rebase a branch that is +// merely behind, so leaving it to the bot strands it under an up-to-date +// rule (hgithub.DependencyBotBranch still covers Renovate and the +// merge-forward / merge-train paths). +// - conflicting, only Dependabot's commits: leave it; Dependabot rebases +// conflicting branches itself. +// - conflicting, edited by others: Dependabot will never rebase it, and the +// App cannot resolve conflicts, so the PR is closed once with a note. +// Dependabot opens a fresh PR for the next release; a maintainer can +// comment `@dependabot recreate` to restore this one now. + +import ( + "context" + "strconv" + "strings" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/effects" + hgithub "github.com/hivecommons/hive/pkg/github" +) + +// dependabotStaleDecision is what the trusted-bot lane does with a stale +// Dependabot PR. +type dependabotStaleDecision int + +const ( + // dependabotStaleNone: the PR is neither behind nor conflicting. + dependabotStaleNone dependabotStaleDecision = iota + // dependabotStaleUpdateBranch: behind only; merge the base in with the + // update-branch API. + dependabotStaleUpdateBranch + // dependabotStaleLeaveToBot: conflicting, but Dependabot still owns every + // commit and rebases the branch itself. + dependabotStaleLeaveToBot + // dependabotStaleClose: conflicting and edited by someone other than + // Dependabot; nothing the App may do can rebase it. + dependabotStaleClose +) + +const ( + // dependabotStaleClosedReason is the lane reason on the tick that closed + // a stale Dependabot PR. + dependabotStaleClosedReason = "closed" + // dependabotStaleCloseKey keys the once-per-head close attempt in + // terminalHoldLogged. + dependabotStaleCloseKey = "dependabot-stale-close" + // dependabotStaleCloseMarker tags the hive's closing note. + dependabotStaleCloseMarker = "" + dependabotCommitsPageSize = 100 +) + +// decideDependabotStale maps a Dependabot PR's mergeable_state and whether +// anyone other than Dependabot committed to the branch onto the lane's action. +func decideDependabotStale(mergeableState string, editedByOthers bool) dependabotStaleDecision { + switch strings.ToLower(strings.TrimSpace(mergeableState)) { + case "behind": + return dependabotStaleUpdateBranch + case "dirty", "conflicting": + if editedByOthers { + return dependabotStaleClose + } + return dependabotStaleLeaveToBot + } + return dependabotStaleNone +} + +// isDependabotPR reports whether pr was opened by Dependabot on a branch the +// hive may update through the App (never a renovate/ head ref). +func isDependabotPR(pr *gh.PullRequest) bool { + if pr == nil { + return false + } + if strings.HasPrefix(strings.TrimSpace(pr.GetHead().GetRef()), "renovate/") { + return false + } + return strings.EqualFold(hgithub.SafeGetLogin(pr.GetUser()), dependabotLogin) +} + +// dependabotUpdateBranchAllowed reports whether a base-sync step may update a +// Dependabot branch with the App instead of leaving it to the bot: only the +// update-branch steps, never a merge-forward or merge-train rebase. +func dependabotUpdateBranchAllowed(pr *gh.PullRequest, step string) bool { + return (step == "update-branch" || step == "current-base") && isDependabotPR(pr) +} + +// isDependabotCommit reports whether a PR commit was authored by Dependabot. +func isDependabotCommit(commit *gh.RepositoryCommit) bool { + if commit == nil { + return false + } + if strings.EqualFold(hgithub.SafeGetLogin(commit.GetAuthor()), dependabotLogin) { + return true + } + return strings.EqualFold(commit.GetCommit().GetAuthor().GetName(), dependabotLogin) +} + +// dependabotEditedByOthers reports whether any commit on the PR was authored +// by someone other than Dependabot (an autofix push, an App update-branch +// merge, a human), which makes Dependabot refuse to rebase it. +func (c *Engine) dependabotEditedByOthers(ctx context.Context, owner, repo string, number int) (bool, error) { + opts := &gh.ListOptions{PerPage: dependabotCommitsPageSize} + for { + commits, resp, err := c.gh.PullRequests.ListCommits(hgithub.WithRESTCaller(ctx, "hive:automerge_sweep"), owner, repo, number, opts) + if err != nil { + return false, err + } + for _, commit := range commits { + if !isDependabotCommit(commit) { + return true, nil + } + } + if resp == nil || resp.NextPage == 0 { + return false, nil + } + opts.Page = resp.NextPage + } +} + +// resolveConflictingDependabotPR handles a conflicting Dependabot PR on the +// trusted-bot lane. It returns the lane reason and true when pr is a +// Dependabot PR; false leaves the caller's "conflicting" hold in place. +func (c *Engine) resolveConflictingDependabotPR(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, number int, headSHA string) (string, bool) { + if c == nil || c.gh == nil || !isDependabotPR(pr) { + return "", false + } + edited, err := c.dependabotEditedByOthers(ctx, owner, repo, number) + if err != nil { + c.warn("automerge could not list Dependabot PR commits", "repo", displayRepo, "pr", number, "sha", headSHA, "error", err) + return "conflicting", true + } + if decideDependabotStale(pr.GetMergeableState(), edited) != dependabotStaleClose { + return "conflicting", true + } + if !c.markTerminalHoldLogged(owner, repo, number, headSHA, dependabotStaleCloseKey) { + // Already attempted for this head; never repeat the note. + return "conflicting", true + } + if c.closeStaleDependabotPR(ctx, displayRepo, owner, repo, number, headSHA) { + return dependabotStaleClosedReason, true + } + return "conflicting", true +} + +func dependabotStaleCloseNote() string { + return dependabotStaleCloseMarker + "\n" + + "Closing: this Dependabot PR conflicts with its base, and its branch has commits not authored by Dependabot, so Dependabot will not rebase it " + + "(and it ignores `@dependabot` commands from the hive App). Dependabot opens a fresh PR for the next release; " + + "a maintainer can comment `@dependabot recreate` to restore this one now." +} + +// closeStaleDependabotPR posts the closing note and closes the PR. It reports +// whether the close went through. Both writes are solicited: the operator +// listed dependabot[bot] as a trusted bot, handing its PRs to this lane. +func (c *Engine) closeStaleDependabotPR(ctx context.Context, displayRepo, owner, repo string, number int, headSHA string) bool { + restCtx := hgithub.WithRESTCaller(ctx, "hive:automerge_sweep") + note := dependabotStaleCloseNote() + _, err := effects.Execute(ctx, c.mutation, effects.Claim{ + Repo: owner + "/" + repo, + Kind: effects.KindIssueComment, + Target: strconv.Itoa(number), + Actor: "automerge", + Inputs: map[string]string{"head_sha": headSHA, "body": effects.StableDigest(note)}, + }, func(ctx context.Context) (effects.Result, error) { + posted, _, apiErr := c.gh.Issues.CreateComment(hgithub.WithRESTCaller(ctx, "hive:automerge_sweep"), owner, repo, number, &gh.IssueComment{Body: gh.Ptr(note)}) // writeback:solicited trusted-bot lane + if apiErr != nil { + return effects.Result{}, effects.NotApplied(apiErr) + } + c.noteOwnStageComment(owner, repo, number) + return effects.Result{Provenance: posted.GetHTMLURL()}, nil + }) + if err != nil { + c.warn("automerge failed to post stale Dependabot close note", "repo", displayRepo, "pr", number, "sha", headSHA, "error", err) + } + if _, _, err := c.gh.PullRequests.Edit(restCtx, owner, repo, number, &gh.PullRequest{State: gh.Ptr("closed")}); err != nil { // writeback:solicited trusted-bot lane + c.warn("automerge failed to close stale Dependabot PR", "repo", displayRepo, "pr", number, "sha", headSHA, "error", err) + return false + } + c.info("automerge closed conflicting Dependabot PR edited by others; Dependabot opens a fresh one", + "repo", displayRepo, "pr", number, "sha", headSHA) + return true +} diff --git a/src/pkg/github/automerge/automerge_dependabot_stale_test.go b/src/pkg/github/automerge/automerge_dependabot_stale_test.go new file mode 100644 index 0000000000..9aecbd93f3 --- /dev/null +++ b/src/pkg/github/automerge/automerge_dependabot_stale_test.go @@ -0,0 +1,219 @@ +package automerge + +// Stale Dependabot PRs (hivecommons/hive#18441): behind -> App update-branch, +// conflicting with only Dependabot's commits -> left to Dependabot, +// conflicting and edited by others -> closed once. No `@dependabot` command +// is ever posted. + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + gh "github.com/google/go-github/v72/github" +) + +func TestDecideDependabotStale(t *testing.T) { + cases := []struct { + name string + state string + edited bool + want dependabotStaleDecision + }{ + {name: "behind is updated", state: "behind", want: dependabotStaleUpdateBranch}, + {name: "behind and edited by others is still updated", state: "behind", edited: true, want: dependabotStaleUpdateBranch}, + {name: "conflicting with only dependabot commits is left to the bot", state: "dirty", want: dependabotStaleLeaveToBot}, + {name: "conflicting state alias", state: "Conflicting", want: dependabotStaleLeaveToBot}, + {name: "conflicting and edited by others is closed", state: "dirty", edited: true, want: dependabotStaleClose}, + {name: "clean is untouched", state: "clean", edited: true, want: dependabotStaleNone}, + {name: "unknown is untouched", state: "", want: dependabotStaleNone}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := decideDependabotStale(tc.state, tc.edited); got != tc.want { + t.Fatalf("decideDependabotStale(%q, %v) = %v, want %v", tc.state, tc.edited, got, tc.want) + } + }) + } +} + +func TestDependabotUpdateBranchAllowed(t *testing.T) { + dependabot := currentBaseTestPR(false, "dependabot/go_modules/src/golang.org/x/image-0.48.0", "dependabot[bot]", "behind") + renovateRef := currentBaseTestPR(false, "renovate/x", "dependabot[bot]", "behind") + renovate := currentBaseTestPR(false, "renovate/x", "renovate[bot]", "behind") + for _, tc := range []struct { + name string + pr *gh.PullRequest + step string + want bool + }{ + {name: "dependabot update-branch", pr: dependabot, step: "update-branch", want: true}, + {name: "dependabot current-base", pr: dependabot, step: "current-base", want: true}, + {name: "dependabot merge-forward stays with the bot", pr: dependabot, step: "merge-forward"}, + {name: "dependabot merge-train stays with the bot", pr: dependabot, step: "merge-train"}, + {name: "renovate head ref", pr: renovateRef, step: "update-branch"}, + {name: "renovate", pr: renovate, step: "update-branch"}, + {name: "nil", step: "update-branch"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := dependabotUpdateBranchAllowed(tc.pr, tc.step); got != tc.want { + t.Fatalf("dependabotUpdateBranchAllowed = %v, want %v", got, tc.want) + } + }) + } +} + +// TestUpdateBranchAndSkipUpdatesBehindDependabotPR: a behind Dependabot PR is +// brought up to date with the App's update-branch call and no comment. +func TestUpdateBranchAndSkipUpdatesBehindDependabotPR(t *testing.T) { + const head = "sha-head" + var mu sync.Mutex + updates, comments := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if servePRCommitsSigned(w, r) { + return + } + mu.Lock() + defer mu.Unlock() + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7": + _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "open", "head": map[string]string{"sha": head}, "base": map[string]string{"ref": "main", "sha": "base1"}}) + case r.Method == http.MethodPut && r.URL.Path == "/repos/acme/widget/pulls/7/update-branch": + updates++ + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"message":"Updating pull request branch."}`)) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments"): + comments++ + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + c := newAutoMergeSweepClient(srv.URL) + pr := currentBaseTestPR(false, "dependabot/npm_and_yarn/x", "dependabot[bot]", "behind") + event, _, err := c.updateBranchAndSkip(context.Background(), "acme/widget", "acme", "widget", 7, head, "behind", pr) + if err != nil { + t.Fatalf("err = %v", err) + } + mu.Lock() + defer mu.Unlock() + if updates != 1 || !event.BranchUpdated { + t.Fatalf("update-branch calls = %d (BranchUpdated %v), want 1", updates, event.BranchUpdated) + } + if comments != 0 { + t.Fatalf("comments = %d, want 0", comments) + } +} + +type dependabotStaleAPI struct { + mu sync.Mutex + commits []map[string]any + comments []string + closes int +} + +func (a *dependabotStaleAPI) server(t *testing.T) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + a.mu.Lock() + defer a.mu.Unlock() + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7/commits": + _ = json.NewEncoder(w).Encode(a.commits) + case r.Method == http.MethodPost && r.URL.Path == "/repos/acme/widget/issues/7/comments": + var body struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + a.comments = append(a.comments, body.Body) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"html_url":"https://example.test/c/1"}`)) + case r.Method == http.MethodPatch && r.URL.Path == "/repos/acme/widget/pulls/7": + a.closes++ + _, _ = w.Write([]byte(`{"number":7,"state":"closed"}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) +} + +func dependabotCommit(sha, login, name string) map[string]any { + out := map[string]any{ + "sha": sha, + "commit": map[string]any{"message": "bump", "author": map[string]any{"name": name}}, + } + if login != "" { + out["author"] = map[string]any{"login": login} + } + return out +} + +// TestResolveConflictingDependabotPR pins the conflicting half of the +// decision: only Dependabot's commits -> hold for Dependabot's own rebase; +// edited by github-actions[bot] (the NOTICE autofix) -> closed once per head +// with a note, never a `@dependabot` command; a non-Dependabot PR is not +// handled. +func TestResolveConflictingDependabotPR(t *testing.T) { + onlyDependabot := []map[string]any{dependabotCommit("c1", "dependabot[bot]", "dependabot[bot]")} + editedByActions := []map[string]any{ + dependabotCommit("c1", "dependabot[bot]", "dependabot[bot]"), + dependabotCommit("c2", githubActionsBotLogin, githubActionsBotLogin), + } + cases := []struct { + name string + author string + commits []map[string]any + wantOK bool + wantReason string + wantClose int + }{ + {name: "conflicting, only dependabot commits", author: "dependabot[bot]", commits: onlyDependabot, wantOK: true, wantReason: "conflicting"}, + {name: "conflicting, edited by others", author: "dependabot[bot]", commits: editedByActions, wantOK: true, wantReason: dependabotStaleClosedReason, wantClose: 1}, + {name: "not a dependabot PR", author: "renovate[bot]", commits: editedByActions}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + api := &dependabotStaleAPI{commits: tc.commits} + srv := api.server(t) + defer srv.Close() + c := newAutoMergeSweepClient(srv.URL) + pr := currentBaseTestPR(false, "dependabot/go_modules/x", tc.author, "dirty") + + reason, ok := c.resolveConflictingDependabotPR(context.Background(), "acme/widget", "acme", "widget", pr, 7, "sha-head") + if ok != tc.wantOK || reason != tc.wantReason { + t.Fatalf("resolve = %q, %v; want %q, %v", reason, ok, tc.wantReason, tc.wantOK) + } + // A second pass on the same head never repeats the note or close. + if again, _ := c.resolveConflictingDependabotPR(context.Background(), "acme/widget", "acme", "widget", pr, 7, "sha-head"); tc.wantClose > 0 && again != "conflicting" { + t.Fatalf("second pass reason = %q, want conflicting", again) + } + api.mu.Lock() + defer api.mu.Unlock() + if api.closes != tc.wantClose { + t.Fatalf("closes = %d, want %d", api.closes, tc.wantClose) + } + if len(api.comments) != tc.wantClose { + t.Fatalf("comments = %q, want %d", api.comments, tc.wantClose) + } + for _, body := range api.comments { + if !strings.Contains(body, dependabotStaleCloseMarker) { + t.Fatalf("close note %q lacks marker", body) + } + for _, line := range strings.Split(body, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "@dependabot") { + t.Fatalf("close note line %q is a Dependabot command", line) + } + } + } + }) + } +} diff --git a/src/pkg/github/automerge/automerge_held_runs.go b/src/pkg/github/automerge/automerge_held_runs.go index c09935e9f0..88fd8a69f1 100644 --- a/src/pkg/github/automerge/automerge_held_runs.go +++ b/src/pkg/github/automerge/automerge_held_runs.go @@ -17,8 +17,11 @@ package automerge // (notice-autofix.yml with GITHUB_TOKEN) and the missing context comes // from a `pull_request_target`-only workflow (`verify PR contents`). Such // pushes never trigger that workflow, so the context is absent forever -// (#11923). Dependabot's own re-push restores normal triggers, so the -// sweep asks for one `@dependabot rebase` per head instead of polling. +// (#11923). Only Dependabot's own re-push restores normal triggers, and +// Dependabot refuses `@dependabot rebase` from the App and on a branch +// someone else pushed to (#18441), so the sweep posts nothing: it holds +// the head as never-ran, logged once per head, until the base moves and +// the lane's App update-branch push re-triggers the workflows. // 4. The PR itself was opened by `github-actions[bot]` with GITHUB_TOKEN, so // no `pull_request` workflow ever runs for it. The bot cannot be asked to // re-push, so the sweep re-authors the PR as the App once per head @@ -62,8 +65,8 @@ const ( // older than heldRunNeverStartedGrace; polling cannot make one appear. requiredCheckNeverStartedPrefix = "required-check-never-started:" // requiredCheckNeverRanPrefix: a trusted-bot head pushed by - // github-actions[bot] is missing a context no held run will produce; the - // sweep nudged the bot to rebase (#11923). + // github-actions[bot] is missing a context no held run will produce + // (#11923, #18441). requiredCheckNeverRanPrefix = "required-check-never-ran:" // requiredCheckSkippedByDesignPrefix logs a required context counted as // satisfied because its workflow concluded `skipped` on a trusted bot's head. @@ -71,10 +74,8 @@ const ( workflowRunConclusionSkipped = "skipped" // githubActionsBotLogin authors commits pushed with a workflow GITHUB_TOKEN. githubActionsBotLogin = "github-actions[bot]" - // dependabotLogin is the only trusted bot that understands the rebase nudge. + // dependabotLogin authors Dependabot's PRs and commits. dependabotLogin = "dependabot[bot]" - // dependabotRebaseComment asks Dependabot to re-push the branch itself. - dependabotRebaseComment = "@dependabot rebase" // workflowRunConclusionActionRequired is GitHub's conclusion for a run // waiting on a person's approval. workflowRunConclusionActionRequired = "action_required" @@ -159,7 +160,7 @@ func (c *Engine) resolveMissingRequiredCheck(ctx context.Context, displayRepo, o return requiredCheckNeverRanPrefix + missing } if headOlderThan(c.now, headPushedAt, heldRunNeverStartedGrace) && c.isAutofixPushedDependabotHead(ctx, displayRepo, owner, repo, pr, number, headSHA) { - c.nudgeDependabotRebase(ctx, displayRepo, owner, repo, number, headSHA, missing) + c.nudgeDependabotRebase(displayRepo, owner, repo, number, headSHA, missing) return requiredCheckNeverRanPrefix + missing } if c.botTakeoverEligible(pr, startedRuns, headPushedAt) { @@ -661,35 +662,21 @@ func (c *Engine) isAutofixPushedDependabotHead(ctx context.Context, displayRepo, return strings.EqualFold(commit.GetCommit().GetAuthor().GetName(), githubActionsBotLogin) } -// nudgeDependabotRebase logs one WARN naming the missing context and posts -// `@dependabot rebase` once per PR head. A failed post is not retried for the -// same head; the hold reason still surfaces in the sweep log. -func (c *Engine) nudgeDependabotRebase(ctx context.Context, displayRepo, owner, repo string, number int, headSHA, missing string) { +// nudgeDependabotRebase logs one WARN per PR head naming the missing context. +// It posts nothing: Dependabot refuses `@dependabot rebase` from the App and +// on a branch github-actions[bot] pushed to, so a comment could only be +// refused again every pass (#18441). The head holds as never-ran until the +// base moves; the lane then update-branches it as the App, whose push fires +// the pull_request and pull_request_target workflows. +func (c *Engine) nudgeDependabotRebase(displayRepo, owner, repo string, number int, headSHA, missing string) { if !c.markRebaseNudged(owner, repo, number, headSHA) { return } - c.warn("automerge required check never ran on autofix-pushed Dependabot head; asking Dependabot to rebase", + c.warn("automerge required check never ran on autofix-pushed Dependabot head; Dependabot ignores the App's commands, holding until the branch is updated", "repo", displayRepo, "pr", number, "sha", headSHA, "context", missing) - _, err := effects.Execute(ctx, c.mutation, effects.Claim{ - Repo: owner + "/" + repo, - Kind: effects.KindIssueComment, - Target: strconv.Itoa(number), - Actor: "automerge", - Inputs: map[string]string{"head_sha": headSHA, "body": effects.StableDigest(dependabotRebaseComment)}, - }, func(ctx context.Context) (effects.Result, error) { - comment, _, apiErr := c.gh.Issues.CreateComment(hgithub.WithRESTCaller(ctx, "hive:automerge_sweep"), owner, repo, number, &gh.IssueComment{Body: gh.Ptr(dependabotRebaseComment)}) - if apiErr != nil { - return effects.Result{}, effects.NotApplied(apiErr) - } - c.noteOwnStageComment(owner, repo, number) - return effects.Result{Provenance: comment.GetHTMLURL()}, nil - }) - if err != nil { - c.warn("automerge failed to post Dependabot rebase nudge", "repo", displayRepo, "pr", number, "sha", headSHA, "error", err) - } } -// rebaseNudged reports whether the nudge was already attempted for this PR +// rebaseNudged reports whether the hold was already recorded for this PR // head, so later ticks skip the head-commit lookup. func (c *Engine) rebaseNudged(owner, repo string, number int, headSHA string) bool { c.heldRunApprovalsMu.Lock() @@ -701,8 +688,8 @@ func rebaseNudgeKey(prKey, headSHA string) string { return "rebase-nudge:" + prKey + "@" + strings.ToLower(headSHA) } -// markRebaseNudged records that the rebase nudge was attempted for this PR -// head and reports whether this is the first attempt. +// markRebaseNudged records the never-ran hold for this PR head and reports +// whether this is the first time. func (c *Engine) markRebaseNudged(owner, repo string, number int, headSHA string) bool { key := rebaseNudgeKey(c.evaluatedHeadKey(owner, repo, number), headSHA) c.heldRunApprovalsMu.Lock() diff --git a/src/pkg/github/automerge/automerge_held_runs_test.go b/src/pkg/github/automerge/automerge_held_runs_test.go index f713c241f0..2c4062b40f 100644 --- a/src/pkg/github/automerge/automerge_held_runs_test.go +++ b/src/pkg/github/automerge/automerge_held_runs_test.go @@ -16,7 +16,6 @@ import ( "time" gh "github.com/google/go-github/v72/github" - "github.com/hivecommons/hive/pkg/effects" "github.com/hivecommons/hive/pkg/oktotest" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -229,8 +228,9 @@ func TestTerminalRequiredCheckHoldLoggedOncePerHeadAndReason(t *testing.T) { // #11923: a Dependabot head autofix-pushed by github-actions[bot] can never // produce a pull_request_target-only required context. The sweep names it -// required-check-never-ran and asks Dependabot to rebase exactly once per head. -func TestTrySweepTrustedBotNudgesDependabotRebaseOncePerHead(t *testing.T) { +// required-check-never-ran. #18441: it never posts `@dependabot rebase`, +// which Dependabot refuses from the App and on an edited branch. +func TestTrySweepTrustedBotHoldsAutofixDependabotHeadWithoutCommand(t *testing.T) { now := time.Date(2026, 10, 14, 19, 0, 0, 0, time.UTC) var comments []string pr := missingRequiredPR(func(p *selfAuthoredPR) { @@ -259,11 +259,14 @@ func TestTrySweepTrustedBotNudgesDependabotRebaseOncePerHead(t *testing.T) { t.Fatalf("tick %d reason = %q, want %q", tick, reason, want) } } - if len(comments) != 1 || comments[0] != dependabotRebaseComment { - t.Fatalf("comments = %q, want exactly one %q", comments, dependabotRebaseComment) + if len(comments) != 0 { + t.Fatalf("comments = %q, want none (Dependabot refuses the App's commands)", comments) + } + if len(rec.claims) != 0 { + t.Fatalf("mutation claims = %#v, want none", rec.claims) } - if len(rec.claims) != 1 || rec.claims[0].Kind != effects.KindIssueComment || rec.claims[0].Target != "23" || rec.claims[0].Inputs["head_sha"] != "sha23" { - t.Fatalf("mutation claims = %#v, want one issue_comment claim for PR 23 head sha23", rec.claims) + if !c.rebaseNudged("acme", "widget", 23, "sha23") { + t.Fatal("rebaseNudged = false; the hold must be recorded once per head") } if !isTerminalRequiredCheckHold(want) { t.Fatalf("isTerminalRequiredCheckHold(%q) = false, want true so the hold logs once", want) @@ -334,10 +337,10 @@ func TestDependabotRebaseNudgeDegradesOnAPIErrors(t *testing.T) { if c.isAutofixPushedDependabotHead(context.Background(), "widget", "acme", "widget", pr, 23, "sha23") { t.Fatal("head-commit lookup failure must not be treated as an autofix head") } - c.nudgeDependabotRebase(context.Background(), "widget", "acme", "widget", 23, "sha23", "ci/build") - c.nudgeDependabotRebase(context.Background(), "widget", "acme", "widget", 23, "sha23", "ci/build") - if posts != 1 { - t.Fatalf("comment POSTs = %d, want 1 (a failed nudge is not retried for the same head)", posts) + c.nudgeDependabotRebase("widget", "acme", "widget", 23, "sha23", "ci/build") + c.nudgeDependabotRebase("widget", "acme", "widget", 23, "sha23", "ci/build") + if posts != 0 { + t.Fatalf("comment POSTs = %d, want 0 (never post a command Dependabot refuses)", posts) } if !c.rebaseNudged("acme", "widget", 23, "SHA23") { t.Fatal("rebaseNudged = false after an attempted nudge") diff --git a/src/pkg/github/automerge/automerge_sweep_trusted.go b/src/pkg/github/automerge/automerge_sweep_trusted.go index 45b2146d6f..9986041b0a 100644 --- a/src/pkg/github/automerge/automerge_sweep_trusted.go +++ b/src/pkg/github/automerge/automerge_sweep_trusted.go @@ -141,6 +141,9 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, evaluatedHeadSHA, "behind", pr) } if mergeableState == "dirty" || mergeableState == "conflicting" { + if reason, ok := c.resolveConflictingDependabotPR(ctx, displayRepo, owner, repo, pr, number, evaluatedHeadSHA); ok { + return AutoMergeSweepEvent{}, reason, nil + } return AutoMergeSweepEvent{}, "conflicting", nil } baseBranch := "" @@ -841,7 +844,9 @@ func (c *Engine) isForkPR(pr *gh.PullRequest) bool { // date — update-branch, merge-forward, a merge-train rebase request — asks // this first: Renovate stops rebasing a branch for good once another identity // has committed to it (projectbluefin/utah#1097), and under strict freshness -// it rebases a behind branch itself. A nil PR is never a bot branch. +// it rebases a behind branch itself. A Dependabot branch is the exception on +// the update-branch steps (dependabotUpdateBranchAllowed, #18441). A nil PR +// is never a bot branch. func (c *Engine) leaveBaseSyncToDependencyBot(displayRepo, owner, repo string, pr *gh.PullRequest, step string) bool { if pr == nil { return false @@ -850,6 +855,11 @@ func (c *Engine) leaveBaseSyncToDependencyBot(displayRepo, owner, repo string, p if !hgithub.DependencyBotBranch(headRef, author) { return false } + if dependabotUpdateBranchAllowed(pr, step) { + // Dependabot never rebases a merely-behind branch and ignores the + // App's commands, so the App updates it (#18441). + return false + } number, headSHA := pr.GetNumber(), pr.GetHead().GetSHA() if c.markTerminalHoldLogged(owner, repo, number, headSHA, "dependency-bot:"+step) { c.info("automerge: branch belongs to a dependency bot; leaving the base sync to the bot", @@ -859,8 +869,8 @@ func (c *Engine) leaveBaseSyncToDependencyBot(displayRepo, owner, repo string, p } // updateBranchAndSkip merges the base into pr's head with GitHub's -// update-branch. A dependency bot's branch is never updated: it holds as -// "behind" until the bot rebases it. +// update-branch. A dependency bot's branch other than Dependabot's is never +// updated: it holds as "behind" until the bot rebases it. func (c *Engine) updateBranchAndSkip(ctx context.Context, displayRepo, owner, repo string, number int, headSHA, reason string, pr *gh.PullRequest) (AutoMergeSweepEvent, string, error) { if c.leaveBaseSyncToDependencyBot(displayRepo, owner, repo, pr, "update-branch") { return AutoMergeSweepEvent{}, "behind", nil diff --git a/src/pkg/scheduler/lane_messages.go b/src/pkg/scheduler/lane_messages.go index 4487e3d49e..c2486c1fe0 100644 --- a/src/pkg/scheduler/lane_messages.go +++ b/src/pkg/scheduler/lane_messages.go @@ -105,7 +105,7 @@ func (s *Scheduler) buildScannerMessage(issues []github.Issue, actionable *githu b.WriteString("\nWORKFLOW:\n") b.WriteString(" 1. Check beads (`bd list --status open`) for context from previous cycles\n") - b.WriteString(" 2. Quick merges + cleanup (10 min cap) — merge PRs whose required checks are GREEN using a squash merge via your App token (MCP `merge_pull_request` with `merge_method: \"squash\"`, or `gh pr merge --squash`). Do NOT use `--admin` — never force-merge past pending or failing CI; wait for the required checks to pass. Ensure the PR body cites the issue it addresses: ask does merging this PR leave anything for that issue to track? If nothing, write `Closes #` — the default, auto-closes on merge. Use `Refs #` or `Part of #` (non-closing) only for an epic/multi-phase tracker or a deliberately partial fix, and say on the same line what remains and why; if the remainder needs a human, write `Refs # (needs-human: )`. Close stale drafts (>48h, needs-rebase + dco-no, or fix already merged). `@dependabot rebase` stale ones. Move on after 10 min.\n") + b.WriteString(" 2. Quick merges + cleanup (10 min cap) — merge PRs whose required checks are GREEN using a squash merge via your App token (MCP `merge_pull_request` with `merge_method: \"squash\"`, or `gh pr merge --squash`). Do NOT use `--admin` — never force-merge past pending or failing CI; wait for the required checks to pass. Ensure the PR body cites the issue it addresses: ask does merging this PR leave anything for that issue to track? If nothing, write `Closes #` — the default, auto-closes on merge. Use `Refs #` or `Part of #` (non-closing) only for an epic/multi-phase tracker or a deliberately partial fix, and say on the same line what remains and why; if the remainder needs a human, write `Refs # (needs-human: )`. Close stale drafts (>48h, needs-rebase + dco-no, or fix already merged). Stale Dependabot PRs: never comment `@dependabot rebase`/`recreate` (Dependabot refuses commands from the App, and refuses rebase once anyone else pushed to the branch); if the PR is only behind, update it with `gh api -X PUT repos/{owner}/{repo}/pulls/{n}/update-branch`; if it conflicts and has a commit not authored by Dependabot, close it so Dependabot opens a fresh one; otherwise leave the rebase to Dependabot. Move on after 10 min.\n") b.WriteString(" 3. Fix blockers — find the ONE fix that unblocks the most PRs/issues. Clone, fix, push, merge.\n") b.WriteString(" 4. Crank quick fixes — launch background agents using the Agent tool (run_in_background: true) to fix remaining issues in parallel. One PR per issue, move fast.\n") diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 201a0d5521..4c246cd233 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -11,7 +11,7 @@ raw pkg/github/automerge/automerge_contributor_held_runs.go 1 raw pkg/github/automerge/automerge_contributor_lane.go 3 raw pkg/github/automerge/automerge_contributor_nudge.go 1 raw pkg/github/automerge/automerge_contributor_workflow_approval.go 1 -raw pkg/github/automerge/automerge_held_runs.go 3 +raw pkg/github/automerge/automerge_held_runs.go 2 raw pkg/github/automerge/automerge_merge_commit.go 1 raw pkg/github/automerge/automerge_merge_forward.go 1 raw pkg/github/automerge/automerge_signoff_attribution.go 1 From e119d81de29db232390e12b16b27d28c94fcc7de Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Mon, 16 Nov 2026 19:36:59 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A7=AA=20automerge:=20pin=20that=20th?= =?UTF-8?q?e=20App's=20own=20update-branch=20merge=20makes=20a=20conflicti?= =?UTF-8?q?ng=20Dependabot=20PR=20closeable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dependabot stops rebasing a branch once anyone other than Dependabot has committed to it, including the App's update-branch merge. A PR that went behind -> update-branch -> conflicting is therefore stuck and is closed with the recreate note, like any other edited PR (#18441). Signed-off-by: Andrew Anderson --- .../github/automerge/automerge_dependabot_stale_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/pkg/github/automerge/automerge_dependabot_stale_test.go b/src/pkg/github/automerge/automerge_dependabot_stale_test.go index 9aecbd93f3..77ffe5aa7a 100644 --- a/src/pkg/github/automerge/automerge_dependabot_stale_test.go +++ b/src/pkg/github/automerge/automerge_dependabot_stale_test.go @@ -168,6 +168,14 @@ func TestResolveConflictingDependabotPR(t *testing.T) { dependabotCommit("c1", "dependabot[bot]", "dependabot[bot]"), dependabotCommit("c2", githubActionsBotLogin, githubActionsBotLogin), } + // The lane's own update-branch merge is a non-Dependabot commit too: + // Dependabot stops rebasing a branch once anyone else has committed to it, + // so a PR the App merged the base into and that later conflicts is stuck + // and is closed like any other edited PR (owner decision on #18446). + editedByAppMerge := []map[string]any{ + dependabotCommit("c1", "dependabot[bot]", "dependabot[bot]"), + dependabotCommit("c2", "hivecommons-hive[bot]", "hivecommons-hive[bot]"), + } cases := []struct { name string author string @@ -178,6 +186,7 @@ func TestResolveConflictingDependabotPR(t *testing.T) { }{ {name: "conflicting, only dependabot commits", author: "dependabot[bot]", commits: onlyDependabot, wantOK: true, wantReason: "conflicting"}, {name: "conflicting, edited by others", author: "dependabot[bot]", commits: editedByActions, wantOK: true, wantReason: dependabotStaleClosedReason, wantClose: 1}, + {name: "conflicting after the App's own update-branch merge", author: "dependabot[bot]", commits: editedByAppMerge, wantOK: true, wantReason: dependabotStaleClosedReason, wantClose: 1}, {name: "not a dependabot PR", author: "renovate[bot]", commits: editedByActions}, } for _, tc := range cases {