From 6c227af8a1901f2cd8e9fad01ab940605e190bce Mon Sep 17 00:00:00 2001 From: Danathar Date: Tue, 10 Nov 2026 15:35:28 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20feat(dependency-bots):=20ask=20?= =?UTF-8?q?a=20stranded=20bot=20to=20rebase=20its=20own=20PR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dependency bot stops maintaining a branch once someone else has committed to it, and the hive never base-syncs a bot's branch, so on a base that requires up-to-date branches such a PR sat behind forever with nobody told. The dependency-bot hand-off sweep never looked at a PR that was only behind, and nothing ever asked the bot itself. The sweep now treats a dependency-bot PR that has been behind or conflicting for governor.dependency_bot_rebase_after_s (default 4h) as stranded when its head commit is not the bot's or its Renovate config rebases never. It asks the bot once per head through the bot's own mechanism: it ticks Renovate's rebase/retry checkbox (only that line of the description changes) or comments `@dependabot recreate`. If the head has not moved one window later, the PR goes to a person through the existing hand-off with the reason "dependency bot will not rebase this branch". A branch carrying someone else's non-merge commit is never regenerated; it goes to a person instead. The request is a new write-back kind, bot_rebase_request, defaulting to L6 with the opt-in label like base_refresh. When it refuses, a stranded PR that is only behind is handed to a person at the window, and a conflicting one keeps the 24-hour conflict hand-off. While a request is due or pending, the conflict and red-CI hand-offs wait, so a PR never gets the request and a person's comment at once. First-seen and requested heads persist beside the conflict ledger. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- .../added-dependency-bot-rebase-request.md | 1 + src/cmd/hive/dependency_bot_conflicts.go | 71 ++- src/cmd/hive/dependency_bot_conflicts_test.go | 2 +- src/cmd/hive/dependency_bot_handoffs.go | 3 + src/cmd/hive/dependency_bot_handoffs_test.go | 2 +- src/cmd/hive/dependency_bot_rebase_request.go | 542 ++++++++++++++++++ .../dependency_bot_rebase_request_test.go | 390 +++++++++++++ src/docs/acmm-policy-matrix.md | 2 +- src/docs/github-write-surface.md | 1 + .../labels-and-control-signals/reference.md | 4 +- src/docs/notifications.md | 2 +- src/docs/operator-reference/README.md | 28 + .../sweeps-and-operations.md | 1 + .../tools_cadence_writeback_ops_test.go | 6 + src/pkg/config/dashboard_config.go | 8 + src/pkg/config/defaults.go | 4 + src/pkg/config/governor_config.go | 7 + src/pkg/config/validate.go | 3 + .../dashboard/settings_parity_allowlist.txt | 1 + src/pkg/github/dependency_bot_rebase.go | 151 +++++ src/pkg/github/dependency_bot_rebase_test.go | 154 +++++ src/pkg/github/write_surface_internal.go | 1 + src/pkg/writeback/dedupe.go | 4 +- src/pkg/writeback/dedupe_test.go | 2 +- src/pkg/writeback/kinds.go | 8 + src/pkg/writeback/writeback_test.go | 43 ++ 26 files changed, 1425 insertions(+), 16 deletions(-) create mode 100644 changelog.d/added-dependency-bot-rebase-request.md create mode 100644 src/cmd/hive/dependency_bot_rebase_request.go create mode 100644 src/cmd/hive/dependency_bot_rebase_request_test.go create mode 100644 src/pkg/github/dependency_bot_rebase.go create mode 100644 src/pkg/github/dependency_bot_rebase_test.go diff --git a/changelog.d/added-dependency-bot-rebase-request.md b/changelog.d/added-dependency-bot-rebase-request.md new file mode 100644 index 0000000000..91e4c1a69d --- /dev/null +++ b/changelog.d/added-dependency-bot-rebase-request.md @@ -0,0 +1 @@ +- Dependency bots: a bot PR the bot has stopped rebasing no longer sits behind its base forever. Renovate and Dependabot stop maintaining a branch once someone else commits to it (a person's "Update branch", a stray merge-forward), and the hive never base-syncs a bot's branch, so on a base that requires up-to-date branches such a PR stayed behind with nobody told. The dependency-bot hand-off sweep now treats a bot PR that has been behind or conflicting for `governor.dependency_bot_rebase_after_s` (default 4 hours) as stranded when its head commit is not the bot's or its Renovate config rebases never, and asks the bot to rebase through the bot's own mechanism, once per head: it ticks Renovate's rebase/retry checkbox (only that line of the description changes) or comments `@dependabot recreate`. If the head has not moved one window later, the PR goes to a person through the existing hand-off (one comment plus `needs-human`, "dependency bot will not rebase this branch"). A branch carrying someone else's non-merge commit is never regenerated; it goes to a person instead. The request is the new write-back kind `bot_rebase_request` (default L6 with the opt-in label, editable in Settings → Features → Write-back containment and through the admin MCP `writeback.kind_policy` operation); when the kind refuses, a stranded PR that is only behind is still handed to a person once the window passes, and a conflicting one keeps the 24-hour conflict hand-off. diff --git a/src/cmd/hive/dependency_bot_conflicts.go b/src/cmd/hive/dependency_bot_conflicts.go index 71fe47b668..57b00bebed 100644 --- a/src/cmd/hive/dependency_bot_conflicts.go +++ b/src/cmd/hive/dependency_bot_conflicts.go @@ -68,6 +68,12 @@ type depBotConflictStore struct { // holds per PR head. observed map[string]*depBotObservation holds map[string]depBotHold + + // rebase holds the persisted stranded-branch records + // (dependency_bot_rebase_request.go); branchFacts, in memory only, what + // each PR's commit list said about its current head. + rebase map[string]*depBotRebaseState + branchFacts map[string]depBotBranchFacts } func loadDepBotConflictStore(path string) *depBotConflictStore { @@ -77,6 +83,9 @@ func loadDepBotConflictStore(path string) *depBotConflictStore { noMarker: map[string]string{}, observed: loadDepBotObservations(depBotObservedPath(path)), holds: map[string]depBotHold{}, + + rebase: loadDepBotRebaseStates(depBotRebasePath(path)), + branchFacts: map[string]depBotBranchFacts{}, } data, err := os.ReadFile(path) if err != nil { @@ -236,23 +245,32 @@ func dependencyBotConflictComment(base string) string { // - a failing required check that stayed red on the same head past // depBotRedCIGrace (the PR stays out of the fix loop); // - a terminal required-check hold the automerge sweep reported (held for -// approval, never started, never ran). +// approval, never started, never ran); +// - a stranded branch: behind or conflicting past +// governor.dependency_bot_rebase_after_s while the bot no longer rebases +// it, one window after a request to the bot through its own mechanism +// (dependency_bot_rebase_request.go) went unanswered, or as soon as the +// window passes when that request is not allowed or not safe. // // It takes that label back off once the reason is over (see // depBotHandoffResolved) or the PR closes — only if this sweep is the one -// that added it. It never pushes, rebases, closes, approves or ticks. +// that added it. It never pushes, rebases, closes or approves; the only +// writes besides the hand-off are that one rebase request per head (a +// ticked Renovate rebase/retry box or `@dependabot recreate`), gated as +// write-back kind bot_rebase_request. func runDependencyBotConflictSweep(ctx context.Context, cfg *config.Config, writer forge.IssueWriter, reader depBotPRReader, actionable *github.ActionableResult, logger *slog.Logger) { org := "" if cfg != nil { org = cfg.Project.Org } - sweepDependencyBotConflicts(ctx, getDepBotConflictStore(), org, writer, reader, actionable, time.Now, logger) + sweepDependencyBotConflicts(ctx, getDepBotConflictStore(), org, cfg.DependencyBotRebaseAfter(), writer, reader, actionable, time.Now, logger) } func sweepDependencyBotConflicts( ctx context.Context, store *depBotConflictStore, org string, + rebaseAfter time.Duration, writer forge.IssueWriter, reader depBotPRReader, actionable *github.ActionableResult, @@ -282,16 +300,44 @@ func sweepDependencyBotConflicts( undoDependencyBotConflicts(ctx, store, writer, reader, seen, logger) + if rebaseAfter <= 0 { + rebaseAfter = config.DefaultDependencyBotRebaseAfterS * time.Second + } + stranded := depBotRebaseCheck{store: store, reader: reader, window: rebaseAfter, now: now(), logger: logger} + store.pruneRebase(seen) + waiting := map[string]bool{} defer store.pruneObservations(waiting) for _, pr := range actionable.PRs.Items { - if pr.HeadSHA == "" || !dependencyBotHandoffCandidate(pr) { + if pr.HeadSHA == "" { + continue + } + botAuthor := dependencyBotHandoffCandidate(pr) + if !botAuthor && !dependencyBotBranchCandidate(pr) { continue } repo := qualify(pr.Repo) key := escalation.Key(repo, pr.Number) - heldReason := store.heldReason(key, pr.HeadSHA) - reason, ok := dependencyBotHandoffReason(pr, heldReason) + heldReason, reason, ok := "", "", false + if botAuthor { + heldReason = store.heldReason(key, pr.HeadSHA) + reason, ok = dependencyBotHandoffReason(pr, heldReason) + } + // A stranded branch (the bot stopped rebasing it) is asked about + // before any conflict or red-CI hand-off: holdHandoff keeps that + // comment back (its grace clock still runs) while a rebase request is + // due or pending, so the PR never gets the request and a person's + // comment at once. + holdHandoff := false + if heldReason == "" { + switch stranded.step(ctx, repo, key, pr) { + case depBotStrandedHandoff: + reason, ok = depBotHandoffStranded, true + case depBotStrandedHold: + holdHandoff = true + waiting[key] = true + } + } if !ok { continue } @@ -309,6 +355,13 @@ func sweepDependencyBotConflicts( case depBotHandoffHeld: comment = dependencyBotHeldCheckComment(pr.Author, heldReason) case depBotHandoffConflict: + if holdHandoff { + // A rebase request is due or pending: keep the grace clock + // running, post nothing yet. + waiting[key] = true + store.observe(key, pr.HeadSHA, reason, now()) + continue + } if pr.Author == renovateBotAuthor && !store.lacksMarker(key, pr.HeadSHA) { body, err := reader.GetPRBody(ctx, repo, pr.Number) if err != nil { @@ -332,10 +385,14 @@ func sweepDependencyBotConflicts( } case depBotHandoffRedCI: waiting[key] = true - if now().Sub(store.observe(key, pr.HeadSHA, reason, now())) < depBotRedCIGrace { + if now().Sub(store.observe(key, pr.HeadSHA, reason, now())) < depBotRedCIGrace || holdHandoff { continue } comment = dependencyBotRedCIComment(pr) + case depBotHandoffStranded: + st, _ := store.rebaseState(key) + facts, known := store.branchFactsFor(key, pr.HeadSHA) + comment = dependencyBotStrandedComment(pr, st, facts, known, rebaseAfter) } if !depBotWritebackAllowed(ctx, reader, repo, pr.Number, writeback.KindNeedsDecisionComment, comment, logger) { continue diff --git a/src/cmd/hive/dependency_bot_conflicts_test.go b/src/cmd/hive/dependency_bot_conflicts_test.go index 88719df141..71943f1eca 100644 --- a/src/cmd/hive/dependency_bot_conflicts_test.go +++ b/src/cmd/hive/dependency_bot_conflicts_test.go @@ -147,7 +147,7 @@ func (h *depBotHarness) pass(prs ...github.PullRequest) { a := &github.ActionableResult{} a.PRs.Items = prs now := func() time.Time { return time.Date(2026, 10, 12, 12, 0, 0, 0, time.UTC) } - sweepDependencyBotConflicts(context.Background(), h.store, "acme", h.writer, h.reader, a, now, discardLogger()) + sweepDependencyBotConflicts(context.Background(), h.store, "acme", 0, h.writer, h.reader, a, now, discardLogger()) } const depBotKey = "acme/widgets#42" diff --git a/src/cmd/hive/dependency_bot_handoffs.go b/src/cmd/hive/dependency_bot_handoffs.go index 25127aa2a5..32f1e4d645 100644 --- a/src/cmd/hive/dependency_bot_handoffs.go +++ b/src/cmd/hive/dependency_bot_handoffs.go @@ -99,6 +99,9 @@ func depBotHandoffResolved(rec depBotConflictRecord, pr github.PullRequest) bool // A new head re-creates the checks; a check that completes green // lets automerge merge (closed is handled by the caller). return pr.HeadSHA != "" && pr.HeadSHA != rec.HeadSHA + case depBotHandoffStranded: + // The bot (or a person) moved the head, or the PR caught up. + return (pr.HeadSHA != "" && pr.HeadSHA != rec.HeadSHA) || depBotStuckResolved(pr) default: return depBotConflictResolved(pr) } diff --git a/src/cmd/hive/dependency_bot_handoffs_test.go b/src/cmd/hive/dependency_bot_handoffs_test.go index a2017e53d0..afa2b4ab6f 100644 --- a/src/cmd/hive/dependency_bot_handoffs_test.go +++ b/src/cmd/hive/dependency_bot_handoffs_test.go @@ -16,7 +16,7 @@ func (h *depBotHarness) passAt(at time.Time, prs ...github.PullRequest) { h.t.Helper() a := &github.ActionableResult{} a.PRs.Items = prs - sweepDependencyBotConflicts(context.Background(), h.store, "acme", h.writer, h.reader, a, func() time.Time { return at }, discardLogger()) + sweepDependencyBotConflicts(context.Background(), h.store, "acme", 0, h.writer, h.reader, a, func() time.Time { return at }, discardLogger()) } func depBotPR(author, sha string, mut func(*github.PullRequest)) github.PullRequest { diff --git a/src/cmd/hive/dependency_bot_rebase_request.go b/src/cmd/hive/dependency_bot_rebase_request.go new file mode 100644 index 0000000000..196f8519bc --- /dev/null +++ b/src/cmd/hive/dependency_bot_rebase_request.go @@ -0,0 +1,542 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/escalation" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/writeback" +) + +// Stranded dependency-bot branches. The hive never base-syncs a dependency +// bot's branch (github.DependencyBotBranch): the bot rebases it itself. But +// a bot stops maintaining a branch once another identity has committed to it +// (a person clicking "Update branch", a stray merge-forward), and Renovate +// says so once ("will not automatically rebase this PR, because it does not +// recognize the last commit author"). On a base that requires up-to-date +// branches such a PR then sits behind forever: the hive will not sync it, the +// bot will not, and nobody is told. +// +// Once a dependency-bot PR has been behind or conflicting for the window +// (governor.dependency_bot_rebase_after_s, default 4h) and the bot has +// stopped rebasing it — its head commit is not the bot's, or its Renovate +// config rebases never — the sweep asks the bot to rebase through the bot's +// own mechanism, at most once per head (write-back kind bot_rebase_request): +// it ticks Renovate's rebase/retry box, or comments `@dependabot recreate`. +// If the head has not moved one window later, a person gets the PR through +// the ordinary hand-off (one comment plus needs-human, reason +// depBotHandoffStranded). It never asks when the branch carries a commit +// someone else wrote other than a merge of the base, because the bot's +// regeneration would drop it; that PR goes to a person instead. + +// depBotHandoffStranded is the hand-off reason for a PR whose bot will not +// rebase it. +const depBotHandoffStranded = "bot-will-not-rebase" + +// depBotStrandedReasonText is the plain-words reason shown with the hand-off. +const depBotStrandedReasonText = "dependency bot will not rebase this branch" + +// Rebase request mechanisms, recorded in depBotRebaseState.Via. +const ( + depBotViaRenovateCheckbox = "renovate-checkbox" + depBotViaAlreadyTicked = "renovate-checkbox-already-ticked" + depBotViaDependabot = "dependabot-recreate" +) + +// depBotRebaseState is the persisted stranded-branch record for one PR head. +// StuckSince is when the head was first seen behind or conflicting (zero +// while it is not); RequestedAt is when the bot was asked to rebase this +// head (zero until then). A new head replaces the record. +type depBotRebaseState struct { + HeadSHA string `json:"head_sha"` + StuckSince time.Time `json:"stuck_since,omitzero"` + RequestedAt time.Time `json:"requested_at,omitzero"` + Via string `json:"via,omitempty"` +} + +// depBotBranchFacts is what the PR's commit list says about one head, read +// once per head (in memory only). +type depBotBranchFacts struct { + HeadSHA string + // ForeignHead: the head commit was not written by the bot. + ForeignHead bool + // ForeignWork: some commit on the branch is neither the bot's nor a + // merge (a person's or a workflow's real change); regenerating the + // branch would drop it. + ForeignWork bool +} + +// depBotStrandedStep is what the stranded check tells the hand-off loop. +type depBotStrandedStep int + +const ( + // depBotStrandedNone: nothing to add; the existing hand-off reasons + // decide as before. + depBotStrandedNone depBotStrandedStep = iota + // depBotStrandedHold: the bot has been (or will be) asked to rebase + // this head; hold a conflict or red-CI hand-off so the PR does not get + // a request and a person's comment at once. + depBotStrandedHold + // depBotStrandedHandoff: hand the PR to a person now with + // depBotHandoffStranded. + depBotStrandedHandoff +) + +// depBotCommitLister reads a PR's commits. *github.Client satisfies it. +type depBotCommitLister interface { + ListPRCommits(ctx context.Context, repo string, number int) ([]github.PRCommit, error) +} + +// depBotRebaseRequester is the write side of a rebase request. +// *github.Client satisfies it. +type depBotRebaseRequester interface { + RequestRenovateRebase(ctx context.Context, repo string, number int, headSHA string) (github.RenovateRebaseCheckbox, error) + PostDependabotRecreate(ctx context.Context, repo string, number int, headSHA string) error +} + +// depBotRebasePolicy is a reader that answers the bot_rebase_request policy +// itself instead of through the GitHub write-back gate (a fake in tests). +type depBotRebasePolicy interface { + BotRebaseRequestAllowed(repo string, number int) bool +} + +// dependencyBotBranchCandidate is dependencyBotHandoffCandidate widened to +// any github.DependencyBotBranch PR (a `renovate/` head ref under any +// account); only the stranded check looks at the wider set. +func dependencyBotBranchCandidate(pr github.PullRequest) bool { + if pr.Draft || (pr.State != "" && !strings.EqualFold(pr.State, "open")) { + return false + } + if !github.DependencyBotBranch(pr.HeadRef, pr.Author) { + return false + } + return !escalation.HasNeedsHumanLabel(pr.Labels) && !github.HasHoldLabel(pr.Labels) && !hasLabel(pr.Labels, "do-not-merge") +} + +func depBotBehind(pr github.PullRequest) bool { + return strings.EqualFold(strings.TrimSpace(pr.MergeableState), "behind") +} + +func depBotStuck(pr github.PullRequest) bool { + return depBotBehind(pr) || conflictMergeState(pr) +} + +// depBotMergeStateKnown reports that GitHub computed a merge state, so "not +// behind and not conflicting" is evidence rather than a gap in the data. +func depBotMergeStateKnown(pr github.PullRequest) bool { + s := strings.ToLower(strings.TrimSpace(pr.MergeableState)) + return s != "" && s != "unknown" +} + +// depBotStuckResolved reports that a stranded hand-off is over without a new +// head: GitHub reports the PR neither behind nor conflicting. +func depBotStuckResolved(pr github.PullRequest) bool { + return depBotMergeStateKnown(pr) && !depBotStuck(pr) +} + +// depBotCommitIsBots reports whether a commit author is the PR's bot: any +// dependency-bot login (a Renovate deployment may commit as renovate[bot] +// while its PRs are authored by another App), or the PR author itself. +func depBotCommitIsBots(pr github.PullRequest, author string) bool { + a := strings.TrimSpace(author) + return github.IsDependencyBotAuthor(a) || (a != "" && strings.EqualFold(a, strings.TrimSpace(pr.Author))) +} + +// depBotFactsFromCommits derives the branch facts for pr's head. ok is false +// when the list does not end at pr.HeadSHA (the snapshot and the branch +// disagree; read again next pass). +func depBotFactsFromCommits(pr github.PullRequest, commits []github.PRCommit) (depBotBranchFacts, bool) { + if len(commits) == 0 || !strings.EqualFold(commits[len(commits)-1].SHA, pr.HeadSHA) { + return depBotBranchFacts{}, false + } + f := depBotBranchFacts{HeadSHA: pr.HeadSHA} + for _, c := range commits { + if depBotCommitIsBots(pr, c.Author) { + continue + } + if c.ParentCount <= 1 { + f.ForeignWork = true + } + } + f.ForeignHead = !depBotCommitIsBots(pr, commits[len(commits)-1].Author) + return f, true +} + +// depBotRenovateBranch reports whether pr is a Renovate PR (any account). +func depBotRenovateBranch(pr github.PullRequest) bool { + return pr.Author == renovateBotAuthor || strings.HasPrefix(strings.TrimSpace(pr.HeadRef), "renovate/") +} + +// depBotRebaseCheck carries what the stranded check needs for one pass. +type depBotRebaseCheck struct { + store *depBotConflictStore + reader depBotPRReader + window time.Duration + now time.Time + logger *slog.Logger +} + +// requestPossible reports, without writing or recording a refusal, whether +// the sweep could ask pr's bot to rebase: the reader can request and the +// bot_rebase_request policy admits the PR. +func (c depBotRebaseCheck) requestPossible(repo string, pr github.PullRequest) bool { + if _, ok := c.reader.(depBotRebaseRequester); !ok { + return false + } + if _, ok := c.reader.(depBotCommitLister); !ok { + return false + } + if p, ok := c.reader.(depBotRebasePolicy); ok { + return p.BotRebaseRequestAllowed(repo, pr.Number) + } + if client, ok := c.reader.(*github.Client); ok { + return client.WritebackGate().Decide(repo, client.WritebackItemForPR(pr), writeback.KindBotRebaseRequest).Allowed + } + return false +} + +// requestAllowed is the gate check right before the write: it records a +// refusal like every other write-back. +func (c depBotRebaseCheck) requestAllowed(ctx context.Context, repo string, pr github.PullRequest, preview string) bool { + if p, ok := c.reader.(depBotRebasePolicy); ok { + return p.BotRebaseRequestAllowed(repo, pr.Number) + } + return depBotWritebackAllowed(ctx, c.reader, repo, pr.Number, writeback.KindBotRebaseRequest, preview, c.logger) +} + +// facts returns the branch facts for pr's head, reading the commit list once +// per head. +func (c depBotRebaseCheck) facts(ctx context.Context, repo, key string, pr github.PullRequest) (depBotBranchFacts, bool) { + if f, ok := c.store.branchFactsFor(key, pr.HeadSHA); ok { + return f, true + } + lister, ok := c.reader.(depBotCommitLister) + if !ok { + return depBotBranchFacts{}, false + } + commits, err := lister.ListPRCommits(ctx, repo, pr.Number) + if err != nil { + c.logger.Warn("dependency-bot sweep: PR commit list failed; will retry next pass", "repo", repo, "pr", pr.Number, "error", err) + return depBotBranchFacts{}, false + } + f, ok := depBotFactsFromCommits(pr, commits) + if !ok { + return depBotBranchFacts{}, false + } + c.store.rememberBranchFacts(key, f) + return f, true +} + +// rebasesNever reports whether a Renovate PR's description carries the +// `rebaseWhen: never` line, reusing the conflict sweep's per-head no-marker +// memo. ok is false when the description could not be read. +func (c depBotRebaseCheck) rebasesNever(ctx context.Context, repo, key string, pr github.PullRequest) (bool, bool) { + if !depBotRenovateBranch(pr) || c.store.lacksMarker(key, pr.HeadSHA) { + return false, true + } + body, err := c.reader.GetPRBody(ctx, repo, pr.Number) + if err != nil { + c.logger.Warn("dependency-bot sweep: PR body fetch failed; will retry next pass", "repo", repo, "pr", pr.Number, "error", err) + return false, false + } + if renovateRebasesNever(body) { + return true, true + } + c.store.rememberNoMarker(key, pr.HeadSHA) + return false, true +} + +// step is the stranded check for one hand-off candidate whose head has no +// terminal check hold. +func (c depBotRebaseCheck) step(ctx context.Context, repo, key string, pr github.PullRequest) depBotStrandedStep { + if !depBotStuck(pr) { + if depBotMergeStateKnown(pr) { + c.store.clearStuck(key, pr.HeadSHA) + } + return depBotStrandedNone + } + st := c.store.noteStuck(key, pr.HeadSHA, c.now) + if !st.RequestedAt.IsZero() { + // Asked once on this head; never again. A new head resets it. + if c.now.Sub(st.RequestedAt) < c.window { + return depBotStrandedHold + } + return depBotStrandedHandoff + } + conflict := conflictMergeState(pr) + possible := c.requestPossible(repo, pr) + if !possible && conflict { + // Report-only: a conflicting PR keeps the existing conflict path. + return depBotStrandedNone + } + if c.now.Sub(st.StuckSince) < c.window { + if possible && conflict { + return depBotStrandedHold + } + return depBotStrandedNone + } + facts, ok := c.facts(ctx, repo, key, pr) + if !ok { + if possible { + return depBotStrandedHold + } + return depBotStrandedNone + } + stranded := facts.ForeignHead + if !stranded { + never, ok := c.rebasesNever(ctx, repo, key, pr) + if !ok { + return depBotStrandedHold + } + stranded = never + } + if !stranded { + // The bot's own head: it rebases on its own schedule. + return depBotStrandedNone + } + if !possible { + c.logger.Info("dependency-bot PR stranded behind its base; bot_rebase_request not allowed, handing to a person", + "repo", repo, "pr", pr.Number, "head", pr.HeadSHA, "reason", depBotStrandedReasonText) + return depBotStrandedHandoff + } + if facts.ForeignWork { + c.logger.Info("dependency-bot PR stranded with someone else's commits; not asking the bot to regenerate it", + "repo", repo, "pr", pr.Number, "head", pr.HeadSHA) + return depBotStrandedHandoff + } + return c.request(ctx, repo, key, pr, conflict) +} + +// request asks the bot to rebase pr's head once. +func (c depBotRebaseCheck) request(ctx context.Context, repo, key string, pr github.PullRequest, conflict bool) depBotStrandedStep { + requester := c.reader.(depBotRebaseRequester) + refused := func() depBotStrandedStep { + if conflict { + return depBotStrandedNone + } + return depBotStrandedHandoff + } + if strings.EqualFold(pr.Author, "dependabot[bot]") { + if !c.requestAllowed(ctx, repo, pr, github.DependabotRecreateCommand) { + return refused() + } + if err := requester.PostDependabotRecreate(ctx, repo, pr.Number, pr.HeadSHA); err != nil { + c.logger.Warn("dependency-bot rebase request failed; will retry next pass", "repo", repo, "pr", pr.Number, "error", err) + return depBotStrandedHold + } + c.store.markRebaseRequested(key, pr.HeadSHA, depBotViaDependabot, c.now) + c.logger.Info("asked Dependabot to recreate a stranded PR", "repo", repo, "pr", pr.Number, "head", pr.HeadSHA) + return depBotStrandedHold + } + if !c.requestAllowed(ctx, repo, pr, "tick the rebase/retry checkbox") { + return refused() + } + state, err := requester.RequestRenovateRebase(ctx, repo, pr.Number, pr.HeadSHA) + switch { + case errors.Is(err, github.ErrDependencyBotHeadMoved): + return depBotStrandedHold + case err != nil: + c.logger.Warn("dependency-bot rebase request failed; will retry next pass", "repo", repo, "pr", pr.Number, "error", err) + return depBotStrandedHold + } + switch state { + case github.RenovateRebaseCheckboxUnticked: + c.store.markRebaseRequested(key, pr.HeadSHA, depBotViaRenovateCheckbox, c.now) + c.logger.Info("ticked Renovate's rebase/retry box on a stranded PR", "repo", repo, "pr", pr.Number, "head", pr.HeadSHA) + return depBotStrandedHold + case github.RenovateRebaseCheckboxTicked: + // Someone already asked; give the bot one window from now. + c.store.markRebaseRequested(key, pr.HeadSHA, depBotViaAlreadyTicked, c.now) + return depBotStrandedHold + } + // No checkbox: the bot offers no way to ask. + return depBotStrandedHandoff +} + +// dependencyBotStrandedComment is the hand-off comment for +// depBotHandoffStranded. +func dependencyBotStrandedComment(pr github.PullRequest, st depBotRebaseState, facts depBotBranchFacts, factsKnown bool, window time.Duration) string { + name := dependencyBotDisplayName(pr.Author) + state := "has been behind " + depBotBaseTarget(pr.BaseRef) + if conflictMergeState(pr) { + state = "has conflicted with " + depBotBaseTarget(pr.BaseRef) + } + var b strings.Builder + fmt.Fprintf(&b, "The %s: this %s PR %s for over %s", depBotStrandedReasonText, name, state, depBotHours(window)) + if factsKnown && facts.ForeignHead { + b.WriteString(", and its last commit is not the bot's, so the bot stopped updating the branch") + } + b.WriteString(". ") + fix := "rebase the branch by hand, or close the PR so the bot can open a fresh one." + if strings.EqualFold(pr.Author, "dependabot[bot]") { + fix = "comment `" + github.DependabotRecreateCommand + "` on this PR (it discards any commits on the branch that are not Dependabot's), or rebase the branch by hand." + } else if depBotRenovateBranch(pr) || st.Via == depBotViaRenovateCheckbox || st.Via == depBotViaAlreadyTicked { + fix = "tick 'If you want to rebase/retry this PR, check this box' in the description if it has one (Renovate regenerates the branch and discards commits that are not its own), or rebase the branch by hand." + } + switch { + case st.Via == depBotViaRenovateCheckbox: + fmt.Fprintf(&b, "Hive ticked the rebase/retry box %s ago and the branch has not moved since. ", depBotHours(window)) + fix = "check the bot's logs or dependency dashboard for why it did not regenerate the branch, rebase it by hand, or close the PR so the bot can open a fresh one." + case st.Via == depBotViaAlreadyTicked: + fmt.Fprintf(&b, "The rebase/retry box has been ticked for over %s and the branch has not moved. ", depBotHours(window)) + fix = "check the bot's logs or dependency dashboard for why it did not regenerate the branch, rebase it by hand, or close the PR so the bot can open a fresh one." + case st.Via == depBotViaDependabot: + fmt.Fprintf(&b, "Hive commented `%s` %s ago and the branch has not moved since. ", github.DependabotRecreateCommand, depBotHours(window)) + fix = "check Dependabot's reply on this PR, rebase the branch by hand, or close the PR so Dependabot can open a fresh one." + case factsKnown && facts.ForeignWork: + b.WriteString("Hive did not ask the bot to regenerate it, because that would drop commits someone else pushed to the branch. ") + fix = "rebase the branch by hand keeping those commits, or, if they may go, " + fix + } + b.WriteString("To fix it, " + fix) + return b.String() +} + +// ---- store ---------------------------------------------------------------- + +func (s *depBotConflictStore) noteStuck(key, headSHA string, now time.Time) depBotRebaseState { + s.mu.Lock() + defer s.mu.Unlock() + if s.rebase == nil { + s.rebase = map[string]*depBotRebaseState{} + } + st := s.rebase[key] + switch { + case st == nil || !strings.EqualFold(st.HeadSHA, headSHA): + st = &depBotRebaseState{HeadSHA: headSHA, StuckSince: now} + s.rebase[key] = st + s.saveRebaseLocked() + case st.StuckSince.IsZero(): + st.StuckSince = now + s.saveRebaseLocked() + } + return *st +} + +// clearStuck records that the PR is neither behind nor conflicting: a new +// head forgets the record, the same head only stops its stuck clock (a +// request already made on it still stands). +func (s *depBotConflictStore) clearStuck(key, headSHA string) { + s.mu.Lock() + defer s.mu.Unlock() + st := s.rebase[key] + switch { + case st == nil: + return + case !strings.EqualFold(st.HeadSHA, headSHA): + delete(s.rebase, key) + case !st.StuckSince.IsZero(): + st.StuckSince = time.Time{} + default: + return + } + s.saveRebaseLocked() +} + +func (s *depBotConflictStore) markRebaseRequested(key, headSHA, via string, at time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + if s.rebase == nil { + s.rebase = map[string]*depBotRebaseState{} + } + st := s.rebase[key] + if st == nil || !strings.EqualFold(st.HeadSHA, headSHA) { + st = &depBotRebaseState{HeadSHA: headSHA, StuckSince: at} + s.rebase[key] = st + } + st.RequestedAt, st.Via = at, via + s.saveRebaseLocked() +} + +func (s *depBotConflictStore) rebaseState(key string) (depBotRebaseState, bool) { + s.mu.Lock() + defer s.mu.Unlock() + st := s.rebase[key] + if st == nil { + return depBotRebaseState{}, false + } + return *st, true +} + +// pruneRebase forgets PRs that left the open snapshot. +func (s *depBotConflictStore) pruneRebase(open map[string]github.PullRequest) { + s.mu.Lock() + defer s.mu.Unlock() + changed := false + for k := range s.rebase { + if _, ok := open[k]; !ok { + delete(s.rebase, k) + changed = true + } + } + for k := range s.branchFacts { + if _, ok := open[k]; !ok { + delete(s.branchFacts, k) + } + } + if changed { + s.saveRebaseLocked() + } +} + +func (s *depBotConflictStore) branchFactsFor(key, headSHA string) (depBotBranchFacts, bool) { + s.mu.Lock() + defer s.mu.Unlock() + f, ok := s.branchFacts[key] + return f, ok && strings.EqualFold(f.HeadSHA, headSHA) +} + +func (s *depBotConflictStore) rememberBranchFacts(key string, f depBotBranchFacts) { + s.mu.Lock() + defer s.mu.Unlock() + if s.branchFacts == nil { + s.branchFacts = map[string]depBotBranchFacts{} + } + s.branchFacts[key] = f +} + +func depBotRebasePath(path string) string { + if path == "" { + return "" + } + return strings.TrimSuffix(path, ".json") + "-rebase.json" +} + +func loadDepBotRebaseStates(path string) map[string]*depBotRebaseState { + out := map[string]*depBotRebaseState{} + if path == "" { + return out + } + data, err := os.ReadFile(path) + if err != nil { + return out + } + var m map[string]*depBotRebaseState + if json.Unmarshal(data, &m) == nil && m != nil { + out = m + } + return out +} + +func (s *depBotConflictStore) saveRebaseLocked() { + path := depBotRebasePath(s.path) + if path == "" { + return + } + data, err := json.MarshalIndent(s.rebase, "", " ") + 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_rebase_request_test.go b/src/cmd/hive/dependency_bot_rebase_request_test.go new file mode 100644 index 0000000000..043368704c --- /dev/null +++ b/src/cmd/hive/dependency_bot_rebase_request_test.go @@ -0,0 +1,390 @@ +package main + +import ( + "context" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/escalation" + "github.com/hivecommons/hive/pkg/github" +) + +// depBotRebaseWindow is the default governor.dependency_bot_rebase_after_s; +// the harness passes 0 so the sweep resolves the default itself. +const depBotRebaseWindow = time.Duration(config.DefaultDependencyBotRebaseAfterS) * time.Second + +// depBotRebaseFakeReader is a reader that can also list commits and make +// the two rebase requests. Its Renovate request runs the real checkbox edit +// against body, so tests see the exact description that would be written. +type depBotRebaseFakeReader struct { + depBotFakeReader + commits []github.PRCommit + commitReads int + denied bool + edits []string + recreates []string +} + +func (r *depBotRebaseFakeReader) ListPRCommits(context.Context, string, int) ([]github.PRCommit, error) { + r.commitReads++ + return r.commits, nil +} + +func (r *depBotRebaseFakeReader) RequestRenovateRebase(_ context.Context, _ string, _ int, _ string) (github.RenovateRebaseCheckbox, error) { + ticked, state := github.TickRenovateRebaseCheckbox(r.body) + if state == github.RenovateRebaseCheckboxUnticked { + r.edits = append(r.edits, ticked) + r.body = ticked + } + return state, nil +} + +func (r *depBotRebaseFakeReader) PostDependabotRecreate(_ context.Context, _ string, _ int, headSHA string) error { + r.recreates = append(r.recreates, headSHA) + return nil +} + +func (r *depBotRebaseFakeReader) BotRebaseRequestAllowed(string, int) bool { return !r.denied } + +var ( + _ depBotCommitLister = (*depBotRebaseFakeReader)(nil) + _ depBotRebaseRequester = (*depBotRebaseFakeReader)(nil) + _ depBotRebasePolicy = (*depBotRebaseFakeReader)(nil) + _ depBotCommitLister = (*github.Client)(nil) + _ depBotRebaseRequester = (*github.Client)(nil) +) + +type depBotRebaseHarness struct { + t *testing.T + path string + store *depBotConflictStore + writer *depBotFakeWriter + reader *depBotRebaseFakeReader +} + +func newDepBotRebaseHarness(t *testing.T, body string, commits ...github.PRCommit) *depBotRebaseHarness { + t.Helper() + path := filepath.Join(t.TempDir(), "dependency-bot-conflicts.json") + return &depBotRebaseHarness{ + t: t, + path: path, + store: loadDepBotConflictStore(path), + writer: &depBotFakeWriter{}, + reader: &depBotRebaseFakeReader{depBotFakeReader: depBotFakeReader{body: body}, commits: commits}, + } +} + +func (h *depBotRebaseHarness) passAt(at time.Time, prs ...github.PullRequest) { + h.t.Helper() + a := &github.ActionableResult{} + a.PRs.Items = prs + sweepDependencyBotConflicts(context.Background(), h.store, "acme", 0, h.writer, h.reader, a, func() time.Time { return at }, discardLogger()) +} + +func (h *depBotRebaseHarness) assertWrites(stage string, edits, recreates, comments, labels int) { + h.t.Helper() + if len(h.reader.edits) != edits || len(h.reader.recreates) != recreates || len(h.writer.comments) != comments || len(h.writer.adds) != labels { + h.t.Fatalf("%s: edits=%d recreates=%v comments=%v labels=%v; want %d edits, %d recreates, %d comments, %d labels", + stage, len(h.reader.edits), h.reader.recreates, h.writer.comments, h.writer.adds, edits, recreates, comments, labels) + } +} + +func depBotRRCommit(author, sha string) github.PRCommit { + return github.PRCommit{SHA: sha, Author: author, ParentCount: 1} +} + +// depBotRRBaseMerge is the "Merge branch 'main' into …" commit GitHub's Update +// branch button writes as the person who clicked it. +func depBotRRBaseMerge(author, sha string) github.PRCommit { + return github.PRCommit{SHA: sha, Author: author, ParentCount: 2} +} + +func depBotRRBehindPR(author, sha string) github.PullRequest { + return depBotPR(author, sha, func(p *github.PullRequest) { + p.MergeableState = "behind" + if author != "dependabot[bot]" { + p.HeadRef = "renovate/widget-2.x" + } + }) +} + +// depBotRRStranded is a Renovate PR someone updated with the Update branch +// button: the head is a person's merge of the base. +func depBotRRStranded(t *testing.T, body string) *depBotRebaseHarness { + return newDepBotRebaseHarness(t, body, depBotRRCommit("renovate[bot]", "c1"), depBotRRBaseMerge("alice", "sha-2")) +} + +func depBotRRWantCheckboxEdit(t *testing.T, before, after string) { + t.Helper() + want := strings.Replace(before, "- [ ] ", "- [x] ", 1) + if want == before { + t.Fatal("fixture has no unticked rebase-check box") + } + if after != want { + t.Fatalf("edited description differs beyond the checkbox:\n got %q\nwant %q", after, want) + } +} + +func TestDependencyBotStrandedRenovateTicksOnlyTheCheckbox(t *testing.T) { + for name, body := range map[string]string{ + "lf": renovateDefaultBody, + "crlf": strings.ReplaceAll(renovateDefaultBody, "\n", "\r\n"), + } { + t.Run(name, func(t *testing.T) { + h := depBotRRStranded(t, body) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow-time.Minute), pr) + h.assertWrites("before the window", 0, 0, 0, 0) + + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("at the window", 1, 0, 0, 0) + depBotRRWantCheckboxEdit(t, body, h.reader.edits[0]) + + h.passAt(depBotT0.Add(depBotRebaseWindow+time.Minute), pr) + h.assertWrites("next pass", 1, 0, 0, 0) + if h.reader.commitReads != 1 { + t.Fatalf("commit reads = %d, want 1 per head", h.reader.commitReads) + } + }) + } +} + +func TestDependencyBotStrandedAlreadyTickedIsNotEdited(t *testing.T) { + ticked := strings.Replace(renovateDefaultBody, "- [ ] ", "- [x] ", 1) + h := depBotRRStranded(t, ticked) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("ticked box at the window", 0, 0, 0, 0) + + // The box stayed ticked a whole window and the head did not move. + h.passAt(depBotT0.Add(2*depBotRebaseWindow), pr) + h.assertWrites("a window after", 0, 0, 1, 1) + if !strings.Contains(h.writer.comments[0], "has been ticked") { + t.Fatalf("comment = %q, want it to say the box was already ticked", h.writer.comments[0]) + } +} + +func TestDependencyBotStrandedNoCheckboxHandsOff(t *testing.T) { + h := newDepBotRebaseHarness(t, "Bumps widget from 1 to 2.\n", depBotRRCommit("mergeraptor[bot]", "c1"), depBotRRBaseMerge("alice", "sha-2")) + pr := depBotRRBehindPR("mergeraptor[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("no checkbox", 0, 0, 1, 1) +} + +func TestDependencyBotBotHeadOnlyBehindIsLeftAlone(t *testing.T) { + // A Renovate deployment running as another App commits as renovate[bot]: + // still the bot's own head. + h := newDepBotRebaseHarness(t, renovateDefaultBody, depBotRRCommit("renovate[bot]", "sha-1")) + pr := depBotRRBehindPR("mergeraptor[bot]", "sha-1") + for _, at := range []time.Duration{0, depBotRebaseWindow - time.Minute, depBotRebaseWindow, 3 * depBotRebaseWindow, 30 * time.Hour} { + h.passAt(depBotT0.Add(at), pr) + } + h.assertWrites("bot head behind", 0, 0, 0, 0) + if h.reader.commitReads != 1 || h.reader.bodyFetches != 1 { + t.Fatalf("commit reads = %d, body fetches = %d; want one of each per head", h.reader.commitReads, h.reader.bodyFetches) + } +} + +func TestDependencyBotForeignHeadBeforeWindowIsLeftAlone(t *testing.T) { + h := depBotRRStranded(t, renovateDefaultBody) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow/2), pr) + h.passAt(depBotT0.Add(depBotRebaseWindow-time.Second), pr) + h.assertWrites("before the window", 0, 0, 0, 0) + if h.reader.commitReads != 0 { + t.Fatalf("commit reads = %d, want none before the window", h.reader.commitReads) + } +} + +func TestDependencyBotStrandedDependabotRecreates(t *testing.T) { + h := newDepBotRebaseHarness(t, "Bumps widget from 1 to 2.\n", depBotRRCommit("dependabot[bot]", "c1"), depBotRRBaseMerge("alice", "sha-2")) + pr := depBotRRBehindPR("dependabot[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.passAt(depBotT0.Add(depBotRebaseWindow+time.Hour), pr) + h.assertWrites("dependabot", 0, 1, 0, 0) + if h.reader.recreates[0] != "sha-2" { + t.Fatalf("recreate requested for %q, want the current head", h.reader.recreates[0]) + } + if h.reader.bodyFetches != 0 { + t.Fatalf("body fetches = %d, want none for Dependabot", h.reader.bodyFetches) + } +} + +func TestDependencyBotStrandedHeadUnchangedHandsOffOnce(t *testing.T) { + h := depBotRRStranded(t, renovateDefaultBody) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.passAt(depBotT0.Add(2*depBotRebaseWindow-time.Minute), pr) + h.assertWrites("before the second window", 1, 0, 0, 0) + + h.passAt(depBotT0.Add(2*depBotRebaseWindow), pr) + h.assertWrites("a window after the request", 1, 0, 1, 1) + c := h.writer.comments[0] + if !strings.Contains(c, depBotStrandedReasonText) || !strings.Contains(c, "Hive ticked the rebase/retry box") || !strings.Contains(c, "behind `main`") { + t.Fatalf("comment = %q, want the reason, the request and the base named", c) + } + if want := depBotKey + ": " + escalation.NeedsHumanLabel; h.writer.adds[0] != want { + t.Fatalf("adds = %v, want [%q]", h.writer.adds, want) + } + + labeled := pr + labeled.Labels = []string{escalation.NeedsHumanLabel} + h.passAt(depBotT0.Add(3*depBotRebaseWindow), labeled) + h.passAt(depBotT0.Add(4*depBotRebaseWindow), pr) // label seen absent on a stale snapshot + h.assertWrites("later passes", 1, 0, 1, 1) + if rec, ok := h.store.get(depBotKey); !ok || rec.Reason != depBotHandoffStranded || rec.HeadSHA != "sha-2" { + t.Fatalf("record = %+v (ok=%v), want the stranded hand-off on sha-2", rec, ok) + } +} + +func TestDependencyBotStrandedNewHeadResets(t *testing.T) { + h := depBotRRStranded(t, renovateDefaultBody) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("request", 1, 0, 0, 0) + + // Renovate regenerated the branch; base moved again since. + h.reader.commits = []github.PRCommit{depBotRRCommit("renovate[bot]", "sha-3")} + next := depBotRRBehindPR("renovate[bot]", "sha-3") + at := depBotT0.Add(depBotRebaseWindow + 10*time.Minute) + h.passAt(at, next) + st, ok := h.store.rebaseState(depBotKey) + if !ok || st.HeadSHA != "sha-3" || !st.RequestedAt.IsZero() || !st.StuckSince.Equal(at) { + t.Fatalf("state = %+v (ok=%v), want a fresh record for sha-3", st, ok) + } + h.passAt(depBotT0.Add(5*depBotRebaseWindow), next) + h.assertWrites("new bot head", 1, 0, 0, 0) +} + +func TestDependencyBotStrandedKindOffReportsOnly(t *testing.T) { + h := depBotRRStranded(t, renovateDefaultBody) + h.reader.denied = true + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow-time.Minute), pr) + h.assertWrites("before the window", 0, 0, 0, 0) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("at the window", 0, 0, 1, 1) + if c := h.writer.comments[0]; !strings.Contains(c, depBotStrandedReasonText) || !strings.Contains(c, "its last commit is not the bot's") { + t.Fatalf("comment = %q, want the stranded reason", c) + } +} + +func TestDependencyBotStrandedKindOffConflictKeepsExistingPath(t *testing.T) { + h := newDepBotRebaseHarness(t, "", depBotRRCommit("dependabot[bot]", "c1"), depBotRRBaseMerge("alice", "sha-2")) + h.reader.denied = true + pr := depBotPR("dependabot[bot]", "sha-2", conflicting) + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("before the conflict grace", 0, 0, 0, 0) + h.passAt(depBotT0.Add(depBotConflictGrace), pr) + h.assertWrites("conflict grace", 0, 0, 1, 1) + if !strings.Contains(h.writer.comments[0], "Dependabot PR has conflicted with `main` for over 24 hours") { + t.Fatalf("comment = %q, want the existing conflict hand-off", h.writer.comments[0]) + } +} + +func TestDependencyBotStrandedConflictAsksBeforeHandingOff(t *testing.T) { + // A conflicting rebaseWhen-never Renovate PR on the bot's own head: with + // the kind allowed it is asked about first, not handed off at once. + h := newDepBotRebaseHarness(t, renovateNeverBody, depBotRRCommit("renovate[bot]", "sha-1")) + pr := renovateConflictPR("sha-1") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(time.Hour), pr) + h.assertWrites("before the window", 0, 0, 0, 0) + + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("at the window", 1, 0, 0, 0) + depBotRRWantCheckboxEdit(t, renovateNeverBody, h.reader.edits[0]) + + h.passAt(depBotT0.Add(2*depBotRebaseWindow), pr) + h.assertWrites("a window after the request", 1, 0, 1, 1) + if !strings.Contains(h.writer.comments[0], "has conflicted with `main`") { + t.Fatalf("comment = %q, want the conflict named", h.writer.comments[0]) + } + h.passAt(depBotT0.Add(depBotConflictGrace+time.Hour), pr) + h.assertWrites("past the conflict grace", 1, 0, 1, 1) +} + +func TestDependencyBotStrandedForeignWorkIsNotRegenerated(t *testing.T) { + h := newDepBotRebaseHarness(t, renovateDefaultBody, depBotRRCommit("renovate[bot]", "c1"), depBotRRCommit("alice", "sha-2")) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("foreign work", 0, 0, 1, 1) + if !strings.Contains(h.writer.comments[0], "drop commits someone else pushed") { + t.Fatalf("comment = %q, want it to say why the bot was not asked", h.writer.comments[0]) + } +} + +func TestDependencyBotStrandedStateSurvivesRestart(t *testing.T) { + h := depBotRRStranded(t, renovateDefaultBody) + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + + h.store = loadDepBotConflictStore(h.path) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("first-seen kept across a restart", 1, 0, 0, 0) + + h.store = loadDepBotConflictStore(h.path) + st, ok := h.store.rebaseState(depBotKey) + if !ok || st.HeadSHA != "sha-2" || !st.RequestedAt.Equal(depBotT0.Add(depBotRebaseWindow)) || st.Via != depBotViaRenovateCheckbox { + t.Fatalf("reloaded state = %+v (ok=%v), want the request on sha-2", st, ok) + } + h.passAt(depBotT0.Add(2*depBotRebaseWindow-time.Minute), pr) + h.assertWrites("after the second restart", 1, 0, 0, 0) + h.passAt(depBotT0.Add(2*depBotRebaseWindow), pr) + h.assertWrites("hand-off on the persisted request clock", 1, 0, 1, 1) +} + +func TestDependencyBotStrandedHandoffUndoneWhenCaughtUp(t *testing.T) { + h := depBotRRStranded(t, renovateDefaultBody) + h.reader.denied = true + pr := depBotRRBehindPR("renovate[bot]", "sha-2") + h.passAt(depBotT0, pr) + h.passAt(depBotT0.Add(depBotRebaseWindow), pr) + h.assertWrites("hand-off", 0, 0, 1, 1) + + clean := depBotPR("renovate[bot]", "sha-4", func(p *github.PullRequest) { + p.HeadRef = "renovate/widget-2.x" + p.Labels = []string{escalation.NeedsHumanLabel} + }) + h.passAt(depBotT0.Add(depBotRebaseWindow+time.Hour), clean) + if want := depBotKey + ": " + escalation.NeedsHumanLabel; len(h.writer.removes) != 1 || h.writer.removes[0] != want { + t.Fatalf("removes = %v, want the stranded label taken back once", h.writer.removes) + } +} + +func TestDepBotFactsFromCommits(t *testing.T) { + pr := depBotRRBehindPR("mergeraptor[bot]", "h") + cases := []struct { + name string + commits []github.PRCommit + head, work, o bool + }{ + {"bot only (renovate commits under another App)", []github.PRCommit{depBotRRCommit("renovate[bot]", "a"), depBotRRCommit("mergeraptor[bot]", "h")}, false, false, true}, + {"person merged the base", []github.PRCommit{depBotRRCommit("renovate[bot]", "a"), depBotRRBaseMerge("alice", "h")}, true, false, true}, + {"person committed a change", []github.PRCommit{depBotRRCommit("renovate[bot]", "a"), depBotRRCommit("alice", "h")}, true, true, true}, + {"workflow fix then bot", []github.PRCommit{depBotRRCommit("github-actions[bot]", "a"), depBotRRCommit("renovate[bot]", "h")}, false, true, true}, + {"list behind the snapshot", []github.PRCommit{depBotRRCommit("renovate[bot]", "a")}, false, false, false}, + {"empty", nil, false, false, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f, ok := depBotFactsFromCommits(pr, tc.commits) + if ok != tc.o || f.ForeignHead != tc.head || f.ForeignWork != tc.work { + t.Fatalf("facts = %+v ok=%v; want head=%v work=%v ok=%v", f, ok, tc.head, tc.work, tc.o) + } + }) + } +} diff --git a/src/docs/acmm-policy-matrix.md b/src/docs/acmm-policy-matrix.md index 554f87508a..88a2c1a395 100644 --- a/src/docs/acmm-policy-matrix.md +++ b/src/docs/acmm-policy-matrix.md @@ -269,7 +269,7 @@ gated. Defaults (override under `writeback.kinds.`): | `hold_gate_notice` (mergeability / drift) | — | hive PRs only | hive PRs only | hive PRs only | | `stage_label`, `needs_decision_comment` on foreign PRs | internal tracking | internal tracking | opt-in label | opt-in label | | `supersession_notice`, `duplicate_fix_notice`, `reporter_trust_hold`, `covered_by_pr_label`, `issue_close`, `parent_issue_edit`, `gate_comment` | — | — | opt-in label | opt-in label | -| `supersession_close`, `contributor_adopt`, `ci_rerun`, `base_refresh` | — | — | — | opt-in label | +| `supersession_close`, `contributor_adopt`, `ci_rerun`, `base_refresh`, `bot_rebase_request` | — | — | — | opt-in label | | `verdict_label` | L3: opt-in label | opt-in label | opt-in label | opt-in label | | `claim_comment` | — | opt-in label | opt-in label | opt-in label | | `welcome_comment` | — | — | opt-in label | all items | diff --git a/src/docs/github-write-surface.md b/src/docs/github-write-surface.md index c01ff8b152..e8cb2aef8f 100644 --- a/src/docs/github-write-surface.md +++ b/src/docs/github-write-surface.md @@ -163,6 +163,7 @@ writes no entry. | Shared-CI rerun (`rerun-failed-jobs`, or `rerun` for a `cancelled` run; `hive-shared-ci-rerun-` + `hive-shared-ci-lifted-` comment) | `shared_ci_rerun.go` | yes (`shared-ci-rerun`) | yes | | Transient-CI rerun (`rerun-failed-jobs` on a hive PR whose failing runs carry `hive-ci-transient`, once per head, no comment) | `transient_ci_rerun.go` | yes (`transient-ci-rerun`) | yes | | Stale-red base refresh (`update-branch` on a red PR behind its base whose failing checks are green on the base tip, once per head and base tip, no comment) | `stale_red_base_refresh.go` | yes (`stale-red-base-refresh`) | yes | +| Dependency-bot rebase request (ticks only Renovate's rebase/retry checkbox line in the PR description, or comments `@dependabot recreate`, once per head, on a bot PR the bot stopped rebasing; write-back kind `bot_rebase_request`) | `dependency_bot_rebase.go` | yes (`dependency_bot_rebase_requested`) | yes | | Open-PR dispatch guard (`has-open-pr` label on a refused issue) and duplicate-fix sweep (one `hive:duplicate-fix` comment; `hive/superseded` close of the later hive PR, or `needs-human` + `Parked` fact on escalation) | `open_pr_links.go`, `pr_duplicate_fix_sweep.go` | yes (`duplicate-fix-*`) | yes | | Duplicate-PR sweep suggestions | `duplicate_sweep.go` | yes (`duplicate-sweep-suggested`) | yes (target = surviving PR) | | Shared-CI tracking issues (one `[shared-ci] failing across ` issue per check failing across a repo; body edits of its own issue only) | `shared_ci_issues.go` | yes (`shared-ci-issue-filed`, `shared-ci-issue-updated`) | yes / issue number | diff --git a/src/docs/labels-and-control-signals/reference.md b/src/docs/labels-and-control-signals/reference.md index a9eda97109..7d3eaacc62 100644 --- a/src/docs/labels-and-control-signals/reference.md +++ b/src/docs/labels-and-control-signals/reference.md @@ -843,7 +843,7 @@ Same exempt behavior as `do-not-merge`; wins over required-label admission. Defa **Release or override.** Remove label or config entry -**Configuration and implementation.** `governor.labels.exempt` (`src/pkg/config/governor_config.go:317`, where `LabelsConfig` appears; `src/pkg/config/defaults.go:365-371`) +**Configuration and implementation.** `governor.labels.exempt` (`src/pkg/config/governor_config.go:324`, where `LabelsConfig` appears; `src/pkg/config/defaults.go:369-375`) #### `hive:unauthorized` @@ -905,7 +905,7 @@ Queue label for human/owner merge action; the sweep also requires its normal aut **Release or override.** Remove label; head changes can de-queue -**Configuration and implementation.** `governor.labels.automerge`, default `lgtm` (`src/pkg/config/governor_config.go:317-325`, where `LabelsConfig` appears; `src/pkg/config/dashboard_config.go:233`, where `DefaultAutoMergeLabel` appears; `src/pkg/github/automerge/automerge_sweep_loop.go:13-82`) +**Configuration and implementation.** `governor.labels.automerge`, default `lgtm` (`src/pkg/config/governor_config.go:324-332`, where `LabelsConfig` appears; `src/pkg/config/dashboard_config.go:233`, where `DefaultAutoMergeLabel` appears; `src/pkg/github/automerge/automerge_sweep_loop.go:13-82`) #### `reviewer-passed` diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 42bb6e7c7f..b5261073fb 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -636,7 +636,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 | +| `main.sweepDependencyBotConflicts` | `attention` | asks a person to rebase or retry a dependency-bot PR; its once-per-head `@dependabot recreate` request (`github.(*Client).PostDependabotRecreate`) is recorded as `protocol_command` | | `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/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index ab6232e5ee..2b9c0ae13a 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -496,6 +496,34 @@ 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). +- 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. + The same sweep now watches for that. A dependency-bot PR (Renovate, + Dependabot, mergeraptor, or any `renovate/*` head) that has been behind or + conflicting for `governor.dependency_bot_rebase_after_s` (default `14400`, + 4 hours; yaml-only) is **stranded** when its head commit is not the bot's, + or its Renovate config rebases never. A bot-authored head that is merely + behind is left to the bot. For a stranded PR the hive asks the bot to + rebase through the bot's own mechanism, once per head: it ticks Renovate's + rebase/retry checkbox (only that line of the description changes; a box + already ticked is left alone) or comments `@dependabot recreate` + (Dependabot refuses `@dependabot rebase` on a branch someone else edited). + If the head has not moved one window later, the PR is handed to a person + (one comment plus `needs-human`, reason "dependency bot will not rebase + this branch"); the request is never repeated on that head, and a new head + starts over. The hive never asks when the branch carries someone else's + non-merge commit, because the bot's regeneration would drop it; that PR is + handed to a person at the window instead. The request is gated as write-back + kind `bot_rebase_request` (default L6 with the opt-in label, like + `base_refresh`; `writeback.kinds.bot_rebase_request.unlabeled_min_level: 6` + lets it reach every bot PR at L6). When the kind refuses, the hive only + reports: a log line, and the person hand-off for a stranded PR that is + behind once the window passes; a conflicting one keeps the 24-hour conflict + hand-off above. While a request is due or pending on a conflicting PR, the + conflict hand-off waits, so the PR never gets the request and a person's + comment at once. First-seen and requested heads persist across restarts in + `dependency-bot-conflicts-rebase.json` beside the conflict ledger. - fork heads, sentinel-alert PRs, and human-authored lanes are never touched; a first-time contributor's held run is still a person's decision — with two exceptions that reach fork heads: the gated-run approval sweep diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index c63c260cec..43c1843ec3 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -558,6 +558,7 @@ that level, the power the write-back exists to govern? | Shared-CI rerun (`shared_ci_rerun.go`) | CI failure watcher | `rerun-failed-jobs`, `hive-shared-ci-rerun-` comment | PRs with failed shared workflows | `ci_rerun` → L6 + label | | Transient-CI rerun (`transient_ci_rerun.go`) | eval cycle, before the stuck-PR reaper | `rerun-failed-jobs`, once per head, no comment | hive-authored red PRs whose every failing run carries `hive-ci-transient` | `ci_rerun` (own items: allowed unless the repo is paused, off or issues-only) | | 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 | +| 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) or comments `@dependabot recreate`; once per head, no other comment | 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)) | | 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_cadence_writeback_ops_test.go b/src/pkg/adminmcp/tools_cadence_writeback_ops_test.go index 52628120a5..ca0a1a326e 100644 --- a/src/pkg/adminmcp/tools_cadence_writeback_ops_test.go +++ b/src/pkg/adminmcp/tools_cadence_writeback_ops_test.go @@ -368,6 +368,12 @@ func TestWritebackKindPolicyOpKeepsUntouchedKinds(t *testing.T) { args: map[string]any{"base_refresh": map[string]any{"unlabeled_min_level": 6}}, want: `{"writebackKinds":{"base_refresh":{"unlabeled_min_level":6}}}`, }, + "the dependency-bot rebase request kind": { + replace: true, + kinds: nil, + args: map[string]any{"bot_rebase_request": map[string]any{"unlabeled_min_level": 6}}, + want: `{"writebackKinds":{"bot_rebase_request":{"unlabeled_min_level":6}}}`, + }, } { t.Run(name, func(t *testing.T) { p := newCadenceWBProvider() diff --git a/src/pkg/config/dashboard_config.go b/src/pkg/config/dashboard_config.go index 6afd268070..e0c2e55eea 100644 --- a/src/pkg/config/dashboard_config.go +++ b/src/pkg/config/dashboard_config.go @@ -592,6 +592,14 @@ func (c *Config) CIFailureKickCooldown() time.Duration { return DefaultCIFailureKickCooldownS * time.Second } +// DependencyBotRebaseAfter resolves governor.dependency_bot_rebase_after_s. +func (c *Config) DependencyBotRebaseAfter() time.Duration { + if c != nil && c.Governor.DependencyBotRebaseAfterS > 0 { + return time.Duration(c.Governor.DependencyBotRebaseAfterS) * time.Second + } + return DefaultDependencyBotRebaseAfterS * time.Second +} + // SetMergeTrainStallWarnS records an explicit value, including zero to // disable warnings. func (c *Config) SetMergeTrainStallWarnS(seconds int) { diff --git a/src/pkg/config/defaults.go b/src/pkg/config/defaults.go index 1e58815697..222a39dce8 100644 --- a/src/pkg/config/defaults.go +++ b/src/pkg/config/defaults.go @@ -36,6 +36,10 @@ const ( DefaultOptionalSweepEveryNCycles = 1 ) +// DefaultDependencyBotRebaseAfterS is governor.dependency_bot_rebase_after_s +// when unset: 4 hours. +const DefaultDependencyBotRebaseAfterS = 4 * 60 * 60 + const ( MaxAgentReplicas = 5 diff --git a/src/pkg/config/governor_config.go b/src/pkg/config/governor_config.go index cfc67c4c8a..3f963e8ec9 100644 --- a/src/pkg/config/governor_config.go +++ b/src/pkg/config/governor_config.go @@ -29,6 +29,13 @@ type GovernorConfig struct { // for a sweep. Cooldown bounds kicks per PR head (default 600 seconds). CIFailureWebhookKick *bool `yaml:"ci_failure_webhook_kick,omitempty"` CIFailureKickCooldownS int `yaml:"ci_failure_kick_cooldown_s,omitempty"` + // DependencyBotRebaseAfterS is how long a dependency-bot PR may sit + // behind or conflicting with its base before the dependency-bot sweep + // treats a bot that stopped rebasing it as stranded: it asks the bot to + // rebase (write-back kind bot_rebase_request) and, one more window later + // with the head unchanged, hands the PR to a person. Seconds; 0 or unset + // means DefaultDependencyBotRebaseAfterS (4 hours). + DependencyBotRebaseAfterS int `yaml:"dependency_bot_rebase_after_s,omitempty" json:"dependency_bot_rebase_after_s,omitempty"` // MergeTrainStallWarnS is the stalled-train warning threshold in seconds // (default DefaultMergeTrainStallWarnS; explicit zero disables warnings; // hivecommons/hive#15395). diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index fa158adb68..86d7532e6c 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -375,6 +375,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if c.Governor.CIFailureKickCooldownS < 0 { return fmt.Errorf("governor.ci_failure_kick_cooldown_s must be at least 0") } + if c.Governor.DependencyBotRebaseAfterS < 0 { + return fmt.Errorf("governor.dependency_bot_rebase_after_s must be at least 0") + } if c.Governor.MergeTrainStallWarnS < 0 { return fmt.Errorf("governor.merge_train_stall_warn_s must be at least 0") } diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 45633c172f..c5fe0c8734 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -230,6 +230,7 @@ governor.ci.auto_approve_workflow_actors[] # trusted workflow-approval actors (# governor.ci.auto_approve_workflows # gated workflow auto-approval flag (#16603); yaml-only governor.ci_failure_kick_cooldown_s # webhook CI-failure kick cooldown (#15291); yaml-only governor.ci_failure_webhook_kick # webhook CI-failure kick flag (#15291); yaml-only +governor.dependency_bot_rebase_after_s # stranded dependency-bot PR window (bot_rebase_request); yaml-only governor.claims.contributor_flap_threshold # contributor flap cool-off (#13579); yaml-only governor.claims.contributor_flap_window_s # contributor flap cool-off (#13579); yaml-only governor.claims.contributor_flap_cooloff_s # contributor flap cool-off (#13579); yaml-only diff --git a/src/pkg/github/dependency_bot_rebase.go b/src/pkg/github/dependency_bot_rebase.go new file mode 100644 index 0000000000..6a91fc932b --- /dev/null +++ b/src/pkg/github/dependency_bot_rebase.go @@ -0,0 +1,151 @@ +package github + +import ( + "context" + "errors" + "strconv" + "strings" + + gh "github.com/google/go-github/v72/github" + + "github.com/hivecommons/hive/pkg/effects" +) + +// Rebase requests to a dependency bot that has stopped maintaining its own +// branch (write-back kind bot_rebase_request). The hive never pushes to a +// dependency bot's branch (DependencyBotBranch); these ask the bot to +// regenerate it through the bot's own mechanism instead. Callers consult +// the write-back gate before calling either method. + +// RenovateRebaseCheckMarker is the HTML comment Renovate puts on the +// rebase/retry checkbox line of every PR description it writes +// (" - [ ] If you want to rebase/retry this PR, check +// this box"). Renovate regenerates the branch on its next run once the box +// is ticked, whoever ticked it. +const RenovateRebaseCheckMarker = "" + +// DependabotRecreateCommand asks Dependabot to regenerate its PR from the +// current base. `@dependabot rebase` is refused once anyone else has pushed +// to the branch ("Looks like this PR has been edited by someone other than +// Dependabot"); recreate is the command Dependabot names for that case. +const DependabotRecreateCommand = "@dependabot recreate" + +// AuditActionDependencyBotRebaseRequested is recorded when the hive ticks a +// Renovate rebase/retry box or posts the Dependabot recreate command. +const AuditActionDependencyBotRebaseRequested = "dependency_bot_rebase_requested" + +// ErrDependencyBotHeadMoved means the PR's head is no longer the one the +// caller asked about: the bot (or someone) already moved it, so nothing was +// written. +var ErrDependencyBotHeadMoved = errors.New("dependency-bot PR head moved since it was read") + +// RenovateRebaseCheckbox is the state of Renovate's rebase/retry checkbox in +// a PR description. +type RenovateRebaseCheckbox int + +const ( + // RenovateRebaseCheckboxAbsent: the description has no rebase-check line. + RenovateRebaseCheckboxAbsent RenovateRebaseCheckbox = iota + // RenovateRebaseCheckboxUnticked: `- [ ] `. + RenovateRebaseCheckboxUnticked + // RenovateRebaseCheckboxTicked: `- [x] `; a + // rebase is already requested and Renovate has not acted on it yet. + RenovateRebaseCheckboxTicked +) + +// TickRenovateRebaseCheckbox returns body with Renovate's rebase/retry box +// ticked and the state the box was in. Only the three bytes "[ ]" on the +// first rebase-check line change; every other byte, line endings and +// indentation included, is returned as it was. A body whose box is absent or +// already ticked is returned unchanged. +func TickRenovateRebaseCheckbox(body string) (string, RenovateRebaseCheckbox) { + const unticked, ticked, tickedUpper = "- [ ] ", "- [x] ", "- [X] " + for start := 0; start < len(body); { + end := strings.IndexByte(body[start:], '\n') + line := body[start:] + if end >= 0 { + line = body[start : start+end] + } + rest := strings.TrimLeft(line, " \t") + indent := len(line) - len(rest) + switch { + case strings.HasPrefix(rest, unticked+RenovateRebaseCheckMarker): + at := start + indent + len("- ") + return body[:at] + "[x]" + body[at+len("[ ]"):], RenovateRebaseCheckboxUnticked + case strings.HasPrefix(rest, ticked+RenovateRebaseCheckMarker), strings.HasPrefix(rest, tickedUpper+RenovateRebaseCheckMarker): + return body, RenovateRebaseCheckboxTicked + } + if end < 0 { + break + } + start += end + 1 + } + return body, RenovateRebaseCheckboxAbsent +} + +// RequestRenovateRebase ticks the rebase/retry box in a Renovate PR's +// description, provided the PR's head is still headSHA. It reads the PR +// fresh (the description changes on every Renovate run) and writes the +// description back with only the checkbox line changed. It returns the state +// the box was in: only RenovateRebaseCheckboxUnticked means a write was made. +// The caller must have consulted the write-back gate (bot_rebase_request). +func (c *Client) RequestRenovateRebase(ctx context.Context, repo string, number int, headSHA string) (RenovateRebaseCheckbox, error) { + if c == nil || c.client == nil { + return RenovateRebaseCheckboxAbsent, ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + ctx = WithRESTCaller(ctx, "hive:dependency_bot_rebase") + pr, _, err := c.client.PullRequests.Get(ctx, owner, repoName, number) + if err != nil { + return RenovateRebaseCheckboxAbsent, err + } + if headSHA != "" && !strings.EqualFold(pr.GetHead().GetSHA(), headSHA) { + return RenovateRebaseCheckboxAbsent, ErrDependencyBotHeadMoved + } + body, state := TickRenovateRebaseCheckbox(pr.GetBody()) + if state != RenovateRebaseCheckboxUnticked { + return state, nil + } + _, resp, err := c.client.PullRequests.Edit(ctx, owner, repoName, number, &gh.PullRequest{Body: gh.Ptr(body)}) // writeback:gated — the dependency-bot sweep consults WritebackAllowed (bot_rebase_request) before calling + c.noteWritebackOutcome(owner+"/"+repoName, resp, err) + if err != nil { + return state, err + } + c.recordWriteAudit(AuditActionDependencyBotRebaseRequested, hiveWriteMeta(), WriteTarget{Repo: owner + "/" + repoName, Number: number}, + "head", headSHA, "via", "renovate-checkbox") + return state, nil +} + +// PostDependabotRecreate comments DependabotRecreateCommand on a Dependabot +// PR, at most once per head: the mutation journal keys the comment on the +// head SHA, so the same command on a later head is a new operation rather +// than a replay of the first. The caller must have consulted the write-back +// gate (bot_rebase_request). +func (c *Client) PostDependabotRecreate(ctx context.Context, repo string, number int, headSHA string) error { + if c == nil || c.client == nil { + return ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + full := owner + "/" + repoName + _, err := effects.Execute(ctx, c.mutationBoundary(), effects.Claim{ + Repo: full, + Kind: effects.KindIssueComment, + Target: strconv.Itoa(number), + Actor: "dependency-bot-sweep", + Inputs: map[string]string{"head_sha": strings.ToLower(headSHA), "body": effects.StableDigest(DependabotRecreateCommand)}, + }, func(ctx context.Context) (effects.Result, error) { + comment, resp, apiErr := c.client.Issues.CreateComment(WithRESTCaller(ctx, "hive:dependency_bot_rebase"), owner, repoName, number, &gh.IssueComment{Body: gh.Ptr(DependabotRecreateCommand)}) // writeback:gated — the dependency-bot sweep consults WritebackAllowed (bot_rebase_request) before calling + c.noteWritebackOutcome(full, resp, apiErr) + if apiErr != nil { + return effects.Result{}, effects.NotApplied(apiErr) + } + return effects.Result{Provenance: comment.GetHTMLURL()}, nil + }) + c.recordNotificationWrite(ctx, notificationWrite{kind: notificationWriteComment, repo: full, item: number, body: DependabotRecreateCommand, class: NotificationClassProtocolCommand, err: err}) + if err != nil { + return err + } + c.recordWriteAudit(AuditActionDependencyBotRebaseRequested, hiveWriteMeta(), WriteTarget{Repo: full, Number: number}, + "head", headSHA, "via", "dependabot-recreate") + return nil +} diff --git a/src/pkg/github/dependency_bot_rebase_test.go b/src/pkg/github/dependency_bot_rebase_test.go new file mode 100644 index 0000000000..f5ec4c026b --- /dev/null +++ b/src/pkg/github/dependency_bot_rebase_test.go @@ -0,0 +1,154 @@ +package github + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const renovateBodyLF = "This PR contains the following updates:\n\n" + + "♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.\n\n" + + "---\n\n" + + " - [ ] If you want to rebase/retry this PR, check this box\n\n" + + "---\n\n" + + "- [ ] an unrelated task list item\n" + +// onlyCheckboxChanged asserts after is before with exactly one byte changed: +// the space inside the rebase-check box, now an x. +func onlyCheckboxChanged(t *testing.T, before, after string) { + t.Helper() + if len(before) != len(after) { + t.Fatalf("length changed: %d → %d", len(before), len(after)) + } + diffs := 0 + for i := range before { + if before[i] != after[i] { + diffs++ + if before[i] != ' ' || after[i] != 'x' || i < 3 || !strings.HasPrefix(after[i-3:], "- [x] "+RenovateRebaseCheckMarker) { + t.Fatalf("byte %d changed %q → %q outside the rebase-check box", i, before[i], after[i]) + } + } + } + if diffs != 1 { + t.Fatalf("%d bytes changed, want exactly 1", diffs) + } +} + +func TestTickRenovateRebaseCheckbox(t *testing.T) { + crlf := strings.ReplaceAll(renovateBodyLF, "\n", "\r\n") + for name, body := range map[string]string{"lf": renovateBodyLF, "crlf": crlf, "box on the last line, no newline": "intro\r\n\r\n - [ ] " + RenovateRebaseCheckMarker + "If you want to rebase/retry this PR, check this box"} { + t.Run(name, func(t *testing.T) { + got, state := TickRenovateRebaseCheckbox(body) + if state != RenovateRebaseCheckboxUnticked { + t.Fatalf("state = %v, want unticked", state) + } + onlyCheckboxChanged(t, body, got) + if strings.Count(got, "\r\n") != strings.Count(body, "\r\n") { + t.Fatal("line endings changed") + } + if again, st := TickRenovateRebaseCheckbox(got); st != RenovateRebaseCheckboxTicked || again != got { + t.Fatalf("second tick: state %v, changed=%v; want ticked and unchanged", st, again != got) + } + }) + } + for name, body := range map[string]string{ + "ticked": strings.Replace(renovateBodyLF, "- [ ] "+RenovateRebaseCheckMarker, "- [x] "+RenovateRebaseCheckMarker, 1), + "ticked upper": strings.Replace(renovateBodyLF, "- [ ] "+RenovateRebaseCheckMarker, "- [X] "+RenovateRebaseCheckMarker, 1), + } { + if got, st := TickRenovateRebaseCheckbox(body); st != RenovateRebaseCheckboxTicked || got != body { + t.Fatalf("%s: state %v changed=%v, want ticked and unchanged", name, st, got != body) + } + } + plain := "Bumps foo from 1 to 2.\n\n- [ ] an unrelated task list item\n" + if got, st := TickRenovateRebaseCheckbox(plain); st != RenovateRebaseCheckboxAbsent || got != plain { + t.Fatalf("no checkbox: state %v changed=%v, want absent and unchanged", st, got != plain) + } +} + +func TestRequestRenovateRebasePatchesOnlyTheCheckbox(t *testing.T) { + body := strings.ReplaceAll(renovateBodyLF, "\n", "\r\n") + head := "abc123" + var patched []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/repos/acme/widget/pulls/42" { + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + return + } + switch r.Method { + case http.MethodGet: + out, _ := json.Marshal(map[string]any{"number": 42, "body": body, "head": map[string]any{"sha": head}}) + _, _ = w.Write(out) + case http.MethodPatch: + raw, _ := io.ReadAll(r.Body) + var req map[string]any + if err := json.Unmarshal(raw, &req); err != nil { + t.Errorf("PATCH body: %v", err) + } + if len(req) != 1 { + t.Errorf("PATCH sends %v, want only the body", req) + } + s, _ := req["body"].(string) + patched = append(patched, s) + _, _ = w.Write([]byte(`{"number":42}`)) + default: + t.Errorf("unexpected method %s", r.Method) + } + })) + defer srv.Close() + c := NewClientForTest(srv.URL, "acme", []string{"widget"}, slog.Default()) + + state, err := c.RequestRenovateRebase(context.Background(), "acme/widget", 42, head) + if err != nil || state != RenovateRebaseCheckboxUnticked { + t.Fatalf("RequestRenovateRebase = %v, %v; want unticked, nil", state, err) + } + if len(patched) != 1 { + t.Fatalf("PATCHes = %d, want 1", len(patched)) + } + onlyCheckboxChanged(t, body, patched[0]) + + // The head moved: nothing is written. + if _, err := c.RequestRenovateRebase(context.Background(), "acme/widget", 42, "def456"); !errors.Is(err, ErrDependencyBotHeadMoved) { + t.Fatalf("moved head: err = %v, want ErrDependencyBotHeadMoved", err) + } + // Already ticked: nothing is written. + body = patched[0] + if state, err := c.RequestRenovateRebase(context.Background(), "acme/widget", 42, head); err != nil || state != RenovateRebaseCheckboxTicked { + t.Fatalf("ticked box: %v, %v; want ticked, nil", state, err) + } + if len(patched) != 1 { + t.Fatalf("PATCHes = %d, want still 1", len(patched)) + } +} + +func TestPostDependabotRecreatePostsTheCommand(t *testing.T) { + var posted []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/repos/acme/widget/issues/7/comments" { + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + return + } + var req struct { + Body string `json:"body"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + posted = append(posted, req.Body) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":1}`)) + })) + defer srv.Close() + c := NewClientForTest(srv.URL, "acme", []string{"widget"}, slog.Default()) + if err := c.PostDependabotRecreate(context.Background(), "acme/widget", 7, "abc123"); err != nil { + t.Fatal(err) + } + if len(posted) != 1 || posted[0] != DependabotRecreateCommand { + t.Fatalf("posted %q, want exactly %q", posted, DependabotRecreateCommand) + } +} diff --git a/src/pkg/github/write_surface_internal.go b/src/pkg/github/write_surface_internal.go index ed558ee9f2..3504ea69b4 100644 --- a/src/pkg/github/write_surface_internal.go +++ b/src/pkg/github/write_surface_internal.go @@ -106,5 +106,6 @@ func InternalWriteAuditActions() []string { AuditActionHiveIDLabelRetired, AuditActionReporterTrustWaitNoticed, AuditActionReporterTrustWaitCleared, + AuditActionDependencyBotRebaseRequested, } } diff --git a/src/pkg/writeback/dedupe.go b/src/pkg/writeback/dedupe.go index 755d656e6a..6101782682 100644 --- a/src/pkg/writeback/dedupe.go +++ b/src/pkg/writeback/dedupe.go @@ -71,8 +71,8 @@ func IsContentReason(reason string) bool { // ContentDedupeKinds are the kinds whose preview is a comment body the // content layer may dedupe. Kinds that re-run their gate check every tick // with a constant preview and keep their own idempotence (hold_gate_notice, -// the closes, parent_issue_edit, ci_rerun, base_refresh), the label kinds and issue_file -// (no existing item) are deliberately absent. +// the closes, parent_issue_edit, ci_rerun, base_refresh, bot_rebase_request), +// the label kinds and issue_file (no existing item) are deliberately absent. var ContentDedupeKinds = map[Kind]bool{ KindSentinel: true, KindNeedsDecisionComment: true, diff --git a/src/pkg/writeback/dedupe_test.go b/src/pkg/writeback/dedupe_test.go index 2463cc4ae1..d2c73bdbfb 100644 --- a/src/pkg/writeback/dedupe_test.go +++ b/src/pkg/writeback/dedupe_test.go @@ -195,7 +195,7 @@ func TestKindSets(t *testing.T) { if !k.RateCapExempt() { t.Errorf("%s: label kinds must be exempt from the hourly cap", k) } - case k.IsIssueFileKind(), k == KindSupersessionClose, k == KindIssueClose, k == KindHoldGateNotice, k == KindParentIssueEdit, k == KindCIRerun, k == KindBaseRefresh: + case k.IsIssueFileKind(), k == KindSupersessionClose, k == KindIssueClose, k == KindHoldGateNotice, k == KindParentIssueEdit, k == KindCIRerun, k == KindBaseRefresh, k == KindBotRebaseRequest: if k.ContentDeduped() { t.Errorf("%s re-checks the gate with a constant preview; it must not be content-deduped", k) } diff --git a/src/pkg/writeback/kinds.go b/src/pkg/writeback/kinds.go index 437116aec7..c3e37fd41b 100644 --- a/src/pkg/writeback/kinds.go +++ b/src/pkg/writeback/kinds.go @@ -91,6 +91,13 @@ const ( // base has fixed what the PR's CI tripped on, and only a new head runs // that check again. It pushes a merge commit and posts nothing. KindBaseRefresh Kind = "base_refresh" + // KindBotRebaseRequest asks a dependency bot to rebase its own PR + // through the bot's own mechanism, once per PR head: it ticks Renovate's + // rebase/retry box in the PR description (editing only that line) or + // comments `@dependabot recreate`. The bot then regenerates the branch; + // the hive never pushes to it. Used only on a PR whose bot has stopped + // rebasing (see cmd/hive/dependency_bot_rebase_request.go). + KindBotRebaseRequest Kind = "bot_rebase_request" ) // KindPolicy is the per-kind rule. A write of this kind on an item the hive @@ -148,6 +155,7 @@ func DefaultKinds() map[Kind]KindPolicy { KindIssueFile: {MinLevel: 3}, KindCIRerun: {MinLevel: 6, RequireLabel: true}, KindBaseRefresh: {MinLevel: 6, RequireLabel: true}, + KindBotRebaseRequest: {MinLevel: 6, RequireLabel: true}, } } diff --git a/src/pkg/writeback/writeback_test.go b/src/pkg/writeback/writeback_test.go index 66c71aa97b..c79dda6a72 100644 --- a/src/pkg/writeback/writeback_test.go +++ b/src/pkg/writeback/writeback_test.go @@ -394,3 +394,46 @@ func TestRepoPausedRefusesEveryKind(t *testing.T) { t.Fatal("nil gate must never report paused") } } + +// bot_rebase_request ticks a dependency bot's rebase box or asks Dependabot +// to recreate its PR, which makes the bot rewrite the branch: it defaults to +// the base_refresh policy (L6 with the opt-in label), the settings table and +// the admin MCP list it from the registry, and an operator can widen it. +func TestBotRebaseRequestKindDefaults(t *testing.T) { + if !IsKind("bot_rebase_request") { + t.Fatal("bot_rebase_request is not a known kind") + } + c := Config{} + if p := c.Policy(KindBotRebaseRequest); p != c.Policy(KindBaseRefresh) || p.MinLevel != 6 || !p.RequireLabel || p.UnlabeledMinLevel != 0 || p.OwnOnly { + t.Fatalf("default policy = %+v, want base_refresh's L6 with the opt-in label", p) + } + listed := false + for _, row := range c.EffectiveKinds() { + listed = listed || row.Kind == KindBotRebaseRequest + } + if !listed { + t.Fatal("bot_rebase_request missing from EffectiveKinds (the Settings kind table)") + } + + level := 6 + g := New(Config{}, Deps{LevelFor: func(string) int { return level }}, "") + bot := Item{Number: 9, IsPR: true, Author: "renovate[bot]"} + if d := g.Decide("acme/widget", bot, KindBotRebaseRequest); d.Allowed || d.Reason != ReasonNeedsLabel { + t.Fatalf("L6 without the label: %+v, want refused for the label", d) + } + labeled := bot + labeled.Labels = []string{DefaultOptInLabel} + if d := g.Decide("acme/widget", labeled, KindBotRebaseRequest); !d.Allowed { + t.Fatalf("L6 with the label: %+v, want allowed", d) + } + level = 5 + if d := g.Decide("acme/widget", labeled, KindBotRebaseRequest); d.Allowed { + t.Fatalf("L5 with the label: %+v, want refused", d) + } + six := 6 + g.SetConfig(Config{Kinds: map[string]KindPolicyOverride{"bot_rebase_request": {UnlabeledMinLevel: &six}}}) + level = 6 + if d := g.Decide("acme/widget", bot, KindBotRebaseRequest); !d.Allowed { + t.Fatalf("L6 without the label after unlabeled_min_level: 6: %+v, want allowed", d) + } +} From 959529102e9967ad1306cf609c04819892c89896 Mon Sep 17 00:00:00 2001 From: Danathar Date: Tue, 10 Nov 2026 15:46:02 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(dependency-bo?= =?UTF-8?q?ts):=20one=20poster=20for=20bot=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestCommentMarkerRatchet counted PostDependabotRecreate as a new unmarked comment emitter. A bot parses the comment as a command, so it cannot carry a marker. Instead, the automerge sweep's existing `@dependabot rebase` nudge and the new `@dependabot recreate` request now share one poster, github.PostBotCommand. It posts the command verbatim through the mutation journal, keyed on PR and head SHA. The nudge's comment body, journal claim (actor, target, head_sha, body digest), REST caller and on-success bookkeeping are unchanged. The unmarked-emitter count is back at the baseline of 46. The raw create call moves from automerge_held_runs.go to dependency_bot_rebase.go, and the write ratchet baseline moves with it (3 to 2, plus 1). The total is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- .../github/automerge/automerge_held_runs.go | 13 +---- src/pkg/github/dependency_bot_rebase.go | 48 ++++++++++++------- .../testdata/direct-writes-baseline.txt | 3 +- 3 files changed, 34 insertions(+), 30 deletions(-) diff --git a/src/pkg/github/automerge/automerge_held_runs.go b/src/pkg/github/automerge/automerge_held_runs.go index 7bfb2fb308..4af6a9f956 100644 --- a/src/pkg/github/automerge/automerge_held_runs.go +++ b/src/pkg/github/automerge/automerge_held_runs.go @@ -624,19 +624,8 @@ func (c *Engine) nudgeDependabotRebase(ctx context.Context, displayRepo, owner, } c.warn("automerge required check never ran on autofix-pushed Dependabot head; asking Dependabot to rebase", "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) - } + err := hgithub.PostBotCommand(ctx, c.mutation, c.gh, owner, repo, number, headSHA, dependabotRebaseComment, "automerge", "hive:automerge_sweep", func() { 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) diff --git a/src/pkg/github/dependency_bot_rebase.go b/src/pkg/github/dependency_bot_rebase.go index 6a91fc932b..0d27d9a58a 100644 --- a/src/pkg/github/dependency_bot_rebase.go +++ b/src/pkg/github/dependency_bot_rebase.go @@ -116,31 +116,45 @@ func (c *Client) RequestRenovateRebase(ctx context.Context, repo string, number return state, nil } -// PostDependabotRecreate comments DependabotRecreateCommand on a Dependabot -// PR, at most once per head: the mutation journal keys the comment on the -// head SHA, so the same command on a later head is a new operation rather -// than a replay of the first. The caller must have consulted the write-back -// gate (bot_rebase_request). -func (c *Client) PostDependabotRecreate(ctx context.Context, repo string, number int, headSHA string) error { - if c == nil || c.client == nil { - return ErrNoGitHubClient - } - owner, repoName := c.splitRepo(repo) - full := owner + "/" + repoName - _, err := effects.Execute(ctx, c.mutationBoundary(), effects.Claim{ - Repo: full, +// PostBotCommand posts command, verbatim and alone, as a comment on PR +// number, at most once per head: the mutation journal keys the operation on +// (PR, head SHA, command), so the same command on a later head is a new +// operation rather than a replay of the first. It is the one poster for the +// commands the hive sends a dependency bot (the automerge sweep's +// `@dependabot rebase` nudge and the dependency-bot sweep's +// `@dependabot recreate`); a bot parses the comment as a command, so it +// carries no marker. onPosted, when set, runs once the comment is created. +// Callers own any write-back gate check. +func PostBotCommand(ctx context.Context, boundary effects.Boundary, client *gh.Client, owner, repo string, number int, headSHA, command, actor, restCaller string, onPosted func()) error { + _, err := effects.Execute(ctx, boundary, effects.Claim{ + Repo: owner + "/" + repo, Kind: effects.KindIssueComment, Target: strconv.Itoa(number), - Actor: "dependency-bot-sweep", - Inputs: map[string]string{"head_sha": strings.ToLower(headSHA), "body": effects.StableDigest(DependabotRecreateCommand)}, + Actor: actor, + Inputs: map[string]string{"head_sha": headSHA, "body": effects.StableDigest(command)}, }, func(ctx context.Context) (effects.Result, error) { - comment, resp, apiErr := c.client.Issues.CreateComment(WithRESTCaller(ctx, "hive:dependency_bot_rebase"), owner, repoName, number, &gh.IssueComment{Body: gh.Ptr(DependabotRecreateCommand)}) // writeback:gated — the dependency-bot sweep consults WritebackAllowed (bot_rebase_request) before calling - c.noteWritebackOutcome(full, resp, apiErr) + comment, _, apiErr := client.Issues.CreateComment(WithRESTCaller(ctx, restCaller), owner, repo, number, &gh.IssueComment{Body: gh.Ptr(command)}) if apiErr != nil { return effects.Result{}, effects.NotApplied(apiErr) } + if onPosted != nil { + onPosted() + } return effects.Result{Provenance: comment.GetHTMLURL()}, nil }) + return err +} + +// PostDependabotRecreate comments DependabotRecreateCommand on a Dependabot +// PR, at most once per head (PostBotCommand). The caller must have consulted +// the write-back gate (bot_rebase_request). +func (c *Client) PostDependabotRecreate(ctx context.Context, repo string, number int, headSHA string) error { + if c == nil || c.client == nil { + return ErrNoGitHubClient + } + owner, repoName := c.splitRepo(repo) + full := owner + "/" + repoName + err := PostBotCommand(ctx, c.mutationBoundary(), c.client, owner, repoName, number, strings.ToLower(headSHA), DependabotRecreateCommand, "dependency-bot-sweep", "hive:dependency_bot_rebase", nil) c.recordNotificationWrite(ctx, notificationWrite{kind: notificationWriteComment, repo: full, item: number, body: DependabotRecreateCommand, class: NotificationClassProtocolCommand, err: err}) if err != nil { return err diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 201a0d5521..2266348cd3 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 @@ -24,6 +24,7 @@ raw pkg/github/automerge/reporter_trust_release.go 2 raw pkg/github/automerge/self_authorization_release.go 2 raw pkg/github/client.go 12 raw pkg/github/close_on_merge.go 3 +raw pkg/github/dependency_bot_rebase.go 1 raw pkg/github/duplicate_sweep.go 2 raw pkg/github/fleet_report.go 2 raw pkg/github/gfi_forge.go 1 From b8d766366e8d946e452661e29cc488c64d549665 Mon Sep 17 00:00:00 2001 From: Danathar Date: Tue, 10 Nov 2026 15:52:59 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=8C=B1=20test(config):=20cover=20gove?= =?UTF-8?q?rnor.dependency=5Fbot=5Frebase=5Fafter=5Fs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The coverage gate put pkg/config at 89.9% against its 90% floor: the resolver and its validation had no test. Cover the default (nil and unset), a set value, and the negative-value rejection. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1 Signed-off-by: Danathar --- src/pkg/config/dependency_bot_rebase_test.go | 43 ++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/pkg/config/dependency_bot_rebase_test.go diff --git a/src/pkg/config/dependency_bot_rebase_test.go b/src/pkg/config/dependency_bot_rebase_test.go new file mode 100644 index 0000000000..6ced97b3ac --- /dev/null +++ b/src/pkg/config/dependency_bot_rebase_test.go @@ -0,0 +1,43 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestDependencyBotRebaseAfter(t *testing.T) { + var nilCfg *Config + if got := nilCfg.DependencyBotRebaseAfter(); got != 4*time.Hour { + t.Errorf("nil config: got %v, want 4h", got) + } + if got := (&Config{}).DependencyBotRebaseAfter(); got != 4*time.Hour { + t.Errorf("unset: got %v, want 4h", got) + } + c := &Config{Governor: GovernorConfig{DependencyBotRebaseAfterS: 2 * 60 * 60}} + if got := c.DependencyBotRebaseAfter(); got != 2*time.Hour { + t.Errorf("set to 7200s: got %v, want 2h", got) + } +} + +func TestValidate_DependencyBotRebaseAfterS(t *testing.T) { + build := func(s int) *Config { + return &Config{ + Project: ProjectConfig{Org: "my-org"}, + GitHub: GitHubConfig{Token: "t"}, + Governor: GovernorConfig{DependencyBotRebaseAfterS: s}, + AgentRuntimeConfig: AgentRuntimeConfig{ + Agents: map[string]AgentConfig{"scanner": {Backend: "claude"}}, + }, + } + } + for _, s := range []int{0, 3600} { + if err := build(s).validate(); err != nil { + t.Errorf("validate() rejected dependency_bot_rebase_after_s=%d: %v", s, err) + } + } + err := build(-1).validate() + if err == nil || !strings.Contains(err.Error(), "dependency_bot_rebase_after_s") { + t.Fatalf("validate() with dependency_bot_rebase_after_s=-1: got %v, want an error naming the key", err) + } +}