diff --git a/changelog.d/fixed-pr-notification-spam.md b/changelog.d/fixed-pr-notification-spam.md new file mode 100644 index 0000000000..528af67054 --- /dev/null +++ b/changelog.d/fixed-pr-notification-spam.md @@ -0,0 +1 @@ +- Hive PR notifications no longer spam authors and watchers: the stage stalled/regressed notes, the trusted-human 071 note and the duplicate-PR redirect share one `` comment per PR that is edited in place instead of appending a comment per event; "**Reviewed** — no findings" reviews are recorded as verdicts without a GitHub review and a head carries at most one hive review; the 071 note @-mentions the author once per cause instead of once per head; a check returning to pending after a push is no longer a regression and a merge-train queued/rebasing wait is never stalled. New knob `github.notifications.mode` (`quiet` default, `normal` restores the old behaviour) ([#15875](https://github.com/hivecommons/hive/issues/15875)). diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index 7583a59f19..5d1f1d5ca1 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -1969,6 +1969,7 @@ func installReviewRelaySettings(client *github.Client, cfg *config.Config, logge func() bool { return cfg.Review.CombinedPerspectives }, func() int { return cfg.Review.MaxReviewsPerHead }, ) + client.SetNotificationsQuiet(func() bool { return cfg.GitHub.Notifications.Quiet() }) // review.require_labels (PR approval allow-list): the relay's half of the // gate, read live so a Features-tab edit applies to the next request. client.SetReviewRequireLabels(func() []string { return cfg.Review.RequireLabels }) @@ -2484,18 +2485,21 @@ func planReviewDispatchWith(ctx context.Context, cfg *config.Config, actionable reviewBotLogins = reviewBots.Logins } plan := review.PlanDispatch(prs, artifact, state, review.DispatchOptions{ - RequireApproval: cfg.Review.RequireApproval, - FanOut: cfg.Review.FanOut, - MaxParallelReviews: cfg.Review.EffectiveMaxParallelReviews(), - MaxPerspectivesPerPR: cfg.Review.MaxPerspectivesPerPR, - Perspectives: reviewPerspectiveSet(cfg, logger), - CombinedPerspectives: cfg.Review.CombinedPerspectives, - ReviewerAgents: cfg.Review.ReviewerAgents, - FixerAgent: cfg.Review.FixerAgent, - PostComments: cfg.Review.PostComments, - WritingGuideSection: cfg.Project.WritingGuideSection(), - FixHumanPRs: cfg.Review.FixHumanPRsEnabled(), - AcknowledgeNoFindings: cfg.Review.AcknowledgeNoFindings, + RequireApproval: cfg.Review.RequireApproval, + FanOut: cfg.Review.FanOut, + MaxParallelReviews: cfg.Review.EffectiveMaxParallelReviews(), + MaxPerspectivesPerPR: cfg.Review.MaxPerspectivesPerPR, + Perspectives: reviewPerspectiveSet(cfg, logger), + CombinedPerspectives: cfg.Review.CombinedPerspectives, + ReviewerAgents: cfg.Review.ReviewerAgents, + FixerAgent: cfg.Review.FixerAgent, + PostComments: cfg.Review.PostComments, + WritingGuideSection: cfg.Project.WritingGuideSection(), + FixHumanPRs: cfg.Review.FixHumanPRsEnabled(), + // Quiet notification mode never acknowledges a clean review on + // GitHub: the one-liner is an email to everyone to say nothing + // happened, and the verdict is already on the evidence bundle. + AcknowledgeNoFindings: cfg.Review.AcknowledgeNoFindings && !cfg.GitHub.Notifications.Quiet(), ReviseRepos: cfg.Review.ReviseRepos, ReviseVerdictsBefore: parseReviseCutoff(cfg.Review.ReviseVerdictsBefore, logger), PendingTTL: cfg.Review.PendingReviewTTL(), diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 2a69441805..8c9a317198 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -135,6 +135,7 @@ func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy ForkGuard: stageForkGuard, DCORequired: stage.DCO.RequiredFor, SquashOnly: cfg.AutoMerge.SquashOnlyFor, + QuietNotifications: cfg.GitHub.Notifications.Quiet(), } } } diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 19ac85b6e5..10738aa28c 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -1116,6 +1116,27 @@ github: - **Merge.** A PR whose rationale (its closing or referencing links, or the request's declared issue list) traces to an untrusted reporter's issue without any `untrusted_require_labels` acceptance label receives `hold` at **every** ACMM level, including L6, together with a marked notice naming the issue reporter (not the PR author). Any one unaccepted untrusted citation holds. A configured acceptance label supplies maintainer sign-off, so accepted issues do not trigger a new reporter-trust PR hold. A human removes the label; Hive never auto-releases a reporter-trust hold — the level-hold release path recognises the notice and leaves the label, and holdguard re-holds on a new head SHA. `github.reporter_trust_hold` follows `reporter_trust.enabled` unless set explicitly; `project.repo_policies[].reporter_trust_hold` overrides per repo; `HIVE_REPORTER_TRUST_HOLD` locks it from the environment, exactly like the #5117 knobs. - **Where you see it.** Both halves are edited in the dashboard: **Settings → Labels → Reporter trust** (the switch, the association checkboxes, extra logins, triage labels) and **Settings → Repos** (the hold, with the same all-repos default / per-repo override / inherit rows as #5117). An active gate is stated in the read-only note under **Projects**, and each repo card counts issues **needs triage** separately from generic filter refusals. The issue itself carries `needs-triage` while waiting when Hive had to add it. Holds carry the reason in the PR notice and in the `agent_pr_created` audit entry (`reporter_trust_held`, `reporter_login`, `reporter_association`). +### Notification mode: how much of the hive's bookkeeping becomes email + +```yaml +github: + notifications: + mode: quiet # default; "normal" posts every note as its own comment/review +``` + +Every issue comment and every review the hive posts emails the PR author +and every watcher of the repository; editing an existing comment notifies +nobody. In `quiet` mode (the default) the hive's own PR notes — stage +stalled/regressed, the trusted-human 071 note, the duplicate-PR redirect — +are sections of one `` comment per PR that is created +once and edited afterwards; a "**Reviewed** — no findings" review is +recorded as a verdict without a GitHub review and a head carries at most +one hive review; the 071 note @-mentions the author once per cause rather +than once per head. Nothing is lost: the Activity Monitor, the evidence +bundle and the stage labels carry the same facts. See +[operator-reference.md → Notification mode](operator-reference.md#notification-mode-githubnotificationsmode) +for the full list. `normal` restores the one-comment-per-event behaviour. + ### Tracking and archive issues Some issues are never meant to be worked or closed: a standing report archive that a workflow appends to every week, a long-lived checklist, a "Keep this issue open" status thread. Mark them with **any one** of the label `hive/tracking`, the body marker ``, or the literal sentence "Keep this issue open" in the body, and the hive treats the issue as a tracking issue. diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 352b79ab51..f915f32641 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -1215,6 +1215,52 @@ above, and `/api/status` → `writeback.dedupe` carries the settings plus the last-hour counters `dedupe_same_item`, `dedupe_burst` and `rate_capped`. `enabled: false` turns the layer off. +### Notification mode (`github.notifications.mode`) + +**Why:** every issue comment and every review the hive posts emails the PR +author and everyone watching the repository. Editing an existing comment or +review notifies nobody. Measured on one busy PR, the hive posted eight +comments and three reviews in two hours — a 071 note per new head (each +@-mentioning the author), a "stage regressed" note for a check that had +merely gone back to pending after a push, a "stalled" note for a PR that +was simply queued in the merge train, a duplicate-PR redirect, and three +"**Reviewed** — no findings" reviews. Multiplied over thirty open PRs that +is dozens of emails an hour saying nothing the Activity Monitor, the +evidence bundle and the stage labels did not already say. + +```yaml +github: + notifications: + mode: quiet # quiet (default) | normal +``` + +`quiet` (the default) changes how the hive delivers its own PR bookkeeping, +not what it records: + +- **One status comment per PR, edited in place.** The stage-stalled and + stage-regressed notes, the trusted-human 071 note and the duplicate-PR + redirect are sections of a single comment marked ``. + The comment is created the first time a note is due and PATCHed for every + later note; only the creation sends email. +- **No "no findings" reviews.** A reviewer whose whole body is the clean + acknowledgement has its verdict recorded through the relay and the + evidence bundle, and no GitHub review is submitted (the reviewer prompts + also stop asking for the line, whatever `review.acknowledge_no_findings` + says). Only perspectives with findings post, and a head carries at most + one hive review: a later perspective's findings for the same head are + folded into the status comment instead of becoming a second review. +- **@-mentions once per cause.** The 071 note mentions the author the first + time a cause class appears (conflict, red CI, changes requested) and is + silent for further heads with the same cause; a new cause mentions again. + +Independently of the mode, a check going back to pending after a push is +no longer reported as a stage regression, and a PR the hive itself is +holding — queued behind the merge-train front, being rebased by the train, +or waiting on a base refresh — is never marked stalled. + +`normal` restores the previous behaviour: every note is its own comment, +every perspective's verdict its own review, every new head its own mention. + ## Suspicious-activity alerts (`sentinel`) The sentinel evaluates open PRs in the watched repos — human, bot, or agent — diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 6a7e3f91d2..047ba28cc5 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:4942-4952`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:4969-4979`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 5245bda3f7..ac022d77a8 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -3576,6 +3576,11 @@ type GitHubConfig struct { // reporterTrustHoldEnvOverride is set by HIVE_REPORTER_TRUST_HOLD and never // serialized, for the same reason as selfAuthorizationHoldEnvOverride. reporterTrustHoldEnvOverride *bool `yaml:"-" json:"-"` + // Notifications governs how loudly the hive's own PR bookkeeping reaches + // people. Every new issue comment and every review submission emails + // the author and every watcher; editing an existing comment does not. + // See GitHubNotificationsConfig. + Notifications GitHubNotificationsConfig `yaml:"notifications,omitempty" json:"notifications,omitempty"` // OAuthBaseURLOverride and OAuthAPIURLOverride redirect the DEVICE-FLOW LOGIN // endpoints away from public github.com. They are a TEST SEAM ONLY — see the // comment on OAuthBaseURL(). They carry the `-` yaml tag so they can never be diff --git a/src/pkg/config/github_notifications.go b/src/pkg/config/github_notifications.go new file mode 100644 index 0000000000..807e1d8b83 --- /dev/null +++ b/src/pkg/config/github_notifications.go @@ -0,0 +1,43 @@ +package config + +import "strings" + +// Values for github.notifications.mode. +const ( + // NotificationsModeQuiet (the default) folds the hive's own PR + // bookkeeping — stage stalled/regressed notes, the trusted-human 071 + // note, the duplicate-PR redirect — into one status comment per PR that + // is edited in place, posts no "no findings" review, and @-mentions a + // person once per cause rather than once per head. + NotificationsModeQuiet = "quiet" + // NotificationsModeNormal posts every note as its own comment and every + // perspective's verdict as its own review, as the hive did before the + // knob existed. + NotificationsModeNormal = "normal" +) + +// GitHubNotificationsConfig is github.notifications: how much of the hive's +// PR bookkeeping becomes an email. Every new issue comment and every review +// submission notifies the author and every watcher of the repository; +// editing an existing comment or review notifies nobody. The Activity +// Monitor, the evidence bundles and the stage labels carry the same facts, +// so the quiet default loses no information. +type GitHubNotificationsConfig struct { + // Mode is "quiet" (default when empty) or "normal". + Mode string `yaml:"mode,omitempty" json:"mode,omitempty"` +} + +// Quiet reports whether the hive should fold its PR notes into one edited +// status comment and suppress no-findings reviews. Empty reads as quiet. +func (c GitHubNotificationsConfig) Quiet() bool { + return !strings.EqualFold(strings.TrimSpace(c.Mode), NotificationsModeNormal) +} + +// Valid reports whether Mode names a known mode (or is unset). +func (c GitHubNotificationsConfig) Valid() bool { + switch strings.ToLower(strings.TrimSpace(c.Mode)) { + case "", NotificationsModeQuiet, NotificationsModeNormal: + return true + } + return false +} diff --git a/src/pkg/config/github_notifications_test.go b/src/pkg/config/github_notifications_test.go new file mode 100644 index 0000000000..9cbf14454a --- /dev/null +++ b/src/pkg/config/github_notifications_test.go @@ -0,0 +1,18 @@ +package config + +import "testing" + +func TestGitHubNotificationsConfig(t *testing.T) { + for mode, quiet := range map[string]bool{"": true, "quiet": true, "Quiet": true, "normal": false, "NORMAL": false} { + c := GitHubNotificationsConfig{Mode: mode} + if !c.Valid() { + t.Errorf("mode %q must be valid", mode) + } + if c.Quiet() != quiet { + t.Errorf("mode %q: Quiet() = %v, want %v", mode, c.Quiet(), quiet) + } + } + if (GitHubNotificationsConfig{Mode: "loud"}).Valid() { + t.Error("unknown mode must be invalid") + } +} diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index ba4d22bcaa..4a77a7ad42 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -435,6 +435,7 @@ "BaseURL": "", "AppAuthoredPRs": null, "AppSignedCommits": null, + "notifications": {}, "OAuthBaseURLOverride": "", "OAuthAPIURLOverride": "" }, diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index 8bedaf9d02..a95ad83dfc 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -122,6 +122,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if c.GitHub.GraphQLPRBatchPageSize < 0 || c.GitHub.GraphQLPRBatchPageSize > 100 { return fmt.Errorf("github.graphql_pr_batch_page_size must be between 1 and 100, or 0 for the default") } + if !c.GitHub.Notifications.Valid() { + return fmt.Errorf("github.notifications.mode must be %q or %q", NotificationsModeQuiet, NotificationsModeNormal) + } if _, err := HeartbeatOmitClasses(c.Hub.HeartbeatOmit); err != nil { return err } diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index fa1b538a81..f3fb23417c 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -189,6 +189,7 @@ duplicate_sweep.bot_authors[] # TODO #11854 evidence.complexity.enabled # TODO #11854 evidence.complexity.static_analysis # TODO #11854 github.additional_bot_logins[] # TODO #11854 +github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) good_first_issue.repos[] # advanced scorer tuning; yaml-only (#12185) diff --git a/src/pkg/github/automerge/automerge_contributor_nudge.go b/src/pkg/github/automerge/automerge_contributor_nudge.go index fd5ee49552..ac40c1b07c 100644 --- a/src/pkg/github/automerge/automerge_contributor_nudge.go +++ b/src/pkg/github/automerge/automerge_contributor_nudge.go @@ -7,6 +7,7 @@ import ( "time" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/prstatus" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -366,9 +367,20 @@ const TrustedHuman071MarkerPrefix = "\n", TrustedHuman071MarkerPrefix, n.HeadSHA) - fmt.Fprintf(&b, "@%s this PR is held at `%s` and the hive will not merge it yet.\n\n", n.Author, stage.Label()) + at := "@" + if !mention { + at = "" + } + fmt.Fprintf(&b, "%s%s this PR is held at `%s` and the hive will not merge it yet.\n\n", at, n.Author, stage.Label()) if len(n.FailingChecks) > 0 { b.WriteString("**Failing checks:**\n") for _, c := range n.FailingChecks { @@ -387,7 +399,7 @@ func TrustedHuman071Comment(n ContributorNudge, stage stagelabels.Stage) string // noteTrustedHuman071 posts TrustedHuman071Comment once per head for a // trusted human PR in 071. It returns the number of comments posted. -func (c *Engine) noteTrustedHuman071(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, now time.Time) (int, error) { +func (c *Engine) noteTrustedHuman071(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, policy StageLabelPolicy, now time.Time) (int, error) { rec, ok := store.Get(key) if !ok || obs.Author == "" || obs.HeadSHA == "" || rec.NudgeHead == obs.HeadSHA { return 0, nil @@ -401,12 +413,21 @@ func (c *Engine) noteTrustedHuman071(ctx context.Context, store *stagelabels.Sto HeadSHA: obs.HeadSHA, Title: obs.Title, URL: obs.URL, Author: obs.Author, OpenedAt: obs.OpenedAt, Reason: obs.Reason, FailingChecks: checks, ReviewAsks: asks, HumanChangesRequested: human, Nudge: 1, } - body := TrustedHuman071Comment(n, stagelabels.NeedsAuthor) - if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + // Normal mode: every head is a fresh comment with a mention. Quiet + // mode: one section of the status comment, rewritten per head, and the + // author is @-mentioned only when the cause changed since the last + // mention — a new head failing the same way is the same ask. + mention := !policy.QuietNotifications || rec.MentionDue(obs.Reason) + body := TrustedHuman071Note(n, stagelabels.NeedsAuthor, mention) + posted, err := c.postStageNote(ctx, policy, obs, prstatus.KeyHuman071Note, body) + if err != nil { c.warn("stage labels: trusted human 071 note failed", "repo", obs.Display, "pr", obs.Number, "error", err) return 0, err } store.MarkNudged(key, obs.HeadSHA, 1, false, now) - c.info("stage labels: trusted human told why the PR is at 071", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "reason", obs.Reason) - return 1, nil + if mention { + store.MarkMentioned(key, obs.Reason) + } + c.info("stage labels: trusted human told why the PR is at 071", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "reason", obs.Reason, "mention", mention) + return posted, nil } diff --git a/src/pkg/github/automerge/automerge_quiet_notifications_test.go b/src/pkg/github/automerge/automerge_quiet_notifications_test.go new file mode 100644 index 0000000000..c28c45c0c1 --- /dev/null +++ b/src/pkg/github/automerge/automerge_quiet_notifications_test.go @@ -0,0 +1,182 @@ +package automerge + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/prstatus" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +func quietStageEngine(t *testing.T, api *stageAPI, clock *contributorLaneClock) (*Engine, *stagelabels.Store) { + t.Helper() + api.statefulComments = true + srv := newStageAPI(t, api) + t.Cleanup(srv.Close) + e, _, store := newStageEngine(t, srv.URL, clock) + e.stageLabelPolicy = func() StageLabelPolicy { + return StageLabelPolicy{Enabled: true, StalledRequireQuiet: true, QuietNotifications: true} + } + return e, store +} + +// Quiet mode: the 071 note, the stall note and a real regression all land +// in ONE hive status comment that is created once and then edited in place. +// Every later change is a PATCH (no email), never a second comment. +func TestQuietNotificationsStageNotesFoldIntoOneEditedComment(t *testing.T) { + api := &stageAPI{labels: map[string]string{}} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + clock := &contributorLaneClock{at: time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)} + e, _ := quietStageEngine(t, api, clock) + ctx := context.Background() + approve := ContributorLaneVerdict{Configured: true, Approved: true, Verdict: "approve"} + observe := func(labels []string, reason string, err error) { + t.Helper() + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", stagePR(11, labels...), reason, false, err) + e.noteStageVerdict("acme", "widget", 11, approve) + e.noteStageRole("acme", "widget", 11, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + } + observe(nil, "review-state-check", errors.New("boom")) // → 080 + clock.advance(30 * time.Minute) + observe([]string{"stage/080-awaiting-merge-admission", "role/trusted", "author/human"}, "review-state-check", errors.New("boom")) // stalled + if len(api.comments) != 1 || !prstatus.IsStatusComment(api.comments[0]) { + t.Fatalf("stall must create the single status comment, got %q", api.comments) + } + if got, ok := prstatus.Get(api.comments[0], prstatus.KeyStageStalled); !ok || !strings.Contains(got, "no activity for 30m0s") { + t.Fatalf("stall section missing: %s", api.comments[0]) + } + // Regression to 070 on a real failure: same comment, edited, both + // sections present. + observe([]string{"stage/080-awaiting-merge-admission", "stage/stalled", "role/trusted", "author/human"}, "check-failing:unit", nil) + if len(api.comments) != 1 { + t.Fatalf("regression posted a second comment: %q", api.comments) + } + if len(api.commentEdits) == 0 { + t.Fatal("regression did not edit the status comment") + } + last := api.commentEdits[len(api.commentEdits)-1] + if got, ok := prstatus.Get(last, prstatus.KeyStageRegressed); !ok || !strings.Contains(got, "080-awaiting-merge-admission → 071-needs-author: check-failing:unit") { + t.Fatalf("edited comment lacks the regression: %s", last) + } + if _, ok := prstatus.Get(last, prstatus.KeyStageStalled); !ok { + t.Fatalf("stall section lost on edit: %s", last) + } +} + +// Quiet mode: a check going back to pending after a push is not a +// regression and produces neither a comment nor an edit. +func TestQuietNotificationsPendingIsNotARegression(t *testing.T) { + api := &stageAPI{labels: map[string]string{}} + for _, d := range stagelabels.AllLabelDefs() { + api.labels[d.Name] = d.Color + } + clock := &contributorLaneClock{at: time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)} + e, _ := quietStageEngine(t, api, clock) + ctx := context.Background() + observe := func(labels []string, reason string) { + t.Helper() + e.recordStage(stageLaneSelf, "acme/widget", "acme", "widget", stagePR(10, labels...), reason, false, nil) + e.noteStageRole("acme", "widget", 10, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(ctx); err != nil { + t.Fatal(err) + } + } + observe(nil, "head-changed-since-eval") + clock.advance(time.Minute) + observe([]string{"stage/100-merge-queue", "role/trusted", "author/human"}, "required-check-pending:unit") + if len(api.comments) != 0 || len(api.commentEdits) != 0 { + t.Fatalf("pending check posted a regression: comments=%q edits=%q", api.comments, api.commentEdits) + } +} + +func TestRegressionNotable(t *testing.T) { + for reason, want := range map[string]bool{ + "check-failing:unit": true, + "required-check-failing:unit": true, + "conflicting": true, + "required-check-pending:unit": false, + "check-pending": false, + "merge-train:queued-behind#15817": false, + "merge-train:rebasing": false, + "base-refresh:pending": false, + "pending: head pushed 54s ago (< min_head_age)": false, + } { + if got := regressionNotable(reason); got != want { + t.Errorf("regressionNotable(%q) = %v, want %v", reason, got, want) + } + } +} + +// Being queued behind another PR in the merge train, or being rebased by the +// hive, is the hive's own wait: it must never read as stalled. +func TestStageReasonWaitsOnHiveMergeTrain(t *testing.T) { + for _, reason := range []string{"merge-train:queued-behind#15817", "merge-train:rebasing", "base-refresh:pending"} { + if !stageReasonWaitsOnHive(reason) { + t.Errorf("stageReasonWaitsOnHive(%q) = false", reason) + } + } + if stageReasonWaitsOnHive("check-failing:unit") { + t.Error("a failing check is not a hive wait") + } +} + +// Quiet mode: the trusted-human 071 note @-mentions the author once per +// distinct cause, not once per head; a new head with the same cause edits +// the status comment without a mention, and a new cause mentions again. +func TestQuietNotificationsHuman071MentionOncePerCause(t *testing.T) { + api := &stageAPI{labels: map[string]string{}} + clock := &contributorLaneClock{at: time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)} + e, _ := quietStageEngine(t, api, clock) + sweep := func(head, reason string) { + t.Helper() + e.recordStage(stageLaneTrusted, "acme/widget", "acme", "widget", trustedHuman071PR(41, head), reason, false, nil) + e.noteStageRole("acme", "widget", 41, stagelabels.RoleTrusted) + if _, err := e.ApplyStageLabels(context.Background()); err != nil { + t.Fatal(err) + } + } + section := func() string { + t.Helper() + body := "" + for _, c := range api.posted[41] { + if b, _ := c["body"].(string); prstatus.IsStatusComment(b) { + body = b + } + } + if body == "" { + t.Fatalf("no status comment: posted=%v", api.posted) + } + text, _ := prstatus.Get(body, prstatus.KeyHuman071Note) + return text + } + sweep("aaa", "conflicting") + if len(api.comments) != 1 { + t.Fatalf("want one status comment, got %q", api.comments) + } + if s := section(); !strings.Contains(s, "@clubanderson") || !strings.Contains(s, "head=aaa") { + t.Fatalf("first note must mention the author: %s", s) + } + clock.at = clock.at.Add(10 * time.Minute) + sweep("bbb", "conflicting") + if len(api.comments) != 1 { + t.Fatalf("new head created a second comment: %q", api.comments) + } + if s := section(); strings.Contains(s, "@clubanderson") || !strings.Contains(s, "head=bbb") { + t.Fatalf("same cause on a new head must update without a mention: %s", s) + } + sweep("ccc", "check-failing:unit") + if s := section(); !strings.Contains(s, "@clubanderson") || !strings.Contains(s, "head=ccc") { + t.Fatalf("new cause must mention again: %s", s) + } + if len(api.comments) != 1 { + t.Fatalf("still one comment expected, got %q", api.comments) + } +} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index bbf411d37e..fc3f77e4f5 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -31,6 +31,7 @@ import ( "github.com/hivecommons/hive/pkg/authorkind" "github.com/hivecommons/hive/pkg/delegatedecision" hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/prstatus" "github.com/hivecommons/hive/pkg/stageengine" "github.com/hivecommons/hive/pkg/stageengine/prstage" "github.com/hivecommons/hive/pkg/stagelabels" @@ -159,6 +160,13 @@ type StageLabelPolicy struct { // nor an adoption can turn the check green (hivecommons/hive#14273). // nil = unknown (no park). ForkGuard func(repo string, number int, head string) []string + // QuietNotifications is github.notifications.mode != normal (default + // quiet): the stall note, the regression note and the trusted-human + // 071 note are folded into the PR's one hive status comment and edited + // in place instead of each being a fresh comment (an edit emails + // nobody; a new comment emails the author and every watcher), and the + // 071 note @-mentions its author once per cause, not once per head. + QuietNotifications bool } // ownershipRoutingPrefix is the lane routing label family. `agent/` @@ -1255,14 +1263,15 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) if want.Stalled && want.Stage.StallNote() { if rec, ok := store.Get(key); ok && !rec.StallCommented { body := stagelabels.StallComment(want.Stage, stagelabels.Dwell(want.Stage, policy.Dwell), obs.Reason) - if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + n, err := c.postStageNote(ctx, policy, obs, prstatus.KeyStageStalled, body) + if err != nil { c.warn("stage labels: stall note failed", "repo", obs.Display, "pr", obs.Number, "error", err) if firstErr == nil { firstErr = err } } else { store.MarkStallCommented(key) - result.Comments++ + result.Comments += n } } } @@ -1373,7 +1382,7 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) if want.Stage == stagelabels.NeedsAuthor && (role == stagelabels.RoleTrusted || reviewerAsked) && obs.AuthorKind != authorkind.Clanker && obs.Reason != stagelabels.LaneReasonHiveSignoffAttribution { // Silence is the worst outcome for a trusted person // (hivecommons/hive#13636): always on, not gated on policy. - n, err := c.noteTrustedHuman071(ctx, store, key, obs, now) + n, err := c.noteTrustedHuman071(ctx, store, key, obs, policy, now) result.Comments += n if err != nil && firstErr == nil { firstErr = err @@ -1403,19 +1412,22 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) firstErr = err } } - if tr.Regressed { + if tr.Regressed && regressionNotable(obs.Reason) { // Keyed by head SHA: a gate flapping between two stages on one // head (e.g. min_head_age) must not post every sweep (#12557). + // A pending check or a hive-controlled wait is not a + // regression at all (regressionNotable) and posts nothing. if rec, ok := store.Get(key); ok && rec.RegressionCommentDue(obs.HeadSHA) { body := stagelabels.RegressionComment(tr.Prev, tr.Next, obs.Reason) - if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + n, err := c.postStageNote(ctx, policy, obs, prstatus.KeyStageRegressed, body) + if err != nil { c.warn("stage labels: regression comment failed", "repo", obs.Display, "pr", obs.Number, "error", err) if firstErr == nil { firstErr = err } } else { store.MarkRegressionCommentedForHead(key, obs.HeadSHA) - result.Comments++ + result.Comments += n } } } @@ -1440,6 +1452,59 @@ func (c *Engine) ApplyStageLabels(ctx context.Context) (StageLabelResult, error) return result, firstErr } +// regressionNotable reports whether a stage regression is worth telling the +// PR about: something failed, or a person is being asked for something. A +// check that went back to pending (CI restarted after a push) or a state +// the hive itself controls (merge train, base refresh, shared-CI incident) +// is not a regression anyone can act on, and posting it as one is noise. +func regressionNotable(reason string) bool { + return classifyCIReason(reason) != ciReasonPending && !stageReasonWaitsOnHive(reason) +} + +// postStageNote delivers one of the stage notes (stall, regression, 071) to +// the PR. In normal mode it is a fresh comment. In quiet mode it is folded +// into the PR's single hive status comment under key, edited in place: the +// comment is created only the first time, and only that creation counts +// as a comment posted. Returns the number of comments created. +func (c *Engine) postStageNote(ctx context.Context, policy StageLabelPolicy, obs stageObservation, key, body string) (int, error) { + if policy.QuietNotifications { + done, fresh, err := c.editStatusSection(ctx, obs.Owner, obs.Repo, obs.Number, key, body) + if err != nil || done { + return 0, err + } + body = fresh + } + if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + return 0, err + } + return 1, nil +} + +// editStatusSection rewrites section key of the PR's hive status comment +// (prstatus.Marker) to text when that comment exists, and reports done. When +// the PR has no status comment yet nothing is written: the caller creates +// one from the returned body, so the create stays a single call site. +func (c *Engine) editStatusSection(ctx context.Context, owner, repo string, number int, key, text string) (done bool, fresh string, err error) { + comments, err := c.listIssueComments(ctx, owner, repo, number) + if err != nil { + return false, "", err + } + for _, cm := range comments { + if cm == nil || !prstatus.IsStatusComment(cm.GetBody()) { + continue + } + next := prstatus.Upsert(cm.GetBody(), key, text) + if next == cm.GetBody() { + return true, "", nil + } + if _, _, err := c.gh.Issues.EditComment(ctx, owner, repo, cm.GetID(), &gh.IssueComment{Body: gh.Ptr(next)}); err != nil { + return true, "", fmt.Errorf("editing hive status comment on %s/%s#%d: %w", owner, repo, number, err) + } + return true, "", nil + } + return false, prstatus.Upsert("", key, text), nil +} + // ensureStageLabels provisions (or recolours) the family's labels in a repo // once per process: one list call, then a create or patch per label that is // missing or whose colour drifted from the table. A PATCH keeps the label on diff --git a/src/pkg/github/automerge/automerge_stage_labels_test.go b/src/pkg/github/automerge/automerge_stage_labels_test.go index b290cfd971..73d12e2f9c 100644 --- a/src/pkg/github/automerge/automerge_stage_labels_test.go +++ b/src/pkg/github/automerge/automerge_stage_labels_test.go @@ -51,6 +51,13 @@ type stageAPI struct { // (hivecommons/hive#15020). Unlisted PRs answer empty lists. issueComments map[int][]map[string]any issueEvents map[int][]map[string]any + // statefulComments makes POST /issues/N/comments persist into the + // GET list (ids 1001, 1002, …) and accepts PATCH /issues/comments/ID, + // recording each edit in commentEdits: the quiet-notification tests + // need the status comment to survive between sweeps. + statefulComments bool + posted map[int][]map[string]any + commentEdits []string } type stageCommitFixture struct { @@ -115,7 +122,21 @@ func newStageAPI(t *testing.T, api *stageAPI) *httptest.Server { if out == nil { out = []map[string]any{} } + out = append(out, api.posted[n]...) _ = json.NewEncoder(w).Encode(out) + case api.statefulComments && r.Method == http.MethodPatch && strings.HasPrefix(path, "/repos/acme/widget/issues/comments/"): + id, _ := strconv.ParseInt(strings.TrimPrefix(path, "/repos/acme/widget/issues/comments/"), 10, 64) + var body map[string]string + _ = json.NewDecoder(r.Body).Decode(&body) + for _, list := range api.posted { + for _, c := range list { + if c["id"] == id { + c["body"] = body["body"] + } + } + } + api.commentEdits = append(api.commentEdits, body["body"]) + _ = json.NewEncoder(w).Encode(map[string]any{"id": id, "body": body["body"]}) case r.Method == http.MethodGet && strings.HasPrefix(path, "/repos/acme/widget/issues/") && strings.HasSuffix(path, "/events"): n, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(path, "/repos/acme/widget/issues/"), "/events")) out := api.issueEvents[n] @@ -169,8 +190,17 @@ func newStageAPI(t *testing.T, api *stageAPI) *httptest.Server { var body map[string]string _ = json.NewDecoder(r.Body).Decode(&body) api.comments = append(api.comments, body["body"]) + id := int64(1) + if api.statefulComments { + n, _ := strconv.Atoi(strings.TrimSuffix(path[strings.LastIndex(path, "/issues/")+len("/issues/"):], "/comments")) + if api.posted == nil { + api.posted = map[int][]map[string]any{} + } + id = int64(1000 + len(api.comments)) + api.posted[n] = append(api.posted[n], map[string]any{"id": id, "body": body["body"], "user": map[string]any{"login": testHiveAppBotLogin}}) + } w.WriteHeader(http.StatusCreated) - _ = json.NewEncoder(w).Encode(map[string]any{"id": 1}) + _ = json.NewEncoder(w).Encode(map[string]any{"id": id}) default: t.Errorf("unexpected request %s %s", r.Method, path) w.WriteHeader(http.StatusTeapot) @@ -2414,8 +2444,10 @@ func TestApplyStageLabelsRegressionFlapOnSameHeadCommentsOnce(t *testing.T) { comments += len(api.comments) api.reset() } - if comments != 1 { - t.Fatalf("regression comments across 4 flaps on one head = %d, want 1", comments) + // A min_head_age wait is the hive's own gate: nothing failed, so since + // the notification-spam fix no regression note is posted for it at all. + if comments != 0 { + t.Fatalf("regression comments across 4 pending flaps on one head = %d, want 0", comments) } } diff --git a/src/pkg/github/automerge/automerge_stage_sharedci.go b/src/pkg/github/automerge/automerge_stage_sharedci.go index eadf71926f..bfb72d467b 100644 --- a/src/pkg/github/automerge/automerge_stage_sharedci.go +++ b/src/pkg/github/automerge/automerge_stage_sharedci.go @@ -67,8 +67,21 @@ func baseBranchRedReason(checks []string) string { return stageengine.BaseBranch // stageReasonWaitsOnHive reports reasons that leave the PR waiting on the // hive rather than a person (no stall): a shared-CI incident being repaired, -// a red base branch, and a branch update deferred to the next sweep tick. +// a red base branch, a branch update deferred to the next sweep tick, a +// merge-train slot behind the front (queued or being rebased by the hive) +// and a base refresh the hive is running. None of those is anything the +// author can act on, so none may read as stage/stalled. func stageReasonWaitsOnHive(reason string) bool { - return reason == autoMergeReasonBehindBudgetExhausted || strings.HasPrefix(reason, stageReasonSharedCIIncident) || - strings.HasPrefix(reason, stageReasonBaseBranchRed) + if reason == autoMergeReasonBehindBudgetExhausted || strings.HasPrefix(reason, stageReasonSharedCIIncident) || + strings.HasPrefix(reason, stageReasonBaseBranchRed) || strings.HasPrefix(reason, basePreparationPrefix) { + return true + } + if rest, ok := strings.CutPrefix(strings.TrimSpace(reason), prstage.MergeTrainReasonPrefix); ok { + state, _, _ := strings.Cut(rest, "#") + switch strings.TrimSpace(state) { + case prstage.MergeTrainStateQueuedBehind, prstage.MergeTrainStateRebasing: + return true + } + } + return false } diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 47ca632235..c3bc954ef1 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -269,6 +269,11 @@ type Client struct { // a negative value disables the backstop. combinedPerspectivesFn func() bool maxReviewsPerHeadFn func() int + // quietNotificationsFn is github.notifications.mode != normal, read + // live: fold the hive's PR notes into one edited status comment, post no + // no-findings review, one hive review per head. nil (nothing wired) + // reads as normal, so unwired clients behave as before. + quietNotificationsFn func() bool // reviewRequireLabelsFn returns review.require_labels, read live so a // Features-tab edit gates the next relay request without a rebuild. nil // or empty means the gate is off. @@ -688,6 +693,24 @@ func (c *Client) SetReviewCadenceLimits(combined func() bool, maxPerHead func() c.maxReviewsPerHeadFn = maxPerHead } +// SetNotificationsQuiet wires github.notifications.mode (quiet when fn +// returns true). Read live so a config reload applies to the next write. +func (c *Client) SetNotificationsQuiet(fn func() bool) { + if c == nil { + return + } + c.quietNotificationsFn = fn +} + +// notificationsQuiet reports whether the hive is in quiet notification +// mode: a new comment or review is an email to the author and every +// watcher, and the Activity Monitor already carries what the comment would +// say. The config default is quiet; a client nothing wired (tests) behaves +// as before. +func (c *Client) notificationsQuiet() bool { + return c != nil && c.quietNotificationsFn != nil && c.quietNotificationsFn() +} + func (c *Client) SetConfidenceScore(enabled func() bool) { if c == nil { return diff --git a/src/pkg/github/pr_duplicate_guard.go b/src/pkg/github/pr_duplicate_guard.go index 8594a6abd1..d00c9685bc 100644 --- a/src/pkg/github/pr_duplicate_guard.go +++ b/src/pkg/github/pr_duplicate_guard.go @@ -12,6 +12,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/dupsweep" + "github.com/hivecommons/hive/pkg/prstatus" ) // Duplicate reasons reported in CreatePRResult.DuplicateReason. @@ -280,11 +281,21 @@ func duplicateGuardComment(f *duplicateFinding, head string) string { } // redirectToExistingPR posts the redirect comment on the existing PR, once. -// Best-effort: the refusal is the enforcement, the comment is courtesy. +// Best-effort: the refusal is the enforcement, the comment is courtesy. In +// quiet notification mode it is a section of the PR's hive status comment, +// edited in place, so a retried request or a second agent never emails the +// watchers again. func (c *Client) redirectToExistingPR(ctx context.Context, owner, repo, head string, f *duplicateFinding) { if f.reason == DuplicateReasonMergedFix { return } + if c.notificationsQuiet() { + if _, err := c.UpsertPRStatusSection(ctx, owner+"/"+repo, f.pr.GetNumber(), prstatus.KeyDuplicateGuard, duplicateGuardComment(f, head)); err != nil { + c.logger.Warn("duplicate guard: could not record the redirect in the status comment", + slog.String("repo", repo), slog.Int("number", f.pr.GetNumber()), slog.String("error", err.Error())) + } + return + } comments, _, err := c.client.Issues.ListComments(ctx, owner, repo, f.pr.GetNumber(), &gh.IssueListCommentsOptions{ListOptions: gh.ListOptions{PerPage: 100}}) if err != nil { c.logger.Warn("duplicate guard: could not read comments on the existing PR, skipping redirect comment", diff --git a/src/pkg/github/pr_duplicate_guard_test.go b/src/pkg/github/pr_duplicate_guard_test.go index 568f4b766f..c1bb331f01 100644 --- a/src/pkg/github/pr_duplicate_guard_test.go +++ b/src/pkg/github/pr_duplicate_guard_test.go @@ -49,6 +49,7 @@ type guardServer struct { mu sync.Mutex created int comments int + edits int } func (g *guardServer) start(t *testing.T) *httptest.Server { @@ -179,6 +180,11 @@ func (g *guardServer) start(t *testing.T) *httptest.Server { g.comments++ g.mu.Unlock() _, _ = io.WriteString(w, `{"id":1}`) + case r.Method == "PATCH" && strings.Contains(path, "/issues/comments/"): + g.mu.Lock() + g.edits++ + g.mu.Unlock() + _, _ = io.WriteString(w, `{"id":1}`) case r.Method == "POST" && strings.HasSuffix(path, "/pulls"): g.mu.Lock() g.created++ diff --git a/src/pkg/github/pr_status_comment.go b/src/pkg/github/pr_status_comment.go new file mode 100644 index 0000000000..700c555de5 --- /dev/null +++ b/src/pkg/github/pr_status_comment.go @@ -0,0 +1,36 @@ +package github + +import ( + "context" + "strings" + + "github.com/hivecommons/hive/pkg/prstatus" +) + +// UpsertPRStatusSection rewrites section key of repo#number's single hive +// status comment (prstatus.Marker) to text, creating the comment only when +// the PR has none. Editing a comment notifies nobody; creating one emails +// the author and every watcher, so this is the quiet-mode delivery for +// every note the hive used to post as its own comment. An empty text +// removes the section. Reports whether a comment was created. +func (c *Client) UpsertPRStatusSection(ctx context.Context, repo string, number int, key, text string) (bool, error) { + if c == nil { + return false, ErrNoGitHubClient + } + current, err := c.UpsertIssueMarkerComment(ctx, repo, number, prstatus.Marker, "", false) + if err != nil { + return false, err + } + if !current.Found && strings.TrimSpace(text) == "" { + return false, nil + } + next := prstatus.Upsert(current.Previous, key, text) + if current.Found && next == current.Previous { + return false, nil + } + res, err := c.UpsertIssueMarkerComment(ctx, repo, number, prstatus.Marker, next, true) + if err != nil { + return false, err + } + return res.Created, nil +} diff --git a/src/pkg/github/pr_status_comment_test.go b/src/pkg/github/pr_status_comment_test.go new file mode 100644 index 0000000000..8ded938bf6 --- /dev/null +++ b/src/pkg/github/pr_status_comment_test.go @@ -0,0 +1,194 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/hivecommons/hive/pkg/prstatus" + "github.com/hivecommons/hive/pkg/review" +) + +// statusCommentServer is a GitHub stand-in that keeps issue comments: POST +// appends, PATCH rewrites, GET lists. It counts creates and edits so a test +// can prove the second write edited in place instead of posting again. +type statusCommentServer struct { + mu sync.Mutex + comments []map[string]any + creates int + edits int +} + +func (s *statusCommentServer) start(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/comments"): + _ = json.NewEncoder(w).Encode(s.comments) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments"): + var body map[string]string + _ = json.NewDecoder(r.Body).Decode(&body) + s.creates++ + cm := map[string]any{"id": 100 + s.creates, "body": body["body"]} + s.comments = append(s.comments, cm) + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(cm) + case r.Method == http.MethodPatch && strings.Contains(r.URL.Path, "/issues/comments/"): + var body map[string]string + _ = json.NewDecoder(r.Body).Decode(&body) + s.edits++ + for _, cm := range s.comments { + if strings.HasSuffix(r.URL.Path, "/"+jsonNumber(cm["id"])) { + cm["body"] = body["body"] + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1}) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func jsonNumber(v any) string { + b, _ := json.Marshal(v) + return string(b) +} + +// The first section creates the status comment; every later section, and +// every change to an existing one, edits that comment. Nothing is posted +// twice, and an unchanged section is not even an edit. +func TestUpsertPRStatusSectionCreatesOnceThenEdits(t *testing.T) { + s := &statusCommentServer{} + srv := s.start(t) + c := testClient(t, srv.URL) + ctx := context.Background() + + created, err := c.UpsertPRStatusSection(ctx, "o/r", 5, prstatus.KeyStageStalled, "stalled at 080") + if err != nil || !created { + t.Fatalf("first upsert: created=%v err=%v", created, err) + } + created, err = c.UpsertPRStatusSection(ctx, "o/r", 5, prstatus.KeyStageRegressed, "080 → 071") + if err != nil || created { + t.Fatalf("second section must edit, not create: created=%v err=%v", created, err) + } + created, err = c.UpsertPRStatusSection(ctx, "o/r", 5, prstatus.KeyStageStalled, "stalled at 080") + if err != nil || created { + t.Fatalf("unchanged section: created=%v err=%v", created, err) + } + if s.creates != 1 || s.edits != 1 { + t.Fatalf("creates=%d edits=%d, want 1 create and 1 edit", s.creates, s.edits) + } + body, _ := s.comments[0]["body"].(string) + if !prstatus.IsStatusComment(body) { + t.Fatalf("not a status comment: %q", body) + } + for _, key := range []string{prstatus.KeyStageStalled, prstatus.KeyStageRegressed} { + if _, ok := prstatus.Get(body, key); !ok { + t.Fatalf("section %q missing from %q", key, body) + } + } + if created, err := c.UpsertPRStatusSection(ctx, "o/r", 5, prstatus.KeyStageStalled, ""); err != nil || created || s.edits != 2 { + t.Fatalf("clearing a section must edit: created=%v err=%v edits=%d", created, err, s.edits) + } + body, _ = s.comments[0]["body"].(string) + if _, ok := prstatus.Get(body, prstatus.KeyStageStalled); ok { + t.Fatalf("cleared section still present: %q", body) + } +} + +// Quiet mode: the duplicate-guard redirect lands in the status comment of +// the PR it points at and a retry edits it rather than stacking comments. +func TestCreatePR_DuplicateGuardQuietModeUsesStatusComment(t *testing.T) { + g := &guardServer{open: []guardPR{{Number: 7, Ref: "a", Body: "Fixes #42", User: "human"}}} + srv := g.start(t) + c := NewClientForTest(srv.URL, "o", nil, prTestLogger()) + c.SetNotificationsQuiet(func() bool { return true }) + res, err := c.CreatePR(context.Background(), "o/r", "new-branch", "main", "title", "Closes #42") + if err != nil || res.Number != 7 || res.DuplicateReason != DuplicateReasonClosesIssue { + t.Fatalf("CreatePR = %+v, %v", res, err) + } + if g.comments != 1 || g.edits != 0 { + t.Fatalf("first redirect must create the status comment: comments=%d edits=%d", g.comments, g.edits) + } + // Retry: the status comment exists now, so the guard edits it. + g.existingComments = []string{prstatus.Upsert("", prstatus.KeyDuplicateGuard, "stale")} + if _, err := c.CreatePR(context.Background(), "o/r", "new-branch", "main", "title", "Closes #42"); err != nil { + t.Fatal(err) + } + if g.comments != 1 || g.edits != 1 { + t.Fatalf("retry must edit the status comment, not post: comments=%d edits=%d", g.comments, g.edits) + } +} + +// Quiet mode: a review whose body is only the clean acknowledgement is +// recorded as a verdict and never submitted to GitHub; a body with findings +// is still a review. +func TestReviewRequestWatcher_QuietModeSuppressesNoFindingsReview(t *testing.T) { + reviewed := 0 + srv := newReviewMockServer(t, &reviewed, nil) + defer srv.Close() + c := reviewTestClient(t, srv.URL) + c.SetNotificationsQuiet(func() bool { return true }) + dir := withReviewDir(t) + oldLinks := ReviewLinksPath + ReviewLinksPath = filepath.Join(t.TempDir(), "review-links.json") + t.Cleanup(func() { ReviewLinksPath = oldLinks }) + withVerdictDispatchState(t, review.DispatchState{Pending: []review.PendingReview{ + {Repo: "o/r", Number: 5, HeadSHA: "abc", Perspective: review.PerspectiveCorrectness, Agent: "reviewer"}, + }}) + + submit := func(body string) ReviewResponse { + t.Helper() + path, err := WriteReviewRequest(dir, ReviewRequest{Repo: "o/r", Number: 5, Event: "comment", Agent: "reviewer", Body: body, Report: validVerdictJSON(t, "o/r", 5, "correctness", "approve")}) + if err != nil { + t.Fatal(err) + } + c.ProcessReviewRequestsOnce(context.Background()) + raw, err := os.ReadFile(strings.TrimSuffix(path, ".json") + ".result.json") + if err != nil { + t.Fatal(err) + } + var resp ReviewResponse + _ = json.Unmarshal(raw, &resp) + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("request must be consumed: %v", err) + } + return resp + } + + resp := submit("**Reviewed** — no findings from this perspective.") + if !resp.OK || resp.State != ReviewEventRecordVerdict || resp.Note != reviewNoFindingsSuppressedNote { + t.Fatalf("no-findings ack must be recorded, not posted: %+v", resp) + } + if reviewed != 0 { + t.Fatalf("no-findings ack submitted %d reviews", reviewed) + } + if resp := submit("`main.go:12` the error is dropped on the floor"); !resp.OK || reviewed != 1 { + t.Fatalf("a body with findings must still post: %+v reviewed=%d", resp, reviewed) + } +} + +func TestMaxReviewsPerHeadQuietMode(t *testing.T) { + c := testClient(t, "http://127.0.0.1:0") + c.SetReviewCadenceLimits(func() bool { return false }, func() int { return 0 }) + normal := c.maxReviewsPerHead() + c.SetNotificationsQuiet(func() bool { return true }) + if got := c.maxReviewsPerHead(); got != 1 { + t.Fatalf("quiet mode must allow one review per head, got %d (normal %d)", got, normal) + } + c.SetReviewCadenceLimits(func() bool { return false }, func() int { return 3 }) + if got := c.maxReviewsPerHead(); got != 3 { + t.Fatalf("an explicit max_reviews_per_head must win: %d", got) + } +} diff --git a/src/pkg/github/review_request_watcher.go b/src/pkg/github/review_request_watcher.go index 65775d5639..6c4204de0d 100644 --- a/src/pkg/github/review_request_watcher.go +++ b/src/pkg/github/review_request_watcher.go @@ -15,6 +15,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/effects" + "github.com/hivecommons/hive/pkg/prstatus" "github.com/hivecommons/hive/pkg/review" ) @@ -298,6 +299,19 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re threadID := strings.TrimSpace(req.ThreadID) // A "comment" that names a thread is an in-thread reply, not a PR review. threadReply := okEvent && apiEvent == "COMMENT" && threadID != "" + // Quiet notification mode: a review whose whole body is the clean + // acknowledgement ("**Reviewed** — no findings from …") is recorded as + // a verdict and never submitted. Submitting it emails the author and + // every watcher to say nothing happened; the verdict still reaches the + // evidence bundle and the Activity Monitor. The request keeps its + // report, so the shape checks below treat it exactly as record_verdict. + noFindingsSuppressed := false + if okEvent && !recordOnly && !resolveThread && threadID == "" && !req.Revise && + c.notificationsQuiet() && strings.TrimSpace(req.Report) != "" && review.NoFindingsAcknowledgement(req.Body) { + recordOnly = true + noFindingsSuppressed = true + req.Event = ReviewEventRecordVerdict + } // Validate shape BEFORE authorizing or touching the API — a hopeless request // must never retry. var shapeErr string @@ -462,6 +476,17 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re // state record_verdict and a note, so the agent's own loop is done. if !recordOnly && !req.Revise && apiEvent != "APPROVE" { if reason := c.perHeadReviewRefusal(ctx, req); reason != "" { + if c.notificationsQuiet() && strings.TrimSpace(req.Body) != "" { + // The head already carries its one hive review. The + // findings are not dropped: they go into the PR's status + // comment, edited in place, where a later perspective's + // findings for the same head join them without another + // review submission (and another email). + if _, ferr := c.UpsertPRStatusSection(ctx, req.Repo, req.Number, prstatus.KeyReviewFindingsPrefix+verdictSlug(req.Agent), reviewFindingsSection(req)); ferr != nil { + c.logger.Warn("review-request watcher: could not fold findings into the status comment", + slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("error", ferr.Error())) + } + } c.recordReviewEvidence(ctx, req, c.recordReviewVerdict(ctx, req, ""), nil, nowFn()) if err := c.fileOutOfScopeReviewBacklog(ctx, req, nowFn().UTC()); err != nil { c.logger.Warn("review-request watcher: could not file out-of-scope backlog", @@ -487,12 +512,16 @@ func (c *Client) handleOneReviewRequest(ctx context.Context, path string, src re slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("error", err.Error())) } - c.writeReviewResult(path, ReviewResponse{OK: true, Number: req.Number, State: ReviewEventRecordVerdict, At: nowFn().UTC().Format(time.RFC3339)}) + resp := ReviewResponse{OK: true, Number: req.Number, State: ReviewEventRecordVerdict, At: nowFn().UTC().Format(time.RFC3339)} + if noFindingsSuppressed { + resp.Note = reviewNoFindingsSuppressedNote + } + c.writeReviewResult(path, resp) _ = os.Remove(path) c.reviewRetries.clear(path) c.logger.Info("review-request watcher: verdict recorded without a comment", slog.String("repo", req.Repo), slog.Int("number", req.Number), - slog.String("agent", req.Agent)) + slog.String("agent", req.Agent), slog.Bool("no_findings_suppressed", noFindingsSuppressed)) return } @@ -924,5 +953,24 @@ func (c *Client) maxReviewsPerHead() int { if c.combinedPerspectivesFn != nil && c.combinedPerspectivesFn() { return 1 } + if c.notificationsQuiet() { + // One review submission per head, whatever the perspective count: + // later perspectives' findings join it through the status comment. + return 1 + } return c.perspectives.Len() } + +// reviewNoFindingsSuppressedNote is the result-file note for a clean +// acknowledgement the quiet mode recorded instead of submitting. +const reviewNoFindingsSuppressedNote = "comment suppressed: no-findings acknowledgement recorded as a verdict (github.notifications.mode: quiet)" + +// reviewFindingsSection renders a perspective's findings for the status +// comment: who found them, then the body as written. +func reviewFindingsSection(req ReviewRequest) string { + var b strings.Builder + fmt.Fprintf(&b, "**Review findings** from `%s`", strings.TrimSpace(req.Agent)) + b.WriteString(" (folded here because this head already carries its hive review):\n\n") + b.WriteString(strings.TrimSpace(req.Body)) + return b.String() +} diff --git a/src/pkg/prstatus/prstatus.go b/src/pkg/prstatus/prstatus.go new file mode 100644 index 0000000000..2dd0cfd4a8 --- /dev/null +++ b/src/pkg/prstatus/prstatus.go @@ -0,0 +1,136 @@ +// Package prstatus renders the one hive status comment a pull request +// carries in github.notifications.mode: quiet. Every new issue comment +// GitHub sends emails the author and every watcher; editing one sends +// nothing. So instead of one comment per note (stage stalled, stage +// regressed, the trusted-human 071 note, the duplicate-PR redirect, …) the +// hive keeps a single comment tagged Marker and rewrites one keyed section +// of it in place. The package is pure string handling; the GitHub client +// and the auto-merge engine each own the list/edit/create calls around it. +package prstatus + +import ( + "strings" +) + +// Marker tags the status comment so a later pass finds it. Exactly one +// comment per PR carries it. +const Marker = "" + +// Heading opens the comment body. It names the contract so a reader +// understands why the comment keeps changing under them. +const Heading = "**Hive status** — updated in place; edits do not notify. Full history is in the Activity Monitor." + +const ( + sectionOpenPrefix = "" + sectionClose = "" +) + +// Section is one keyed block of the status comment. +type Section struct { + Key string + Body string +} + +// Parse splits a status comment body into its sections, in order. Text +// outside a section (the heading, anything a person typed) is dropped: the +// comment is the hive's, and Render rebuilds the frame. +func Parse(body string) []Section { + var out []Section + rest := body + for { + i := strings.Index(rest, sectionOpenPrefix) + if i < 0 { + return out + } + rest = rest[i+len(sectionOpenPrefix):] + j := strings.Index(rest, sectionOpenSuffix) + if j < 0 { + return out + } + key := strings.TrimSpace(rest[:j]) + rest = rest[j+len(sectionOpenSuffix):] + k := strings.Index(rest, sectionClose) + if k < 0 { + out = append(out, Section{Key: key, Body: strings.TrimSpace(rest)}) + return out + } + out = append(out, Section{Key: key, Body: strings.TrimSpace(rest[:k])}) + rest = rest[k+len(sectionClose):] + } +} + +// Render builds the comment body from its sections. +func Render(sections []Section) string { + var b strings.Builder + b.WriteString(Marker) + b.WriteString("\n") + b.WriteString(Heading) + for _, s := range sections { + b.WriteString("\n\n") + b.WriteString(sectionOpenPrefix) + b.WriteString(s.Key) + b.WriteString(sectionOpenSuffix) + b.WriteString("\n") + b.WriteString(strings.TrimSpace(s.Body)) + b.WriteString("\n") + b.WriteString(sectionClose) + } + b.WriteString("\n") + return b.String() +} + +// Upsert returns existing with the section key set to text: replaced in +// place when present, appended otherwise. An empty text removes the +// section. existing may be "" (no status comment yet). +func Upsert(existing, key, text string) string { + sections := Parse(existing) + text = strings.TrimSpace(text) + out := make([]Section, 0, len(sections)+1) + replaced := false + for _, s := range sections { + if s.Key != key { + out = append(out, s) + continue + } + if text == "" || replaced { + continue + } + out = append(out, Section{Key: key, Body: text}) + replaced = true + } + if !replaced && text != "" { + out = append(out, Section{Key: key, Body: text}) + } + return Render(out) +} + +// Get returns the body of section key and whether it exists. +func Get(existing, key string) (string, bool) { + for _, s := range Parse(existing) { + if s.Key == key { + return s.Body, true + } + } + return "", false +} + +// IsStatusComment reports whether body is the hive status comment. +func IsStatusComment(body string) bool { + return strings.Contains(body, Marker) +} + +// Section keys the hive writes. Each replaces what used to be a standalone +// comment carrying the legacy `` marker named alongside it; +// the legacy marker stays inside the section text so existing readers that +// grep for it still find it. +const ( + KeyStageStalled = "stage-stalled" // + KeyStageRegressed = "stage-regressed" // + KeyHuman071Note = "human-071-note" // + KeyDuplicateGuard = "create-pr-duplicate-guard" // + // KeyReviewFindingsPrefix + perspective holds a perspective's findings + // when the head already carries the hive review it may have, so the + // findings are kept without a second review submission. + KeyReviewFindingsPrefix = "review-findings:" +) diff --git a/src/pkg/prstatus/prstatus_test.go b/src/pkg/prstatus/prstatus_test.go new file mode 100644 index 0000000000..45366e0319 --- /dev/null +++ b/src/pkg/prstatus/prstatus_test.go @@ -0,0 +1,48 @@ +package prstatus + +import ( + "strings" + "testing" +) + +func TestUpsertReplacesSectionInPlace(t *testing.T) { + body := Upsert("", KeyStageStalled, "\nstage 080: no activity for 30m") + if !IsStatusComment(body) || !strings.Contains(body, Heading) { + t.Fatalf("first upsert did not frame the comment:\n%s", body) + } + body = Upsert(body, KeyStageRegressed, "\nstage 080 → 071: conflicting") + body = Upsert(body, KeyStageStalled, "\nstage 085: no activity for 2h") + sections := Parse(body) + if len(sections) != 2 { + t.Fatalf("want 2 sections, got %d:\n%s", len(sections), body) + } + if sections[0].Key != KeyStageStalled || !strings.Contains(sections[0].Body, "stage 085") || strings.Contains(body, "stage 080: no") { + t.Fatalf("stalled section not replaced in place:\n%s", body) + } + if sections[1].Key != KeyStageRegressed { + t.Fatalf("regressed section lost: %+v", sections) + } + if strings.Count(body, Marker) != 1 { + t.Fatalf("marker must appear exactly once:\n%s", body) + } +} + +func TestUpsertEmptyRemovesSection(t *testing.T) { + body := Upsert("", KeyDuplicateGuard, "redirect") + body = Upsert(body, KeyHuman071Note, "note") + body = Upsert(body, KeyDuplicateGuard, "") + if _, ok := Get(body, KeyDuplicateGuard); ok { + t.Fatalf("empty text did not remove the section:\n%s", body) + } + if got, ok := Get(body, KeyHuman071Note); !ok || got != "note" { + t.Fatalf("other section disturbed: %q %v", got, ok) + } +} + +func TestUpsertIdempotent(t *testing.T) { + a := Upsert("", KeyStageStalled, "x") + b := Upsert(a, KeyStageStalled, "x") + if a != b { + t.Fatalf("same text should render identically:\n%s\n---\n%s", a, b) + } +} diff --git a/src/pkg/review/no_findings.go b/src/pkg/review/no_findings.go new file mode 100644 index 0000000000..5476a98162 --- /dev/null +++ b/src/pkg/review/no_findings.go @@ -0,0 +1,23 @@ +package review + +import ( + "regexp" + "strings" +) + +// noFindingsRe matches the one-line clean-review acknowledgement the +// publish instruction asks for ("**Reviewed** — no findings from ."), +// alone in the body. Markdown emphasis, the dash variant, the optional +// review-heads suffix and a trailing period are all tolerated; anything +// else in the body (a real finding) does not match. +var noFindingsRe = regexp.MustCompile(`(?is)\A\s*(?:\*\*|_)?\s*reviewed\s*(?:\*\*|_)?\s*[—–-]+\s*no findings from[^\n]*?\.?\s*\z`) + +// NoFindingsAcknowledgement reports whether body is nothing but the clean +// acknowledgement line. In quiet notification mode the relay records such a +// review's verdict without submitting a GitHub review: the submission would +// email the author and every watcher to say nothing happened, while the +// verdict already reaches the evidence bundle and the Activity Monitor. +func NoFindingsAcknowledgement(body string) bool { + body = strings.TrimSpace(body) + return body != "" && noFindingsRe.MatchString(body) +} diff --git a/src/pkg/review/no_findings_test.go b/src/pkg/review/no_findings_test.go new file mode 100644 index 0000000000..630bac0462 --- /dev/null +++ b/src/pkg/review/no_findings_test.go @@ -0,0 +1,29 @@ +package review + +import "testing" + +func TestNoFindingsAcknowledgement(t *testing.T) { + yes := []string{ + "**Reviewed** — no findings from this perspective.", + "**Reviewed** — no findings from security, correctness.", + "**Reviewed** — no findings from adjudicator (all 2 review heads agreed: abc1234, def5678).", + " Reviewed - no findings from this perspective \n", + "_Reviewed_ – no findings from maintainability", + } + for _, b := range yes { + if !NoFindingsAcknowledgement(b) { + t.Errorf("should match: %q", b) + } + } + no := []string{ + "", + "**Reviewed** — no findings from security.\n\n**correctness**\n- src/x.go:12 nil deref", + "**security**\n- src/x.go:12 nil deref\n\n_No findings from: style._", + "No findings from this perspective, but one nit: …", + } + for _, b := range no { + if NoFindingsAcknowledgement(b) { + t.Errorf("should not match: %q", b) + } + } +} diff --git a/src/pkg/stagelabels/mention_test.go b/src/pkg/stagelabels/mention_test.go new file mode 100644 index 0000000000..f6c22466fd --- /dev/null +++ b/src/pkg/stagelabels/mention_test.go @@ -0,0 +1,41 @@ +package stagelabels + +import ( + "path/filepath" + "testing" + "time" +) + +// An @-mention is due once per distinct cause class, not once per head: the +// same cause again is silent, a new cause mentions, and an empty cause never +// does. +func TestMentionDueOncePerCause(t *testing.T) { + now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) + s := NewStore(filepath.Join(t.TempDir(), "s.json"), func() time.Time { return now }) + s.Observe("k", NeedsAuthor, "conflicting") + r, _ := s.Get("k") + if !r.MentionDue("conflicting") { + t.Fatal("first cause must mention") + } + s.MarkMentioned("k", "conflicting") + r, _ = s.Get("k") + if r.MentionDue("conflicting") { + t.Fatal("same cause must not mention again") + } + if !r.MentionDue("check-failing:unit") { + t.Fatal("new cause must mention") + } + s.MarkMentioned("k", "check-failing:unit") + r, _ = s.Get("k") + for _, same := range []string{"check-failing:lint", "required-check-failing:unit", "check-failing:unit(1 of 3)"} { + if r.MentionDue(same) { + t.Fatalf("%q is the same cause class as a failing check and must not mention again", same) + } + } + if r.MentionDue("") { + t.Fatal("empty cause never mentions") + } + if !r.MentionDue("conflicting") { + t.Fatal("cause changing back must mention again") + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index 310e93f5c4..7a75540898 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -124,6 +124,12 @@ type Record struct { // "superseder merged but this PR has moved on" note was posted, so a // diverged original is told once per head rather than every poll. SupersederMergedNotedHead string `json:"superseder_merged_noted_head,omitempty"` + // MentionCause is the cause (ReasonClass) the author was last + // @-mentioned for in the hive status comment. In quiet notification + // mode a person is mentioned once per distinct cause, not once per + // head: a mention is an email, and the same cause on a new head is the + // same ask. + MentionCause string `json:"mention_cause,omitempty"` // DCOHead, DCOTotal and DCOUnsigned cache the commit check for one head // (hivecommons/hive#12542): how many non-merge commits the PR carried // and how many lacked a Signed-off-by trailer. DCOUnsignedHive / @@ -1164,6 +1170,41 @@ func (r Record) EntryCommentExplains(head, cause string) bool { return len(r.EntryCommentedCauses) == 0 || cause == "" || slices.Contains(r.EntryCommentedCauses, cause) } +// MentionDue reports whether the author should be @-mentioned for cause: +// never for an empty cause, otherwise only when it differs from the cause +// of the last mention. +func (r Record) MentionDue(cause string) bool { + cause = MentionCauseClass(cause) + return cause != "" && !strings.EqualFold(r.MentionCause, cause) +} + +// MentionCauseClass collapses a stage reason to what the author would be +// asked to do about it: "check-failing:unit" and "check-failing:lint" are +// both "CI is red, fix it", so a second red check on a later head is the +// same cause and earns no second @-mention; a conflict after a red check is +// a new one. The class is the reason's kind (ReasonClass, then the part +// before the first ':'), with the "required-" qualifier dropped. +func MentionCauseClass(reason string) string { + class := ReasonClass(reason) + if i := strings.IndexByte(class, ':'); i >= 0 { + class = class[:i] + } + return strings.TrimPrefix(strings.TrimSpace(class), "required-") +} + +// MarkMentioned records that the author was @-mentioned for cause. +func (s *Store) MarkMentioned(key, cause string) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok { + return + } + r.MentionCause = MentionCauseClass(cause) + s.items[key] = r + s.dirty = true +} + // MarkStallCommented records that the stall note for this stage visit was posted. func (s *Store) MarkStallCommented(key string) { s.mu.Lock() diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 7cebf677ba..78977525c6 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -9,7 +9,7 @@ raw pkg/github/automerge/automerge_bot_takeover.go 2 raw pkg/github/automerge/automerge_contributor_adopt.go 15 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 3 +raw pkg/github/automerge/automerge_contributor_nudge.go 2 raw pkg/github/automerge/automerge_contributor_workflow_approval.go 1 raw pkg/github/automerge/automerge_held_runs.go 3 raw pkg/github/automerge/automerge_merge_commit.go 1