From 7fe93ab32ec4cfcac768c5ce8375b8534306a9c6 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sun, 8 Nov 2026 18:57:10 -0700 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20contributor=20nudge:=20per-P?= =?UTF-8?q?R=20CI-failure=20cooldown=20and=20failing-set=20dedupe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI-failure nudges are keyed on the failing-check set rather than the lane's reason prefix. The same set on a new head, or a check joining the set on the same head, edits the PR's one nudge comment (marker gains checks= attempt=; no relay re-dispatch for the same head). A changed set on a new head within governor.labels.stage.contributor_nudge.ci_failure_cooldown (default 6h) is folded into the comment instead of counting as a fresh nudge. The ledger persists in the stage-label store across restarts. Fixes #17328 Signed-off-by: Andrew Anderson --- .../changed-ci-failure-nudge-cooldown.md | 1 + src/cmd/hive/merge_eligibility.go | 1 + .../stage-labels.md | 10 + src/docs/operator-reference/README.md | 1 + src/hive.yaml.example | 1 + src/pkg/config/config.go | 14 ++ src/pkg/dashboard/api_governor.go | 26 ++- .../nudge_repeat_after_settings_test.go | 35 +++ .../static-src/js/config-governor.js | 8 + .../dashboard/static-src/js/config-state.js | 2 +- src/pkg/dashboard/static/index.html | 10 +- .../automerge/automerge_contributor_nudge.go | 156 ++++++++++++- ...erge_contributor_nudge_ci_cooldown_test.go | 218 ++++++++++++++++++ .../automerge/automerge_stage_labels.go | 6 + src/pkg/stagelabels/stagelabels_test.go | 24 ++ src/pkg/stagelabels/store.go | 51 +++- 16 files changed, 546 insertions(+), 18 deletions(-) create mode 100644 changelog.d/changed-ci-failure-nudge-cooldown.md create mode 100644 src/pkg/github/automerge/automerge_contributor_nudge_ci_cooldown_test.go diff --git a/changelog.d/changed-ci-failure-nudge-cooldown.md b/changelog.d/changed-ci-failure-nudge-cooldown.md new file mode 100644 index 0000000000..66085f2466 --- /dev/null +++ b/changelog.d/changed-ci-failure-nudge-cooldown.md @@ -0,0 +1 @@ +- Contributor nudge: CI-failure nudges are keyed on the failing-check set, not the lane's reason prefix — the same set on a new head or a check joining the set on the same head edits the PR's one `hive:contributor-nudge` comment (no relay re-dispatch for the same head), and a changed set within `governor.labels.stage.contributor_nudge.ci_failure_cooldown` (default 6h) folds into it instead of counting as a fresh nudge. The ledger persists in the stage-label store across restarts. diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index c8bfc424eb..1f06e579c6 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -115,6 +115,7 @@ func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy StalledRequireQuiet: stage.Stalled.IsRequireQuiet(), ContributorNudge: stage.ContributorNudge.IsEnabled(), RenudgeInterval: nudgeRepeatAfter(cfg), + CIFailureCooldown: stage.ContributorNudge.EffectiveCIFailureCooldown(), Adoption: stage.Adoption.IsEnabled(), GraceOnline: stage.EffectiveContributorGraceOnline(), GraceOffline: stage.EffectiveContributorGraceOffline(), diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index 7a98414f7b..c5bc086c13 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -778,6 +778,16 @@ When a contributor-agent PR goes red the hive does not just relabel it (a human- agent get interrupted?". `governor.labels.stage.contributor_nudge.enabled: false` turns the comment and the relay task off; the stage label still moves. + Failing checks are one class whatever the lane's prefix + (`check-failing`, `required-check-failing`, `optional-check-failing`), + keyed on the failing-check set (hivecommons/hive#17328): the marker adds + `checks= attempt=`, the same set red on another head or a + check joining the set on the same head edits the comment (the relay is + not re-dispatched for the same head), and a *changed* set on a new head + within `governor.labels.stage.contributor_nudge.ci_failure_cooldown` + (default 6h) is folded into the comment too; after the cooldown it + counts as a fresh nudge. The ledger lives in the stage-label store, so + a restart does not re-nudge. 2. Relay contributors (the author has a contributor profile and a live relay connection) also receive the diagnosis in their relay session as a `fix-pr` task with `priority: interrupt`. Presence = a relay heartbeat diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index a31416e76c..eb2bc663f5 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -476,6 +476,7 @@ advanced into the merge path. | `auto_merge.max_merges` | `3` (`DefaultAutoMergeSweepMaxMerges`) when 0/unset | Caps merges per sweep pass. | | `auto_merge.min_head_age` | `3m` | Minimum PR head age before automerge trusts an unknown required-check set. A fresh head pushed more recently than this waits with `pending: head pushed ... ago (< min_head_age)` unless `auto_merge.required_checks` is declared and every required check is complete and successful. Head age is measured from the head commit's committer date (never earlier than the PR's creation), not the PR's `updated_at`, so label and comment activity — including the hive's own — does not restart it. When GitHub's head time is ahead of the host clock (clock skew), age is measured from when the hive first observed the head instead, so the hold lasts one window and then clears (`pending: head time ahead of host clock; head first seen ... ago (< min_head_age)`). | | `auto_merge.nudge_repeat_after` | `72h` | How long a contributor nudge's condition must persist before the hive nudges once more. Nudges are one comment per PR and reason class, edited in place for a new head or changed reason; after this interval with the same condition the comment is re-posted once (cap 2 per reason), then never again. `governor.labels.stage.contributor_nudge.renudge_interval`, when set, overrides it. | +| `governor.labels.stage.contributor_nudge.ci_failure_cooldown` | `6h` | CI-failure nudges are keyed on the failing-check set: the same set red on a new head, or a check joining the set on the same head, edits the PR's one nudge comment. A *different* set on a new head inside this window is folded into that comment too (count unchanged); after it the hive counts a fresh nudge. | | `auto_merge.required_checks` | unset | Default operator-declared status-check contexts / check-run names (e.g. `["build-gate"]`) that the sweep's green gate requires on repos without a per-repo override. See below. | | `auto_merge.repos..required_checks` | inherits default | Per-repo override for heterogeneous hives. `` may be the bare name from `project.repos` or `owner/repo`; an explicit empty list declares that GitHub has no required contexts, while Hive still requires positive CI evidence from at least one real successful check-run before merge. | | `auto_merge.allow_unprotected_base` | deprecated no-op | Accepted for compatibility only. [`hive-merge`](../hive-merge.md) no longer refuses solely because a base branch has no GitHub branch protection; it may merge into any branch the App can write after positive CI evidence. | diff --git a/src/hive.yaml.example b/src/hive.yaml.example index 6c7b5649aa..3277db7eba 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -524,6 +524,7 @@ governor: # contributor_nudge: # stage/072: one @-mention comment per head + relay fix-pr interrupt (#12436) # enabled: true # renudge_interval: 24h # second (and last) nudge; default = the stage dwell + # ci_failure_cooldown: 6h # a new head red on a different check set inside this window folds into the one nudge comment (#17328) # presence_window: 15m # relay heartbeat this fresh = contributor online → relay interrupt, else comment only # contributor_grace_online: 2h # nudge unanswered this long (online author) → stage/074 adoption # contributor_grace_offline: 15m # same for offline / external authors (comment-only nudge) diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index e9cf8a847f..428821f64a 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -3179,6 +3179,20 @@ type ContributorNudgeConfig struct { // more (the documented cap is 2 nudges per PR and reason class). Unset // defers to auto_merge.nudge_repeat_after (default 72h). RenudgeInterval string `yaml:"renudge_interval,omitempty"` + // CIFailureCooldown is how long after a CI-failure nudge a changed + // failing-check set on a new head is folded into the PR's one nudge + // comment instead of counting as a fresh nudge + // (hivecommons/hive#17328). Default DefaultContributorNudgeCIFailureCooldown (6h). + CIFailureCooldown string `yaml:"ci_failure_cooldown,omitempty"` +} + +// DefaultContributorNudgeCIFailureCooldown is +// governor.labels.stage.contributor_nudge.ci_failure_cooldown's default. +const DefaultContributorNudgeCIFailureCooldown = 6 * time.Hour + +// EffectiveCIFailureCooldown parses CIFailureCooldown with the 6h default. +func (c ContributorNudgeConfig) EffectiveCIFailureCooldown() time.Duration { + return parseDurationOr(c.CIFailureCooldown, DefaultContributorNudgeCIFailureCooldown) } // IsEnabled reports whether the contributor nudge runs (default on). diff --git a/src/pkg/dashboard/api_governor.go b/src/pkg/dashboard/api_governor.go index 0e55191dc0..096cb82a7e 100644 --- a/src/pkg/dashboard/api_governor.go +++ b/src/pkg/dashboard/api_governor.go @@ -168,8 +168,12 @@ func (s *Server) handleGovernorConfigGet(w http.ResponseWriter, r *http.Request) "stageNudgeRenudge": cfg.Governor.Labels.Stage.ContributorNudge.RenudgeInterval, // auto_merge.nudge_repeat_after (hivecommons/hive#17067): the // same-reason re-nudge window the legacy renudge_interval defers to. - "nudgeRepeatAfter": cfg.AutoMerge.NudgeRepeatAfter, - "stagePresenceWindow": cfg.Governor.Labels.Stage.PresenceWindow, + "nudgeRepeatAfter": cfg.AutoMerge.NudgeRepeatAfter, + // governor.labels.stage.contributor_nudge.ci_failure_cooldown + // (hivecommons/hive#17328): the fold window for a changed + // failing-check set. + "stageNudgeCICooldown": cfg.Governor.Labels.Stage.ContributorNudge.CIFailureCooldown, + "stagePresenceWindow": cfg.Governor.Labels.Stage.PresenceWindow, // governor.labels.stage.adoption.enabled / contributor_grace_*: the // stage-074 adoption of red contributor PRs. "stageAdoptionEnabled": cfg.Governor.Labels.Stage.Adoption.IsEnabled(), @@ -815,6 +819,10 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { // NudgeRepeatAfter is auto_merge.nudge_repeat_after // (hivecommons/hive#17067); a Go duration, empty restores 72h. NudgeRepeatAfter *string `json:"nudge_repeat_after"` + // StageNudgeCICooldown is + // governor.labels.stage.contributor_nudge.ci_failure_cooldown + // (hivecommons/hive#17328); a Go duration, empty restores 6h. + StageNudgeCICooldown *string `json:"stage_nudge_ci_failure_cooldown"` // Stage-074 adoption: governor.labels.stage.adoption.enabled and // governor.labels.stage.contributor_grace_online / _offline. StageAdoptionEnabled *bool `json:"stage_adoption_enabled"` @@ -922,11 +930,12 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { } } for name, v := range map[string]*string{ - "stage_nudge_renudge_interval": body.StageNudgeRenudge, - "nudge_repeat_after": body.NudgeRepeatAfter, - "stage_presence_window": body.StagePresenceWindow, - "stage_grace_online": body.StageGraceOnline, - "stage_grace_offline": body.StageGraceOffline, + "stage_nudge_renudge_interval": body.StageNudgeRenudge, + "nudge_repeat_after": body.NudgeRepeatAfter, + "stage_nudge_ci_failure_cooldown": body.StageNudgeCICooldown, + "stage_presence_window": body.StagePresenceWindow, + "stage_grace_online": body.StageGraceOnline, + "stage_grace_offline": body.StageGraceOffline, } { if v == nil || strings.TrimSpace(*v) == "" { continue @@ -1037,6 +1046,9 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { if body.NudgeRepeatAfter != nil { s.deps.Config.AutoMerge.NudgeRepeatAfter = strings.TrimSpace(*body.NudgeRepeatAfter) } + if body.StageNudgeCICooldown != nil { + s.deps.Config.Governor.Labels.Stage.ContributorNudge.CIFailureCooldown = strings.TrimSpace(*body.StageNudgeCICooldown) + } if body.StagePresenceWindow != nil { s.deps.Config.Governor.Labels.Stage.PresenceWindow = strings.TrimSpace(*body.StagePresenceWindow) } diff --git a/src/pkg/dashboard/nudge_repeat_after_settings_test.go b/src/pkg/dashboard/nudge_repeat_after_settings_test.go index 6479cce7ac..d5c1e78dc5 100644 --- a/src/pkg/dashboard/nudge_repeat_after_settings_test.go +++ b/src/pkg/dashboard/nudge_repeat_after_settings_test.go @@ -40,3 +40,38 @@ func TestHandleGovernorLabels_NudgeRepeatAfterRoundTrip(t *testing.T) { t.Fatalf("empty must clear the override, got %q", got) } } + +// governor.labels.stage.contributor_nudge.ci_failure_cooldown +// (hivecommons/hive#17328) sits beside the nudge intervals on the Labels tab. +func TestHandleGovernorLabels_CIFailureCooldownRoundTrip(t *testing.T) { + srv := newFullServer(t) + w := httptest.NewRecorder() + srv.handleGovernorLabels(w, ownerPUT(t, "/api/config/governor/labels", `{"stage_nudge_ci_failure_cooldown":" 2h "}`)) + if w.Code != http.StatusOK { + t.Fatalf("code = %d, body = %s", w.Code, w.Body.String()) + } + if got := srv.deps.Config.Governor.Labels.Stage.ContributorNudge.CIFailureCooldown; got != "2h" { + t.Fatalf("ci_failure_cooldown = %q, want trimmed 2h", got) + } + if got := decodeGovernorConfigGet(t, srv)["stageNudgeCICooldown"]; got != "2h" { + t.Fatalf("GET stageNudgeCICooldown = %v, want 2h", got) + } + + w = httptest.NewRecorder() + srv.handleGovernorLabels(w, ownerPUT(t, "/api/config/governor/labels", `{"stage_nudge_ci_failure_cooldown":"-1h"}`)) + if w.Code != http.StatusBadRequest { + t.Fatalf("negative duration: code = %d, want 400; body = %s", w.Code, w.Body.String()) + } + if got := srv.deps.Config.Governor.Labels.Stage.ContributorNudge.CIFailureCooldown; got != "2h" { + t.Fatalf("rejected save mutated ci_failure_cooldown to %q", got) + } + + w = httptest.NewRecorder() + srv.handleGovernorLabels(w, ownerPUT(t, "/api/config/governor/labels", `{"stage_nudge_ci_failure_cooldown":""}`)) + if w.Code != http.StatusOK { + t.Fatalf("clear: code = %d, body = %s", w.Code, w.Body.String()) + } + if got := srv.deps.Config.Governor.Labels.Stage.ContributorNudge.CIFailureCooldown; got != "" { + t.Fatalf("empty must restore the default, got %q", got) + } +} diff --git a/src/pkg/dashboard/static-src/js/config-governor.js b/src/pkg/dashboard/static-src/js/config-governor.js index 454d97282e..0cc16442a8 100644 --- a/src/pkg/dashboard/static-src/js/config-governor.js +++ b/src/pkg/dashboard/static-src/js/config-governor.js @@ -707,6 +707,9 @@ const nudgeRepeatAfter = (_configState.dirty.labels && _configState.dirty.labels.nudge_repeat_after !== undefined) ? _configState.dirty.labels.nudge_repeat_after : (_configState.data.nudgeRepeatAfter || ''); + const stageNudgeCICooldown = (_configState.dirty.labels && _configState.dirty.labels.stage_nudge_ci_failure_cooldown !== undefined) + ? _configState.dirty.labels.stage_nudge_ci_failure_cooldown + : (_configState.data.stageNudgeCICooldown || ''); const stagePresenceWindow = (_configState.dirty.labels && _configState.dirty.labels.stage_presence_window !== undefined) ? _configState.dirty.labels.stage_presence_window : (_configState.data.stagePresenceWindow || ''); @@ -788,6 +791,11 @@
How long a contributor PR must stay red for the same reason before its one hive:contributor-nudge comment is rewritten a second (and last) time; empty = 72h.
+
+ + +
After a CI-failure nudge, a new head failing a different set of checks within this window is folded into the PR's existing hive:contributor-nudge comment instead of counting as a fresh nudge; empty = 6h.
+
diff --git a/src/pkg/dashboard/static-src/js/config-state.js b/src/pkg/dashboard/static-src/js/config-state.js index bdecee1865..81f7869d99 100644 --- a/src/pkg/dashboard/static-src/js/config-state.js +++ b/src/pkg/dashboard/static-src/js/config-state.js @@ -80,7 +80,7 @@ { tab: 'Labels', section: 'Labels', label: 'Central stage engine', key: 'governor.labels.stage.engine.mode', text: 'stage engine mode shadow enforce dry run pause anomaly reconciler ADR-0025 governor.labels.stage.engine.mode' }, { tab: 'Labels', section: 'Labels', label: 'Stage dwell overrides', key: 'governor.labels.stage.dwell', text: 'stage dwell stalled threshold governor.labels.stage.dwell' }, { tab: 'Labels', section: 'Labels', label: 'Adoption of a maintainer\'s PR', key: 'governor.labels.stage.adoption.maintainer_policy', text: 'adoption maintainer policy adopt ask never maintainer own pr clanker disconnected offline adopt action governor.labels.stage.adoption.maintainer_policy' }, - { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval auto_merge.nudge_repeat_after governor.labels.stage.presence_window' }, + { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval auto_merge.nudge_repeat_after governor.labels.stage.contributor_nudge.ci_failure_cooldown governor.labels.stage.presence_window' }, { tab: 'Labels', section: 'Labels', label: 'Adopt red contributor PRs', key: 'governor.labels.stage.adoption.enabled', text: 'adoption adopted-by-hive stage 074 red contributor pr grace online offline supersede takeover in place after offline unregistered heartbeat governor.labels.stage.adoption.enabled governor.labels.stage.contributor_grace_online governor.labels.stage.contributor_grace_offline governor.labels.stage.adoption.after_offline governor.labels.stage.adoption.after_unregistered governor.labels.stage.adoption.in_place governor.labels.stage.adoption.strict_attribution strict attribution governor.labels.stage.adoption.auto_merge auto merge adopted head hive authority governor.labels.stage.adoption.supersede.close_first close first superseded reopen copy failed governor.labels.stage.adoption.close_superseded close superseded on adopt on merge clanker authored opt-in label governor.labels.stage.adoption.offline_grace offline grace rebase failed twice fixer resolving conflicts governor.labels.stage.adoption.rebase_attempt_timeout rebase attempt timeout' }, { tab: 'Hub', section: 'Contributor Relay', label: 'Fix budget', key: 'contribute.max_parallel_fixes', text: 'fix budget parallel fixes focus window red pr fix-pr preempt spawn contribute.max_parallel_fixes contribute.min_focus_window' }, { tab: 'Logging', section: 'Logging', label: 'Governor logging', key: 'governor.logging.max_size_mb', text: 'governor logging directory level compression max size age backups governor.logging.compress governor.logging.dir governor.logging.level governor.logging.max_age_days governor.logging.max_backups governor.logging.max_size_mb' }, diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 196740460b..3b318cb2be 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -53520,7 +53520,7 @@

Configure LiteLLM

{ tab: 'Labels', section: 'Labels', label: 'Central stage engine', key: 'governor.labels.stage.engine.mode', text: 'stage engine mode shadow enforce dry run pause anomaly reconciler ADR-0025 governor.labels.stage.engine.mode' }, { tab: 'Labels', section: 'Labels', label: 'Stage dwell overrides', key: 'governor.labels.stage.dwell', text: 'stage dwell stalled threshold governor.labels.stage.dwell' }, { tab: 'Labels', section: 'Labels', label: 'Adoption of a maintainer\'s PR', key: 'governor.labels.stage.adoption.maintainer_policy', text: 'adoption maintainer policy adopt ask never maintainer own pr clanker disconnected offline adopt action governor.labels.stage.adoption.maintainer_policy' }, - { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval auto_merge.nudge_repeat_after governor.labels.stage.presence_window' }, + { tab: 'Labels', section: 'Labels', label: 'Contributor nudge', key: 'governor.labels.stage.contributor_nudge.enabled', text: 'contributor nudge returned-to-contributor red ci fix-pr relay interrupt renudge presence window governor.labels.stage.contributor_nudge.enabled governor.labels.stage.contributor_nudge.renudge_interval auto_merge.nudge_repeat_after governor.labels.stage.contributor_nudge.ci_failure_cooldown governor.labels.stage.presence_window' }, { tab: 'Labels', section: 'Labels', label: 'Adopt red contributor PRs', key: 'governor.labels.stage.adoption.enabled', text: 'adoption adopted-by-hive stage 074 red contributor pr grace online offline supersede takeover in place after offline unregistered heartbeat governor.labels.stage.adoption.enabled governor.labels.stage.contributor_grace_online governor.labels.stage.contributor_grace_offline governor.labels.stage.adoption.after_offline governor.labels.stage.adoption.after_unregistered governor.labels.stage.adoption.in_place governor.labels.stage.adoption.strict_attribution strict attribution governor.labels.stage.adoption.auto_merge auto merge adopted head hive authority governor.labels.stage.adoption.supersede.close_first close first superseded reopen copy failed governor.labels.stage.adoption.close_superseded close superseded on adopt on merge clanker authored opt-in label governor.labels.stage.adoption.offline_grace offline grace rebase failed twice fixer resolving conflicts governor.labels.stage.adoption.rebase_attempt_timeout rebase attempt timeout' }, { tab: 'Hub', section: 'Contributor Relay', label: 'Fix budget', key: 'contribute.max_parallel_fixes', text: 'fix budget parallel fixes focus window red pr fix-pr preempt spawn contribute.max_parallel_fixes contribute.min_focus_window' }, { tab: 'Logging', section: 'Logging', label: 'Governor logging', key: 'governor.logging.max_size_mb', text: 'governor logging directory level compression max size age backups governor.logging.compress governor.logging.dir governor.logging.level governor.logging.max_age_days governor.logging.max_backups governor.logging.max_size_mb' }, @@ -60325,6 +60325,9 @@

Backend placement policy

const nudgeRepeatAfter = (_configState.dirty.labels && _configState.dirty.labels.nudge_repeat_after !== undefined) ? _configState.dirty.labels.nudge_repeat_after : (_configState.data.nudgeRepeatAfter || ''); + const stageNudgeCICooldown = (_configState.dirty.labels && _configState.dirty.labels.stage_nudge_ci_failure_cooldown !== undefined) + ? _configState.dirty.labels.stage_nudge_ci_failure_cooldown + : (_configState.data.stageNudgeCICooldown || ''); const stagePresenceWindow = (_configState.dirty.labels && _configState.dirty.labels.stage_presence_window !== undefined) ? _configState.dirty.labels.stage_presence_window : (_configState.data.stagePresenceWindow || ''); @@ -60406,6 +60409,11 @@

Stage labels

How long a contributor PR must stay red for the same reason before its one hive:contributor-nudge comment is rewritten a second (and last) time; empty = 72h.
+
+ + +
After a CI-failure nudge, a new head failing a different set of checks within this window is folded into the PR's existing hive:contributor-nudge comment instead of counting as a fresh nudge; empty = 6h.
+
diff --git a/src/pkg/github/automerge/automerge_contributor_nudge.go b/src/pkg/github/automerge/automerge_contributor_nudge.go index d52ce25b09..36935fec1c 100644 --- a/src/pkg/github/automerge/automerge_contributor_nudge.go +++ b/src/pkg/github/automerge/automerge_contributor_nudge.go @@ -2,6 +2,8 @@ package automerge import ( "context" + "crypto/sha256" + "encoding/hex" "fmt" "slices" "strings" @@ -43,7 +45,36 @@ const contributorNudgeCap = 2 // and delivery mode. The upsert searches for ContributorNudgeMarkerPrefix // alone, so a changed reason slug still finds the comment. func ContributorNudgeMarker(reason, head string, nudge int, mode string) string { - return fmt.Sprintf("%s reason=%s head=%s n=%d mode=%s -->", ContributorNudgeMarkerPrefix, stagelabels.NudgeReasonSlug(reason), head, nudge, nonEmpty(mode, "comment")) + return contributorNudgeMarker(reason, head, nudge, mode, nil, 0) +} + +// contributorNudgeMarker is ContributorNudgeMarker plus, for a CI-failure +// nudge, `checks= attempt=` +// (hivecommons/hive#17328). +func contributorNudgeMarker(reason, head string, nudge int, mode string, checks []string, attempt int) string { + var b strings.Builder + fmt.Fprintf(&b, "%s reason=%s head=%s n=%d mode=%s", ContributorNudgeMarkerPrefix, stagelabels.NudgeReasonSlug(reason), head, nudge, nonEmpty(mode, "comment")) + if len(checks) > 0 && attempt > 0 { + fmt.Fprintf(&b, " checks=%s attempt=%d", ciFailureSetDigest(checks), attempt) + } + b.WriteString(" -->") + return b.String() +} + +// ciFailureSetDigest keys a failing-check set independent of order: the +// first 12 hex chars of the SHA-256 of the sorted names. +func ciFailureSetDigest(checks []string) string { + sorted := append([]string(nil), checks...) + slices.Sort(sorted) + sum := sha256.Sum256([]byte(strings.Join(sorted, "\n"))) + return hex.EncodeToString(sum[:])[:12] +} + +// isCIFailureNudgeReason reports whether reason is a failing-check reason +// (any check-failing prefix): the nudges that share the per-PR +// failing-set ledger and the ci_failure_cooldown. +func isCIFailureNudgeReason(reason string) bool { + return stagelabels.NudgeReasonSlug(reason) == stagelabels.NudgeReasonCIFailure } // ContributorNudge is the diagnosis handed to the sink for one PR in stage 072. @@ -75,6 +106,9 @@ type ContributorNudge struct { Nudge int // Stalled is true when this nudge is the repeat re-nudge. Stalled bool + // Attempt is, for a CI-failure nudge, how many red heads the same + // failing set has been seen on (1 for the first); 0 otherwise. + Attempt int } // ContributorNudgeOutcome is what the sink did with a nudge. @@ -219,7 +253,7 @@ func nudgeDiagnosisRouted(reason string, d stageDetail, route *stagelabels.Route // the prose. func ContributorNudgeComment(n ContributorNudge, out ContributorNudgeOutcome) string { var b strings.Builder - b.WriteString(ContributorNudgeMarker(n.Reason, n.HeadSHA, n.Nudge, out.Mode)) + b.WriteString(contributorNudgeMarker(n.Reason, n.HeadSHA, n.Nudge, out.Mode, n.FailingChecks, n.Attempt)) b.WriteString("\n") if n.Stalled { fmt.Fprintf(&b, "@%s this PR has been waiting on you for a while (`%s`). ", n.Author, stagelabels.ReturnedToContributor.Label()) @@ -232,6 +266,9 @@ func ContributorNudgeComment(n ContributorNudge, out ContributorNudgeOutcome) st for _, c := range n.FailingChecks { fmt.Fprintf(&b, "- `%s`\n", c) } + if n.Attempt > 1 { + fmt.Fprintf(&b, "\nThe same checks have failed on %d heads so far (latest `%s`).\n", n.Attempt, shortSHA(n.HeadSHA)) + } } if len(n.ReviewAsks) > 0 { b.WriteString("**Review asks:**\n") @@ -286,6 +323,12 @@ func nudgeDue(rec stagelabels.Record, head, reason string, repeatAfter time.Dura if rec.NudgeHead != head { return 0, true } + return nudgeRepeatDue(rec, repeatAfter, now) +} + +// nudgeRepeatDue is the same-head, same-class tail of nudgeDue: the one +// repeat reminder once repeatAfter elapsed since the class was counted. +func nudgeRepeatDue(rec stagelabels.Record, repeatAfter time.Duration, now time.Time) (ordinal int, ok bool) { if rec.NudgeReasonCount >= contributorNudgeCap { return 0, false } @@ -295,6 +338,45 @@ func nudgeDue(rec stagelabels.Record, head, reason string, repeatAfter time.Dura return rec.NudgeReasonCount + 1, true } +// ciNudgeDue is nudgeDue for a failing-check reason, keyed on the failing +// set rather than the reason prefix (hivecommons/hive#17328). checks is the +// set the comment would list now (already unioned with the recorded set +// when the head is unchanged). Ordinal 1: the class is new to the PR, or +// the set changed on a new head after cooldown elapsed since the set was +// last counted. Ordinal 0 (a fold into the existing comment, uncounted): +// the same set on a new head, a set that grew on the same head, or a +// changed set on a new head inside the cooldown. Same head and same set +// falls through to the repeat reminder. +func ciNudgeDue(rec stagelabels.Record, head string, checks []string, repeatAfter, cooldown time.Duration, now time.Time) (ordinal int, ok bool) { + if head == "" { + return 0, false + } + if rec.NudgeReason != stagelabels.NudgeReasonCIFailure { + return 1, true + } + sorted := append([]string(nil), checks...) + slices.Sort(sorted) + sameSet := slices.Equal(sorted, rec.NudgeCIChecks) + if rec.NudgeHead == head { + if !sameSet { + return 0, true + } + return nudgeRepeatDue(rec, repeatAfter, now) + } + if sameSet { + return 0, true + } + // Records written before the ledger existed count from the class. + countedAt := rec.NudgeCIAt + if countedAt.IsZero() { + countedAt = rec.NudgeReasonAt + } + if cooldown > 0 && !countedAt.IsZero() && now.Sub(countedAt) < cooldown { + return 0, true + } + return 1, true +} + // nudgeContributor runs the stage-072 nudge for one observation. It returns // the number of GitHub comments posted. func (c *Engine) nudgeContributor(ctx context.Context, store *stagelabels.Store, key string, obs stageObservation, policy StageLabelPolicy, now time.Time) (int, error) { @@ -302,10 +384,6 @@ func (c *Engine) nudgeContributor(ctx context.Context, store *stagelabels.Store, if !ok || obs.Author == "" { return 0, nil } - ordinal, due := nudgeDue(rec, obs.HeadSHA, obs.Reason, policy.RenudgeInterval, now) - if !due { - return 0, nil - } checks, asks, human := nudgeDiagnosisRouted(obs.Reason, obs.Detail, obs.Route) // A fork guard is a maintainer's to clear (hivecommons/hive#14273): the // author is never asked to fix it, and a head red on nothing else is not @@ -318,20 +396,48 @@ func (c *Engine) nudgeContributor(ctx context.Context, store *stagelabels.Store, return 0, nil } } + ciFailure := isCIFailureNudgeReason(obs.Reason) + var ordinal int + var due bool + if ciFailure { + // On one head the failing set only accumulates: the lane's reason + // names whichever red check it saw first, and a set that shrank is + // a flap, not news. + if rec.NudgeReason == stagelabels.NudgeReasonCIFailure && rec.NudgeHead == obs.HeadSHA { + checks = unionChecks(rec.NudgeCIChecks, checks) + } + ordinal, due = ciNudgeDue(rec, obs.HeadSHA, checks, policy.RenudgeInterval, policy.CIFailureCooldown, now) + } else { + ordinal, due = nudgeDue(rec, obs.HeadSHA, obs.Reason, policy.RenudgeInterval, now) + } + if !due { + return 0, nil + } // A head-only rewrite (ordinal 0) keeps the class's recorded count in // the marker; the author pushed, so it is not the stall reminder. shown := ordinal if shown == 0 { shown = max(rec.NudgeReasonCount, 1) } + attempt := 0 + if ciFailure { + attempt = ciNudgeAttempt(rec, obs.HeadSHA, checks, ordinal) + } n := ContributorNudge{ Owner: obs.Owner, Repo: obs.Repo, Display: obs.Display, Number: obs.Number, 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: shown, Stalled: ordinal > 1, + Nudge: shown, Stalled: ordinal > 1, Attempt: attempt, } + // Another check going red on the head the relay already has as a + // fix-pr task is folded into the comment, not dispatched again + // (hivecommons/hive#17328); the recorded delivery mode keeps the + // marker and prose honest. + sameHeadFold := ordinal == 0 && rec.NudgeHead == obs.HeadSHA var out ContributorNudgeOutcome - if c.contributorNudge != nil { + if sameHeadFold { + out = ContributorNudgeOutcome{Mode: rec.NudgeMode, Online: rec.NudgeOnline} + } else if c.contributorNudge != nil { out = c.contributorNudge.Nudge(ctx, n) } body := ContributorNudgeComment(n, out) @@ -359,10 +465,44 @@ func (c *Engine) nudgeContributor(ctx context.Context, store *stagelabels.Store, // as online gave an offline clanker the 2h online grace (#15566). store.MarkNudged(key, obs.HeadSHA, max(ordinal, 1), out.Online || out.Mode == "spawn" || out.Mode == "preempt", now) store.MarkNudgedReason(key, obs.Reason, ordinal, now) + if ciFailure { + store.MarkNudgedCIFailure(key, checks, obs.HeadSHA, nonEmpty(out.Mode, "comment"), attempt, ordinal == 1, now) + } c.info("stage labels: contributor nudged", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "nudge", ordinal, "posted", posted == 1, "mode", nonEmpty(out.Mode, "comment"), "online", out.Online, "queue_depth", out.QueueDepth, "relay_failed", out.RelayFailed, "reason", obs.Reason) return posted, nil } +// ciNudgeAttempt is the attempt count the CI-failure nudge comment shows: +// 1 for a fresh nudge or a changed failing set, one more than recorded +// for the same set on a new head, unchanged otherwise. +func ciNudgeAttempt(rec stagelabels.Record, head string, checks []string, ordinal int) int { + switch { + case ordinal == 1, !slices.Equal(sortedChecks(checks), rec.NudgeCIChecks): + return 1 + case rec.NudgeCIHead != head: + return max(rec.NudgeCIAttempts, 1) + 1 + } + return max(rec.NudgeCIAttempts, 1) +} + +func sortedChecks(checks []string) []string { + out := append([]string(nil), checks...) + slices.Sort(out) + return out +} + +// unionChecks is prev plus the names in cur not already present, in +// prev's order then cur's. +func unionChecks(prev, cur []string) []string { + out := append([]string(nil), prev...) + for _, c := range cur { + if !slices.Contains(out, c) { + out = append(out, c) + } + } + return out +} + // withoutForkGuard drops the fork-guard checks from a nudge's failing // checks; checks is returned unchanged when there is no guard. func withoutForkGuard(checks, guard []string) []string { diff --git a/src/pkg/github/automerge/automerge_contributor_nudge_ci_cooldown_test.go b/src/pkg/github/automerge/automerge_contributor_nudge_ci_cooldown_test.go new file mode 100644 index 0000000000..d3de8719c0 --- /dev/null +++ b/src/pkg/github/automerge/automerge_contributor_nudge_ci_cooldown_test.go @@ -0,0 +1,218 @@ +package automerge + +import ( + "context" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + hgithub "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// newNudgeEngineAt is newNudgeEngine with the stage store at storePath so a +// second engine can be booted on the same file (a restart). +func newNudgeEngineAt(t *testing.T, apiURL, storePath string, clock *contributorLaneClock, sink ContributorNudgeSink, policy StageLabelPolicy) *Engine { + t.Helper() + client := hgithub.NewClient("token", "acme", []string{"widget"}, nil, apiURL) + client.SetAppBotLogin(testHiveAppBotLogin) + store := stagelabels.NewStore(storePath, clock.now) + if err := store.Load(); err != nil { + t.Fatal(err) + } + return New(client, Options{ + Now: clock.now, + StageLabelPolicy: func() StageLabelPolicy { return policy }, + StageTracker: NewStageTracker(), + StageStore: store, + ContributorNudge: sink, + }) +} + +// CI-failure nudges are keyed on the failing-check set (hivecommons/hive#17328): +// the reason prefix flapping between check-failing / optional- / required- +// on one head is one class; a check joining the set on the same head folds +// into the comment without a relay re-dispatch; the same set on a new head +// bumps the attempt count; a changed set on a new head inside the cooldown +// folds, after it counts a fresh nudge. All of it survives a restart. +func TestContributorNudgeCIFailureSetCooldown(t *testing.T) { + api, closeAPI := seededStageAPI(t) + defer closeAPI() + api.statefulComments = true + clock := &contributorLaneClock{at: time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)} + sink := &fakeNudgeSink{outcome: ContributorNudgeOutcome{Mode: "preempt", Online: true}} + policy := StageLabelPolicy{Enabled: true, ContributorNudge: true, RenudgeInterval: 72 * time.Hour, CIFailureCooldown: 6 * time.Hour} + storePath := filepath.Join(t.TempDir(), "stage.json") + e := newNudgeEngineAt(t, apiURLOf(t, api), storePath, clock, sink, policy) + ctx := context.Background() + observe := func(e *Engine, pr *gh.PullRequest, reason string, red ...string) StageLabelResult { + if len(red) > 0 { + e.noteStageRedChecks("acme", "widget", 7, pr.GetHead().GetSHA(), red) + } + e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, reason, false, nil) + e.noteStageRole("acme", "widget", 7, stagelabels.RoleContributor) + res, err := e.ApplyStageLabels(ctx) + if err != nil { + t.Fatal(err) + } + return res + } + lastEdit := func() string { + if len(api.commentEdits) == 0 { + return "" + } + return api.commentEdits[len(api.commentEdits)-1] + } + in072 := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} + key := stageKey("acme", "widget", 7) + + // First red head: one comment, attempt 1, relay dispatched. + res := observe(e, nudgePR(7, "aaa"), "check-failing:changelog-fragment-guard") + if got := nudgeComments(api); len(got) != 1 || res.Comments != 1 { + t.Fatalf("first nudge: res=%+v comments=%v", res, api.comments) + } else if !strings.Contains(got[0], "reason=check-failing head=aaa n=1 mode=preempt checks=") || !strings.Contains(got[0], "attempt=1") { + t.Fatalf("marker: %s", got[0]) + } + if len(sink.nudges) != 1 { + t.Fatalf("sink=%d", len(sink.nudges)) + } + + // Same head, the lane's prefix flips to optional-check-failing and a + // second check is red: same class, the set grows → the comment is + // edited (both checks listed), the relay is NOT dispatched again, the + // class count stays at 1 and the cooldown clock does not move. + api.reset() + clock.advance(4 * time.Minute) + res = observe(e, nudgePR(7, "aaa", in072...), "optional-check-failing:native-queue-policy", "changelog-fragment-guard", "native-queue-policy") + if res.Comments != 0 || len(nudgeComments(api)) != 0 || len(api.commentEdits) != 1 { + t.Fatalf("set grew on same head: res=%+v comments=%v edits=%d", res, api.comments, len(api.commentEdits)) + } + for _, want := range []string{"reason=check-failing head=aaa n=1 mode=preempt", "attempt=1", "`changelog-fragment-guard`", "`native-queue-policy`"} { + if !strings.Contains(lastEdit(), want) { + t.Fatalf("fold missing %q:\n%s", want, lastEdit()) + } + } + if len(sink.nudges) != 1 { + t.Fatalf("relay re-dispatched on the same head: %d", len(sink.nudges)) + } + rec, _ := e.stageStore.Get(key) + if rec.NudgeReasonCount != 1 || !reflect.DeepEqual(rec.NudgeCIChecks, []string{"changelog-fragment-guard", "native-queue-policy"}) || !rec.NudgeCIAt.Equal(clock.at.Add(-4*time.Minute)) { + t.Fatalf("ledger after fold: %+v", rec) + } + + // Same head again, prefix flips back to required- naming one check: + // the set is a subset of what the comment lists → nothing at all. + api.reset() + clock.advance(time.Minute) + observe(e, nudgePR(7, "aaa", in072...), "required-check-failing:changelog-fragment-guard") + if api.writes() != 0 || len(api.commentEdits) != 1 || len(sink.nudges) != 1 { + t.Fatalf("subset flap wrote: comments=%v edits=%d sink=%d", api.comments, len(api.commentEdits), len(sink.nudges)) + } + + // New head, same failing set: edited in place with attempt 2, the + // relay is told (the author pushed), still no new comment. + api.reset() + clock.advance(10 * time.Minute) + res = observe(e, nudgePR(7, "bbb", in072...), "optional-check-failing:changelog-fragment-guard", "changelog-fragment-guard", "native-queue-policy") + if res.Comments != 0 || len(nudgeComments(api)) != 0 || len(api.commentEdits) != 2 || len(sink.nudges) != 2 { + t.Fatalf("same set new head: res=%+v comments=%v edits=%d sink=%d", res, api.comments, len(api.commentEdits), len(sink.nudges)) + } + for _, want := range []string{"head=bbb n=1", "attempt=2", "failed on 2 heads so far (latest `bbb`)"} { + if !strings.Contains(lastEdit(), want) { + t.Fatalf("attempt rewrite missing %q:\n%s", want, lastEdit()) + } + } + + // Restart: a fresh engine on the same store file sees the ledger and + // the same head + set is still nothing. + if err := e.stageStore.Save(); err != nil { + t.Fatal(err) + } + api.reset() + e = newNudgeEngineAt(t, apiURLOf(t, api), storePath, clock, sink, policy) + clock.advance(time.Minute) + observe(e, nudgePR(7, "bbb", in072...), "check-failing:native-queue-policy") + if api.writes() != 0 || len(api.commentEdits) != 2 || len(sink.nudges) != 2 { + t.Fatalf("restart re-nudged: comments=%v edits=%d sink=%d", api.comments, len(api.commentEdits), len(sink.nudges)) + } + rec, _ = e.stageStore.Get(key) + if rec.NudgeCIAttempts != 2 || rec.NudgeCIHead != "bbb" || rec.NudgeMode != "preempt" { + t.Fatalf("ledger not persisted: %+v", rec) + } + + // New head, a different failing set, 15 minutes into the 6h cooldown: + // folded into the comment (attempt restarts at 1 for the new set) and + // the class count does not restart. + api.reset() + res = observe(e, nudgePR(7, "ccc", in072...), "check-failing:lint") + if res.Comments != 0 || len(nudgeComments(api)) != 0 || len(api.commentEdits) != 3 || len(sink.nudges) != 3 { + t.Fatalf("changed set inside cooldown: res=%+v comments=%v edits=%d sink=%d", res, api.comments, len(api.commentEdits), len(sink.nudges)) + } + if !strings.Contains(lastEdit(), "head=ccc n=1") || !strings.Contains(lastEdit(), "attempt=1") || !strings.Contains(lastEdit(), "`lint`") || strings.Contains(lastEdit(), "native-queue-policy") { + t.Fatalf("fold rewrite:\n%s", lastEdit()) + } + rec, _ = e.stageStore.Get(key) + if rec.NudgeReasonCount != 1 || !rec.NudgeCIAt.Equal(time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)) || !reflect.DeepEqual(rec.NudgeCIChecks, []string{"lint"}) { + t.Fatalf("ledger after cooldown fold: %+v", rec) + } + + // Past the cooldown, yet another set on a new head: a fresh nudge + // (count restarts, cooldown clock moves) — still the one comment. + api.reset() + clock.advance(7 * time.Hour) + res = observe(e, nudgePR(7, "ddd", in072...), "check-failing:vet") + if res.Comments != 0 || len(nudgeComments(api)) != 0 || len(api.commentEdits) != 4 || len(sink.nudges) != 4 || sink.nudges[3].Nudge != 1 { + t.Fatalf("changed set after cooldown: res=%+v comments=%v edits=%d sink=%+v", res, api.comments, len(api.commentEdits), sink.nudges) + } + rec, _ = e.stageStore.Get(key) + if rec.NudgeReasonCount != 1 || !rec.NudgeCIAt.Equal(clock.at) || rec.NudgeCIAttempts != 1 { + t.Fatalf("ledger after fresh nudge: %+v", rec) + } + if len(api.comments) != 0 { + t.Fatalf("a second nudge comment was posted: %v", api.comments) + } +} + +func TestCINudgeDue(t *testing.T) { + now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) + rec := stagelabels.Record{NudgeHead: "a", NudgeReason: stagelabels.NudgeReasonCIFailure, NudgeReasonCount: 1, NudgeReasonAt: now.Add(-time.Hour), NudgeCIChecks: []string{"lint", "unit"}, NudgeCIAt: now.Add(-time.Hour)} + legacy := stagelabels.Record{NudgeHead: "a", NudgeReason: stagelabels.NudgeReasonCIFailure, NudgeReasonCount: 1, NudgeReasonAt: now.Add(-time.Hour)} + cases := []struct { + name string + rec stagelabels.Record + head string + checks []string + cooldown time.Duration + ordinal int + ok bool + }{ + {name: "empty head", rec: rec, head: "", checks: []string{"unit"}, cooldown: 6 * time.Hour}, + {name: "new class", rec: stagelabels.Record{NudgeReason: "conflicting"}, head: "a", checks: []string{"unit"}, cooldown: 6 * time.Hour, ordinal: 1, ok: true}, + {name: "same head same set inside repeat window", rec: rec, head: "a", checks: []string{"unit", "lint"}, cooldown: 6 * time.Hour}, + {name: "same head set changed folds", rec: rec, head: "a", checks: []string{"unit", "lint", "vet"}, cooldown: 6 * time.Hour, ordinal: 0, ok: true}, + {name: "new head same set folds", rec: rec, head: "b", checks: []string{"lint", "unit"}, cooldown: 6 * time.Hour, ordinal: 0, ok: true}, + {name: "new head changed set inside cooldown folds", rec: rec, head: "b", checks: []string{"vet"}, cooldown: 6 * time.Hour, ordinal: 0, ok: true}, + {name: "new head changed set after cooldown counts", rec: rec, head: "b", checks: []string{"vet"}, cooldown: 30 * time.Minute, ordinal: 1, ok: true}, + {name: "zero cooldown counts", rec: rec, head: "b", checks: []string{"vet"}, cooldown: 0, ordinal: 1, ok: true}, + {name: "legacy record counts from the class", rec: legacy, head: "b", checks: []string{"vet"}, cooldown: 6 * time.Hour, ordinal: 0, ok: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + n, ok := ciNudgeDue(tc.rec, tc.head, tc.checks, 72*time.Hour, tc.cooldown, now) + if n != tc.ordinal || ok != tc.ok { + t.Fatalf("ciNudgeDue = (%d, %v), want (%d, %v)", n, ok, tc.ordinal, tc.ok) + } + }) + } + if ciFailureSetDigest([]string{"unit", "lint"}) != ciFailureSetDigest([]string{"lint", "unit"}) || len(ciFailureSetDigest([]string{"unit"})) != 12 { + t.Fatal("digest must be order-independent and 12 hex chars") + } + for in, want := range map[string]bool{"check-failing:unit": true, "optional-check-failing:links": true, "required-check-failing:lint": true, "conflicting": false, "status-failure": false} { + if got := isCIFailureNudgeReason(in); got != want { + t.Errorf("isCIFailureNudgeReason(%q) = %v", in, got) + } + } +} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index be53f3d364..999500dcc4 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -56,6 +56,12 @@ type StageLabelPolicy struct { // class that persists (auto_merge.nudge_repeat_after, default 72h); // 0 never re-nudges. RenudgeInterval time.Duration + // CIFailureCooldown is how long after a counted CI-failure nudge a + // changed failing set on a new head folds into the existing comment + // instead of counting as a fresh nudge + // (governor.labels.stage.contributor_nudge.ci_failure_cooldown, + // default 6h; hivecommons/hive#17328). 0 disables the fold. + CIFailureCooldown time.Duration // Adoption turns the stage-074 adoption on // (governor.labels.stage.adoption.enabled, default true): a contributor // PR still red after the grace is superseded by an App PR that preserves diff --git a/src/pkg/stagelabels/stagelabels_test.go b/src/pkg/stagelabels/stagelabels_test.go index 860a714f2a..a193ef95ba 100644 --- a/src/pkg/stagelabels/stagelabels_test.go +++ b/src/pkg/stagelabels/stagelabels_test.go @@ -651,6 +651,7 @@ func TestNudgeReasonSlug(t *testing.T) { " ": "unknown", "check-failing:unit (lint)": "check-failing", "required-check-failing:unit": "check-failing", + "optional-check-failing:links": "check-failing", "Changes Requested by @Reviewer": "changes-requested-by--reviewer", "--merge_conflict.v2--": "merge_conflict.v2", "(only parenthetical)": "unknown", @@ -1828,3 +1829,26 @@ func TestTransitionDampenerExpiresAfterWindow(t *testing.T) { t.Fatalf("move after window expiry must be allowed: %+v", tr) } } + +func TestStoreMarkNudgedCIFailure(t *testing.T) { + now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) + s := NewStore("", func() time.Time { return now }) + s.MarkNudgedCIFailure("missing", []string{"unit"}, "a", "spawn", 1, true, now) // unknown key: no-op + if _, ok := s.Get("missing"); ok { + t.Fatal("MarkNudgedCIFailure created a record") + } + key := Key("acme/widget", 7) + s.Observe(key, ReturnedToContributor, "check-failing:unit") + s.MarkNudgedCIFailure(key, []string{"unit", "lint"}, "a", "spawn", 1, true, now) + r, _ := s.Get(key) + if !reflect.DeepEqual(r.NudgeCIChecks, []string{"lint", "unit"}) || r.NudgeCIHead != "a" || r.NudgeCIAttempts != 1 || r.NudgeMode != "spawn" || !r.NudgeCIAt.Equal(now) { + t.Fatalf("after first: %+v", r) + } + // A fold (not counted) moves the set, head and attempt but keeps the + // cooldown clock and, with no mode given, the recorded mode. + s.MarkNudgedCIFailure(key, []string{"lint", "unit", "vet"}, "b", "", 2, false, now.Add(time.Hour)) + r, _ = s.Get(key) + if !reflect.DeepEqual(r.NudgeCIChecks, []string{"lint", "unit", "vet"}) || r.NudgeCIHead != "b" || r.NudgeCIAttempts != 2 || r.NudgeMode != "spawn" || !r.NudgeCIAt.Equal(now) { + t.Fatalf("after fold: %+v", r) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index eb977c542d..ed411b478d 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -92,6 +92,18 @@ type Record struct { NudgeReason string `json:"nudge_reason,omitempty"` NudgeReasonCount int `json:"nudge_reason_count,omitempty"` NudgeReasonAt time.Time `json:"nudge_reason_at,omitempty"` + // NudgeCIChecks, NudgeCIHead, NudgeCIAt, NudgeCIAttempts and NudgeMode + // are the CI-failure nudge ledger (hivecommons/hive#17328): the sorted + // failing check names the one nudge comment currently lists, the head + // they were last seen on, when that set was last counted as a nudge + // (the ci_failure_cooldown clock), how many red heads the set has been + // seen on since, and the relay delivery mode of the last dispatch + // (reused by a same-head rewrite that does not re-dispatch). + NudgeCIChecks []string `json:"nudge_ci_checks,omitempty"` + NudgeCIHead string `json:"nudge_ci_head,omitempty"` + NudgeCIAt time.Time `json:"nudge_ci_at,omitempty"` + NudgeCIAttempts int `json:"nudge_ci_attempts,omitempty"` + NudgeMode string `json:"nudge_mode,omitempty"` // AdoptedHead / AdoptedBy / AdoptedAt record the stage-074 adoption: the // contributor head the hive adopted, the superseding App PR's number // (0 while the attempt is recorded but no PR exists) and when. One @@ -1463,9 +1475,15 @@ func (s *Store) MarkNudgedReason(key, reason string, n int, now time.Time) { // NudgeReasonSlug is the marker-safe reason class a contributor nudge is // keyed by: MentionCauseClass (so every red check is one "check-failing" // ask), lower-cased, with anything outside [a-z0-9._-] folded to '-'; -// an empty reason is "unknown". +// an empty reason is "unknown". Every CI-failure prefix (required-, +// optional-, plain check-failing) is the one NudgeReasonCIFailure class +// (hivecommons/hive#17328): the lane's prefix flaps between them as checks +// finish, and each flip used to count as a new class. func NudgeReasonSlug(reason string) string { class := strings.ToLower(MentionCauseClass(reason)) + if class == "optional-check-failing" { + class = NudgeReasonCIFailure + } var b strings.Builder for _, r := range class { switch { @@ -1482,6 +1500,37 @@ func NudgeReasonSlug(reason string) string { return slug } +// NudgeReasonCIFailure is the NudgeReasonSlug of every CI-failure reason. +const NudgeReasonCIFailure = "check-failing" + +// MarkNudgedCIFailure records the CI-failure nudge ledger after a nudge for +// the check-failing class: checks is the failing set the comment now lists +// (stored sorted), head the red head it was seen on, mode the relay +// delivery mode, attempt the count the comment shows, and counted whether +// this nudge started a new cooldown window (a fresh nudge, not a fold into +// the existing comment). +func (s *Store) MarkNudgedCIFailure(key string, checks []string, head, mode string, attempt int, counted bool, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok { + return + } + sorted := append([]string(nil), checks...) + slices.Sort(sorted) + if counted { + r.NudgeCIAt = now + } + r.NudgeCIChecks = sorted + r.NudgeCIHead = head + r.NudgeCIAttempts = attempt + if strings.TrimSpace(mode) != "" { + r.NudgeMode = mode + } + s.items[key] = r + s.dirty = true +} + // Adoption modes (Record.AdoptMode). const ( AdoptModeSupersede = "supersede" From 57cbd1b0967a65ae42acf1541087e4710ef1b924 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sun, 8 Nov 2026 19:04:21 -0700 Subject: [PATCH 2/2] test(config): golden gains contributor_nudge.ci_failure_cooldown Signed-off-by: Andrew Anderson --- src/pkg/config/testdata/agent_runtime_golden.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index b5201ad0d5..7c9d594606 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -194,7 +194,8 @@ "Dwell": null, "ContributorNudge": { "Enabled": null, - "RenudgeInterval": "" + "RenudgeInterval": "", + "CIFailureCooldown": "" }, "PresenceWindow": "", "ContributorGraceOnline": "",