From 7e3b358c69b343e74338475e4080f4b37bfe53cc Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Tue, 27 Oct 2026 13:20:11 -0400 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20RFC=20lifecycle=20notices=20to?= =?UTF-8?q?=20Discord:=20opened,=20closed,=20and=20taken=20off=20hold=20(#?= =?UTF-8?q?14616)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add pkg/rfcnotify, a transition detector over polled issue snapshots that posts one Discord line when an RFC issue (rfc label or RFC-prefixed title) is opened, closed (completed or not planned), or has its hold lifted or moves from held to stage/010-actionable. Per-issue records persist in /data/rfc-notify.json so restarts and the slack re-read never re-post. - notifications.discord.rfc_channel_id (env HIVE_DISCORD_RFC_CHANNEL_ID), default empty = off; posts with the existing bot token through a new discord.Bot.SendMessageTo without starting the command bot. - github.Client.ListIssueSnapshots lists issues (not PRs) across managed repos by state and since, the raw input the actionable enumeration cannot provide for closed or held issues. - Wired into the eval cycle's optional sweeps next to the RFC existing-coverage check; each post is audited as rfc-notify. Signed-off-by: Andrew Anderson --- .../added-14616-rfc-discord-notifications.md | 1 + src/cmd/hive/boot.go | 3 + src/cmd/hive/rfcnotify_wire.go | 149 ++++++ src/cmd/hive/rfcnotify_wire_test.go | 153 ++++++ src/cmd/hive/run_loop_deps.go | 1 + src/docs/notifications.md | 19 + src/docs/operator-reference.md | 1 + src/pkg/config/config.go | 15 + src/pkg/discord/bot.go | 14 +- src/pkg/discord/bot_test.go | 20 + src/pkg/github/issue_snapshots.go | 97 ++++ src/pkg/github/issue_snapshots_test.go | 117 +++++ src/pkg/rfcnotify/detector.go | 217 +++++++++ src/pkg/rfcnotify/rfcnotify.go | 136 ++++++ src/pkg/rfcnotify/rfcnotify_test.go | 460 ++++++++++++++++++ src/pkg/rfcnotify/sweeper.go | 154 ++++++ 16 files changed, 1556 insertions(+), 1 deletion(-) create mode 100644 changelog.d/added-14616-rfc-discord-notifications.md create mode 100644 src/cmd/hive/rfcnotify_wire.go create mode 100644 src/cmd/hive/rfcnotify_wire_test.go create mode 100644 src/pkg/github/issue_snapshots.go create mode 100644 src/pkg/github/issue_snapshots_test.go create mode 100644 src/pkg/rfcnotify/detector.go create mode 100644 src/pkg/rfcnotify/rfcnotify.go create mode 100644 src/pkg/rfcnotify/rfcnotify_test.go create mode 100644 src/pkg/rfcnotify/sweeper.go diff --git a/changelog.d/added-14616-rfc-discord-notifications.md b/changelog.d/added-14616-rfc-discord-notifications.md new file mode 100644 index 0000000000..4cec422b7a --- /dev/null +++ b/changelog.d/added-14616-rfc-discord-notifications.md @@ -0,0 +1 @@ +- RFC lifecycle notices to Discord: with `notifications.discord.rfc_channel_id` set (env `HIVE_DISCORD_RFC_CHANNEL_ID`; default empty, off) and a bot token, the hive posts one line to that channel when an RFC issue in a managed repo is opened (`RFC opened: #N - <url> (by @author)`), closed (`RFC closed (completed|not planned): ...`), or taken off hold so it can be implemented (`RFC ready to implement (hold removed): ...`, on `hold` coming off an open RFC or a held RFC reaching `stage/010-actionable`, once per hold episode). An RFC is an issue with the `rfc` label or an `RFC`-prefixed title. The detector (`pkg/rfcnotify`) polls issues updated since its last pass and keeps per-issue records in `/data/rfc-notify.json`, so restarts never re-post and the first pass only records the baseline. Operators see each post in the audit log as `rfc-notify` (#14616). diff --git a/src/cmd/hive/boot.go b/src/cmd/hive/boot.go index a8e0748bf1..e1728bbdf6 100644 --- a/src/cmd/hive/boot.go +++ b/src/cmd/hive/boot.go @@ -251,6 +251,9 @@ type boot struct { // rfcCoverage is the triage existing-coverage check state // (issues.rfc_existing_check.*). rfcCoverage *rfcCoverageState + // rfcNotify is the RFC lifecycle Discord notice state + // (notifications.discord.rfc_channel_id). + rfcNotify *rfcNotifyState // reviewEvents queues webhook-triggered review dispatch and reviewWake // carries its wakes to the governor loop (hivecommons/hive#11091). diff --git a/src/cmd/hive/rfcnotify_wire.go b/src/cmd/hive/rfcnotify_wire.go new file mode 100644 index 0000000000..7065f079b6 --- /dev/null +++ b/src/cmd/hive/rfcnotify_wire.go @@ -0,0 +1,149 @@ +package main + +import ( + "context" + "fmt" + "log/slog" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/dashboard" + "github.com/hivecommons/hive/pkg/discord" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/rfcnotify" +) + +// rfcNotifyStatePath persists the RFC lifecycle detector's per-issue +// records so a restart does not re-announce a transition. +const rfcNotifyStatePath = "/data/rfc-notify.json" + +// rfcNotifyState is the process-lifetime half of the RFC lifecycle notices +// (notifications.discord.rfc_channel_id): the sweeper and the Discord +// poster, built once from the config that enabled them. +type rfcNotifyState struct { + sweeper *rfcnotify.Sweeper + post rfcnotify.Poster + // channel the poster was built for; a config change rebuilds it. + channel string + // statePath is rfcNotifyStatePath in production; tests point it at a + // temp dir. + statePath string + // newPoster builds the Discord poster; nil means discordRFCPoster. + // Tests inject a recorder. + newPoster func(token, channel string) rfcnotify.Poster +} + +// rfcNotifyState lazily builds the boot's notice state. +func (b *boot) rfcNotifyState() *rfcNotifyState { + if b.rfcNotify == nil { + b.rfcNotify = &rfcNotifyState{statePath: rfcNotifyStatePath} + } + return b.rfcNotify +} + +// rfcNotifySettings returns the bot token and channel when the notices are +// configured, or ok=false when either is missing. +func rfcNotifySettings(cfg *config.Config) (token, channel string, ok bool) { + if cfg == nil || cfg.Notifications.Discord == nil { + return "", "", false + } + d := cfg.Notifications.Discord + token, channel = strings.TrimSpace(d.BotToken), strings.TrimSpace(d.RFCChannelID) + return token, channel, token != "" && channel != "" +} + +// ensure (re)builds the sweeper and poster for the configured channel. +func (s *rfcNotifyState) ensure(cfg *config.Config, repos int, logger *slog.Logger) bool { + token, channel, ok := rfcNotifySettings(cfg) + if !ok { + return false + } + newPoster := s.newPoster + if newPoster == nil { + newPoster = discordRFCPoster(logger) + } + if s.sweeper == nil { + s.sweeper = rfcnotify.NewSweeper(rfcnotify.Options{ + StatePath: s.statePath, + IncludeRepo: repos > 1, + Logger: logger, + }) + } + if s.post == nil || s.channel != channel { + s.post = newPoster(token, channel) + 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) } + } +} + +// rfcNotifySource adapts the GitHub client to rfcnotify.Source. +type rfcNotifySource struct{ c *github.Client } + +// newRFCNotifySource returns nil without a client, which turns the pass off. +func newRFCNotifySource(c *github.Client) rfcnotify.Source { + if c == nil { + return nil + } + return rfcNotifySource{c: c} +} + +func (s rfcNotifySource) ListOpen(ctx context.Context) ([]rfcnotify.Issue, error) { + snaps, err := s.c.ListIssueSnapshots(ctx, github.IssueSnapshotOptions{State: "open"}) + return rfcNotifyIssues(snaps), err +} + +func (s rfcNotifySource) ListUpdatedSince(ctx context.Context, since time.Time) ([]rfcnotify.Issue, error) { + snaps, err := s.c.ListIssueSnapshots(ctx, github.IssueSnapshotOptions{State: "all", Since: since}) + return rfcNotifyIssues(snaps), err +} + +func rfcNotifyIssues(snaps []github.IssueSnapshot) []rfcnotify.Issue { + out := make([]rfcnotify.Issue, 0, len(snaps)) + for _, s := range snaps { + 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, + }) + } + return out +} + +// runRFCNotifySweep is the per-cycle RFC lifecycle pass +// (notifications.discord.rfc_channel_id, default off). The sweeper owns the +// cadence, so calling it every cycle costs nothing between polls; a poll is +// one list call per managed repo. Posts are audited per issue. +func runRFCNotifySweep(ctx context.Context, src rfcnotify.Source, repos int, cfg *config.Config, dashSrv *dashboard.Server, state *rfcNotifyState, logger *slog.Logger) rfcnotify.Result { + if logger == nil { + logger = slog.Default() + } + if src == nil || state == nil || !state.ensure(cfg, repos, logger) { + return rfcnotify.Result{} + } + res, err := state.sweeper.Run(ctx, src, state.post) + if err != nil { + logger.Warn("rfc notify sweep failed", "error", err) + return res + } + if res.Seeded { + logger.Info("rfc notify: baseline recorded; transitions announce from the next poll", "channel", state.channel) + } + if dashSrv != nil { + for i, ev := range res.Events { + dashSrv.AuditLogRecord("system", "rfc-notify", fmt.Sprintf("channel=%s %s", state.channel, res.Posted[i]), "", ev.Issue.Repo, ev.Issue.Number) + } + } + if len(res.Posted) > 0 || res.Errors > 0 { + logger.Info("rfc notify sweep", "posted", len(res.Posted), "errors", res.Errors) + } + return res +} diff --git a/src/cmd/hive/rfcnotify_wire_test.go b/src/cmd/hive/rfcnotify_wire_test.go new file mode 100644 index 0000000000..2be8ec23d2 --- /dev/null +++ b/src/cmd/hive/rfcnotify_wire_test.go @@ -0,0 +1,153 @@ +package main + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/rfcnotify" +) + +type rfcNotifyFakeSource struct { + open, updated []rfcnotify.Issue + opens, polls int +} + +func (f *rfcNotifyFakeSource) ListOpen(context.Context) ([]rfcnotify.Issue, error) { + f.opens++ + return f.open, nil +} + +func (f *rfcNotifyFakeSource) ListUpdatedSince(context.Context, time.Time) ([]rfcnotify.Issue, error) { + f.polls++ + return f.updated, nil +} + +func rfcNotifyConfig(token, channel string) *config.Config { + cfg := &config.Config{} + cfg.Project.Repos = []string{"hive"} + cfg.Notifications.Discord = &config.DiscordConfig{BotToken: token, RFCChannelID: channel} + return cfg +} + +func TestRunRFCNotifySweepDisabledIsNoOp(t *testing.T) { + src := &rfcNotifyFakeSource{open: []rfcnotify.Issue{{Repo: "o/r", Number: 1, Title: "RFC: a", State: "open"}}} + state := &rfcNotifyState{newPoster: func(string, string) rfcnotify.Poster { + t.Fatal("disabled notices must not build a poster") + return nil + }} + for _, cfg := range []*config.Config{nil, {}, rfcNotifyConfig("", "123"), rfcNotifyConfig("tok", "")} { + if res := runRFCNotifySweep(context.Background(), src, 1, cfg, nil, state, nil); res.Seeded || len(res.Posted) != 0 { + t.Fatalf("disabled config acted: %+v", res) + } + } + if src.opens != 0 { + t.Fatal("disabled notices must not list issues") + } + if res := runRFCNotifySweep(context.Background(), nil, 1, rfcNotifyConfig("tok", "123"), nil, state, nil); res.Seeded { + t.Fatal("no source must no-op") + } + if res := runRFCNotifySweep(context.Background(), src, 1, rfcNotifyConfig("tok", "123"), nil, nil, nil); res.Seeded { + t.Fatal("no state must no-op") + } +} + +func TestRunRFCNotifySweepSeedsThenPosts(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + var posted []string + var builtFor []string + state := &rfcNotifyState{ + statePath: filepath.Join(t.TempDir(), "rfc-notify.json"), + newPoster: func(token, channel string) rfcnotify.Poster { + builtFor = append(builtFor, token+"@"+channel) + return func(s string) error { posted = append(posted, s); return nil } + }, + } + held := rfcnotify.Issue{Repo: "hivecommons/hive", Number: 12062, Title: "[RFC]: Evidence pipeline", URL: "https://github.com/hivecommons/hive/issues/12062", State: "open", Labels: []string{"hold"}, CreatedAt: time.Now().Add(-time.Hour)} + src := &rfcNotifyFakeSource{open: []rfcnotify.Issue{held}} + cfg := rfcNotifyConfig("tok", "1540404487099777136") + + res := runRFCNotifySweep(context.Background(), src, 1, cfg, nil, state, logger) + if !res.Seeded || len(posted) != 0 || src.opens != 1 { + t.Fatalf("seed: %+v posted=%v opens=%d", res, posted, src.opens) + } + if len(builtFor) != 1 || builtFor[0] != "tok@1540404487099777136" { + t.Fatalf("poster built for %v", builtFor) + } + // Same cycle again: inside the interval, skipped without listing. + if res := runRFCNotifySweep(context.Background(), src, 1, cfg, nil, state, logger); !res.Skipped || src.polls != 0 { + t.Fatalf("expected skip: %+v polls=%d", res, src.polls) + } + // Force the next poll and lift the hold. + lifted := held + lifted.Labels = nil + src.updated = []rfcnotify.Issue{lifted} + state.sweeper = rfcnotify.NewSweeper(rfcnotify.Options{StatePath: state.statePath, Logger: logger}) + res = runRFCNotifySweep(context.Background(), src, 1, cfg, nil, state, logger) + if len(res.Posted) != 1 || len(posted) != 1 || !strings.HasPrefix(posted[0], "RFC ready to implement (hold removed): #12062 ") { + t.Fatalf("lift: %+v posted=%v", res, posted) + } + // A channel change rebuilds the poster; the token alone does not. + cfg.Notifications.Discord.RFCChannelID = "999" + state.sweeper = rfcnotify.NewSweeper(rfcnotify.Options{StatePath: state.statePath, Logger: logger}) + runRFCNotifySweep(context.Background(), src, 1, cfg, nil, state, logger) + if len(builtFor) != 2 || builtFor[1] != "tok@999" { + t.Fatalf("poster not rebuilt for the new channel: %v", builtFor) + } +} + +func TestRunRFCNotifySweepIncludesRepoForMultiRepoHive(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + var posted []string + state := &rfcNotifyState{ + statePath: filepath.Join(t.TempDir(), "rfc-notify.json"), + newPoster: func(string, string) rfcnotify.Poster { + return func(s string) error { posted = append(posted, s); return nil } + }, + } + cfg := rfcNotifyConfig("tok", "1") + cfg.Project.Repos = []string{"a", "b"} + src := &rfcNotifyFakeSource{} + runRFCNotifySweep(context.Background(), src, 2, cfg, nil, state, logger) + fresh := rfcnotify.Issue{Repo: "org/b", Number: 5, Title: "RFC: x", URL: "u", State: "open", Author: "bob", CreatedAt: time.Now().Add(time.Hour)} + src.updated = []rfcnotify.Issue{fresh} + state.sweeper = rfcnotify.NewSweeper(rfcnotify.Options{StatePath: state.statePath, IncludeRepo: true, Logger: logger}) + runRFCNotifySweep(context.Background(), src, 2, cfg, nil, state, logger) + if len(posted) != 1 || posted[0] != "RFC opened: org/b#5 RFC: x - <u> (by @bob)" { + t.Fatalf("posted = %v", posted) + } +} + +func TestRFCNotifySourceAdaptsClient(t *testing.T) { + if newRFCNotifySource(nil) != nil { + t.Fatal("nil client must yield a nil source") + } + var queries []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + queries = append(queries, r.URL.RawQuery) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"number":7,"title":"RFC: seven","state":"closed","state_reason":"completed","html_url":"https://x/7","user":{"login":"ann"},"labels":[{"name":"hold"}],"created_at":"2026-10-01T00:00:00Z","updated_at":"2026-10-27T00:00:00Z"}]`)) + })) + defer server.Close() + c := github.NewClientForTest(server.URL, "org", []string{"repo"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + src := newRFCNotifySource(c) + open, err := src.ListOpen(context.Background()) + if err != nil || len(open) != 1 || open[0].Repo != "org/repo" || open[0].Number != 7 || open[0].Author != "ann" || open[0].StateReason != "completed" || len(open[0].Labels) != 1 { + t.Fatalf("ListOpen = %+v %v", open, err) + } + since := time.Date(2026, 10, 27, 0, 0, 0, 0, time.UTC) + if _, err := src.ListUpdatedSince(context.Background(), since); err != nil { + t.Fatal(err) + } + if len(queries) != 2 || !strings.Contains(queries[0], "state=open") || !strings.Contains(queries[1], "state=all") || !strings.Contains(queries[1], "since=") { + t.Fatalf("queries = %v", queries) + } +} diff --git a/src/cmd/hive/run_loop_deps.go b/src/cmd/hive/run_loop_deps.go index 425e2592c1..852351135f 100644 --- a/src/cmd/hive/run_loop_deps.go +++ b/src/cmd/hive/run_loop_deps.go @@ -110,6 +110,7 @@ func defaultRunLoopDeps() runLoopDeps { runGoodFirstIssueSweepIfDue(b.ctx, b.ghClient, b.cfg, b.dashSrv, b.gfiState(), b.lastActionable.Load(), &b.lastGFISweep, b.logger) runFirstTimerWelcome(b.ctx, b.ghClient, b.cfg, b.dashSrv, b.firstTimerState(), b.firstTimerKnownContributor, b.lastActionable.Load(), b.logger) runRFCExistingCheck(b.ctx, newRFCCoverageForge(b.ghClient), b.cfg, b.dashSrv, b.rfcCoverageState(), b.lastActionable.Load(), b.logger) + runRFCNotifySweep(b.ctx, newRFCNotifySource(b.ghClient), len(b.cfg.Project.Repos), b.cfg, b.dashSrv, b.rfcNotifyState(), b.logger) }, persist: func(b *boot) { persistState(b.agentMgr, b.gov, b.cfg, spokeStatePath, b.logger, b.dashSrv, b.wd) diff --git a/src/docs/notifications.md b/src/docs/notifications.md index dbb5534777..19791d42d8 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -184,3 +184,22 @@ Webhook notifications are the `notifications.discord.webhook` field above. The repository also contains a separate Discord bot under [`../../discord/`](../../discord/). That bot is a Node.js service using `DISCORD_BOT_TOKEN` and `DISCORD_CHANNEL_PRIMARY` to connect to Discord, route commands, and bridge dashboard/pipeline status. It is not required for webhook notifications, and a bot token cannot replace `notifications.discord.webhook`. For the Hive Go process, bot startup uses `notifications.discord.bot_token` and `notifications.discord.channel_id` when both are set. Those fields start the bot integration; they do not send ordinary webhook notifications unless `notifications.discord.webhook` is also configured. + +## RFC lifecycle notices (Discord bot) + +Set `notifications.discord.rfc_channel_id` (or the env var `HIVE_DISCORD_RFC_CHANNEL_ID`, which overrides it) together with `notifications.discord.bot_token` and the hive posts one line to that channel when an RFC issue in a managed repo: + +- is opened: `RFC opened: #N <title> - <url> (by @author)` +- is closed: `RFC closed (completed): ...` or `RFC closed (not planned): ...`, from GitHub's close reason +- is taken off hold so it can be implemented: `RFC ready to implement (hold removed): #N <title> - <url>`, when the `hold` label (Prow `/unhold`) comes off an open RFC, or a held RFC moves to `stage/010-actionable`. One notice per hold episode. + +An issue is an RFC when it carries the `rfc` label or its title starts with `RFC` after any leading emoji or `[tag]` (`RFC: ...`, `[RFC] ...`, `📝 RFC: [v6] ...`). A hive that manages several repos prefixes the number with the repo (`owner/repo#N`). + +The default is empty, which turns the notices off. `channel_id` is not required: the notices only post with the bot token and never start the command bot. The hive polls GitHub every three minutes for issues updated since its last poll (one list call per repo) and keeps per-issue records in `/data/rfc-notify.json`, so a restart never re-announces a transition. The first poll after the key is set only records the current open RFCs; transitions announce from the next poll on. Each post is also written to the audit log as `rfc-notify`. + +```yaml +notifications: + discord: + bot_token: ${DISCORD_BOT_TOKEN} + rfc_channel_id: "1540404487099777136" +``` diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 2cd475b043..435d3ccf02 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -164,6 +164,7 @@ Top-level YAML keys accepted by `config.Config`: | `governor` | Cadences, labels, sensing, health, budgets, inference gateways, trajectory review. | See notable fields below. | | `github` | PAT or GitHub App credentials and forge URLs. | Use one auth method. | | `notifications` | ntfy, Slack, and Discord webhooks. | All optional; see [notifications.md](notifications.md). | +| `notifications.discord.rfc_channel_id` | empty (off). | Discord channel that receives RFC lifecycle notices (RFC issue opened, closed, or taken off hold) through `notifications.discord.bot_token`. Env override `HIVE_DISCORD_RFC_CHANNEL_ID`; see [RFC lifecycle notices](notifications.md#rfc-lifecycle-notices-discord-bot). | | `dashboard` | Web UI port, snapshots, auth token, frame allowlist, authorized users. | `auth_token` can come from `HIVE_DASHBOARD_TOKEN`. | | `agent_sandbox` | Podman-rootless sandbox launcher for hub/pod agents (`pkg/sandbox`). | Opt-in and **two-gate**: this block's own `enabled: true` sandboxes nothing by itself — each agent also needs `sandbox.enabled: true` under `agents.<name>`. The dashboard's Security tab writes only this global flag, so enabling it there alone can leave every agent unconfined — but the tab now shows this: `security.sandboxWarnings` in `GET /api/config/governor` carries `config.AgentSandboxGateWarnings`'s diagnosis (also logged at WARN at boot/reload), rendered both in the page's coherence-warnings box and inline under the toggle, naming the still-unconfined agents and the fixing key (#4918). See [sandbox-isolation.md](sandbox-isolation.md) and the [getting-started confinement section](getting-started.md#where-agents-actually-run-read-this-before-l3). | | `data` | Metrics, logs, session, and agent overlay directories. | Defaults are `/data/...` in containers. | diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index c54ba1e118..ec516ac36e 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -3932,6 +3932,9 @@ type SlackConfig struct { Webhook string `yaml:"webhook"` } +// DiscordRFCChannelIDEnvVar overrides notifications.discord.rfc_channel_id. +const DiscordRFCChannelIDEnvVar = "HIVE_DISCORD_RFC_CHANNEL_ID" + type DiscordConfig struct { Webhook string `yaml:"webhook"` FactoryWebhook string `yaml:"factory_webhook,omitempty"` @@ -3940,6 +3943,12 @@ type DiscordConfig struct { RequestsWebhookURL string `yaml:"requests_webhook_url,omitempty" json:"-"` BotToken string `yaml:"bot_token"` ChannelID string `yaml:"channel_id"` + // RFCChannelID is the channel that receives RFC lifecycle notices (an + // RFC issue opened, closed, or taken off hold; pkg/rfcnotify). Posted + // with BotToken; needs no ChannelID and does not start the command bot. + // Empty (the default) disables the notices. The env var + // HIVE_DISCORD_RFC_CHANNEL_ID overrides it. + RFCChannelID string `yaml:"rfc_channel_id,omitempty" json:"rfc_channel_id,omitempty"` // AllowedUsers is an allowlist of Discord user IDs permitted to issue bot // COMMANDS (!kick, !pause, agent actions — anything that drives an agent). // SECURITY: without it, any member of the guild who can post in the channel @@ -5425,6 +5434,12 @@ func (c *Config) applyBootstrapEnv() { c.Dashboard.AuthorizedUsers = parseAuthorizedUsers(v) } } + if v := strings.TrimSpace(os.Getenv(DiscordRFCChannelIDEnvVar)); v != "" { + if c.Notifications.Discord == nil { + c.Notifications.Discord = &DiscordConfig{} + } + c.Notifications.Discord.RFCChannelID = v + } if v := os.Getenv("HIVE_SELF_AUTHORIZATION_HOLD"); strings.TrimSpace(v) != "" { if b, err := strconv.ParseBool(strings.TrimSpace(v)); err == nil { c.GitHub.SelfAuthorizationHold = &b diff --git a/src/pkg/discord/bot.go b/src/pkg/discord/bot.go index eb68265d13..d2542bde3c 100644 --- a/src/pkg/discord/bot.go +++ b/src/pkg/discord/bot.go @@ -190,13 +190,25 @@ func (b *Bot) Start(ctx context.Context) error { } func (b *Bot) SendMessage(content string) error { + return b.SendMessageTo(b.channelID, content) +} + +// 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]string{"content": content} data, err := json.Marshal(payload) if err != nil { return err } - url := fmt.Sprintf("%s/channels/%s/messages", discordAPIBase, b.channelID) + url := fmt.Sprintf("%s/channels/%s/messages", discordAPIBase, channelID) req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) if err != nil { return err diff --git a/src/pkg/discord/bot_test.go b/src/pkg/discord/bot_test.go index 8a876620d5..30f813f6e9 100644 --- a/src/pkg/discord/bot_test.go +++ b/src/pkg/discord/bot_test.go @@ -1065,3 +1065,23 @@ func TestPollLoop_TickerFetchErrorPath(t *testing.T) { t.Error("expected at least one fetch attempt through the ticker, got 0") } } + +func TestSendMessageTo_OtherChannelAndEmptyChannel(t *testing.T) { + var gotPath string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + w.WriteHeader(http.StatusOK) + })) + defer ts.Close() + + b := newTestBot(ts, "status-channel") + if err := b.SendMessageTo("rfc-channel", "RFC opened"); err != nil { + t.Fatalf("SendMessageTo returned error: %v", err) + } + if !strings.HasSuffix(gotPath, "/channels/rfc-channel/messages") { + t.Fatalf("path = %q, want the explicit channel, not the status channel", gotPath) + } + if err := b.SendMessageTo(" ", "x"); err == nil { + t.Fatal("empty channel must error before any request") + } +} diff --git a/src/pkg/github/issue_snapshots.go b/src/pkg/github/issue_snapshots.go new file mode 100644 index 0000000000..73c922396d --- /dev/null +++ b/src/pkg/github/issue_snapshots.go @@ -0,0 +1,97 @@ +package github + +import ( + "context" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// IssueSnapshot is one issue as GitHub reports it at list time, independent +// of the enumeration's actionable filtering: open or closed, held or not. +// Repo is always owner/name. It is the raw input of transition detectors +// (pkg/rfcnotify) that need to see an issue leave the actionable set, which +// ActionableResult by construction cannot show. +type IssueSnapshot struct { + Repo string + Number int + Title string + URL string + Author string + // State is "open" or "closed". + State string + // StateReason is GitHub's state_reason: "completed", "not_planned", + // "reopened" or "" when GitHub did not report one. + StateReason string + Labels []string + CreatedAt time.Time + UpdatedAt time.Time + ClosedAt time.Time +} + +// IssueSnapshotOptions selects the issues ListIssueSnapshots returns. +type IssueSnapshotOptions struct { + // State is "open", "closed" or "all" (empty means "open"). + State string + // Since, when set, returns only issues updated at or after it. + Since time.Time +} + +// ListIssueSnapshots lists issues (never pull requests) across every managed +// repo, newest activity first, paging through GitHub's list endpoint. It +// stops at the first repo that fails so a caller never mistakes a partial +// read for a quiet period. +func (c *Client) ListIssueSnapshots(ctx context.Context, opts IssueSnapshotOptions) ([]IssueSnapshot, error) { + if c == nil || c.client == nil { + return nil, ErrNoGitHubClient + } + state := strings.ToLower(strings.TrimSpace(opts.State)) + if state == "" { + state = "open" + } + var out []IssueSnapshot + for _, repo := range c.getRepos() { + owner, repoName := c.splitRepo(repo) + listOpts := &gh.IssueListByRepoOptions{ + State: state, + Since: opts.Since, + Sort: "updated", + Direction: "desc", + ListOptions: gh.ListOptions{PerPage: 100}, + } + for { + issues, resp, err := c.client.Issues.ListByRepo(ctx, owner, repoName, listOpts) + if err != nil { + return nil, err + } + for _, issue := range issues { + if issue == nil || issue.IsPullRequest() { + continue + } + out = append(out, issueSnapshotFrom(owner+"/"+repoName, issue)) + } + if resp == nil || resp.NextPage == 0 { + break + } + listOpts.ListOptions.Page = resp.NextPage + } + } + return out, nil +} + +func issueSnapshotFrom(repo string, issue *gh.Issue) IssueSnapshot { + return IssueSnapshot{ + Repo: repo, + Number: issue.GetNumber(), + Title: issue.GetTitle(), + URL: issue.GetHTMLURL(), + Author: safeGetLogin(issue.GetUser()), + State: strings.ToLower(issue.GetState()), + StateReason: strings.ToLower(issue.GetStateReason()), + Labels: issueLabelNames(issue.Labels), + CreatedAt: issue.GetCreatedAt().Time, + UpdatedAt: issue.GetUpdatedAt().Time, + ClosedAt: issue.GetClosedAt().Time, + } +} diff --git a/src/pkg/github/issue_snapshots_test.go b/src/pkg/github/issue_snapshots_test.go new file mode 100644 index 0000000000..57cebd1edb --- /dev/null +++ b/src/pkg/github/issue_snapshots_test.go @@ -0,0 +1,117 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestListIssueSnapshots(t *testing.T) { + type wireIssue struct { + Number int `json:"number"` + Title string `json:"title"` + State string `json:"state"` + StateReason string `json:"state_reason,omitempty"` + HTMLURL string `json:"html_url"` + User wireUser `json:"user"` + Labels []wireLabel `json:"labels"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + ClosedAt string `json:"closed_at,omitempty"` + PullRequest *struct { + URL string `json:"url"` + } `json:"pull_request,omitempty"` + } + var gotQueries []string + mux := http.NewServeMux() + mux.HandleFunc("/repos/org/alpha/issues", func(w http.ResponseWriter, r *http.Request) { + gotQueries = append(gotQueries, r.URL.RawQuery) + w.Header().Set("Content-Type", "application/json") + if r.URL.Query().Get("page") == "2" { + _ = json.NewEncoder(w).Encode([]wireIssue{ + {Number: 3, Title: "RFC: closed one", State: "closed", StateReason: "not_planned", HTMLURL: "https://example.test/alpha/3", User: wireUser{Login: "carol"}, CreatedAt: "2026-10-01T00:00:00Z", UpdatedAt: "2026-10-27T10:00:00Z", ClosedAt: "2026-10-27T10:00:00Z"}, + }) + return + } + w.Header().Set("Link", fmt.Sprintf(`<%s/repos/org/alpha/issues?page=2>; rel="next"`, "http://"+r.Host)) + _ = json.NewEncoder(w).Encode([]wireIssue{ + {Number: 1, Title: "RFC: open one", State: "OPEN", HTMLURL: "https://example.test/alpha/1", User: wireUser{Login: "alice"}, Labels: []wireLabel{{Name: "hold"}, {Name: "proposal"}}, CreatedAt: "2026-10-20T00:00:00Z", UpdatedAt: "2026-10-27T11:00:00Z"}, + {Number: 2, Title: "a PR", State: "open", HTMLURL: "https://example.test/alpha/pull/2", PullRequest: &struct { + URL string `json:"url"` + }{URL: "x"}, CreatedAt: "2026-10-20T00:00:00Z", UpdatedAt: "2026-10-27T11:00:00Z"}, + }) + }) + mux.HandleFunc("/repos/org/beta/issues", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]wireIssue{ + {Number: 7, Title: "plain", State: "open", HTMLURL: "https://example.test/beta/7", CreatedAt: "2026-10-20T00:00:00Z", UpdatedAt: "2026-10-27T11:00:00Z"}, + }) + }) + mux.HandleFunc("/repos/org/broken/issues", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + }) + server := httptest.NewServer(mux) + defer server.Close() + + c := newTestClient(t, server, "org", []string{"alpha", "org/beta"}) + since := time.Date(2026, 10, 27, 9, 0, 0, 0, time.UTC) + got, err := c.ListIssueSnapshots(context.Background(), IssueSnapshotOptions{State: "all", Since: since}) + if err != nil { + t.Fatalf("list: %v", err) + } + if len(got) != 3 { + t.Fatalf("got %d snapshots, want 3 (PR dropped): %+v", len(got), got) + } + first := got[0] + if first.Repo != "org/alpha" || first.Number != 1 || first.State != "open" || first.Author != "alice" || first.URL != "https://example.test/alpha/1" { + t.Errorf("first = %+v", first) + } + if len(first.Labels) != 2 || first.Labels[0] != "hold" || !first.CreatedAt.Equal(time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC)) { + t.Errorf("first labels/created = %v %v", first.Labels, first.CreatedAt) + } + if got[1].Number != 3 || got[1].StateReason != "not_planned" || got[1].ClosedAt.IsZero() { + t.Errorf("second = %+v", got[1]) + } + if got[2].Repo != "org/beta" || got[2].Number != 7 || got[2].Author != "" { + t.Errorf("third = %+v", got[2]) + } + if len(gotQueries) != 2 { + t.Fatalf("alpha queries = %v, want two pages", gotQueries) + } + for _, want := range []string{"state=all", "since=2026-10-27T09%3A00%3A00Z", "sort=updated", "per_page=100"} { + if !containsQuery(gotQueries[0], want) { + t.Errorf("first query %q lacks %q", gotQueries[0], want) + } + } + + // Default state is open and a failing repo surfaces as an error. + gotQueries = nil + if _, err := c.ListIssueSnapshots(context.Background(), IssueSnapshotOptions{}); err != nil { + t.Fatalf("open list: %v", err) + } + if !containsQuery(gotQueries[0], "state=open") || containsQuery(gotQueries[0], "since=") { + t.Errorf("default query = %q, want state=open and no since", gotQueries[0]) + } + bad := newTestClient(t, server, "org", []string{"broken"}) + if _, err := bad.ListIssueSnapshots(context.Background(), IssueSnapshotOptions{}); err == nil { + t.Fatal("expected error from a failing repo") + } + var nilClient *Client + if _, err := nilClient.ListIssueSnapshots(context.Background(), IssueSnapshotOptions{}); err == nil { + t.Fatal("nil client must error") + } +} + +func containsQuery(raw, part string) bool { + for _, kv := range strings.Split(raw, "&") { + if kv == part || (strings.HasSuffix(part, "=") && strings.HasPrefix(kv, part)) { + return true + } + } + return false +} diff --git a/src/pkg/rfcnotify/detector.go b/src/pkg/rfcnotify/detector.go new file mode 100644 index 0000000000..bf6234c5c5 --- /dev/null +++ b/src/pkg/rfcnotify/detector.go @@ -0,0 +1,217 @@ +package rfcnotify + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "time" +) + +const ( + // stateVersion guards the on-disk shape. + stateVersion = 1 + // closedRetention is how long a closed issue's record is kept so a + // late re-read of the same close cannot post it twice. + closedRetention = 30 * 24 * time.Hour +) + +// issueRecord is what the detector remembers about one RFC between polls. +type issueRecord struct { + Open bool `json:"open"` + Held bool `json:"held"` + Actionable bool `json:"actionable"` + // ReadyAnnounced is set once a ready notice went out for the current + // hold episode; a new hold resets it. + ReadyAnnounced bool `json:"ready_announced,omitempty"` + LastSeen time.Time `json:"last_seen"` +} + +// State is the persisted detector memory. +type State struct { + Version int `json:"version"` + // Seeded is set after the first full read of open issues; before it, + // nothing is announced because there is no prior to compare against. + Seeded bool `json:"seeded"` + // Watermark is when the last successful poll ran; the next poll asks + // GitHub for issues updated since it (minus slack), and an unknown + // issue created after it counts as newly opened. + Watermark time.Time `json:"watermark"` + Issues map[string]*issueRecord `json:"issues"` +} + +// Detector turns successive issue snapshots into lifecycle events. +type Detector struct { + state State +} + +// NewDetector returns an empty, unseeded detector. +func NewDetector() *Detector { + return &Detector{state: State{Version: stateVersion, Issues: map[string]*issueRecord{}}} +} + +// Load reads a detector from path. A missing file yields an unseeded +// detector; a corrupt one is an error so the caller can decide, rather than +// silently re-announcing every RFC. +func Load(path string) (*Detector, error) { + d := NewDetector() + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return d, nil + } + if err != nil { + return nil, fmt.Errorf("read rfc notify state: %w", err) + } + var st State + if err := json.Unmarshal(data, &st); err != nil { + return nil, fmt.Errorf("parse rfc notify state: %w", err) + } + if st.Issues == nil { + st.Issues = map[string]*issueRecord{} + } + st.Version = stateVersion + d.state = st + return d, nil +} + +// Save writes the state to path (0600, directory created as needed). +func (d *Detector) Save(path string) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return fmt.Errorf("create rfc notify state dir: %w", err) + } + data, err := json.MarshalIndent(d.state, "", " ") + if err != nil { + return fmt.Errorf("marshal rfc notify state: %w", err) + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, data, 0o600); err != nil { + return fmt.Errorf("write rfc notify state: %w", err) + } + if err := os.Rename(tmp, path); err != nil { + return fmt.Errorf("replace rfc notify state: %w", err) + } + return nil +} + +// Seeded reports whether the detector has a baseline to diff against. +func (d *Detector) Seeded() bool { return d.state.Seeded } + +// Watermark is the time of the last successful poll (zero before seeding). +func (d *Detector) Watermark() time.Time { return d.state.Watermark } + +// Known reports whether the detector has a record for the issue key. +func (d *Detector) Known(key string) bool { _, ok := d.state.Issues[key]; return ok } + +// Seed records the current open issues without announcing anything and +// marks the detector seeded as of now. Call it once with the full open set. +func (d *Detector) Seed(issues []Issue, now time.Time) { + for _, is := range issues { + if !IsRFC(is.Title, is.Labels) { + continue + } + d.state.Issues[is.Key()] = recordOf(is, now) + } + d.state.Seeded = true + d.state.Watermark = now +} + +// Observe diffs issues (any issue updated since the last poll, open or +// closed) against the remembered records and returns the events to +// announce, in a stable order. It also advances the watermark to now and +// prunes closed records older than the retention window. Calling it with +// the same snapshot twice yields events only once. +func (d *Detector) Observe(issues []Issue, now time.Time) []Event { + if !d.state.Seeded { + d.Seed(issues, now) + return nil + } + var events []Event + for _, is := range issues { + if !IsRFC(is.Title, is.Labels) { + // An issue that stopped being an RFC (label dropped, title + // edited) is forgotten so a later re-labeling starts clean. + delete(d.state.Issues, is.Key()) + continue + } + key := is.Key() + prev, known := d.state.Issues[key] + cur := recordOf(is, now) + switch { + case !known: + if is.Open() && is.CreatedAt.After(d.state.Watermark) { + events = append(events, Event{Kind: KindOpened, Issue: is}) + } + case prev.Open && !cur.Open: + events = append(events, Event{Kind: KindClosed, Issue: is}) + case prev.Open && cur.Open && prev.Held: + // Inside a hold episode. One ready notice per episode: the + // flag rides along while the hold label stays on and resets + // once it is gone, so the next hold starts clean. + lifted := !cur.Held + staged := cur.Actionable && !prev.Actionable + if !prev.ReadyAnnounced && (lifted || staged) { + events = append(events, Event{Kind: KindReady, Issue: is}) + cur.ReadyAnnounced = true + } else if cur.Held { + cur.ReadyAnnounced = prev.ReadyAnnounced + } + } + d.state.Issues[key] = cur + } + d.state.Watermark = now + d.prune(now) + sort.SliceStable(events, func(i, j int) bool { + a, b := events[i].Issue, events[j].Issue + if a.Repo != b.Repo { + return a.Repo < b.Repo + } + return a.Number < b.Number + }) + return events +} + +func recordOf(is Issue, now time.Time) *issueRecord { + return &issueRecord{ + Open: is.Open(), + Held: is.Open() && Held(is.Labels), + Actionable: Actionable(is.Labels), + LastSeen: now, + } +} + +func (d *Detector) prune(now time.Time) { + for key, rec := range d.state.Issues { + if !rec.Open && now.Sub(rec.LastSeen) > closedRetention { + delete(d.state.Issues, key) + } + } +} + +// clone copies the state so an Observe can be partially undone. +func (d *Detector) clone() State { + out := d.state + out.Issues = make(map[string]*issueRecord, len(d.state.Issues)) + for k, v := range d.state.Issues { + rec := *v + out.Issues[k] = &rec + } + return out +} + +// rollback restores the records of the issues behind unposted events to +// what they were in before, and moves the watermark back so the next poll +// lists them again. Records of issues whose events were posted are kept. +func (d *Detector) rollback(before State, unposted []Event) { + for _, ev := range unposted { + key := ev.Issue.Key() + if rec, ok := before.Issues[key]; ok { + cp := *rec + d.state.Issues[key] = &cp + } else { + delete(d.state.Issues, key) + } + } + d.state.Watermark = before.Watermark +} diff --git a/src/pkg/rfcnotify/rfcnotify.go b/src/pkg/rfcnotify/rfcnotify.go new file mode 100644 index 0000000000..94645105c5 --- /dev/null +++ b/src/pkg/rfcnotify/rfcnotify.go @@ -0,0 +1,136 @@ +// Package rfcnotify posts an RFC issue's lifecycle to a Discord channel: +// opened, closed (completed or not planned), and taken off hold so it can be +// implemented. The detector is a pure function over successive issue +// snapshots plus a small persisted per-issue record, so a restart never +// re-posts a transition it already announced and a polling hive needs no +// webhook to see the change. +// +// An issue is an RFC when it carries the `rfc` label or its title is +// prefixed with RFC (`RFC: ...`, `[RFC] ...`, `📝 RFC: ...`), which is the +// convention hivecommons/hive uses (for example #12062). +package rfcnotify + +import ( + "fmt" + "regexp" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// RFCLabel marks an issue as an RFC regardless of its title. +const RFCLabel = "rfc" + +// Kind is one announced transition. +type Kind string + +const ( + // KindOpened: a new RFC issue appeared. + KindOpened Kind = "opened" + // KindClosed: an RFC issue went from open to closed. + KindClosed Kind = "closed" + // KindReady: an open RFC that was on hold is no longer held, or moved + // to the actionable stage while held. + KindReady Kind = "ready" +) + +const ( + closedCompleted = "completed" + closedNotPlanned = "not planned" +) + +// Issue is the detector's view of one issue at one point in time. +type Issue struct { + Repo string + Number int + Title string + URL string + Author string + State string + StateReason string + Labels []string + CreatedAt time.Time +} + +// Key is the per-issue identity the state is keyed by. +func (i Issue) Key() string { return fmt.Sprintf("%s#%d", i.Repo, i.Number) } + +// Open reports whether the issue is open. +func (i Issue) Open() bool { return strings.EqualFold(strings.TrimSpace(i.State), "open") } + +// Event is one transition to announce. +type Event struct { + Kind Kind + Issue Issue +} + +// rfcTitleRE matches a title whose first word, after any leading emoji, +// punctuation and bracketed tags such as [v6], is RFC. "RFCs" and a +// parenthetical "(RFC #13617)" later in the title do not match. +var rfcTitleRE = regexp.MustCompile(`(?i)^(?:[^\p{L}\p{N}]*(?:\[[^\]]*\])?)*\s*\[?RFC\b`) + +// IsRFC reports whether the issue is an RFC by label or title prefix. +func IsRFC(title string, labels []string) bool { + for _, l := range labels { + if strings.EqualFold(strings.TrimSpace(l), RFCLabel) { + return true + } + } + title = strings.TrimSpace(title) + loc := rfcTitleRE.FindStringIndex(title) + if loc == nil { + return false + } + // "RFC #123 follow-up" references an RFC rather than being one. + return !strings.HasPrefix(strings.TrimSpace(title[loc[1]:]), "#") +} + +// Held reports whether labels carry a hold label (Prow's `hold`, plus the +// spellings pkg/github treats as holds). +func Held(labels []string) bool { return github.HasHoldLabel(labels) } + +// Actionable reports whether labels carry the actionable stage label. +func Actionable(labels []string) bool { + want := stagelabels.Actionable.Label() + for _, l := range labels { + if strings.EqualFold(strings.TrimSpace(l), want) { + return true + } + } + return false +} + +// ClosedReason renders GitHub's state_reason for a closed issue. +func ClosedReason(stateReason string) string { + switch strings.ToLower(strings.TrimSpace(stateReason)) { + case "not_planned", "not planned": + return closedNotPlanned + default: + return closedCompleted + } +} + +// Format renders the Discord line for an event. The URL is wrapped in angle +// brackets so Discord does not add a preview card. includeRepo prefixes +// the issue number with its repo, for a hive that manages several. +func Format(e Event, includeRepo bool) string { + ref := fmt.Sprintf("#%d", e.Issue.Number) + if includeRepo && e.Issue.Repo != "" { + ref = e.Issue.Repo + ref + } + tail := fmt.Sprintf("%s %s - <%s>", ref, strings.TrimSpace(e.Issue.Title), strings.TrimSpace(e.Issue.URL)) + switch e.Kind { + case KindOpened: + if a := strings.TrimSpace(e.Issue.Author); a != "" { + return fmt.Sprintf("RFC opened: %s (by @%s)", tail, a) + } + return "RFC opened: " + tail + case KindClosed: + return fmt.Sprintf("RFC closed (%s): %s", ClosedReason(e.Issue.StateReason), tail) + case KindReady: + return "RFC ready to implement (hold removed): " + tail + } + return "RFC " + string(e.Kind) + ": " + tail +} diff --git a/src/pkg/rfcnotify/rfcnotify_test.go b/src/pkg/rfcnotify/rfcnotify_test.go new file mode 100644 index 0000000000..dcd123a7fe --- /dev/null +++ b/src/pkg/rfcnotify/rfcnotify_test.go @@ -0,0 +1,460 @@ +package rfcnotify + +import ( + "context" + "errors" + "io" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +var t0 = time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + +func rfc(n int, state string, labels ...string) Issue { + return Issue{ + Repo: "hivecommons/hive", Number: n, Title: "RFC: thing " + strings.Repeat("x", n%3), + URL: "https://github.com/hivecommons/hive/issues/1", Author: "alice", + State: state, Labels: labels, CreatedAt: t0.Add(-time.Hour), + } +} + +var quiet = slog.New(slog.NewTextHandler(io.Discard, nil)) + +func kinds(evs []Event) []Kind { + out := make([]Kind, 0, len(evs)) + for _, e := range evs { + out = append(out, e.Kind) + } + return out +} + +func TestIsRFC(t *testing.T) { + yes := []string{ + "RFC: Contribution UI", + "[RFC] Harden the Hub's login with PKCE", + "📝 RFC: [v6] Proxy egress allowlist", + "✨ RFC: Repo-targeted campaigns", + "[v6] RFC: something", + "rfc - lowercase works", + } + for _, title := range yes { + if !IsRFC(title, nil) { + t.Errorf("IsRFC(%q) = false, want true", title) + } + } + no := []string{ + "", + "[scanner] [v6] Your-turn critical path (RFC #13617 P1)", + "[v6] ✨ settings: expose config (RFC 11585 follow-up)", + "RFCs are great", + "RFC #123 follow-up", + "Fix the rfc parser", + } + for _, title := range no { + if IsRFC(title, nil) { + t.Errorf("IsRFC(%q) = true, want false", title) + } + } + if !IsRFC("plain title", []string{"enhancement", " RFC "}) { + t.Error("rfc label should mark an RFC regardless of title") + } + if IsRFC("plain title", []string{"enhancement"}) { + t.Error("unrelated label must not mark an RFC") + } +} + +func TestHeldAndActionable(t *testing.T) { + if !Held([]string{"hold"}) || !Held([]string{"do-not-merge/hold"}) || Held([]string{"enhancement"}) { + t.Error("Held mismatch") + } + if !Actionable([]string{"stage/010-actionable"}) || Actionable([]string{"stage/020-claimed"}) { + t.Error("Actionable mismatch") + } +} + +func TestFormat(t *testing.T) { + is := Issue{Repo: "hivecommons/hive", Number: 12062, Title: " RFC: Evidence pipeline ", URL: "https://github.com/hivecommons/hive/issues/12062", Author: "clubanderson"} + cases := []struct { + ev Event + includeRepo bool + want string + }{ + {Event{KindOpened, is}, false, "RFC opened: #12062 RFC: Evidence pipeline - <https://github.com/hivecommons/hive/issues/12062> (by @clubanderson)"}, + {Event{KindOpened, Issue{Number: 1, Title: "RFC: x", URL: "u"}}, false, "RFC opened: #1 RFC: x - <u>"}, + {Event{KindClosed, withReason(is, "completed")}, false, "RFC closed (completed): #12062 RFC: Evidence pipeline - <https://github.com/hivecommons/hive/issues/12062>"}, + {Event{KindClosed, withReason(is, "not_planned")}, true, "RFC closed (not planned): hivecommons/hive#12062 RFC: Evidence pipeline - <https://github.com/hivecommons/hive/issues/12062>"}, + {Event{KindClosed, withReason(is, "")}, false, "RFC closed (completed): #12062 RFC: Evidence pipeline - <https://github.com/hivecommons/hive/issues/12062>"}, + {Event{KindReady, is}, true, "RFC ready to implement (hold removed): hivecommons/hive#12062 RFC: Evidence pipeline - <https://github.com/hivecommons/hive/issues/12062>"}, + {Event{Kind("odd"), is}, false, "RFC odd: #12062 RFC: Evidence pipeline - <https://github.com/hivecommons/hive/issues/12062>"}, + } + for _, c := range cases { + if got := Format(c.ev, c.includeRepo); got != c.want { + t.Errorf("Format(%s)\n got %q\nwant %q", c.ev.Kind, got, c.want) + } + } +} + +func withReason(is Issue, reason string) Issue { + is.State = "closed" + is.StateReason = reason + return is +} + +func TestDetectorSeedThenOpened(t *testing.T) { + d := NewDetector() + if d.Seeded() { + t.Fatal("new detector must not be seeded") + } + // Observe before seeding takes a baseline and announces nothing. + if evs := d.Observe([]Issue{rfc(1, "open"), rfc(2, "open", "hold")}, t0); len(evs) != 0 { + t.Fatalf("unseeded observe announced %v", kinds(evs)) + } + if !d.Seeded() || !d.Known("hivecommons/hive#1") || !d.Known("hivecommons/hive#2") { + t.Fatal("seed did not record the baseline") + } + // A pre-existing issue not in the seed (closed at seed time, now + // updated) is recorded silently. + old := rfc(3, "open") + old.CreatedAt = t0.Add(-2 * time.Hour) + // A new RFC created after the watermark is announced once. + fresh := rfc(4, "open") + fresh.CreatedAt = t0.Add(time.Minute) + // A non-RFC issue is ignored entirely. + plain := Issue{Repo: "hivecommons/hive", Number: 5, Title: "Fix a bug", State: "open", CreatedAt: t0.Add(time.Minute)} + evs := d.Observe([]Issue{old, fresh, plain}, t0.Add(2*time.Minute)) + if got := kinds(evs); len(got) != 1 || got[0] != KindOpened || evs[0].Issue.Number != 4 { + t.Fatalf("events = %v (%+v)", got, evs) + } + if d.Known("hivecommons/hive#5") { + t.Error("non-RFC must not be recorded") + } + // Re-observing the same snapshot posts nothing. + if evs := d.Observe([]Issue{old, fresh, plain}, t0.Add(3*time.Minute)); len(evs) != 0 { + t.Fatalf("double post: %v", kinds(evs)) + } +} + +func TestDetectorClosedBothReasons(t *testing.T) { + d := NewDetector() + d.Seed([]Issue{rfc(1, "open"), rfc(2, "open")}, t0) + done := withReason(rfc(1, "open"), "completed") + dropped := withReason(rfc(2, "open"), "not_planned") + evs := d.Observe([]Issue{dropped, done}, t0.Add(time.Minute)) + if got := kinds(evs); len(got) != 2 || got[0] != KindClosed || got[1] != KindClosed { + t.Fatalf("events = %v", got) + } + if evs[0].Issue.Number != 1 || evs[1].Issue.Number != 2 { + t.Fatalf("events not ordered by number: %+v", evs) + } + if ClosedReason(evs[0].Issue.StateReason) != "completed" || ClosedReason(evs[1].Issue.StateReason) != "not planned" { + t.Fatalf("reasons = %q %q", evs[0].Issue.StateReason, evs[1].Issue.StateReason) + } + if evs := d.Observe([]Issue{dropped, done}, t0.Add(2*time.Minute)); len(evs) != 0 { + t.Fatalf("closed announced twice: %v", kinds(evs)) + } + // Reopen then close again announces the second close. + if evs := d.Observe([]Issue{rfc(1, "open")}, t0.Add(3*time.Minute)); len(evs) != 0 { + t.Fatalf("reopen announced %v", kinds(evs)) + } + if evs := d.Observe([]Issue{done}, t0.Add(4*time.Minute)); len(evs) != 1 || evs[0].Kind != KindClosed { + t.Fatalf("second close = %v", kinds(evs)) + } +} + +func TestDetectorHoldRemoved(t *testing.T) { + d := NewDetector() + d.Seed([]Issue{rfc(1, "open", "hold", "proposal")}, t0) + // Unrelated label churn while held: nothing. + if evs := d.Observe([]Issue{rfc(1, "open", "hold", "proposal", "help wanted")}, t0.Add(time.Minute)); len(evs) != 0 { + t.Fatalf("label churn announced %v", kinds(evs)) + } + evs := d.Observe([]Issue{rfc(1, "open", "proposal", "help wanted")}, t0.Add(2*time.Minute)) + if got := kinds(evs); len(got) != 1 || got[0] != KindReady { + t.Fatalf("events = %v", got) + } + // Same snapshot again, and further unrelated label changes: nothing. + if evs := d.Observe([]Issue{rfc(1, "open", "proposal")}, t0.Add(3*time.Minute)); len(evs) != 0 { + t.Fatalf("ready announced twice: %v", kinds(evs)) + } + // Re-held and lifted again is a new episode. + if evs := d.Observe([]Issue{rfc(1, "open", "hold")}, t0.Add(4*time.Minute)); len(evs) != 0 { + t.Fatalf("re-hold announced %v", kinds(evs)) + } + if evs := d.Observe([]Issue{rfc(1, "open")}, t0.Add(5*time.Minute)); len(evs) != 1 || evs[0].Kind != KindReady { + t.Fatalf("second lift = %v", kinds(evs)) + } + // Hold removed together with the close is a close, not a ready. + d.Seed([]Issue{rfc(2, "open", "hold")}, t0) + if evs := d.Observe([]Issue{withReason(rfc(2, "open"), "completed")}, t0.Add(time.Minute)); len(evs) != 1 || evs[0].Kind != KindClosed { + t.Fatalf("close while held = %v", kinds(evs)) + } + // Adding hold to an open RFC that was not held announces nothing. + d.Seed([]Issue{rfc(3, "open")}, t0) + if evs := d.Observe([]Issue{rfc(3, "open", "hold")}, t0.Add(time.Minute)); len(evs) != 0 { + t.Fatalf("hold added announced %v", kinds(evs)) + } +} + +func TestDetectorHeldToActionableDedupes(t *testing.T) { + d := NewDetector() + d.Seed([]Issue{rfc(1, "open", "hold")}, t0) + evs := d.Observe([]Issue{rfc(1, "open", "hold", "stage/010-actionable")}, t0.Add(time.Minute)) + if got := kinds(evs); len(got) != 1 || got[0] != KindReady { + t.Fatalf("held to actionable = %v", got) + } + // Hold label removed afterwards: already announced for this episode. + if evs := d.Observe([]Issue{rfc(1, "open", "stage/010-actionable")}, t0.Add(2*time.Minute)); len(evs) != 0 { + t.Fatalf("second ready after stage transition: %v", kinds(evs)) + } + // Actionable already present when held, then lifted: one ready. + d.Seed([]Issue{rfc(2, "open", "hold", "stage/010-actionable")}, t0) + if evs := d.Observe([]Issue{rfc(2, "open", "hold", "stage/010-actionable", "x")}, t0.Add(time.Minute)); len(evs) != 0 { + t.Fatalf("still held announced %v", kinds(evs)) + } + if evs := d.Observe([]Issue{rfc(2, "open", "stage/010-actionable")}, t0.Add(2*time.Minute)); len(evs) != 1 || evs[0].Kind != KindReady { + t.Fatalf("lift = %v", kinds(evs)) + } +} + +func TestDetectorForgetsIssueThatStopsBeingRFC(t *testing.T) { + d := NewDetector() + d.Seed([]Issue{rfc(1, "open")}, t0) + plain := rfc(1, "open") + plain.Title = "not one any more" + d.Observe([]Issue{plain}, t0.Add(time.Minute)) + if d.Known("hivecommons/hive#1") { + t.Fatal("record should be dropped") + } +} + +func TestDetectorPrunesOldClosed(t *testing.T) { + d := NewDetector() + d.Seed([]Issue{rfc(1, "open")}, t0) + d.Observe([]Issue{withReason(rfc(1, "open"), "completed")}, t0.Add(time.Minute)) + if !d.Known("hivecommons/hive#1") { + t.Fatal("closed record kept inside retention") + } + d.Observe(nil, t0.Add(closedRetention+2*time.Minute)) + if d.Known("hivecommons/hive#1") { + t.Fatal("closed record should be pruned after retention") + } +} + +func TestLoadSaveRoundTrip(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "nested", "rfc-notify.json") + d := NewDetector() + d.Seed([]Issue{rfc(1, "open", "hold")}, t0) + if err := d.Save(path); err != nil { + t.Fatal(err) + } + loaded, err := Load(path) + if err != nil { + t.Fatal(err) + } + if !loaded.Seeded() || !loaded.Watermark().Equal(t0) || !loaded.Known("hivecommons/hive#1") { + t.Fatalf("round trip lost state: %+v", loaded.state) + } + // Restart then lift the hold: announced exactly once, from the + // persisted record. + if evs := loaded.Observe([]Issue{rfc(1, "open")}, t0.Add(time.Minute)); len(evs) != 1 || evs[0].Kind != KindReady { + t.Fatalf("after restart = %v", kinds(evs)) + } + + missing, err := Load(filepath.Join(dir, "none.json")) + if err != nil || missing.Seeded() { + t.Fatalf("missing file: %v %v", err, missing.Seeded()) + } + if err := os.WriteFile(filepath.Join(dir, "bad.json"), []byte("{nope"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Load(filepath.Join(dir, "bad.json")); err == nil { + t.Fatal("corrupt state must error") + } + if err := os.WriteFile(filepath.Join(dir, "null.json"), []byte(`{"seeded":true}`), 0o600); err != nil { + t.Fatal(err) + } + if nul, err := Load(filepath.Join(dir, "null.json")); err != nil || nul.state.Issues == nil { + t.Fatalf("nil issues map not repaired: %v", err) + } + if err := os.Mkdir(filepath.Join(dir, "unreadable.json"), 0o700); err != nil { + t.Fatal(err) + } + if _, err := Load(filepath.Join(dir, "unreadable.json")); err == nil { + t.Fatal("directory as state must error") + } + if err := d.Save(filepath.Join(dir, "bad.json", "y.json")); err == nil { + t.Fatal("save under a regular file must error") + } +} + +// fakeSource scripts the two listings. +type fakeSource struct { + open []Issue + updated []Issue + since []time.Time + openErr error + updErr error +} + +func (f *fakeSource) ListOpen(context.Context) ([]Issue, error) { return f.open, f.openErr } +func (f *fakeSource) ListUpdatedSince(_ context.Context, since time.Time) ([]Issue, error) { + f.since = append(f.since, since) + return f.updated, f.updErr +} + +func TestSweeperSeedsThenPostsAndPersists(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "rfc-notify.json") + now := t0 + clock := func() time.Time { return now } + var posted []string + post := func(s string) error { posted = append(posted, s); return nil } + 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) + if err != nil || !res.Seeded || len(posted) != 0 { + t.Fatalf("seed run: %+v %v posted=%v", res, err, posted) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("state not persisted: %v", err) + } + // Within the interval: skipped, no listing. + now = now.Add(time.Minute) + if res, _ := sw.Run(context.Background(), src, post); !res.Skipped { + t.Fatal("expected skip inside the interval") + } + // Next poll: hold lifted on #1, #2 closed, new #3 opened. + now = now.Add(DefaultInterval) + 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) + if err != nil || res.Errors != 0 || len(res.Posted) != 3 { + t.Fatalf("poll run: %+v %v", res, err) + } + if len(src.since) != 1 || !src.since[0].Equal(t0.Add(-DefaultSlack)) { + t.Fatalf("since = %v, want watermark minus slack", src.since) + } + wantPrefixes := []string{"RFC ready to implement (hold removed): hivecommons/hive#1 ", "RFC closed (not planned): hivecommons/hive#2 ", "RFC opened: hivecommons/hive#3 "} + for i, p := range wantPrefixes { + if !strings.HasPrefix(posted[i], p) { + t.Errorf("posted[%d] = %q, want prefix %q", i, posted[i], p) + } + } + // A new sweeper on the same state file (restart) re-reads the same + // snapshot and posts nothing. + now = now.Add(DefaultInterval) + posted = nil + sw2 := NewSweeper(Options{StatePath: path, Now: clock, Logger: quiet}) + res, err = sw2.Run(context.Background(), src, post) + if err != nil || len(posted) != 0 || res.Seeded { + t.Fatalf("restart re-posted: %+v %v %v", res, err, posted) + } +} + +func TestSweeperPostFailureRetriesNextPoll(t *testing.T) { + now := t0 + 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 { + t.Fatal(err) + } + now = now.Add(DefaultInterval) + src.updated = []Issue{withReason(rfc(1, "open"), "completed"), withReason(rfc(2, "open"), "completed")} + calls := 0 + failSecond := func(string) error { + calls++ + if calls == 2 { + return errors.New("discord down") + } + return nil + } + res, err := sw.Run(context.Background(), src, failSecond) + if err != nil || res.Errors != 1 || len(res.Posted) != 1 { + t.Fatalf("first run: %+v %v", res, err) + } + // The watermark rolled back so the next listing covers the same window. + if !sw.Detector().Watermark().Equal(t0) { + t.Fatalf("watermark = %v, want %v", sw.Detector().Watermark(), t0) + } + now = now.Add(DefaultInterval) + var posted []string + res, err = sw.Run(context.Background(), src, 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 { + t.Fatal("re-posted") + } +} + +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 { + 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 { + 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 { + t.Fatalf("retry: %+v", res) + } +} + +func TestSweeperErrors(t *testing.T) { + sw := NewSweeper(Options{}) + if _, err := sw.Run(context.Background(), nil, nil); err == nil { + 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 { + 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 { + 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 { + t.Fatal("list error must surface") + } +} + +func TestNewSweeperUnreadableStateStartsFresh(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bad.json") + if err := os.WriteFile(path, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + sw := NewSweeper(Options{StatePath: path, Logger: quiet}) + if sw.Detector().Seeded() { + t.Fatal("fresh detector expected") + } + // 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 { + t.Fatal("save into a directory path must error") + } +} diff --git a/src/pkg/rfcnotify/sweeper.go b/src/pkg/rfcnotify/sweeper.go new file mode 100644 index 0000000000..e47c9ba9e8 --- /dev/null +++ b/src/pkg/rfcnotify/sweeper.go @@ -0,0 +1,154 @@ +package rfcnotify + +import ( + "context" + "fmt" + "log/slog" + "time" +) + +const ( + // DefaultInterval is how often a hive polls for RFC transitions. + DefaultInterval = 3 * time.Minute + // DefaultSlack is re-read behind the watermark so an update that + // landed while the previous poll ran is not missed; the per-issue + // records make the overlap idempotent. + DefaultSlack = 2 * time.Minute +) + +// Source lists issues. ListOpen returns every open issue (the seed); +// ListUpdatedSince returns every issue, open or closed, updated at or after +// since. +type Source interface { + ListOpen(ctx context.Context) ([]Issue, error) + ListUpdatedSince(ctx context.Context, since time.Time) ([]Issue, error) +} + +// Poster sends one message to the configured channel. +type Poster func(content string) error + +// Options tune one Sweeper. +type Options struct { + // StatePath persists the detector between restarts. Empty keeps the + // state in memory only. + StatePath string + // Interval between polls; non-positive means DefaultInterval. + Interval time.Duration + // Slack re-read behind the watermark; non-positive means DefaultSlack. + Slack time.Duration + // IncludeRepo prefixes issue numbers with their repo. + IncludeRepo bool + Logger *slog.Logger + // Now is the clock; nil means time.Now. + Now func() time.Time +} + +// Result summarises one Run. +type Result struct { + // Skipped is true when the interval had not elapsed. + Skipped bool + // Seeded is true when this run took the baseline instead of diffing. + Seeded bool + // Posted lists the messages sent, in order; Events are the matching + // transitions. + Posted []string + Events []Event + // Errors counts failed posts; the failed events stay unannounced and + // are retried on the next poll because the state is not advanced for + // them. + Errors int +} + +// Sweeper owns the detector and its cadence. +type Sweeper struct { + opts Options + det *Detector + lastRun time.Time +} + +// NewSweeper loads the state at opts.StatePath (an unreadable file logs +// and starts fresh, which re-seeds silently rather than re-announcing). +func NewSweeper(opts Options) *Sweeper { + if opts.Interval <= 0 { + opts.Interval = DefaultInterval + } + if opts.Slack <= 0 { + opts.Slack = DefaultSlack + } + if opts.Logger == nil { + opts.Logger = slog.Default() + } + if opts.Now == nil { + opts.Now = time.Now + } + det := NewDetector() + if opts.StatePath != "" { + loaded, err := Load(opts.StatePath) + if err != nil { + opts.Logger.Warn("rfc notify: state unreadable; starting fresh", "path", opts.StatePath, "error", err) + } else { + det = loaded + } + } + return &Sweeper{opts: opts, det: det} +} + +// Detector exposes the sweeper's detector for inspection. +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) { + var res Result + if src == nil || post == nil { + return res, fmt.Errorf("rfc notify: source and poster are required") + } + now := s.opts.Now() + if !s.lastRun.IsZero() && now.Sub(s.lastRun) < s.opts.Interval { + res.Skipped = true + return res, nil + } + s.lastRun = now + + if !s.det.Seeded() { + open, err := src.ListOpen(ctx) + if err != nil { + return res, fmt.Errorf("rfc notify: seed: %w", err) + } + s.det.Seed(open, now) + res.Seeded = true + return res, s.save() + } + + since := s.det.Watermark().Add(-s.opts.Slack) + issues, err := src.ListUpdatedSince(ctx, since) + if err != nil { + return res, fmt.Errorf("rfc notify: list since %s: %w", since.Format(time.RFC3339), err) + } + // Diff against a copy first so a failed post leaves the state where + // the event will be seen again next poll. + before := s.det.clone() + events := s.det.Observe(issues, now) + for i, ev := range events { + msg := Format(ev, s.opts.IncludeRepo) + if err := post(msg); err != nil { + res.Errors++ + s.opts.Logger.Warn("rfc notify: post failed", "issue", ev.Issue.Key(), "kind", ev.Kind, "error", err) + // 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:]) + break + } + res.Posted = append(res.Posted, msg) + res.Events = append(res.Events, ev) + } + return res, s.save() +} + +func (s *Sweeper) save() error { + if s.opts.StatePath == "" { + return nil + } + return s.det.Save(s.opts.StatePath) +} From ccb3598c16da7fb57083c4adf88c6880bfe0a80e Mon Sep 17 00:00:00 2001 From: Andrew Anderson <andy@clubanderson.com> Date: Tue, 27 Oct 2026 13:37:11 -0400 Subject: [PATCH 2/2] Add Settings control for notifications.discord.rfc_channel_id The Settings parity test requires every hive.yaml leaf to have a Settings dialog control. Expose the RFC channel id in the Discord bot subgroup, round-trip it through the notifications settings handler, and cover it in the handler test. Signed-off-by: Andrew Anderson <andy@clubanderson.com> --- src/pkg/dashboard/notifications_settings.go | 10 ++++++++-- src/pkg/dashboard/notifications_settings_test.go | 6 +++++- src/pkg/dashboard/static/index.html | 5 +++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/pkg/dashboard/notifications_settings.go b/src/pkg/dashboard/notifications_settings.go index 9f854e9051..e6c426f50d 100644 --- a/src/pkg/dashboard/notifications_settings.go +++ b/src/pkg/dashboard/notifications_settings.go @@ -15,6 +15,7 @@ import ( type notificationsExtraBody struct { DiscordBotToken *string `json:"discordBotToken"` DiscordChannelID *string `json:"discordChannelId"` + DiscordRFCChannelID *string `json:"discordRfcChannelId"` DiscordAllowedUsers []string `json:"discordAllowedUsers"` DiscordFactoryWebhook *string `json:"discordFactoryWebhook"` DiscordRequestsWebhookURL *string `json:"discordRequestsWebhookUrl"` @@ -35,7 +36,7 @@ type githubActivitySettingsBody struct { } func (b notificationsExtraBody) empty() bool { - return b.DiscordBotToken == nil && b.DiscordChannelID == nil && b.DiscordAllowedUsers == nil && + return b.DiscordBotToken == nil && b.DiscordChannelID == nil && b.DiscordRFCChannelID == nil && b.DiscordAllowedUsers == nil && b.DiscordFactoryWebhook == nil && b.DiscordRequestsWebhookURL == nil && b.GitHubActivity == nil } @@ -95,6 +96,9 @@ func applyNotificationsExtra(cfg *config.Config, body notificationsExtraBody) er if body.DiscordChannelID != nil { discord.ChannelID = strings.TrimSpace(*body.DiscordChannelID) } + if body.DiscordRFCChannelID != nil { + discord.RFCChannelID = strings.TrimSpace(*body.DiscordRFCChannelID) + } if body.DiscordAllowedUsers != nil { discord.AllowedUsers = cleanSettingsList(body.DiscordAllowedUsers) } @@ -157,7 +161,7 @@ func applyNotificationsExtra(cfg *config.Config, body notificationsExtraBody) er } } - discordTouched := body.DiscordBotToken != nil || body.DiscordChannelID != nil || body.DiscordAllowedUsers != nil || + discordTouched := body.DiscordBotToken != nil || body.DiscordChannelID != nil || body.DiscordRFCChannelID != nil || body.DiscordAllowedUsers != nil || body.DiscordFactoryWebhook != nil || body.DiscordRequestsWebhookURL != nil if cfg.Notifications.Discord != nil || discordTouched { cfg.Notifications.Discord = &discord @@ -171,6 +175,7 @@ func applyNotificationsExtra(cfg *config.Config, body notificationsExtraBody) er // (factory webhook as a masked tail); their values are never echoed. func notificationsExtraPayload(cfg *config.Config, out map[string]any) { out["discordChannelId"] = "" + out["discordRfcChannelId"] = "" out["discordAllowedUsers"] = []string{} out["discordFactoryWebhook"] = "" out["hasDiscordBotToken"] = false @@ -178,6 +183,7 @@ func notificationsExtraPayload(cfg *config.Config, out map[string]any) { out["hasDiscordRequestsWebhook"] = false if d := cfg.Notifications.Discord; d != nil { out["discordChannelId"] = d.ChannelID + out["discordRfcChannelId"] = d.RFCChannelID out["discordAllowedUsers"] = append([]string{}, d.AllowedUsers...) out["discordFactoryWebhook"] = maskSecret(d.FactoryWebhook) out["hasDiscordBotToken"] = d.BotToken != "" diff --git a/src/pkg/dashboard/notifications_settings_test.go b/src/pkg/dashboard/notifications_settings_test.go index bd8d42f0aa..c168d6c5cf 100644 --- a/src/pkg/dashboard/notifications_settings_test.go +++ b/src/pkg/dashboard/notifications_settings_test.go @@ -37,6 +37,7 @@ func TestNotificationsSettingsDiscordBotAndGitHubActivityRoundTrip(t *testing.T) rec := doPut(s, notificationsSettings, map[string]any{ "discordBotToken": testDiscordBotToken, "discordChannelId": " 1234567890 ", + "discordRfcChannelId": " 1540404487099777136 ", "discordAllowedUsers": []string{" 42 ", "", "42", "77"}, "discordFactoryWebhook": testFactoryWebhook, "discordRequestsWebhookUrl": testRequestsWebhook, @@ -61,7 +62,7 @@ func TestNotificationsSettingsDiscordBotAndGitHubActivityRoundTrip(t *testing.T) if d == nil { t.Fatal("discord config not created") } - if d.BotToken != testDiscordBotToken || d.ChannelID != "1234567890" || + if d.BotToken != testDiscordBotToken || d.ChannelID != "1234567890" || d.RFCChannelID != "1540404487099777136" || d.FactoryWebhook != testFactoryWebhook || d.RequestsWebhookURL != testRequestsWebhook { t.Fatalf("discord config = %+v", d) } @@ -94,6 +95,9 @@ func TestNotificationsSettingsDiscordBotAndGitHubActivityRoundTrip(t *testing.T) if payload["discordChannelId"] != "1234567890" { t.Errorf("discordChannelId = %v", payload["discordChannelId"]) } + if payload["discordRfcChannelId"] != "1540404487099777136" { + t.Errorf("discordRfcChannelId = %v", payload["discordRfcChannelId"]) + } gaPayload, ok := payload["githubActivity"].(map[string]any) if !ok || gaPayload["enabled"] != true || gaPayload["org"] != "hivecommons" || gaPayload["filterBots"] != false { t.Fatalf("githubActivity payload = %#v", payload["githubActivity"]) diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index a02b205a45..fc77de7761 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -48015,6 +48015,11 @@ <h4 class="rt-h4">Clanker-requested PRs</h4> <input type="text" value="${esc(n.discordChannelId || '')}" placeholder="1234567890" data-change-action="markDirty" data-arg0="notifications" data-arg1="discordChannelId" data-arg-types="s,s,w"> <div class="config-help">Requires restart.</div> </div> + <div class="config-field"> + <label>RFC channel id ${yamlHint('notifications.discord.rfc_channel_id')} ${settingHelpMark('notifications', 'configuration', 'Discord RFC channel id', `Discord channel that receives RFC lifecycle notices: an RFC issue (rfc label or RFC-prefixed title) opened, closed, or taken off hold so it can be implemented. Posts with the bot token only; the command bot and the channel id above are not required. Empty turns the notices off.`)}</label> + <input type="text" value="${esc(n.discordRfcChannelId || '')}" placeholder="1234567890" data-change-action="markDirty" data-arg0="notifications" data-arg1="discordRfcChannelId" data-arg-types="s,s,w"> + <div class="config-help">Empty disables RFC notices. Env HIVE_DISCORD_RFC_CHANNEL_ID overrides.</div> + </div> <div class="config-field"> <label>Allowed users ${yamlHint('notifications.discord.allowed_users[]')} ${settingHelpMark('notifications', 'configuration', 'Discord allowed users', `Discord user IDs permitted to issue bot commands (!kick, !pause, agent actions). When empty, command handling is disabled (fail closed): the bot still posts status but accepts no commands.`)}</label> <textarea rows="3" placeholder="One Discord user id per line" data-change-action="markNotificationsList" data-arg0="discordAllowedUsers" data-arg-types="s,v">${esc((n.discordAllowedUsers || []).join('\n'))}</textarea>