Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/changed-contributor-nudge-dedupe.md
Original file line number Diff line number Diff line change
@@ -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).
13 changes: 12 additions & 1 deletion src/cmd/hive/merge_eligibility.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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()
}
10 changes: 6 additions & 4 deletions src/docs/hive-merge.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<!-- hive:contributor-nudge head=…
-->` 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 `<!-- hive:contributor-nudge
reason=<slug> head=… -->` 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
Expand Down
17 changes: 10 additions & 7 deletions src/docs/labels-and-control-signals/stage-labels.md
Original file line number Diff line number Diff line change
Expand Up @@ -753,13 +753,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 `<!-- hive:contributor-nudge
head=<sha> n=<1|2> mode=<comment|queued|spawn|preempt> -->` 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=<slug> head=<sha> n=<1|2> mode=<comment|queued|spawn|preempt> -->`
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
Expand Down
6 changes: 5 additions & 1 deletion src/docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<state>`), the decision-downgrade note left when a label
(`agent-note:<state>`), an agent's free-text relay comment whose only
marker is the identity footer's `<!-- hive:origin … -->`
(`agent-note:origin`, latest note; outside quiet mode these append to the
one `<!-- hive:origin-notes -->` 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
Expand Down
1 change: 1 addition & 0 deletions src/docs/operator-reference/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,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.<repo>.required_checks` | inherits default | Per-repo override for heterogeneous hives. `<repo>` 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. |
Expand Down
7 changes: 4 additions & 3 deletions src/docs/operator-reference/sweeps-and-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
249 changes: 249 additions & 0 deletions src/internal/testutil/comment_marker_ratchet_test.go
Original file line number Diff line number Diff line change
@@ -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 `<!-- hive:… -->` 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 `<!-- hive…` marker literal, names a
// marker (`Marker`, `marker`), writes a prstatus section, or upserts.
var commentMarkerEvidence = []string{
"<!-- hive",
"arker",
"prstatus.",
"Upsert",
}

// commentMarkerAllowList names the transport primitives: the functions
// that ARE the raw create call every marked helper is built on, and so
// cannot carry a marker themselves. Keyed by `path:Recv.Func` relative
// to commentMarkerRoot. Add here only for a new primitive, never for a
// feature emitter.
var commentMarkerAllowList = map[string]bool{
"client.go:Client.CreateIssueComment": true,
"issue_comment_budget.go:Client.CreateIssueCommentBudgeted": true,
"pr_status_comment.go:clientStatusForge.CreateComment": true,
"automerge/automerge_stage_labels.go:engineStatusForge.CreateComment": true,
}

// commentMarkerRoot is the tree the ratchet walks, relative to this package
// (src/internal/testutil): the GitHub client and the auto-merge engine,
// which between them own every bot comment the hive posts.
var commentMarkerRoot = filepath.Join("..", "..", "pkg", "github")

var (
funcDeclRE = regexp.MustCompile(`^func\s+(?:\([^)]*\)\s*)?([A-Za-z0-9_]+)`)
funcRecvDeclRE = regexp.MustCompile(`^func\s+\(\s*\w*\s*\*?([A-Za-z0-9_]+)\s*\)\s*([A-Za-z0-9_]+)`)
)

// commentEmitters scans one Go source file and returns the identities
// (`relpath:Recv.Func`) of functions that call a raw comment create,
// split into those with marker evidence and those without. Top-level
// `func ` lines delimit functions; `//` comment lines are not calls.
func commentEmitters(relPath string, src string) (marked, unmarked []string) {
lines := strings.Split(src, "\n")
var starts []int
for i, l := range lines {
if strings.HasPrefix(l, "func ") {
starts = append(starts, i)
}
}
for k, s := range starts {
e := len(lines)
if k+1 < len(starts) {
e = starts[k+1]
}
body := lines[s:e]
hit := false
for _, l := range body[1:] {
if strings.HasPrefix(strings.TrimSpace(l), "//") {
continue
}
for _, call := range commentEmitterCalls {
if strings.Contains(l, call) {
hit = true
break
}
}
if hit {
break
}
}
if !hit {
continue
}
name := ""
if m := funcRecvDeclRE.FindStringSubmatch(lines[s]); m != nil {
name = m[1] + "." + m[2]
} else if m := funcDeclRE.FindStringSubmatch(lines[s]); m != nil {
name = m[1]
}
ident := relPath + ":" + name
text := strings.Join(body, "\n")
evidence := false
for _, mk := range commentMarkerEvidence {
if strings.Contains(text, mk) {
evidence = true
break
}
}
if evidence {
marked = append(marked, ident)
} else {
unmarked = append(unmarked, ident)
}
}
return marked, unmarked
}

// TestCommentMarkerRatchet fails when the number of unmarked raw comment
// emitters under pkg/github exceeds commentMarkerBaseline, and when an
// allow-listed primitive no longer exists (so the list cannot rot). Runs
// in well under a second: a file walk and substring scans.
func TestCommentMarkerRatchet(t *testing.T) {
var marked, unmarked []string
files := 0
err := filepath.WalkDir(commentMarkerRoot, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(d.Name(), ".go") || strings.HasSuffix(d.Name(), "_test.go") {
return nil
}
files++
data, err := os.ReadFile(path)
if err != nil {
return err
}
rel, err := filepath.Rel(commentMarkerRoot, path)
if err != nil {
return err
}
m, u := commentEmitters(filepath.ToSlash(rel), string(data))
marked = append(marked, m...)
unmarked = append(unmarked, u...)
return nil
})
if err != nil {
t.Fatalf("walking %s: %v", commentMarkerRoot, err)
}
// Fail closed: no files means the wrong working directory.
if files == 0 {
t.Fatalf("no .go files found under %s — is the test running from src/internal/testutil?", commentMarkerRoot)
}

seen := map[string]bool{}
var counted []string
for _, id := range unmarked {
seen[id] = true
if !commentMarkerAllowList[id] {
counted = append(counted, id)
}
}
for id := range commentMarkerAllowList {
if !seen[id] {
t.Errorf("allow-listed %q is no longer an unmarked emitter; remove it from commentMarkerAllowList", id)
}
}
sort.Strings(counted)
total := len(counted)
switch {
case total > commentMarkerBaseline:
t.Fatalf("%d functions under pkg/github post comments without a marker (%d marker-aware), above the baseline of %d.\n"+
"Every bot comment must be idempotent across sweeps: carry a `<!-- hive:… -->` 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 := \"<!-- hive:x -->\" + 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)
}
})
}
}
Loading
Loading