diff --git a/changelog.d/added-attention-pilot-issue-status-card.md b/changelog.d/added-attention-pilot-issue-status-card.md new file mode 100644 index 0000000000..51832d91cc --- /dev/null +++ b/changelog.d/added-attention-pilot-issue-status-card.md @@ -0,0 +1 @@ +- `github.notifications.attention_pilot` (default off) opts a hive in to the attention pilot ([#16358](https://github.com/hivecommons/hive/issues/16358), part of [#16270](https://github.com/hivecommons/hive/issues/16270)): routine issue notes — partial work, close/auto-close narration (merged fix, decomposed parent), reopened-after-merge, stage regressions, the covering-PR note and the blocker-settled note — fold into the issue's single `hive:status` card through the shared status writer, and a newly required action (confirming a merged fix) is still announced by exactly one notifying write. With the flag off nothing changes. diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index d2ff9c1ac9..8e742c2aab 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -1986,6 +1986,9 @@ func installReviewRelaySettings(client *github.Client, cfg *config.Config, logge // github.notifications.shadow (hivecommons/hive#16264): would-notify // instrumentation only, read live; nothing is suppressed. client.SetNotificationsShadow(func() bool { return cfg.GitHub.Notifications.Shadow }) + // github.notifications.attention_pilot (hivecommons/hive#16358): fold + // routine issue notes into the issue's hive:status card. Read live. + client.SetAttentionPilot(func() bool { return cfg.GitHub.Notifications.AttentionPilot }) // review.require_labels (PR approval allow-list): the relay's half of the // gate, read live so a Features-tab edit applies to the next request. client.SetReviewRequireLabels(func() []string { return cfg.Review.RequireLabels }) diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 81cf14d1be..25c43cc354 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -415,6 +415,7 @@ without a class. Review submissions and review requests are always counted as | `github.(*Client).SweepLegacyFleetReportIssues` | `status` | | | `github.(*Client).UpsertIssueMarkerComment` | `status` | passthrough wrapper; attributed to its caller | | `github.(*clientStatusForge).CreateComment` | `status` | passthrough wrapper (status-comment forge under `prstatus.Write`); attributed to its caller | +| `github.(*Client).PostIssueNote` | `status` | passthrough wrapper (issue status card, `attention_pilot`); attributed to its caller | | `github.(*Client).closeDecomposedParent` | `status` | | | `github.(*Client).closeIssueForMergedPRClaimWithIssue` | `status` | | | `github.(*Client).closeSupersededPRDecision` | `status` | | @@ -440,6 +441,7 @@ without a class. Review submissions and review requests are always counted as | `dashboard.(*Server).handleReviewPipelineSendToHuman` | `attention` | | | `dashboard.(*Server).reroutePickupLapsed` | `attention` | | | `dashboard.(*Server).settleRebaseMergeLedger` | `attention` | | +| `github.(*Client).PostIssueAttention` | `attention` | the one explicit announcement of a newly required action (`attention_pilot`) | | `github.(*Client).NudgeTrackingIssueClosingRefs` | `attention` | | | `github.(*Client).appendFoldedFinding` | `attention` | | | `github.(*Client).bindProwLgtm` | `attention` | | @@ -483,3 +485,57 @@ Go client; listed for completeness): | `promote-stable.yml` | `attention` | Emergency stable-promotion exception note. | | `weekly-competitor-report.md` (`.lock.yml`) | `status` | Weekly report comment on the tracking issue. | | `hive-ok-to-test.yml` | `protocol_command` | The `/ok-to-test` command that releases held workflow runs. | + +## Attention pilot and the issue status card (`github.notifications.attention_pilot`) + +The attention pilot is the opt-in gate for the attention changes in +[#16270](https://github.com/hivecommons/hive/issues/16270); every +attention-pilot behaviour reads this one flag. It is **off by default**, and +with it off the hive behaves exactly as before. + +```yaml +github: + notifications: + attention_pilot: true # default false +``` + +Quiet mode (`github.notifications.mode: quiet`) folds the hive's PR +bookkeeping into one edited `hive:status` comment but leaves issue notes as +comments of their own, so one issue lifecycle (partial merge, remainder, +close) could still email its watchers several times. With the pilot on, the +issue gets the same card, written through the same single status writer +(`prstatus.Write`, serialised per item, duplicates merged into the oldest): + +- **Folded into the card** (section key in brackets): partial work left by a + non-closing merged PR (`issue-partial:`), close/auto-close narration — + "Fixed by #N … Reply /reopen if the problem persists" and the decomposed + parent's all-children-delivered close — (`issue-close`), + reopened-after-merge (`issue-reopened`), a lapsed claim's stage regression + (`stage-regressed`), the covering-PR stage note (`issue-pr-link`) and the + blocker-settled note (`unblocked`, whatever `mode` says). Claim notes + already fold under `claim` in quiet mode. The legacy markers stay inside + each section, so every reader that greps for them still finds them, and + the reopen/release guidance stays visible on the card. +- **Native events notify instead.** The issue is still closed (with its + state reason) by the API call, which is GitHub's own notification; the + hive no longer adds a "for visibility" comment beside it. +- **A newly required action is still announced once.** Editing a comment + notifies nobody, so an action asked of a person (today: confirming a + merged fix with `/fixed` or `/reopen`) is recorded on the card under + `attention:` *and* announced by exactly one notifying write — + creating the card when the issue has none, otherwise one explicit + comment tagged ``. A later pass that + sees the tag only refreshes the card; a new cause gets its own single + announcement. The explicit comment consults the write-back gate like + every other unsolicited comment; a refusal is returned to the caller as + `writeback.ErrSuppressed` before anything is written (no comment, no tag + on the card), so the action is not reported as announced and the next + pass retries once the policy admits it. +- **Not folded:** the blocked sweep's re-target note (``) + stays a comment, because the sweep reads the *newest* blocked-on marker + by comment order and a section in an older card would not be newest. + +Acknowledge/snooze commands, reminders and the per-repo attention queue are +separate pilot steps ([#16359](https://github.com/hivecommons/hive/issues/16359), +[#16361](https://github.com/hivecommons/hive/issues/16361)–[#16363](https://github.com/hivecommons/hive/issues/16363)) +and are not part of this flag's first behaviour. diff --git a/src/docs/operator-reference/sweeps-and-operations.md b/src/docs/operator-reference/sweeps-and-operations.md index aa47ccbebc..6294f93ad7 100644 --- a/src/docs/operator-reference/sweeps-and-operations.md +++ b/src/docs/operator-reference/sweeps-and-operations.md @@ -594,6 +594,12 @@ exported on `/metrics`. See [GitHub writes: inventory and shadow mode](../notifications.md#github-writes-inventory-and-shadow-mode-githubnotificationsshadow) for the write-site inventory and how to compare baseline windows. +`github.notifications.attention_pilot: true` (default off) opts the hive in +to the attention pilot: routine issue notes fold into the issue's single +`hive:status` card, and a newly required action is still announced by +exactly one notifying write. See [Attention pilot and the issue status +card](../notifications.md#attention-pilot-and-the-issue-status-card-githubnotificationsattention_pilot). + ## Suspicious-activity alerts (`sentinel`) The sentinel evaluates open PRs in the watched repos — human, bot, or agent — diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index b49f26fa1f..58fe965a78 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5068-5078`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5075-5085`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/pkg/config/github_notifications.go b/src/pkg/config/github_notifications.go index 0a9e7541c2..6cf92826a1 100644 --- a/src/pkg/config/github_notifications.go +++ b/src/pkg/config/github_notifications.go @@ -31,6 +31,14 @@ type GitHubNotificationsConfig struct { // decision is recorded for repeats of the same condition. Measurement // only — nothing is suppressed or rerouted. Default off. Shadow bool `yaml:"shadow,omitempty" json:"shadow,omitempty"` + // AttentionPilot opts this hive in to the attention pilot + // (hivecommons/hive#16270): the single gate every attention-pilot + // change reads. With it on, routine issue notes (partial work, + // dependency progress, close/auto-close narration, regressions, PR + // links) fold into the issue's one hive:status card, and a newly + // required action is still announced by exactly one notifying write. + // Default off: behaviour is unchanged. + AttentionPilot bool `yaml:"attention_pilot,omitempty" json:"attention_pilot,omitempty"` } // Quiet reports whether the hive should fold its PR notes into one edited diff --git a/src/pkg/config/github_notifications_test.go b/src/pkg/config/github_notifications_test.go index 1cf95eab7a..a385e03e27 100644 --- a/src/pkg/config/github_notifications_test.go +++ b/src/pkg/config/github_notifications_test.go @@ -1,6 +1,10 @@ package config -import "testing" +import ( + "testing" + + "gopkg.in/yaml.v3" +) func TestGitHubNotificationsConfig(t *testing.T) { for mode, quiet := range map[string]bool{"": true, "quiet": true, "Quiet": true, "normal": false, "NORMAL": false} { @@ -22,3 +26,20 @@ func TestGitHubNotificationsShadowDefaultsOff(t *testing.T) { t.Fatal("github.notifications.shadow must default to off") } } + +func TestGitHubNotificationsAttentionPilotDefaultsOff(t *testing.T) { + if (GitHubNotificationsConfig{}).AttentionPilot { + t.Fatal("github.notifications.attention_pilot must default to off") + } + var c struct { + GitHub struct { + Notifications GitHubNotificationsConfig `yaml:"notifications"` + } `yaml:"github"` + } + if err := yaml.Unmarshal([]byte("github:\n notifications:\n attention_pilot: true\n"), &c); err != nil { + t.Fatal(err) + } + if !c.GitHub.Notifications.AttentionPilot { + t.Fatal("github.notifications.attention_pilot: true must parse as on") + } +} diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 2733e95fa0..74c60d7e26 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -198,6 +198,7 @@ evidence.complexity.static_analysis # TODO #11854 github.additional_bot_logins[] # TODO #11854 github.attention.admitter. # single-admitter ownership and flap window are YAML-only rollout controls; see src/docs/attention-episodes.md github.attention.flap_window # single-admitter ownership and flap window are YAML-only rollout controls; see src/docs/attention-episodes.md +github.notifications.attention_pilot # opt-in attention-pilot issue status card; yaml-only, see docs/notifications.md (#16358) github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 2dcba6e8e6..7cf1957651 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -286,6 +286,10 @@ type Client struct { // recorded in notificationShadow. nil reads as off. shadowNotificationsFn func() bool notificationShadow notificationShadow + // attentionPilotFn is github.notifications.attention_pilot, read live: + // when it returns true routine issue notes fold into the issue's + // hive:status card (issue_status_card.go). nil reads as off. + attentionPilotFn func() bool // reviewRequireLabelsFn returns review.require_labels, read live so a // Features-tab edit gates the next relay request without a rebuild. nil // or empty means the gate is off. diff --git a/src/pkg/github/close_on_merge.go b/src/pkg/github/close_on_merge.go index 7c19b57f9b..239bc97fda 100644 --- a/src/pkg/github/close_on_merge.go +++ b/src/pkg/github/close_on_merge.go @@ -15,6 +15,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/claims" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/prstatus" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -624,7 +625,11 @@ func (c *Client) closeIssueForMergedPRClaimWithIssue(ctx context.Context, issueR } if closeOnMergeReopenedAfter(events, opts.Identity) { res.Action, res.Reason = CloseOnMergeSkipped, "reopened_after_merge" - if _, _, err := c.client.Issues.CreateComment(WithRESTCaller(ctx, "hive:close_on_merge"), owner, repoName, issueNumber, &gh.IssueComment{Body: gh.Ptr(closeOnMergeReopenedComment(pr))}); err != nil && opts.Logger != nil { + body := closeOnMergeReopenedComment(pr) + if _, err := c.PostIssueNote(WithRESTCaller(ctx, "hive:close_on_merge"), issueRepo, issueNumber, prstatus.KeyIssueReopened, body, func(ctx context.Context) error { + _, _, err := c.client.Issues.CreateComment(ctx, owner, repoName, issueNumber, &gh.IssueComment{Body: gh.Ptr(body)}) + return err + }); err != nil && opts.Logger != nil { opts.Logger.Warn("close-on-merge: posting reopened-after-merge marker failed", "repo", issueRepo, "issue", issueNumber, "pr", pr.GetNumber(), "error", err) } return res @@ -636,7 +641,12 @@ func (c *Client) closeIssueForMergedPRClaimWithIssue(ctx context.Context, issueR return res } body := closeOnMergeAwaitingComment(pr) - if _, _, err := c.client.Issues.CreateComment(WithRESTCaller(ctx, "hive:close_on_merge"), owner, repoName, issueNumber, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + // Confirming the fix is an action asked of a person, so under the + // attention pilot it is announced once rather than only edited in. + if _, err := c.PostIssueAttention(WithRESTCaller(ctx, "hive:close_on_merge"), issueRepo, issueNumber, fmt.Sprintf("close-on-merge-awaiting-%d", pr.GetNumber()), body, func(ctx context.Context) error { + _, _, err := c.client.Issues.CreateComment(ctx, owner, repoName, issueNumber, &gh.IssueComment{Body: gh.Ptr(body)}) + return err + }); err != nil { res.Action, res.Reason = CloseOnMergeNoop, "awaiting_comment_failed" return res } @@ -658,7 +668,10 @@ func (c *Client) closeIssueForMergedPRClaimWithIssue(ctx context.Context, issueR // comment per issue is enough (hivecommons/hive#15727 vs #15843). if stageNoted { c.noteCommentSuppressed() - } else if _, _, err := c.client.Issues.CreateComment(WithRESTCaller(ctx, "hive:close_on_merge"), owner, repoName, issueNumber, &gh.IssueComment{Body: gh.Ptr(closeOnMergeCloseComment(pr))}); err != nil { + } else if _, err := c.PostIssueNote(WithRESTCaller(ctx, "hive:close_on_merge"), issueRepo, issueNumber, prstatus.KeyIssueClose, closeOnMergeCloseComment(pr), func(ctx context.Context) error { + _, _, err := c.client.Issues.CreateComment(ctx, owner, repoName, issueNumber, &gh.IssueComment{Body: gh.Ptr(closeOnMergeCloseComment(pr))}) + return err + }); err != nil { res.Action, res.Reason = CloseOnMergeNoop, "close_comment_failed" return res } diff --git a/src/pkg/github/decomposed_parents.go b/src/pkg/github/decomposed_parents.go index 5475e54d0e..22d2edab94 100644 --- a/src/pkg/github/decomposed_parents.go +++ b/src/pkg/github/decomposed_parents.go @@ -11,6 +11,7 @@ import ( "strings" gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/prstatus" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -296,7 +297,10 @@ func (c *Client) closeDecomposedParent(ctx context.Context, in IssueStageInput, if store != nil { store.Forget(key) } - if err := c.CreateIssueCommentBudgeted(ctx, in.Repo, in.Number, decomposedParentCloseComment(children, closers)); err != nil && logger != nil { + note := decomposedParentCloseComment(children, closers) + if _, err := c.PostIssueNote(ctx, in.Repo, in.Number, prstatus.KeyIssueClose, note, func(ctx context.Context) error { + return c.CreateIssueCommentBudgeted(ctx, in.Repo, in.Number, note) + }); err != nil && logger != nil { logger.Warn("issue stage labels: decomposed parent close comment failed", "repo", in.Repo, "issue", in.Number, "error", err) } if logger != nil { diff --git a/src/pkg/github/issue_blocked.go b/src/pkg/github/issue_blocked.go index c575bd4259..4a43559e47 100644 --- a/src/pkg/github/issue_blocked.go +++ b/src/pkg/github/issue_blocked.go @@ -661,7 +661,9 @@ func (c *Client) postUnblockedNote(ctx context.Context, repo string, number int, return } } - if c.notificationsQuiet() { + // The attention pilot folds dependency progress into the issue's + // status card whatever github.notifications.mode says. + if c.notificationsQuiet() || c.attentionPilot() { if created, err := c.UpsertPRStatusSection(ctx, repo, number, prstatus.KeyUnblocked, note); err != nil { logger.Warn("blocked sweep: unblock note not recorded on status comment", "repo", repo, "issue", number, "error", err) } else if !created { diff --git a/src/pkg/github/issue_stage_labels.go b/src/pkg/github/issue_stage_labels.go index dfd5365b1a..f24861c650 100644 --- a/src/pkg/github/issue_stage_labels.go +++ b/src/pkg/github/issue_stage_labels.go @@ -68,6 +68,7 @@ import ( gh "github.com/google/go-github/v72/github" "github.com/hivecommons/hive/pkg/authorkind" "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/prstatus" "github.com/hivecommons/hive/pkg/stageengine" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -604,7 +605,10 @@ func SyncIssueStageLabelsWith(ctx context.Context, client *Client, result *Actio // note; a covering PR's own falls are narrated on the PR. if tr.Regressed && !covered && tr.Prev.Before(stagelabels.CoveredByPR) { if rec, ok := store.Get(key); ok && !rec.RegressionCommented { - if err := client.CreateIssueComment(ctx, in.Repo, in.Number, stagelabels.RegressionComment(tr.Prev, tr.Next, reason)); err != nil { + note := stagelabels.RegressionComment(tr.Prev, tr.Next, reason) + if _, err := client.PostIssueNote(ctx, in.Repo, in.Number, prstatus.KeyStageRegressed, note, func(ctx context.Context) error { + return client.CreateIssueComment(ctx, in.Repo, in.Number, note) + }); err != nil { if logger != nil { logger.Warn("issue stage labels: regression comment failed", "repo", in.Repo, "issue", in.Number, "error", err) } @@ -680,7 +684,9 @@ func handleMergedPRIssueStage(ctx context.Context, client *Client, in IssueStage url = fmt.Sprintf("#%d", in.Claim.PRNumber) } body := fmt.Sprintf("%s\nPR #%d has merged: %s\n\nHive is moving this issue back to the actionable lane because the PR used a non-closing reference (`Refs` / `Part of`) and therefore landed partial work without closing the issue.", marker, in.Claim.PRNumber, url) - if err := client.CreateIssueComment(ctx, in.Repo, in.Number, body); err != nil { + if _, err := client.PostIssueNote(ctx, in.Repo, in.Number, prstatus.KeyIssuePartial(in.Claim.PRNumber), body, func(ctx context.Context) error { + return client.CreateIssueComment(ctx, in.Repo, in.Number, body) + }); err != nil { if logger != nil { logger.Warn("issue stage labels: merged partial PR comment failed", "repo", in.Repo, "issue", in.Number, "pr", in.Claim.PRNumber, "error", err) } @@ -706,7 +712,9 @@ func handleMergedPRIssueStage(ctx context.Context, client *Client, in IssueStage if strings.TrimSpace(in.Claim.PRURL) != "" { body = fmt.Sprintf("%s\nFixed by #%d (%s, merged). Closing because Hive's PR claim metadata says this PR was the full fix.", marker, in.Claim.PRNumber, in.Claim.PRURL) } - if err := client.CreateIssueComment(ctx, in.Repo, in.Number, body); err != nil { + if _, err := client.PostIssueNote(ctx, in.Repo, in.Number, prstatus.KeyIssueClose, body, func(ctx context.Context) error { + return client.CreateIssueComment(ctx, in.Repo, in.Number, body) + }); err != nil { if logger != nil { logger.Warn("issue stage labels: merged full-fix PR close comment failed", "repo", in.Repo, "issue", in.Number, "pr", in.Claim.PRNumber, "error", err) } @@ -766,7 +774,9 @@ func ensureIssueStagePRLink(ctx context.Context, client *Client, in IssueStageIn if !ok || rec.EntryCommented { return false, false, false } - if err := client.CreateIssueComment(ctx, in.Repo, in.Number, link.StageComment); err != nil { + if _, err := client.PostIssueNote(ctx, in.Repo, in.Number, prstatus.KeyIssuePRLink, link.StageComment, func(ctx context.Context) error { + return client.CreateIssueComment(ctx, in.Repo, in.Number, link.StageComment) + }); err != nil { owner, name := client.splitRepo(in.Repo) if client.noteArchivedWrite(strings.ToLower(owner+"/"+name), err) { if logger != nil { diff --git a/src/pkg/github/issue_status_card.go b/src/pkg/github/issue_status_card.go new file mode 100644 index 0000000000..0a47fe7cea --- /dev/null +++ b/src/pkg/github/issue_status_card.go @@ -0,0 +1,137 @@ +package github + +import ( + "context" + "fmt" + "strings" + + "github.com/hivecommons/hive/pkg/prstatus" + "github.com/hivecommons/hive/pkg/writeback" +) + +// The attention pilot (github.notifications.attention_pilot, +// hivecommons/hive#16358) is the opt-in gate every attention-pilot change +// reads. Its first effect is the issue-side status card: the routine notes +// the hive leaves on an issue (claim/release, partial work, dependency +// progress, close/auto-close narration) become sections of the issue's one +// hive:status comment, written through prstatus.Write like the PR card, so +// an issue's lifecycle emails its watchers once instead of once per note. +// A newly required action is the exception: it still gets exactly one +// explicit comment, because an edit notifies nobody. + +// SetAttentionPilot wires github.notifications.attention_pilot. Read live so +// a config reload applies to the next write. nil (nothing wired) is off. +func (c *Client) SetAttentionPilot(fn func() bool) { + if c == nil { + return + } + c.attentionPilotFn = fn +} + +// attentionPilot reports whether this hive opted in to the attention pilot. +func (c *Client) attentionPilot() bool { + return c != nil && c.attentionPilotFn != nil && c.attentionPilotFn() +} + +// PostIssueNote delivers a routine issue note. With the attention pilot off +// it runs legacy, the call site's own write, so behaviour is unchanged. +// With it on the note becomes section key of the issue's status card; the +// only comment ever created is the card itself. Reports whether a new +// comment was created. +func (c *Client) PostIssueNote(ctx context.Context, repo string, number int, key, body string, legacy func(context.Context) error) (bool, error) { + if c == nil { + return false, ErrNoGitHubClient + } + if !c.attentionPilot() { + return true, legacy(ctx) + } + created, err := c.UpsertPRStatusSection(ctx, repo, number, key, body) + if err == nil && !created { + c.noteCommentSuppressed() + } + return created, err +} + +// PostIssueAttention delivers a newly required action (cause names it, e.g. +// the PR whose merge awaits confirmation). With the attention pilot off it +// runs legacy. With it on the action is recorded on the status card and +// announced by exactly one notifying write: creating the card when the +// issue has none, otherwise one explicit comment tagged +// prstatus.IssueAttentionMarker(cause) — a card edit alone would reach +// nobody. A cause already announced is only refreshed on the card. Reports +// whether a new comment was created. +// +// The explicit comment consults the write-back gate. A refusal is returned +// as an error wrapping writeback.ErrSuppressed before anything is written: +// the card carries no marker, so the caller does not treat the action as +// announced and the next pass retries once the policy admits it. +func (c *Client) PostIssueAttention(ctx context.Context, repo string, number int, cause, body string, legacy func(context.Context) error) (bool, error) { + if c == nil { + return false, ErrNoGitHubClient + } + if !c.attentionPilot() { + return true, legacy(ctx) + } + marker := prstatus.IssueAttentionMarker(cause) + owner, name := c.splitRepo(repo) + comments, err := c.listIssueComments(ctx, owner, name, number) + if err != nil { + return false, err + } + announced, cardExists := false, false + for _, cm := range comments { + b := cm.GetBody() + if strings.Contains(b, marker) { + announced = true + } + if prstatus.IsStatusComment(b) { + cardExists = true + } + } + posted := false + // The explicit comment goes first: if the card edit then fails, the + // next pass finds the marker and only retries the edit, never a second + // announcement. A gate refusal returns before any write so the marker + // is never recorded for an announcement that did not happen. + if !announced && cardExists { + if err := c.issueAttentionAllowed(ctx, owner, name, number, repo, body); err != nil { + return false, err + } + if err := c.CreateIssueComment(WithNotificationSubject(ctx, prstatus.KeyIssueAttentionPrefix+cause), repo, number, marker+"\n"+body); err != nil { // writeback:gated — issueAttentionAllowed consulted the gate above + return false, err + } + posted = true + } + created, err := c.UpsertPRStatusSection(ctx, repo, number, prstatus.KeyIssueAttentionPrefix+cause, body+"\n"+marker) + if err == nil && !created && !posted { + c.noteCommentSuppressed() + } + return posted || created, err +} + +// issueAttentionAllowed consults the write-back gate for the explicit +// attention comment on an issue. A refusal is an error wrapping +// writeback.ErrSuppressed; a failed issue read is returned as is. Either +// way the caller writes nothing and retries on its next pass. +func (c *Client) issueAttentionAllowed(ctx context.Context, owner, name string, number int, repo, body string) error { + issue, _, _, err := c.getIssueWithBlockedCount(ctx, owner, name, number) + if err != nil { + return fmt.Errorf("issue attention %s#%d: reading issue: %w", repo, number, err) + } + if issue == nil { + return fmt.Errorf("issue attention %s#%d: reading issue: empty response", repo, number) + } + item := writeback.Item{ + Number: number, + Author: issue.GetUser().GetLogin(), + HiveAuthored: issue.GetUser().GetType() == "Bot" && c.IsHiveAuthorLogin(issue.GetUser().GetLogin()), + CreatedAt: issue.GetCreatedAt().Time, + } + for _, l := range issue.Labels { + item.Labels = append(item.Labels, l.GetName()) + } + if d := c.WritebackAllowed(repo, item, writeback.KindNeedsDecisionComment, body); !d.Allowed { + return fmt.Errorf("issue attention %s#%d: %w: %s", repo, number, writeback.ErrSuppressed, d.Reason) + } + return nil +} diff --git a/src/pkg/github/issue_status_card_test.go b/src/pkg/github/issue_status_card_test.go new file mode 100644 index 0000000000..53b3a0473e --- /dev/null +++ b/src/pkg/github/issue_status_card_test.go @@ -0,0 +1,239 @@ +package github + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "sync" + "testing" + + "github.com/hivecommons/hive/pkg/prstatus" + "github.com/hivecommons/hive/pkg/writeback" +) + +// github.notifications.attention_pilot off (the default, and nothing wired): +// every issue note goes through the call site's own write, exactly as +// before — one plain comment per note, no status card. +func TestIssueStatusCardPilotOffUnchanged(t *testing.T) { + ctx := context.Background() + for name, wire := range map[string]func(*Client){ + "unwired": func(*Client) {}, + "off": func(c *Client) { c.SetAttentionPilot(func() bool { return false }) }, + } { + t.Run(name, func(t *testing.T) { + s := &statusCommentServer{} + c := testClient(t, s.start(t).URL) + wire(c) + legacyCalls := 0 + legacy := func(body string) func(context.Context) error { + return func(ctx context.Context) error { + legacyCalls++ + return c.CreateIssueComment(ctx, "o/r", 5, body) + } + } + if _, err := c.PostIssueNote(ctx, "o/r", 5, prstatus.KeyIssueClose, "closed", legacy("closed")); err != nil { + t.Fatal(err) + } + if _, err := c.PostIssueAttention(ctx, "o/r", 5, "confirm-9", "please confirm", legacy("please confirm")); err != nil { + t.Fatal(err) + } + if legacyCalls != 2 || s.creates != 2 || s.edits != 0 { + t.Fatalf("legacy=%d creates=%d edits=%d, want both notes posted by their own write", legacyCalls, s.creates, s.edits) + } + for _, cm := range s.comments { + body, _ := cm["body"].(string) + if prstatus.IsStatusComment(body) || strings.Contains(body, "hive:attention") { + t.Fatalf("pilot off wrote a card or attention marker: %q", body) + } + } + }) + } +} + +// With the pilot on, several runtime writers on one issue — partial work, +// dependency progress, a stage regression, close narration — leave exactly +// one Hive status comment, created once; the rest is edits. None of them +// runs its legacy write. +func TestIssueStatusCardPilotFoldsRoutineNotes(t *testing.T) { + ctx := context.Background() + s := &statusCommentServer{} + c := testClient(t, s.start(t).URL) + c.SetAttentionPilot(func() bool { return true }) + logger := slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)) + noLegacy := func(context.Context) error { + t.Error("legacy write ran with the attention pilot on") + return nil + } + notes := map[string]string{ + prstatus.KeyIssuePartial(9): mergedPRPartialStageMarker + " pr=9 -->\nPR #9 has merged.", + prstatus.KeyStageRegressed: "stage regressed", + prstatus.KeyIssuePRLink: "covered by #9", + prstatus.KeyIssueClose: CloseOnMergeMarker + "\nFixed by #9. Closing. Reply /reopen if the problem persists.", + prstatus.KeyIssueReopened: closeOnMergeReopenedMarker(9) + "\nReopened by a person after #9 merged.", + prstatus.KeyIssuePartial(10): mergedPRPartialStageMarker + " pr=10 -->\nPR #10 has merged.", + } + // The blocked sweep's unblocked note folds too, with quiet mode off. + // It runs first: it stays silent on an issue whose card already says + // the merge closes it. + c.postUnblockedNote(ctx, "o/r", 5, blockedUnblockedMarker+"\nUnblocked: o/r#12 is no longer open.", logger) + var wg sync.WaitGroup + for key, body := range notes { + wg.Add(1) + go func(key, body string) { + defer wg.Done() + if _, err := c.PostIssueNote(ctx, "o/r", 5, key, body, noLegacy); err != nil { + t.Errorf("%s: %v", key, err) + } + }(key, body) + } + wg.Wait() + + if s.creates != 1 || len(s.comments) != 1 { + t.Fatalf("creates=%d comments=%d, want one status comment", s.creates, len(s.comments)) + } + body, _ := s.comments[0]["body"].(string) + if !prstatus.IsStatusComment(body) { + t.Fatalf("the one comment is not the status card: %q", body) + } + for key, want := range notes { + if got, ok := prstatus.Get(body, key); !ok || got != strings.TrimSpace(want) { + t.Errorf("section %s = %q, %v; want %q", key, got, ok, want) + } + } + if _, ok := prstatus.Get(body, prstatus.KeyUnblocked); !ok { + t.Error("unblocked note not folded into the card") + } + // Legacy marker readers still find their markers inside the card. + if !strings.Contains(body, CloseOnMergeMarker) || !strings.Contains(body, closeOnMergeReopenedMarker(9)) { + t.Errorf("legacy markers missing from card: %q", body) + } + + // Routine progress after the card exists creates nothing. + if _, err := c.PostIssueNote(ctx, "o/r", 5, prstatus.KeyStageRegressed, "stage regressed again", noLegacy); err != nil { + t.Fatal(err) + } + if s.creates != 1 { + t.Fatalf("creates=%d after routine progress, want still 1", s.creates) + } +} + +// A newly required action that arrives after the card exists is announced +// by exactly one explicit comment — an edit alone notifies nobody — and is +// recorded on the card. A repeat of the same cause posts nothing more. +func TestIssueStatusCardAttentionAfterCardExists(t *testing.T) { + ctx := context.Background() + s := &statusCommentServer{} + c := testClient(t, s.start(t).URL) + c.SetAttentionPilot(func() bool { return true }) + noLegacy := func(context.Context) error { + t.Error("legacy write ran with the attention pilot on") + return nil + } + if _, err := c.PostIssueNote(ctx, "o/r", 5, prstatus.KeyIssuePRLink, "covered by #9", noLegacy); err != nil { + t.Fatal(err) + } + if s.creates != 1 { + t.Fatalf("creates=%d, want the card", s.creates) + } + ask := "Fix merged in #9; awaiting confirmation. Reply /fixed when verified." + for i := 0; i < 3; i++ { + posted, err := c.PostIssueAttention(ctx, "o/r", 5, "confirm-9", ask, noLegacy) + if err != nil { + t.Fatal(err) + } + if posted != (i == 0) { + t.Fatalf("call %d: posted=%v", i, posted) + } + } + if s.creates != 2 || len(s.comments) != 2 { + t.Fatalf("creates=%d comments=%d, want the card plus exactly one attention comment", s.creates, len(s.comments)) + } + card, _ := s.comments[0]["body"].(string) + event, _ := s.comments[1]["body"].(string) + if prstatus.IsStatusComment(event) || !strings.Contains(event, prstatus.IssueAttentionMarker("confirm-9")) || !strings.Contains(event, ask) { + t.Fatalf("attention comment = %q", event) + } + if got, ok := prstatus.Get(card, prstatus.KeyIssueAttentionPrefix+"confirm-9"); !ok || !strings.Contains(got, ask) { + t.Fatalf("attention section = %q, %v", got, ok) + } + + // A different newly required action is its own single event. + if posted, err := c.PostIssueAttention(ctx, "o/r", 5, "confirm-10", "confirm #10", noLegacy); err != nil || !posted { + t.Fatalf("posted=%v err=%v", posted, err) + } + if s.creates != 3 { + t.Fatalf("creates=%d, want one more for the new cause", s.creates) + } +} + +// With no card yet, creating the card is the one notifying write for the +// action; no separate attention comment follows, now or on a repeat. +func TestIssueStatusCardAttentionCreatesCardOnce(t *testing.T) { + ctx := context.Background() + s := &statusCommentServer{} + c := testClient(t, s.start(t).URL) + c.SetAttentionPilot(func() bool { return true }) + noLegacy := func(context.Context) error { + t.Error("legacy write ran with the attention pilot on") + return nil + } + for i := 0; i < 2; i++ { + if _, err := c.PostIssueAttention(ctx, "o/r", 5, "confirm-9", "confirm #9", noLegacy); err != nil { + t.Fatal(err) + } + } + if s.creates != 1 || len(s.comments) != 1 { + t.Fatalf("creates=%d comments=%d, want only the card", s.creates, len(s.comments)) + } + body, _ := s.comments[0]["body"].(string) + if !prstatus.IsStatusComment(body) || !strings.Contains(body, prstatus.IssueAttentionMarker("confirm-9")) { + t.Fatalf("card = %q", body) + } +} + +// When the write-back gate refuses the explicit attention comment, the +// refusal surfaces as writeback.ErrSuppressed before anything is written: +// no comment, no marker on the card, so the caller does not report the +// action as announced. Once the policy admits the write, the next pass +// posts the one announcement. +func TestIssueStatusCardAttentionGateRefusalRetries(t *testing.T) { + ctx := context.Background() + s := &statusCommentServer{} + c := testClient(t, s.start(t).URL) + c.SetAttentionPilot(func() bool { return true }) + noLegacy := func(context.Context) error { + t.Error("legacy write ran with the attention pilot on") + return nil + } + if _, err := c.PostIssueNote(ctx, "o/r", 5, prstatus.KeyIssuePRLink, "covered by #9", noLegacy); err != nil { + t.Fatal(err) + } + c.SetWritebackGate(writeback.New(writeback.Config{}, writeback.Deps{RepoPause: func(string) (writeback.RepoPauseInfo, bool) { + return writeback.RepoPauseInfo{By: "op", Reason: "paused"}, true + }}, "")) + posted, err := c.PostIssueAttention(ctx, "o/r", 5, "confirm-9", "confirm #9", noLegacy) + if posted || !errors.Is(err, writeback.ErrSuppressed) { + t.Fatalf("refused attention: posted=%v err=%v, want ErrSuppressed", posted, err) + } + if s.creates != 1 || s.edits != 0 { + t.Fatalf("creates=%d edits=%d after refusal, want nothing written", s.creates, s.edits) + } + card, _ := s.comments[0]["body"].(string) + if strings.Contains(card, prstatus.IssueAttentionMarker("confirm-9")) { + t.Fatalf("refused announcement left its marker on the card: %q", card) + } + + c.SetWritebackGate(nil) + posted, err = c.PostIssueAttention(ctx, "o/r", 5, "confirm-9", "confirm #9", noLegacy) + if err != nil || !posted { + t.Fatalf("admitted attention: posted=%v err=%v", posted, err) + } + if s.creates != 2 { + t.Fatalf("creates=%d, want the card plus one attention comment", s.creates) + } + if posted, err := c.PostIssueAttention(ctx, "o/r", 5, "confirm-9", "confirm #9", noLegacy); err != nil || posted || s.creates != 2 { + t.Fatalf("repeat: posted=%v err=%v creates=%d", posted, err, s.creates) + } +} diff --git a/src/pkg/github/notification_write_sites.go b/src/pkg/github/notification_write_sites.go index 5cee988c5b..4cf02f14bf 100644 --- a/src/pkg/github/notification_write_sites.go +++ b/src/pkg/github/notification_write_sites.go @@ -28,6 +28,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "main.liveTriageCommenter.CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "github.(*Client).UpsertIssueMarkerComment": {Class: NotificationClassStatus, Passthrough: true}, "github.(*clientStatusForge).CreateComment": {Class: NotificationClassStatus, Passthrough: true}, + "github.(*Client).PostIssueNote": {Class: NotificationClassStatus, Passthrough: true}, // status: bookkeeping readable on demand. "dashboard.(*ContributeWSHub).markAlreadyDoneIssue": {Class: NotificationClassStatus}, @@ -73,6 +74,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "dashboard.(*Server).handleReviewPipelineSendToHuman": {Class: NotificationClassAttention}, "dashboard.(*Server).reroutePickupLapsed": {Class: NotificationClassAttention}, "dashboard.(*Server).settleRebaseMergeLedger": {Class: NotificationClassAttention}, + "github.(*Client).PostIssueAttention": {Class: NotificationClassAttention}, "github.(*Client).NudgeTrackingIssueClosingRefs": {Class: NotificationClassAttention}, "github.(*Client).appendFoldedFinding": {Class: NotificationClassAttention}, "github.(*Client).bindProwLgtm": {Class: NotificationClassAttention}, diff --git a/src/pkg/github/pr_status_comment_test.go b/src/pkg/github/pr_status_comment_test.go index 3bccbbd9ef..40ffd15f28 100644 --- a/src/pkg/github/pr_status_comment_test.go +++ b/src/pkg/github/pr_status_comment_test.go @@ -7,6 +7,8 @@ import ( "net/http/httptest" "os" "path/filepath" + "regexp" + "strconv" "strings" "sync" "testing" @@ -17,7 +19,9 @@ import ( // statusCommentServer is a GitHub stand-in that keeps issue comments: POST // appends, PATCH rewrites, GET lists. It counts creates and edits so a test -// can prove the second write edited in place instead of posting again. +// can prove the second write edited in place instead of posting again. GET +// of the issue itself answers with a plain open issue by a human, so a +// writer that consults the write-back gate can build its item. type statusCommentServer struct { mu sync.Mutex comments []map[string]any @@ -26,6 +30,8 @@ type statusCommentServer struct { deletes []string } +var issuePathRe = regexp.MustCompile(`^/repos/[^/]+/[^/]+/issues/(\d+)$`) + func (s *statusCommentServer) start(t *testing.T) *httptest.Server { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -33,6 +39,9 @@ func (s *statusCommentServer) start(t *testing.T) *httptest.Server { defer s.mu.Unlock() w.Header().Set("Content-Type", "application/json") switch { + case r.Method == http.MethodGet && issuePathRe.MatchString(r.URL.Path): + n, _ := strconv.Atoi(issuePathRe.FindStringSubmatch(r.URL.Path)[1]) + _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "user": map[string]any{"login": "alice", "type": "User"}, "labels": []any{}}) case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/comments"): _ = json.NewEncoder(w).Encode(s.comments) case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/comments"): diff --git a/src/pkg/prstatus/issue.go b/src/pkg/prstatus/issue.go new file mode 100644 index 0000000000..3a49e5d048 --- /dev/null +++ b/src/pkg/prstatus/issue.go @@ -0,0 +1,41 @@ +package prstatus + +import ( + "fmt" + "strings" +) + +// Section keys of the issue-side status card (github.notifications. +// attention_pilot, hivecommons/hive#16358). Each replaces a routine issue +// note that used to be its own comment; as with the PR keys, the legacy +// marker stays inside the section text so marker readers still find it. +const ( + // KeyIssueClose is close/auto-close narration: "Fixed by #N", + // awaiting-confirmation and reopened-after-merge notes + // (). The native close event is what + // notifies; the card keeps the /reopen guidance. + KeyIssueClose = "issue-close" + // KeyIssueReopened records that a person reopened the issue after a + // merge, so Hive will not close it for that PR again. + KeyIssueReopened = "issue-reopened" + // KeyIssuePartialPrefix + PR number is the partial-work/remainder note + // a non-closing merged PR leaves on the issue. + KeyIssuePartialPrefix = "issue-partial:" + // KeyIssuePRLink is the stage note naming the PR that covers the issue. + KeyIssuePRLink = "issue-pr-link" + // KeyIssueAttentionPrefix + cause is a newly required action recorded + // on the card; IssueAttentionMarker tags the one explicit comment that + // announces it. + KeyIssueAttentionPrefix = "attention:" +) + +// IssueAttentionMarker tags the one explicit attention comment posted for +// cause, so a later pass that sees it never posts a second. +func IssueAttentionMarker(cause string) string { + return fmt.Sprintf("", strings.TrimSpace(cause)) +} + +// KeyIssuePartial is the partial-work section key for pr. +func KeyIssuePartial(pr int) string { + return fmt.Sprintf("%s%d", KeyIssuePartialPrefix, pr) +}