diff --git a/changelog.d/added-attention-ack-snooze-commands.md b/changelog.d/added-attention-ack-snooze-commands.md new file mode 100644 index 0000000000..ce9b6b7e0a --- /dev/null +++ b/changelog.d/added-attention-ack-snooze-commands.md @@ -0,0 +1 @@ +- **`/hive ack` and `/hive snooze ` for attention episodes, plus the attention action contract** ([#16359](https://github.com/hivecommons/hive/issues/16359), part of [#16270](https://github.com/hivecommons/hive/issues/16270)). On a repository whose `github.attention.admitter` is this hive, the episode's responsible person or a maintainer (`write`/`maintain`/`admin`) can acknowledge an attention episode or pause its reminders (1m–30d) from a comment; the un-park sweep records who and when on the episode (`acked_by`, `snoozed_by`, `snoozed_until`), refreshes the attention status section and replies once. Anyone else is ignored and nothing is recorded. Acknowledgement is not approval: neither command changes a label, releases a security/merge/review hold or opens a merge gate. `attention.Event` / `attention.NewObservation` define the contract every attention event must satisfy — who, what changed and why now, requested action, evidence, what Hive tried, what happens next, and how to ack, snooze or resolve — and refuse incomplete events. See `src/docs/maintainer-commands.md` and `src/docs/notifications.md`. diff --git a/src/docs/maintainer-commands.md b/src/docs/maintainer-commands.md index 8bf971ff68..97053867d0 100644 --- a/src/docs/maintainer-commands.md +++ b/src/docs/maintainer-commands.md @@ -19,6 +19,8 @@ https://github.com/hivecommons/hive/blob/v5/src/docs/maintainer-commands.md | `/hive decision proceed — ` | Confirms a feature request parked by the prior-art gate is a real gap. | The issue author, or a human commenter with `write`, `maintain`, or `admin`. | Open issues carrying `stage/017-possible-existing` below a `` comment. | Next un-park sweep. | Removes `stage/017-possible-existing`, appends a **Scope vs existing** section with `` to the issue body, records the un-park so the issue re-derives `stage/010-actionable` ([#13575](https://github.com/hivecommons/hive/issues/13575)). | | `/hive decision exists` | Agrees the request already exists. | Same as above. | Same as above. | Next un-park sweep. | Adds `already-exists`, closes the issue `not_planned`, replies with a pointer at the quoted findings. Reopen the issue to continue; the gate does not ask again. | | `/hive help` | Posts this command list. On parked issues it also repeats the issue-specific approve/decision options. | Any human commenter with at least `triage` repository permission for the on-demand workflow; the sweep path on parked issues requires `write`, `maintain`, or `admin`. | Any open issue or pull request. | GitHub Actions on the new comment; if Actions is unavailable on a parked issue, the next un-park sweep can also answer. | None. | +| `/hive ack [episode]` | Acknowledges an attention episode on the item: you have seen it, so reminders for it stop. **Acknowledgement is not approval.** See [Attention ack and snooze](#attention-ack-and-snooze). | The episode's named responsible person, or a human with `write`, `maintain`, or `admin` repository permission. Anyone else is ignored in silence. | Open issues and pull requests with an unresolved attention episode, on a repository whose `github.attention.admitter` is this hive. | Next un-park sweep, normally within 5 minutes. | None. Never releases a security, merge or review hold and never opens a merge gate. | +| `/hive snooze [episode]` | Pauses reminders for an attention episode until the duration elapses (`90m`, `4h`, `2d`, `1w`; 1m to 30d). | Same as `/hive ack`. | Same as `/hive ack`. | Next un-park sweep, normally within 5 minutes. | None. A snooze releases no hold. | | `/fixed` | Confirms that an open issue's fix is verified — or that what a parked issue waited on was done, in or outside the repository — and closes it as completed. Alias: `/close`. Plain-language confirmations such as "yes, this has been fixed" are accepted only when Hive is already waiting for reporter confirmation. | The issue reporter, or a human with `write`, `maintain`, or `admin` repository permission. On a parked issue (`stage/045-needs-decision`, `needs-human`, or a retired park spelling) the un-park sweep honours it from a human with `write`, `maintain`, or `admin` permission. | Open issues only, not pull requests. | GitHub Actions on the new comment where the repository runs the `/fixed` workflow; on parked issues, the next un-park sweep, normally within 5 minutes ([dibs#459](https://github.com/hivecommons/dibs/issues/459)). | Closes the issue as completed. The workflow adds `hive: reporter-confirmed` and removes `hive/likely-done` and `needs-reporter-confirmation` when present. On a parked issue the sweep removes `needs-human` and the retired park spellings, the stage engine strips `stage/*`, and Hive posts one acknowledgement; `hold` is never touched. | | `/reopen` | Reopens a closed issue that was closed too early. | The issue reporter, or a human with `write`, `maintain`, or `admin` repository permission. | Closed issues only, not pull requests. | GitHub Actions on the new comment. | Removes `needs-reporter-confirmation` when present. The reopen sticks: close-on-merge does not close the issue again for a PR that merged before the reopen, whether Hive (`` comment) or GitHub's closing keyword closed it; Hive records the latter with a `` comment. A later PR can still close it. | | `/help-wanted` | Adds the `help wanted` label. | Any non-bot commenter accepted by the label-helper workflow. | Issues and pull requests. | GitHub Actions on the new comment. | Adds `help wanted`. | @@ -128,6 +130,32 @@ take outside the repository — the un-park sweep itself honours a maintainer's `/fixed`, so a repository without the `/fixed` workflow still gets the close, the label clean-up and one acknowledgement. +## Attention ack and snooze + +Attention episodes ([#16270](https://github.com/hivecommons/hive/issues/16270)) +ask one named person to act on one condition. `/hive ack` and +`/hive snooze ` let that person, or a maintainer, answer the ask +without resolving it ([#16359](https://github.com/hivecommons/hive/issues/16359)): + +- The command must be the first non-empty line of a recent, unedited comment + by a human, outside quotes and fences — the same rules as the un-park + commands. Only the hive named by `github.attention.admitter` for the + repository answers, so a fleet replies once. +- Without an `[episode]` argument the command applies to every unresolved + episode on the item that you may act on. To target one, pass the key prefix + shown in the item's attention status section, e.g. `/hive ack 3f9a0c12b7de`. +- `/hive ack` records who acknowledged and when; `/hive snooze` records who + snoozed and until when. Both are stored on the episode in the attention + ledger, refresh the status section, and get one reply. +- **Acknowledgement is not approval.** Neither command adds or removes a + label, releases a security, merge or review hold, or opens a merge gate. To + release a hold use the lever the hold names (for example a trusted merger's + GitHub **Approve** review); to resolve the episode, fix the condition — it + resolves when Hive no longer observes it. +- A caller who is neither the episode's responsible person nor a maintainer + is ignored in silence and nothing is recorded. A malformed duration from an + eligible caller gets a reply explaining the accepted forms. + ## Prose replies on parked issues Plain approvals such as "approved", "go ahead", "sounds good", or "ship it" do diff --git a/src/docs/notifications.md b/src/docs/notifications.md index 81cf14d1be..5a7a126f8d 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -173,6 +173,29 @@ takes effect once the ledger routes its non-urgent writes through it. every security/merge hold notice always deliver immediately and do not consume budget. Unclassified writes are treated as exempt. +### Attention action contract + +Every admitted attention event must let the recipient act without digging +([#16359](https://github.com/hivecommons/hive/issues/16359), part of +[#16270](https://github.com/hivecommons/hive/issues/16270)). Producers build +the event body with `attention.NewObservation`, which refuses an incomplete +`attention.Event`; `Event.Render` emits, in order: + +| Field | Meaning | +|---|---| +| **Who** | The person or team asked to act. | +| **What changed / why now** | The change that made the condition need attention now. | +| **Requested action** | The single concrete thing asked of the recipient. | +| **Evidence** | What the condition was observed from (run, finding, SHA). | +| **What Hive tried** | What Hive already attempted on its own. | +| **What happens next** | What Hive will do if nobody acts. | +| **How to ack, snooze or resolve** | `/hive ack`, `/hive snooze `, and what clears the condition. | + +Every event ends with the same wording: *Acknowledgement is not approval: +`/hive ack` and `/hive snooze` only quiet reminders. They release no security, +merge or review hold, change no label and open no merge gate.* See +[maintainer commands](maintainer-commands.md#attention-ack-and-snooze). + ## What triggers notifications The Hive Go process sends notifications for these events: diff --git a/src/pkg/attention/ack.go b/src/pkg/attention/ack.go new file mode 100644 index 0000000000..29f9b3204f --- /dev/null +++ b/src/pkg/attention/ack.go @@ -0,0 +1,175 @@ +package attention + +import ( + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +// MaxSnooze bounds `/hive snooze`: a snooze quiets reminders, it must not +// become an indefinite mute of a condition that still needs a person. +const MaxSnooze = 30 * 24 * time.Hour + +// CommandKind is an attention sub-command of `/hive`. +type CommandKind string + +const ( + CommandAck CommandKind = "ack" + CommandSnooze CommandKind = "snooze" +) + +var ( + // ErrNoEpisode means the item has no unresolved episode the command names. + ErrNoEpisode = errors.New("attention: no unresolved attention episode matches") + // ErrNotPermitted means the caller is neither the episode's named + // recipient nor a maintainer; nothing was recorded. + ErrNotPermitted = errors.New("attention: only the responsible person or a maintainer may ack or snooze") +) + +// Command is a parsed `/hive ack [episode]` or `/hive snooze +// [episode]`. Target is an optional episode key-hash prefix as shown in the +// status card; empty means every unresolved episode on the item. +type Command struct { + Kind CommandKind + Snooze time.Duration + Target string +} + +// ParseCommand reads an attention command off the comment's first non-empty +// line, never inside a quote or a fence. ok reports whether the comment is an +// attention command at all; err reports a malformed one (for example a +// missing or out-of-range snooze duration) so the caller can explain it. +func ParseCommand(body string) (cmd Command, ok bool, err error) { + line := "" + for _, l := range strings.Split(body, "\n") { + if l = strings.TrimSpace(l); l != "" { + line = l + break + } + } + if line == "" || strings.HasPrefix(line, ">") || strings.HasPrefix(line, "```") || strings.HasPrefix(line, "~~~") { + return Command{}, false, nil + } + f := strings.Fields(line) + if len(f) < 2 || !strings.EqualFold(f[0], "/hive") { + return Command{}, false, nil + } + switch CommandKind(strings.ToLower(f[1])) { + case CommandAck: + cmd = Command{Kind: CommandAck} + if len(f) > 2 { + cmd.Target = f[2] + } + case CommandSnooze: + cmd = Command{Kind: CommandSnooze} + if len(f) < 3 { + return cmd, true, errors.New("snooze needs a duration, for example `/hive snooze 2d`") + } + d, perr := ParseSnooze(f[2]) + if perr != nil { + return cmd, true, perr + } + cmd.Snooze = d + if len(f) > 3 { + cmd.Target = f[3] + } + default: + return Command{}, false, nil + } + cmd.Target = strings.ToLower(strings.Trim(cmd.Target, "`")) + if cmd.Target != "" && strings.Trim(cmd.Target, "0123456789abcdef") != "" { + return cmd, true, fmt.Errorf("episode %q is not a key from the attention status card", cmd.Target) + } + return cmd, true, nil +} + +// ParseSnooze accepts Go durations ("90m", "4h") plus whole days ("2d") and +// weeks ("1w"), bounded by MaxSnooze. +func ParseSnooze(s string) (time.Duration, error) { + s = strings.ToLower(strings.TrimSpace(s)) + var d time.Duration + var err error + if n := len(s); n > 1 && (s[n-1] == 'd' || s[n-1] == 'w') { + var v int + v, err = strconv.Atoi(s[:n-1]) + unit := 24 * time.Hour + if s[n-1] == 'w' { + unit *= 7 + } + if err == nil && v > 0 && v <= int(MaxSnooze/unit) { + d = time.Duration(v) * unit + } + } else { + d, err = time.ParseDuration(s) + } + if err != nil || d < time.Minute || d > MaxSnooze { + return 0, fmt.Errorf("snooze duration %q must be between 1m and 30d, for example `4h` or `2d`", s) + } + return d, nil +} + +// MayAct reports whether actor may ack or snooze e: the episode's named +// recipient (case-insensitive, optional `@`) or a maintainer. +func MayAct(e Episode, actor string, maintainer bool) bool { + if maintainer { + return true + } + a := canonical(strings.TrimPrefix(strings.TrimSpace(actor), "@")) + return a != "" && a == canonical(strings.TrimPrefix(strings.TrimSpace(e.Key.Recipient), "@")) +} + +// Apply records an ack or snooze from actor on every unresolved episode of +// repo#item that cmd targets and actor may act on. It changes only the +// reminder state on the episode (AckedAt/AckedBy, SnoozedUntil/SnoozedBy). +// It never touches a hold label, a merge gate or a review verdict: +// acknowledgement is not approval, and a snooze releases no hold. +func (s *Store) Apply(repo string, item int, actor string, maintainer bool, cmd Command) ([]Episode, error) { + if cmd.Kind != CommandAck && cmd.Kind != CommandSnooze { + return nil, errors.New("attention: unsupported command") + } + if cmd.Kind == CommandSnooze && (cmd.Snooze <= 0 || cmd.Snooze > MaxSnooze) { + return nil, errors.New("attention: snooze duration out of range") + } + actor = strings.TrimPrefix(strings.TrimSpace(actor), "@") + s.mu.Lock() + defer s.mu.Unlock() + var matched, permitted []*Episode + for hash, e := range s.state.Episodes { + if e.State == Resolved || e.Key == (Key{}) || canonical(e.Key.Repo) != canonical(repo) || e.Key.Item != item || !strings.HasPrefix(hash, cmd.Target) { + continue + } + matched = append(matched, e) + if MayAct(*e, actor, maintainer) { + permitted = append(permitted, e) + } + } + if len(matched) == 0 { + return nil, ErrNoEpisode + } + if len(permitted) == 0 { + return nil, ErrNotPermitted + } + now := s.now().UTC() + out := make([]Episode, 0, len(permitted)) + for _, e := range permitted { + switch cmd.Kind { + case CommandAck: + e.State = Acknowledged + if e.AckedAt.IsZero() { + e.AckedAt = now + } + e.AckedBy = actor + case CommandSnooze: + e.SnoozedUntil = now.Add(cmd.Snooze) + e.SnoozedBy = actor + } + e.WouldNotify = false + out = append(out, *e) + } + if err := s.save(); err != nil { + return nil, err + } + return out, nil +} diff --git a/src/pkg/attention/ack_test.go b/src/pkg/attention/ack_test.go new file mode 100644 index 0000000000..16cfde6340 --- /dev/null +++ b/src/pkg/attention/ack_test.go @@ -0,0 +1,148 @@ +package attention + +import ( + "errors" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestParseCommand(t *testing.T) { + for _, tc := range []struct { + body string + ok bool + bad bool + kind CommandKind + snooze time.Duration + target string + }{ + {body: "/hive ack", ok: true, kind: CommandAck}, + {body: "\n /HIVE Ack abc123\nthanks", ok: true, kind: CommandAck, target: "abc123"}, + {body: "/hive snooze 2d", ok: true, kind: CommandSnooze, snooze: 48 * time.Hour}, + {body: "/hive snooze 90m `ABCDEF`", ok: true, kind: CommandSnooze, snooze: 90 * time.Minute, target: "abcdef"}, + {body: "/hive snooze 1w", ok: true, kind: CommandSnooze, snooze: 7 * 24 * time.Hour}, + {body: "/hive snooze", ok: true, bad: true}, + {body: "/hive snooze 31d", ok: true, bad: true}, + {body: "/hive snooze 10s", ok: true, bad: true}, + {body: "/hive snooze forever", ok: true, bad: true}, + {body: "/hive ack not-a-key", ok: true, bad: true}, + {body: "> /hive ack", ok: false}, + {body: "please /hive ack", ok: false}, + {body: "/hive approve", ok: false}, + } { + cmd, ok, err := ParseCommand(tc.body) + if ok != tc.ok || (err != nil) != tc.bad { + t.Fatalf("%q: ok=%v err=%v", tc.body, ok, err) + } + if !tc.ok || tc.bad { + continue + } + if cmd.Kind != tc.kind || cmd.Snooze != tc.snooze || cmd.Target != tc.target { + t.Fatalf("%q: got %+v", tc.body, cmd) + } + } +} + +func seeded(t *testing.T, path string) (*Store, Episode) { + t.Helper() + s := openStore(t, path) + f := &forge{} + es := report(t, s, f, "owner", observation()) + if len(es) != 1 || es[0].State != Notified { + t.Fatalf("seed: %+v", es) + } + return s, es[0] +} + +func TestAckAndSnoozeRecordedOnEpisodeByRecipientOrMaintainer(t *testing.T) { + path := filepath.Join(t.TempDir(), "episodes.json") + s, _ := seeded(t, path) + now := time.Date(2026, 11, 3, 10, 0, 0, 0, time.UTC) + s.now = func() time.Time { return now } + + es, err := s.Apply("org/repo", 1, "@Maintainer", false, Command{Kind: CommandAck}) + if err != nil || len(es) != 1 { + t.Fatalf("recipient ack: %v %+v", err, es) + } + if es[0].State != Acknowledged || !es[0].AckedAt.Equal(now) || es[0].AckedBy != "Maintainer" { + t.Fatalf("ack not recorded: %+v", es[0]) + } + es, err = s.Apply("org/repo", 1, "repo-admin", true, Command{Kind: CommandSnooze, Snooze: 4 * time.Hour}) + if err != nil || len(es) != 1 { + t.Fatalf("maintainer snooze: %v %+v", err, es) + } + if !es[0].SnoozedUntil.Equal(now.Add(4*time.Hour)) || es[0].SnoozedBy != "repo-admin" || es[0].State != Acknowledged { + t.Fatalf("snooze not recorded: %+v", es[0]) + } + // Persisted for the reminder scheduler, across a restart. + got := openStore(t, path).Snapshot("org/repo", 1) + if len(got) != 1 || got[0].AckedBy != "Maintainer" || got[0].SnoozedBy != "repo-admin" || !got[0].SnoozedUntil.Equal(now.Add(4*time.Hour)) { + t.Fatalf("not persisted: %+v", got) + } +} + +func TestAckAndSnoozeRejectedForOtherCallers(t *testing.T) { + s, before := seeded(t, filepath.Join(t.TempDir(), "episodes.json")) + for _, cmd := range []Command{{Kind: CommandAck}, {Kind: CommandSnooze, Snooze: time.Hour}} { + if _, err := s.Apply("org/repo", 1, "drive-by", false, cmd); !errors.Is(err, ErrNotPermitted) { + t.Fatalf("%s by non-recipient non-maintainer: err=%v", cmd.Kind, err) + } + } + after := s.Snapshot("org/repo", 1) + if len(after) != 1 || after[0] != before { + t.Fatalf("rejected command changed the episode:\n%+v\n%+v", before, after) + } + if _, err := s.Apply("org/repo", 2, "maintainer", true, Command{Kind: CommandAck}); !errors.Is(err, ErrNoEpisode) { + t.Fatalf("other item: %v", err) + } + other := "0" + if strings.HasPrefix(before.Key.Hash(), other) { + other = "1" + } + if _, err := s.Apply("org/repo", 1, "maintainer", true, Command{Kind: CommandAck, Target: other}); !errors.Is(err, ErrNoEpisode) { + t.Fatalf("unmatched target: %v", err) + } + if _, err := s.Apply("org/repo", 1, "maintainer", false, Command{Kind: CommandAck, Target: before.Key.Hash()[:12]}); err != nil { + t.Fatalf("status-card key prefix: %v", err) + } +} + +func TestAckAndSnoozeChangeOnlyReminderState(t *testing.T) { + s, before := seeded(t, filepath.Join(t.TempDir(), "episodes.json")) + if _, err := s.Apply("org/repo", 1, "maintainer", false, Command{Kind: CommandAck}); err != nil { + t.Fatal(err) + } + if _, err := s.Apply("org/repo", 1, "maintainer", false, Command{Kind: CommandSnooze, Snooze: time.Hour}); err != nil { + t.Fatal(err) + } + after := s.Snapshot("org/repo", 1)[0] + after.State, after.AckedAt, after.AckedBy, after.SnoozedUntil, after.SnoozedBy = before.State, before.AckedAt, before.AckedBy, before.SnoozedUntil, before.SnoozedBy + if after != before { + t.Fatalf("ack/snooze changed non-reminder state:\n%+v\n%+v", before, after) + } +} + +func TestEventRenderEmitsEveryContractField(t *testing.T) { + ev := Event{Who: "@alice", WhyNow: "required check failed on the new head", Action: "re-run or fix the ARM64 job", Evidence: "run 42", Tried: "two automatic re-runs", Next: "Hive re-checks on the next push", Resolve: "the required check passes"} + body := ev.Render() + for _, want := range []string{ + "**Who:** @alice", "**What changed / why now:** required check", "**Requested action:** re-run", "**Evidence:** run 42", + "**What Hive tried:** two automatic", "**What happens next:** Hive re-checks", "**How to ack, snooze or resolve:**", + "`/hive ack`", "`/hive snooze `", "Resolve: the required check passes", + "Acknowledgement is not approval", "release no security, merge or review hold", + } { + if !strings.Contains(body, want) { + t.Fatalf("render missing %q:\n%s", want, body) + } + } + key := observation().Key + o, err := NewObservation(key, true, "run 42", ev) + if err != nil || o.Body != body || o.Key != key || !o.Actionable { + t.Fatalf("observation: %v %+v", err, o) + } + ev.Tried = " " + if _, err := NewObservation(key, true, "run 42", ev); err == nil || !strings.Contains(err.Error(), "what Hive tried") { + t.Fatalf("incomplete event admitted: %v", err) + } +} diff --git a/src/pkg/attention/contract.go b/src/pkg/attention/contract.go new file mode 100644 index 0000000000..aea72f41a3 --- /dev/null +++ b/src/pkg/attention/contract.go @@ -0,0 +1,78 @@ +package attention + +import ( + "errors" + "fmt" + "strings" +) + +// NotApproval is the contract wording every attention event carries so a +// recipient never mistakes `/hive ack` for a release. +const NotApproval = "Acknowledgement is not approval: `/hive ack` and `/hive snooze` only quiet reminders. They release no security, merge or review hold, change no label and open no merge gate." + +// Event is the attention action contract. Every admitted attention event must +// say who is asked, what changed and why now, the requested action, the +// evidence, what Hive already tried, what happens next, and how to ack, +// snooze or resolve it. Producers build Observation bodies with NewObservation +// so an incomplete event is refused rather than paged. +type Event struct { + // Who is the person or team asked to act (normally Key.Recipient). + Who string + // WhyNow is what changed and why it needs attention now. + WhyNow string + // Action is the single concrete thing the recipient is asked to do. + Action string + // Evidence links or names what the condition was observed from. + Evidence string + // Tried is what Hive already attempted on its own. + Tried string + // Next is what Hive will do if nobody acts. + Next string + // Resolve says what clears the condition (so the episode resolves). + Resolve string +} + +// Validate refuses an event missing any contract field. +func (e Event) Validate() error { + var missing []string + for _, f := range []struct{ name, v string }{ + {"who", e.Who}, {"why now", e.WhyNow}, {"requested action", e.Action}, {"evidence", e.Evidence}, + {"what Hive tried", e.Tried}, {"what happens next", e.Next}, {"how to resolve", e.Resolve}, + } { + if strings.TrimSpace(f.v) == "" { + missing = append(missing, f.name) + } + } + if len(missing) > 0 { + return errors.New("attention: event missing contract fields: " + strings.Join(missing, ", ")) + } + return nil +} + +// Render emits every contract field, the ack/snooze/resolve instructions and +// the NotApproval wording. +func (e Event) Render() string { + var b strings.Builder + fmt.Fprintf(&b, "**Who:** %s\n", oneLine(e.Who)) + fmt.Fprintf(&b, "**What changed / why now:** %s\n", oneLine(e.WhyNow)) + fmt.Fprintf(&b, "**Requested action:** %s\n", oneLine(e.Action)) + fmt.Fprintf(&b, "**Evidence:** %s\n", oneLine(e.Evidence)) + fmt.Fprintf(&b, "**What Hive tried:** %s\n", oneLine(e.Tried)) + fmt.Fprintf(&b, "**What happens next:** %s\n", oneLine(e.Next)) + b.WriteString("**How to ack, snooze or resolve:**\n") + b.WriteString("- `/hive ack` — you have seen this; reminders stop for this episode.\n") + b.WriteString("- `/hive snooze ` (for example `4h`, `2d`; at most 30d) — reminders pause until then.\n") + fmt.Fprintf(&b, "- Resolve: %s\n", oneLine(e.Resolve)) + b.WriteString("\n" + NotApproval + "\n") + return b.String() +} + +// NewObservation builds an observation whose body satisfies the contract. +func NewObservation(key Key, actionable bool, evidence string, ev Event) (Observation, error) { + if err := ev.Validate(); err != nil { + return Observation{}, err + } + return Observation{Key: key, Actionable: actionable, Evidence: evidence, Body: ev.Render()}, nil +} + +func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") } diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go index 46b9a23e36..6dd9f8f187 100644 --- a/src/pkg/attention/episodes.go +++ b/src/pkg/attention/episodes.go @@ -123,6 +123,10 @@ type Episode struct { // Baseline is fail-quiet recovery: history must be reconciled, not replayed. Baseline bool `json:"baseline,omitempty"` QuietReopen bool `json:"quiet_reopen,omitempty"` + // AckedBy and SnoozedBy record who ran `/hive ack` / `/hive snooze` + // (see Store.Apply); reminder scheduling reads them, holds never do. + AckedBy string `json:"acked_by,omitempty"` + SnoozedBy string `json:"snoozed_by,omitempty"` } func (e Episode) Marker() string { diff --git a/src/pkg/github/attention_command.go b/src/pkg/github/attention_command.go new file mode 100644 index 0000000000..48da1f2ad9 --- /dev/null +++ b/src/pkg/github/attention_command.go @@ -0,0 +1,122 @@ +package github + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" + + "github.com/hivecommons/hive/pkg/attention" +) + +// replyAttentionCommands answers `/hive ack` and `/hive snooze ` +// on an item that has unresolved attention episodes (hivecommons/hive#16359). +// Only the admitting hive answers, so a fleet replies once. The commands +// record reminder state on the episode and refresh the attention status +// section; they never add or remove a label, never release a security, +// merge or review hold and never open a merge gate. Like the un-park +// commands, a caller who is neither the episode's recipient nor a +// write/maintain/admin maintainer is ignored in silence, and the reply's +// ID marker keeps every command answered at most once. +func (c *Client) replyAttentionCommands(ctx context.Context, displayRepo, owner, repo string, issue *gh.Issue, cutoff time.Time) (int, error) { + if c.attentionConfig == nil || c.attentionHiveID == "" || c.attentionConfig().Owner(displayRepo) != c.attentionHiveID { + return 0, nil + } + number := issue.GetNumber() + store, err := c.WritebackGate().AttentionStore() + if err != nil { + return 0, err + } + open := false + for _, e := range store.Snapshot(displayRepo, number) { + open = open || e.State != attention.Resolved + } + if !open { + return 0, nil + } + comments, err := c.listIssueCommentsSince(ctx, owner, repo, number, cutoff) + if err != nil { + return 0, err + } + answered := c.answeredUnparkCommentIDs(comments) + replies := 0 + for _, cm := range comments { + if cm == nil || cm.GetID() <= 0 || answered[cm.GetID()] || cm.GetCreatedAt().Time.Before(cutoff) || cm.GetUpdatedAt().Time.After(cm.GetCreatedAt().Time) { + continue + } + cmd, ok, parseErr := attention.ParseCommand(cm.GetBody()) + if !ok || !c.isHumanAuthor(cm.GetUser()) { + continue + } + actor := safeGetLogin(cm.GetUser()) + maintainer, err := c.commenterMayUnpark(ctx, owner, repo, actor, false) + if err != nil { + return replies, err + } + var body string + if parseErr != nil { + if !maintainer && !recipientOf(store.Snapshot(displayRepo, number), actor) { + continue + } + body = fmt.Sprintf("@%s nothing was recorded: %s.\n\n%s", actor, strings.TrimSuffix(parseErr.Error(), "."), attention.NotApproval) + } else { + episodes, applyErr := store.Apply(displayRepo, number, actor, maintainer, cmd) + switch { + case errors.Is(applyErr, attention.ErrNotPermitted): + continue + case errors.Is(applyErr, attention.ErrNoEpisode): + if !maintainer && !recipientOf(store.Snapshot(displayRepo, number), actor) { + continue + } + body = fmt.Sprintf("@%s nothing was recorded: no open attention episode on this item matches `%s`.", actor, cmd.Target) + if cmd.Target == "" { + body = fmt.Sprintf("@%s nothing was recorded: this item has no open attention episode.", actor) + } + case applyErr != nil: + return replies, applyErr + default: + body = renderAttentionCommandReply(actor, cmd, episodes) + // The ack is already durable; a stale card must not cost the reply. + if _, err := c.UpsertPRStatusSection(ctx, displayRepo, number, "attention", attentionStatus(store.Snapshot(displayRepo, number))); err != nil && c.logger != nil { + c.logger.Warn("attention status refresh after command failed", "repo", displayRepo, "item", number, "error", err) + } + } + } + if err := c.postUnparkReply(ctx, owner, repo, number, cm.GetID(), body); err != nil { + return replies, err + } + replies++ + } + return replies, nil +} + +func recipientOf(episodes []attention.Episode, actor string) bool { + for _, e := range episodes { + if e.State != attention.Resolved && attention.MayAct(e, actor, false) { + return true + } + } + return false +} + +func renderAttentionCommandReply(actor string, cmd attention.Command, episodes []attention.Episode) string { + var b strings.Builder + switch cmd.Kind { + case attention.CommandAck: + fmt.Fprintf(&b, "@%s acknowledged %d attention episode(s); reminders for them stop.\n", actor, len(episodes)) + case attention.CommandSnooze: + until := time.Time{} + if len(episodes) > 0 { + until = episodes[0].SnoozedUntil + } + fmt.Fprintf(&b, "@%s snoozed reminders for %d attention episode(s) until %s.\n", actor, len(episodes), until.UTC().Format("2006-01-02T15:04Z")) + } + for _, e := range episodes { + fmt.Fprintf(&b, "- `%s`: %s → %s\n", e.Key.Hash()[:12], statusText(e.Key.Action), statusText(e.Key.Recipient)) + } + b.WriteString("\n" + attention.NotApproval + "\n") + return b.String() +} diff --git a/src/pkg/github/attention_command_test.go b/src/pkg/github/attention_command_test.go new file mode 100644 index 0000000000..ca290c6986 --- /dev/null +++ b/src/pkg/github/attention_command_test.go @@ -0,0 +1,84 @@ +package github + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/hivecommons/hive/pkg/attention" + "github.com/hivecommons/hive/pkg/writeback" +) + +type nopAttentionDelivery struct{} + +func (nopAttentionDelivery) History(context.Context, string, int) ([]string, error) { return nil, nil } +func (nopAttentionDelivery) Find(context.Context, attention.Episode) (bool, error) { return false, nil } +func (nopAttentionDelivery) Post(context.Context, attention.Episode, string) error { return nil } + +// `/hive ack` and `/hive snooze` record reminder state on the episode for the +// recipient or a maintainer, are ignored for anyone else, and never touch a +// hold label, an issue/PR state or a merge endpoint (hivecommons/hive#16359). +func TestSweepAttentionAckSnoozeRecordOnlyAndNeverReleaseHolds(t *testing.T) { + pr := parkedIssue(7, + humanComment(20, "bob", "/hive ack"), + humanComment(21, "alice", "/hive snooze 2d"), + humanComment(22, "maintainer", "/hive ack"), + ) + pr.PullRequest = &unparkWirePRLink{URL: "https://example.test/pulls/7"} + pr.Labels = []wireLabel{{Name: "hold"}, {Name: PRNeedsDecisionStageLabel}, {Name: "needs-human"}} + inner, rec := newUnparkServer(t, "org", "repo", []unparkWireIssue{pr}, map[string]string{"maintainer": "write"}) + var mu sync.Mutex + var writes []string + outer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + mu.Lock() + writes = append(writes, r.Method+" "+r.URL.Path) + mu.Unlock() + } + inner.Config.Handler.ServeHTTP(w, r) + })) + t.Cleanup(outer.Close) + c := newTestClient(t, outer, "org", []string{"repo"}) + c.SetWritebackGate(writeback.New(writeback.Config{}, writeback.Deps{}, "")) + cfg := attention.Config{Admitter: map[string]string{"org/repo": "hive-a"}} + c.SetAttention("hive-a", func() attention.Config { return cfg }) + store, err := c.WritebackGate().AttentionStore() + if err != nil { + t.Fatal(err) + } + key := attention.Key{Repo: "org/repo", Item: 7, Action: "security-repair", Recipient: "@alice", Subject: "finding-identity/v1:risk"} + if _, err := store.Report(context.Background(), cfg, "hive-a", "org/repo", 7, []attention.Observation{{Key: key, Actionable: true, Body: "x"}}, nopAttentionDelivery{}); err != nil { + t.Fatal(err) + } + + if _, err := c.SweepIssueUnparkCommands(context.Background(), IssueUnparkSweepOptions{}); err != nil { + t.Fatal(err) + } + + es := store.Snapshot("org/repo", 7) + if len(es) != 1 || es[0].State != attention.Acknowledged || es[0].AckedBy != "maintainer" || es[0].SnoozedBy != "alice" || es[0].SnoozedUntil.IsZero() { + t.Fatalf("episode = %+v", es) + } + if len(rec.added[7]) != 0 || len(rec.removed[7]) != 0 || len(rec.patched[7]) != 0 { + t.Fatalf("labels/state changed: added=%v removed=%v patched=%v", rec.added[7], rec.removed[7], rec.patched[7]) + } + mu.Lock() + defer mu.Unlock() + for _, w := range writes { + if !strings.HasSuffix(w, "/issues/7/comments") && !strings.Contains(w, "/issues/comments/") { + t.Fatalf("ack/snooze made a non-comment write: %s (all: %v)", w, writes) + } + } + replies := strings.Join(rec.posted[7], "\n---\n") + if strings.Contains(replies, unparkReplyMarkerPrefix+"20 ") { + t.Fatalf("non-recipient non-maintainer was answered:\n%s", replies) + } + for _, want := range []string{unparkReplyMarkerPrefix + "21 -->", "@alice snoozed", unparkReplyMarkerPrefix + "22 -->", "@maintainer acknowledged", "Acknowledgement is not approval"} { + if !strings.Contains(replies, want) { + t.Fatalf("replies missing %q:\n%s", want, replies) + } + } +} diff --git a/src/pkg/github/issue_unpark_command.go b/src/pkg/github/issue_unpark_command.go index 4a68d0604a..e02d86ef33 100644 --- a/src/pkg/github/issue_unpark_command.go +++ b/src/pkg/github/issue_unpark_command.go @@ -308,6 +308,15 @@ func (c *Client) SweepIssueUnparkCommands(ctx context.Context, opts IssueUnparkS if issue == nil { continue } + // `/hive ack` / `/hive snooze` only touch the attention ledger + // (hivecommons/hive#16359); the item then continues through + // the un-park paths below unchanged. + // Items without an open episode cost no API call. + n, err := c.replyAttentionCommands(ctx, owner+"/"+repoName, owner, repoName, issue, cutoff) + result.Replies += n + if err != nil && c.logger != nil { + c.logger.Warn("unpark sweep skipped attention commands", "repo", repo, "item", issue.GetNumber(), "error", err) + } labels := issueLabelNames(issue.Labels) if issue.IsPullRequest() { // `/hive approve` on any PR gets an acknowledgement or an