diff --git a/changelog.d/added-rfc-notify-cards.md b/changelog.d/added-rfc-notify-cards.md new file mode 100644 index 0000000000..506fb2eda7 --- /dev/null +++ b/changelog.d/added-rfc-notify-cards.md @@ -0,0 +1 @@ +- Render RFC lifecycle notices as Discord summary-card embeds alongside transition text when `rfc_format: card` is configured on the designated announcer. diff --git a/src/cmd/hive/rfcnotify_wire.go b/src/cmd/hive/rfcnotify_wire.go index 0733302f89..169716b80d 100644 --- a/src/cmd/hive/rfcnotify_wire.go +++ b/src/cmd/hive/rfcnotify_wire.go @@ -30,6 +30,7 @@ const rfcRepoVisibilityTTL = time.Hour // poster, built once from the config that enabled them. type rfcNotifyState struct { sweeper *rfcnotify.Sweeper + pub rfcnotify.Publisher post rfcnotify.Poster // channel the poster was built for; a config change rebuilds it. channel string @@ -45,9 +46,11 @@ type rfcNotifyState struct { // statePath is rfcNotifyStatePath in production; tests point it at a // temp dir. statePath string - // newPoster builds the Discord poster; nil means discordRFCPoster. + // newPoster builds the Discord poster; nil builds botPublisher. // Tests inject a recorder. newPoster func(token, channel string) rfcnotify.Poster + // newPublisher builds the Discord publisher; nil adapts newPoster or builds botPublisher. + newPublisher func(token, channel string) rfcnotify.Publisher } // rfcNotifyState lazily builds the boot's notice state. @@ -99,10 +102,6 @@ func (s *rfcNotifyState) ensure(cfg *config.Config, repos int, logger *slog.Logg if !ok { return false } - newPoster := s.newPoster - if newPoster == nil { - newPoster = discordRFCPoster(logger) - } gates := rfcNotifyGatesFor(cfg, repos) if s.sweeper == nil || s.gates != gates { s.sweeper = rfcnotify.NewSweeper(rfcnotify.Options{ @@ -117,20 +116,36 @@ func (s *rfcNotifyState) ensure(cfg *config.Config, repos int, logger *slog.Logg }) s.gates = gates } - if s.post == nil || s.channel != channel { - s.post = newPoster(token, channel) + if s.pub == nil || s.channel != channel { + if s.newPublisher != nil { + s.pub = s.newPublisher(token, channel) + s.post = func(content string) error { return s.pub.Post(content) } + } else if s.newPoster != nil { + p := s.newPoster(token, channel) + s.post = p + s.pub = p + } else { + bot := discord.NewBot(discord.Config{Token: token}, logger) + s.pub = botPublisher{bot: bot, channel: channel} + s.post = func(content string) error { return bot.SendMessageTo(channel, content) } + } s.channel = channel } return true } -// discordRFCPoster posts through the bot token to the RFC channel without -// starting the command bot. -func discordRFCPoster(logger *slog.Logger) func(token, channel string) rfcnotify.Poster { - return func(token, channel string) rfcnotify.Poster { - bot := discord.NewBot(discord.Config{Token: token}, logger) - return func(content string) error { return bot.SendMessageTo(channel, content) } - } +// botPublisher adapts discord.Bot to rfcnotify.Publisher. +type botPublisher struct { + bot *discord.Bot + channel string +} + +func (p botPublisher) Post(content string) error { + return p.bot.SendMessageTo(p.channel, content) +} + +func (p botPublisher) PostCard(content string, embed rfcnotify.Embed) (string, error) { + return p.bot.SendEmbedTo(p.channel, content, embed) } type rfcRepoVisibility struct { @@ -321,6 +336,7 @@ func rfcNotifyIssues(snaps []github.IssueSnapshot) []rfcnotify.Issue { out = append(out, rfcnotify.Issue{ Repo: s.Repo, Number: s.Number, Title: s.Title, URL: s.URL, Author: s.Author, State: s.State, StateReason: s.StateReason, Labels: s.Labels, CreatedAt: s.CreatedAt, + Body: s.Body, }) } return out @@ -337,7 +353,7 @@ func runRFCNotifySweep(ctx context.Context, src rfcnotify.Source, repos int, cfg if src == nil || state == nil || !state.ensure(cfg, repos, logger) { return rfcnotify.Result{} } - res, err := state.sweeper.Run(ctx, src, state.post) + res, err := state.sweeper.Run(ctx, src, state.pub) if err != nil { logger.Warn("rfc notify sweep failed", "error", err) return res diff --git a/src/cmd/hive/rfcnotify_wire_test.go b/src/cmd/hive/rfcnotify_wire_test.go index ccaca92950..3d02d712f7 100644 --- a/src/cmd/hive/rfcnotify_wire_test.go +++ b/src/cmd/hive/rfcnotify_wire_test.go @@ -451,3 +451,76 @@ func TestRunRFCNotifySweepRFCPRs(t *testing.T) { t.Fatalf("merge: %+v posted=%q", res, posted) } } + +func TestRFCNotifyIssues_MapsBody(t *testing.T) { + snaps := []github.IssueSnapshot{ + { + Repo: "o/r", + Number: 42, + Title: "RFC: Test", + Body: "| Target | v5 |\n\n## Summary\nHello", + }, + } + issues := rfcNotifyIssues(snaps) + if len(issues) != 1 { + t.Fatalf("len(issues) = %d, want 1", len(issues)) + } + if issues[0].Body != snaps[0].Body { + t.Errorf("Body = %q, want %q", issues[0].Body, snaps[0].Body) + } +} + +type testCardPublisher struct { + posted []string + cards []rfcnotify.Embed +} + +func (p *testCardPublisher) Post(content string) error { + p.posted = append(p.posted, content) + return nil +} + +func (p *testCardPublisher) PostCard(content string, embed rfcnotify.Embed) (string, error) { + p.cards = append(p.cards, embed) + return "msg-id-1", nil +} + +func TestRFCNotifyWire_CardFormatPostsEmbed(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + cfg := &config.Config{ + Notifications: config.NotificationsConfig{ + Discord: &config.DiscordConfig{ + BotToken: "tok", + RFCChannelID: "chan", + RFCFormat: "card", + RFCAnnouncer: true, + }, + }, + } + pub := &testCardPublisher{} + state := &rfcNotifyState{ + statePath: filepath.Join(t.TempDir(), "rfc-notify.json"), + newPublisher: func(token, channel string) rfcnotify.Publisher { + return pub + }, + } + src := &rfcNotifyFakeSource{ + open: []rfcnotify.Issue{{Repo: "o/r", Number: 1, Title: "Existing RFC", State: "open", Labels: []string{"rfc"}}}, + } + ctx := context.Background() + runRFCNotifySweep(ctx, src, 1, cfg, nil, state, logger) + + body := "| Field | Value |\n| --- | --- |\n| Target | v5 |\n| Status | Proposal |\n\n## Summary\nTest summary\n\n## Decisions for maintainers\n1. Question\n" + src.updated = []rfcnotify.Issue{ + {Repo: "o/r", Number: 2, Title: "RFC: Rich Card", URL: "https://x/2", State: "open", CreatedAt: time.Now().Add(time.Hour), Body: body}, + } + forcePoll(state) + runRFCNotifySweep(ctx, src, 1, cfg, nil, state, logger) + + if len(pub.cards) != 1 { + t.Fatalf("cards = %d, want 1", len(pub.cards)) + } + if pub.cards[0].Title != "#2 RFC: Rich Card" { + t.Errorf("card.Title = %q", pub.cards[0].Title) + } +} diff --git a/src/docs/notifications.md b/src/docs/notifications.md index f0adf091b2..f2d9f01c11 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -210,7 +210,7 @@ These keys sit next to `rfc_channel_id`. All of them default off, and with none | Key | Default | Effect | | --- | --- | --- | -| `rfc_format` | `""` (= `line`) | `line` posts one line per transition. `card` selects rich mode; card rendering lands in a later change. Any other value is a config error. | +| `rfc_format` | `""` (= `line`) | `line` posts one line per transition. `card` posts the transition text (including a linked RFC for accepted documents) alongside a Discord summary card (embed) with target, status, scrubbed summary, open-decision count and colour by state (held grey, needs-decision amber, ready green, closed completed blue, closed not-planned dark); malformed bodies fall back to the line. Any other value is a config error. | | `rfc_threads` | `false` | Rich mode: one Discord thread per RFC (rendering lands later). | | `rfc_announcer` | `false` | Marks this hive as the one designated announcer for `rfc_channel_id`. Rich mode posts only from the announcer. | | `rfc_backlink_comment` | `false` | Parsed now; a later change uses it to comment the thread link back on the RFC. | diff --git a/src/pkg/dashboard/api_event_triggers_test.go b/src/pkg/dashboard/api_event_triggers_test.go index 926b33718d..a5d04eead8 100644 --- a/src/pkg/dashboard/api_event_triggers_test.go +++ b/src/pkg/dashboard/api_event_triggers_test.go @@ -174,7 +174,10 @@ func TestEventTriggersRejectInvalidAndUnpersistedRules(t *testing.T) { t.Fatalf("failed persistence accepted: %d %s", failed.Code, failed.Body.String()) } cfg.SourcePath = t.TempDir() - config.RuntimeConfigFile, config.DashboardOverlayFile = t.TempDir(), t.TempDir() + // Save removes an empty runtime-path directory and retries successfully. + // A missing parent keeps the fallback unwritable after that retry. + unwritable := filepath.Join(t.TempDir(), "missing") + config.RuntimeConfigFile, config.DashboardOverlayFile = filepath.Join(unwritable, "runtime"), filepath.Join(unwritable, "overlay") failed = putEventTriggers(s, `{"rules":[]}`, version) if failed.Code != http.StatusInternalServerError || !reflect.DeepEqual(cfg.TriggerRulesSnapshot(), before) || strings.Contains(failed.Body.String(), cfg.SourcePath) { diff --git a/src/pkg/discord/bot.go b/src/pkg/discord/bot.go index c123a32254..594cb19404 100644 --- a/src/pkg/discord/bot.go +++ b/src/pkg/discord/bot.go @@ -9,6 +9,7 @@ import ( "log/slog" "net/http" "net/url" + "strconv" "strings" "sync" "time" @@ -98,6 +99,7 @@ type Bot struct { mu sync.RWMutex logger *slog.Logger client *http.Client + sleep func(time.Duration) msgQueue chan msgItem lastState *statusSnapshot @@ -193,45 +195,154 @@ func (b *Bot) SendMessage(content string) error { return b.SendMessageTo(b.channelID, content) } +// Embed represents a Discord embed object. +type Embed struct { + Title string `json:"title,omitempty"` + Description string `json:"description,omitempty"` + URL string `json:"url,omitempty"` + Color int `json:"color,omitempty"` + Author *EmbedAuthor `json:"author,omitempty"` + Fields []EmbedField `json:"fields,omitempty"` + Footer *EmbedFooter `json:"footer,omitempty"` + Timestamp string `json:"timestamp,omitempty"` +} + +// EmbedAuthor is the author field of a Discord embed. +type EmbedAuthor struct { + Name string `json:"name,omitempty"` + URL string `json:"url,omitempty"` + IconURL string `json:"icon_url,omitempty"` +} + +// EmbedField is a name/value field within a Discord embed. +type EmbedField struct { + Name string `json:"name"` + Value string `json:"value"` + Inline bool `json:"inline,omitempty"` +} + +// EmbedFooter is the footer field of a Discord embed. +type EmbedFooter struct { + Text string `json:"text"` + IconURL string `json:"icon_url,omitempty"` +} + +const maxDiscordRetryAfter = 5 * time.Second + // SendMessageTo posts content to an arbitrary channel the bot token can // write to, bypassing the status channel and the drain queue. It works on a // Bot that was never started, so a feature that only needs to post (RFC // lifecycle notices, pkg/rfcnotify) can share the token without running the // command loops. func (b *Bot) SendMessageTo(channelID, content string) error { - if strings.TrimSpace(channelID) == "" { - return fmt.Errorf("discord send: channel id not configured") + payload := map[string]any{ + "content": content, } + _, err := b.postMessage(channelID, payload) + return err +} + +// SendEmbedTo posts an embed (and optional content) to an arbitrary channel +// the bot token can write to. It always sets allowed_mentions: {parse: []} so +// user text never pings roles, users or @everyone, and returns the created +// message ID. +func (b *Bot) SendEmbedTo(channelID, content string, embed Embed) (string, error) { payload := map[string]any{ - "content": content, - "allowed_mentions": map[string]any{"parse": []string{}}, + "embeds": []Embed{embed}, + } + if content != "" { + payload["content"] = content } + return b.postMessage(channelID, payload) +} + +func (b *Bot) postMessage(channelID string, payload map[string]any) (string, error) { + if strings.TrimSpace(channelID) == "" { + return "", fmt.Errorf("discord send: channel id not configured") + } + if payload == nil { + payload = make(map[string]any) + } + payload["allowed_mentions"] = map[string]any{"parse": []string{}} data, err := json.Marshal(payload) if err != nil { - return err + return "", err } url := fmt.Sprintf("%s/channels/%s/messages", discordAPIBase, channelID) - req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) - if err != nil { - return err - } - req.Header.Set("Authorization", "Bot "+b.token) - req.Header.Set("Content-Type", "application/json") + doRequest := func() (*http.Response, []byte, error) { + req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) + if err != nil { + return nil, nil, err + } - resp, err := b.client.Do(req) + req.Header.Set("Authorization", "Bot "+b.token) + req.Header.Set("Content-Type", "application/json") + + resp, err := b.client.Do(req) + if err != nil { + return nil, nil, fmt.Errorf("discord send: %w", err) + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, nil, fmt.Errorf("discord read body: %w", err) + } + return resp, body, nil + } + + resp, body, err := doRequest() if err != nil { - return fmt.Errorf("discord send: %w", err) + return "", err + } + + if resp.StatusCode == http.StatusTooManyRequests { + retryAfter := parseDiscordRetryAfter(resp.Header.Get("Retry-After"), body) + if retryAfter <= 0 { + retryAfter = 100 * time.Millisecond + } + if retryAfter > maxDiscordRetryAfter { + retryAfter = maxDiscordRetryAfter + } + if b.sleep != nil { + b.sleep(retryAfter) + } else { + time.Sleep(retryAfter) + } + resp, body, err = doRequest() + if err != nil { + return "", err + } } - defer func() { _ = resp.Body.Close() }() if resp.StatusCode >= 400 { - body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("discord API %d: %s", resp.StatusCode, string(body)) + return "", fmt.Errorf("discord API %d: %s", resp.StatusCode, string(body)) } - return nil + var created struct { + ID string `json:"id"` + } + if err := json.Unmarshal(body, &created); err == nil && created.ID != "" { + return created.ID, nil + } + return "", nil +} + +func parseDiscordRetryAfter(header string, body []byte) time.Duration { + var rl struct { + RetryAfter float64 `json:"retry_after"` + } + if err := json.Unmarshal(body, &rl); err == nil && rl.RetryAfter > 0 { + return time.Duration(rl.RetryAfter * float64(time.Second)) + } + if header = strings.TrimSpace(header); header != "" { + if f, err := strconv.ParseFloat(header, 64); err == nil && f > 0 { + return time.Duration(f * float64(time.Second)) + } + } + return 0 } func (b *Bot) enqueue(content string) { diff --git a/src/pkg/discord/bot_test.go b/src/pkg/discord/bot_test.go index 23cd1c33fa..5bf812bfa1 100644 --- a/src/pkg/discord/bot_test.go +++ b/src/pkg/discord/bot_test.go @@ -55,9 +55,11 @@ func newTestBot(ts *httptest.Server, channelID string) *Bot { AllowedUsers: []string{"uid", "u1"}, }, slog.New(slog.NewTextHandler(io.Discard, nil))) - b.client = &http.Client{ - Transport: &redirectTransport{target: ts.URL}, - Timeout: httpTimeoutS * time.Second, + if ts != nil { + b.client = &http.Client{ + Transport: &redirectTransport{target: ts.URL}, + Timeout: httpTimeoutS * time.Second, + } } return b @@ -1118,3 +1120,137 @@ func TestSendMessageTo_SuppressesMentions(t *testing.T) { t.Errorf("allowed_mentions.parse = %#v, want empty non-nil", got.AllowedMentions.Parse) } } + +func TestSendEmbedTo_PayloadAndAllowedMentions(t *testing.T) { + var body []byte + var gotPath string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + body, _ = io.ReadAll(r.Body) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id": "msg-embed-987"}`)) + })) + defer ts.Close() + + b := newTestBot(ts, "status-channel") + embed := Embed{ + Title: "#15869 RFC: Richer RFC publishing @everyone <@&999>", + Description: "A summary with @here", + URL: "https://github.com/hivecommons/hive/issues/15869", + Color: 0x95a5a6, + Author: &EmbedAuthor{Name: "hanthor"}, + Fields: []EmbedField{ + {Name: "Target", Value: "v5", Inline: true}, + {Name: "Status", Value: "Proposal, not accepted", Inline: true}, + }, + } + + msgID, err := b.SendEmbedTo("rfc-channel", "RFC notice: @everyone", embed) + if err != nil { + t.Fatalf("SendEmbedTo failed: %v", err) + } + if msgID != "msg-embed-987" { + t.Errorf("msgID = %q, want msg-embed-987", msgID) + } + if !strings.HasSuffix(gotPath, "/channels/rfc-channel/messages") { + t.Errorf("path = %q, want rfc-channel", gotPath) + } + + var got struct { + Content string `json:"content"` + Embeds []Embed `json:"embeds"` + AllowedMentions struct { + Parse []string `json:"parse"` + } `json:"allowed_mentions"` + } + if err := json.Unmarshal(body, &got); err != nil { + t.Fatalf("unmarshal body: %v", err) + } + if got.Content != "RFC notice: @everyone" { + t.Errorf("content = %q", got.Content) + } + if len(got.Embeds) != 1 { + t.Fatalf("len(embeds) = %d, want 1", len(got.Embeds)) + } + if got.Embeds[0].Title != embed.Title { + t.Errorf("embed.Title = %q, want %q", got.Embeds[0].Title, embed.Title) + } + if got.Embeds[0].Color != 0x95a5a6 { + t.Errorf("embed.Color = %x, want 0x95a5a6", got.Embeds[0].Color) + } + if !strings.Contains(string(body), `"allowed_mentions":{"parse":[]}`) { + t.Errorf("allowed_mentions.parse must be an empty array, body: %s", body) + } + if got.AllowedMentions.Parse == nil || len(got.AllowedMentions.Parse) != 0 { + t.Errorf("allowed_mentions.parse = %#v, want empty non-nil", got.AllowedMentions.Parse) + } +} + +func TestSendEmbedTo_EmptyChannelFails(t *testing.T) { + b := newTestBot(nil, "chan") + if _, err := b.SendEmbedTo(" ", "", Embed{Title: "t"}); err == nil { + t.Fatal("expected error on empty channel") + } +} + +func TestSendEmbedTo_RateLimit429RetrySuccess(t *testing.T) { + attempts := 0 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempts++ + if attempts == 1 { + w.Header().Set("Retry-After", "0.01") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"message": "rate limited", "retry_after": 0.01}`)) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id": "msg-after-retry"}`)) + })) + defer ts.Close() + + b := newTestBot(ts, "status") + var slept time.Duration + b.sleep = func(d time.Duration) { slept += d } + + msgID, err := b.SendEmbedTo("rfc-chan", "", Embed{Title: "RFC"}) + if err != nil { + t.Fatalf("expected retry to succeed: %v", err) + } + if msgID != "msg-after-retry" { + t.Errorf("msgID = %q, want msg-after-retry", msgID) + } + if attempts != 2 { + t.Errorf("attempts = %d, want 2", attempts) + } + if slept <= 0 { + t.Errorf("expected sleep on 429, slept = %v", slept) + } +} + +func TestSendEmbedTo_RateLimit429RetryPersistentFailure(t *testing.T) { + attempts := 0 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempts++ + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"message": "persistent rate limit", "retry_after": 0.01}`)) + })) + defer ts.Close() + + b := newTestBot(ts, "status") + b.sleep = func(time.Duration) {} + + _, err := b.SendEmbedTo("rfc-chan", "", Embed{Title: "RFC"}) + if err == nil { + t.Fatal("expected error after persistent 429") + } + if attempts != 2 { + t.Errorf("attempts = %d, want exactly 2 (at most one retry)", attempts) + } + if !strings.Contains(err.Error(), "429") { + t.Errorf("err = %v, want 429", err) + } +} diff --git a/src/pkg/github/issue_snapshots.go b/src/pkg/github/issue_snapshots.go index 73c922396d..db1641f773 100644 --- a/src/pkg/github/issue_snapshots.go +++ b/src/pkg/github/issue_snapshots.go @@ -19,6 +19,8 @@ type IssueSnapshot struct { Title string URL string Author string + // Body is the issue's markdown description. + Body string // State is "open" or "closed". State string // StateReason is GitHub's state_reason: "completed", "not_planned", @@ -87,6 +89,7 @@ func issueSnapshotFrom(repo string, issue *gh.Issue) IssueSnapshot { Title: issue.GetTitle(), URL: issue.GetHTMLURL(), Author: safeGetLogin(issue.GetUser()), + Body: issue.GetBody(), State: strings.ToLower(issue.GetState()), StateReason: strings.ToLower(issue.GetStateReason()), Labels: issueLabelNames(issue.Labels), diff --git a/src/pkg/rfcnotify/card.go b/src/pkg/rfcnotify/card.go new file mode 100644 index 0000000000..1ed04800f8 --- /dev/null +++ b/src/pkg/rfcnotify/card.go @@ -0,0 +1,334 @@ +package rfcnotify + +import ( + "fmt" + "regexp" + "strings" + + "github.com/hivecommons/hive/crux/logscrub" + "github.com/hivecommons/hive/pkg/discord" +) + +// Embed is an alias for discord.Embed. +type Embed = discord.Embed + +// Colors for RFC status cards in Discord. +const ( + ColorHeld = 0x95a5a6 // grey + ColorNeedsDecision = 0xf1c40f // amber + ColorReady = 0x2ecc71 // green + ColorCompleted = 0x3498db // blue + ColorNotPlanned = 0x2c2f33 // dark +) + +// Discord embed text limits. +const ( + MaxTitleRunes = 256 + MaxDescriptionRunes = 4096 + MaxFieldValueRunes = 1024 + MaxAuthorNameRunes = 256 + MaxSummaryRunes = 300 +) + +// RFCMeta holds structured fields parsed from an RFC body. +type RFCMeta struct { + Target string + Status string + Summary string + OpenDecisions int + RelatedRFCLinks []string +} + +// Empty reports whether neither an RFC field table nor a summary was found. +func (m RFCMeta) Empty() bool { + return m.Target == "" && m.Status == "" && m.Summary == "" +} + +var ( + headingSummaryRE = regexp.MustCompile(`(?i)^#{1,6}\s+(?:executive\s+)?summary\b`) + headingDecisionsRE = regexp.MustCompile(`(?i)^#{1,6}\s+decisions\s*(?:for\s+maintainers)?\b`) + genericHeadingRE = regexp.MustCompile(`^#{1,6}\s+`) + numberedCheckboxRE = regexp.MustCompile(`(?i)^(?:\d+[\.\)]|\(\d+\))\s+\[x\]`) + numberedItemRE = regexp.MustCompile(`^(?:\d+[\.\)]|\(\d+\))\s+\S+`) + rfcLinkRE = regexp.MustCompile(`(?i)(?:[\w.-]+/[\w.-]+)?#\d+|https?://github\.com/[\w.-]+/[\w.-]+/(?:issues|pull)/\d+`) +) + +// ParseRFC extracts Target and Status from the RFC field table, the first +// paragraph under ## Summary (capped to 300 runes and scrubbed), the count +// of open items under ## Decisions for maintainers, and related RFC links. +// Parsing never fails; missing fields stay empty. +func ParseRFC(body string) RFCMeta { + var meta RFCMeta + body = strings.ReplaceAll(body, "\r\n", "\n") + lines := strings.Split(body, "\n") + + inSummary := false + inDecisions := false + var summaryLines []string + + for i := 0; i < len(lines); i++ { + line := strings.TrimSpace(lines[i]) + + if genericHeadingRE.MatchString(line) { + if headingSummaryRE.MatchString(line) { + inSummary = true + inDecisions = false + continue + } else if headingDecisionsRE.MatchString(line) { + inDecisions = true + inSummary = false + continue + } else { + inSummary = false + inDecisions = false + } + } + + if inSummary { + if len(summaryLines) == 0 && line == "" { + continue + } + if line == "" { + inSummary = false + continue + } + if strings.HasPrefix(line, "|") || strings.HasPrefix(line, "- ") || strings.HasPrefix(line, "* ") { + if len(summaryLines) > 0 { + inSummary = false + continue + } + } + summaryLines = append(summaryLines, line) + continue + } + + if inDecisions { + if line == "" { + continue + } + if strings.Contains(line, "~~") { + continue + } + if isCheckedCheckbox(line) { + continue + } + if isUncheckedCheckbox(line) { + meta.OpenDecisions++ + continue + } + if isNumberedItem(line) { + meta.OpenDecisions++ + continue + } + } + + if strings.Contains(line, "|") { + cols := splitTableCols(line) + if len(cols) >= 2 { + key := strings.ToLower(cols[0]) + val := cols[1] + if !isTableHeaderOrSeparator(key, val) { + switch { + case key == "target": + if meta.Target == "" { + meta.Target = val + } + case key == "status": + if meta.Status == "" { + meta.Status = val + } + case isRelatedKey(key): + links := extractRFCLinks(val) + if len(links) > 0 { + for _, l := range links { + if !containsString(meta.RelatedRFCLinks, l) { + meta.RelatedRFCLinks = append(meta.RelatedRFCLinks, l) + } + } + } else if val != "" && !containsString(meta.RelatedRFCLinks, val) { + meta.RelatedRFCLinks = append(meta.RelatedRFCLinks, val) + } + } + } + } + } + } + + if len(summaryLines) > 0 { + rawSummary := strings.Join(strings.Fields(strings.Join(summaryLines, " ")), " ") + meta.Summary = truncateRunes(logscrub.ScrubString(rawSummary), MaxSummaryRunes) + } + + return meta +} + +func isTableHeaderOrSeparator(key, val string) bool { + if key == "field" || key == "key" || strings.HasPrefix(key, "---") || strings.HasPrefix(val, "---") { + return true + } + return false +} + +func isRelatedKey(k string) bool { + return k == "related" || k == "related rfcs" || k == "related rfc" || + k == "builds on" || k == "supersedes" || strings.HasPrefix(k, "related") +} + +func splitTableCols(line string) []string { + parts := strings.Split(line, "|") + var cols []string + for _, p := range parts { + t := strings.TrimSpace(p) + if t != "" { + cols = append(cols, t) + } + } + return cols +} + +func extractRFCLinks(val string) []string { + matches := rfcLinkRE.FindAllString(val, -1) + var out []string + seen := make(map[string]bool) + for _, m := range matches { + m = strings.TrimSpace(m) + if !seen[m] { + seen[m] = true + out = append(out, m) + } + } + return out +} + +func isUncheckedCheckbox(line string) bool { + return strings.HasPrefix(line, "- [ ]") || strings.HasPrefix(line, "* [ ]") || strings.HasPrefix(line, "+ [ ]") +} + +func isCheckedCheckbox(line string) bool { + return numberedCheckboxRE.MatchString(line) || strings.HasPrefix(line, "- [x]") || strings.HasPrefix(line, "- [X]") || + strings.HasPrefix(line, "* [x]") || strings.HasPrefix(line, "* [X]") || + strings.HasPrefix(line, "+ [x]") || strings.HasPrefix(line, "+ [X]") +} + +func isNumberedItem(line string) bool { + return numberedItemRE.MatchString(line) +} + +func containsString(slice []string, s string) bool { + for _, v := range slice { + if v == s { + return true + } + } + return false +} + +func truncateRunes(s string, limit int) string { + if limit <= 0 { + return "" + } + runes := []rune(s) + if len(runes) <= limit { + return s + } + return string(runes[:limit]) +} + +func isNeedsDecision(labels []string) bool { + for _, l := range labels { + l = strings.ToLower(strings.TrimSpace(l)) + if l == "stage/045-needs-decision" || l == "needs-decision" || l == "stage/085-needs-decision" { + return true + } + } + return false +} + +// CardColor returns the Discord embed color for an event: held grey, +// needs-decision amber, ready green, closed completed blue, closed +// not-planned dark. +func CardColor(e Event) int { + if !e.Issue.Open() || e.Kind == KindClosed { + if ClosedReason(e.Issue.StateReason) == closedNotPlanned { + return ColorNotPlanned + } + return ColorCompleted + } + if e.Kind == KindDocAccepted { + return ColorCompleted + } + if e.Kind == KindReady { + return ColorReady + } + if isNeedsDecision(e.Issue.Labels) { + return ColorNeedsDecision + } + if Held(e.Issue.Labels) { + return ColorHeld + } + if Actionable(e.Issue.Labels) { + return ColorReady + } + return ColorHeld +} + +// Card builds a Discord summary card (embed) for an RFC lifecycle event. +func Card(e Event, meta RFCMeta, includeRepo bool) Embed { + ref := fmt.Sprintf("#%d", e.Issue.Number) + if includeRepo && e.Issue.Repo != "" { + ref = e.Issue.Repo + ref + } + title := strings.TrimSpace(e.Issue.Title) + if d := strings.TrimSpace(e.Issue.DocTitle); d != "" { + title = d + } + cardTitle := fmt.Sprintf("%s %s", ref, title) + cardTitle = truncateRunes(logscrub.ScrubString(cardTitle), MaxTitleRunes) + + var author *discord.EmbedAuthor + if a := strings.TrimSpace(e.Issue.Author); a != "" { + author = &discord.EmbedAuthor{ + Name: truncateRunes(a, MaxAuthorNameRunes), + IconURL: fmt.Sprintf("https://github.com/%s.png", a), + } + } + + var fields []discord.EmbedField + if meta.Target != "" { + fields = append(fields, discord.EmbedField{ + Name: "Target", + Value: truncateRunes(logscrub.ScrubString(meta.Target), MaxFieldValueRunes), + Inline: true, + }) + } + if meta.Status != "" { + fields = append(fields, discord.EmbedField{ + Name: "Status", + Value: truncateRunes(logscrub.ScrubString(meta.Status), MaxFieldValueRunes), + Inline: true, + }) + } + if meta.OpenDecisions > 0 { + fields = append(fields, discord.EmbedField{ + Name: "Decisions", + Value: fmt.Sprintf("%d open", meta.OpenDecisions), + Inline: true, + }) + } + if len(meta.RelatedRFCLinks) > 0 { + fields = append(fields, discord.EmbedField{ + Name: "Related", + Value: truncateRunes(logscrub.ScrubString(strings.Join(meta.RelatedRFCLinks, ", ")), MaxFieldValueRunes), + Inline: false, + }) + } + + return Embed{ + Title: cardTitle, + URL: strings.TrimSpace(e.Issue.URL), + Author: author, + Description: truncateRunes(meta.Summary, MaxDescriptionRunes), + Color: CardColor(e), + Fields: fields, + } +} diff --git a/src/pkg/rfcnotify/card_test.go b/src/pkg/rfcnotify/card_test.go new file mode 100644 index 0000000000..0ee3c19a88 --- /dev/null +++ b/src/pkg/rfcnotify/card_test.go @@ -0,0 +1,512 @@ +package rfcnotify + +import ( + "context" + "errors" + "io" + "log/slog" + "strings" + "testing" + "time" +) + +const rfc15869Body = `Held RFC. This is a design proposal for discussion. It carries ` + "`hold`" + ` so no hive agent picks it up until maintainers settle **Decisions for maintainers**. + +| Field | Value | +| --- | --- | +| Status | Proposal, not accepted | +| Target | v5 | +| Scope | ` + "`src/pkg/rfcnotify`" + ` (detector, sweeper, ` + "`Format`" + `), ` + "`src/pkg/discord/bot.go`" + ` | +| Out of scope | Two-way sync, slash commands | +| Builds on | #14616 / #14617 (RFC lifecycle notices, merged on v5 2026-10-27) | +| Channel | ` + "`#architecture-rfcs`" + `, https://discord.com/channels/1539670512744136715/1540404487099777136 | + +## Summary + +RFCs already reach Discord automatically. #14617 shipped ` + "`pkg/rfcnotify`" + `: set ` + "`notifications.discord.rfc_channel_id`" + ` and the hive polls every 3 min. It posts one plain line when an RFC issue is opened, when it closes, and when its hold comes off. + +This RFC makes that feed something people read and discuss rather than scroll past: + +- a summary card instead of a bare link; +- one Discord thread per RFC; + +## Decisions for maintainers + +1. **Defaults.** Make ` + "`card`" + ` and threads the default on upgrade (proposed), or keep today's one-liner and opt in? +2. **Text channel or Forum channel.** Keep ` + "`#architecture-rfcs`" + ` as a text channel with threads (proposed), or move to a Forum channel? +3. **Single announcer.** The channel-history idempotency check (proposed), or designate one hive or the hub as the announcer? +4. **Backlink comment.** Should the bot comment on GitHub issues it did not open? +5. **Comment digest.** Daily per-thread digest: in scope, or later? +` + +func TestParseRFC_RFC15869(t *testing.T) { + meta := ParseRFC(rfc15869Body) + if meta.Empty() { + t.Fatal("RFC #15869 body should parse, but Empty() was true") + } + if meta.Target != "v5" { + t.Errorf("Target = %q, want %q", meta.Target, "v5") + } + if meta.Status != "Proposal, not accepted" { + t.Errorf("Status = %q, want %q", meta.Status, "Proposal, not accepted") + } + if meta.OpenDecisions != 5 { + t.Errorf("OpenDecisions = %d, want 5", meta.OpenDecisions) + } + if len(meta.RelatedRFCLinks) != 2 || meta.RelatedRFCLinks[0] != "#14616" || meta.RelatedRFCLinks[1] != "#14617" { + t.Errorf("RelatedRFCLinks = %v, want [#14616 #14617]", meta.RelatedRFCLinks) + } + if !strings.HasPrefix(meta.Summary, "RFCs already reach Discord automatically.") { + t.Errorf("Summary = %q, want prefix RFCs already reach...", meta.Summary) + } + if len([]rune(meta.Summary)) > 300 { + t.Errorf("Summary runes = %d, want <= 300", len([]rune(meta.Summary))) + } +} + +func TestParseRFC_DecisionsStrikethroughAndCheckboxes(t *testing.T) { + body := ` +| Field | Value | +| --- | --- | +| Target | v6 | + +## Summary +A short summary of changes. + +## Decisions for maintainers + +1. Open numbered question +2. ~~Resolved numbered question~~ +- [ ] Open checkbox decision +- [x] Completed checkbox decision +- [X] Also completed checkbox decision +- [ ] ~~Struck through checkbox decision~~ +3. Another open question +4. [x] Completed numbered decision +5) [X] Also completed numbered decision +(6) [x] Completed parenthesized decision +7. [ ] Open numbered checkbox +` + meta := ParseRFC(body) + if meta.Target != "v6" { + t.Errorf("Target = %q, want v6", meta.Target) + } + // Items 1, checkbox open, item 3, item 7 = 4 open decisions + if meta.OpenDecisions != 4 { + t.Errorf("OpenDecisions = %d, want 4", meta.OpenDecisions) + } +} + +func TestParseRFC_SummaryScrubbingAndTruncation(t *testing.T) { + fakeToken := "ghp_" + strings.Repeat("a", 36) + longText := strings.Repeat("Long text sentence. ", 30) // ~600 runes + body := ` +| Field | Value | +| --- | --- | +| Status | In review | + +## Summary +` + fakeToken + " " + longText + + meta := ParseRFC(body) + if strings.Contains(meta.Summary, fakeToken) { + t.Error("Summary must not contain raw credential token") + } + if !strings.Contains(meta.Summary, "[REDACTED]") { + t.Errorf("Summary must contain [REDACTED], got: %q", meta.Summary) + } + if len([]rune(meta.Summary)) > 300 { + t.Errorf("Summary length = %d runes, want <= 300", len([]rune(meta.Summary))) + } +} + +func TestParseRFC_MalformedBody(t *testing.T) { + bodies := []string{ + "", + "Just a normal bug description with no RFC table and no summary heading.", + "# Not an RFC\nSome text here\nAnother line", + } + for _, b := range bodies { + meta := ParseRFC(b) + if !meta.Empty() { + t.Errorf("body %q should be Empty(), got %+v", b, meta) + } + } +} + +func TestCard_FieldsAndMentionsSafety(t *testing.T) { + ev := Event{ + Kind: KindOpened, + Issue: Issue{ + Repo: "hivecommons/hive", + Number: 15869, + Title: "📝 RFC: Richer RFC publishing @everyone <@&12345>", + URL: "https://github.com/hivecommons/hive/issues/15869", + Author: "hanthor", + State: "open", + Labels: []string{"rfc", "hold"}, + Body: rfc15869Body, + }, + } + meta := ParseRFC(rfc15869Body) + card := Card(ev, meta, false) + + if card.Title != "#15869 📝 RFC: Richer RFC publishing @everyone <@&12345>" { + t.Errorf("Title = %q", card.Title) + } + if card.URL != "https://github.com/hivecommons/hive/issues/15869" { + t.Errorf("URL = %q", card.URL) + } + if card.Author == nil || card.Author.Name != "hanthor" { + t.Errorf("Author = %+v, want hanthor", card.Author) + } + if card.Author.IconURL != "https://github.com/hanthor.png" { + t.Errorf("Author.IconURL = %q, want https://github.com/hanthor.png", card.Author.IconURL) + } + if card.Color != ColorHeld { + t.Errorf("Color = %x, want ColorHeld (%x)", card.Color, ColorHeld) + } + + fieldMap := make(map[string]string) + for _, f := range card.Fields { + fieldMap[f.Name] = f.Value + } + if fieldMap["Target"] != "v5" { + t.Errorf("Field Target = %q, want v5", fieldMap["Target"]) + } + if fieldMap["Status"] != "Proposal, not accepted" { + t.Errorf("Field Status = %q, want Proposal, not accepted", fieldMap["Status"]) + } + if fieldMap["Decisions"] != "5 open" { + t.Errorf("Field Decisions = %q, want '5 open'", fieldMap["Decisions"]) + } + if fieldMap["Related"] != "#14616, #14617" { + t.Errorf("Field Related = %q, want '#14616, #14617'", fieldMap["Related"]) + } + + // Test with includeRepo = true + cardRepo := Card(ev, meta, true) + if !strings.HasPrefix(cardRepo.Title, "hivecommons/hive#15869 ") { + t.Errorf("cardRepo.Title = %q, want repo prefix", cardRepo.Title) + } +} + +func TestCard_FieldScrubbing(t *testing.T) { + fakeToken := "ghp_" + strings.Repeat("b", 36) + ev := Event{ + Issue: Issue{ + Number: 42, + Title: "RFC: Test Title", + URL: "https://example.com/42", + }, + } + meta := RFCMeta{ + Target: "target with " + fakeToken, + Status: "status with " + fakeToken, + RelatedRFCLinks: []string{"related with " + fakeToken}, + } + card := Card(ev, meta, false) + for _, f := range card.Fields { + if strings.Contains(f.Value, fakeToken) { + t.Errorf("field %s contains unscrubbed token: %q", f.Name, f.Value) + } + } +} + +func TestCard_ColorsByState(t *testing.T) { + cases := []struct { + name string + kind Kind + open bool + reason string + labels []string + wantColor int + }{ + { + name: "held open", + kind: KindOpened, + open: true, + labels: []string{"rfc", "hold"}, + wantColor: ColorHeld, // grey + }, + { + name: "needs decision", + kind: KindOpened, + open: true, + labels: []string{"rfc", "stage/045-needs-decision"}, + wantColor: ColorNeedsDecision, // amber + }, + { + name: "legacy needs-decision", + kind: KindOpened, + open: true, + labels: []string{"rfc", "needs-decision"}, + wantColor: ColorNeedsDecision, // amber + }, + { + name: "ready to implement", + kind: KindReady, + open: true, + labels: []string{"rfc"}, + wantColor: ColorReady, // green + }, + { + name: "actionable without hold", + kind: KindOpened, + open: true, + labels: []string{"rfc", "stage/010-actionable"}, + wantColor: ColorReady, // green + }, + { + name: "closed completed", + kind: KindClosed, + open: false, + reason: "completed", + labels: []string{"rfc"}, + wantColor: ColorCompleted, // blue + }, + { + name: "closed not planned", + kind: KindClosed, + open: false, + reason: "not_planned", + labels: []string{"rfc"}, + wantColor: ColorNotPlanned, // dark + }, + { + name: "doc accepted PR", + kind: KindDocAccepted, + open: false, + labels: []string{"rfc"}, + wantColor: ColorCompleted, // blue + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + state := "open" + if !tc.open { + state = "closed" + } + ev := Event{ + Kind: tc.kind, + Issue: Issue{ + Number: 1, + Title: "RFC test", + State: state, + StateReason: tc.reason, + Labels: tc.labels, + }, + } + color := CardColor(ev) + if color != tc.wantColor { + t.Errorf("CardColor = %x, want %x", color, tc.wantColor) + } + }) + } +} + +type recordPublisher struct { + posted []string + cards []Embed + cardContents []string + fail bool +} + +func (p *recordPublisher) Post(content string) error { + if p.fail { + return errors.New("post error") + } + p.posted = append(p.posted, content) + return nil +} + +func (p *recordPublisher) PostCard(content string, embed Embed) (string, error) { + if p.fail { + return "", errors.New("card post error") + } + p.cards = append(p.cards, embed) + p.cardContents = append(p.cardContents, content) + return "msg-card-1", nil +} + +func TestSweeperCardFormat_PostsCardAndFallsBackOnMalformed(t *testing.T) { + now := time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC) + quiet := slog.New(slog.NewTextHandler(io.Discard, nil)) + sw := NewSweeper(Options{ + Format: FormatCard, + Announcer: true, + Now: func() time.Time { return now }, + Logger: quiet, + }) + + // Seed sweeper + src := &fakeSource{ + open: []Issue{ + {Number: 1, Title: "Existing RFC", State: "open", Labels: []string{"rfc"}}, + }, + } + pub := &recordPublisher{} + if res, err := sw.Run(context.Background(), src, pub); err != nil || !res.Seeded { + t.Fatalf("seed failed: %+v, err: %v", res, err) + } + + // Poll 1: Well-formed RFC #2, and malformed RFC #3 + now = now.Add(5 * time.Minute) + src.updated = []Issue{ + { + Number: 2, + Title: "RFC: Well-formed", + URL: "https://x/2", + State: "open", + Labels: []string{"rfc", "hold"}, + Body: rfc15869Body, + CreatedAt: now, + }, + { + Number: 3, + Title: "RFC: Malformed body", + URL: "https://x/3", + State: "open", + Labels: []string{"rfc"}, + Body: "No table, no summary heading here.", + CreatedAt: now, + }, + } + + res, err := sw.Run(context.Background(), src, pub) + if err != nil { + t.Fatalf("run failed: %v", err) + } + if len(res.Posted) != 2 { + t.Fatalf("len(res.Posted) = %d, want 2", len(res.Posted)) + } + // Card #2 should be posted as card embed + if len(pub.cards) != 1 { + t.Fatalf("len(pub.cards) = %d, want 1", len(pub.cards)) + } + if !strings.HasPrefix(pub.cardContents[0], "RFC opened: #2 RFC: Well-formed - ") { + t.Errorf("card content = %q", pub.cardContents[0]) + } + if pub.cards[0].Title != "#2 RFC: Well-formed" { + t.Errorf("card title = %q, want '#2 RFC: Well-formed'", pub.cards[0].Title) + } + if pub.cards[0].Color != ColorHeld { + t.Errorf("card color = %x, want ColorHeld", pub.cards[0].Color) + } + + // Malformed #3 should fall back to plain line post + if len(pub.posted) != 1 { + t.Fatalf("len(pub.posted) = %d, want 1", len(pub.posted)) + } + if !strings.HasPrefix(pub.posted[0], "RFC opened: #3 RFC: Malformed body - ") { + t.Errorf("pub.posted[0] = %q", pub.posted[0]) + } +} + +func TestSweeperCardFormat_PostCardFailureRollsBack(t *testing.T) { + now := time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC) + quiet := slog.New(slog.NewTextHandler(io.Discard, nil)) + sw := NewSweeper(Options{ + Format: FormatCard, + Announcer: true, + Now: func() time.Time { return now }, + Logger: quiet, + }) + + src := &fakeSource{ + open: []Issue{ + {Number: 1, Title: "Existing RFC", State: "open", Labels: []string{"rfc"}}, + }, + } + pub := &recordPublisher{} + if _, err := sw.Run(context.Background(), src, pub); err != nil { + t.Fatalf("seed failed: %v", err) + } + + // Fail the card post + pub.fail = true + now = now.Add(5 * time.Minute) + src.updated = []Issue{ + { + Number: 2, + Title: "RFC: Card fail", + URL: "https://x/2", + State: "open", + Labels: []string{"rfc"}, + Body: rfc15869Body, + CreatedAt: now, + }, + } + + res, err := sw.Run(context.Background(), src, pub) + if err != nil { + t.Fatalf("run returned error: %v", err) + } + if res.Errors != 1 { + t.Errorf("res.Errors = %d, want 1", res.Errors) + } + + // Retry on next poll without failure: should succeed + pub.fail = false + now = now.Add(5 * time.Minute) + res2, err := sw.Run(context.Background(), src, pub) + if err != nil { + t.Fatalf("run retry returned error: %v", err) + } + if len(res2.Posted) != 1 || len(pub.cards) != 1 { + t.Fatalf("retry should post card: posted=%d cards=%d", len(res2.Posted), len(pub.cards)) + } +} + +func TestSweeperCardFormat_PreservesTransitions(t *testing.T) { + fresh := rfc(2, "open") + fresh.CreatedAt = t0.Add(time.Second) + proposal := rfcPR(2, "📝 proposal: cards", t0.Add(time.Second)) + for _, tc := range []struct { + name string + before []Issue + after Issue + prefix string + }{ + {"opened", nil, fresh, "RFC opened: "}, + {"ready", []Issue{rfc(2, "open", "hold")}, rfc(2, "open"), "RFC ready to implement (hold removed): "}, + {"completed", []Issue{rfc(2, "open")}, withReason(rfc(2, "open"), "completed"), "RFC closed (completed): "}, + {"not planned", []Issue{rfc(2, "open")}, withReason(rfc(2, "open"), "not_planned"), "RFC closed (not planned): "}, + {"doc proposed", nil, proposal, "RFC doc proposed: "}, + {"doc accepted", []Issue{rfc(1, "open")}, merged(proposal, t0.Add(time.Second)), "RFC doc accepted (RFC #1): "}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, fallback := range []bool{false, true} { + now := t0 + sw := NewSweeper(Options{Format: FormatCard, Announcer: true, IncludeRepo: true, Logger: quiet, Now: func() time.Time { return now }}) + src := &fakeSource{open: tc.before} + pub := &recordPublisher{} + var publisher Publisher = pub + if fallback { + publisher = Poster(pub.Post) + } + if _, err := sw.Run(context.Background(), src, publisher); err != nil { + t.Fatal(err) + } + after := tc.after + after.Body = "Refs #1\n\n## Summary\nRFC summary." + src.updated = []Issue{after} + now = now.Add(DefaultInterval) + res, err := sw.Run(context.Background(), src, publisher) + if err != nil || len(res.Posted) != 1 { + t.Fatalf("fallback=%v: result=%+v err=%v", fallback, res, err) + } + contents := pub.cardContents + if fallback { + contents = pub.posted + } else if len(pub.cards) != 1 { + t.Fatalf("cards = %d, want 1", len(pub.cards)) + } + if len(contents) != 1 || !strings.HasPrefix(contents[0], tc.prefix+"hivecommons/hive#2 ") || !strings.Contains(contents[0], "<"+after.URL+">") { + t.Fatalf("fallback=%v: content=%v, want transition %q, repo and URL", fallback, contents, tc.prefix) + } + } + }) + } +} diff --git a/src/pkg/rfcnotify/pr_test.go b/src/pkg/rfcnotify/pr_test.go index 88c94063e6..3afa9a5f71 100644 --- a/src/pkg/rfcnotify/pr_test.go +++ b/src/pkg/rfcnotify/pr_test.go @@ -153,10 +153,10 @@ func TestSweeperRFCPRsRichModeOnly(t *testing.T) { // Line mode never asks for pull requests. src := &prFakeSource{} line := NewSweeper(Options{Logger: quiet, Now: clock, Interval: time.Minute}) - _, _ = line.Run(ctx, src, post) + _, _ = line.Run(ctx, src, Poster(post)) now = now.Add(2 * time.Minute) src.prs = []Issue{rfcPR(5, "📝 proposal: x", now.Add(-time.Second))} - if res, err := line.Run(ctx, src, post); err != nil || src.prPolls != 0 || len(res.Posted) != 0 { + if res, err := line.Run(ctx, src, Poster(post)); err != nil || src.prPolls != 0 || len(res.Posted) != 0 { t.Fatalf("line mode: %+v err=%v prPolls=%d", res, err, src.prPolls) } @@ -164,17 +164,17 @@ func TestSweeperRFCPRsRichModeOnly(t *testing.T) { now = t0 src = &prFakeSource{} rich := NewSweeper(Options{Logger: quiet, Now: clock, Interval: time.Minute, Format: FormatCard, Announcer: true}) - _, _ = rich.Run(ctx, src, post) + _, _ = rich.Run(ctx, src, Poster(post)) now = now.Add(2 * time.Minute) priv := rfcPR(6, "📝 proposal: secret", now.Add(-time.Second)) priv.Repo, priv.Private = "o/private", true src.prs = []Issue{rfcPR(5, "📝 proposal: x", now.Add(-time.Second)), priv} - res, err := rich.Run(ctx, src, post) + res, err := rich.Run(ctx, src, Poster(post)) if err != nil || src.prPolls != 1 || len(posted) != 1 || !strings.HasPrefix(posted[0], "RFC doc proposed: #5 📝 proposal: x") || res.Withheld != 1 { t.Fatalf("rich mode: %+v err=%v posted=%v", res, err, posted) } now = now.Add(2 * time.Minute) - if res, _ := rich.Run(ctx, src, post); len(res.Posted) != 0 || len(posted) != 1 { + if res, _ := rich.Run(ctx, src, Poster(post)); len(res.Posted) != 0 || len(posted) != 1 { t.Fatalf("second poll re-announced: %+v", res) } } diff --git a/src/pkg/rfcnotify/rfcnotify.go b/src/pkg/rfcnotify/rfcnotify.go index 6cbf8e9eeb..3ebefbe4c8 100644 --- a/src/pkg/rfcnotify/rfcnotify.go +++ b/src/pkg/rfcnotify/rfcnotify.go @@ -69,7 +69,8 @@ type Issue struct { // IsPR marks a pull request (an RFC document proposal). PRs share the // repo#N key space with issues. IsPR bool - // Body is the PR description, read for the linked RFC issue. + // Body is the issue or PR description, read for summary cards and + // linked RFC issues. Body string // Files are the PR's added or changed paths. Only filled when the // title alone does not mark the PR as an RFC. diff --git a/src/pkg/rfcnotify/rfcnotify_test.go b/src/pkg/rfcnotify/rfcnotify_test.go index 4f8a3d8389..9c1b6aee1f 100644 --- a/src/pkg/rfcnotify/rfcnotify_test.go +++ b/src/pkg/rfcnotify/rfcnotify_test.go @@ -318,7 +318,7 @@ func TestSweeperSeedsThenPostsAndPersists(t *testing.T) { src := &fakeSource{open: []Issue{rfc(1, "open", "hold"), rfc(2, "open")}} sw := NewSweeper(Options{StatePath: path, Now: clock, IncludeRepo: true, Logger: quiet}) - res, err := sw.Run(context.Background(), src, post) + res, err := sw.Run(context.Background(), src, Poster(post)) if err != nil || !res.Seeded || len(posted) != 0 { t.Fatalf("seed run: %+v %v posted=%v", res, err, posted) } @@ -327,7 +327,7 @@ func TestSweeperSeedsThenPostsAndPersists(t *testing.T) { } // Within the interval: skipped, no listing. now = now.Add(time.Minute) - if res, _ := sw.Run(context.Background(), src, post); !res.Skipped { + if res, _ := sw.Run(context.Background(), src, Poster(post)); !res.Skipped { t.Fatal("expected skip inside the interval") } // Next poll: hold lifted on #1, #2 closed, new #3 opened. @@ -335,7 +335,7 @@ func TestSweeperSeedsThenPostsAndPersists(t *testing.T) { fresh := rfc(3, "open") fresh.CreatedAt = t0.Add(time.Minute) src.updated = []Issue{rfc(1, "open"), withReason(rfc(2, "open"), "not_planned"), fresh} - res, err = sw.Run(context.Background(), src, post) + res, err = sw.Run(context.Background(), src, Poster(post)) if err != nil || res.Errors != 0 || len(res.Posted) != 3 { t.Fatalf("poll run: %+v %v", res, err) } @@ -353,7 +353,7 @@ func TestSweeperSeedsThenPostsAndPersists(t *testing.T) { now = now.Add(DefaultInterval) posted = nil sw2 := NewSweeper(Options{StatePath: path, Now: clock, Logger: quiet}) - res, err = sw2.Run(context.Background(), src, post) + res, err = sw2.Run(context.Background(), src, Poster(post)) if err != nil || len(posted) != 0 || res.Seeded { t.Fatalf("restart re-posted: %+v %v %v", res, err, posted) } @@ -364,7 +364,7 @@ func TestSweeperPostFailureRetriesNextPoll(t *testing.T) { clock := func() time.Time { return now } src := &fakeSource{open: []Issue{rfc(1, "open"), rfc(2, "open")}} sw := NewSweeper(Options{Now: clock, Logger: quiet}) - if _, err := sw.Run(context.Background(), src, func(string) error { return nil }); err != nil { + if _, err := sw.Run(context.Background(), src, Poster(func(string) error { return nil })); err != nil { t.Fatal(err) } now = now.Add(DefaultInterval) @@ -377,7 +377,7 @@ func TestSweeperPostFailureRetriesNextPoll(t *testing.T) { } return nil } - res, err := sw.Run(context.Background(), src, failSecond) + res, err := sw.Run(context.Background(), src, Poster(failSecond)) if err != nil || res.Errors != 1 || len(res.Posted) != 1 { t.Fatalf("first run: %+v %v", res, err) } @@ -387,13 +387,13 @@ func TestSweeperPostFailureRetriesNextPoll(t *testing.T) { } now = now.Add(DefaultInterval) var posted []string - res, err = sw.Run(context.Background(), src, func(s string) error { posted = append(posted, s); return nil }) + res, err = sw.Run(context.Background(), src, Poster(func(s string) error { posted = append(posted, s); return nil })) if err != nil || len(posted) != 1 || !strings.Contains(posted[0], "#2 ") { t.Fatalf("retry run: %+v %v posted=%v", res, err, posted) } // Third poll: nothing left. now = now.Add(DefaultInterval) - if res, _ := sw.Run(context.Background(), src, func(string) error { t.Fatal("unexpected post"); return nil }); len(res.Posted) != 0 { + if res, _ := sw.Run(context.Background(), src, Poster(func(string) error { t.Fatal("unexpected post"); return nil })); len(res.Posted) != 0 { t.Fatal("re-posted") } } @@ -402,21 +402,21 @@ func TestSweeperRollbackForgetsUnpostedNewIssue(t *testing.T) { now := t0 sw := NewSweeper(Options{Now: func() time.Time { return now }, Logger: quiet}) src := &fakeSource{} - if _, err := sw.Run(context.Background(), src, func(string) error { return nil }); err != nil { + if _, err := sw.Run(context.Background(), src, Poster(func(string) error { return nil })); err != nil { t.Fatal(err) } now = now.Add(DefaultInterval) fresh := rfc(9, "open") fresh.CreatedAt = t0.Add(time.Second) src.updated = []Issue{fresh} - if res, _ := sw.Run(context.Background(), src, func(string) error { return errors.New("no") }); res.Errors != 1 { + if res, _ := sw.Run(context.Background(), src, Poster(func(string) error { return errors.New("no") })); res.Errors != 1 { t.Fatalf("expected one error: %+v", res) } if sw.Detector().Known(fresh.Key()) { t.Fatal("unposted new issue must be forgotten so it is announced next poll") } now = now.Add(DefaultInterval) - if res, _ := sw.Run(context.Background(), src, func(string) error { return nil }); len(res.Posted) != 1 { + if res, _ := sw.Run(context.Background(), src, Poster(func(string) error { return nil })); len(res.Posted) != 1 { t.Fatalf("retry: %+v", res) } } @@ -427,18 +427,18 @@ func TestSweeperErrors(t *testing.T) { t.Fatal("nil source must error") } src := &fakeSource{openErr: errors.New("boom")} - if _, err := sw.Run(context.Background(), src, func(string) error { return nil }); err == nil { + if _, err := sw.Run(context.Background(), src, Poster(func(string) error { return nil })); err == nil { t.Fatal("seed error must surface") } src.openErr = nil now := t0 sw = NewSweeper(Options{Now: func() time.Time { return now }, Logger: quiet}) - if _, err := sw.Run(context.Background(), src, func(string) error { return nil }); err != nil { + if _, err := sw.Run(context.Background(), src, Poster(func(string) error { return nil })); err != nil { t.Fatal(err) } now = now.Add(DefaultInterval) src.updErr = errors.New("rate limited") - if _, err := sw.Run(context.Background(), src, func(string) error { return nil }); err == nil { + if _, err := sw.Run(context.Background(), src, Poster(func(string) error { return nil })); err == nil { t.Fatal("list error must surface") } } @@ -455,7 +455,7 @@ func TestNewSweeperUnreadableStateStartsFresh(t *testing.T) { } // Save failure (state path is a directory) surfaces from Run. sw = NewSweeper(Options{StatePath: dir, Logger: quiet}) - if _, err := sw.Run(context.Background(), &fakeSource{}, func(string) error { return nil }); err == nil { + if _, err := sw.Run(context.Background(), &fakeSource{}, Poster(func(string) error { return nil })); err == nil { t.Fatal("save into a directory path must error") } } @@ -471,7 +471,7 @@ func gateSweeper(t *testing.T, opts Options, src *fakeSource) (*Sweeper, func()) } sw := NewSweeper(opts) src.open = []Issue{rfc(1, "open"), rfc(2, "open")} - if _, err := sw.Run(context.Background(), src, func(string) error { t.Fatal("seed posted"); return nil }); err != nil { + if _, err := sw.Run(context.Background(), src, Poster(func(string) error { t.Fatal("seed posted"); return nil })); err != nil { t.Fatal(err) } return sw, func() { now = now.Add(DefaultInterval) } @@ -495,13 +495,13 @@ func TestSweeperRichModeWithoutAnnouncerPostsNothingOnce(t *testing.T) { sw, tick := gateSweeper(t, opts, src) tick() src.updated = []Issue{withReason(rfc(1, "open"), "completed")} - res, err := sw.Run(context.Background(), src, func(string) error { t.Fatal("non-announcer posted"); return nil }) + res, err := sw.Run(context.Background(), src, Poster(func(string) error { t.Fatal("non-announcer posted"); return nil })) if err != nil || len(res.Posted) != 0 || res.Withheld != 1 { t.Fatalf("first run: %+v %v", res, err) } tick() src.updated = []Issue{withReason(rfc(2, "open"), "completed")} - if res, _ := sw.Run(context.Background(), src, func(string) error { t.Fatal("non-announcer posted"); return nil }); res.Withheld != 1 { + if res, _ := sw.Run(context.Background(), src, Poster(func(string) error { t.Fatal("non-announcer posted"); return nil })); res.Withheld != 1 { t.Fatalf("second run: %+v", res) } if n := strings.Count(logs.String(), "rich mode requires rfc_announcer; not posting"); n != 1 { @@ -511,7 +511,7 @@ func TestSweeperRichModeWithoutAnnouncerPostsNothingOnce(t *testing.T) { sw.opts.Announcer = true tick() src.updated = []Issue{withReason(rfc(1, "open"), "completed"), withReason(rfc(2, "open"), "completed")} - if res, _ := sw.Run(context.Background(), src, func(string) error { t.Fatal("backfilled"); return nil }); len(res.Posted) != 0 { + if res, _ := sw.Run(context.Background(), src, Poster(func(string) error { t.Fatal("backfilled"); return nil })); len(res.Posted) != 0 { t.Fatalf("backfill: %+v", res) } } @@ -523,7 +523,7 @@ func TestSweeperRichModeAnnouncerPosts(t *testing.T) { tick() src.updated = []Issue{withReason(rfc(1, "open"), "completed")} var posted []string - res, err := sw.Run(context.Background(), src, func(s string) error { posted = append(posted, s); return nil }) + res, err := sw.Run(context.Background(), src, Poster(func(s string) error { posted = append(posted, s); return nil })) if err != nil || len(posted) != 1 || res.Withheld != 0 { t.Fatalf("announcer: %+v %v %v", res, err, posted) } @@ -536,7 +536,7 @@ func TestSweeperLineModeIgnoresAnnouncer(t *testing.T) { tick() src.updated = []Issue{withReason(rfc(1, "open"), "completed")} var posted []string - if _, err := sw.Run(context.Background(), src, func(s string) error { posted = append(posted, s); return nil }); err != nil { + if _, err := sw.Run(context.Background(), src, Poster(func(s string) error { posted = append(posted, s); return nil })); err != nil { t.Fatal(err) } want := "RFC closed (completed): #1 " + rfc(1, "open").Title + " - " @@ -554,7 +554,7 @@ func TestSweeperPrivateGate(t *testing.T) { src.updated = []Issue{private(withReason(rfc(1, "open"), "completed")), withReason(rfc(2, "open"), "completed")} var posted []string post := func(s string) error { posted = append(posted, s); return nil } - res, err := sw.Run(context.Background(), src, post) + res, err := sw.Run(context.Background(), src, Poster(post)) if err != nil || res.Withheld != 1 || len(posted) != 1 || !strings.Contains(posted[0], "#2 ") { t.Fatalf("private run: %+v %v %v", res, err, posted) } @@ -562,7 +562,7 @@ func TestSweeperPrivateGate(t *testing.T) { sw.opts.IncludePrivate = true tick() posted = nil - if res, _ := sw.Run(context.Background(), src, post); len(posted) != 0 || res.Withheld != 0 { + if res, _ := sw.Run(context.Background(), src, Poster(post)); len(posted) != 0 || res.Withheld != 0 { t.Fatalf("replayed: %+v %v", res, posted) } @@ -571,7 +571,7 @@ func TestSweeperPrivateGate(t *testing.T) { tick2() src2.updated = []Issue{private(withReason(rfc(1, "open"), "completed"))} posted = nil - if res, _ := sw2.Run(context.Background(), src2, post); len(posted) != 1 || res.Withheld != 0 { + if res, _ := sw2.Run(context.Background(), src2, Poster(post)); len(posted) != 1 || res.Withheld != 0 { t.Fatalf("include_private: %+v %v", res, posted) } } @@ -584,7 +584,7 @@ func TestSweeperUnknownVisibilityRetriesNextPoll(t *testing.T) { src.updated = []Issue{unknown(withReason(rfc(1, "open"), "completed")), withReason(rfc(2, "open"), "completed")} var posted []string post := func(s string) error { posted = append(posted, s); return nil } - res, err := sw.Run(context.Background(), src, post) + res, err := sw.Run(context.Background(), src, Poster(post)) if err != nil || res.Unresolved != 1 || res.Withheld != 0 || len(posted) != 1 || !strings.Contains(posted[0], "#2 ") { t.Fatalf("unknown run: %+v %v %v", res, err, posted) } @@ -592,7 +592,7 @@ func TestSweeperUnknownVisibilityRetriesNextPoll(t *testing.T) { src.updated = []Issue{withReason(rfc(1, "open"), "completed")} tick() posted = nil - if res, _ := sw.Run(context.Background(), src, post); len(posted) != 1 || res.Unresolved != 0 { + if res, _ := sw.Run(context.Background(), src, Poster(post)); len(posted) != 1 || res.Unresolved != 0 { t.Fatalf("retry: %+v %v", res, posted) } } diff --git a/src/pkg/rfcnotify/sweeper.go b/src/pkg/rfcnotify/sweeper.go index 4c8d1b5e63..1b3d58f445 100644 --- a/src/pkg/rfcnotify/sweeper.go +++ b/src/pkg/rfcnotify/sweeper.go @@ -32,9 +32,28 @@ type PRSource interface { ListPRsUpdatedSince(ctx context.Context, since time.Time) ([]Issue, error) } +// Publisher sends messages or summary cards to the configured channel. +type Publisher interface { + Post(content string) error + PostCard(content string, embed Embed) (string, error) +} + // Poster sends one message to the configured channel. type Poster func(content string) error +// Post implements Publisher for Poster. +func (p Poster) Post(content string) error { + return p(content) +} + +// PostCard implements Publisher for Poster by falling back to Post. +func (p Poster) PostCard(content string, embed Embed) (string, error) { + if content != "" { + return "", p(content) + } + return "", p(embed.Title) +} + // Values for Options.Format. const ( FormatLine = "line" @@ -55,8 +74,8 @@ type Options struct { Slack time.Duration // IncludeRepo prefixes issue numbers with their repo. IncludeRepo bool - // Format is FormatLine (or empty, the default) or FormatCard. Card - // rendering is not implemented yet; FormatCard only turns on rich mode. + // Format is FormatLine (or empty, the default) or FormatCard. FormatCard + // renders transitions as Discord summary cards (embeds). Format string // Threads opts into one thread per RFC (rich mode). Threads bool @@ -138,9 +157,9 @@ func (s *Sweeper) Detector() *Detector { return s.det } // Run polls once if the interval has elapsed, posts each event, and saves // the state. A post failure stops the batch so the remaining events are // retried next time rather than reordered. -func (s *Sweeper) Run(ctx context.Context, src Source, post Poster) (Result, error) { +func (s *Sweeper) Run(ctx context.Context, src Source, pub Publisher) (Result, error) { var res Result - if src == nil || post == nil { + if src == nil || pub == nil { return res, fmt.Errorf("rfc notify: source and poster are required") } now := s.opts.Now() @@ -199,9 +218,21 @@ func (s *Sweeper) Run(ctx context.Context, src Source, post Poster) (Result, err continue } msg := Format(ev, s.opts.IncludeRepo) - if err := post(msg); err != nil { + var postErr error + if s.opts.Format == FormatCard { + meta := ParseRFC(ev.Issue.Body) + if meta.Empty() { + postErr = pub.Post(msg) + } else { + card := Card(ev, meta, s.opts.IncludeRepo) + _, postErr = pub.PostCard(msg, card) + } + } else { + postErr = pub.Post(msg) + } + if postErr != nil { res.Errors++ - s.opts.Logger.Warn("rfc notify: post failed", "issue", ev.Issue.Key(), "kind", ev.Kind, "error", err) + s.opts.Logger.Warn("rfc notify: post failed", "issue", ev.Issue.Key(), "kind", ev.Kind, "error", postErr) // Keep what was announced, forget what was not: replay the // snapshot for the unposted issues on top of the old records. s.det.rollback(before, events[i:])