Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-14616-rfc-discord-notifications.md
Original file line number Diff line number Diff line change
@@ -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 <title> - <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).
3 changes: 3 additions & 0 deletions src/cmd/hive/boot.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
149 changes: 149 additions & 0 deletions src/cmd/hive/rfcnotify_wire.go
Original file line number Diff line number Diff line change
@@ -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
}
153 changes: 153 additions & 0 deletions src/cmd/hive/rfcnotify_wire_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions src/cmd/hive/run_loop_deps.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package main

import (
Expand Down Expand Up @@ -110,6 +110,7 @@
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)
Expand Down
19 changes: 19 additions & 0 deletions src/docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
```
1 change: 1 addition & 0 deletions src/docs/operator-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
15 changes: 15 additions & 0 deletions src/pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package config

import (
Expand Down Expand Up @@ -3932,6 +3932,9 @@
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"`
Expand All @@ -3940,6 +3943,12 @@
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
Expand Down Expand Up @@ -5425,6 +5434,12 @@
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
Expand Down
Loading
Loading