diff --git a/changelog.d/changed-16271-attention-budget-wired.md b/changelog.d/changed-16271-attention-budget-wired.md new file mode 100644 index 0000000000..e7b069c51d --- /dev/null +++ b/changelog.d/changed-16271-attention-budget-wired.md @@ -0,0 +1 @@ +- The per-recipient attention budget (`github.attention.recipient_budget`, still `0` = off) and opt-in digest (`github.attention.digest_recipients`) now load from the `github.attention` block and gate the episode ledger's live first pings and reminders: over-budget asks stay open and listed (status card, attention queue, digest) instead of being posted, and security, required-review, protocol-command and hold asks are never budgeted ([#16271](https://github.com/hivecommons/hive/issues/16271)). diff --git a/src/docs/attention-episodes.md b/src/docs/attention-episodes.md index 0d0de4c306..0651c7250b 100644 --- a/src/docs/attention-episodes.md +++ b/src/docs/attention-episodes.md @@ -16,6 +16,8 @@ github: hivecommons/hive: hosted-hive-id flap_window: 12h reminder_interval: 24h + recipient_budget: 0 # off; see notifications.md + digest_recipients: [] ``` Keys must be fully qualified repositories. Exactly one deployment may own the @@ -29,7 +31,10 @@ Unknown-owner uncertain attempts remain visible and are not automatically retrie Unset/empty `admitter` means this new path does nothing, without opening a ledger or changing today's quiet-mode delivery. The default flap window is 12 hours. -There is no per-recipient budget in this layer (#16271). With +Every first ping and reminder is admitted through the per-recipient attention +budget (`recipient_budget`, off by default, #16271); see +[Per-recipient attention budget](notifications.md#per-recipient-attention-budget-opt-in-off-by-default). +With `github.notifications.attention_pilot` on, `reminder_interval` (default `24h`) bounds reminders to one per unresolved episode per interval; see [Attention section, tracking issue and reminders](notifications.md#attention-section-tracking-issue-and-reminders). diff --git a/src/docs/notifications.md b/src/docs/notifications.md index a1589410cc..cae202ed3a 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -147,15 +147,25 @@ items, and never drops an ask that goes over the cap | `github.attention.digest_recipients` | empty | GitHub logins (case-insensitive, optional `@`) that opted into the digest. | These keys live in the `github.attention` block owned by the condition-episode -ledger ([#16267](https://github.com/hivecommons/hive/issues/16267)); the budget -takes effect once the ledger routes its non-urgent writes through it. +ledger ([#16267](https://github.com/hivecommons/hive/issues/16267)), which +admits every non-urgent write through the budget: the ledger's first ping for +a newly actionable episode (`Store.Report`) and every attention-pilot reminder +(`SweepAttentionQueue`). The budget is seeded from the ledger's delivered +history (`paged_to`/`paged_at` and the last reminder) when the ledger opens, so +the rolling window survives restarts. An over-budget ask is never dropped: its +episode stays open and would-notify, is marked `overflowed` in the ledger, +stays in the repo's attention queue issue, and is posted on a later pass once +the recipient's budget frees up (or cleared when it is acknowledged, snoozed +or resolved). Producers mark exempt asks with `Observation.Class` +(`security`, `required_review`, `protocol_command`, `hold`); an unset class is +an ordinary non-urgent ping. - **Off (shadow mode).** With `recipient_budget: 0` every write is delivered exactly as before. The budget still counts, per recipient, how many writes would have overflowed a candidate cap of 5 (`ShadowBudget`) and reports `delivered`, `exempt`, `overflowed` and `would_overflow` per login in the - `attention budget:` log line, so an operator can choose N from evidence - before enabling it. + `attention budget:` log line (emitted on every attention-queue sweep), so an + operator can choose N from evidence before enabling it. - **Enabled, recipient opted into the digest.** The (N+1)th non-urgent ping or reminder in the window is not posted. It stays an open, overflowed ask: it is listed in the item's status card (`attention-overflow` section), in the @@ -164,9 +174,9 @@ takes effect once the ledger routes its non-urgent writes through it. actionable asks are always posted; only reminders over the cap are deferred (and remain visible in the status card and action queue). - **Digest.** One comment per recipient per repo, identified by - ``, created once through the - existing marker-comment upsert and edited in place afterwards (edits notify - nobody). It serves as the reminder for the asks it lists. No external + ``, posted on the repo's + attention queue issue, created once through the existing marker-comment + upsert and edited in place afterwards (edits notify nobody). It serves as the reminder for the asks it lists. No external service is involved. - **Never budgeted.** Materially new security risk or imminent destructive action, mandatory/required reviews, machine-consumed protocol commands, and diff --git a/src/internal/settingsparity/settingsparity.go b/src/internal/settingsparity/settingsparity.go index e10dd84e96..32d2aa8af1 100644 --- a/src/internal/settingsparity/settingsparity.go +++ b/src/internal/settingsparity/settingsparity.go @@ -51,6 +51,7 @@ func ConfigLeaves(repoRoot string) ([]Leaf, error) { filepath.Join("pkg", "dashboard", "theme"), filepath.Join("pkg", "writeback"), filepath.Join("pkg", "attention"), + filepath.Join("pkg", "attentionbudget"), } { if err := c.collect(fset, repoRoot, rel); err != nil { return nil, err diff --git a/src/internal/settingsparity/settingsparity_test.go b/src/internal/settingsparity/settingsparity_test.go index 17780e153c..8ad7b7d102 100644 --- a/src/internal/settingsparity/settingsparity_test.go +++ b/src/internal/settingsparity/settingsparity_test.go @@ -170,7 +170,7 @@ func TestConfigLeavesRealRepoEnumeratesAttention(t *testing.T) { for _, leaf := range leaves { got[leaf.Path] = true } - for _, want := range []string{"github.attention.admitter.", "github.attention.flap_window"} { + for _, want := range []string{"github.attention.admitter.", "github.attention.flap_window", "github.attention.recipient_budget", "github.attention.digest_recipients[]"} { if !got[want] { t.Errorf("leaf %q must be enumerated", want) } diff --git a/src/pkg/attention/ack.go b/src/pkg/attention/ack.go index 29f9b3204f..efc78a8325 100644 --- a/src/pkg/attention/ack.go +++ b/src/pkg/attention/ack.go @@ -166,6 +166,7 @@ func (s *Store) Apply(repo string, item int, actor string, maintainer bool, cmd e.SnoozedBy = actor } e.WouldNotify = false + s.releaseBudget(e) out = append(out, *e) } if err := s.save(); err != nil { diff --git a/src/pkg/attention/budget_test.go b/src/pkg/attention/budget_test.go new file mode 100644 index 0000000000..a45bd3bb46 --- /dev/null +++ b/src/pkg/attention/budget_test.go @@ -0,0 +1,186 @@ +package attention + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/attentionbudget" +) + +func budgetConfig(n int, digest ...string) Config { + return Config{Admitter: testConfig.Admitter, Config: attentionbudget.Config{RecipientBudget: n, DigestRecipients: digest}} +} + +// asks returns n distinct actionable observations for the same recipient. +func asks(n int, class attentionbudget.Class) []Observation { + var out []Observation + for i := 0; i < n; i++ { + o := observation() + o.Key.Subject = fmt.Sprintf("%s-%d", class, i) + o.Class = class + out = append(out, o) + } + return out +} + +func reportWith(t *testing.T, s *Store, cfg Config, f *forge, obs ...Observation) []Episode { + t.Helper() + es, err := s.Report(context.Background(), cfg, "owner", "org/repo", 1, obs, f) + if err != nil { + t.Fatal(err) + } + return es +} + +func TestBudgetDisabledChangesNothing(t *testing.T) { + s := openStore(t, "") + f := &forge{} + es := report(t, s, f, "owner", asks(attentionbudget.ShadowBudget+2, "")...) + if len(f.posts) != attentionbudget.ShadowBudget+2 { + t.Fatalf("disabled budget held back asks: posts=%d", len(f.posts)) + } + for _, e := range es { + if e.Overflowed || e.State != Notified { + t.Fatalf("disabled budget changed an episode: %+v", e) + } + } + if c := s.Budget().Snapshot()["maintainer"]; c.Delivered != len(f.posts) || c.WouldOverflow != 2 || c.Overflowed != 0 { + t.Fatalf("shadow counts = %+v", c) + } + if line := s.Budget().LogLine(); !strings.HasPrefix(line, "attention budget: off") || !strings.Contains(line, "would_overflow=2") { + t.Fatalf("shadow log line = %q", line) + } +} + +func TestBudgetOverflowIsRecordedNotDropped(t *testing.T) { + s := openStore(t, "") + f := &forge{} + cfg := budgetConfig(2, "maintainer") + obs := asks(3, "") + es := reportWith(t, s, cfg, f, obs...) + if len(f.posts) != 2 { + t.Fatalf("(N+1)th ask posted: posts=%d", len(f.posts)) + } + held := obs[2].Key.Hash() + var found bool + for _, e := range es { + if e.Key.Hash() != held { + continue + } + found = true + if !e.Overflowed || e.State != Actionable || !e.WouldNotify || !e.PagedAt.IsZero() { + t.Fatalf("overflowed ask not kept open: %+v", e) + } + } + if !found { + t.Fatal("overflowed ask dropped from the ledger") + } + open := s.OpenEpisodes("org/repo") + if len(open) != 3 { + t.Fatalf("overflowed ask missing from the action queue: %d open", len(open)) + } + over := s.Budget().Overflowed("org/repo", "maintainer", 1) + if len(over) != 1 || over[0].Key != held { + t.Fatalf("overflowed ask not visible: %+v", over) + } + if !strings.Contains(attentionbudget.RenderSection(over), "#1") || !strings.Contains(attentionbudget.RenderDigest("maintainer", over), "#1") { + t.Fatal("overflowed ask not rendered for the status card and digest") + } + // The next report retries, still held, and never double-posts. + reportWith(t, s, cfg, f, obs...) + if len(f.posts) != 2 { + t.Fatalf("held ask posted while over budget: posts=%d", len(f.posts)) + } + // Resolving the episode clears the overflowed entry. + resolved := obs[2] + resolved.Resolved = true + reportWith(t, s, cfg, f, obs[0], obs[1], resolved) + if over := s.Budget().Overflowed("org/repo", "", 0); len(over) != 0 { + t.Fatalf("resolved ask still listed: %+v", over) + } +} + +func TestBudgetNotOptedInKeepsNewAsks(t *testing.T) { + s := openStore(t, "") + f := &forge{} + reportWith(t, s, budgetConfig(1), f, asks(3, "")...) + if len(f.posts) != 3 { + t.Fatalf("recipient without digest lost a new ask: posts=%d", len(f.posts)) + } +} + +func TestBudgetExemptClassesAlwaysDeliver(t *testing.T) { + for _, class := range []attentionbudget.Class{attentionbudget.Security, attentionbudget.RequiredReview, attentionbudget.ProtocolCommand, attentionbudget.Hold} { + t.Run(string(class), func(t *testing.T) { + s := openStore(t, "") + f := &forge{} + cfg := budgetConfig(1, "maintainer") + obs := append(asks(1, ""), asks(3, class)...) + es := reportWith(t, s, cfg, f, obs...) + if len(f.posts) != 4 { + t.Fatalf("exempt %s ask held by budget: posts=%d", class, len(f.posts)) + } + for _, e := range es { + if e.Overflowed { + t.Fatalf("exempt episode overflowed: %+v", e) + } + } + for _, e := range es { + if e.Class != class { + continue + } + if d, err := s.AdmitReminder(cfg, e, time.Now()); err != nil || d.Outcome != attentionbudget.Deliver { + t.Fatalf("exempt %s reminder held: %+v %v", class, d, err) + } + } + }) + } +} + +func TestBudgetReminderOverflowAndSeedFromLedger(t *testing.T) { + path := filepath.Join(t.TempDir(), "episodes.json") + s := openStore(t, path) + f := &forge{} + cfg := budgetConfig(1, "maintainer") + es := reportWith(t, s, cfg, f, asks(1, "")...) + if len(f.posts) != 1 || len(es) != 1 { + t.Fatalf("posts=%d", len(f.posts)) + } + // A restart reseeds the window from paged_to/paged_at. + s = openStore(t, path) + d, err := s.AdmitReminder(cfg, es[0], time.Now()) + if err != nil || d.Outcome != attentionbudget.Overflow || !d.Digest { + t.Fatalf("reminder over a seeded budget = %+v %v", d, err) + } + if got := s.Snapshot("org/repo", 1); len(got) != 1 || !got[0].Overflowed { + t.Fatalf("held reminder not recorded: %+v", got) + } + if over := s.Budget().Overflowed("org/repo", "maintainer", 0); len(over) != 1 || over[0].Class != attentionbudget.Reminder { + t.Fatalf("held reminder not visible: %+v", over) + } + if _, err := s.Apply("org/repo", 1, "maintainer", false, Command{Kind: CommandAck, Target: es[0].Key.Hash()[:12]}); err != nil { + t.Fatal(err) + } + if over := s.Budget().Overflowed("org/repo", "", 0); len(over) != 0 { + t.Fatalf("acknowledged reminder still listed: %+v", over) + } + // Disabled, the same reminder is delivered. + if d, err := s.AdmitReminder(testConfig, es[0], time.Now()); err != nil || d.Outcome != attentionbudget.Deliver { + t.Fatalf("disabled budget held a reminder: %+v %v", d, err) + } +} + +func TestConfigValidatesBudget(t *testing.T) { + for _, cfg := range []Config{budgetConfig(-1), budgetConfig(attentionbudget.MaxRecipientBudget + 1), budgetConfig(1, "a", "A")} { + if err := cfg.Validate(); err == nil { + t.Fatalf("accepted invalid budget config: %+v", cfg.Config) + } + } + if err := budgetConfig(3, "alice").Validate(); err != nil { + t.Fatal(err) + } +} diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go index db1e1df0be..328a4c4869 100644 --- a/src/pkg/attention/episodes.go +++ b/src/pkg/attention/episodes.go @@ -14,8 +14,10 @@ import ( "path/filepath" "strings" "sync" + "sync/atomic" "time" + "github.com/hivecommons/hive/pkg/attentionbudget" "github.com/hivecommons/hive/pkg/findingidentity" ) @@ -31,6 +33,10 @@ type Config struct { // ReminderInterval is the minimum gap between pings of one unresolved // episode (attention_pilot reminders); zero means DefaultReminderInterval. ReminderInterval time.Duration `yaml:"reminder_interval,omitempty" json:"reminder_interval,omitempty"` + // Config carries github.attention.recipient_budget and + // github.attention.digest_recipients (#16271): the per-recipient budget + // every non-urgent ping and reminder is admitted through. Off by default. + attentionbudget.Config `yaml:",inline"` } func (c Config) Owner(repo string) string { @@ -49,6 +55,9 @@ func (c Config) Validate() error { if c.ReminderInterval < 0 { return errors.New("github.attention.reminder_interval must not be negative") } + if err := c.Config.Validate(); err != nil { + return err + } seen := map[string]bool{} for repo, owner := range c.Admitter { key := canonical(repo) @@ -139,6 +148,11 @@ type Episode struct { RemindedAt time.Time `json:"reminded_at,omitempty"` Reminders int `json:"reminders,omitempty"` RecipientActedAt time.Time `json:"recipient_acted_at,omitempty"` + // Class is the producer's attention class (see Observation.Class). + Class attentionbudget.Class `json:"class,omitempty"` + // Overflowed is set while the per-recipient attention budget holds the + // episode's ping or reminder back; the episode stays open and listed. + Overflowed bool `json:"overflowed,omitempty"` } func (e Episode) Marker() string { @@ -151,6 +165,11 @@ type Observation struct { Resolved bool Evidence string Body string + // Class says whether the first ping is budgeted. Empty means an + // ordinary non-urgent ask (attentionbudget.Ping); producers of security, + // required-review, protocol-command or hold notices set the exempt class + // so the per-recipient budget never holds them back. + Class attentionbudget.Class } // Delivery is supplied by the existing write boundary. History returns the keys @@ -183,11 +202,29 @@ type Store struct { path string state disk now func() time.Time + + budgetOnce sync.Once + budget *attentionbudget.Budget + budgetCfg atomic.Pointer[attentionbudget.Config] } // Open treats missing/corrupt state as recovery, never as permission to replay. // Unknown versions are refused rather than clobbered during rolling upgrades. +// The per-recipient attention budget is seeded from the ledger's delivered +// history so its rolling window survives restarts. func Open(path string) (*Store, error) { + s, err := open(path) + if err != nil { + return nil, err + } + s.mu.Lock() + writes := s.deliveredWrites() + s.mu.Unlock() + s.Budget().Seed(writes) + return s, nil +} + +func open(path string) (*Store, error) { s := &Store{path: path, now: time.Now, state: disk{Version: 1, Items: map[string]bool{}, ItemSeen: map[string]time.Time{}, Episodes: map[string]*Episode{}}} if path == "" { return s, nil @@ -309,6 +346,7 @@ func (s *Store) Report(ctx context.Context, cfg Config, hiveID, repo string, ite if owner == "" { return nil, nil } + s.setBudgetConfig(cfg) if item <= 0 || d == nil { return nil, errors.New("attention: item and delivery are required") } @@ -466,11 +504,15 @@ func (s *Store) record(cfg Config, itemKey string, first bool, history []string, e.Key = o.Key e.LastSeen = now e.Evidence = o.Evidence + if o.Class != "" { + e.Class = o.Class + } if o.Resolved { e.State = Resolved if e.ResolvedAt.IsZero() { e.ResolvedAt = now } + s.releaseBudget(e) continue } if o.Actionable && e.State == Observed { @@ -508,6 +550,19 @@ func (s *Store) deliver(ctx context.Context, d Delivery, o Observation, hiveID, } needFind := reconcileOnly || e.Attempt != "" if !needFind { + // Only a fresh POST is admitted: a retry of an uncertain attempt was + // already counted. An over-budget ask is never dropped; it stays an + // open, would-notify episode, listed as overflowed until delivered. + if s.Budget().Admit(budgetAsk(*e, attentionbudget.Ping, now)).Outcome == attentionbudget.Overflow { + var err error + if !e.Overflowed { + e.Overflowed = true + err = s.save() + } + s.mu.Unlock() + return err + } + e.Overflowed = false var id [16]byte if _, err := rand.Read(id[:]); err != nil { s.mu.Unlock() @@ -609,5 +664,88 @@ func (s *Store) Update(key Key, state State, snooze time.Time) error { return errors.New("attention: unsupported transition") } e.SnoozedUntil = snooze + s.releaseBudget(e) return s.save() } + +// Budget is the store's per-recipient attention budget (#16271). With +// github.attention.recipient_budget 0 (the default) it only counts, in +// shadow mode; every decision is Deliver. +func (s *Store) Budget() *attentionbudget.Budget { + s.budgetOnce.Do(func() { + s.budget = attentionbudget.New(func() attentionbudget.Config { + if c := s.budgetCfg.Load(); c != nil { + return *c + } + return attentionbudget.Config{} + }) + }) + return s.budget +} + +// setBudgetConfig applies the hot-reloadable budget keys of cfg. +func (s *Store) setBudgetConfig(cfg Config) { + c := cfg.Config + s.budgetCfg.Store(&c) +} + +// AdmitReminder asks the budget whether a reminder for e may be posted now. +// An Overflow outcome must not be posted: the episode is marked overflowed +// and stays open (and listed) until its recipient's budget frees or it is +// acknowledged, snoozed or resolved. Exempt classes always Deliver. +func (s *Store) AdmitReminder(cfg Config, e Episode, now time.Time) (attentionbudget.Decision, error) { + s.setBudgetConfig(cfg) + s.mu.Lock() + defer s.mu.Unlock() + d := s.Budget().Admit(budgetAsk(e, attentionbudget.Reminder, now)) + cur := s.state.Episodes[e.Key.Hash()] + if cur == nil || cur.Overflowed == (d.Outcome == attentionbudget.Overflow) { + return d, nil + } + cur.Overflowed = d.Outcome == attentionbudget.Overflow + return d, s.save() +} + +// budgetClass maps an episode's producer class onto the budget: an empty or +// non-urgent class is the given non-urgent kind (Ping or Reminder); every +// exempt class passes through unchanged. +func budgetClass(c, nonUrgent attentionbudget.Class) attentionbudget.Class { + if c == "" || c == attentionbudget.Ping || c == attentionbudget.Reminder { + return nonUrgent + } + return c +} + +func budgetAsk(e Episode, nonUrgent attentionbudget.Class, now time.Time) attentionbudget.Ask { + return attentionbudget.Ask{ + Repo: e.Key.Repo, + Item: e.Key.Item, + Recipient: e.Key.Recipient, + Class: budgetClass(e.Class, nonUrgent), + Summary: e.Key.Action, + At: now, + Key: e.Key.Hash(), + } +} + +// releaseBudget clears e's overflowed ask once it was acknowledged, snoozed +// or resolved. Caller holds s.mu. +func (s *Store) releaseBudget(e *Episode) { + e.Overflowed = false + s.Budget().Resolve(e.Key.Repo, e.Key.Hash()) +} + +// deliveredWrites is the ledger's delivered history (paged_to/paged_at and +// the last reminder) for seeding the budget. Caller holds s.mu. +func (s *Store) deliveredWrites() []attentionbudget.Write { + var out []attentionbudget.Write + for _, e := range s.state.Episodes { + if !e.PagedAt.IsZero() && e.PagedTo != "" { + out = append(out, attentionbudget.Write{Recipient: e.PagedTo, At: e.PagedAt, Class: budgetClass(e.Class, attentionbudget.Ping)}) + } + if !e.RemindedAt.IsZero() && e.Key.Recipient != "" { + out = append(out, attentionbudget.Write{Recipient: e.Key.Recipient, At: e.RemindedAt, Class: budgetClass(e.Class, attentionbudget.Reminder)}) + } + } + return out +} diff --git a/src/pkg/attention/reminder.go b/src/pkg/attention/reminder.go index 5391f72430..81d1ba761a 100644 --- a/src/pkg/attention/reminder.go +++ b/src/pkg/attention/reminder.go @@ -85,6 +85,7 @@ func (s *Store) ResolveItem(repo string, item int) ([]Episode, error) { e.State = Resolved e.ResolvedAt = now e.WouldNotify = false + s.releaseBudget(e) out = append(out, *e) } if len(out) == 0 { diff --git a/src/pkg/config/github_attention_budget_test.go b/src/pkg/config/github_attention_budget_test.go new file mode 100644 index 0000000000..a77f6f0a62 --- /dev/null +++ b/src/pkg/config/github_attention_budget_test.go @@ -0,0 +1,39 @@ +package config + +import ( + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +// github.attention.recipient_budget / digest_recipients load from the +// github.attention block and are validated with it (#16271). +func TestGitHubAttentionBudgetKeysLoad(t *testing.T) { + var c struct { + GitHub GitHubConfig `yaml:"github"` + } + if err := yaml.Unmarshal([]byte("github:\n attention:\n recipient_budget: 3\n digest_recipients: [\"@Alice\", bob]\n"), &c); err != nil { + t.Fatal(err) + } + a := c.GitHub.Attention + if a.RecipientBudget != 3 || len(a.DigestRecipients) != 2 || !a.DigestOptIn("alice") || a.DigestOptIn("carol") { + t.Fatalf("budget keys not loaded: %+v", a) + } + if err := a.Validate(); err != nil { + t.Fatal(err) + } + var off struct { + GitHub GitHubConfig `yaml:"github"` + } + if err := yaml.Unmarshal([]byte("github:\n attention:\n flap_window: 1h\n"), &off); err != nil { + t.Fatal(err) + } + if off.GitHub.Attention.Config.Enabled() { + t.Fatal("recipient_budget must default to off") + } + off.GitHub.Attention.RecipientBudget = -1 + if err := off.GitHub.Attention.Validate(); err == nil || !strings.Contains(err.Error(), "recipient_budget") { + t.Fatalf("negative recipient_budget accepted: %v", err) + } +} diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 882af4d1ec..c88a5414ed 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -197,7 +197,9 @@ evidence.complexity.enabled # TODO #11854 evidence.complexity.static_analysis # TODO #11854 github.additional_bot_logins[] # TODO #11854 github.attention.admitter. # single-admitter ownership and flap window are YAML-only rollout controls; see src/docs/attention-episodes.md +github.attention.digest_recipients[] # opt-in attention digest recipients; yaml-only, see docs/notifications.md (#16271) github.attention.flap_window # single-admitter ownership and flap window are YAML-only rollout controls; see src/docs/attention-episodes.md +github.attention.recipient_budget # per-recipient attention budget, off by default; yaml-only, see docs/notifications.md (#16271) github.attention.reminder_interval # attention-pilot reminder interval; yaml-only, see src/docs/attention-episodes.md (#16361) github.notifications.attention_pilot # opt-in attention-pilot issue status card; yaml-only, see docs/notifications.md (#16358) github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md diff --git a/src/pkg/github/attention.go b/src/pkg/github/attention.go index 075b64bf40..e9615e6ad2 100644 --- a/src/pkg/github/attention.go +++ b/src/pkg/github/attention.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/hivecommons/hive/pkg/attention" + "github.com/hivecommons/hive/pkg/attentionbudget" "github.com/hivecommons/hive/pkg/writeback" ) @@ -53,6 +54,10 @@ func (c *Client) ReportAttention(ctx context.Context, repo string, item writebac episodes = store.Snapshot(repo, item.Number) } _, statusErr := c.UpsertPRStatusSection(ctx, repo, item.Number, "attention", attentionStatus(episodes)) + if cfg.Config.Enabled() && statusErr == nil { + // Asks the per-recipient budget held back stay visible on the item. + _, statusErr = c.UpsertPRStatusSection(ctx, repo, item.Number, attentionbudget.SectionKey, attentionbudget.RenderSection(store.Budget().Overflowed(repo, "", item.Number))) + } if reportErr != nil { return episodes, reportErr } diff --git a/src/pkg/github/attention_queue.go b/src/pkg/github/attention_queue.go index 16cc6e0294..b5a5c2b377 100644 --- a/src/pkg/github/attention_queue.go +++ b/src/pkg/github/attention_queue.go @@ -11,6 +11,7 @@ import ( "github.com/hivecommons/hive/crux/logscrub" "github.com/hivecommons/hive/pkg/advisory" "github.com/hivecommons/hive/pkg/attention" + "github.com/hivecommons/hive/pkg/attentionbudget" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/issueshape" "github.com/hivecommons/hive/pkg/writeback" @@ -32,7 +33,12 @@ import ( // Prow already owns is never duplicated; // - keeps one per-repo tracking issue listing every open episode. The // issue is created once — its only notifying write — and afterwards -// edited in place, which notifies nobody. +// edited in place, which notifies nobody; +// - admits every reminder through the per-recipient attention budget +// (github.attention.recipient_budget, #16271): an over-budget reminder +// is not posted but stays open, listed on the item and in the queue, and +// for github.attention.digest_recipients in their single edited-in-place +// digest comment on the tracking issue. // attentionNow is the reminder clock; tests replace it. var attentionNow = time.Now @@ -55,6 +61,9 @@ type AttentionQueueResult struct { // Suppressed counts reminders the write-back gate refused; they are // retried on a later pass. Suppressed int + // Overflowed counts reminders the per-recipient attention budget held + // back; they stay open and are retried on a later pass. + Overflowed int // QueueIssue is the tracking issue number (0 when none exists). QueueIssue int // QueueCreated and QueueEdited report the tracking issue write. @@ -117,6 +126,8 @@ func (c *Client) SweepAttentionQueue(ctx context.Context, repo string) (Attentio switch { case errors.Is(err, writeback.ErrSuppressed): res.Suppressed++ + case errors.Is(err, errAttentionOverflow): + res.Overflowed++ case err != nil: errs = append(errs, err) case sent: @@ -129,15 +140,49 @@ func (c *Client) SweepAttentionQueue(ctx context.Context, repo string) (Attentio errs = append(errs, err) } } + if cfg.Config.Enabled() { + if _, err := c.UpsertPRStatusSection(ctx, repo, n, attentionbudget.SectionKey, attentionbudget.RenderSection(store.Budget().Overflowed(repo, "", n))); err != nil { + errs = append(errs, err) + } + } } num, created, edited, err := c.syncAttentionQueueIssue(ctx, repo, store.OpenEpisodes(repo)) res.QueueIssue, res.QueueCreated, res.QueueEdited = num, created, edited if err != nil { errs = append(errs, err) } + if err := c.syncAttentionDigests(ctx, cfg, store, repo, num); err != nil { + errs = append(errs, err) + } + if c.logger != nil { + c.logger.Info(store.Budget().LogLine(), "repo", repo) + } return res, errors.Join(errs...) } +// errAttentionOverflow reports a reminder the per-recipient attention budget +// held back. It is not a failure: the episode stays open and listed. +var errAttentionOverflow = errors.New("attention reminder held by recipient budget") + +// syncAttentionDigests keeps one digest comment per opted-in recipient on the +// repo's tracking issue through the existing marker-comment upsert: created +// once when something overflowed, edited in place thereafter, never reposted. +func (c *Client) syncAttentionDigests(ctx context.Context, cfg attention.Config, store *attention.Store, repo string, queueIssue int) error { + if !cfg.Config.Enabled() || len(cfg.DigestRecipients) == 0 || queueIssue <= 0 { + return nil + } + if d := c.WritebackAllowed(repo, writeback.Item{Number: queueIssue, HiveAuthored: true}, writeback.KindIssueFile, ""); !d.Allowed { + return fmt.Errorf("attention digest %s: %w: %s", repo, writeback.ErrSuppressed, d.Reason) + } + var errs []error + for _, login := range cfg.DigestRecipients { + if _, err := attentionbudget.UpsertDigest(ctx, c, repo, queueIssue, login, store.Budget().Overflowed(repo, login, 0)); err != nil { // writeback:gated — WritebackAllowed consulted above + errs = append(errs, fmt.Errorf("attention digest %s#%d: %w", repo, queueIssue, err)) + } + } + return errors.Join(errs...) +} + // remindAttention sends one reminder for e unless its recipient acted on the // item since the last ping, in which case the action is recorded and the // interval restarts from it. The comment consults the write-back gate; a @@ -165,6 +210,15 @@ func (c *Client) remindAttention(ctx context.Context, store *attention.Store, re if d := c.WritebackAllowed(repo, item, writeback.KindNeedsDecisionComment, body); !d.Allowed { return false, fmt.Errorf("attention reminder %s#%d: %w: %s", repo, n, writeback.ErrSuppressed, d.Reason) } + if c.attentionConfig != nil { + d, err := store.AdmitReminder(c.attentionConfig(), e, now) + if err != nil { + return false, err + } + if d.Outcome == attentionbudget.Overflow { + return false, fmt.Errorf("attention reminder %s#%d: %w: %s", repo, n, errAttentionOverflow, d.Reason) + } + } if err := c.CreateIssueComment(WithNotificationSubject(ctx, "attention-reminder:"+e.Key.Hash()), repo, n, body); err != nil { // writeback:gated — WritebackAllowed consulted above return false, err }