From 5ecab6e8410183a66fbd8e1851430f45e4713749 Mon Sep 17 00:00:00 2001 From: thatguywob Date: Sat, 31 Oct 2026 05:11:57 +0000 Subject: [PATCH 1/6] =?UTF-8?q?=E2=9C=A8=20feat:=20render=20RFC=20notices?= =?UTF-8?q?=20as=20summary-card=20embeds=20when=20rfc=5Fformat:=20card?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Render an RFC event as a Discord summary card (embed) when rfc_format: card is configured on the designated announcer. Line mode is unchanged. - Add Body to github.IssueSnapshot and map it in rfcnotify.Issue. - Parse RFC target, status, scrubbed summary, and decisions count in rfcnotify.ParseRFC. - Render Discord embed with state-based color in rfcnotify.Card. - Fall back to plain Format when the RFC body is malformed. - Support SendEmbedTo and bounded 429 retries in pkg/discord. - Adapt Sweeper to Publisher interface. Hive-Run: hivecommons/hive#15927 Hive-Plan: summary-card-embeds Hive-Spec: rfc-publishing#summary-cards Signed-off-by: thatguywob --- changelog.d/added-rfc-notify-cards.md | 1 + src/cmd/hive/rfcnotify_wire.go | 35 ++- src/cmd/hive/rfcnotify_wire_test.go | 72 +++++ src/docs/notifications.md | 2 +- src/pkg/discord/bot.go | 145 ++++++++- src/pkg/discord/bot_test.go | 134 ++++++++ src/pkg/github/issue_snapshots.go | 3 + src/pkg/rfcnotify/card.go | 333 ++++++++++++++++++++ src/pkg/rfcnotify/card_test.go | 429 ++++++++++++++++++++++++++ src/pkg/rfcnotify/rfcnotify.go | 3 +- src/pkg/rfcnotify/sweeper.go | 60 +++- 11 files changed, 1189 insertions(+), 28 deletions(-) create mode 100644 changelog.d/added-rfc-notify-cards.md create mode 100644 src/pkg/rfcnotify/card.go create mode 100644 src/pkg/rfcnotify/card_test.go diff --git a/changelog.d/added-rfc-notify-cards.md b/changelog.d/added-rfc-notify-cards.md new file mode 100644 index 0000000000..79e5bc138c --- /dev/null +++ b/changelog.d/added-rfc-notify-cards.md @@ -0,0 +1 @@ +- Render RFC lifecycle notices as Discord summary-card embeds 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..361b1ce38c 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 @@ -48,6 +49,8 @@ type rfcNotifyState struct { // newPoster builds the Discord poster; nil means discordRFCPoster. // 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. @@ -117,13 +120,38 @@ 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 } +// 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) +} + // 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 { @@ -321,6 +349,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 +366,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..a0492080b4 100644 --- a/src/cmd/hive/rfcnotify_wire_test.go +++ b/src/cmd/hive/rfcnotify_wire_test.go @@ -451,3 +451,75 @@ 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{ + 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..60424d7af2 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` renders each transition as 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/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..ba8bbe8014 100644 --- a/src/pkg/discord/bot_test.go +++ b/src/pkg/discord/bot_test.go @@ -1118,3 +1118,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..c541f9536e --- /dev/null +++ b/src/pkg/rfcnotify/card.go @@ -0,0 +1,333 @@ +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+`) + 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 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(meta.Target, MaxFieldValueRunes), + Inline: true, + }) + } + if meta.Status != "" { + fields = append(fields, discord.EmbedField{ + Name: "Status", + Value: truncateRunes(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(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..f41f9ba29c --- /dev/null +++ b/src/pkg/rfcnotify/card_test.go @@ -0,0 +1,429 @@ +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 +` + meta := ParseRFC(body) + if meta.Target != "v6" { + t.Errorf("Target = %q, want v6", meta.Target) + } + // Items 1, checkbox open, item 3 = 3 open decisions + if meta.OpenDecisions != 3 { + t.Errorf("OpenDecisions = %d, want 3", 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_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 + 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) + 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.since = []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 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.since = []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)) + } +} 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/sweeper.go b/src/pkg/rfcnotify/sweeper.go index 4c8d1b5e63..714621c914 100644 --- a/src/pkg/rfcnotify/sweeper.go +++ b/src/pkg/rfcnotify/sweeper.go @@ -32,9 +32,44 @@ 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) +} + +func toPublisher(post any) Publisher { + if post == nil { + return nil + } + switch p := post.(type) { + case Publisher: + return p + case Poster: + return p + case func(content string) error: + return Poster(p) + default: + return nil + } +} + // Values for Options.Format. const ( FormatLine = "line" @@ -55,8 +90,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 +173,10 @@ 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, post any) (Result, error) { var res Result - if src == nil || post == nil { + pub := toPublisher(post) + if src == nil || pub == nil { return res, fmt.Errorf("rfc notify: source and poster are required") } now := s.opts.Now() @@ -199,9 +235,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("", 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:]) From f3b1eeb5d9aaaa51d45958e184a796b14b67071d Mon Sep 17 00:00:00 2001 From: thatguywob Date: Sat, 31 Oct 2026 05:35:37 +0000 Subject: [PATCH 2/6] =?UTF-8?q?=F0=9F=90=9B=20fix:=20repair=20RFC=20notify?= =?UTF-8?q?=20card=20tests,=20bot=20client=20transport=20and=20trigger=20p?= =?UTF-8?q?ersistence=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Assign updated instead of since on fakeSource in card_test.go - Guard redirectTransport against nil httptest.Server in newTestBot - Provide statePath in TestRFCNotifyWire_CardFormatPostsEmbed to persist state across forcePoll - Point trigger persistence test storage paths to uncreatable locations Hive-Fix-Attempt: 1/6 Signed-off-by: thatguywob --- src/cmd/hive/rfcnotify_wire_test.go | 1 + src/pkg/dashboard/api_event_triggers_test.go | 3 ++- src/pkg/discord/bot_test.go | 8 +++++--- src/pkg/rfcnotify/card_test.go | 4 ++-- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/cmd/hive/rfcnotify_wire_test.go b/src/cmd/hive/rfcnotify_wire_test.go index a0492080b4..3d02d712f7 100644 --- a/src/cmd/hive/rfcnotify_wire_test.go +++ b/src/cmd/hive/rfcnotify_wire_test.go @@ -499,6 +499,7 @@ func TestRFCNotifyWire_CardFormatPostsEmbed(t *testing.T) { } pub := &testCardPublisher{} state := &rfcNotifyState{ + statePath: filepath.Join(t.TempDir(), "rfc-notify.json"), newPublisher: func(token, channel string) rfcnotify.Publisher { return pub }, diff --git a/src/pkg/dashboard/api_event_triggers_test.go b/src/pkg/dashboard/api_event_triggers_test.go index 926b33718d..5f08a4e662 100644 --- a/src/pkg/dashboard/api_event_triggers_test.go +++ b/src/pkg/dashboard/api_event_triggers_test.go @@ -174,7 +174,8 @@ 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() + 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_test.go b/src/pkg/discord/bot_test.go index ba8bbe8014..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 diff --git a/src/pkg/rfcnotify/card_test.go b/src/pkg/rfcnotify/card_test.go index f41f9ba29c..4270808512 100644 --- a/src/pkg/rfcnotify/card_test.go +++ b/src/pkg/rfcnotify/card_test.go @@ -325,7 +325,7 @@ func TestSweeperCardFormat_PostsCardAndFallsBackOnMalformed(t *testing.T) { // Poll 1: Well-formed RFC #2, and malformed RFC #3 now = now.Add(5 * time.Minute) - src.since = []Issue{ + src.updated = []Issue{ { Number: 2, Title: "RFC: Well-formed", @@ -396,7 +396,7 @@ func TestSweeperCardFormat_PostCardFailureRollsBack(t *testing.T) { // Fail the card post pub.fail = true now = now.Add(5 * time.Minute) - src.since = []Issue{ + src.updated = []Issue{ { Number: 2, Title: "RFC: Card fail", From c23c0870091e0b22127a2898776a6f8072fe57b4 Mon Sep 17 00:00:00 2001 From: thatguywob Date: Sat, 31 Oct 2026 05:37:14 +0000 Subject: [PATCH 3/6] =?UTF-8?q?=F0=9F=94=92=20fix:=20scrub=20Target,=20Sta?= =?UTF-8?q?tus,=20and=20Related=20fields=20in=20RFC=20summary=20card?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply logscrub.ScrubString to embed field values extracted from contributor-controlled RFC tables and add TestCard_FieldScrubbing. Signed-off-by: thatguywob --- src/pkg/rfcnotify/card.go | 6 +++--- src/pkg/rfcnotify/card_test.go | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/pkg/rfcnotify/card.go b/src/pkg/rfcnotify/card.go index c541f9536e..d6c47ee379 100644 --- a/src/pkg/rfcnotify/card.go +++ b/src/pkg/rfcnotify/card.go @@ -296,14 +296,14 @@ func Card(e Event, meta RFCMeta, includeRepo bool) Embed { if meta.Target != "" { fields = append(fields, discord.EmbedField{ Name: "Target", - Value: truncateRunes(meta.Target, MaxFieldValueRunes), + Value: truncateRunes(logscrub.ScrubString(meta.Target), MaxFieldValueRunes), Inline: true, }) } if meta.Status != "" { fields = append(fields, discord.EmbedField{ Name: "Status", - Value: truncateRunes(meta.Status, MaxFieldValueRunes), + Value: truncateRunes(logscrub.ScrubString(meta.Status), MaxFieldValueRunes), Inline: true, }) } @@ -317,7 +317,7 @@ func Card(e Event, meta RFCMeta, includeRepo bool) Embed { if len(meta.RelatedRFCLinks) > 0 { fields = append(fields, discord.EmbedField{ Name: "Related", - Value: truncateRunes(strings.Join(meta.RelatedRFCLinks, ", "), MaxFieldValueRunes), + Value: truncateRunes(logscrub.ScrubString(strings.Join(meta.RelatedRFCLinks, ", ")), MaxFieldValueRunes), Inline: false, }) } diff --git a/src/pkg/rfcnotify/card_test.go b/src/pkg/rfcnotify/card_test.go index 4270808512..af56a64493 100644 --- a/src/pkg/rfcnotify/card_test.go +++ b/src/pkg/rfcnotify/card_test.go @@ -187,6 +187,28 @@ func TestCard_FieldsAndMentionsSafety(t *testing.T) { } } +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 From ecb7b1cbe2b15b65ce41e9f07215d1d86c125bd9 Mon Sep 17 00:00:00 2001 From: thatguywob Date: Sat, 31 Oct 2026 05:54:54 +0000 Subject: [PATCH 4/6] =?UTF-8?q?=F0=9F=90=9B=20fix:=20remove=20ineffectual?= =?UTF-8?q?=20assignment=20and=20unreachable=20type=20switch=20case?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove ineffectual newPoster assignment and unused discordRFCPoster in cmd/hive/rfcnotify_wire.go - Remove unreachable Poster case in rfcnotify.toPublisher type switch Signed-off-by: thatguywob --- src/cmd/hive/rfcnotify_wire.go | 15 +-------------- src/pkg/rfcnotify/sweeper.go | 2 -- 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/src/cmd/hive/rfcnotify_wire.go b/src/cmd/hive/rfcnotify_wire.go index 361b1ce38c..169716b80d 100644 --- a/src/cmd/hive/rfcnotify_wire.go +++ b/src/cmd/hive/rfcnotify_wire.go @@ -46,7 +46,7 @@ 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. @@ -102,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{ @@ -152,15 +148,6 @@ func (p botPublisher) PostCard(content string, embed rfcnotify.Embed) (string, e return p.bot.SendEmbedTo(p.channel, content, embed) } -// 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) } - } -} - type rfcRepoVisibility struct { private bool at time.Time diff --git a/src/pkg/rfcnotify/sweeper.go b/src/pkg/rfcnotify/sweeper.go index 714621c914..3850ae33dc 100644 --- a/src/pkg/rfcnotify/sweeper.go +++ b/src/pkg/rfcnotify/sweeper.go @@ -61,8 +61,6 @@ func toPublisher(post any) Publisher { switch p := post.(type) { case Publisher: return p - case Poster: - return p case func(content string) error: return Poster(p) default: From 146f530e1765e7d62e597cc8c0604166096e2056 Mon Sep 17 00:00:00 2001 From: thatguywob Date: Sat, 31 Oct 2026 06:17:31 +0000 Subject: [PATCH 5/6] =?UTF-8?q?=F0=9F=90=9B=20fix:=20preserve=20RFC=20card?= =?UTF-8?q?=20transitions=20and=20type=20publisher=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Send the formatted lifecycle event alongside cards so Discord and plain-poster fallbacks retain the transition, URL and linked RFC. Exclude checked numbered decisions, require Publisher at compile time, and cover lifecycle transitions in both publishing paths. Drop the unrelated dashboard persistence test change as requested in review. Signed-off-by: thatguywob --- changelog.d/added-rfc-notify-cards.md | 2 +- src/docs/notifications.md | 2 +- src/pkg/dashboard/api_event_triggers_test.go | 3 +- src/pkg/rfcnotify/card.go | 3 +- src/pkg/rfcnotify/card_test.go | 73 ++++++++++++++++++-- src/pkg/rfcnotify/pr_test.go | 10 +-- src/pkg/rfcnotify/rfcnotify_test.go | 52 +++++++------- src/pkg/rfcnotify/sweeper.go | 19 +---- 8 files changed, 105 insertions(+), 59 deletions(-) diff --git a/changelog.d/added-rfc-notify-cards.md b/changelog.d/added-rfc-notify-cards.md index 79e5bc138c..506fb2eda7 100644 --- a/changelog.d/added-rfc-notify-cards.md +++ b/changelog.d/added-rfc-notify-cards.md @@ -1 +1 @@ -- Render RFC lifecycle notices as Discord summary-card embeds when `rfc_format: card` is configured on the designated announcer. +- 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/docs/notifications.md b/src/docs/notifications.md index 60424d7af2..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` renders each transition as 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_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 5f08a4e662..926b33718d 100644 --- a/src/pkg/dashboard/api_event_triggers_test.go +++ b/src/pkg/dashboard/api_event_triggers_test.go @@ -174,8 +174,7 @@ func TestEventTriggersRejectInvalidAndUnpersistedRules(t *testing.T) { t.Fatalf("failed persistence accepted: %d %s", failed.Code, failed.Body.String()) } cfg.SourcePath = t.TempDir() - unwritable := filepath.Join(t.TempDir(), "missing") - config.RuntimeConfigFile, config.DashboardOverlayFile = filepath.Join(unwritable, "runtime"), filepath.Join(unwritable, "overlay") + config.RuntimeConfigFile, config.DashboardOverlayFile = t.TempDir(), t.TempDir() 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/rfcnotify/card.go b/src/pkg/rfcnotify/card.go index d6c47ee379..1ed04800f8 100644 --- a/src/pkg/rfcnotify/card.go +++ b/src/pkg/rfcnotify/card.go @@ -48,6 +48,7 @@ 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+`) ) @@ -204,7 +205,7 @@ func isUncheckedCheckbox(line string) bool { } func isCheckedCheckbox(line string) bool { - return strings.HasPrefix(line, "- [x]") || strings.HasPrefix(line, "- [X]") || + 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]") } diff --git a/src/pkg/rfcnotify/card_test.go b/src/pkg/rfcnotify/card_test.go index af56a64493..0ee3c19a88 100644 --- a/src/pkg/rfcnotify/card_test.go +++ b/src/pkg/rfcnotify/card_test.go @@ -82,14 +82,18 @@ A short summary of changes. - [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 = 3 open decisions - if meta.OpenDecisions != 3 { - t.Errorf("OpenDecisions = %d, want 3", meta.OpenDecisions) + // Items 1, checkbox open, item 3, item 7 = 4 open decisions + if meta.OpenDecisions != 4 { + t.Errorf("OpenDecisions = %d, want 4", meta.OpenDecisions) } } @@ -303,9 +307,10 @@ func TestCard_ColorsByState(t *testing.T) { } type recordPublisher struct { - posted []string - cards []Embed - fail bool + posted []string + cards []Embed + cardContents []string + fail bool } func (p *recordPublisher) Post(content string) error { @@ -321,6 +326,7 @@ func (p *recordPublisher) PostCard(content string, embed Embed) (string, error) return "", errors.New("card post error") } p.cards = append(p.cards, embed) + p.cardContents = append(p.cardContents, content) return "msg-card-1", nil } @@ -379,6 +385,9 @@ func TestSweeperCardFormat_PostsCardAndFallsBackOnMalformed(t *testing.T) { 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) } @@ -449,3 +458,55 @@ func TestSweeperCardFormat_PostCardFailureRollsBack(t *testing.T) { 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_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 3850ae33dc..1b3d58f445 100644 --- a/src/pkg/rfcnotify/sweeper.go +++ b/src/pkg/rfcnotify/sweeper.go @@ -54,20 +54,6 @@ func (p Poster) PostCard(content string, embed Embed) (string, error) { return "", p(embed.Title) } -func toPublisher(post any) Publisher { - if post == nil { - return nil - } - switch p := post.(type) { - case Publisher: - return p - case func(content string) error: - return Poster(p) - default: - return nil - } -} - // Values for Options.Format. const ( FormatLine = "line" @@ -171,9 +157,8 @@ 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 any) (Result, error) { +func (s *Sweeper) Run(ctx context.Context, src Source, pub Publisher) (Result, error) { var res Result - pub := toPublisher(post) if src == nil || pub == nil { return res, fmt.Errorf("rfc notify: source and poster are required") } @@ -240,7 +225,7 @@ func (s *Sweeper) Run(ctx context.Context, src Source, post any) (Result, error) postErr = pub.Post(msg) } else { card := Card(ev, meta, s.opts.IncludeRepo) - _, postErr = pub.PostCard("", card) + _, postErr = pub.PostCard(msg, card) } } else { postErr = pub.Post(msg) From d53f1a9ae43c09f5b9b3cf7adb71916b311ed209 Mon Sep 17 00:00:00 2001 From: thatguywob Date: Sat, 31 Oct 2026 06:23:11 +0000 Subject: [PATCH 6/6] =?UTF-8?q?=F0=9F=90=9B=20test:=20make=20dashboard=20p?= =?UTF-8?q?ersistence=20failure=20fixture=20deterministic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI at 146f530e1 fails TestEventTriggersRejectInvalidAndUnpersistedRules in both dashboard 2/4 and dashboard shuffle 2/3. Save removes the empty directory used as RuntimeConfigFile and retries successfully, returning HTTP 200 instead of the expected failure. Use paths beneath a missing parent so persistence still fails after the remove-and-retry recovery. Keep this base-test repair separate from RFC card changes for review and bisectability. Related: #15978. Signed-off-by: thatguywob --- src/pkg/dashboard/api_event_triggers_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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) {