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/added-16360.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Neutralise incidental `@user` mentions in copied text inside hive-authored status comments, so copying a title or quote no longer re-notifies the person named.
20 changes: 20 additions & 0 deletions src/docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,26 @@ Operator-defined [hooks](hooks.md) with the `notify` action send through the sam

The legacy shell scripts in `bin/` also use `bin/notify.sh` for events such as stale agents, rate limits, backend switches, and kick status when those scripts are deployed. Those scripts read environment variables (`NTFY_TOPIC`, `NTFY_SERVER`, `SLACK_WEBHOOK`, `DISCORD_WEBHOOK`) rather than the `notifications:` YAML block.

## Mention hygiene

Text the hive copies into a body it authors (issue/PR titles, quoted comments,
evidence, attribution) must never notify the people it names. The status
comment writer (`prstatus.Write`) passes every section through
`advisory.NeutralizeMentions`, the same convention the advisory digest and
duplicate-sweep renderers use: `@login` becomes `` `login` `` (only the `@` is
dropped inside code spans and fences). Email addresses, URLs and `#123`
references are untouched, and the rewrite is idempotent. Sections of a status
comment another author posted are neutralised too when they are merged into
the hive-owned comment, since that body is re-edited on every pass. This
applies regardless of the attention-pilot flag.

Deliberate mentions are posted as their own comments or reviews through the
notification-class framework and are not rewritten. The one deliberate mention
that lives in the status comment, the trusted-human 071 note's `@author` in
quiet-notification mode, goes through `prstatus.WriteMentioning`, which posts
the section verbatim; its composer neutralises the copied check names and
review asks itself, so the author is the only person it notifies.

## Testing delivery

Test the target channel directly before putting it in `hive.yaml`:
Expand Down
18 changes: 13 additions & 5 deletions src/pkg/github/automerge/automerge_contributor_nudge.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"time"

gh "github.com/google/go-github/v72/github"
"github.com/hivecommons/hive/pkg/advisory"
"github.com/hivecommons/hive/pkg/prstatus"
"github.com/hivecommons/hive/pkg/stagelabels"
)
Expand Down Expand Up @@ -373,6 +374,11 @@ func TrustedHuman071Comment(n ContributorNudge, stage stagelabels.Stage) string
// TrustedHuman071Note is TrustedHuman071Comment with the @-mention optional:
// in quiet notification mode the author is mentioned once per cause, and a
// re-render for a new head with the same cause names them without the @.
//
// The author's mention is the only deliberate one. The diagnosis quotes
// check names and review text the hive did not write, so that part is
// neutralised (advisory.NeutralizeMentions) and never notifies the people
// it happens to name.
func TrustedHuman071Note(n ContributorNudge, stage stagelabels.Stage, mention bool) string {
var b strings.Builder
fmt.Fprintf(&b, "%s head=%s -->\n", TrustedHuman071MarkerPrefix, n.HeadSHA)
Expand All @@ -381,18 +387,20 @@ func TrustedHuman071Note(n ContributorNudge, stage stagelabels.Stage, mention bo
at = ""
}
fmt.Fprintf(&b, "%s%s this PR is held at `%s` and the hive will not merge it yet.\n\n", at, n.Author, stage.Label())
var d strings.Builder
if len(n.FailingChecks) > 0 {
b.WriteString("**Failing checks:**\n")
d.WriteString("**Failing checks:**\n")
for _, c := range n.FailingChecks {
fmt.Fprintf(&b, "- `%s`\n", c)
fmt.Fprintf(&d, "- `%s`\n", c)
}
}
if len(n.ReviewAsks) > 0 {
b.WriteString("**Why:**\n")
d.WriteString("**Why:**\n")
for _, a := range n.ReviewAsks {
fmt.Fprintf(&b, "- %s\n", a)
fmt.Fprintf(&d, "- %s\n", a)
}
}
b.WriteString(advisory.NeutralizeMentions(d.String()))
b.WriteString("\nNext: the hive does not push to your branch. Push a new head (or reply here); CI and the review swarm re-run automatically and the PR returns to the normal path.\n")
return b.String()
}
Expand All @@ -419,7 +427,7 @@ func (c *Engine) noteTrustedHuman071(ctx context.Context, store *stagelabels.Sto
// mention — a new head failing the same way is the same ask.
mention := !policy.QuietNotifications || rec.MentionDue(obs.Reason)
body := TrustedHuman071Note(n, stagelabels.NeedsAuthor, mention)
posted, err := c.postStageNote(ctx, policy, obs, prstatus.KeyHuman071Note, body)
posted, err := c.postStageNoteMentioning(ctx, policy, obs, prstatus.KeyHuman071Note, body)
if err != nil {
c.warn("stage labels: trusted human 071 note failed", "repo", obs.Display, "pr", obs.Number, "error", err)
return 0, err
Expand Down
18 changes: 18 additions & 0 deletions src/pkg/github/automerge/automerge_contributor_nudge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,21 @@ func TestContributorNudgeCommentRelayFailed(t *testing.T) {
t.Fatalf("plain queued comment = %q", body)
}
}

func TestTrustedHuman071NoteNeutralisesCopiedMentions(t *testing.T) {
n := ContributorNudge{Author: "alice", HeadSHA: "abc",
FailingChecks: []string{"lint @bob"},
ReviewAsks: []string{"@carol asked for a test"}}
got := TrustedHuman071Note(n, stagelabels.NeedsAuthor, true)
if !strings.Contains(got, "@alice this PR is held") {
t.Fatalf("deliberate author mention lost: %s", got)
}
for _, live := range []string{"@bob", "@carol"} {
if strings.Contains(got, live) {
t.Fatalf("copied mention %s survived: %s", live, got)
}
}
if !strings.Contains(got, "`carol`") || !strings.Contains(got, "lint bob") {
t.Fatalf("copied logins not kept readably: %s", got)
}
}
36 changes: 26 additions & 10 deletions src/pkg/github/automerge/automerge_stage_labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -1469,29 +1469,45 @@ func regressionNotable(reason string) bool {
return classifyCIReason(reason) != ciReasonPending && !stageReasonWaitsOnHive(reason)
}

// postStageNote delivers one of the stage notes (stall, regression, 071) to
// postStageNote delivers one of the stage notes (stall, regression) to
// the PR. In normal mode it is a fresh comment. In quiet mode it is folded
// into the PR's single hive status comment under key, edited in place: the
// comment is created only the first time, and only that creation counts
// as a comment posted. Returns the number of comments created.
// as a comment posted. body is copied prose: in quiet mode prstatus.Write
// neutralises any @login in it. Returns the number of comments created.
func (c *Engine) postStageNote(ctx context.Context, policy StageLabelPolicy, obs stageObservation, key, body string) (int, error) {
return c.postStageNoteWith(ctx, policy, obs, key, body, prstatus.Write)
}

// postStageNoteMentioning is postStageNote for the trusted-human 071 note,
// whose @author is deliberate: body is delivered verbatim, so the composer
// must have neutralised the copied text in it itself.
func (c *Engine) postStageNoteMentioning(ctx context.Context, policy StageLabelPolicy, obs stageObservation, key, body string) (int, error) {
return c.postStageNoteWith(ctx, policy, obs, key, body, prstatus.WriteMentioning)
}

func (c *Engine) postStageNoteWith(ctx context.Context, policy StageLabelPolicy, obs stageObservation, key, body string, write statusWriter) (int, error) {
if policy.QuietNotifications {
return c.writeStatusSection(ctx, obs.Owner, obs.Repo, obs.Number, key, body)
return c.writeStatusSectionWith(ctx, obs.Owner, obs.Repo, obs.Number, key, body, write)
}
if _, _, err := c.gh.Issues.CreateComment(ctx, obs.Owner, obs.Repo, obs.Number, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil {
return 0, err
}
return 1, nil
}

// writeStatusSection rewrites section key of the PR's hive status comment
// to text through prstatus.Write, the one status writer
// the GitHub client shares: it is serialised per PR, the edit is retried
// when the comment changed underneath, and the comment is created only when
// the PR has none. Returns the number of comments created.
func (c *Engine) writeStatusSection(ctx context.Context, owner, repo string, number int, key, text string) (int, error) {
// statusWriter is prstatus.Write or prstatus.WriteMentioning.
type statusWriter func(ctx context.Context, f prstatus.Forge, item, key, text string) (prstatus.WriteResult, error)

// writeStatusSectionWith rewrites section key of the PR's hive status
// comment to text through write (prstatus.Write or prstatus.WriteMentioning),
// the one status writer the GitHub client shares: it is serialised per PR,
// the edit is retried when the comment changed underneath, and the comment
// is created only when the PR has none. Returns the number of comments
// created.
func (c *Engine) writeStatusSectionWith(ctx context.Context, owner, repo string, number int, key, text string, write statusWriter) (int, error) {
f := &engineStatusForge{e: c, owner: owner, repo: repo, number: number}
res, err := prstatus.Write(ctx, f, prstatus.ItemKey(owner+"/"+repo, number), key, text)
res, err := write(ctx, f, prstatus.ItemKey(owner+"/"+repo, number), key, text)
if res.Created {
return 1, err
}
Expand Down
41 changes: 38 additions & 3 deletions src/pkg/prstatus/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"sort"
"strings"
"sync"

"github.com/hivecommons/hive/pkg/advisory"
)

// Comment is one issue/PR comment as the status writer sees it.
Expand Down Expand Up @@ -68,7 +70,26 @@ var (
// duplicates are reconciled: their sections are merged into the oldest
// hive-authored comment and the other hive-authored copies deleted. A
// comment the hive did not author is never edited or deleted.
//
// text is copied prose as far as Write is concerned: every @login in it is
// neutralised (advisory.NeutralizeMentions) so that a quoted title or
// comment never notifies the person named, and so are the bodies of
// foreign status comments merged into a hive-owned one. A section that
// deliberately mentions someone goes through WriteMentioning instead.
func Write(ctx context.Context, f Forge, item, key, text string) (WriteResult, error) {
return write(ctx, f, item, key, advisory.NeutralizeMentions(text))
}

// WriteMentioning is Write for the one kind of section that is meant to
// notify: text is posted verbatim, so a deliberate @login in it stays live.
// The caller owns the hygiene of that text and must neutralise any copied
// prose (check names, review quotes, titles) it composed into it. Foreign
// status comments merged into the hive-owned one are still neutralised.
func WriteMentioning(ctx context.Context, f Forge, item, key, text string) (WriteResult, error) {
return write(ctx, f, item, key, text)
}

func write(ctx context.Context, f Forge, item, key, text string) (WriteResult, error) {
unlock := lockItem(item)
defer unlock()
var res WriteResult
Expand All @@ -81,10 +102,12 @@ func Write(ctx context.Context, f Forge, item, key, text string) (WriteResult, e
return res, nil
}
// Foreign status comments are merged from but never edited, so a
// hive-owned comment is created to carry the merged sections.
// hive-owned comment is created to carry the merged sections. Their
// text becomes part of a body the hive owns and re-edits, so any
// live mention in it is neutralised on the way in.
bodies := make([]string, 0, len(status))
for _, c := range status {
bodies = append(bodies, c.Body)
bodies = append(bodies, foreignBody(c))
}
if err := f.CreateComment(ctx, Upsert(Merge(bodies...), key, text)); err != nil {
return res, err
Expand Down Expand Up @@ -141,7 +164,7 @@ func reconcile(ctx context.Context, f Forge, res *WriteResult) error {
continue
}
newer = append(newer, c)
others = append(others, c.Body)
others = append(others, foreignBody(c))
}
edited, err := editCompareAndRetry(ctx, f, oldest.ID, oldest.Body, func(cur string) string {
return Merge(append([]string{cur}, others...)...)
Expand All @@ -162,6 +185,18 @@ func reconcile(ctx context.Context, f Forge, res *WriteResult) error {
return nil
}

// foreignBody returns c's body as it may be merged into a hive-owned
// comment: a comment the hive did not author is neutralised, since its
// mentions would otherwise notify again on every later edit of the merged
// body; a hive-authored body is already hygienic (or deliberately
// mentioning) and is taken as is.
func foreignBody(c Comment) string {
if c.Own {
return c.Body
}
return advisory.NeutralizeMentions(c.Body)
}

// ownStatus returns the hive-authored comments of status, keeping order.
func ownStatus(status []Comment) []Comment {
var out []Comment
Expand Down
71 changes: 71 additions & 0 deletions src/pkg/prstatus/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,74 @@ func TestNoStatusWriterOutsideWrite(t *testing.T) {
t.Fatalf("hive:status comments must be written through prstatus.Write only:\n%s", strings.Join(offenders, "\n"))
}
}

func TestWriteNeutralisesIncidentalMentions(t *testing.T) {
f := &fakeForge{}
text := "Title: fix for @someuser's bug, contact bob@example.com"
if _, err := Write(context.Background(), f, "o/r#1", "k", text); err != nil {
t.Fatal(err)
}
if len(f.comments) != 1 {
t.Fatalf("comments = %d, want 1", len(f.comments))
}
body := f.comments[0].Body
if strings.Contains(body, "@someuser") {
t.Fatalf("live mention survived: %q", body)
}
if !strings.Contains(body, "`someuser`") {
t.Fatalf("login not preserved readably: %q", body)
}
if !strings.Contains(body, "bob@example.com") {
t.Fatalf("email address was altered: %q", body)
}
}

func TestWriteMentioningKeepsDeliberateMention(t *testing.T) {
f := &fakeForge{}
if _, err := WriteMentioning(context.Background(), f, "o/r#1", "k", "@author this PR is held"); err != nil {
t.Fatal(err)
}
if len(f.comments) != 1 || !strings.Contains(f.comments[0].Body, "@author this PR is held") {
t.Fatalf("deliberate mention must survive WriteMentioning: %+v", f.comments)
}
}

func TestWriteNeutralisesMergedForeignStatusBodies(t *testing.T) {
// Create path: the only status comment is foreign, so its sections are
// merged into the new hive-owned comment.
f := &fakeForge{}
f.add(Upsert("", "theirs", "see @victim for details"), false)
if _, err := Write(context.Background(), f, "o/r#1", "k", "ours"); err != nil {
t.Fatal(err)
}
var own []Comment
for _, c := range f.comments {
if c.Own {
own = append(own, c)
}
}
if len(own) != 1 {
t.Fatalf("own comments = %d, want 1", len(own))
}
if strings.Contains(own[0].Body, "@victim") {
t.Fatalf("foreign mention went live in the hive-owned comment: %q", own[0].Body)
}
if got, _ := Get(own[0].Body, "theirs"); !strings.Contains(got, "`victim`") {
t.Fatalf("foreign section not merged readably: %q", own[0].Body)
}
if strings.Contains(f.comments[0].Body, "`victim`") {
t.Fatalf("foreign comment must not be edited: %q", f.comments[0].Body)
}

// Reconcile path: a foreign status comment newer than the hive-owned one
// is merged into it.
f = &fakeForge{}
f.add(Upsert("", "k", "ours"), true)
f.add(Upsert("", "theirs", "ping @victim"), false)
if _, err := Reconcile(context.Background(), f, "o/r#1"); err != nil {
t.Fatal(err)
}
if b := f.comments[0].Body; strings.Contains(b, "@victim") || !strings.Contains(b, "`victim`") {
t.Fatalf("reconcile merged a live foreign mention: %q", b)
}
}
Loading