From 6bb266c2e04607a7b2585e5307b6f648f19cc511 Mon Sep 17 00:00:00 2001 From: Danathar <6772335+Danathar@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:19:06 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20dependency-bot:=20opt-in=20hive?= =?UTF-8?q?=20adoption=20of=20red=20dependency-bot=20PRs=20that=20need=20a?= =?UTF-8?q?=20code=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add auto_merge.dependency_bot_adopt.enabled (default off). With it on, the dependency-bot sweep, at the point it would hand a red trusted-bot Renovate/Dependabot/mergeraptor PR to a person (red on the same head past the 4h grace and the transient re-run hold), reads the review swarm's own aggregate verdict for exactly that head from review-verdicts.json. When it is changes_requested, it adds adoption/supersede (the dashboard Adopt decision's label) once per bot head, gated as write-back kind contributor_adopt, and posts no hand-off for that head. The existing adoption path copies the PR to hive/adopt- and the fix loop repairs it. Held, human-merge-labelled or -titled PRs, heads touching auto_merge.human_merge_paths (read-only check sharing the relay's pin-only exception), heads without a changes_requested verdict, hives with stage adoption off and write-back refusals keep the person hand-off. A failed label write is recorded for the head and the hand-off follows next pass. Requests persist in dependency-bot-conflicts-adopt.json. The setting is wired through config, PUT /api/config/auto-merge (dependency_bot_adopt_enabled), the Features → Auto-merge toggle and the admin MCP auto_merge.update op, with docs and a changelog fragment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar <6772335+Danathar@users.noreply.github.com> --- changelog.d/added-dependency-bot-adopt.md | 1 + src/cmd/hive/dependency_bot_adopt.go | 341 ++++++++++++++++++ src/cmd/hive/dependency_bot_adopt_test.go | 322 +++++++++++++++++ src/cmd/hive/dependency_bot_conflicts.go | 35 +- src/docs/hive-merge.md | 49 +++ src/docs/operator-reference/README.md | 7 + .../sweeps-and-operations.md | 1 + src/pkg/adminmcp/tools_automerge_ops.go | 1 + src/pkg/adminmcp/tools_automerge_ops_test.go | 24 ++ src/pkg/config/automerge_trusted_bot_test.go | 32 ++ src/pkg/config/review_config.go | 21 ++ .../config/testdata/agent_runtime_golden.json | 1 + src/pkg/dashboard/api_config_automerge.go | 7 + .../dashboard/github_settings_parity_test.go | 35 +- .../static-src/js/config-features.js | 4 + .../dashboard/static-src/js/config-state.js | 2 +- src/pkg/dashboard/static/index.html | 6 +- src/pkg/github/human_merge_paths.go | 78 +++- src/pkg/github/human_merge_paths_test.go | 46 +++ .../rfccoverage/testdata/settings_index.html | 2 +- 20 files changed, 995 insertions(+), 20 deletions(-) create mode 100644 changelog.d/added-dependency-bot-adopt.md create mode 100644 src/cmd/hive/dependency_bot_adopt.go create mode 100644 src/cmd/hive/dependency_bot_adopt_test.go diff --git a/changelog.d/added-dependency-bot-adopt.md b/changelog.d/added-dependency-bot-adopt.md new file mode 100644 index 0000000000..4058dce511 --- /dev/null +++ b/changelog.d/added-dependency-bot-adopt.md @@ -0,0 +1 @@ +- `auto_merge.dependency_bot_adopt.enabled` (default off; Settings → Features → Auto-merge, admin MCP `auto_merge.update` field `dependency_bot_adopt_enabled`) lets the hive take over a red dependency-bot PR that needs a code change instead of only handing it to a person. When a Renovate/Dependabot/mergeraptor PR whose bot is in `auto_merge.trusted_bot_authors` reaches the 4-hour red-CI hand-off and the review swarm's own verdict on that exact head is `changes_requested`, the dependency-bot sweep adds `adoption/supersede` (what the dashboard's Adopt decision adds) once per bot head, gated as write-back kind `contributor_adopt`, and posts no hand-off for that head; the existing adoption path copies the PR to `hive/adopt-` and the fix loop repairs the copy. Held, human-merge-labelled and `human_merge_paths` PRs, heads without a `changes_requested` verdict, and hives with stage adoption off keep the person hand-off, as does a head whose label write failed. Before this, a person's Adopt click was the only step between such a PR and a merged fix. diff --git a/src/cmd/hive/dependency_bot_adopt.go b/src/cmd/hive/dependency_bot_adopt.go new file mode 100644 index 0000000000..df49c2988f --- /dev/null +++ b/src/cmd/hive/dependency_bot_adopt.go @@ -0,0 +1,341 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "os" + "path/filepath" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/forge" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Hive adoption of red dependency-bot PRs (auto_merge.dependency_bot_adopt). +// +// A dependency-bot PR whose bump needs a code change (a Go module major bump +// whose imports still name the old path, say) cannot go green on its own: the +// fix loop refuses another bot's branch (review.FixDispatchExcludedOtherBotAuthor, +// the bot regenerates it), so the red-CI hand-off only told a person. The +// person's one step was then the dashboard's Adopt decision, which adds +// `adoption/supersede`; the adoption path copies the PR to `hive/adopt-` +// and the fix loop repairs the copy. +// +// With the switch on, the sweep takes that step itself at the moment the +// red-CI hand-off would fire, when the bot is a trusted bot author and the +// review swarm's own verdict on that exact head is changes_requested (the +// reviewer named a change; the bump is not merely flaky). It adds the label +// once per bot head and does not post the hand-off for that head. Every +// other case keeps the hand-off, and the adoption path itself is unchanged. + +// depBotAdoptReason is the reason logged with an adoption request. +const depBotAdoptReason = "red-ci-changes-requested" + +// Skip reasons the sweep logs when the switch is on but the request is not +// made, so the hand-off that follows says why. +const ( + depBotAdoptSkipNotTrustedBot = "not-trusted-bot-author" + depBotAdoptSkipAdoptionOff = "stage-adoption-disabled" + depBotAdoptSkipHumanMerge = "human-merge-rule" + depBotAdoptSkipHoldLabel = "hold-label" + depBotAdoptSkipAlreadyAsked = "adoption-already-requested" + depBotAdoptSkipNoVerdict = "no-changes-requested-verdict" + depBotAdoptSkipHumanMergePath = "human-merge-path" + depBotAdoptSkipPathUnknown = "human-merge-path-unreadable" + depBotAdoptSkipWriteback = "writeback-refused" +) + +// depBotAdoptLabelColor and depBotAdoptLabelDesc are the label the dashboard's +// Adopt decision creates (pkg/dashboard adoptRequestLabelColor/Desc). +const ( + depBotAdoptLabelColor = "5319e7" + depBotAdoptLabelDesc = "Owner-delegate request: adopt now in supersede mode" +) + +// depBotAdoptPolicy is what the red-CI adoption request reads. The zero value +// is the switch off: the sweep behaves exactly as without it. +type depBotAdoptPolicy struct { + // Enabled is auto_merge.dependency_bot_adopt.enabled. + Enabled bool + // StageAdoption is governor.labels.stage with its adoption half on, the + // gate the dashboard's Adopt decision checks (stageAdoptionEnabled): + // without it nothing consumes the label. + StageAdoption bool + // TrustedBot reports an auto_merge.trusted_bot_authors login (the PR then + // rides the self-authored sweep's trusted-bot lane, whose adoption path + // handles a delegated supersede). + TrustedBot func(author string) bool + // HumanMerge reports the auto_merge.human_merge_title_prefixes / + // human_merge_labels rule (needs-owner-merge, a ⚠️ title). + HumanMerge func(pr github.PullRequest) bool + // HeadVerdict is the review swarm's aggregate verdict on exactly this + // head ("" when none is recorded): the raw swarm verdict, not the + // trusted-bot lane's advisory downgrade. + HeadVerdict func(repo string, number int, headSHA string) string + // HumanMergePath reports that the head touches the repo's + // auto_merge.human_merge_paths without its pin-only exception admitting + // it. An error is read as "touches" (fail closed). + HumanMergePath func(ctx context.Context, repo string, number int, headSHA string) (bool, error) +} + +// depBotAdoptPolicyFromConfig builds the live policy. reader is the sweep's +// PR reader; *github.Client answers the human-merge-path check. +func depBotAdoptPolicyFromConfig(cfg *config.Config, reader depBotPRReader, logger *slog.Logger) depBotAdoptPolicy { + if cfg == nil || !cfg.AutoMerge.DependencyBotAdopt.IsEnabled() { + return depBotAdoptPolicy{} + } + stage := cfg.Governor.Labels.Stage + rule := humanMergeRuleFor(cfg) + p := depBotAdoptPolicy{ + Enabled: true, + StageAdoption: stage.IsEnabled() && stage.Adoption.IsEnabled(), + TrustedBot: func(author string) bool { return dbrTrustedBotAuthor(cfg, author) }, + HumanMerge: func(pr github.PullRequest) bool { + held, _ := rule.RequiresHumanMerge(pr.Title, pr.Labels) + return held + }, + HeadVerdict: func(repo string, number int, headSHA string) string { + return depBotHeadVerdictFromArtifact(repo, number, headSHA, logger) + }, + } + if checker, ok := reader.(interface { + HumanMergePathHeld(ctx context.Context, repo string, number int, headSHA string) (bool, error) + }); ok { + p.HumanMergePath = checker.HumanMergePathHeld + } + return p +} + +// depBotHeadVerdictFromArtifact reads the swarm's aggregate verdict for +// exactly headSHA from review-verdicts.json, the artifact the automerge +// trusted-bot lane reads before it downgrades the verdict to advisory. A +// missing or unreadable artifact, or no aggregate on this head, is "". +func depBotHeadVerdictFromArtifact(repo string, number int, headSHA string, logger *slog.Logger) string { + art, err := review.LoadArtifact("") + if err != nil { + if !errors.Is(err, os.ErrNotExist) && logger != nil { + logger.Warn("dependency-bot adoption: review-verdicts.json unreadable; not adopting", "repo", repo, "pr", number, "error", err) + } + return "" + } + return depBotHeadVerdict(art, repo, number, headSHA) +} + +// depBotHeadVerdict is the newest aggregate verdict on exactly headSHA (no +// fallback to an older head), matched the way the contributor-lane verdict +// gate matches it (contributorLaneVerdictFromArtifact): normalized items, +// case-insensitive repo, under the repo as given or its short name (the +// artifact records either form). +func depBotHeadVerdict(art review.Artifact, repo string, number int, headSHA string) string { + if strings.TrimSpace(headSHA) == "" || number <= 0 { + return "" + } + repo = strings.TrimSpace(repo) + _, short, _ := strings.Cut(repo, "/") + var match review.Aggregate + found := false + for _, item := range art.Items { + item = item.Normalize() + if item.Number != number || !review.SameHeadSHA(item.HeadSHA, headSHA) { + continue + } + r := strings.TrimSpace(item.Repo) + if !strings.EqualFold(r, repo) && (short == "" || !strings.EqualFold(r, short)) { + continue + } + if !found || item.RecordedAt.After(match.RecordedAt) { + match, found = item, true + } + } + if !found { + return "" + } + return string(match.Verdict) +} + +// skipReason is why this head gets the person hand-off instead of an +// adoption request, or "" when the request may be made. The cheap checks run +// first; the human-merge-path check may read the PR's files. +func (p depBotAdoptPolicy) skipReason(ctx context.Context, repo string, pr github.PullRequest) string { + switch { + case p.TrustedBot == nil || !p.TrustedBot(pr.Author): + return depBotAdoptSkipNotTrustedBot + case !p.StageAdoption: + return depBotAdoptSkipAdoptionOff + case github.HasHoldLabel(pr.Labels) || hasLabel(pr.Labels, "do-not-merge") || hasLabel(pr.Labels, "do-not-merge/hold"): + return depBotAdoptSkipHoldLabel + case p.HumanMerge != nil && p.HumanMerge(pr): + return depBotAdoptSkipHumanMerge + case hasLabel(pr.Labels, delegatedecision.LabelAdoptSupersede): + return depBotAdoptSkipAlreadyAsked + } + verdict := "" + if p.HeadVerdict != nil { + verdict = p.HeadVerdict(repo, pr.Number, pr.HeadSHA) + } + if !strings.EqualFold(strings.TrimSpace(verdict), string(review.VerdictChangesRequested)) { + return depBotAdoptSkipNoVerdict + } + if p.HumanMergePath == nil { + return depBotAdoptSkipPathUnknown + } + held, err := p.HumanMergePath(ctx, repo, pr.Number, pr.HeadSHA) + switch { + case err != nil: + return depBotAdoptSkipPathUnknown + case held: + return depBotAdoptSkipHumanMergePath + } + return "" +} + +// requestDependencyBotAdoption runs at the point the red-CI hand-off would +// be posted for pr's head. It reports true when the hand-off must not be +// posted this pass: the adoption was requested now, or earlier for this same +// head and the label write succeeded, or the write failed this pass (the +// hand-off follows on the next one). Every request is recorded per head +// before the write, so a restart or a failed write never repeats it. +func requestDependencyBotAdoption(ctx context.Context, p depBotAdoptPolicy, store *depBotConflictStore, writer forge.IssueWriter, reader depBotPRReader, repo, key string, pr github.PullRequest, now time.Time, logger *slog.Logger) bool { + if !p.Enabled || pr.HeadSHA == "" { + return false + } + if rec, ok := store.adoptRequest(key); ok && rec.HeadSHA == pr.HeadSHA { + // One request per bot head: after a successful one the adoption + // path owns the PR; after a failed one the person gets it. + return !rec.Failed + } + if why := p.skipReason(ctx, repo, pr); why != "" { + logger.Info("dependency-bot red CI: hive adoption not requested; handing to a person", + "repo", repo, "pr", pr.Number, "head", pr.HeadSHA, "reason", why) + return false + } + if !depBotWritebackAllowed(ctx, reader, repo, pr.Number, writeback.KindContributorAdopt, delegatedecision.LabelAdoptSupersede, logger) { + logger.Info("dependency-bot red CI: hive adoption not requested; handing to a person", + "repo", repo, "pr", pr.Number, "head", pr.HeadSHA, "reason", depBotAdoptSkipWriteback) + return false + } + store.markAdoptRequested(key, pr.HeadSHA, now) + if err := addDepBotAdoptLabel(ctx, writer, repo, pr.Number); err != nil { + store.markAdoptFailed(key, pr.HeadSHA) + logger.Warn("dependency-bot red CI: adoption label failed; a person gets the hand-off next pass", + "repo", repo, "pr", pr.Number, "head", pr.HeadSHA, "error", err) + return true + } + logger.Info("dependency-bot red CI: hive adoption requested", + "repo", repo, "pr", pr.Number, "head", pr.HeadSHA, "reason", depBotAdoptReason, "label", delegatedecision.LabelAdoptSupersede) + return true +} + +// depBotLabelEnsurer is the optional label-create call the dashboard's Adopt +// decision makes before adding the label. *github.Client satisfies it. +type depBotLabelEnsurer interface { + EnsureIssueLabel(ctx context.Context, repo, name, color, description string) error +} + +func addDepBotAdoptLabel(ctx context.Context, writer forge.IssueWriter, repo string, number int) error { + if ensurer, ok := writer.(depBotLabelEnsurer); ok { + if err := ensurer.EnsureIssueLabel(ctx, repo, delegatedecision.LabelAdoptSupersede, depBotAdoptLabelColor, depBotAdoptLabelDesc); err != nil { + return err + } + } + return writer.AddLabels(ctx, repo, number, []string{delegatedecision.LabelAdoptSupersede}) // writeback:gated +} + +// depBotAdoptRecord is the persisted adoption request for one PR: the bot +// head it was made for and whether the label write failed. +type depBotAdoptRecord struct { + HeadSHA string `json:"head_sha"` + RequestedAt time.Time `json:"requested_at"` + Failed bool `json:"failed,omitempty"` +} + +func (s *depBotConflictStore) adoptRequest(key string) (depBotAdoptRecord, bool) { + s.mu.Lock() + defer s.mu.Unlock() + r := s.adopt[key] + if r == nil { + return depBotAdoptRecord{}, false + } + return *r, true +} + +func (s *depBotConflictStore) markAdoptRequested(key, headSHA string, at time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + if s.adopt == nil { + s.adopt = map[string]*depBotAdoptRecord{} + } + s.adopt[key] = &depBotAdoptRecord{HeadSHA: headSHA, RequestedAt: at} + s.saveAdoptLocked() +} + +func (s *depBotConflictStore) markAdoptFailed(key, headSHA string) { + s.mu.Lock() + defer s.mu.Unlock() + if r := s.adopt[key]; r != nil && r.HeadSHA == headSHA { + r.Failed = true + s.saveAdoptLocked() + } +} + +// pruneAdopt forgets PRs that left the open snapshot. +func (s *depBotConflictStore) pruneAdopt(open map[string]github.PullRequest) { + s.mu.Lock() + defer s.mu.Unlock() + changed := false + for k := range s.adopt { + if _, ok := open[k]; !ok { + delete(s.adopt, k) + changed = true + } + } + if changed { + s.saveAdoptLocked() + } +} + +func depBotAdoptPath(path string) string { + if path == "" { + return "" + } + return strings.TrimSuffix(path, ".json") + "-adopt.json" +} + +func loadDepBotAdoptRecords(path string) map[string]*depBotAdoptRecord { + out := map[string]*depBotAdoptRecord{} + if path == "" { + return out + } + data, err := os.ReadFile(path) + if err != nil { + return out + } + var m map[string]*depBotAdoptRecord + if json.Unmarshal(data, &m) == nil && m != nil { + out = m + } + return out +} + +func (s *depBotConflictStore) saveAdoptLocked() { + path := depBotAdoptPath(s.path) + if path == "" { + return + } + data, err := json.MarshalIndent(s.adopt, "", " ") + if err != nil { + return + } + _ = os.MkdirAll(filepath.Dir(path), 0o755) + tmp := path + ".tmp" + if os.WriteFile(tmp, data, 0o644) == nil { + _ = os.Rename(tmp, path) + } +} diff --git a/src/cmd/hive/dependency_bot_adopt_test.go b/src/cmd/hive/dependency_bot_adopt_test.go new file mode 100644 index 0000000000..2ac4ad061b --- /dev/null +++ b/src/cmd/hive/dependency_bot_adopt_test.go @@ -0,0 +1,322 @@ +package main + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/escalation" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +// depBotAdoptFake is a policy with every check answered by the test. +type depBotAdoptFake struct { + verdicts map[string]string // head SHA -> swarm verdict + pathHeld bool + pathErr error + pathChecks int + verdictReads int +} + +func (f *depBotAdoptFake) policy() depBotAdoptPolicy { + return depBotAdoptPolicy{ + Enabled: true, + StageAdoption: true, + TrustedBot: func(author string) bool { return author == "dependabot[bot]" || author == "mergeraptor[bot]" }, + HumanMerge: func(pr github.PullRequest) bool { + return hasLabel(pr.Labels, "needs-owner-merge") + }, + HeadVerdict: func(_ string, _ int, head string) string { + f.verdictReads++ + return f.verdicts[head] + }, + HumanMergePath: func(context.Context, string, int, string) (bool, error) { + f.pathChecks++ + return f.pathHeld, f.pathErr + }, + } +} + +func newDepBotAdoptFake() *depBotAdoptFake { + return &depBotAdoptFake{verdicts: map[string]string{"sha-1": "changes_requested", "sha-2": "changes_requested"}} +} + +func (h *depBotHarness) adoptPassAt(at time.Time, p depBotAdoptPolicy, prs ...github.PullRequest) { + h.t.Helper() + a := &github.ActionableResult{} + a.PRs.Items = prs + sweepDependencyBotConflictsWith(context.Background(), h.store, "acme", 0, p, h.writer, h.reader, a, func() time.Time { return at }, discardLogger()) +} + +// redPastGrace runs the two passes that start the red-CI clock and reach the +// grace on pr's head. +func (h *depBotHarness) redPastGrace(start time.Time, p depBotAdoptPolicy, pr github.PullRequest) time.Time { + h.t.Helper() + h.adoptPassAt(start, p, pr) + at := start.Add(depBotRedCIGrace) + h.adoptPassAt(at, p, pr) + return at +} + +func (h *depBotHarness) adoptLabelAdds() int { + n := 0 + for _, a := range h.writer.adds { + if strings.HasSuffix(a, ": "+delegatedecision.LabelAdoptSupersede) { + n++ + } + } + return n +} + +func (h *depBotHarness) wantHandoffOnly(what string) { + h.t.Helper() + if len(h.writer.comments) != 1 { + h.t.Fatalf("%s: comments = %v, want the one person hand-off", what, h.writer.comments) + } + if n := h.adoptLabelAdds(); n != 0 { + h.t.Fatalf("%s: adds = %v, want no adoption request", what, h.writer.adds) + } + if want := depBotKey + ": " + escalation.NeedsHumanLabel; len(h.writer.adds) != 1 || h.writer.adds[0] != want { + h.t.Fatalf("%s: adds = %v, want [%q]", what, h.writer.adds, want) + } +} + +// Switch off: the red-CI hand-off is exactly today's, and no verdict is read. +func TestDependencyBotAdoptSwitchOffKeepsHandoff(t *testing.T) { + h := newDepBotHarness(t) + f := newDepBotAdoptFake() + p := f.policy() + p.Enabled = false + h.redPastGrace(depBotT0, p, depBotPR("dependabot[bot]", "sha-1", redCI)) + h.wantHandoffOnly("switch off") + if f.verdictReads != 0 || f.pathChecks != 0 { + t.Fatalf("switch off read verdicts=%d paths=%d, want none", f.verdictReads, f.pathChecks) + } + if _, ok := h.store.adoptRequest(depBotKey); ok { + t.Fatal("switch off recorded an adoption request") + } +} + +// Switch on, red past the grace, swarm said changes_requested on this head: +// one adoption label, no hand-off comment, no needs-human. Later passes on the +// same head (and a restart) never repeat it; a new head is eligible again. +func TestDependencyBotAdoptRequestsOncePerHead(t *testing.T) { + h := newDepBotHarness(t) + f := newDepBotAdoptFake() + pr := depBotPR("dependabot[bot]", "sha-1", redCI) + + h.adoptPassAt(depBotT0, f.policy(), pr) + h.adoptPassAt(depBotT0.Add(depBotRedCIGrace-time.Minute), f.policy(), pr) + if len(h.writer.adds) != 0 || len(h.writer.comments) != 0 { + t.Fatalf("before grace: adds=%v comments=%v, want none", h.writer.adds, h.writer.comments) + } + h.adoptPassAt(depBotT0.Add(depBotRedCIGrace), f.policy(), pr) + if want := depBotKey + ": " + delegatedecision.LabelAdoptSupersede; len(h.writer.adds) != 1 || h.writer.adds[0] != want { + t.Fatalf("adds = %v, want exactly [%q]", h.writer.adds, want) + } + if len(h.writer.comments) != 0 { + t.Fatalf("comments = %v, want no person hand-off", h.writer.comments) + } + rec, ok := h.store.adoptRequest(depBotKey) + if !ok || rec.HeadSHA != "sha-1" || rec.Failed { + t.Fatalf("adopt record = %+v (ok=%v), want sha-1, not failed", rec, ok) + } + + // Second pass on the same head: nothing new, even with the label on. + labeled := pr + labeled.Labels = []string{delegatedecision.LabelAdoptSupersede} + h.adoptPassAt(depBotT0.Add(2*depBotRedCIGrace), f.policy(), labeled) + h.adoptPassAt(depBotT0.Add(3*depBotRedCIGrace), f.policy(), pr) + if len(h.writer.adds) != 1 || len(h.writer.comments) != 0 { + t.Fatalf("same head again: adds=%v comments=%v, want no new writes", h.writer.adds, h.writer.comments) + } + + // A restart reloads the request from disk. + h.store = loadDepBotConflictStore(h.path) + h.adoptPassAt(depBotT0.Add(4*depBotRedCIGrace), f.policy(), pr) + if len(h.writer.adds) != 1 || len(h.writer.comments) != 0 { + t.Fatalf("after restart: adds=%v comments=%v, want no new writes", h.writer.adds, h.writer.comments) + } + + // The bot pushed a new head: eligible again once it is red past the grace. + next := depBotPR("dependabot[bot]", "sha-2", redCI) + h.redPastGrace(depBotT0.Add(5*depBotRedCIGrace), f.policy(), next) + if n := h.adoptLabelAdds(); n != 2 || len(h.writer.comments) != 0 { + t.Fatalf("new head: adds=%v comments=%v, want a second adoption request and no hand-off", h.writer.adds, h.writer.comments) + } + if rec, _ := h.store.adoptRequest(depBotKey); rec.HeadSHA != "sha-2" { + t.Fatalf("adopt record head = %q, want sha-2", rec.HeadSHA) + } +} + +// Every case the switch must leave to a person gets today's hand-off and no +// adoption request. +func TestDependencyBotAdoptSkipsToHandoff(t *testing.T) { + cases := []struct { + name string + author string + mut func(*github.PullRequest) + tweak func(*depBotAdoptFake, *depBotAdoptPolicy) + }{ + {"verdict missing", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { delete(f.verdicts, "sha-1") }}, + {"verdict advisory", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { f.verdicts["sha-1"] = "advisory" }}, + {"verdict approve", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { f.verdicts["sha-1"] = string(review.VerdictApprove) }}, + {"verdict requires_human", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { + f.verdicts["sha-1"] = string(review.VerdictRequiresHuman) + }}, + {"verdict on another head only", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { + delete(f.verdicts, "sha-1") + f.verdicts["sha-0"] = "changes_requested" + }}, + {"human-merge path", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { f.pathHeld = true }}, + {"human-merge path unreadable", "dependabot[bot]", nil, func(f *depBotAdoptFake, _ *depBotAdoptPolicy) { f.pathErr = errors.New("502") }}, + {"no human-merge path checker", "dependabot[bot]", nil, func(_ *depBotAdoptFake, p *depBotAdoptPolicy) { p.HumanMergePath = nil }}, + {"needs-owner-merge label", "dependabot[bot]", func(p *github.PullRequest) { p.Labels = []string{"needs-owner-merge"} }, nil}, + {"adoption disabled", "dependabot[bot]", nil, func(_ *depBotAdoptFake, p *depBotAdoptPolicy) { p.StageAdoption = false }}, + {"not a trusted bot", "renovate[bot]", nil, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h := newDepBotHarness(t) + f := newDepBotAdoptFake() + p := f.policy() + if tc.tweak != nil { + tc.tweak(f, &p) + } + pr := depBotPR(tc.author, "sha-1", func(p *github.PullRequest) { + redCI(p) + if tc.mut != nil { + tc.mut(p) + } + }) + h.redPastGrace(depBotT0, p, pr) + h.wantHandoffOnly(tc.name) + if _, ok := h.store.adoptRequest(depBotKey); ok { + t.Fatal("a skipped head recorded an adoption request") + } + }) + } +} + +// A held PR is already out of the hand-off sweep (dependencyBotHandoffCandidate); +// the switch does not change that: no request, no comment. A `hold` alone also +// keeps skipReason from asking, should the candidate filter ever widen. +func TestDependencyBotAdoptSkipsHeldPR(t *testing.T) { + h := newDepBotHarness(t) + f := newDepBotAdoptFake() + pr := depBotPR("dependabot[bot]", "sha-1", func(p *github.PullRequest) { + redCI(p) + p.Labels = []string{"hold"} + }) + h.redPastGrace(depBotT0, f.policy(), pr) + if len(h.writer.adds) != 0 || len(h.writer.comments) != 0 { + t.Fatalf("held PR: adds=%v comments=%v, want none", h.writer.adds, h.writer.comments) + } + for _, label := range []string{"hold", "do-not-merge", "do-not-merge/hold"} { + if why := f.policy().skipReason(context.Background(), "acme/widgets", depBotPR("dependabot[bot]", "sha-1", func(p *github.PullRequest) { + redCI(p) + p.Labels = []string{label} + })); why != depBotAdoptSkipHoldLabel { + t.Fatalf("%s: skipReason = %q, want %q", label, why, depBotAdoptSkipHoldLabel) + } + } +} + +// A green PR is never asked about, switch on or off. +func TestDependencyBotAdoptGreenDoesNothing(t *testing.T) { + h := newDepBotHarness(t) + f := newDepBotAdoptFake() + pr := depBotPR("dependabot[bot]", "sha-1", nil) + h.redPastGrace(depBotT0, f.policy(), pr) + if len(h.writer.adds) != 0 || len(h.writer.comments) != 0 || f.verdictReads != 0 { + t.Fatalf("green PR: adds=%v comments=%v verdict reads=%d, want none", h.writer.adds, h.writer.comments, f.verdictReads) + } +} + +// A failed label write is recorded for the head, so it is not retried; the +// next pass gives the person the usual hand-off. +func TestDependencyBotAdoptLabelFailureFallsBackToHandoff(t *testing.T) { + h := newDepBotHarness(t) + f := newDepBotAdoptFake() + pr := depBotPR("dependabot[bot]", "sha-1", redCI) + + h.adoptPassAt(depBotT0, f.policy(), pr) + h.writer.failAddLabel = true + h.adoptPassAt(depBotT0.Add(depBotRedCIGrace), f.policy(), pr) + if len(h.writer.comments) != 0 { + t.Fatalf("failure pass: comments = %v, want none yet", h.writer.comments) + } + if rec, ok := h.store.adoptRequest(depBotKey); !ok || !rec.Failed || rec.HeadSHA != "sha-1" { + t.Fatalf("adopt record = %+v (ok=%v), want a failed request on sha-1", rec, ok) + } + + h.writer.failAddLabel = false + h.adoptPassAt(depBotT0.Add(depBotRedCIGrace+time.Minute), f.policy(), pr) + h.wantHandoffOnly("after a failed request") + h.adoptPassAt(depBotT0.Add(2*depBotRedCIGrace), f.policy(), pr) + if len(h.writer.comments) != 1 || h.adoptLabelAdds() != 0 { + t.Fatalf("repeat: comments=%v adds=%v, want no retry and no second hand-off", h.writer.comments, h.writer.adds) + } +} + +// The verdict is the swarm's aggregate on exactly the PR's head, under the +// full or the short repo name, whatever the trusted-bot lane later logs. +func TestDependencyBotHeadVerdict(t *testing.T) { + art := review.Artifact{Items: []review.Aggregate{ + {Repo: "widgets", Number: 42, HeadSHA: "sha-1", Verdict: review.VerdictChangesRequested}, + {Repo: "acme/widgets", Number: 42, HeadSHA: "sha-0", Verdict: review.VerdictApprove}, + {Repo: "acme/gadgets", Number: 7, HeadSHA: "sha-9", Verdict: review.VerdictRequiresHuman}, + }} + for _, tc := range []struct { + repo string + number int + head string + want string + }{ + {"acme/widgets", 42, "sha-1", "changes_requested"}, + {"ACME/Widgets", 42, "sha-1", "changes_requested"}, + {"acme/widgets", 43, "sha-1", ""}, + {"acme/widgets", 42, "sha-0", "approve"}, + {"acme/widgets", 42, "sha-2", ""}, + {"acme/widgets", 42, "", ""}, + {"acme/gadgets", 7, "sha-9", "requires_human"}, + } { + if got := depBotHeadVerdict(art, tc.repo, tc.number, tc.head); got != tc.want { + t.Errorf("depBotHeadVerdict(%s#%d@%s) = %q, want %q", tc.repo, tc.number, tc.head, got, tc.want) + } + } +} + +// The live policy is off unless auto_merge.dependency_bot_adopt.enabled is +// set, and reads stage adoption and the trusted bot set from the config. +func TestDependencyBotAdoptPolicyFromConfig(t *testing.T) { + cfg := &config.Config{} + if p := depBotAdoptPolicyFromConfig(cfg, &depBotFakeReader{}, discardLogger()); p.Enabled { + t.Fatal("policy enabled with the switch unset") + } + cfg.AutoMerge.DependencyBotAdopt.Enabled = true + cfg.AutoMerge.TrustedBotAuthors = []string{"mergeraptor[bot]"} + p := depBotAdoptPolicyFromConfig(cfg, &depBotFakeReader{}, discardLogger()) + if !p.Enabled || !p.StageAdoption { + t.Fatalf("policy = %+v, want enabled with stage adoption on by default", p) + } + if !p.TrustedBot("mergeraptor[bot]") || p.TrustedBot("dependabot[bot]") { + t.Fatal("TrustedBot does not follow auto_merge.trusted_bot_authors") + } + if p.HumanMergePath != nil { + t.Fatal("a reader without HumanMergePathHeld must leave the path check unset (fail closed)") + } + if !p.HumanMerge(github.PullRequest{Labels: []string{"needs-owner-merge"}}) || p.HumanMerge(github.PullRequest{Title: "chore(deps): bump x"}) { + t.Fatal("HumanMerge does not follow the human-merge rule defaults") + } + off := false + cfg.Governor.Labels.Stage.Adoption.Enabled = &off + if p := depBotAdoptPolicyFromConfig(cfg, &depBotFakeReader{}, discardLogger()); p.StageAdoption { + t.Fatal("StageAdoption on with governor.labels.stage.adoption.enabled: false") + } +} diff --git a/src/cmd/hive/dependency_bot_conflicts.go b/src/cmd/hive/dependency_bot_conflicts.go index 9ed676114b..5eb9d036b3 100644 --- a/src/cmd/hive/dependency_bot_conflicts.go +++ b/src/cmd/hive/dependency_bot_conflicts.go @@ -74,6 +74,10 @@ type depBotConflictStore struct { // each PR's commit list said about its current head. rebase map[string]*depBotRebaseState branchFacts map[string]depBotBranchFacts + + // adopt holds the persisted red-CI adoption requests, one per bot head + // (dependency_bot_adopt.go). + adopt map[string]*depBotAdoptRecord } func loadDepBotConflictStore(path string) *depBotConflictStore { @@ -86,6 +90,8 @@ func loadDepBotConflictStore(path string) *depBotConflictStore { rebase: loadDepBotRebaseStates(depBotRebasePath(path)), branchFacts: map[string]depBotBranchFacts{}, + + adopt: loadDepBotAdoptRecords(depBotAdoptPath(path)), } data, err := os.ReadFile(path) if err != nil { @@ -246,6 +252,9 @@ func dependencyBotConflictComment(base string) string { // depBotRedCIGrace (the PR stays out of the fix loop); on a trusted-bot // head triaged as transient, only once the hive's one re-run of it // failed again or re-ran nothing (dependency_bot_transient_rerun.go); +// with auto_merge.dependency_bot_adopt on, a trusted-bot head the review +// swarm asked to change is instead given to the hive's adoption path, +// once per head (dependency_bot_adopt.go); // - a terminal required-check hold the automerge sweep reported (held for // approval, never started, never ran); // - a stranded branch: behind or conflicting past @@ -266,9 +275,12 @@ func runDependencyBotConflictSweep(ctx context.Context, cfg *config.Config, writ if cfg != nil { org = cfg.Project.Org } - sweepDependencyBotConflicts(ctx, getDepBotConflictStore(), org, cfg.DependencyBotRebaseAfter(), writer, reader, actionable, time.Now, logger) + adopt := depBotAdoptPolicyFromConfig(cfg, reader, logger) + sweepDependencyBotConflictsWith(ctx, getDepBotConflictStore(), org, cfg.DependencyBotRebaseAfter(), adopt, writer, reader, actionable, time.Now, logger) } +// sweepDependencyBotConflicts is the sweep with auto_merge.dependency_bot_adopt +// off. func sweepDependencyBotConflicts( ctx context.Context, store *depBotConflictStore, @@ -279,6 +291,21 @@ func sweepDependencyBotConflicts( actionable *github.ActionableResult, now func() time.Time, logger *slog.Logger, +) { + sweepDependencyBotConflictsWith(ctx, store, org, rebaseAfter, depBotAdoptPolicy{}, writer, reader, actionable, now, logger) +} + +func sweepDependencyBotConflictsWith( + ctx context.Context, + store *depBotConflictStore, + org string, + rebaseAfter time.Duration, + adopt depBotAdoptPolicy, + writer forge.IssueWriter, + reader depBotPRReader, + actionable *github.ActionableResult, + now func() time.Time, + logger *slog.Logger, ) { if store == nil || writer == nil || reader == nil || actionable == nil { return @@ -308,6 +335,7 @@ func sweepDependencyBotConflicts( } stranded := depBotRebaseCheck{store: store, reader: reader, window: rebaseAfter, now: now(), logger: logger} store.pruneRebase(seen) + store.pruneAdopt(seen) waiting := map[string]bool{} defer store.pruneObservations(waiting) @@ -407,6 +435,11 @@ func sweepDependencyBotConflicts( if red < depBotRedCIGrace || holdHandoff || rerun.holdsHandoff(red, owed) { continue } + if requestDependencyBotAdoption(ctx, adopt, store, writer, reader, repo, key, pr, now(), logger) { + // The hive's adoption path owns this head now (or the + // label write just failed: the hand-off follows next pass). + continue + } comment = dependencyBotRedCIComment(pr, rerun) case depBotHandoffStranded: st, _ := store.rebaseState(key) diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 71e5b4bd35..66ad8212a9 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -693,6 +693,55 @@ auto_merge: enabled: true # default; set false to leave such PRs held ``` +### Dependency-bot PRs that need a code change + +Some dependency bumps cannot go green without a code change, for example a Go +module major-version bump whose imports still name the old path. The fix loop +never pushes to another bot's branch (the bot regenerates it), so by default +the dependency-bot sweep hands such a PR to a person once a required check has +stayed red on the same head for 4 hours (see the operator reference). + +`auto_merge.dependency_bot_adopt.enabled` (default **off**) lets the hive take +that step itself. It applies to a Renovate, Dependabot or mergeraptor PR whose +bot is also in `auto_merge.trusted_bot_authors`. At the moment the red-CI +hand-off would fire (red past the 4 hours and after the hive's one transient +re-run, if one is owed), the sweep reads the review swarm's own aggregate +verdict for exactly that head from `review-verdicts.json`. This is the raw +swarm verdict, not the trusted-bot lane's advisory downgrade +(`auto_merge.trusted_bot_skip_review`). When it is `changes_requested`, the sweep +adds the `adoption/supersede` label, which is the same label the dashboard's +Adopt decision adds, and posts no hand-off for that head. The existing adoption +path then copies the PR to `hive/adopt-`, the fix loop repairs the copy, and +the copy merges through the self-authored lane. + +The request is made once per bot head and persisted beside the hand-off ledger +(`dependency-bot-conflicts-adopt.json`), so a restart does not repeat it; a new +head is eligible again. The label write is gated as write-back kind +`contributor_adopt`. The sweep keeps the usual person hand-off when: + +- the swarm's verdict on the head is missing, `advisory`, `approve` or + `requires_human`; +- the PR carries `hold`, `do-not-merge` or a human-merge label or title prefix + (`auto_merge.human_merge_labels`, `auto_merge.human_merge_title_prefixes`); +- the head touches the repo's `auto_merge.human_merge_paths` (the pin-only + exception still applies), or the changed files cannot be read; +- `governor.labels.stage.adoption` is off, so nothing would consume the label; +- the write-back gate refuses `contributor_adopt` on the PR. + +If the label write fails, the head is not asked again and the person gets the +hand-off on the next pass. Each request logs one INFO line, +`dependency-bot red CI: hive adoption requested`, with the repo, PR, head and +reason; a skip logs `hive adoption not requested; handing to a person` with +why. + +```yaml +auto_merge: + trusted_bot_authors: + - renovate[bot] + dependency_bot_adopt: + enabled: true # default false +``` + ### Breaking-titled or `needs-owner-merge` PRs wait for a human A PR whose trimmed title starts with `⚠️` (U+26A0, with or without the VS16 diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 1be4cff645..74d17fbcbb 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -533,6 +533,12 @@ fallback when the approval sweep is off or refused: already labelled `needs-human`, `hold` or `do-not-merge`, comments once per head and reason, and removes only the `needs-human` label it added once CI is green, the conflict is gone or the PR closes (#11558, #12379). + With `auto_merge.dependency_bot_adopt.enabled` on (default off), a red + trusted-bot PR whose head the review swarm marked `changes_requested` is + given to the hive's adoption path instead of a person: the sweep adds + `adoption/supersede` once per head (write-back kind `contributor_adopt`) and + posts no hand-off for that head. Every other case keeps the hand-off; see + [hive-merge.md](../hive-merge.md#dependency-bot-prs-that-need-a-code-change). - A dependency bot stops rebasing a branch once someone else has committed to it (a person's "Update branch", a stray merge-forward), and the hive never base-syncs a bot's branch, so such a PR could sit behind its base forever. @@ -617,6 +623,7 @@ advanced into the merge path. | `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). | | `auto_merge.trusted_bot_skip_review` | `true` | The review swarm's verdict is advisory for PRs authored by a `trusted_bot_authors` login: a `requires_human` / `changes_requested` verdict is recorded but never holds the merge or routes the PR to "needs a person" — the lane's safety is the repo's CI. Set `false` to make bot PRs obey the swarm like the App's own. See [hive-merge.md](../hive-merge.md#trusted-bot-authors). | | `auto_merge.bot_takeover.enabled` | `true` | When `github-actions[bot]` is in `auto_merge.trusted_bot_authors`, re-author its same-repo PRs whose required `pull_request` checks can never run (the bot opened them with a workflow `GITHUB_TOKEN`). After the head is older than both `min_head_age` and 30 minutes with no `pull_request` run, the App pushes the same change as one signed-off commit to `hive/takeover-`, opens a PR with the original title/body plus `Supersedes #`, comments `Superseded by #N` on the bot PR and closes it. One attempt per bot head SHA. See [hive-merge.md](../hive-merge.md#github-actionsbot-pr-takeover). | +| `auto_merge.dependency_bot_adopt.enabled` | `false` | **Settings → Features → Auto-merge → "Adopt red dependency-bot PRs that need a code change"**; admin MCP `auto_merge.update` field `dependency_bot_adopt_enabled`. When a Renovate/Dependabot/mergeraptor PR whose bot is in `auto_merge.trusted_bot_authors` reaches the dependency-bot red-CI hand-off (red on the same head for 4 hours, after the hive's one transient re-run if owed) and the review swarm's own verdict on that exact head is `changes_requested`, the sweep adds `adoption/supersede` (what the dashboard's Adopt decision adds) instead of handing the PR to a person, once per bot head. The adoption path copies it to `hive/adopt-` and the fix loop repairs the copy. Kept for a person: no `changes_requested` verdict on the head, a hold or human-merge label/title, a head touching `auto_merge.human_merge_paths` (pin-only exception honored), stage adoption off, or `contributor_adopt` refused by the write-back gate. A failed label write falls back to the hand-off on the next pass. See [hive-merge.md](../hive-merge.md#dependency-bot-prs-that-need-a-code-change). | | `auto_merge.trusted_authors.enabled` | `false` | Enables the opt-in human-authored PR tier: Hive may merge a green PR only when the author already holds the required hive role and, by default, GitHub push/maintain/admin permission on that repo. | | `auto_merge.trusted_authors.repos` | empty = all watched repos | Optional repo allow-list for the trusted-author tier. The dashboard renders this as a watched-repo multi-select; selecting nothing preserves the all-repos default. | | `auto_merge.trusted_authors.require_role` | `merger` | Minimum `dashboard.authorized_users` role the PR author must hold (`merger` or `owner`). | diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index fff4f49c90..55ce41c4c7 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -632,6 +632,7 @@ that level, the power the write-back exists to govern? | Stale-red base refresh (`cmd/hive/stale_red_base_refresh.go`, `pkg/github/stale_red_base_refresh.go`) | eval cycle, before the stuck-PR reaper, at most every 5 min | **branch push** (`update-branch` merge of the base), once per head and base tip, no comment | red PRs behind their base whose every failing check is green on the base tip; not drafts, held, non-editable forks, dependency-bot branches, 072 or 074 | `base_refresh` → hive-authored PRs, else L6 + label | | Missing-check base refresh (`cmd/hive/missing_check_base_refresh.go`, `pkg/github/missing_check_base_refresh.go`) | eval cycle, after the stale-red base refresh, at most every 5 min | **branch push** (`update-branch` merge of the base), once per head and base tip and once per missing check, no comment | PRs behind their base, otherwise green, whose head has no run at all for a required check that runs on the base tip or another open PR; not drafts, held, parked, non-editable forks, dependency-bot branches, 072 or 074 | `base_refresh` → hive-authored PRs, else L6 + label | | Dependency-bot rebase request (`cmd/hive/dependency_bot_rebase_request.go`, `pkg/github/dependency_bot_rebase.go`) | governor eval, in the dependency-bot hand-off sweep | ticks Renovate's rebase/retry checkbox (only that line of the PR description changes); once per head, no other comment. Never asks Dependabot, which refuses commands from apps: a stranded Dependabot PR is handed to a person at once | dependency-bot PRs behind or conflicting with their base past `governor.dependency_bot_rebase_after_s` (4h) whose bot stopped rebasing them; never a branch carrying someone else's non-merge commit | `bot_rebase_request` → L6 + label; refused: the PR is handed to a person instead (see [README](README.md)) | +| Dependency-bot adoption request (`cmd/hive/dependency_bot_adopt.go`) | governor eval, in the dependency-bot hand-off sweep, where the red-CI hand-off would fire; only with `auto_merge.dependency_bot_adopt.enabled` (default off) | `adoption/supersede` label (the dashboard Adopt decision's label); once per head, no comment | red dependency-bot PRs by a `trusted_bot_authors` bot whose head the review swarm marked `changes_requested`; never held, human-merge-labelled or `human_merge_paths` PRs, or with stage adoption off | `contributor_adopt` → L6 + label; refused: the PR gets the usual person hand-off | | Level hold, self-authorization & reporter-trust releases (`pr_level_hold.go`, `automerge/self_authorization_release.go`, `reporter_trust_release.go`) | PR watcher | `hold` label add/remove | agent PRs | own items (hive-authored) — not gated | | Migrations & retirements (`hive_hold_migration.go`, `hive_id_label_retire.go`, `claimed_by_human_migration.go`, `origin_labels.go`) | boot, one-shot | label renames | items carrying hive labels | opted in by carrying hive labels | diff --git a/src/pkg/adminmcp/tools_automerge_ops.go b/src/pkg/adminmcp/tools_automerge_ops.go index 33d4de76ce..ca19ed129c 100644 --- a/src/pkg/adminmcp/tools_automerge_ops.go +++ b/src/pkg/adminmcp/tools_automerge_ops.go @@ -114,6 +114,7 @@ var autoMergeFields = []amField{ {key: "human_merge_paths", kind: amRepoPaths, widen: amWidenPaths, why: "pull requests touching these paths no longer wait for a person to merge them"}, {key: "human_merge_pin_only", kind: amPinOnly, widen: amWidenPinOnly}, {key: "bot_takeover_enabled", kind: amBool, widen: amWidenOn, why: "the App re-authors trusted github-actions[bot] pull requests and merges its copy"}, + {key: "dependency_bot_adopt_enabled", kind: amBool, widen: amWidenOn, why: "the hive adopts red trusted dependency-bot pull requests its review asked to change, and merges its fixed copy"}, {key: "require_current_base_default", kind: amBool, widen: amWidenOff, why: "repositories without an override may merge without the current base tip"}, {key: "merge_train.enabled", kind: amBool}, {key: "merge_train.max_rebase_attempts", kind: amInt}, diff --git a/src/pkg/adminmcp/tools_automerge_ops_test.go b/src/pkg/adminmcp/tools_automerge_ops_test.go index 1383a5d182..43322c5938 100644 --- a/src/pkg/adminmcp/tools_automerge_ops_test.go +++ b/src/pkg/adminmcp/tools_automerge_ops_test.go @@ -59,6 +59,7 @@ func autoMergeFixture() map[string]any { "project_repos": []string{"org/a", "org/b", "org/c"}, "trusted_bot_authors": []string{"dependabot[bot]"}, "bot_takeover_enabled": false, + "dependency_bot_adopt_enabled": false, "require_current_base_default": false, "merge_train": map[string]any{"enabled": true, "max_rebase_attempts": 2}, "native_merge_queue": map[string]any{"enabled": true, "repos": []string{"org/a"}, "bases": []string{"org/a#main"}, "skip_current_base_gate": false, "probe_ttl": "30m0s"}, @@ -152,6 +153,28 @@ func TestAutoMergeUpdateOneRepoChangeKeepsTheOthers(t *testing.T) { } } +// auto_merge.dependency_bot_adopt.enabled travels as the endpoint's flat +// dependency_bot_adopt_enabled field, and turning it on is widening: the hive +// then takes red trusted dependency-bot pull requests over on its own. +func TestAutoMergeUpdateDependencyBotAdoptEnabled(t *testing.T) { + p := &autoMergeProvider{settings: autoMergeFixture()} + h := autoMergeHandler(p) + preview, id := autoMergePreview(t, h, map[string]any{"dependency_bot_adopt_enabled": true}) + want := `{"dependency_bot_adopt_enabled":true}` + if got := compactJSON(preview.Request.Body); got != want { + t.Fatalf("body = %s, want %s", got, want) + } + if !strings.HasPrefix(preview.WideningDisclosure, "Widening:") { + t.Fatalf("turning dependency_bot_adopt_enabled on must be widening: %s", preview.WideningDisclosure) + } + if _, err := h.ConfirmWrite(context.Background(), map[string]any{"confirmation_id": id}); err != nil { + t.Fatalf("confirm: %v", err) + } + if len(p.requests) != 1 || compactJSON(p.requests[0].Body) != want { + t.Fatalf("executed %+v, want body %s", p.requests, want) + } +} + // Taking a pattern away from human_merge_paths lets the hive merge pull // requests that touch it, so the preview must say so; adding one must not. func TestAutoMergeUpdateFlagsHumanMergePathRemovalAsWidening(t *testing.T) { @@ -194,6 +217,7 @@ func TestAutoMergeUpdateWideningRules(t *testing.T) { "soak 0 is the default 30": {map[string]any{"contributor_lane": map[string]any{"soak_minutes": float64(0)}}, false}, "exclude label added": {map[string]any{"trusted_authors": map[string]any{"exclude_labels": map[string]any{"add": []any{"wip"}}}}, false}, "self-authored switched off": {map[string]any{"self_authored": false}, false}, + "dependency-bot adopt on": {map[string]any{"dependency_bot_adopt_enabled": true}, true}, } { t.Run(name, func(t *testing.T) { preview, _ := autoMergePreview(t, autoMergeHandler(&autoMergeProvider{settings: autoMergeFixture()}), tc.args) diff --git a/src/pkg/config/automerge_trusted_bot_test.go b/src/pkg/config/automerge_trusted_bot_test.go index ef8b0433cd..cbd4944ca4 100644 --- a/src/pkg/config/automerge_trusted_bot_test.go +++ b/src/pkg/config/automerge_trusted_bot_test.go @@ -168,6 +168,38 @@ func TestBotTakeoverAutoMergeConfigDefaultsOnAndHonorsExplicitOff(t *testing.T) } } +func TestDependencyBotAdoptAutoMergeConfigDefaultsOffAndRoundTrips(t *testing.T) { + var a AutoMergeConfig + if a.DependencyBotAdopt.IsEnabled() { + t.Fatal("auto_merge.dependency_bot_adopt.enabled must default off") + } + if err := yaml.Unmarshal([]byte("dependency_bot_adopt:\n enabled: true\n"), &a); err != nil { + t.Fatal(err) + } + if !a.DependencyBotAdopt.IsEnabled() { + t.Fatal("explicit auto_merge.dependency_bot_adopt.enabled: true must enable the adoption request") + } + out, err := yaml.Marshal(a) + if err != nil { + t.Fatal(err) + } + var back AutoMergeConfig + if err := yaml.Unmarshal(out, &back); err != nil { + t.Fatal(err) + } + if !back.DependencyBotAdopt.IsEnabled() { + t.Fatalf("auto_merge.dependency_bot_adopt.enabled lost on a YAML round trip:\n%s", out) + } + var off AutoMergeConfig + out, err = yaml.Marshal(off) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(out), "dependency_bot_adopt") { + t.Fatalf("the default (off) must not be written to hive.yaml:\n%s", out) + } +} + // registry_tiers_sufficient defaults on so an operator-granted registry tier // admits a contributor-lane PR without a claim marker; an explicit false // turns the registry path off. diff --git a/src/pkg/config/review_config.go b/src/pkg/config/review_config.go index 83bda632f7..acefccc680 100644 --- a/src/pkg/config/review_config.go +++ b/src/pkg/config/review_config.go @@ -589,6 +589,15 @@ type AutoMergeConfig struct { // that supersedes the bot PR, and closes the bot PR. It applies only when // github-actions[bot] is in TrustedBotAuthors. BotTakeover BotTakeoverAutoMergeConfig `yaml:"bot_takeover,omitempty" json:"bot_takeover,omitempty"` + // DependencyBotAdopt lets the dependency-bot hand-off sweep ask the hive + // to adopt a red Renovate/Dependabot PR that needs a code change, instead + // of only handing it to a person. It applies to a dependency-bot PR whose + // author is also in TrustedBotAuthors, once the red-CI hand-off would + // fire, when the review swarm's own verdict on that exact head is + // changes_requested: the sweep adds the `adoption/supersede` label (what + // the dashboard's Adopt decision adds), and the existing adoption path + // copies the PR to `hive/adopt-` for the fix loop. Default off. + DependencyBotAdopt DependencyBotAdoptAutoMergeConfig `yaml:"dependency_bot_adopt,omitempty" json:"dependency_bot_adopt,omitempty"` // TrustedAuthors enables a separate, default-off sweep for human-authored // PRs whose AUTHOR already holds merge authority. Unlike the App // self-authored lane, this never bypasses to create new authority: the @@ -904,6 +913,18 @@ func (b BotTakeoverAutoMergeConfig) IsEnabled() bool { return b.Enabled == nil || *b.Enabled } +// DependencyBotAdoptAutoMergeConfig is auto_merge.dependency_bot_adopt.*. +type DependencyBotAdoptAutoMergeConfig struct { + // Enabled turns the adoption request on. Unset means OFF: the sweep + // only hands a red dependency-bot PR to a person, as before. + Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` +} + +// IsEnabled reports auto_merge.dependency_bot_adopt.enabled (default false). +func (d DependencyBotAdoptAutoMergeConfig) IsEnabled() bool { + return d.Enabled +} + type TrustedAuthorAutoMergeConfig struct { Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` Repos []string `yaml:"repos,omitempty" json:"repos,omitempty"` diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 9150b2d04a..8168fec683 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -802,6 +802,7 @@ }, "auto_merge": { "bot_takeover": {}, + "dependency_bot_adopt": {}, "trusted_authors": {}, "contributor_lane": {}, "contributor_tier": {}, diff --git a/src/pkg/dashboard/api_config_automerge.go b/src/pkg/dashboard/api_config_automerge.go index d61f7226f3..563d43c177 100644 --- a/src/pkg/dashboard/api_config_automerge.go +++ b/src/pkg/dashboard/api_config_automerge.go @@ -176,6 +176,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { // BotTakeoverEnabled is auto_merge.bot_takeover.enabled; flat so the // dialog's plain toggle can stage it. BotTakeoverEnabled *bool `json:"bot_takeover_enabled"` + // DependencyBotAdoptEnabled is auto_merge.dependency_bot_adopt.enabled; + // flat for the same reason. + DependencyBotAdoptEnabled *bool `json:"dependency_bot_adopt_enabled"` // RequireCurrentBaseDefault is auto_merge.require_current_base_default, // the Features toggle "Merge only on current base" (#15335). Per-repo // overrides travel on PUT /api/config/governor/repos. @@ -436,6 +439,9 @@ func (s *Server) handleAutoMergePut(w http.ResponseWriter, r *http.Request) { v := *body.BotTakeoverEnabled cfg.AutoMerge.BotTakeover.Enabled = &v } + if body.DependencyBotAdoptEnabled != nil { + cfg.AutoMerge.DependencyBotAdopt.Enabled = *body.DependencyBotAdoptEnabled + } if body.RequireCurrentBaseDefault != nil { v := *body.RequireCurrentBaseDefault cfg.AutoMerge.RequireCurrentBaseDefault = &v @@ -620,6 +626,7 @@ func autoMergeSectionResponse(cfg *config.Config) map[string]interface{} { "trusted_bot_authors_set": am.TrustedBotAuthors != nil, "trusted_bot_skip_review": am.TrustedBotSkipsReview(), "bot_takeover_enabled": am.BotTakeover.IsEnabled(), + "dependency_bot_adopt_enabled": am.DependencyBotAdopt.IsEnabled(), "require_current_base_default": am.CurrentBaseDefaultEnabled(), "skip_current_base": emptyIfNilStrings(am.SkipCurrentBase), "merge_train": map[string]interface{}{ diff --git a/src/pkg/dashboard/github_settings_parity_test.go b/src/pkg/dashboard/github_settings_parity_test.go index e7f8b21b41..fe506daa71 100644 --- a/src/pkg/dashboard/github_settings_parity_test.go +++ b/src/pkg/dashboard/github_settings_parity_test.go @@ -134,8 +134,8 @@ func TestConfigGitHubParityBatch6RoundTrip(t *testing.T) { } } -// The scorer-tuning good_first_issue.* keys and auto_merge.bot_takeover -// round-trip through their section PUTs. +// The scorer-tuning good_first_issue.* keys, auto_merge.bot_takeover and +// auto_merge.dependency_bot_adopt round-trip through their section PUTs. func TestParityBatch6FeaturesRoundTrip(t *testing.T) { s := covApiServer(t) before := s.deps.Config.GoodFirstIssue @@ -200,6 +200,36 @@ func TestParityBatch6FeaturesRoundTrip(t *testing.T) { if am["bot_takeover_enabled"] != false { t.Fatalf("auto-merge response bot_takeover_enabled = %v", am["bot_takeover_enabled"]) } + if am["dependency_bot_adopt_enabled"] != false { + t.Fatalf("auto-merge response dependency_bot_adopt_enabled = %v, want false by default", am["dependency_bot_adopt_enabled"]) + } + + // auto_merge.dependency_bot_adopt.enabled defaults off and round-trips. + if s.deps.Config.AutoMerge.DependencyBotAdopt.IsEnabled() { + t.Fatal("dependency-bot adoption should default off") + } + rec = doPut(s, "/api/config/auto-merge", map[string]any{"dependency_bot_adopt_enabled": true}) + if rec.Code != http.StatusOK { + t.Fatalf("auto-merge PUT: %d — %s", rec.Code, rec.Body.String()) + } + if !s.deps.Config.AutoMerge.DependencyBotAdopt.IsEnabled() { + t.Fatal("dependency_bot_adopt_enabled=true not applied") + } + am = nil + if err := json.Unmarshal(rec.Body.Bytes(), &am); err != nil { + t.Fatal(err) + } + if am["dependency_bot_adopt_enabled"] != true { + t.Fatalf("auto-merge response dependency_bot_adopt_enabled = %v", am["dependency_bot_adopt_enabled"]) + } + // The flat toggles are independent: setting one leaves the other. + if s.deps.Config.AutoMerge.BotTakeover.IsEnabled() { + t.Fatal("dependency_bot_adopt_enabled PUT changed bot_takeover") + } + rec = doPut(s, "/api/config/auto-merge", map[string]any{"dependency_bot_adopt_enabled": false}) + if rec.Code != http.StatusOK || s.deps.Config.AutoMerge.DependencyBotAdopt.IsEnabled() { + t.Fatalf("dependency_bot_adopt_enabled=false not applied: %d — %s", rec.Code, rec.Body.String()) + } } // Every key this batch exposes renders with its YAML-key hint next to a @@ -216,6 +246,7 @@ func TestParityBatch6SettingsRenderEveryKey(t *testing.T) { {"good_first_issue.docs_url", `data-arg1="goodFirstIssueDocsUrl" data-arg-types="s,s,w"`}, {"good_first_issue.comment_template", `data-arg1="goodFirstIssueCommentTemplate" data-arg-types="s,s,v"`}, {"auto_merge.bot_takeover.enabled", `data-section="auto-merge" data-key="bot_takeover_enabled"`}, + {"auto_merge.dependency_bot_adopt.enabled", `data-section="auto-merge" data-key="dependency_bot_adopt_enabled"`}, } { if !strings.Contains(features, "yamlHint('"+c.yaml+"')") { t.Errorf("%s has no YAML-key hint", c.yaml) diff --git a/src/pkg/dashboard/static-src/js/config-features.js b/src/pkg/dashboard/static-src/js/config-features.js index 8131057dd9..a4b296c957 100644 --- a/src/pkg/dashboard/static-src/js/config-features.js +++ b/src/pkg/dashboard/static-src/js/config-features.js @@ -596,6 +596,10 @@
Take over github-actions[bot] PRs whose checks cannot run ${yamlHint('auto_merge.bot_takeover.enabled')} ${settingHelpMark('operator-reference/README', 'app-self-merge-sweep-auto_merge', 'Take over github-actions[bot] PRs', `On by default. Applies only when github-actions[bot] is a trusted bot author above. A PR that bot opens with a workflow GITHUB_TOKEN never triggers pull_request checks, so it can never go green. Once its head is older than both the minimum head age and 30 minutes with no pull_request run, the App pushes the same change as one signed-off commit to hive/takeover-<n>, opens a PR that supersedes it and closes the bot PR. One attempt per bot head SHA. Applies on the next sweep.`)} +
+
+ Adopt red dependency-bot PRs that need a code change ${yamlHint('auto_merge.dependency_bot_adopt.enabled')} ${settingHelpMark('operator-reference/README', 'app-self-merge-sweep-auto_merge', 'Adopt red dependency-bot PRs', `Off by default. Applies to a Renovate or Dependabot PR whose bot is a trusted bot author above. When a required check has stayed red on the same head for 4 hours (after the hive's one transient re-run, if owed) and the hive's review of that exact head asked for changes, the hive adds the adoption/supersede label instead of handing the PR to a person: the adoption path copies it to hive/adopt-<n> and the fix loop repairs the copy. One request per bot head. Skipped, with the usual hand-off, for a held PR, a human-merge label or title, a PR touching auto_merge.human_merge_paths, or when stage adoption is off. Applies on the next sweep.`)} +
diff --git a/src/pkg/dashboard/static-src/js/config-state.js b/src/pkg/dashboard/static-src/js/config-state.js index 571b404bc1..473e715445 100644 --- a/src/pkg/dashboard/static-src/js/config-state.js +++ b/src/pkg/dashboard/static-src/js/config-state.js @@ -128,7 +128,7 @@ { tab: 'Features', section: 'Agents & tooling', label: 'Swarm banner wording', key: 'swarm.event_name', text: 'swarm event name call to arms leaderboard title banner swarm.event_name swarm.call_to_arms swarm.leaderboard_title' }, { tab: 'Features', section: 'Agents & tooling', label: 'Tool approval inbox path', key: 'tool_approval.inbox_path', text: 'tool approval inbox pending approvals path tool_approval.inbox_path' }, { tab: 'Features', section: 'Auto-merge', label: 'Merge train', key: 'auto_merge.merge_train.enabled', text: 'merge train conflict overlap rebase attempts stall warning after seconds governor.merge_train_stall_warn_s auto_merge.merge_train.max_rebase_attempts' }, - { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled' }, + { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled dependency bot adopt renovate dependabot red ci auto_merge.dependency_bot_adopt.enabled' }, { tab: 'Features', section: 'Experimental', label: 'Long-running runs: checkpoints, triage and Spek recheck', key: 'runs.checkpoints.implement', text: 'runs checkpoints spec plan implement hold owner approval wait timeout severity triage clarify comment body length spek spektacular recheck cadence interval delta tasks discovery proxy timeout runs.checkpoints.spec runs.checkpoints.implement runs.wait_timeout_seconds runs.wait_severity runs.triage.min_body_chars runs.triage.clarify_comment runs.spektacular.binary runs.spektacular.recheck.enabled runs.spektacular.recheck.default_interval runs.spektacular.recheck.max_delta_tasks runs.spektacular.recheck.discovery_proxy runs.spektacular.recheck.discovery.enabled runs.spektacular.recheck.discovery.timeout runs.spektacular.recheck.discovery.max_total_items' }, { tab: 'Features', section: 'Experimental', label: 'External execution: Flue, OMP and vibe-kanban', key: 'runs.external.flue.mode', text: 'external execution flue omp vibe kanban workbench report-only shadow endpoint workflow version project state dir mcp command runs.external.flue.mode runs.external.flue.endpoint runs.external.flue.workflow_version runs.external.omp.mode runs.external.omp.workflow_version runs.external.vibe_kanban.enabled runs.external.vibe_kanban.mode runs.external.vibe_kanban.project_id runs.external.vibe_kanban.state_dir runs.external.vibe_kanban.workflow_version runs.external.vibe_kanban.mcp_command' }, { tab: 'Features', section: 'Integrations & observability', label: 'OpenTelemetry export', key: 'otel.enabled', text: 'otel opentelemetry export endpoint headers insecure sample ratio service name otel.enabled otel.endpoint otel.headers. otel.insecure otel.sample_ratio otel.service_name' }, diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index fce37a565d..48a4dc84b5 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -60968,7 +60968,7 @@

Configure LiteLLM

{ tab: 'Features', section: 'Agents & tooling', label: 'Swarm banner wording', key: 'swarm.event_name', text: 'swarm event name call to arms leaderboard title banner swarm.event_name swarm.call_to_arms swarm.leaderboard_title' }, { tab: 'Features', section: 'Agents & tooling', label: 'Tool approval inbox path', key: 'tool_approval.inbox_path', text: 'tool approval inbox pending approvals path tool_approval.inbox_path' }, { tab: 'Features', section: 'Auto-merge', label: 'Merge train', key: 'auto_merge.merge_train.enabled', text: 'merge train conflict overlap rebase attempts stall warning after seconds governor.merge_train_stall_warn_s auto_merge.merge_train.max_rebase_attempts' }, - { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled' }, + { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled dependency bot adopt renovate dependabot red ci auto_merge.dependency_bot_adopt.enabled' }, { tab: 'Features', section: 'Experimental', label: 'Long-running runs: checkpoints, triage and Spek recheck', key: 'runs.checkpoints.implement', text: 'runs checkpoints spec plan implement hold owner approval wait timeout severity triage clarify comment body length spek spektacular recheck cadence interval delta tasks discovery proxy timeout runs.checkpoints.spec runs.checkpoints.implement runs.wait_timeout_seconds runs.wait_severity runs.triage.min_body_chars runs.triage.clarify_comment runs.spektacular.binary runs.spektacular.recheck.enabled runs.spektacular.recheck.default_interval runs.spektacular.recheck.max_delta_tasks runs.spektacular.recheck.discovery_proxy runs.spektacular.recheck.discovery.enabled runs.spektacular.recheck.discovery.timeout runs.spektacular.recheck.discovery.max_total_items' }, { tab: 'Features', section: 'Experimental', label: 'External execution: Flue, OMP and vibe-kanban', key: 'runs.external.flue.mode', text: 'external execution flue omp vibe kanban workbench report-only shadow endpoint workflow version project state dir mcp command runs.external.flue.mode runs.external.flue.endpoint runs.external.flue.workflow_version runs.external.omp.mode runs.external.omp.workflow_version runs.external.vibe_kanban.enabled runs.external.vibe_kanban.mode runs.external.vibe_kanban.project_id runs.external.vibe_kanban.state_dir runs.external.vibe_kanban.workflow_version runs.external.vibe_kanban.mcp_command' }, { tab: 'Features', section: 'Integrations & observability', label: 'OpenTelemetry export', key: 'otel.enabled', text: 'otel opentelemetry export endpoint headers insecure sample ratio service name otel.enabled otel.endpoint otel.headers. otel.insecure otel.sample_ratio otel.service_name' }, @@ -75617,6 +75617,10 @@

${esc(s.title)}

Take over github-actions[bot] PRs whose checks cannot run ${yamlHint('auto_merge.bot_takeover.enabled')} ${settingHelpMark('operator-reference/README', 'app-self-merge-sweep-auto_merge', 'Take over github-actions[bot] PRs', `On by default. Applies only when github-actions[bot] is a trusted bot author above. A PR that bot opens with a workflow GITHUB_TOKEN never triggers pull_request checks, so it can never go green. Once its head is older than both the minimum head age and 30 minutes with no pull_request run, the App pushes the same change as one signed-off commit to hive/takeover-<n>, opens a PR that supersedes it and closes the bot PR. One attempt per bot head SHA. Applies on the next sweep.`)}
+
+
+ Adopt red dependency-bot PRs that need a code change ${yamlHint('auto_merge.dependency_bot_adopt.enabled')} ${settingHelpMark('operator-reference/README', 'app-self-merge-sweep-auto_merge', 'Adopt red dependency-bot PRs', `Off by default. Applies to a Renovate or Dependabot PR whose bot is a trusted bot author above. When a required check has stayed red on the same head for 4 hours (after the hive's one transient re-run, if owed) and the hive's review of that exact head asked for changes, the hive adds the adoption/supersede label instead of handing the PR to a person: the adoption path copies it to hive/adopt-<n> and the fix loop repairs the copy. One request per bot head. Skipped, with the usual hand-off, for a held PR, a human-merge label or title, a PR touching auto_merge.human_merge_paths, or when stage adoption is off. Applies on the next sweep.`)} +
diff --git a/src/pkg/github/human_merge_paths.go b/src/pkg/github/human_merge_paths.go index 74623ba133..38cf217cab 100644 --- a/src/pkg/github/human_merge_paths.go +++ b/src/pkg/github/human_merge_paths.go @@ -273,20 +273,9 @@ func (c *Client) mergeRequestHumanMergePathRefusal(ctx context.Context, req Merg if len(matches) == 0 { return "", nil } - if ex := c.humanMergePinOnlyFor(req.Repo); ex.Enabled { - reason := "PR author is not trusted" - if PinOnlyTrustedLogin(ex.TrustedAuthors, SafeGetLogin(pr.GetUser())) { - switch { - case req.ExpectSHA == "" || pr.GetHead().GetSHA() != req.ExpectSHA: - reason = "PR head does not match requested head" - case pr.ChangedFiles == nil || pr.GetChangedFiles() != len(files): - reason = "complete changed-file count is unavailable" - default: - reason = c.pinOnlyProvenance(ctx, owner, name, req, pr, files, matches, ex) - if reason == "" { - return "", nil - } - } + if reason, enabled := c.humanMergePinOnlyRejection(ctx, owner, name, req, pr, files, matches); enabled { + if reason == "" { + return "", nil } c.warn("merge-request watcher: pin-only exception rejected", "repo", req.Repo, "pr", req.Number, "reason", reason) } @@ -296,6 +285,67 @@ func (c *Client) mergeRequestHumanMergePathRefusal(ctx context.Context, req Merg return HumanMergePathReason(matches), nil } +// humanMergePinOnlyRejection applies the repo's auto_merge.human_merge_pin_only +// exception to a PR whose files match the human-merge paths. enabled is false +// when the repo has no enabled exception; otherwise reason is "" when the +// exception admits the PR and the refusal reason when it does not. It writes +// nothing: the relay and HumanMergePathHeld share it so both read one policy. +func (c *Client) humanMergePinOnlyRejection(ctx context.Context, owner, name string, req MergeRequest, pr *gh.PullRequest, files []intent.ChangedFile, matches []string) (reason string, enabled bool) { + ex := c.humanMergePinOnlyFor(req.Repo) + if !ex.Enabled { + return "", false + } + if !PinOnlyTrustedLogin(ex.TrustedAuthors, SafeGetLogin(pr.GetUser())) { + return "PR author is not trusted", true + } + switch { + case req.ExpectSHA == "" || pr.GetHead().GetSHA() != req.ExpectSHA: + return "PR head does not match requested head", true + case pr.ChangedFiles == nil || pr.GetChangedFiles() != len(files): + return "complete changed-file count is unavailable", true + } + return c.pinOnlyProvenance(ctx, owner, name, req, pr, files, matches, ex), true +} + +// HumanMergePathHeld reports whether PR number of repo, at headSHA, touches +// one of the repo's auto_merge.human_merge_paths without the repo's +// pin-only exception admitting it: the same files, matcher and exception the +// merge-request relay applies, read-only (no hold label, no comment). An +// unconfigured repo answers false with no API call. A PR that cannot be read, +// an incomplete changed-file list or a head other than headSHA answers +// (true, err) or true, so a caller deciding whether the hive may act on the +// PR fails closed. +func (c *Client) HumanMergePathHeld(ctx context.Context, repo string, number int, headSHA string) (bool, error) { + patterns := c.humanMergePathsFor(repo) + if len(patterns) == 0 { + return false, nil + } + if c.client == nil { + return true, fmt.Errorf("%s is set for %s but no GitHub client is configured", HumanMergePathsConfigKey, repo) + } + owner, name := c.splitRepo(repo) + pr, _, err := c.client.PullRequests.Get(ctx, owner, name, number) + if err != nil { + return true, fmt.Errorf("%s is set for %s but the PR could not be fetched: %w", HumanMergePathsConfigKey, repo, err) + } + if headSHA == "" || pr.GetHead().GetSHA() != headSHA { + return true, nil + } + files, err := ListPRChangedFiles(ctx, c.client, owner, name, pr) + if err != nil { + return true, fmt.Errorf("%s is set for %s but the complete changed-file list is unavailable: %w", HumanMergePathsConfigKey, repo, err) + } + matches := intent.HumanMergePathMatches(files, patterns) + if len(matches) == 0 { + return false, nil + } + req := MergeRequest{Repo: repo, Number: number, ExpectSHA: headSHA} + if reason, enabled := c.humanMergePinOnlyRejection(ctx, owner, name, req, pr, files, matches); enabled && reason == "" { + return false, nil + } + return true, nil +} + // pinOnlyProvenance applies the relay's share of the pin-only exception once // the author, requested head and file count have qualified: the whole diff // must classify as pin replacements, every commit must be a verified diff --git a/src/pkg/github/human_merge_paths_test.go b/src/pkg/github/human_merge_paths_test.go index 5667a88c61..08400fd4c9 100644 --- a/src/pkg/github/human_merge_paths_test.go +++ b/src/pkg/github/human_merge_paths_test.go @@ -454,3 +454,49 @@ func TestMergeRequestPinOnlyRequiresExpectedHead(t *testing.T) { t.Fatalf("refusal=%q err=%v labels=%v comments=%v; missing requested head must hold", refusal, err, f.labels, f.comments) } } + +// HumanMergePathHeld is the relay gate's read-only twin: the same file list, +// matcher and pin-only exception, failing closed, and never a hold label or a +// comment. +func TestHumanMergePathHeld(t *testing.T) { + trustedPin := map[string]PinOnlySpec{"o/r": {Enabled: true, Paths: []string{"Containerfile"}, Kinds: []string{"image-digest"}, TrustedAuthors: []string{"alice"}}} + for _, tc := range []struct { + name string + f *humanPathMergeFixture + paths map[string][]string + pinOnly map[string]PinOnlySpec + head string + want bool + wantErr bool + hits int + }{ + {name: "unconfigured", f: &humanPathMergeFixture{files: []string{".claude/settings.json"}}, head: "abc", want: false, hits: 0}, + {name: "configured without match", f: &humanPathMergeFixture{files: []string{"go.mod"}}, paths: map[string][]string{"o/r": {".claude/**"}}, head: "abc", want: false, hits: 1}, + {name: "match", f: &humanPathMergeFixture{files: []string{"go.mod", ".claude/settings.json"}}, paths: map[string][]string{"r": {".claude/**"}}, head: "abc", want: true, hits: 1}, + {name: "head moved", f: &humanPathMergeFixture{files: []string{"go.mod"}}, paths: map[string][]string{"o/r": {".claude/**"}}, head: "def", want: true, hits: 0}, + {name: "files error", f: &humanPathMergeFixture{filesStatus: http.StatusInternalServerError}, paths: map[string][]string{"o/r": {".claude/**"}}, head: "abc", want: true, wantErr: true, hits: -1}, + {name: "PR error", f: &humanPathMergeFixture{prStatus: http.StatusInternalServerError}, paths: map[string][]string{"o/r": {".claude/**"}}, head: "abc", want: true, wantErr: true, hits: -1}, + {name: "pin-only exception admits", f: pinOnlyRelayFixture(), paths: map[string][]string{"o/r": {"Containerfile"}}, pinOnly: trustedPin, head: "abc", want: false, hits: 1}, + {name: "pin-only exception disabled", f: pinOnlyRelayFixture(), paths: map[string][]string{"o/r": {"Containerfile"}}, head: "abc", want: true, hits: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + srv := newHumanPathMergeServer(t, tc.f) + t.Cleanup(srv.Close) + c := testMergeClient(t, srv.URL) + c.SetHumanMergePaths(tc.paths) + if tc.pinOnly != nil { + c.SetHumanMergePinOnly(tc.pinOnly) + } + got, err := c.HumanMergePathHeld(context.Background(), "o/r", 42, tc.head) + if got != tc.want || (err != nil) != tc.wantErr { + t.Fatalf("HumanMergePathHeld = (%v, %v), want (%v, err=%v)", got, err, tc.want, tc.wantErr) + } + if tc.hits >= 0 && tc.f.filesHits != tc.hits { + t.Fatalf("files hits = %d, want %d", tc.f.filesHits, tc.hits) + } + if len(tc.f.labels) != 0 || len(tc.f.comments) != 0 || tc.f.merges != 0 { + t.Fatalf("labels=%v comments=%v merges=%d; the check must write nothing", tc.f.labels, tc.f.comments, tc.f.merges) + } + }) + } +} diff --git a/src/pkg/rfccoverage/testdata/settings_index.html b/src/pkg/rfccoverage/testdata/settings_index.html index ac93c7d6cd..7721cc87c6 100644 --- a/src/pkg/rfccoverage/testdata/settings_index.html +++ b/src/pkg/rfccoverage/testdata/settings_index.html @@ -8,7 +8,7 @@ { tab: 'Features', section: 'Work intake & issue lifecycle', label: 'Duplicate PR sweep', key: 'duplicate_sweep.enabled', text: 'duplicate pr sweep superseded comments budget duplicate_sweep.enabled duplicate_sweep.post_comments duplicate_sweep.max_comments duplicate_sweep.max_prs_per_repo' }, { tab: 'Features', section: 'Work intake & issue lifecycle', label: 'Good first issue curation', key: 'good_first_issue.enabled', text: 'good first issue help wanted gfi curation new contributors coding agent clanker relay advertise welcome comment good_first_issue.enabled good_first_issue.max_per_repo good_first_issue.max_per_sweep good_first_issue.min_age good_first_issue.interval scorer body length packages score reselect cooldown docs url welcome comment template good_first_issue.min_body_chars good_first_issue.max_body_chars good_first_issue.max_packages good_first_issue.min_score good_first_issue.reselect_cooldown good_first_issue.docs_url good_first_issue.comment_template' }, { tab: 'Features', section: 'Work intake & issue lifecycle', label: 'Superseded PR grace period', key: 'supersession_sweep.grace_period', text: 'supersession superseded grace period close contributor pr supersession_sweep.grace_period' }, - { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled' }, + { tab: 'Features', section: 'Auto-merge', label: 'Auto-merge sweep limits', key: 'auto_merge.min_head_age', text: 'auto merge max merges per sweep minimum head age required author role auto_merge.max_merges auto_merge.min_head_age auto_merge.trusted_authors.require_role bot takeover github-actions auto_merge.bot_takeover.enabled dependency bot adopt renovate dependabot red ci auto_merge.dependency_bot_adopt.enabled' }, { tab: 'Features', section: 'Edge', label: 'Reviewer\'s note', key: 'edge.quoted', text: 'it\'s a quoted entry' }, { tab: 'Features', section: 'Edge', label: 'No key here', text: 'entries without a key are dropped' }, ]; From 58936593cd927212ef3a53c6a246ff1d0f2a682e Mon Sep 17 00:00:00 2001 From: Danathar <6772335+Danathar@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:31:12 -0500 Subject: [PATCH 2/2] test(notifications): track the renamed dependency-bot sweep write site The sweep's write calls moved into sweepDependencyBotConflictsWith, so the notification write-site inventory and its doc row name that function. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar <6772335+Danathar@users.noreply.github.com> --- src/docs/notifications.md | 2 +- src/pkg/github/notification_write_sites.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 10f32ef0aa..555e88332f 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -637,7 +637,7 @@ without a class. Review submissions and review requests are always counted as | `main.claimEscalationLookup` | `attention` | | | `main.liveTriageCommenter.CreateIssueComment` | `attention` | passthrough wrapper; attributed to its caller | | `main.noteHeldPRUpdateStopped` | `attention` | | -| `main.sweepDependencyBotConflicts` | `attention` | asks a person to rebase or retry a dependency-bot PR, or to comment `@dependabot recreate` on a stranded Dependabot PR (the hive never posts that command: Dependabot refuses commands from apps) | +| `main.sweepDependencyBotConflictsWith` | `attention` | asks a person to rebase or retry a dependency-bot PR, or to comment `@dependabot recreate` on a stranded Dependabot PR (the hive never posts that command: Dependabot refuses commands from apps) | | `mention.(*Responder).HandleAgentEvent` | `attention` | solicited completion reply to an explicit mention | | `mergelane.(*round).ensureForkWaitComment` | `attention` | asks the fork author to refresh the branch | | `worksource.(*forgeWorkSource).AddComment` | `attention` | passthrough wrapper; attributed to its caller | diff --git a/src/pkg/github/notification_write_sites.go b/src/pkg/github/notification_write_sites.go index 738fc0e45a..083085d87c 100644 --- a/src/pkg/github/notification_write_sites.go +++ b/src/pkg/github/notification_write_sites.go @@ -99,7 +99,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "github.attentionDelivery.Post": {Class: NotificationClassAttention}, "main.claimEscalationLookup": {Class: NotificationClassAttention}, "main.noteHeldPRUpdateStopped": {Class: NotificationClassAttention}, - "main.sweepDependencyBotConflicts": {Class: NotificationClassAttention}, + "main.sweepDependencyBotConflictsWith": {Class: NotificationClassAttention}, "mention.(*Responder).HandleAgentEvent": {Class: NotificationClassAttention}, "mergelane.(*round).ensureForkWaitComment": {Class: NotificationClassAttention}, "main.rfcCoverageForge.CreateComment": {Class: NotificationClassAttention},