From 427917c8ba39c531ecfa5b2c5ceea87ffd5ad02e Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 14:04:18 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=8C=B1=20contributor-nudge=20once=20p?= =?UTF-8?q?er=20PR+reason;=20fold=20origin=20notes=20into=20status;=20mark?= =?UTF-8?q?er=20ratchet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Contributor nudges carry a hive:contributor-nudge reason= marker and are edited in place for a new head or changed reason, with one re-nudge after auto_merge.nudge_repeat_after (default 72h). Agent free-text relay comments whose only marker is the hive:origin footer fold into the hive:status card in quiet mode or one hive:origin-notes comment per item otherwise. A grep-based ratchet in internal/testutil caps unmarked raw comment emitters under pkg/github at the current 45. Fixes #17067 Signed-off-by: Andrew Anderson --- .../changed-contributor-nudge-dedupe.md | 1 + src/cmd/hive/merge_eligibility.go | 13 +- src/docs/hive-merge.md | 10 +- .../stage-labels.md | 17 +- src/docs/notifications.md | 6 +- src/docs/operator-reference/README.md | 1 + .../sweeps-and-operations.md | 7 +- .../testutil/comment_marker_ratchet_test.go | 249 ++++++++++++++++++ src/pkg/config/config.go | 22 +- src/pkg/github/attribution.go | 28 ++ .../automerge/automerge_contributor_nudge.go | 109 +++++--- .../automerge_contributor_nudge_test.go | 152 ++++++++--- .../automerge/automerge_stage_labels.go | 5 +- src/pkg/github/issue_request_watcher.go | 9 + src/pkg/github/origin_notes.go | 78 ++++++ src/pkg/github/origin_notes_test.go | 136 ++++++++++ src/pkg/stagelabels/store.go | 55 ++++ 17 files changed, 806 insertions(+), 92 deletions(-) create mode 100644 changelog.d/changed-contributor-nudge-dedupe.md create mode 100644 src/internal/testutil/comment_marker_ratchet_test.go create mode 100644 src/pkg/github/origin_notes.go create mode 100644 src/pkg/github/origin_notes_test.go diff --git a/changelog.d/changed-contributor-nudge-dedupe.md b/changelog.d/changed-contributor-nudge-dedupe.md new file mode 100644 index 0000000000..3d5e879937 --- /dev/null +++ b/changelog.d/changed-contributor-nudge-dedupe.md @@ -0,0 +1 @@ +- Contributor nudges are now one comment per PR and reason class, edited in place for a new head or changed reason, with a single re-nudge after `auto_merge.nudge_repeat_after` (default 72h); an agent's free-text relay comments fold into the `hive:status` card in quiet mode or one `hive:origin-notes` comment per item otherwise; a marker ratchet test caps unmarked bot comment emitters (hivecommons/hive#17067). diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index a3512f8f8c..c8bfc424eb 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -114,7 +114,7 @@ func stageLabelPolicyFunc(cfg *config.Config) func() automerge.StageLabelPolicy Dwell: stage.DwellOverrides(), StalledRequireQuiet: stage.Stalled.IsRequireQuiet(), ContributorNudge: stage.ContributorNudge.IsEnabled(), - RenudgeInterval: stage.ContributorNudge.EffectiveRenudgeInterval(), + RenudgeInterval: nudgeRepeatAfter(cfg), Adoption: stage.Adoption.IsEnabled(), GraceOnline: stage.EffectiveContributorGraceOnline(), GraceOffline: stage.EffectiveContributorGraceOffline(), @@ -1415,3 +1415,14 @@ func normalizedAutoMergeLabel(label string) string { } return github.AutoMergeQueuedLabel } + +// nudgeRepeatAfter is the delay before the one contributor re-nudge: +// governor.labels.stage.contributor_nudge.renudge_interval when set, +// otherwise auto_merge.nudge_repeat_after (default 72h, +// hivecommons/hive#17067). +func nudgeRepeatAfter(cfg *config.Config) time.Duration { + if d := cfg.Governor.Labels.Stage.ContributorNudge.EffectiveRenudgeInterval(); d > 0 { + return d + } + return cfg.AutoMerge.EffectiveNudgeRepeatAfter() +} diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index d56f26b65d..b9c9613238 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -1236,10 +1236,12 @@ when the copy is closed without merging (`adopted_by_state` closed / closed-twice / copy-failed). A clanker PR entering `stage/072-returned-to-contributor` also triggers the -contributor nudge: the sweep posts one `` comment per head naming the failing checks / review asks (re-nudged -once at the stall threshold, cap 2) and hands the diagnosis to the contribute -hub, which — when the author's relay heartbeat is fresh — pushes a `fix-pr` +contributor nudge: the sweep keeps one `` comment per PR and reason class naming the failing +checks / review asks — a changed reason or new head edits that comment in +place; one re-nudge after `auto_merge.nudge_repeat_after` (default 72h) if +the condition persists, then no more — and hands the diagnosis to the +contribute hub, which — when the author's relay heartbeat is fresh — pushes a `fix-pr` interrupt task into their relay session (parallel sub-session or preempt, per the relay's declared capability) under a per-contributor fix budget; queued fixes are served before new work ("contributors should clean up their diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index 54052572a9..ce14b53f04 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -750,13 +750,16 @@ When a contributor-agent PR goes red the hive does not just relabel it (a human- [hive-merge.md](../hive-merge.md#stage-labels)): 1. `stage/072-returned-to-contributor` and ONE `` comment - @-mentioning the author with the failing checks / review asks and "reply - here or push a new head". Re-posted only for a new head; re-nudged once - more after `governor.labels.stage.contributor_nudge.renudge_interval` - (default = the stage's 24h dwell, i.e. at `stage/stalled`), then no more - — **cap: 2 nudges per head**. `mode=` records how the relay side was - handled so the comment itself answers "did their agent get interrupted?". + reason= head= n=<1|2> mode= -->` + comment per PR and reason class @-mentioning the author with the failing + checks / review asks and "reply here or push a new head". A new head or a + changed reason **edits** that comment in place (no notification) rather + than posting another; re-nudged once more after + `governor.labels.stage.contributor_nudge.renudge_interval` (default = + `auto_merge.nudge_repeat_after`, 72h) if the same condition persists, + then no more — **cap: 2 nudges per PR + reason**. `mode=` records how + the relay side was handled so the comment itself answers "did their + agent get interrupted?". `governor.labels.stage.contributor_nudge.enabled: false` turns the comment and the relay task off; the stage label still moves. 2. Relay contributors (the author has a contributor profile and a live relay diff --git a/src/docs/notifications.md b/src/docs/notifications.md index af7fd425cb..ec1b219282 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -584,7 +584,11 @@ issue gets the same card, written through the same single status writer reopened-after-merge (`issue-reopened`), a lapsed claim's stage regression (`stage-regressed`), the covering-PR stage note (`issue-pr-link`), the relay's one-line state notes — awaiting CI, parking, already fixed — - (`agent-note:`), the decision-downgrade note left when a label + (`agent-note:`), an agent's free-text relay comment whose only + marker is the identity footer's `` + (`agent-note:origin`, latest note; outside quiet mode these append to the + one `` comment per item instead, last 10 kept — + hivecommons/hive#17067), the decision-downgrade note left when a label change walks back an earlier maintainer decision (`issue-decision-downgrade`) and the blocker-settled note (`unblocked`, whatever `mode` says). Claim notes and the relay state notes already fold diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 4528369000..7cefa7e322 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -470,6 +470,7 @@ advanced into the merge path. | `auto_merge.self_authored` | **on** when unset | The only off switch. `false` disables the sweep and App-authored PRs fall back to fully manual merges. | | `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. | | `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/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index 984ee983bc..1e9a7b8b2a 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -89,9 +89,10 @@ on; `governor.labels.stage.enabled: false` stops the reconciler, `governor.labels.stage.stalled.require_quiet: false` measures the dwell from stage entry instead of last activity (Settings → Labels). When a clanker PR enters -`stage/072-returned-to-contributor` the hive posts one nudge comment per head -(re-nudged once after `governor.labels.stage.contributor_nudge.renudge_interval`, -default = the 24h dwell; cap 2) and, for a contributor whose relay heartbeat is +`stage/072-returned-to-contributor` the hive keeps one nudge comment per PR +and reason class, edited in place for a new head or changed reason (re-nudged +once after `governor.labels.stage.contributor_nudge.renudge_interval`, +default = `auto_merge.nudge_repeat_after`, 72h; cap 2 per reason) and, for a contributor whose relay heartbeat is within `governor.labels.stage.presence_window` (default 15m), pushes a `fix-pr` interrupt to their relay session, bounded by the per-contributor fix budget (`contribute.max_parallel_fixes` / `contribute.min_focus_window`). diff --git a/src/internal/testutil/comment_marker_ratchet_test.go b/src/internal/testutil/comment_marker_ratchet_test.go new file mode 100644 index 0000000000..4b1ceffb08 --- /dev/null +++ b/src/internal/testutil/comment_marker_ratchet_test.go @@ -0,0 +1,249 @@ +package testutil + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" +) + +// commentMarkerBaseline is the number of functions under src/pkg/github +// (including automerge) that post an issue/PR comment through a raw create +// call without any idempotence marker in sight, at the commit that +// introduced this ratchet (hivecommons/hive#17067), measured with the same +// rules TestCommentMarkerRatchet uses. +// +// It is a ratchet, not a target: lower this constant when you convert an +// emitter — to a `` marker with EditIssueMarkerComment / +// findOwnEntryComment, or to a prstatus section — but it must never go UP. +// Every unmarked emitter is a comment the hive can post again on the next +// sweep; the 2026-11-07 spam audit traced 30–46 such comments a day to them. +const commentMarkerBaseline = 45 + +// commentEmitterCalls are the raw comment-create calls the ratchet looks +// for. Marker-aware helpers (EditIssueMarkerComment, UpsertPRStatusSection, +// PostNoteOrFold) are built on these and are what new code should call. +var commentEmitterCalls = []string{ + ".Issues.CreateComment(", + ".CreateIssueComment(", + ".CreateIssueCommentBudgeted(", +} + +// commentMarkerEvidence: a function containing any of these is treated as +// marker-aware — it carries a `` marker and edit in place "+ + "(EditIssueMarkerComment / findOwnEntryComment) or write a prstatus section (UpsertPRStatusSection). "+ + "If this is a deliberate one-shot, convert another emitter so the total does not grow.\n%s", + total, len(marked), commentMarkerBaseline, listEmitters(counted)) + case total < commentMarkerBaseline: + t.Logf("%d unmarked emitters, below the baseline of %d — lower commentMarkerBaseline in "+ + "internal/testutil/comment_marker_ratchet_test.go to %d so the ratchet keeps biting", + total, commentMarkerBaseline, total) + } +} + +func listEmitters(ids []string) string { + var b strings.Builder + b.WriteString("unmarked emitters:\n") + for _, id := range ids { + fmt.Fprintf(&b, " %s\n", id) + } + return b.String() +} + +// The scanner's rules on synthetic sources: a raw create with no marker +// counts, marker evidence in the same function clears it, a commented-out +// call is not a call, and a receiver method is named Recv.Func. +func TestCommentEmittersRules(t *testing.T) { + tests := []struct { + name string + src string + wantMarked []string + wantUnmarked []string + }{ + { + name: "raw create without marker", + src: "package x\n\nfunc (c *Client) note() {\n\tc.CreateIssueComment(ctx, repo, n, body)\n}\n", + wantUnmarked: []string{"f.go:Client.note"}, + }, + { + name: "marker literal in function", + src: "package x\n\nfunc (c *Client) note() {\n\tbody := \"\" + s\n\tc.CreateIssueCommentBudgeted(ctx, repo, n, body)\n}\n", + wantMarked: []string{"f.go:Client.note"}, + }, + { + name: "prstatus writer", + src: "package x\n\nfunc post() {\n\tprstatus.Write(ctx, f, k, key, text)\n\tf.c.client.Issues.CreateComment(ctx, o, r, n, cm)\n}\n", + wantMarked: []string{"f.go:post"}, + }, + { + name: "commented-out call is not an emitter", + src: "package x\n\nfunc (c *Client) note() {\n\t// c.CreateIssueComment(ctx, repo, n, body)\n}\n", + }, + { + name: "two functions, one marked", + src: "package x\n\nfunc a() {\n\tc.CreateIssueComment(ctx, repo, n, body)\n}\n\nfunc b() {\n\tif marker != \"\" {\n\t\tc.CreateIssueComment(ctx, repo, n, body)\n\t}\n}\n", + wantMarked: []string{"f.go:b"}, + wantUnmarked: []string{"f.go:a"}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + marked, unmarked := commentEmitters("f.go", tc.src) + if strings.Join(marked, ",") != strings.Join(tc.wantMarked, ",") { + t.Errorf("marked = %v, want %v", marked, tc.wantMarked) + } + if strings.Join(unmarked, ",") != strings.Join(tc.wantUnmarked, ",") { + t.Errorf("unmarked = %v, want %v", unmarked, tc.wantUnmarked) + } + }) + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 85a446d85d..5053be3f10 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -3169,8 +3169,8 @@ type ContributorNudgeConfig struct { // Enabled turns the nudge on. nil = true. Enabled *bool `yaml:"enabled"` // RenudgeInterval is how long after the first nudge the hive nudges once - // more (the documented cap is 2 nudges per head). Default: the stage's - // dwell (24h), i.e. the re-nudge coincides with stage/stalled. + // 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"` } @@ -3181,7 +3181,7 @@ func (c ContributorNudgeConfig) IsEnabled() bool { return c.Enabled == nil || *c const DefaultPresenceWindow = 15 * time.Minute // EffectiveRenudgeInterval parses RenudgeInterval; unset/invalid returns 0 -// (the caller falls back to the stage dwell). +// (the caller falls back to auto_merge.nudge_repeat_after). func (c ContributorNudgeConfig) EffectiveRenudgeInterval() time.Duration { return parseDurationOr(c.RenudgeInterval, 0) } @@ -8319,6 +8319,13 @@ type AutoMergeConfig struct { // GitHub Actions check-runs have not registered yet. Non-positive values // use DefaultAutoMergeMinHeadAge. MinHeadAge time.Duration `yaml:"min_head_age,omitempty" json:"min_head_age,omitempty"` + // NudgeRepeatAfter is how long a contributor PR must stay red for the + // same reason class before the hive rewrites its one + // `hive:contributor-nudge` comment a second (and last) time + // (hivecommons/hive#17067). Default DefaultNudgeRepeatAfter (72h); + // governor.labels.stage.contributor_nudge.renudge_interval, when set, + // takes precedence for backwards compatibility. + NudgeRepeatAfter string `yaml:"nudge_repeat_after,omitempty" json:"nudge_repeat_after,omitempty"` // RequiredChecks is the default operator-declared list of status-check // contexts/check-run names that the self-merge sweep's commitGreen must // gate on for repos without an auto_merge.repos..required_checks @@ -8605,6 +8612,15 @@ func (m MergeTrainAutoMergeConfig) EffectiveMaxRebaseAttempts() int { return m.MaxRebaseAttempts } +// DefaultNudgeRepeatAfter is auto_merge.nudge_repeat_after's default: a +// contributor PR red for the same reason class is re-nudged once after 72h. +const DefaultNudgeRepeatAfter = 72 * time.Hour + +// EffectiveNudgeRepeatAfter parses NudgeRepeatAfter (default 72h). +func (a AutoMergeConfig) EffectiveNudgeRepeatAfter() time.Duration { + return parseDurationOr(a.NudgeRepeatAfter, DefaultNudgeRepeatAfter) +} + // CreditIssueAuthorsEnabled reports the auto_merge.credit_issue_authors // switch; unset is on. func (a AutoMergeConfig) CreditIssueAuthorsEnabled() bool { diff --git a/src/pkg/github/attribution.go b/src/pkg/github/attribution.go index 0d9e9a0c4c..2c0a457215 100644 --- a/src/pkg/github/attribution.go +++ b/src/pkg/github/attribution.go @@ -344,6 +344,34 @@ func HasAttributionTrailer(body string) bool { // footer may end with the origin marker (``, #12539). var attributionIdentityFooter = regexp.MustCompile("\\n[ \\t]*---[ \\t]*\\n🐝 \\*\\*Hive Agent\\*\\*:(?: `[^`\\n]+`)?(?: \\| \\*\\*Instance:\\*\\* `[^`\\n]+`)? \\| \\*\\*SHA:\\*\\* `[^`\\n]+`[ \\t]*(?:\\n[ \\t]*)?[ \\t\\n]*$") +// OriginFooterNote reports whether body is an agent's free-text note whose +// only machine marker is the identity footer's `` +// (hivecommons/hive#17067): the footer is present and carries the origin +// marker, and no other `", ContributorNudgeMarkerPrefix, stagelabels.NudgeReasonSlug(reason), head, nudge, nonEmpty(mode, "comment")) +} + // ContributorNudge is the diagnosis handed to the sink for one PR in stage 072. type ContributorNudge struct { Owner, Repo string @@ -53,9 +69,11 @@ type ContributorNudge struct { // HumanChangesRequested is true when a human reviewer asked for changes // (outranks CI-red in the contributor's fix queue). HumanChangesRequested bool - // Nudge is 1 for the first nudge at this head, 2 for the stall re-nudge. + // Nudge is 1 for the first nudge for this reason class, 2 for the + // repeat re-nudge, and 0 for a head-only rewrite of the existing + // comment (the class is unchanged and already counted). Nudge int - // Stalled is true when this nudge is the stall re-nudge. + // Stalled is true when this nudge is the repeat re-nudge. Stalled bool } @@ -196,11 +214,13 @@ func nudgeDiagnosisRouted(reason string, d stageDetail, route *stagelabels.Route } // ContributorNudgeComment renders the nudge comment. The marker carries the -// head, the nudge ordinal and the delivery mode so a later pass can prove the -// comment exists without a per-PR GET. +// reason class, the head, the nudge ordinal and the delivery mode so a later +// pass can prove the comment exists and what it explains without parsing +// the prose. func ContributorNudgeComment(n ContributorNudge, out ContributorNudgeOutcome) string { var b strings.Builder - fmt.Fprintf(&b, "%s head=%s n=%d mode=%s -->\n", ContributorNudgeMarkerPrefix, n.HeadSHA, n.Nudge, nonEmpty(out.Mode, "comment")) + b.WriteString(ContributorNudgeMarker(n.Reason, n.HeadSHA, n.Nudge, out.Mode)) + 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()) } else { @@ -249,23 +269,30 @@ func nonEmpty(s, def string) string { return s } -// nudgeDue decides whether a nudge is owed for the record at this head: the -// first on entering 072 with a new head, the second once renudge elapsed -// (the stall threshold), never a third. -func nudgeDue(rec stagelabels.Record, head string, renudge time.Duration, now time.Time) (ordinal int, ok bool) { +// nudgeDue decides whether the nudge comment is owed a write for the record +// at this head and reason: ordinal 1 when the reason class is new to the PR +// (first nudge, or a changed reason rewriting the comment), 0 when a new +// head is red for the class already explained (rewrite only, uncounted), +// 2 once repeatAfter elapsed since the class was last counted — never a +// third. Same head, same class, inside the window: nothing. +func nudgeDue(rec stagelabels.Record, head, reason string, repeatAfter time.Duration, now time.Time) (ordinal int, ok bool) { if head == "" { return 0, false } - if rec.NudgeHead != head { + slug := stagelabels.NudgeReasonSlug(reason) + if rec.NudgeReason != slug { return 1, true } - if rec.NudgeCount >= contributorNudgeCap { + if rec.NudgeHead != head { + return 0, true + } + if rec.NudgeReasonCount >= contributorNudgeCap { return 0, false } - if renudge <= 0 || rec.LastNudgeAt.IsZero() || now.Sub(rec.LastNudgeAt) < renudge { + if repeatAfter <= 0 || rec.NudgeReasonAt.IsZero() || now.Sub(rec.NudgeReasonAt) < repeatAfter { return 0, false } - return rec.NudgeCount + 1, true + return rec.NudgeReasonCount + 1, true } // nudgeContributor runs the stage-072 nudge for one observation. It returns @@ -275,11 +302,7 @@ func (c *Engine) nudgeContributor(ctx context.Context, store *stagelabels.Store, if !ok || obs.Author == "" { return 0, nil } - renudge := policy.RenudgeInterval - if renudge <= 0 { - renudge = stagelabels.Dwell(stagelabels.ReturnedToContributor, policy.Dwell) - } - ordinal, due := nudgeDue(rec, obs.HeadSHA, renudge, now) + ordinal, due := nudgeDue(rec, obs.HeadSHA, obs.Reason, policy.RenudgeInterval, now) if !due { return 0, nil } @@ -295,27 +318,49 @@ func (c *Engine) nudgeContributor(ctx context.Context, store *stagelabels.Store, 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) + } 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: ordinal, Stalled: ordinal > 1, + Nudge: shown, Stalled: ordinal > 1, } var out ContributorNudgeOutcome if c.contributorNudge != nil { out = c.contributorNudge.Nudge(ctx, n) } body := ContributorNudgeComment(n, out) - if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { - c.warn("stage labels: contributor nudge failed", "repo", obs.Display, "pr", obs.Number, "error", err) - return 0, err + // One nudge comment per PR (hivecommons/hive#17067): the hive's + // existing comment carrying the marker is rewritten for a new head or + // a changed reason; an edit notifies nobody, the relay dispatch above + // is the interrupt. + posted := 0 + if existing := c.findOwnEntryComment(ctx, obs, ContributorNudgeMarkerPrefix); existing != nil { + if existing.GetBody() != body { + if _, _, err := c.gh.Issues.EditComment(ctx, obs.Owner, obs.Repo, existing.GetID(), &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + c.warn("stage labels: contributor nudge edit failed", "repo", obs.Display, "pr", obs.Number, "error", err) + return 0, err + } + } + } else { + if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + c.warn("stage labels: contributor nudge failed", "repo", obs.Display, "pr", obs.Number, "error", err) + return 0, err + } + posted = 1 } // "queued" only says the author has a relay registered here; the work // sits in its queue whether or not that relay is connected. Counting it // as online gave an offline clanker the 2h online grace (#15566). - store.MarkNudged(key, obs.HeadSHA, ordinal, out.Online || out.Mode == "spawn" || out.Mode == "preempt", now) - c.info("stage labels: contributor nudged", "repo", obs.Display, "pr", obs.Number, "author", obs.Author, "head", obs.HeadSHA, "nudge", ordinal, "mode", nonEmpty(out.Mode, "comment"), "online", out.Online, "queue_depth", out.QueueDepth, "relay_failed", out.RelayFailed, "reason", obs.Reason) - return 1, nil + store.MarkNudged(key, obs.HeadSHA, max(ordinal, 1), out.Online || out.Mode == "spawn" || out.Mode == "preempt", now) + store.MarkNudgedReason(key, obs.Reason, ordinal, 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 } // withoutForkGuard drops the fork-guard checks from a nudge's failing diff --git a/src/pkg/github/automerge/automerge_contributor_nudge_test.go b/src/pkg/github/automerge/automerge_contributor_nudge_test.go index 7743f254f0..77126a87b8 100644 --- a/src/pkg/github/automerge/automerge_contributor_nudge_test.go +++ b/src/pkg/github/automerge/automerge_contributor_nudge_test.go @@ -105,14 +105,18 @@ func nudgeComments(api *stageAPI) []string { return out } -// One nudge per head on entering 072, a second at the stall threshold, never -// a third; a new head re-arms; leaving 072 resolves the sink entry. -func TestContributorNudgeOncePerHeadThenAtStall(t *testing.T) { +// One nudge comment per PR (hivecommons/hive#17067): posted on entering 072, +// rewritten in place for a new head red for the same reason class and for a +// changed class, rewritten once more as the repeat reminder after +// RenudgeInterval, never a third time for the same class; leaving 072 +// resolves the sink entry. +func TestContributorNudgeOncePerPRAndReason(t *testing.T) { api, closeAPI := seededStageAPI(t) defer closeAPI() + api.statefulComments = true clock := &contributorLaneClock{at: time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC)} sink := &fakeNudgeSink{outcome: ContributorNudgeOutcome{Mode: "spawn", Online: true}} - e := newNudgeEngine(t, apiURLOf(t, api), clock, sink, StageLabelPolicy{Enabled: true, ContributorNudge: true}) + e := newNudgeEngine(t, apiURLOf(t, api), clock, sink, StageLabelPolicy{Enabled: true, ContributorNudge: true, RenudgeInterval: 72 * time.Hour}) ctx := context.Background() observe := func(pr *gh.PullRequest, reason string) StageLabelResult { e.recordStage(stageLaneContributor, "acme/widget", "acme", "widget", pr, reason, false, nil) @@ -123,15 +127,22 @@ func TestContributorNudgeOncePerHeadThenAtStall(t *testing.T) { } 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"} + stalled := append([]string{"stage/stalled"}, in072...) res := observe(nudgePR(7, "aaa"), "check-failing:unit") if got := nudgeComments(api); len(got) != 1 { t.Fatalf("nudges=%d comments=%v", len(got), api.comments) } else { - c := got[0] - for _, want := range []string{"head=aaa n=1 mode=spawn", "@mallory", "`unit`", "push a new head", "parallel fix session"} { - if !strings.Contains(c, want) { - t.Fatalf("comment missing %q:\n%s", want, c) + for _, want := range []string{"reason=check-failing head=aaa n=1 mode=spawn", "@mallory", "`unit`", "push a new head", "parallel fix session"} { + if !strings.Contains(got[0], want) { + t.Fatalf("comment missing %q:\n%s", want, got[0]) } } } @@ -140,54 +151,92 @@ func TestContributorNudgeOncePerHeadThenAtStall(t *testing.T) { t.Fatalf("res=%+v sink=%+v", res, sink.nudges) } - // Same head, same stage, next cycles: idempotent. + // Same head, same class, next cycles: idempotent, even past the stall + // threshold (24h) — the repeat window is 72h. api.reset() - labels := []string{"stage/072-returned-to-contributor", "role/contributor", "author/clanker"} clock.advance(time.Hour) - observe(nudgePR(7, "aaa", labels...), "check-failing:unit") - if api.writes() != 0 || len(sink.nudges) != 1 { - t.Fatalf("re-nudged early: comments=%v sink=%d", api.comments, len(sink.nudges)) + observe(nudgePR(7, "aaa", in072...), "check-failing:unit") + if api.writes() != 0 || len(api.commentEdits) != 0 || len(sink.nudges) != 1 { + t.Fatalf("re-nudged early: comments=%v edits=%v sink=%d", api.comments, api.commentEdits, len(sink.nudges)) } - - // Stall threshold (dwell 24h): stalled label + second nudge, no third. clock.advance(23 * time.Hour) - observe(nudgePR(7, "aaa", labels...), "check-failing:unit") - if got := nudgeComments(api); len(got) != 1 || !strings.Contains(got[0], "n=2") || !strings.Contains(got[0], "last automatic reminder") { - t.Fatalf("stall nudge: %v", api.comments) + observe(nudgePR(7, "aaa", in072...), "check-failing:unit") + if len(nudgeComments(api)) != 0 || len(api.commentEdits) != 0 || len(sink.nudges) != 1 { + t.Fatalf("stall threshold nudged: comments=%v edits=%v", api.comments, api.commentEdits) } if !reflect.DeepEqual(api.added, [][]string{{"stage/stalled"}}) { t.Fatalf("stalled label: %v", api.added) } - if len(sink.nudges) != 2 || !sink.nudges[1].Stalled { + + // New head, still red for the same class (another check): the one + // comment is rewritten, nothing new is posted, the relay is told, and + // the class count does not move. + api.reset() + clock.advance(time.Hour) + res = observe(nudgePR(7, "bbb", stalled...), "check-failing:lint") + if res.Comments != 0 || len(nudgeComments(api)) != 0 || len(api.commentEdits) != 1 { + t.Fatalf("new head same class: res=%+v comments=%v edits=%v", res, api.comments, api.commentEdits) + } + for _, want := range []string{"reason=check-failing head=bbb n=1 mode=spawn", "`lint`"} { + if !strings.Contains(lastEdit(), want) { + t.Fatalf("rewrite missing %q:\n%s", want, lastEdit()) + } + } + if len(sink.nudges) != 2 || sink.nudges[1].Nudge != 1 || sink.nudges[1].Stalled { t.Fatalf("sink=%+v", sink.nudges) } + rec, _ := e.stageStore.Get(stageKey("acme", "widget", 7)) + if rec.NudgeReason != "check-failing" || rec.NudgeReasonCount != 1 || rec.NudgeHead != "bbb" { + t.Fatalf("ledger %+v", rec) + } + + // 72h after the class was first counted: the one repeat reminder, as a + // rewrite; then never again for this class. api.reset() clock.advance(48 * time.Hour) - observe(nudgePR(7, "aaa", "stage/stalled", "stage/072-returned-to-contributor", "role/contributor", "author/clanker"), "check-failing:unit") - if len(nudgeComments(api)) != 0 || len(sink.nudges) != 2 { - t.Fatalf("third nudge posted: %v", api.comments) + observe(nudgePR(7, "bbb", stalled...), "check-failing:lint") + if len(nudgeComments(api)) != 0 || len(api.commentEdits) != 2 || !strings.Contains(lastEdit(), "reason=check-failing head=bbb n=2") || !strings.Contains(lastEdit(), "last automatic reminder") { + t.Fatalf("repeat nudge: comments=%v edits=%v", api.comments, api.commentEdits) + } + if len(sink.nudges) != 3 || !sink.nudges[2].Stalled || sink.nudges[2].Nudge != 2 { + t.Fatalf("sink=%+v", sink.nudges) + } + api.reset() + clock.advance(96 * time.Hour) + observe(nudgePR(7, "bbb", stalled...), "check-failing:lint") + if len(nudgeComments(api)) != 0 || len(api.commentEdits) != 2 || len(sink.nudges) != 3 { + t.Fatalf("third nudge: comments=%v edits=%v sink=%d", api.comments, api.commentEdits, len(sink.nudges)) } - // Author pushes a new head that is still red: count restarts. + // A different class on a new head restarts the count — still as a + // rewrite of the same comment. api.reset() - observe(nudgePR(7, "bbb", "stage/stalled", "stage/072-returned-to-contributor", "role/contributor", "author/clanker"), "changes-requested") - if got := nudgeComments(api); len(got) != 1 || !strings.Contains(got[0], "head=bbb n=1") || !strings.Contains(got[0], "reviewer requested changes") { - t.Fatalf("new-head nudge: %v", api.comments) + res = observe(nudgePR(7, "ccc", stalled...), "changes-requested") + if res.Comments != 0 || len(nudgeComments(api)) != 0 || len(api.commentEdits) != 3 { + t.Fatalf("changed reason: res=%+v comments=%v edits=%v", res, api.comments, api.commentEdits) + } + for _, want := range []string{"reason=changes-requested head=ccc n=1", "reviewer requested changes"} { + if !strings.Contains(lastEdit(), want) { + t.Fatalf("rewrite missing %q:\n%s", want, lastEdit()) + } } - if len(sink.nudges) != 3 || !sink.nudges[2].HumanChangesRequested { + if len(sink.nudges) != 4 || !sink.nudges[3].HumanChangesRequested || sink.nudges[3].Nudge != 1 { t.Fatalf("sink=%+v", sink.nudges) } if len(sink.resolved) != 0 { t.Fatalf("resolved while still in 072: %v", sink.resolved) } + if len(api.comments) != 0 { + t.Fatalf("a second nudge comment was posted: %v", api.comments) + } // New head goes green and awaits review: leaves 072 → Resolve once. api.reset() - observe(nudgePR(7, "ccc", "stage/072-returned-to-contributor", "role/contributor", "author/clanker"), "required-check-missing:unit") + observe(nudgePR(7, "ddd", in072...), "required-check-missing:unit") if !reflect.DeepEqual(sink.resolved, []int{7}) { t.Fatalf("resolved=%v", sink.resolved) } - observe(nudgePR(7, "ccc", "stage/050-review-pending", "role/contributor", "author/clanker"), "required-check-missing:unit") + observe(nudgePR(7, "ddd", "stage/050-review-pending", "role/contributor", "author/clanker"), "required-check-missing:unit") if !reflect.DeepEqual(sink.resolved, []int{7}) { t.Fatalf("resolve repeated: %v", sink.resolved) } @@ -230,6 +279,7 @@ func TestContributorNudgeTerminalDisabledAndNilSink(t *testing.T) { } api.reset() + api.statefulComments = true e = newNudgeEngine(t, apiURLOf(t, api), clock, nil, StageLabelPolicy{Enabled: true, ContributorNudge: true, RenudgeInterval: time.Hour}) pr := nudgePR(9, "aaa") e.recordStage(stageLaneTrusted, "acme/widget", "acme", "widget", pr, "status-failure", false, nil) @@ -239,15 +289,15 @@ func TestContributorNudgeTerminalDisabledAndNilSink(t *testing.T) { if got := nudgeComments(api); len(got) != 1 || !strings.Contains(got[0], "mode=comment") || !strings.Contains(got[0], "`status-failure`") { t.Fatalf("nil-sink nudge: %v", api.comments) } - // RenudgeInterval overrides the dwell: second nudge after 1h, not 24h. + // RenudgeInterval times the repeat: rewritten (not re-posted) after 1h. api.reset() clock.advance(time.Hour) e.recordStage(stageLaneTrusted, "acme/widget", "acme", "widget", nudgePR(9, "aaa", "stage/072-returned-to-contributor", "role/trusted", "author/clanker"), "status-failure", false, nil) if _, err := e.ApplyStageLabels(ctx); err != nil { t.Fatal(err) } - if got := nudgeComments(api); len(got) != 1 || !strings.Contains(got[0], "n=2") { - t.Fatalf("renudge interval: %v", api.comments) + if len(nudgeComments(api)) != 0 || len(api.commentEdits) != 1 || !strings.Contains(api.commentEdits[0], "reason=status-failure head=aaa n=2") { + t.Fatalf("renudge interval: comments=%v edits=%v", api.comments, api.commentEdits) } // A hive-authored PR (self lane → 070-fixing) is never nudged. api.reset() @@ -285,15 +335,39 @@ func TestNudgeDiagnosisAndDue(t *testing.T) { if !reflect.DeepEqual(checks, []string{"links"}) { t.Fatalf("red optional without detail: %v", checks) } +} + +func TestNudgeDue(t *testing.T) { now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) - if _, ok := nudgeDue(stagelabels.Record{}, "", time.Hour, now); ok { - t.Fatal("empty head due") - } - if n, ok := nudgeDue(stagelabels.Record{NudgeHead: "a", NudgeCount: 1, LastNudgeAt: now.Add(-time.Hour)}, "a", 0, now); ok || n != 0 { - t.Fatal("zero renudge interval should never re-nudge") + counted := stagelabels.Record{NudgeHead: "a", NudgeReason: "check-failing", NudgeReasonCount: 1, NudgeReasonAt: now.Add(-73 * time.Hour)} + cases := []struct { + name string + rec stagelabels.Record + head string + reason string + repeat time.Duration + ordinal int + ok bool + }{ + {name: "empty head", rec: stagelabels.Record{}, head: "", reason: "check-failing:unit", repeat: time.Hour}, + {name: "first nudge", rec: stagelabels.Record{}, head: "a", reason: "check-failing:unit", repeat: time.Hour, ordinal: 1, ok: true}, + {name: "same head same class inside window", rec: counted, head: "a", reason: "check-failing:lint", repeat: 100 * time.Hour}, + {name: "same head same class after window", rec: counted, head: "a", reason: "check-failing:lint", repeat: 72 * time.Hour, ordinal: 2, ok: true}, + {name: "zero repeat never re-nudges", rec: counted, head: "a", reason: "check-failing:unit", repeat: 0}, + {name: "zero NudgeReasonAt never re-nudges", rec: stagelabels.Record{NudgeHead: "a", NudgeReason: "check-failing", NudgeReasonCount: 1}, head: "a", reason: "check-failing:unit", repeat: time.Hour}, + {name: "cap reached", rec: stagelabels.Record{NudgeHead: "a", NudgeReason: "check-failing", NudgeReasonCount: 2, NudgeReasonAt: now.Add(-200 * time.Hour)}, head: "a", reason: "check-failing:unit", repeat: time.Hour}, + {name: "new head same class rewrites uncounted", rec: counted, head: "b", reason: "required-check-failing:lint", repeat: time.Hour, ordinal: 0, ok: true}, + {name: "new head same class at cap still rewrites", rec: stagelabels.Record{NudgeHead: "a", NudgeReason: "check-failing", NudgeReasonCount: 2, NudgeReasonAt: now}, head: "b", reason: "check-failing:unit", repeat: time.Hour, ordinal: 0, ok: true}, + {name: "changed class restarts", rec: counted, head: "a", reason: "conflicting", repeat: time.Hour, ordinal: 1, ok: true}, + {name: "legacy record without class", rec: stagelabels.Record{NudgeHead: "a", NudgeCount: 2, LastNudgeAt: now}, head: "a", reason: "check-failing:unit", repeat: time.Hour, ordinal: 1, ok: true}, } - if n, ok := nudgeDue(stagelabels.Record{NudgeHead: "a", NudgeCount: 1}, "a", time.Hour, now); ok || n != 0 { - t.Fatal("zero LastNudgeAt re-nudged") + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + n, ok := nudgeDue(tc.rec, tc.head, tc.reason, tc.repeat, now) + if n != tc.ordinal || ok != tc.ok { + t.Fatalf("nudgeDue = (%d, %v), want (%d, %v)", n, ok, tc.ordinal, tc.ok) + } + }) } } diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 13eef2c7fb..2b3fe9a602 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -52,8 +52,9 @@ type StageLabelPolicy struct { // ContributorNudge turns the stage-072 nudge comment + relay interrupt // on (governor.labels.stage.contributor_nudge.enabled, default true). ContributorNudge bool - // RenudgeInterval is the delay before the single re-nudge; 0 uses the - // stage's dwell (the stall threshold). + // RenudgeInterval is the delay before the single re-nudge for a reason + // class that persists (auto_merge.nudge_repeat_after, default 72h); + // 0 never re-nudges. RenudgeInterval time.Duration // Adoption turns the stage-074 adoption on // (governor.labels.stage.adoption.enabled, default true): a contributor diff --git a/src/pkg/github/issue_request_watcher.go b/src/pkg/github/issue_request_watcher.go index d3fe80d9ce..71364ebb8e 100644 --- a/src/pkg/github/issue_request_watcher.go +++ b/src/pkg/github/issue_request_watcher.go @@ -679,6 +679,15 @@ func (c *Client) handleOneIssueRequest(ctx context.Context, path string, nowFn f if err == nil && !created { c.noteCommentSuppressed() } + } else if note, ok := OriginFooterNote(body); ok && req.BlockedOnPR == 0 { + // Free text whose only marker is the identity footer is an + // agent note: one upserted comment per item, or a status + // section in quiet mode (hivecommons/hive#17067). + var created bool + created, err = c.postOriginNote(ctx, req.Repo, req.Number, req.Agent, note, nowFn()) + if err == nil && !created { + c.noteCommentSuppressed() + } } else { err = c.CreateIssueCommentBudgeted(ctx, req.Repo, req.Number, body) } diff --git a/src/pkg/github/origin_notes.go b/src/pkg/github/origin_notes.go new file mode 100644 index 0000000000..81ccf4f02b --- /dev/null +++ b/src/pkg/github/origin_notes.go @@ -0,0 +1,78 @@ +package github + +import ( + "context" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/prstatus" +) + +// OriginNotesMarker tags the one comment per item that collects an agent's +// free-text notes — the relayed `gh pr comment` bodies whose only marker +// is the identity footer's `` (hivecommons/hive#17067). +// Each new note edits that comment in place instead of posting another. +const OriginNotesMarker = "" + +// originNotesHeading opens the collected-notes comment. +const originNotesHeading = "**Agent notes** — updated in place; edits do not notify. Full history is in the Activity Monitor." + +// originNotesKeep caps how many notes the collected comment retains; the +// oldest drop off first. +const originNotesKeep = 10 + +// originNoteStatusKey is the status-comment section the notes fold into in +// quiet notification mode. +const originNoteStatusKey = prstatus.KeyAgentNotePrefix + "origin" + +// originNoteEntry renders one note as a list item. Continuation lines are +// indented so a multi-paragraph note stays inside its bullet. +func originNoteEntry(agent, note string, now time.Time) string { + head := "- " + if agent = strings.TrimSpace(agent); agent != "" { + head += "**" + agent + "** " + } + head += "(" + now.UTC().Format("2006-01-02 15:04 UTC") + "): " + lines := strings.Split(strings.TrimSpace(note), "\n") + for i := 1; i < len(lines); i++ { + lines[i] = " " + lines[i] + } + return head + strings.Join(lines, "\n") +} + +// renderOriginNotes returns the collected-notes comment body with entry +// appended to the notes already in previous (or a fresh comment when +// previous is empty), keeping at most originNotesKeep entries. +func renderOriginNotes(previous, entry string) string { + var entries []string + if i := strings.Index(previous, "\n- "); i >= 0 { + for _, block := range strings.Split(previous[i+1:], "\n- ") { + block = strings.TrimRight(block, "\n") + if strings.TrimSpace(block) == "" { + continue + } + entries = append(entries, "- "+strings.TrimPrefix(block, "- ")) + } + } + entries = append(entries, entry) + if len(entries) > originNotesKeep { + entries = entries[len(entries)-originNotesKeep:] + } + return OriginNotesMarker + "\n" + originNotesHeading + "\n\n" + strings.Join(entries, "\n") +} + +// postOriginNote delivers an agent's free-text note without a new +// notification per note: in quiet mode it is the agent-note section of the +// item's status comment; otherwise it is appended to the one +// OriginNotesMarker comment on the item, created on first use. Reports +// whether a comment was created. +func (c *Client) postOriginNote(ctx context.Context, repo string, number int, agent, note string, now time.Time) (bool, error) { + entry := originNoteEntry(agent, note, now) + if c.notificationsQuiet() { + return c.UpsertPRStatusSection(ctx, repo, number, originNoteStatusKey, entry) + } + res, err := c.EditIssueMarkerComment(ctx, repo, number, OriginNotesMarker, func(previous string) string { + return renderOriginNotes(previous, entry) + }) + return res.Created, err +} diff --git a/src/pkg/github/origin_notes_test.go b/src/pkg/github/origin_notes_test.go new file mode 100644 index 0000000000..3e92674dcd --- /dev/null +++ b/src/pkg/github/origin_notes_test.go @@ -0,0 +1,136 @@ +package github + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/prstatus" +) + +const testOriginFooter = "\n\n---\n🐝 **Hive Agent**: `a1` | **Instance:** `test-hive` | **SHA:** `abc1234`\n" + +// The footer the wrapper emits for a hive without an instance id: no origin marker. +const testBareFooter = "\n\n---\n🐝 **Hive Agent**: `a1` | **SHA:** `abc1234`" + +// Only a free-text body whose sole marker is the identity footer's origin +// marker is an agent note; anything else keeps its own path. +func TestOriginFooterNote(t *testing.T) { + tests := []struct { + name string + body string + want string + ok bool + }{ + {"plain note with footer", "Looked at this; the flake is in the retry loop." + testOriginFooter, "Looked at this; the flake is in the retry loop.", true}, + {"multi-line note", "First line.\n\nSecond paragraph." + testOriginFooter, "First line.\n\nSecond paragraph.", true}, + {"crlf body", strings.ReplaceAll("Note here."+testOriginFooter, "\n", "\r\n"), "Note here.", true}, + {"no footer", "Just a comment.", "", false}, + {"footer only", testOriginFooter, "", false}, + {"footer without origin marker", "Note." + testBareFooter, "", false}, + {"origin marker without footer", "Note.\n\n", "", false}, + {"verification marker present", "Verified.\n" + testOriginFooter, "", false}, + {"status marker present", prstatus.Marker + "\nstate" + testOriginFooter, "", false}, + {"footer not at end", "x" + testOriginFooter + "\n\ntrailing text", "", false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, ok := OriginFooterNote(tc.body) + if ok != tc.ok || got != tc.want { + t.Fatalf("OriginFooterNote() = %q, %v; want %q, %v", got, ok, tc.want, tc.ok) + } + }) + } +} + +// Notes accumulate under the one marker comment, oldest dropping past the cap. +func TestRenderOriginNotes(t *testing.T) { + now := time.Date(2026, 11, 7, 10, 0, 0, 0, time.UTC) + tests := []struct { + name string + previous string + entry string + wantCount int + wantFirst string + wantAbsent string + }{ + {"fresh", "", originNoteEntry("a1", "first", now), 1, "**a1** (2026-11-07 10:00 UTC): first", ""}, + {"append", renderOriginNotes("", originNoteEntry("a1", "first", now)), originNoteEntry("a2", "second\nmore", now), 2, "first", ""}, + {"cap", func() string { + body := "" + for i := 0; i < originNotesKeep; i++ { + body = renderOriginNotes(body, originNoteEntry("a", strings.Repeat("x", i+1), now)) + } + return body + }(), originNoteEntry("a", "newest", now), originNotesKeep, "xx", "): x\n"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := renderOriginNotes(tc.previous, tc.entry) + if !strings.HasPrefix(got, OriginNotesMarker+"\n") { + t.Fatalf("missing marker:\n%s", got) + } + if n := strings.Count(got, "\n- "); n != tc.wantCount { + t.Fatalf("entries = %d, want %d:\n%s", n, tc.wantCount, got) + } + if !strings.Contains(got, tc.wantFirst) { + t.Fatalf("missing %q:\n%s", tc.wantFirst, got) + } + if tc.wantAbsent != "" && strings.Contains(got, tc.wantAbsent) { + t.Fatalf("oldest entry should have dropped:\n%s", got) + } + if !strings.HasSuffix(got, tc.entry) { + t.Fatalf("newest entry not last:\n%s", got) + } + }) + } +} + +// Normal mode: the first note creates the marker comment, the next edits it. +// Quiet mode: notes are a section of the status comment. +func TestPostOriginNoteOneCommentPerItem(t *testing.T) { + ctx := context.Background() + now := time.Date(2026, 11, 7, 10, 0, 0, 0, time.UTC) + tests := []struct { + name string + quiet bool + wantCreates int + wantEdits int + wantMarker string + }{ + {"normal mode edits the notes comment", false, 1, 2, OriginNotesMarker}, + {"quiet mode folds into status", true, 1, 2, prstatus.Marker}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + s := &statusCommentServer{} + c := testClient(t, s.start(t).URL) + c.SetAppBotLogin("hive-app[bot]") + c.SetNotificationsQuiet(func() bool { return tc.quiet }) + for i, note := range []string{"first", "second", "third"} { + created, err := c.postOriginNote(ctx, "o/r", 7, "agent-1", note, now.Add(time.Duration(i)*time.Minute)) + if err != nil { + t.Fatal(err) + } + if created != (i == 0) { + t.Fatalf("note %d: created=%v", i, created) + } + } + if s.creates != tc.wantCreates || s.edits != tc.wantEdits { + t.Fatalf("creates=%d edits=%d, want %d/%d", s.creates, s.edits, tc.wantCreates, tc.wantEdits) + } + body, _ := s.comments[0]["body"].(string) + if !strings.Contains(body, tc.wantMarker) || !strings.Contains(body, "third") { + t.Fatalf("comment body:\n%s", body) + } + if tc.quiet { + if sec, ok := prstatus.Get(body, originNoteStatusKey); !ok || !strings.Contains(sec, "third") { + t.Fatalf("status section = %q, %v", sec, ok) + } + } else if !strings.Contains(body, "first") { + t.Fatalf("earlier note dropped:\n%s", body) + } + }) + } +} diff --git a/src/pkg/stagelabels/store.go b/src/pkg/stagelabels/store.go index a896990ded..00ce987fc4 100644 --- a/src/pkg/stagelabels/store.go +++ b/src/pkg/stagelabels/store.go @@ -83,6 +83,15 @@ type Record struct { // NudgeOnline records whether the author's relay was online at the first // nudge for NudgeHead (selects the online vs offline grace). NudgeOnline bool `json:"nudge_online,omitempty"` + // NudgeReason, NudgeReasonCount and NudgeReasonAt are the per-reason + // nudge ledger (hivecommons/hive#17067): the reason class the one + // nudge comment on the PR currently explains, how many nudges that + // class has had (cap 2, counted across heads) and when the last one + // went out. A new head red for the same class rewrites the comment + // without counting; a new class restarts the count. + NudgeReason string `json:"nudge_reason,omitempty"` + NudgeReasonCount int `json:"nudge_reason_count,omitempty"` + NudgeReasonAt time.Time `json:"nudge_reason_at,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 @@ -1426,6 +1435,52 @@ func (s *Store) MarkNudged(key, head string, n int, online bool, now time.Time) s.dirty = true } +// MarkNudgedReason records that nudge number n for reason class reason was +// posted (or the one nudge comment rewritten) at now. A different class +// restarts the count at n; the same class keeps the larger of n and the +// recorded count so a head-only rewrite (n == 0) never resets it. +func (s *Store) MarkNudgedReason(key, reason string, n int, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.items[key] + if !ok { + return + } + reason = NudgeReasonSlug(reason) + if r.NudgeReason != reason { + r.NudgeReason = reason + r.NudgeReasonCount = 0 + } + if n > r.NudgeReasonCount { + r.NudgeReasonCount = n + r.NudgeReasonAt = now + } + s.items[key] = r + s.dirty = true +} + +// 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". +func NudgeReasonSlug(reason string) string { + class := strings.ToLower(MentionCauseClass(reason)) + var b strings.Builder + for _, r := range class { + switch { + case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '.', r == '_', r == '-': + b.WriteRune(r) + default: + b.WriteByte('-') + } + } + slug := strings.Trim(b.String(), "-") + if slug == "" { + return "unknown" + } + return slug +} + // Adoption modes (Record.AdoptMode). const ( AdoptModeSupersede = "supersede" From ef6907c584af29d0301e776abf4d5f921d1b9699 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 14:49:52 -0500 Subject: [PATCH 2/3] contributor nudge: expose auto_merge.nudge_repeat_after in Settings TestSettingsDialogReferencesEveryHiveYAMLLeaf requires every hive.yaml leaf to have a Settings control. Add a Re-nudge-after field to the Labels tab next to the legacy renudge_interval it supersedes, read and write it via /api/config/governor/labels with the same positive-duration validation, and cover the round trip. Signed-off-by: Andrew Anderson --- src/pkg/dashboard/api_governor.go | 14 ++++++- .../nudge_repeat_after_settings_test.go | 42 +++++++++++++++++++ .../static-src/js/config-governor.js | 12 +++++- .../dashboard/static-src/js/config-state.js | 2 +- src/pkg/dashboard/static/index.html | 14 +++++-- 5 files changed, 76 insertions(+), 8 deletions(-) create mode 100644 src/pkg/dashboard/nudge_repeat_after_settings_test.go diff --git a/src/pkg/dashboard/api_governor.go b/src/pkg/dashboard/api_governor.go index 1b15f345d2..0e55191dc0 100644 --- a/src/pkg/dashboard/api_governor.go +++ b/src/pkg/dashboard/api_governor.go @@ -164,8 +164,11 @@ func (s *Server) handleGovernorConfigGet(w http.ResponseWriter, r *http.Request) "stageLabelsDwell": formatStageDwell(cfg.Governor.Labels.Stage.Dwell), // governor.labels.stage.contributor_nudge.* and presence_window // (hivecommons/hive#12436): the stage-072 contributor nudge. - "stageNudgeEnabled": cfg.Governor.Labels.Stage.ContributorNudge.IsEnabled(), - "stageNudgeRenudge": cfg.Governor.Labels.Stage.ContributorNudge.RenudgeInterval, + "stageNudgeEnabled": cfg.Governor.Labels.Stage.ContributorNudge.IsEnabled(), + "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, // governor.labels.stage.adoption.enabled / contributor_grace_*: the // stage-074 adoption of red contributor PRs. @@ -809,6 +812,9 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { StageNudgeEnabled *bool `json:"stage_nudge_enabled"` StageNudgeRenudge *string `json:"stage_nudge_renudge_interval"` StagePresenceWindow *string `json:"stage_presence_window"` + // NudgeRepeatAfter is auto_merge.nudge_repeat_after + // (hivecommons/hive#17067); a Go duration, empty restores 72h. + NudgeRepeatAfter *string `json:"nudge_repeat_after"` // Stage-074 adoption: governor.labels.stage.adoption.enabled and // governor.labels.stage.contributor_grace_online / _offline. StageAdoptionEnabled *bool `json:"stage_adoption_enabled"` @@ -917,6 +923,7 @@ 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, @@ -1027,6 +1034,9 @@ func (s *Server) handleGovernorLabels(w http.ResponseWriter, r *http.Request) { if body.StageNudgeRenudge != nil { s.deps.Config.Governor.Labels.Stage.ContributorNudge.RenudgeInterval = strings.TrimSpace(*body.StageNudgeRenudge) } + if body.NudgeRepeatAfter != nil { + s.deps.Config.AutoMerge.NudgeRepeatAfter = strings.TrimSpace(*body.NudgeRepeatAfter) + } 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 new file mode 100644 index 0000000000..6479cce7ac --- /dev/null +++ b/src/pkg/dashboard/nudge_repeat_after_settings_test.go @@ -0,0 +1,42 @@ +package dashboard + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +// auto_merge.nudge_repeat_after (hivecommons/hive#17067) is edited from the +// Labels tab alongside the legacy renudge_interval it supersedes. +func TestHandleGovernorLabels_NudgeRepeatAfterRoundTrip(t *testing.T) { + srv := newFullServer(t) + w := httptest.NewRecorder() + srv.handleGovernorLabels(w, ownerPUT(t, "/api/config/governor/labels", `{"nudge_repeat_after":" 48h "}`)) + if w.Code != http.StatusOK { + t.Fatalf("code = %d, body = %s", w.Code, w.Body.String()) + } + if got := srv.deps.Config.AutoMerge.NudgeRepeatAfter; got != "48h" { + t.Fatalf("nudge_repeat_after = %q, want trimmed 48h", got) + } + if got := decodeGovernorConfigGet(t, srv)["nudgeRepeatAfter"]; got != "48h" { + t.Fatalf("GET nudgeRepeatAfter = %v, want 48h", got) + } + + w = httptest.NewRecorder() + srv.handleGovernorLabels(w, ownerPUT(t, "/api/config/governor/labels", `{"nudge_repeat_after":"soon"}`)) + if w.Code != http.StatusBadRequest { + t.Fatalf("invalid duration: code = %d, want 400; body = %s", w.Code, w.Body.String()) + } + if got := srv.deps.Config.AutoMerge.NudgeRepeatAfter; got != "48h" { + t.Fatalf("rejected save mutated nudge_repeat_after to %q", got) + } + + w = httptest.NewRecorder() + srv.handleGovernorLabels(w, ownerPUT(t, "/api/config/governor/labels", `{"nudge_repeat_after":""}`)) + if w.Code != http.StatusOK { + t.Fatalf("clear: code = %d, body = %s", w.Code, w.Body.String()) + } + if got := srv.deps.Config.AutoMerge.NudgeRepeatAfter; got != "" { + t.Fatalf("empty must clear the override, 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 819710967f..5fc0bed3c5 100644 --- a/src/pkg/dashboard/static-src/js/config-governor.js +++ b/src/pkg/dashboard/static-src/js/config-governor.js @@ -704,6 +704,9 @@ const stageNudgeRenudge = (_configState.dirty.labels && _configState.dirty.labels.stage_nudge_renudge_interval !== undefined) ? _configState.dirty.labels.stage_nudge_renudge_interval : (_configState.data.stageNudgeRenudge || ''); + const nudgeRepeatAfter = (_configState.dirty.labels && _configState.dirty.labels.nudge_repeat_after !== undefined) + ? _configState.dirty.labels.nudge_repeat_after + : (_configState.data.nudgeRepeatAfter || ''); const stagePresenceWindow = (_configState.dirty.labels && _configState.dirty.labels.stage_presence_window !== undefined) ? _configState.dirty.labels.stage_presence_window : (_configState.data.stagePresenceWindow || ''); @@ -777,8 +780,13 @@
Contributor nudge on returned-to-contributor ${yamlHint('governor.labels.stage.contributor_nudge.enabled')} ${settingHelpMark('settings', 'labels', 'Contributor nudge', `When a contributor's PR enters stage/072-returned-to-contributor (red CI, changes requested, conflicts) the hive posts ONE @-mention comment per head with the failing checks / review asks and, for relay contributors, pushes a fix-pr task to their relay session (parallel sub-session when the relay advertises parallel_sessions, otherwise preempting the current task). Re-nudged once at the stall threshold; cap 2 per head. See docs/labels-and-control-signals.md.`)}
- -
Go duration before the single re-nudge; empty = the returned-to-contributor dwell.
+ +
Legacy override: Go duration before the single re-nudge; empty defers to the re-nudge-after setting below.
+
+
+ + +
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.
diff --git a/src/pkg/dashboard/static-src/js/config-state.js b/src/pkg/dashboard/static-src/js/config-state.js index 073d86eb55..f1d9ecf467 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 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.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 f3e9a1cc4e..b26753502a 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -52569,7 +52569,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 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.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' }, @@ -59367,6 +59367,9 @@

Backend placement policy

const stageNudgeRenudge = (_configState.dirty.labels && _configState.dirty.labels.stage_nudge_renudge_interval !== undefined) ? _configState.dirty.labels.stage_nudge_renudge_interval : (_configState.data.stageNudgeRenudge || ''); + const nudgeRepeatAfter = (_configState.dirty.labels && _configState.dirty.labels.nudge_repeat_after !== undefined) + ? _configState.dirty.labels.nudge_repeat_after + : (_configState.data.nudgeRepeatAfter || ''); const stagePresenceWindow = (_configState.dirty.labels && _configState.dirty.labels.stage_presence_window !== undefined) ? _configState.dirty.labels.stage_presence_window : (_configState.data.stagePresenceWindow || ''); @@ -59440,8 +59443,13 @@

Stage labels

Contributor nudge on returned-to-contributor ${yamlHint('governor.labels.stage.contributor_nudge.enabled')} ${settingHelpMark('settings', 'labels', 'Contributor nudge', `When a contributor's PR enters stage/072-returned-to-contributor (red CI, changes requested, conflicts) the hive posts ONE @-mention comment per head with the failing checks / review asks and, for relay contributors, pushes a fix-pr task to their relay session (parallel sub-session when the relay advertises parallel_sessions, otherwise preempting the current task). Re-nudged once at the stall threshold; cap 2 per head. See docs/labels-and-control-signals.md.`)}
- -
Go duration before the single re-nudge; empty = the returned-to-contributor dwell.
+ +
Legacy override: Go duration before the single re-nudge; empty defers to the re-nudge-after setting below.
+
+
+ + +
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.
From 9d3701878f9c2ab38b521646e0076a98f90ea5c7 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 15:05:19 -0500 Subject: [PATCH 3/3] stagelabels: cover MarkNudgedReason, NudgeReasonSlug and NudgeStart The per-reason nudge ledger added for hivecommons/hive#17067 had no direct tests, dropping pkg/stagelabels under its 90% coverage floor. Signed-off-by: Andrew Anderson --- src/pkg/stagelabels/stagelabels_test.go | 59 +++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/pkg/stagelabels/stagelabels_test.go b/src/pkg/stagelabels/stagelabels_test.go index f06d1c69f6..860a714f2a 100644 --- a/src/pkg/stagelabels/stagelabels_test.go +++ b/src/pkg/stagelabels/stagelabels_test.go @@ -602,6 +602,65 @@ func TestStoreMarksForgetsAndSharedLoad(t *testing.T) { } } +func TestStoreMarkNudgedReason(t *testing.T) { + now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) + s := NewStore("", func() time.Time { return now }) + s.MarkNudgedReason("missing", "check-failing:unit", 1, now) // unknown key: no-op + if _, ok := s.Get("missing"); ok { + t.Fatal("MarkNudgedReason created a record") + } + key := Key("acme/widget", 7) + s.Observe(key, ReturnedToContributor, "check-failing:unit") + s.MarkNudgedReason(key, "required-check-failing:unit (lint)", 1, now) + r, _ := s.Get(key) + if r.NudgeReason != "check-failing" || r.NudgeReasonCount != 1 || !r.NudgeReasonAt.Equal(now) { + t.Fatalf("after first: %+v", r) + } + // A head-only rewrite (n == 0) for the same class keeps the count and time. + s.MarkNudgedReason(key, "check-failing:e2e", 0, now.Add(time.Hour)) + if r, _ = s.Get(key); r.NudgeReasonCount != 1 || !r.NudgeReasonAt.Equal(now) { + t.Fatalf("rewrite: %+v", r) + } + s.MarkNudgedReason(key, "check-failing:e2e", 2, now.Add(2*time.Hour)) + if r, _ = s.Get(key); r.NudgeReasonCount != 2 || !r.NudgeReasonAt.Equal(now.Add(2*time.Hour)) { + t.Fatalf("second nudge: %+v", r) + } + // A different class restarts the count. + s.MarkNudgedReason(key, "changes-requested", 1, now.Add(3*time.Hour)) + if r, _ = s.Get(key); r.NudgeReason != "changes-requested" || r.NudgeReasonCount != 1 || !r.NudgeReasonAt.Equal(now.Add(3*time.Hour)) { + t.Fatalf("new class: %+v", r) + } +} + +func TestRecordNudgeStart(t *testing.T) { + now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) + if got := (Record{}).NudgeStart(); !got.IsZero() { + t.Fatalf("never nudged: %v", got) + } + if got := (Record{NudgeCount: 1, LastNudgeAt: now}).NudgeStart(); !got.Equal(now) { + t.Fatalf("legacy record falls back to LastNudgeAt: %v", got) + } + if got := (Record{NudgeCount: 2, FirstNudgeAt: now, LastNudgeAt: now.Add(time.Hour)}).NudgeStart(); !got.Equal(now) { + t.Fatalf("FirstNudgeAt wins: %v", got) + } +} + +func TestNudgeReasonSlug(t *testing.T) { + for in, want := range map[string]string{ + "": "unknown", + " ": "unknown", + "check-failing:unit (lint)": "check-failing", + "required-check-failing:unit": "check-failing", + "Changes Requested by @Reviewer": "changes-requested-by--reviewer", + "--merge_conflict.v2--": "merge_conflict.v2", + "(only parenthetical)": "unknown", + } { + if got := NudgeReasonSlug(in); got != want { + t.Errorf("NudgeReasonSlug(%q) = %q, want %q", in, got, want) + } + } +} + func TestStoreMarkNudged(t *testing.T) { now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) s := NewStore("", func() time.Time { return now })