diff --git a/changelog.d/added-16271-attention-recipient-budget.md b/changelog.d/added-16271-attention-recipient-budget.md new file mode 100644 index 0000000000..e9a4d1a06f --- /dev/null +++ b/changelog.d/added-16271-attention-recipient-budget.md @@ -0,0 +1 @@ +- Per-recipient attention budget (`github.attention.recipient_budget`, `0` = off) with shadow would-overflow counting and an opt-in, edited-in-place digest (`github.attention.digest_recipients`); security, required-review, protocol-command and hold notices are never budgeted ([#16271](https://github.com/hivecommons/hive/issues/16271)). diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 75ae147cdb..63325e62c3 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -131,6 +131,48 @@ Current v1 event coverage: | PR | merged | Includes the target branch (`merged into v6`) and merge/head SHA dedupe. | | PR | closed unmerged | Open → closed without merge. | +### Per-recipient attention budget (opt-in, off by default) + +Per-condition reminder limits do not add up to an attention budget: ten +conditions on ten items each reminding daily is still ten pings a day for one +person. `pkg/attentionbudget` caps **non-urgent** attention writes (first +pings and reminders) per responsible recipient per rolling 24 hours, across +items, and never drops an ask that goes over the cap +([#16271](https://github.com/hivecommons/hive/issues/16271), part of +[#16075](https://github.com/hivecommons/hive/issues/16075)). + +| Field | Default | Notes | +|---|---|---| +| `github.attention.recipient_budget` | `0` (off) | Max non-urgent attention writes per recipient per rolling 24h. `0` keeps today's behaviour; maximum `1000`. | +| `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. + +- **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. +- **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 + repo's action queue, and in the recipient's digest. +- **Enabled, recipient not opted in.** Per-episode delivery is kept: newly + 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 + service is involved. +- **Never budgeted.** Materially new security risk or imminent destructive + action, mandatory/required reviews, machine-consumed protocol commands, and + every security/merge hold notice always deliver immediately and do not + consume budget. Unclassified writes are treated as exempt. + ## What triggers notifications The Hive Go process sends notifications for these events: diff --git a/src/pkg/attentionbudget/budget.go b/src/pkg/attentionbudget/budget.go new file mode 100644 index 0000000000..46f50d7613 --- /dev/null +++ b/src/pkg/attentionbudget/budget.go @@ -0,0 +1,395 @@ +// Package attentionbudget caps non-urgent attention writes (pings and +// reminders) per responsible recipient per rolling day, across items, with an +// opt-in digest for the overflow (#16271, part of the #16075 attention RFC). +// +// It is store-agnostic: the condition-episode ledger seeds it with the writes +// it has already delivered (Seed) and asks it before every non-urgent write +// (Admit). It never discards an ask: an over-budget ask is kept as an open +// overflowed entry that the item's status card, the per-repo action queue and +// the recipient's digest all render until the episode is resolved. +// +// The budget ships disabled. With recipient_budget 0 every decision is +// Deliver, exactly as before, and the would-overflow counter (shadow mode) +// records what a ShadowBudget cap would have done so operators can pick N +// from evidence before enabling it. +package attentionbudget + +import ( + "errors" + "fmt" + "sort" + "strings" + "sync" + "time" +) + +// Window is the rolling period the per-recipient budget is counted over. +const Window = 24 * time.Hour + +// ShadowBudget is the candidate cap shadow mode evaluates while the budget is +// disabled. It is a measurement point, not policy: the enforced cap is always +// the operator-set recipient_budget. +const ShadowBudget = 5 + +// MaxRecipientBudget bounds the configured cap so a typo cannot turn into an +// effectively unlimited (and thus silently disabled) budget. +const MaxRecipientBudget = 1000 + +// Class says whether an attention write is budgeted and why. +type Class string + +const ( + // Ping is the first non-urgent ask on a newly actionable episode. + Ping Class = "ping" + + // Reminder is a repeat non-urgent ask on an episode still open. + Reminder Class = "reminder" + + // Security is a materially new security risk or imminent destructive + // action. Exempt. + Security Class = "security" + + // RequiredReview is a mandatory/required review request. Exempt. + RequiredReview Class = "required_review" + + // ProtocolCommand is a machine-consumed protocol command. Exempt. + ProtocolCommand Class = "protocol_command" + + // Hold is any security or merge hold notice. Exempt. + Hold Class = "hold" +) + +// Exempt reports whether c always delivers immediately regardless of +// budget. Unknown classes are treated as exempt: the budget only ever +// applies to writes positively classified as non-urgent. +func (c Class) Exempt() bool { + return c != Ping && c != Reminder +} + +// Config is the budget's slice of github.attention. The zero value is the +// shipped default: budget off, nobody opted into the digest. +type Config struct { + // RecipientBudget is the maximum number of non-urgent attention writes + // per responsible recipient per rolling 24h, across items. 0 = off. + RecipientBudget int `yaml:"recipient_budget,omitempty" json:"recipient_budget,omitempty"` + + // DigestRecipients are the GitHub logins that opted into the daily + // digest. Their over-budget pings and reminders go to one edited-in-place + // digest comment per repo. Everyone else keeps per-episode delivery and + // the budget only defers their reminders. + DigestRecipients []string `yaml:"digest_recipients,omitempty" json:"digest_recipients,omitempty"` +} + +// Enabled reports whether the budget is enforced. +func (c Config) Enabled() bool { return c.RecipientBudget > 0 } + +// DigestOptIn reports whether login opted into the digest. +func (c Config) DigestOptIn(login string) bool { + login = normLogin(login) + if login == "" { + return false + } + for _, r := range c.DigestRecipients { + if normLogin(r) == login { + return true + } + } + return false +} + +// Validate rejects negative or absurd caps and malformed digest logins. +func (c Config) Validate() error { + if c.RecipientBudget < 0 { + return errors.New("github.attention.recipient_budget must not be negative (0 = off)") + } + if c.RecipientBudget > MaxRecipientBudget { + return fmt.Errorf("github.attention.recipient_budget must be at most %d", MaxRecipientBudget) + } + seen := map[string]bool{} + for _, r := range c.DigestRecipients { + login := normLogin(r) + if login == "" || strings.ContainsAny(login, " \t\r\n/") { + return fmt.Errorf("github.attention.digest_recipients: %q is not a GitHub login", r) + } + if seen[login] { + return fmt.Errorf("github.attention.digest_recipients: duplicate login %q", r) + } + seen[login] = true + } + return nil +} + +func normLogin(s string) string { + return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s), "@")) +} + +func normRepo(s string) string { return strings.ToLower(strings.TrimSpace(s)) } + +// Write is one attention write already delivered to Recipient at At. +type Write struct { + Recipient string + At time.Time + Class Class +} + +// Ask is a prospective attention write for one episode. +type Ask struct { + Repo string + Item int + Recipient string + Class Class + Summary string + At time.Time + + // Key identifies the episode (e.g. the ledger's condition key hash); it + // dedupes overflowed entries and is what Resolve clears. + Key string + + // URL links the digest/queue line to the item; optional. + URL string +} + +// Outcome is what the caller must do with an Ask. +type Outcome string + +const ( + // Deliver: post the ping/reminder as before. + Deliver Outcome = "deliver" + + // Overflow: do not post; the ask is recorded as open+overflowed and is + // rendered by the status card, the action queue and (when opted in) + // the recipient's digest. + Overflow Outcome = "overflow" +) + +// Decision explains an Admit result. +type Decision struct { + Outcome Outcome + Reason string + + // Count is the recipient's budgeted writes in the window before this ask. + Count int + + // WouldOverflow is the shadow verdict against ShadowBudget, computed + // only while the budget is disabled. + WouldOverflow bool + + // Digest is set when an overflowed ask is routed to the digest. + Digest bool +} + +// Counts is the per-recipient tally exposed for logs/health. +type Counts struct { + Delivered int `json:"delivered"` + Exempt int `json:"exempt"` + Overflowed int `json:"overflowed"` + WouldOverflow int `json:"would_overflow"` +} + +// Budget is safe for concurrent use. +type Budget struct { + mu sync.Mutex + cfg func() Config + now func() time.Time + writes []Write + open map[string]Ask + tally map[string]*Counts +} + +// New returns a Budget reading its config through cfg on every decision, so +// a hot-reloaded hive.yaml applies without a restart. A nil cfg is "off". +func New(cfg func() Config) *Budget { + if cfg == nil { + cfg = func() Config { return Config{} } + } + return &Budget{cfg: cfg, now: time.Now, open: map[string]Ask{}, tally: map[string]*Counts{}} +} + +// Seed loads writes the episode ledger already delivered (its paged_to / +// paged_at history), so the window survives restarts. Exempt writes are +// ignored: they never consume budget. +func (b *Budget) Seed(writes []Write) { + b.mu.Lock() + defer b.mu.Unlock() + for _, w := range writes { + if w.Class.Exempt() || normLogin(w.Recipient) == "" { + continue + } + w.Recipient = normLogin(w.Recipient) + b.writes = append(b.writes, w) + } + b.pruneLocked(b.now()) +} + +func (b *Budget) pruneLocked(now time.Time) { + cutoff := now.Add(-Window) + kept := b.writes[:0] + for _, w := range b.writes { + if w.At.After(cutoff) { + kept = append(kept, w) + } + } + b.writes = kept +} + +func (b *Budget) countLocked(recipient string) int { + n := 0 + for _, w := range b.writes { + if w.Recipient == recipient { + n++ + } + } + return n +} + +func (b *Budget) countsLocked(recipient string) *Counts { + c := b.tally[recipient] + if c == nil { + c = &Counts{} + b.tally[recipient] = c + } + return c +} + +func openKey(repo, recipient, key string) string { + return normRepo(repo) + "\x00" + recipient + "\x00" + key +} + +// Admit decides one ask and records its effect: a delivered budgeted write +// consumes budget; an overflowed ask is kept open until Resolve. +func (b *Budget) Admit(ask Ask) Decision { + b.mu.Lock() + defer b.mu.Unlock() + if ask.At.IsZero() { + ask.At = b.now() + } + recipient := normLogin(ask.Recipient) + counts := b.countsLocked(recipient) + if ask.Class.Exempt() || recipient == "" { + counts.Exempt++ + return Decision{Outcome: Deliver, Reason: "exempt from attention budget"} + } + b.pruneLocked(ask.At) + cfg := b.cfg() + count := b.countLocked(recipient) + d := Decision{Outcome: Deliver, Count: count} + if !cfg.Enabled() { + if count >= ShadowBudget { + d.WouldOverflow = true + counts.WouldOverflow++ + } + d.Reason = "attention budget off" + b.deliverLocked(ask, recipient, counts) + return d + } + if count < cfg.RecipientBudget { + d.Reason = "within attention budget" + b.deliverLocked(ask, recipient, counts) + return d + } + optIn := cfg.DigestOptIn(recipient) + if ask.Class == Ping && !optIn { + // A recipient without a digest keeps per-episode delivery for + // newly actionable asks; only their reminders are budgeted. + d.Reason = "over attention budget; new ask delivered (recipient not opted into digest)" + b.deliverLocked(ask, recipient, counts) + return d + } + d.Outcome = Overflow + d.Digest = optIn + if optIn { + d.Reason = "over attention budget; routed to digest" + } else { + d.Reason = "over attention budget; reminder deferred to action queue" + } + counts.Overflowed++ + ask.Recipient = recipient + b.open[openKey(ask.Repo, recipient, ask.Key)] = ask + return d +} + +func (b *Budget) deliverLocked(ask Ask, recipient string, counts *Counts) { + counts.Delivered++ + b.writes = append(b.writes, Write{Recipient: recipient, At: ask.At, Class: ask.Class}) + delete(b.open, openKey(ask.Repo, recipient, ask.Key)) +} + +// Resolve clears every overflowed entry for the episode key in repo (the +// episode was resolved, acknowledged, snoozed or acted on). +func (b *Budget) Resolve(repo, key string) { + b.mu.Lock() + defer b.mu.Unlock() + repo = normRepo(repo) + for k, a := range b.open { + if normRepo(a.Repo) == repo && a.Key == key { + delete(b.open, k) + } + } +} + +// Overflowed lists the open overflowed asks in repo, optionally filtered by +// recipient ("" = all) and item (0 = all), oldest first. +func (b *Budget) Overflowed(repo, recipient string, item int) []Ask { + b.mu.Lock() + defer b.mu.Unlock() + repo = normRepo(repo) + recipient = normLogin(recipient) + var out []Ask + for _, a := range b.open { + if normRepo(a.Repo) != repo || (recipient != "" && a.Recipient != recipient) || (item != 0 && a.Item != item) { + continue + } + out = append(out, a) + } + sortAsks(out) + return out +} + +// Snapshot returns a copy of the per-recipient tallies. +func (b *Budget) Snapshot() map[string]Counts { + b.mu.Lock() + defer b.mu.Unlock() + out := make(map[string]Counts, len(b.tally)) + for k, v := range b.tally { + out[k] = *v + } + return out +} + +// LogLine summarises the tallies for the periodic notification log, e.g. +// "attention budget: off (shadow N=5); alice delivered=7 exempt=1 overflowed=0 would_overflow=2". +func (b *Budget) LogLine() string { + snap := b.Snapshot() + mode := fmt.Sprintf("off (shadow N=%d)", ShadowBudget) + if n := b.cfg().RecipientBudget; n > 0 { + mode = fmt.Sprintf("N=%d", n) + } + logins := make([]string, 0, len(snap)) + for k := range snap { + logins = append(logins, k) + } + sort.Strings(logins) + var sb strings.Builder + sb.WriteString("attention budget: " + mode) + for _, l := range logins { + c := snap[l] + name := l + if name == "" { + name = "(none)" + } + fmt.Fprintf(&sb, "; %s delivered=%d exempt=%d overflowed=%d would_overflow=%d", name, c.Delivered, c.Exempt, c.Overflowed, c.WouldOverflow) + } + return sb.String() +} + +func sortAsks(a []Ask) { + sort.Slice(a, func(i, j int) bool { + if !a[i].At.Equal(a[j].At) { + return a[i].At.Before(a[j].At) + } + if a[i].Item != a[j].Item { + return a[i].Item < a[j].Item + } + return a[i].Key < a[j].Key + }) +} diff --git a/src/pkg/attentionbudget/budget_test.go b/src/pkg/attentionbudget/budget_test.go new file mode 100644 index 0000000000..eb2375448e --- /dev/null +++ b/src/pkg/attentionbudget/budget_test.go @@ -0,0 +1,216 @@ +package attentionbudget + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/gfi" +) + +var t0 = time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC) + +func fixed(c Config) func() Config { return func() Config { return c } } + +func ask(recipient string, class Class, item int, at time.Time) Ask { + return Ask{Repo: "hivecommons/hive", Item: item, Recipient: recipient, Class: class, Key: "k" + string(rune('a'+item)), Summary: "please look", At: at} +} + +func TestDisabledByDefaultIsNoOp(t *testing.T) { + var zero Config + if zero.Enabled() || zero.Validate() != nil { + t.Fatalf("zero config must be valid and disabled") + } + b := New(nil) + for i := 0; i < 20; i++ { + d := b.Admit(ask("alice", Reminder, i%10, t0.Add(time.Duration(i)*time.Minute))) + if d.Outcome != Deliver { + t.Fatalf("write %d: outcome %q with budget off; want deliver", i, d.Outcome) + } + } + if got := b.Overflowed("hivecommons/hive", "", 0); len(got) != 0 { + t.Fatalf("budget off must not record overflow, got %d", len(got)) + } +} + +func TestShadowCountsWouldOverflowWithoutChangingWrites(t *testing.T) { + b := New(fixed(Config{})) + n := ShadowBudget + 3 + for i := 0; i < n; i++ { + d := b.Admit(ask("Alice", Ping, i, t0.Add(time.Duration(i)*time.Minute))) + if d.Outcome != Deliver { + t.Fatalf("shadow mode changed write %d to %q", i, d.Outcome) + } + if want := i >= ShadowBudget; d.WouldOverflow != want { + t.Fatalf("write %d: WouldOverflow=%v want %v", i, d.WouldOverflow, want) + } + } + c := b.Snapshot()["alice"] + if c.WouldOverflow != 3 || c.Delivered != n || c.Overflowed != 0 { + t.Fatalf("shadow tally = %+v", c) + } + if line := b.LogLine(); !strings.Contains(line, "alice") || !strings.Contains(line, "would_overflow=3") || !strings.Contains(line, "off (shadow") { + t.Fatalf("log line %q missing shadow counter", line) + } +} + +func TestEnabledOverflowIsRecordedNotDropped(t *testing.T) { + cases := []struct { + name string + cfg Config + class Class + want Outcome + wantDigest bool + }{ + {"opted-in ping goes to digest", Config{RecipientBudget: 2, DigestRecipients: []string{"@Alice"}}, Ping, Overflow, true}, + {"opted-in reminder goes to digest", Config{RecipientBudget: 2, DigestRecipients: []string{"alice"}}, Reminder, Overflow, true}, + {"not opted-in reminder deferred to queue", Config{RecipientBudget: 2}, Reminder, Overflow, false}, + {"not opted-in new ask keeps per-episode delivery", Config{RecipientBudget: 2}, Ping, Deliver, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + b := New(fixed(tc.cfg)) + for i := 0; i < tc.cfg.RecipientBudget; i++ { + if d := b.Admit(ask("alice", tc.class, i, t0.Add(time.Duration(i)*time.Minute))); d.Outcome != Deliver { + t.Fatalf("write %d within budget: %q", i, d.Outcome) + } + } + extra := ask("alice", tc.class, 7, t0.Add(time.Hour)) + d := b.Admit(extra) + if d.Outcome != tc.want || d.Digest != tc.wantDigest { + t.Fatalf("N+1th ask: %+v; want outcome %q digest %v", d, tc.want, tc.wantDigest) + } + open := b.Overflowed("HiveCommons/Hive", "ALICE", 7) + if tc.want == Overflow { + if len(open) != 1 || open[0].Key != extra.Key { + t.Fatalf("overflowed ask not recorded: %+v", open) + } + if s := RenderSection(open); !strings.Contains(s, "#7") || !strings.Contains(s, "alice") { + t.Fatalf("status/queue section does not show the ask: %q", s) + } + b.Resolve("hivecommons/hive", extra.Key) + if got := b.Overflowed("hivecommons/hive", "", 0); len(got) != 0 { + t.Fatalf("resolve left %d entries", len(got)) + } + } else if len(open) != 0 { + t.Fatalf("delivered ask must not stay overflowed") + } + }) + } +} + +func TestWindowIsRollingAndSeeded(t *testing.T) { + b := New(fixed(Config{RecipientBudget: 1, DigestRecipients: []string{"alice"}})) + b.now = func() time.Time { return t0 } + b.Seed([]Write{ + {Recipient: "Alice", At: t0.Add(-time.Hour), Class: Reminder}, + {Recipient: "alice", At: t0.Add(-2 * time.Hour), Class: Security}, + }) + if d := b.Admit(ask("alice", Reminder, 1, t0)); d.Outcome != Overflow || d.Count != 1 { + t.Fatalf("seeded write should consume the budget (exempt ones not): %+v", d) + } + if d := b.Admit(ask("alice", Reminder, 2, t0.Add(Window))); d.Outcome != Deliver { + t.Fatalf("budget must free up after the rolling window: %+v", d) + } +} + +func TestExemptClassesBypassBudget(t *testing.T) { + for _, class := range []Class{Security, RequiredReview, ProtocolCommand, Hold} { + t.Run(string(class), func(t *testing.T) { + b := New(fixed(Config{RecipientBudget: 1, DigestRecipients: []string{"alice"}})) + b.Admit(ask("alice", Ping, 1, t0)) + for i := 0; i < 5; i++ { + d := b.Admit(ask("alice", class, 2+i, t0.Add(time.Duration(i+1)*time.Minute))) + if d.Outcome != Deliver { + t.Fatalf("exempt %s write %d was %q", class, i, d.Outcome) + } + } + if d := b.Admit(ask("alice", Reminder, 9, t0.Add(time.Hour))); d.Count != 1 { + t.Fatalf("exempt writes consumed budget: count=%d", d.Count) + } + if c := b.Snapshot()["alice"]; c.Exempt != 5 { + t.Fatalf("exempt tally = %+v", c) + } + }) + } +} + +func TestConfigValidate(t *testing.T) { + cases := []struct { + cfg Config + ok bool + }{ + {Config{}, true}, + {Config{RecipientBudget: 5, DigestRecipients: []string{"alice", "@bob"}}, true}, + {Config{RecipientBudget: -1}, false}, + {Config{RecipientBudget: MaxRecipientBudget + 1}, false}, + {Config{DigestRecipients: []string{" "}}, false}, + {Config{DigestRecipients: []string{"org/team"}}, false}, + {Config{DigestRecipients: []string{"alice", "@Alice"}}, false}, + } + for _, tc := range cases { + if err := tc.cfg.Validate(); (err == nil) != tc.ok { + t.Errorf("Validate(%+v) = %v; want ok=%v", tc.cfg, err, tc.ok) + } + } +} + +type fakeForge struct { + comments []string + creates int + edits int +} + +func (f *fakeForge) UpsertIssueMarkerComment(_ context.Context, _ string, _ int, marker, body string, create bool) (gfi.MarkerComment, error) { + for i, c := range f.comments { + if !strings.Contains(c, marker) { + continue + } + res := gfi.MarkerComment{Found: true, Previous: c} + if body != "" && body != c { + f.comments[i] = body + f.edits++ + } + return res, nil + } + if !create || body == "" { + return gfi.MarkerComment{}, nil + } + f.comments = append(f.comments, body) + f.creates++ + return gfi.MarkerComment{Created: true}, nil +} + +func TestDigestCreatedOnceThenEditedInPlace(t *testing.T) { + ctx := context.Background() + f := &fakeForge{} + if _, err := UpsertDigest(ctx, f, "hivecommons/hive", 42, "alice", nil); err != nil || f.creates != 0 { + t.Fatalf("empty digest must not create a comment (creates=%d err=%v)", f.creates, err) + } + day1 := []Ask{ask("alice", Reminder, 1, t0)} + day2 := append(day1, ask("alice", Ping, 2, t0.Add(24*time.Hour))) + for _, asks := range [][]Ask{day1, day2, day2, nil} { + if _, err := UpsertDigest(ctx, f, "hivecommons/hive", 42, "@Alice", asks); err != nil { + t.Fatal(err) + } + } + if f.creates != 1 || len(f.comments) != 1 { + t.Fatalf("digest created %d times (%d comments); want exactly once", f.creates, len(f.comments)) + } + if f.edits != 2 { + t.Fatalf("digest edits = %d; want 2 (unchanged body is not rewritten)", f.edits) + } + if !strings.Contains(f.comments[0], "Nothing outstanding") { + t.Fatalf("cleared digest body = %q", f.comments[0]) + } + if _, err := UpsertDigest(ctx, f, "hivecommons/hive", 42, "bob", day1); err != nil || len(f.comments) != 2 { + t.Fatalf("each recipient gets its own digest comment (comments=%d err=%v)", len(f.comments), err) + } +} + +func TestDigestMarkerDoesNotMatchPrefixLogin(t *testing.T) { + if strings.Contains(DigestMarker("alice"), DigestMarker("al")) { + t.Fatalf("marker for a prefix login must not match another recipient's digest") + } +} diff --git a/src/pkg/attentionbudget/digest.go b/src/pkg/attentionbudget/digest.go new file mode 100644 index 0000000000..cd278c2d3b --- /dev/null +++ b/src/pkg/attentionbudget/digest.go @@ -0,0 +1,89 @@ +package attentionbudget + +import ( + "context" + "fmt" + "strings" + + "github.com/hivecommons/hive/pkg/gfi" +) + +// SectionKey is the hive:status section the item's Attention card uses for +// asks the budget held back, so they stay visible on the item itself. +const SectionKey = "attention-overflow" + +// MarkerUpserter is the existing marker-comment upsert boundary +// (*github.Client.UpsertIssueMarkerComment, gfi.Forge): find the first +// comment containing marker, edit it when body differs, create only when +// create is set. The digest needs nothing else. +type MarkerUpserter interface { + UpsertIssueMarkerComment(ctx context.Context, repo string, number int, marker, body string, create bool) (gfi.MarkerComment, error) +} + +// DigestMarker identifies recipient's single digest comment in a repo. +func DigestMarker(recipient string) string { + return fmt.Sprintf("", normLogin(recipient)) +} + +// RenderDigest renders recipient's digest body for asks (already filtered to +// that recipient and repo). Edits of it notify nobody; it is the reminder for +// every non-urgent ask it lists. +func RenderDigest(recipient string, asks []Ask) string { + recipient = normLogin(recipient) + var sb strings.Builder + sb.WriteString(DigestMarker(recipient) + "\n") + fmt.Fprintf(&sb, "### Attention digest for @%s\n\n", recipient) + if len(asks) == 0 { + sb.WriteString("Nothing outstanding. This comment is edited in place; it is not reposted.\n") + return sb.String() + } + sb.WriteString("Non-urgent asks held back by the per-recipient attention budget. Security, required-review and hold notices are never held here.\n\n") + sb.WriteString(renderLines(asks, false)) + sb.WriteString("\nThis comment is edited in place; it is not reposted.\n") + return sb.String() +} + +// UpsertDigest writes recipient's digest on issue number of repo (typically +// the repo's action-queue issue): created once, edited in place thereafter. +// With no asks it never creates a comment, only clears an existing one. +func UpsertDigest(ctx context.Context, f MarkerUpserter, repo string, number int, recipient string, asks []Ask) (gfi.MarkerComment, error) { + if f == nil { + return gfi.MarkerComment{}, fmt.Errorf("attentionbudget: no forge for digest") + } + if normLogin(recipient) == "" || number <= 0 { + return gfi.MarkerComment{}, fmt.Errorf("attentionbudget: digest needs a recipient and an issue number") + } + return f.UpsertIssueMarkerComment(ctx, repo, number, DigestMarker(recipient), RenderDigest(recipient, asks), len(asks) > 0) +} + +// RenderSection renders the item's status-card / action-queue lines for +// overflowed asks; "" (which removes the section) when there are none. +func RenderSection(asks []Ask) string { + if len(asks) == 0 { + return "" + } + return "**Attention (held by recipient budget)**\n\n" + renderLines(asks, true) +} + +func renderLines(asks []Ask, withRecipient bool) string { + sorted := append([]Ask(nil), asks...) + sortAsks(sorted) + var sb strings.Builder + for _, a := range sorted { + ref := fmt.Sprintf("#%d", a.Item) + if a.URL != "" { + ref = fmt.Sprintf("[#%d](%s)", a.Item, a.URL) + } + summary := strings.Join(strings.Fields(a.Summary), " ") + if summary == "" { + summary = string(a.Class) + } + who := "" + if withRecipient { + // Backticks keep the status card from mentioning anyone. + who = fmt.Sprintf(" — `%s`", a.Recipient) + } + fmt.Fprintf(&sb, "- %s %s (%s since %s)%s\n", ref, summary, a.Class, a.At.UTC().Format("2006-01-02 15:04Z"), who) + } + return sb.String() +}