diff --git a/changelog.d/added-condition-episodes.md b/changelog.d/added-condition-episodes.md new file mode 100644 index 0000000000..436c11a9bf --- /dev/null +++ b/changelog.d/added-condition-episodes.md @@ -0,0 +1 @@ +- Add an opt-in, per-repo single-admitter attention primitive with durable condition episodes, quiet recovery, and uncertain-POST reconciliation; existing quiet-mode writers and review/hold behavior remain unchanged. diff --git a/src/cmd/hive/github_client_config.go b/src/cmd/hive/github_client_config.go index f48d785dda..819487b96b 100644 --- a/src/cmd/hive/github_client_config.go +++ b/src/cmd/hive/github_client_config.go @@ -9,6 +9,7 @@ import ( cruxconfig "github.com/hivecommons/hive/crux/config" "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/attention" "github.com/hivecommons/hive/pkg/authorkind" "github.com/hivecommons/hive/pkg/beads" "github.com/hivecommons/hive/pkg/claims" @@ -109,6 +110,7 @@ func (b *boot) applyGitHubClientConfigHooks(client *github.Client) { // one process-wide write-back gate (pkg/writeback); a rebuilt client // must inherit it or the sweeps regress to ungated. client.SetWritebackGate(b.writebackGate()) + client.SetAttention(b.cfg.HiveID, func() attention.Config { return b.cfg.GitHub.Attention }) client.SetSentinelAlertLabel(b.cfg.Sentinel.LabelOrDefault()) // Evaluated heads persist so a restart or rebuild neither re-diffs every // open PR nor blanks the Matrix feed until the next sweep (#16276). diff --git a/src/docs/attention-episodes.md b/src/docs/attention-episodes.md new file mode 100644 index 0000000000..993a368ca9 --- /dev/null +++ b/src/docs/attention-episodes.md @@ -0,0 +1,93 @@ +# Condition episodes and attention admission + +The opt-in condition delivery primitive for RFC #16075 / #16267 reuses the +writeback gate and `hive:status`. It does **not** migrate existing note producers, +change quiet mode, or enable the issue-side pilot (#16270). The authoritative +status writer (#16263) is a prerequisite to enabling concurrent producer routing. +No review, machine command, security hold or merge hold is changed. An +acknowledgement is not approval. + +## Configuration + +```yaml +github: + attention: + admitter: + hivecommons/hive: hosted-hive-id + flap_window: 12h +``` + +Keys must be fully qualified repositories. Exactly one deployment may own the +configured hive ID for a repo. Other hive IDs record **would notify** and update +status only; they cannot create attention events. This is explicit single-owner +admission, **not** a distributed lock or atomic GitHub list-before-create scheme. +Do not clone an admitter's identity into another active deployment. During +handoff, stop the old admitter before starting the new one, preserve its ledger, +and reconcile its uncertain attempts before changing the configured owner. +Unknown-owner uncertain attempts remain visible and are not automatically retried. + +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 reminder or per-recipient budget in this layer (#16270 / #16271). + +## Producer contract + +`github.Client.ReportAttention` takes the full current condition inventory for +one item, a writeback item/kind, and structured observations. All reporters must +use the same action class, responsible recipient and subject, independent of +producer. Do not derive identities from comment prose: + +- CI: `attention.CISubject(requiredJobName, normalizedErrorClass)`. The caller + classifies errors; run IDs and head SHAs belong in evidence only. +- Sentinel/security: `attention.FindingSubject(findingidentity.Record)` reuses the + existing subject/predicate/location identity, without head SHA. +- Holds/decisions: `attention.DecisionSubject(requiredDecisionID)`. + +A materially different risk, action or owner changes the key. Consequently a +new urgent finding does not share a previous finding's delivery budget. The +attention body is supplied by the producer (the action contract belongs to +#16270); this API must not be used for arbitrary untrusted/protocol text. + +Repeated reports update `last_seen` and evidence, not the episode or delivery. +Explicit resolved observations close episodes; absence from an inventory is not +proof of recovery. Within the flap window, recovery/reappearance reopens quietly. +After that window a recorded recovery followed by recurrence starts a new episode. +`Store.Update` records acknowledgement, snooze or resolution; it has no access to +holds, permissions or reviews. + +## Recovery and delivery + +The ledger lives beside the writeback state (`writeback.json.attention`, following +`HIVE_WRITEBACK_STATE_PATH`), uses a versioned JSON schema and fsync/atomic rename, +and is shared by clients using the process-wide writeback gate. Save failures +fence POSTs. Unknown schema versions fail closed instead of being overwritten. + +The first **complete inventory per item** consults delivery history: list trusted +Hive attention comments (status-card condition markers do not count) and seed any +matching current condition without sending. A condition with no prior attention +comment notifies on its first report, so ledger loss never swallows a genuinely +new risk and never replays an already-paged one. Do not send partial producer +snapshots during recovery: aggregate the item's known conditions before calling +this API. Conditions seeded from history are marked uncertain for human +reconciliation in the status section. This deliberately chooses no historical +replay over guessing which unrecorded old incident deserves another page. + +Before POST, persist a random attempt ID and its owner. Comments carry +``. After any ambiguous failure or +restart with an unfinished attempt, paginate comments and look for that exact +trusted marker before retrying. A lookup failure never permits a retry; a found +attempt becomes notified without another POST. An absent attempt retries with +the **same** ID, even if evidence/body changed. This reconciliation is only for +the single admitter's own attempts, not cross-instance deduplication. The existing +mutation journal remains in the GitHub write path as an additional safeguard. + +The file is bounded to 4096 episodes and 4096 initialized items. Resolved +episodes are pruned once the flap window has passed (recurrence would start a +fresh episode anyway); uncertain episodes and history-seeded baselines are kept. +Capacity errors fail closed and retain history instead of evicting an active +incident and replaying it. Operators must reconcile/archive inventory before +resetting a full ledger; a reset re-enters baseline recovery, never an automatic +re-page. Status displays up to 20 active conditions with an overflow count; all +records remain in the ledger. Status includes owner/action, last evidence, +acknowledged/snoozed state and uncertain/would-notify indicators, with copied +mentions neutralized. This is a queue snapshot, not an unbounded transcript. diff --git a/src/pkg/attention/config_test.go b/src/pkg/attention/config_test.go new file mode 100644 index 0000000000..ea22abaaf4 --- /dev/null +++ b/src/pkg/attention/config_test.go @@ -0,0 +1,56 @@ +package attention + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/findingidentity" +) + +func TestConfigValidation(t *testing.T) { + for _, cfg := range []Config{ + {FlapWindow: -time.Second}, + {Admitter: map[string]string{"repo": "owner"}}, + {Admitter: map[string]string{"o/r": ""}}, + {Admitter: map[string]string{"o/r": "one", "O/R": "two"}}, + } { + if err := cfg.Validate(); err == nil { + t.Fatalf("accepted ambiguous config: %+v", cfg) + } + } + if err := testConfig.Validate(); err != nil { + t.Fatal(err) + } + if (Config{}).Window() != 12*time.Hour || (Config{FlapWindow: 6 * time.Hour}).Window() != 6*time.Hour { + t.Fatal("flap defaults") + } + if testConfig.Owner("ORG/REPO") != "owner" || testConfig.Owner("repo") != "" { + t.Fatal("owner must match full repo") + } +} +func TestFindingIdentityUsesExistingKey(t *testing.T) { + r := findingidentity.Record{SubjectDigest: "subject", Predicate: "security", Location: "pkg/file.go:12"} + want := findingidentity.Key(r) + if FindingSubject(r) != want { + t.Fatal("finding identity changed") + } + r.Location = "pkg/file.go:25" + if FindingSubject(r) != want { + t.Fatal("new head line number split episode") + } + r.Predicate = "urgent-new-risk" + if FindingSubject(r) == want { + t.Fatal("new risk collapsed") + } +} +func TestUnknownVersionDoesNotOverwrite(t *testing.T) { + path := filepath.Join(t.TempDir(), "state") + if err := os.WriteFile(path, []byte(`{"version":2,"items":{},"episodes":{}}`), 0600); err != nil { + t.Fatal(err) + } + if _, err := Open(path); err == nil { + t.Fatal("future ledger version accepted") + } +} diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go new file mode 100644 index 0000000000..88f225f5cd --- /dev/null +++ b/src/pkg/attention/episodes.go @@ -0,0 +1,439 @@ +// Package attention persists producer-independent condition episodes. It is an +// opt-in delivery primitive, not a review authority or a replacement for holds. +package attention + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/pkg/findingidentity" +) + +const DefaultFlapWindow = 12 * time.Hour +const MaxEpisodes = 4096 +const MaxItems = 4096 + +// Config names exactly one deployment per fully qualified repo. Operators must +// not run two independent deployments with the same hive ID and ledger. +type Config struct { + Admitter map[string]string `yaml:"admitter,omitempty" json:"admitter,omitempty"` + FlapWindow time.Duration `yaml:"flap_window,omitempty" json:"flap_window,omitempty"` +} + +func (c Config) Owner(repo string) string { + for r, owner := range c.Admitter { + if canonical(r) == canonical(repo) { + return strings.TrimSpace(owner) + } + } + return "" +} +func (c Config) Validate() error { + if c.FlapWindow < 0 { + return errors.New("github.attention.flap_window must not be negative") + } + seen := map[string]bool{} + for repo, owner := range c.Admitter { + key := canonical(repo) + parts := strings.Split(key, "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" || strings.ContainsAny(key, " \t\r\n") { + return errors.New("github.attention.admitter requires fully qualified owner/repo keys") + } + if seen[key] { + return errors.New("github.attention.admitter has duplicate normalized repo keys") + } + seen[key] = true + if strings.TrimSpace(owner) == "" || strings.ContainsAny(owner, " \t\r\n") { + return errors.New("github.attention.admitter requires a nonempty hive ID") + } + } + return nil +} +func (c Config) Window() time.Duration { + if c.FlapWindow > 0 { + return c.FlapWindow + } + return DefaultFlapWindow +} + +func canonical(s string) string { return strings.ToLower(strings.TrimSpace(s)) } + +// Key excludes producer, SHA, run IDs and URLs. Subject must be a structured +// identity, not free prose. An action, owner or risk change changes this key. +type Key struct { + Repo string `json:"repo"` + Item int `json:"item"` + Action string `json:"action"` + Recipient string `json:"recipient"` + Subject string `json:"subject"` +} + +func (k Key) Hash() string { + b, _ := json.Marshal([]any{canonical(k.Repo), k.Item, canonical(k.Action), canonical(k.Recipient), k.Subject}) + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} + +// CISubject accepts a job name and an already classified error (not log text). +func CISubject(job, errorClass string) string { + b, _ := json.Marshal([]string{"ci", strings.Join(strings.Fields(job), " "), canonical(errorClass)}) + return string(b) +} +func FindingSubject(r findingidentity.Record) string { return findingidentity.Key(r) } +func DecisionSubject(id string) string { return "decision:" + strings.TrimSpace(id) } + +type State string + +const ( + Observed State = "observed" + Actionable State = "actionable" + Notified State = "notified" + Acknowledged State = "acknowledged" + Resolved State = "resolved" +) + +type Episode struct { + Key Key `json:"key"` + State State `json:"state"` + FirstSeen time.Time `json:"first_seen"` + LastSeen time.Time `json:"last_seen"` + PagedAt time.Time `json:"paged_at,omitempty"` + PagedTo string `json:"paged_to,omitempty"` + AckedAt time.Time `json:"acked_at,omitempty"` + SnoozedUntil time.Time `json:"snoozed_until,omitempty"` + ResolvedAt time.Time `json:"resolved_at,omitempty"` + Attempt string `json:"last_attempt,omitempty"` + AttemptOwner string `json:"attempt_owner,omitempty"` + Evidence string `json:"evidence,omitempty"` + Uncertain bool `json:"uncertain,omitempty"` + WouldNotify bool `json:"would_notify,omitempty"` + // Baseline is fail-quiet recovery: history must be reconciled, not replayed. + Baseline bool `json:"baseline,omitempty"` + QuietReopen bool `json:"quiet_reopen,omitempty"` +} + +func (e Episode) Marker() string { + return fmt.Sprintf("", e.Key.Hash(), e.Attempt) +} + +type Observation struct { + Key Key + Actionable bool + Resolved bool + Evidence string + Body string +} + +// Delivery is supplied by the existing write boundary. History returns the keys +// of trusted hive attention markers (evidence of a real POST, not status-card +// condition markers), with pagination. Find must reconcile this exact attempt, +// not content or another hive's attempt. +type Delivery interface { + History(context.Context, string, int) ([]string, error) + Find(context.Context, Episode) (bool, error) + Post(context.Context, Episode, string) error +} + +type disk struct { + Version int `json:"version"` + Items map[string]bool `json:"items"` + Episodes map[string]*Episode `json:"episodes"` +} +type Store struct { + mu sync.Mutex + path string + state disk + now func() time.Time +} + +// Open treats missing/corrupt state as recovery, never as permission to replay. +// Unknown versions are refused rather than clobbered during rolling upgrades. +func Open(path string) (*Store, error) { + s := &Store{path: path, now: time.Now, state: disk{Version: 1, Items: map[string]bool{}, Episodes: map[string]*Episode{}}} + if path == "" { + return s, nil + } + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return s, nil + } + if err != nil { + return nil, err + } + var d disk + if json.Unmarshal(b, &d) != nil { + return s, nil + } + if d.Version == 0 { + return s, nil + } + if d.Version != 1 { + return nil, fmt.Errorf("attention: unsupported ledger version %d", d.Version) + } + if d.Items == nil || d.Episodes == nil { + return s, nil + } + if len(d.Items) > MaxItems || len(d.Episodes) > MaxEpisodes { + return nil, errors.New("attention: ledger exceeds capacity") + } + for _, e := range d.Episodes { + if e == nil { + return s, nil + } + } + s.state = d + return s, nil +} + +// save uses fsync + rename, and errors fence every outbound POST. Memory may +// lead disk after a failed save, but no subsequent POST can bypass another save. +func (s *Store) save() error { + if s.path == "" { + return nil + } + b, err := json.Marshal(s.state) + if err != nil { + return err + } + if err = os.MkdirAll(filepath.Dir(s.path), 0700); err != nil { + return err + } + f, err := os.CreateTemp(filepath.Dir(s.path), ".attention-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + if _, err = f.Write(b); err != nil { + f.Close() + return err + } + if err = f.Sync(); err != nil { + f.Close() + return err + } + if err = f.Close(); err != nil { + return err + } + if err = os.Rename(f.Name(), s.path); err != nil { + return err + } + dir, err := os.Open(filepath.Dir(s.path)) + if err != nil { + return err + } + defer dir.Close() + return dir.Sync() +} + +// prune drops resolved episodes once recurrence would start a fresh episode +// anyway, so the capacity cap bounds live inventory rather than eventually +// refusing every report. Uncertain episodes stay until reconciled, and +// history-seeded hash-only baselines stay as the replay guard. +func (s *Store) prune(now time.Time, window time.Duration) { + for k, e := range s.state.Episodes { + if e.State == Resolved && !e.Uncertain && !e.ResolvedAt.IsZero() && now.Sub(e.ResolvedAt) > window { + delete(s.state.Episodes, k) + } + } +} + +// Report accepts the full current condition snapshot for one item. The first +// snapshot per item consults delivery history: a condition with a prior trusted +// attention marker is seeded as a baseline WITHOUT sending, while a condition +// that was never paged notifies immediately, ledger loss or not. +// Calls are serialized through the POST outcome, including concurrent producers. +// Non-admitters only record would-notify. No marker lookup grants ownership. +func (s *Store) Report(ctx context.Context, cfg Config, hiveID, repo string, item int, observations []Observation, d Delivery) ([]Episode, error) { + s.mu.Lock() + defer s.mu.Unlock() + if err := cfg.Validate(); err != nil { + return nil, err + } + owner := cfg.Owner(repo) + if owner == "" { + return nil, nil + } + if item <= 0 || d == nil { + return nil, errors.New("attention: item and delivery are required") + } + itemKey := fmt.Sprintf("%s#%d", canonical(repo), item) + for _, o := range observations { + if canonical(o.Key.Repo) != canonical(repo) || o.Key.Item != item || o.Key.Action == "" || o.Key.Recipient == "" || o.Key.Subject == "" || len(o.Key.Subject) > 2048 || len(o.Key.Recipient) > 256 || len(o.Key.Action) > 256 || len(o.Evidence) > 4096 { + return nil, errors.New("attention: incomplete, oversized or mismatched key") + } + } + now := s.now().UTC() + s.prune(now, cfg.Window()) + first := !s.state.Items[itemKey] + historical := map[string]bool{} + if first { + if len(s.state.Items) >= MaxItems { + return nil, errors.New("attention: item capacity reached; refusing replay-prone eviction") + } + keys, err := d.History(ctx, repo, item) + if err != nil { + return nil, err + } + for _, k := range keys { + historical[k] = true + if s.state.Episodes[k] == nil { + if len(s.state.Episodes) >= MaxEpisodes { + return nil, errors.New("attention: recovery capacity reached") + } + s.state.Episodes[k] = &Episode{State: Observed, FirstSeen: now, Baseline: true} + } + } + } + for _, o := range observations { + hash := o.Key.Hash() + e := s.state.Episodes[hash] + if e == nil { + if len(s.state.Episodes) >= MaxEpisodes { + return nil, errors.New("attention: episode capacity reached; refusing replay-prone eviction") + } + e = &Episode{Key: o.Key, State: Observed, FirstSeen: now, Baseline: historical[hash]} + s.state.Episodes[hash] = e + } else if e.State == Resolved && !o.Resolved { + if now.Sub(e.ResolvedAt) > cfg.Window() && !e.Uncertain { + e = &Episode{Key: o.Key, State: Observed, FirstSeen: now} + s.state.Episodes[hash] = e + } else { + e.State = Observed + e.QuietReopen = true + if !e.PagedAt.IsZero() { + e.State = Notified + } + if !e.AckedAt.IsZero() { + e.State = Acknowledged + } + } + e.ResolvedAt = time.Time{} + } + e.Key = o.Key + e.LastSeen = now + e.Evidence = o.Evidence + if o.Resolved { + e.State = Resolved + if e.ResolvedAt.IsZero() { + e.ResolvedAt = now + } + continue + } + if o.Actionable && e.State == Observed { + e.State = Actionable + } + // A flap reopens the same episode without clearing its delivery/ack history. + e.WouldNotify = o.Actionable && !e.QuietReopen && e.PagedAt.IsZero() && e.AckedAt.IsZero() && !now.Before(e.SnoozedUntil) + } + s.state.Items[itemKey] = true + if err := s.save(); err != nil { + return nil, err + } + for _, o := range observations { + e := s.state.Episodes[o.Key.Hash()] + if !e.WouldNotify || o.Resolved || e.Baseline || owner != hiveID || hiveID == "" { + continue + } + if e.Attempt != "" { + // Configuration handoff must not retry a previous admitter's uncertain POST. + if e.AttemptOwner != hiveID { + continue + } + found, err := d.Find(ctx, *e) + if err != nil { + return nil, err + } + if found { + e.PagedAt = now + e.PagedTo = e.Key.Recipient + e.State = Notified + e.Uncertain = false + e.WouldNotify = false + if err = s.save(); err != nil { + return nil, err + } + continue + } + } else { + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + return nil, err + } + e.Attempt = hex.EncodeToString(id[:]) + e.AttemptOwner = hiveID + } + e.Uncertain = true + if err := s.save(); err != nil { + return nil, err + } + if err := d.Post(ctx, *e, o.Body+"\n\n"+e.Marker()); err != nil { + return nil, err + } + e.PagedAt = now + e.PagedTo = e.Key.Recipient + e.State = Notified + e.Uncertain = false + e.WouldNotify = false + if err := s.save(); err != nil { + return nil, err + } + } + return s.snapshot(repo, item), nil +} +func (s *Store) snapshot(repo string, item int) []Episode { + out := []Episode{} + for _, e := range s.state.Episodes { + if canonical(e.Key.Repo) == canonical(repo) && e.Key.Item == item { + out = append(out, *e) + } + } + return out +} + +// Snapshot returns copies for status reconciliation, including uncertain POSTs. +func (s *Store) Snapshot(repo string, item int) []Episode { + s.mu.Lock() + defer s.mu.Unlock() + return s.snapshot(repo, item) +} + +// Update records acknowledgement/snooze/resolution only; it never changes a +// security or merge hold. An acknowledgement is explicitly not approval. +func (s *Store) Update(key Key, state State, snooze time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + e := s.state.Episodes[key.Hash()] + if e == nil { + return errors.New("attention: unknown episode") + } + switch state { + case Acknowledged: + if e.State == Resolved { + return errors.New("attention: cannot acknowledge a resolved episode") + } + e.State = state + if e.AckedAt.IsZero() { + e.AckedAt = s.now().UTC() + } + case Resolved: + e.State = state + if e.ResolvedAt.IsZero() { + e.ResolvedAt = s.now().UTC() + } + case "": + default: + return errors.New("attention: unsupported transition") + } + e.SnoozedUntil = snooze + return s.save() +} diff --git a/src/pkg/attention/episodes_test.go b/src/pkg/attention/episodes_test.go new file mode 100644 index 0000000000..35a4f10890 --- /dev/null +++ b/src/pkg/attention/episodes_test.go @@ -0,0 +1,318 @@ +package attention + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +type forge struct { + posts []Episode + landed map[string]bool + history []string + fail bool + finds int + findErr error + historyErr error +} + +func (f *forge) History(context.Context, string, int) ([]string, error) { + return f.history, f.historyErr +} +func (f *forge) Find(_ context.Context, e Episode) (bool, error) { + f.finds++ + return f.landed[e.Attempt], f.findErr +} +func (f *forge) Post(_ context.Context, e Episode, _ string) error { + f.posts = append(f.posts, e) + if f.landed == nil { + f.landed = map[string]bool{} + } + f.landed[e.Attempt] = true + if f.fail { + return errors.New("timeout after server accepted POST") + } + return nil +} + +var testConfig = Config{Admitter: map[string]string{"org/repo": "owner"}} + +func observation() Observation { + return Observation{Key: Key{Repo: "org/repo", Item: 1, Action: "repair-ci", Recipient: "maintainer", Subject: CISubject("required ARM64", "download-http2")}, Actionable: true, Evidence: "sha-1/run-1", Body: "Please repair the download"} +} +func openStore(t *testing.T, path string) *Store { + t.Helper() + s, err := Open(path) + if err != nil { + t.Fatal(err) + } + return s +} +func report(t *testing.T, s *Store, f *forge, owner string, obs ...Observation) []Episode { + t.Helper() + es, err := s.Report(context.Background(), testConfig, owner, "org/repo", 1, obs, f) + if err != nil { + t.Fatal(err) + } + return es +} +func TestAcrossProducersPushesAndRestart(t *testing.T) { + path := filepath.Join(t.TempDir(), "episodes.json") + s := openStore(t, path) + f := &forge{} + o := observation() + report(t, s, f, "owner", o) + for _, producer := range []string{"scanner", "runtime", "Actions"} { + o.Body = producer + " describes the same underlying failure differently" + o.Evidence = producer + "/new-sha/new-run" + report(t, s, f, "owner", o) + } + s = openStore(t, path) + es := report(t, s, f, "owner", o) + if len(f.posts) != 1 || len(es) != 1 || es[0].Evidence != o.Evidence || es[0].PagedTo != "maintainer" { + t.Fatalf("posts=%d episodes=%+v", len(f.posts), es) + } +} +func TestEmptyAndCorruptStateNeverReplay(t *testing.T) { + for _, corrupt := range []bool{false, true} { + t.Run(map[bool]string{false: "missing", true: "corrupt"}[corrupt], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "episodes.json") + if corrupt { + if err := os.WriteFile(path, []byte("truncated{"), 0600); err != nil { + t.Fatal(err) + } + } + s := openStore(t, path) + paged := observation() + paged.Key.Action = "urgent-security" + paged.Key.Subject = "new-rule:file:location" + f := &forge{history: []string{paged.Key.Hash()}} + o := observation() + es := report(t, s, f, "owner", o, paged) + report(t, s, f, "owner", o, paged) + if len(f.posts) != 1 || f.posts[0].Key != o.Key { + t.Fatalf("never-paged condition swallowed or history replayed: posts=%+v", f.posts) + } + for _, e := range es { + if e.Baseline != (e.Key == paged.Key) { + t.Fatalf("baseline marking wrong: %+v", e) + } + } + }) + } +} +func TestRecoveryRetainsMarkersNotInFirstInventory(t *testing.T) { + s := openStore(t, filepath.Join(t.TempDir(), "state")) + o := observation() + f := &forge{history: []string{o.Key.Hash()}} + report(t, s, f, "owner") + es := report(t, s, f, "owner", o) + if len(f.posts) != 0 || !es[0].Baseline { + t.Fatal("marker history replayed") + } +} +func TestFirstReportOfNewItemPagesOnce(t *testing.T) { + path := filepath.Join(t.TempDir(), "state") + s := openStore(t, path) + f := &forge{} + es := report(t, s, f, "owner", observation()) + if len(f.posts) != 1 || es[0].Baseline || es[0].State != Notified { + t.Fatalf("first inventory of a never-seen item was swallowed: %+v", es) + } + s = openStore(t, path) + report(t, s, f, "owner", observation()) + if len(f.posts) != 1 { + t.Fatal("restart replayed") + } +} +func TestResolvedEpisodesPrunedAfterWindow(t *testing.T) { + s := openStore(t, "") + f := &forge{} + now := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC) + s.now = func() time.Time { return now } + for i := 0; i < MaxEpisodes-1; i++ { + s.state.Episodes[fmt.Sprint(i)] = &Episode{State: Resolved, ResolvedAt: now.Add(-DefaultFlapWindow - time.Second)} + } + s.state.Episodes["uncertain"] = &Episode{State: Resolved, Uncertain: true, ResolvedAt: now.Add(-DefaultFlapWindow - time.Second)} + es := report(t, s, f, "owner", observation()) + if len(f.posts) != 1 || len(es) != 1 || len(s.state.Episodes) != 2 || s.state.Episodes["uncertain"] == nil { + t.Fatalf("pruning wrong: posts=%d episodes=%d", len(f.posts), len(s.state.Episodes)) + } + o := observation() + o.Resolved = true + report(t, s, f, "owner", o) + report(t, s, f, "owner") + if len(s.state.Episodes) != 2 { + t.Fatal("fresh resolution pruned inside window") + } + now = now.Add(DefaultFlapWindow + time.Second) + report(t, s, f, "owner") + if len(s.state.Episodes) != 1 { + t.Fatal("aged resolution retained") + } +} +func TestUncertainLandedPOSTReconcilesAfterRestart(t *testing.T) { + path := filepath.Join(t.TempDir(), "state") + s := openStore(t, path) + f := &forge{fail: true} + _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + if err == nil { + t.Fatal("expected timeout") + } + pending := s.Snapshot("org/repo", 1)[0] + if !pending.Uncertain || pending.Attempt == "" { + t.Fatal("attempt not durable") + } + s = openStore(t, path) + es := report(t, s, f, "owner", observation()) + if len(f.posts) != 1 || f.finds != 1 || es[0].Uncertain || es[0].State != Notified || es[0].Attempt != pending.Attempt { + t.Fatalf("reconciliation failed: %+v", es) + } +} +func TestUncertainAbsentRetryKeepsAttempt(t *testing.T) { + s := openStore(t, "") + f := &forge{fail: true} + _, _ = s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + f.landed = map[string]bool{} + f.fail = false + report(t, s, f, "owner", observation()) + if len(f.posts) != 2 || f.finds != 1 || f.posts[0].Attempt != f.posts[1].Attempt { + t.Fatal("retry minted another episode/attempt") + } +} +func TestFailedLookupNeverRetries(t *testing.T) { + s := openStore(t, "") + f := &forge{fail: true} + _, _ = s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + f.findErr = errors.New("GitHub unavailable") + _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + if err == nil || len(f.posts) != 1 { + t.Fatal("retried without successful reconciliation") + } +} +func TestFlappingAndGenuineRecurrence(t *testing.T) { + s := openStore(t, "") + f := &forge{} + now := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC) + s.now = func() time.Time { return now } + o := observation() + report(t, s, f, "owner", o) + first := f.posts[0].Attempt + o.Resolved = true + report(t, s, f, "owner", o) + now = now.Add(time.Hour) + o.Resolved = false + report(t, s, f, "owner", o) + o.Resolved = true + report(t, s, f, "owner", o) + if len(f.posts) != 1 { + t.Fatal("flap repaged") + } + now = now.Add(DefaultFlapWindow + time.Second) + o.Resolved = false + report(t, s, f, "owner", o) + if len(f.posts) != 2 || first == f.posts[1].Attempt { + t.Fatal("genuine recurrence did not start a new episode") + } +} +func TestNonAdmitterAndUnset(t *testing.T) { + s := openStore(t, "") + f := &forge{} + es := report(t, s, f, "other", observation()) + if len(f.posts) != 0 || len(es) != 1 || !es[0].WouldNotify { + t.Fatal("non-admitter posted or lost shadow decision") + } + _, err := s.Report(context.Background(), Config{}, "owner", "org/repo", 1, []Observation{observation()}, f) + if err != nil || len(f.posts) != 0 { + t.Fatal("unset admitter changed behavior") + } +} +func TestConcurrentProducers(t *testing.T) { + s := openStore(t, "") + f := &forge{} + var wg sync.WaitGroup + for i := 0; i < 12; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + if err != nil { + t.Error(err) + } + }() + } + wg.Wait() + if len(f.posts) != 1 { + t.Fatalf("posts=%d", len(f.posts)) + } +} +func TestAckAndSnoozeDoNotResetDelivery(t *testing.T) { + s := openStore(t, "") + f := &forge{} + o := observation() + o.Actionable = false + report(t, s, f, "owner", o) + if err := s.Update(o.Key, Acknowledged, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + o.Actionable = true + report(t, s, f, "owner", o) + if len(f.posts) != 0 || s.Snapshot("org/repo", 1)[0].State != Acknowledged { + t.Fatal("acknowledged request paged") + } +} +func TestCapacityFailsClosedAcrossRestart(t *testing.T) { + path := filepath.Join(t.TempDir(), "state") + s := openStore(t, path) + f := &forge{} + for i := 0; i < MaxEpisodes; i++ { + s.state.Episodes[string(rune(i))] = &Episode{State: Observed} + } + if err := s.save(); err != nil { + t.Fatal(err) + } + s = openStore(t, path) + _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + if err == nil || len(f.posts) != 0 || len(s.state.Episodes) != MaxEpisodes { + t.Fatal("capacity evicted delivery history") + } +} +func TestPersistenceFailureNeverPosts(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "state") + s := openStore(t, path) + f := &forge{} + report(t, s, f, "owner") // Creates the ledger file so it can be replaced below. + // A directory at the ledger destination makes atomic replacement fail. + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f) + if err == nil || len(f.posts) != 0 { + t.Fatal("posted without durable reservation") + } +} +func TestIdentityDimensions(t *testing.T) { + k := observation().Key + same := k + same.Repo = "ORG/REPO" + same.Recipient = "MAINTAINER" + if k.Hash() != same.Hash() { + t.Fatal("case changed identity") + } + for _, change := range []func(*Key){func(k *Key) { k.Recipient = "security-owner" }, func(k *Key) { k.Action = "new-decision" }, func(k *Key) { k.Subject = CISubject("required ARM64", "permission-denied") }} { + changed := k + change(&changed) + if changed.Hash() == k.Hash() { + t.Fatal("material change collapsed") + } + } +} diff --git a/src/pkg/attention/recovery_test.go b/src/pkg/attention/recovery_test.go new file mode 100644 index 0000000000..6cede3e40b --- /dev/null +++ b/src/pkg/attention/recovery_test.go @@ -0,0 +1,208 @@ +package attention + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +func TestOpenInvalidLedgers(t *testing.T) { + for _, body := range []string{ + `{"version":0,"items":{},"episodes":{}}`, + `{"version":1,"episodes":{}}`, + `{"version":1,"items":{}}`, + `{"version":1,"items":{},"episodes":{"key":null}}`, + } { + t.Run(body, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "state") + if err := os.WriteFile(path, []byte(body), 0600); err != nil { + t.Fatal(err) + } + s := openStore(t, path) + f := &forge{history: []string{observation().Key.Hash()}} + es := report(t, s, f, "owner", observation()) + if len(es) != 1 || !es[0].Baseline || len(f.posts) != 0 { + t.Fatalf("replayed invalid ledger: %+v", es) + } + }) + } + if _, err := Open(t.TempDir()); err == nil { + t.Fatal("accepted unreadable ledger directory") + } + for _, items := range []bool{true, false} { + d := disk{Version: 1, Items: map[string]bool{}, Episodes: map[string]*Episode{}} + for i := 0; i <= MaxEpisodes; i++ { + key := fmt.Sprint(i) + if items { + d.Items[key] = true + } else { + d.Episodes[key] = &Episode{} + } + } + b, err := json.Marshal(d) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "state") + if err := os.WriteFile(path, b, 0600); err != nil { + t.Fatal(err) + } + if _, err := Open(path); err == nil { + t.Fatal("accepted oversized ledger") + } + } +} + +func TestReportRejectsInvalidInput(t *testing.T) { + ctx := context.Background() + for _, mutate := range []func(*Observation){ + func(o *Observation) { o.Key.Repo = "other/repo" }, + func(o *Observation) { o.Key.Item = 2 }, + func(o *Observation) { o.Key.Action = "" }, + func(o *Observation) { o.Key.Recipient = "" }, + func(o *Observation) { o.Key.Subject = "" }, + } { + s := openStore(t, "") + o := observation() + mutate(&o) + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, []Observation{o}, &forge{}); err == nil { + t.Fatal("accepted invalid observation") + } + if len(s.state.Items) != 0 || len(s.state.Episodes) != 0 { + t.Fatal("invalid input mutated ledger") + } + } + s := openStore(t, "") + if _, err := s.Report(ctx, Config{FlapWindow: -1}, "owner", "org/repo", 1, nil, &forge{}); err == nil { + t.Fatal("accepted invalid config") + } + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 0, nil, &forge{}); err == nil { + t.Fatal("accepted invalid item") + } + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, nil, nil); err == nil { + t.Fatal("accepted nil delivery") + } +} + +func TestRecoveryFailuresFenceDelivery(t *testing.T) { + for _, mode := range []string{"history", "items", "recovery"} { + t.Run(mode, func(t *testing.T) { + s := openStore(t, "") + f := &forge{} + switch mode { + case "history": + f.historyErr = errors.New("history unavailable") + case "items": + for i := 0; i < MaxItems; i++ { + s.state.Items[fmt.Sprint(i)] = true + } + case "recovery": + for i := 0; i < MaxEpisodes; i++ { + s.state.Episodes[fmt.Sprint(i)] = &Episode{} + } + f.history = []string{observation().Key.Hash()} + } + if _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f); err == nil { + t.Fatal("accepted failed recovery") + } + if len(f.posts) != 0 || s.state.Items["org/repo#1"] { + t.Fatal("failed recovery allowed delivery or established baseline") + } + }) + } +} + +func TestSaveFailsOnInvalidTimeAndParent(t *testing.T) { + s := openStore(t, filepath.Join(t.TempDir(), "state")) + s.state.Episodes["invalid"] = &Episode{FirstSeen: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)} + if err := s.save(); err == nil { + t.Fatal("saved unencodable timestamp") + } + parent := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(parent, nil, 0600); err != nil { + t.Fatal(err) + } + s.path = filepath.Join(parent, "state") + s.state.Episodes = map[string]*Episode{} + if err := s.save(); err == nil { + t.Fatal("saved beneath a regular file") + } +} + +func TestUpdateTransitionsAndQuietAcknowledgedReopen(t *testing.T) { + s := openStore(t, "") + o := observation() + f := &forge{history: []string{o.Key.Hash()}} // Seeded baseline: no page, so ack/snooze transitions are exercised from actionable. + now := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC) + s.now = func() time.Time { return now } + if err := s.Update(o.Key, Acknowledged, time.Time{}); err == nil { + t.Fatal("updated unknown episode") + } + report(t, s, f, "owner", o) + if err := s.Update(o.Key, Notified, time.Time{}); err == nil { + t.Fatal("accepted unsupported transition") + } + snooze := now.Add(time.Hour) + if err := s.Update(o.Key, "", snooze); err != nil { + t.Fatal(err) + } + if got := s.Snapshot("org/repo", 1)[0]; !got.SnoozedUntil.Equal(snooze) || got.State != Actionable { + t.Fatalf("snooze changed state: %+v", got) + } + if err := s.Update(o.Key, Acknowledged, snooze); err != nil { + t.Fatal(err) + } + now = now.Add(time.Minute) + if err := s.Update(o.Key, Acknowledged, snooze); err != nil { + t.Fatal(err) + } + acked := s.Snapshot("org/repo", 1)[0].AckedAt + if acked.Equal(now) { + t.Fatal("duplicate acknowledgement reset timestamp") + } + if err := s.Update(o.Key, Resolved, time.Time{}); err != nil { + t.Fatal(err) + } + resolved := s.Snapshot("org/repo", 1)[0].ResolvedAt + now = now.Add(time.Minute) + if err := s.Update(o.Key, Resolved, time.Time{}); err != nil { + t.Fatal(err) + } + if !s.Snapshot("org/repo", 1)[0].ResolvedAt.Equal(resolved) { + t.Fatal("duplicate resolution reset timestamp") + } + if err := s.Update(o.Key, Acknowledged, time.Time{}); err == nil { + t.Fatal("acknowledged resolved episode") + } + es := report(t, s, f, "owner", o) + if es[0].State != Acknowledged || !es[0].QuietReopen || !es[0].AckedAt.Equal(acked) || len(f.posts) != 0 { + t.Fatalf("acknowledged flap lost history: %+v", es) + } +} + +func TestHandoffDoesNotRetryPreviousOwnersAttempt(t *testing.T) { + s := openStore(t, "") + f := &forge{fail: true} + if _, err := s.Report(context.Background(), testConfig, "owner", "org/repo", 1, []Observation{observation()}, f); err == nil { + t.Fatal("expected uncertain POST") + } + cfg := Config{Admitter: map[string]string{"org/repo": "replacement"}} + es, err := s.Report(context.Background(), cfg, "replacement", "org/repo", 1, []Observation{observation()}, f) + if err != nil { + t.Fatal(err) + } + if len(f.posts) != 1 || f.finds != 0 || !es[0].Uncertain || es[0].AttemptOwner != "owner" { + t.Fatalf("handoff retried old attempt: %+v", es) + } +} + +func TestDecisionSubjectTrimsIdentity(t *testing.T) { + if got := DecisionSubject(" decision-42 \n"); got != "decision:decision-42" { + t.Fatal(got) + } +} diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 7b455118c2..b2dd0232c1 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -22,6 +22,7 @@ import ( "testing" "time" + "github.com/hivecommons/hive/pkg/attention" "github.com/hivecommons/hive/pkg/authorkind" dashboardtheme "github.com/hivecommons/hive/pkg/dashboard/theme" "github.com/hivecommons/hive/pkg/ioscan" @@ -3595,6 +3596,8 @@ type GitHubConfig struct { // the author and every watcher; editing an existing comment does not. // See GitHubNotificationsConfig. Notifications GitHubNotificationsConfig `yaml:"notifications,omitempty" json:"notifications,omitempty"` + // Attention is an opt-in, single-admitter condition episode ledger. + Attention attention.Config `yaml:"attention,omitempty" json:"attention,omitempty"` // OAuthBaseURLOverride and OAuthAPIURLOverride redirect the DEVICE-FLOW LOGIN // endpoints away from public github.com. They are a TEST SEAM ONLY — see the // comment on OAuthBaseURL(). They carry the `-` yaml tag so they can never be diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index 5bb038a442..31797a5df0 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -436,6 +436,7 @@ "BaseURL": "", "AppAuthoredPRs": null, "AppSignedCommits": null, + "attention": {}, "notifications": {}, "OAuthBaseURLOverride": "", "OAuthAPIURLOverride": "" diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index ef95afbc59..048e2efcd8 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -137,6 +137,9 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.Governor.LiteLLM.Validate(); err != nil { return err } + if err := c.GitHub.Attention.Validate(); err != nil { + return err + } if err := c.Writeback.Validate(); err != nil { return err } diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 39a82c16c5..c10cc800ae 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -192,6 +192,7 @@ duplicate_sweep.bot_authors[] # TODO #11854 evidence.complexity.enabled # TODO #11854 evidence.complexity.static_analysis # TODO #11854 github.additional_bot_logins[] # TODO #11854 +github.attention # single-admitter ownership and flap window are YAML-only rollout controls; see src/docs/attention-episodes.md github.notifications.mode # quiet|normal PR notification mode; yaml-only, see operator-reference.md github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) diff --git a/src/pkg/github/attention.go b/src/pkg/github/attention.go new file mode 100644 index 0000000000..39cb083857 --- /dev/null +++ b/src/pkg/github/attention.go @@ -0,0 +1,152 @@ +package github + +import ( + "context" + "fmt" + "html" + "regexp" + "sort" + "strings" + + "github.com/hivecommons/hive/pkg/attention" + "github.com/hivecommons/hive/pkg/writeback" +) + +// SetAttention wires live opt-in ownership. Existing note/review/protocol paths +// deliberately do not infer condition identities from prose or change behavior. +func (c *Client) SetAttention(hiveID string, cfg func() attention.Config) { + if c == nil { + return + } + c.attentionHiveID = hiveID + c.attentionConfig = cfg +} + +// ReportAttention accepts a complete current condition inventory for an item. +// Producers must share structured subjects and action classes. Conditions with a +// prior trusted attention comment are seeded as a baseline without sending; a +// never-paged condition notifies on its first report. +// This path never bypasses writeback policy, including pause and repo mode off. +// Routing existing producers into this API is the separately opted-in pilot. +func (c *Client) ReportAttention(ctx context.Context, repo string, item writeback.Item, kind writeback.Kind, observations []attention.Observation) ([]attention.Episode, error) { + if c == nil { + return nil, ErrNoGitHubClient + } + if c.attentionConfig == nil { + return nil, nil + } + cfg := c.attentionConfig() + if cfg.Owner(repo) == "" { + return nil, nil + } + if d := c.WritebackAllowed(repo, item, kind, ""); !d.Allowed { + return nil, fmt.Errorf("%w: %s", writeback.ErrSuppressed, d.Reason) + } + store, err := c.WritebackGate().AttentionStore() + if err != nil { + return nil, err + } + episodes, reportErr := store.Report(ctx, cfg, c.attentionHiveID, repo, item.Number, observations, attentionDelivery{c: c, kind: kind, item: item}) + // Even failed POSTs must remain visible in the GitHub-native status card. + // Reload the snapshot on failure so uncertain attempts are not lost in UI. + if reportErr != nil { + episodes = store.Snapshot(repo, item.Number) + } + _, statusErr := c.UpsertPRStatusSection(ctx, repo, item.Number, "attention", attentionStatus(episodes)) + if reportErr != nil { + return episodes, reportErr + } + return episodes, statusErr +} + +type attentionDelivery struct { + c *Client + kind writeback.Kind + item writeback.Item +} + +// Only attention markers prove a delivery; status-card condition markers also +// cover non-admitter and never-paged episodes and must not seed baselines. +var attentionKeyMarker = regexp.MustCompile(``) + +func (d attentionDelivery) History(ctx context.Context, repo string, item int) ([]string, error) { + owner, name := d.c.splitRepo(repo) + comments, err := d.c.listIssueComments(ctx, owner, name, item) + if err != nil { + return nil, err + } + var keys []string + for _, cm := range comments { + if cm == nil || !(d.c.isHiveAccount(cm.GetUser()) || d.c.IsHiveAuthorLogin(cm.GetUser().GetLogin())) { + continue + } + for _, m := range attentionKeyMarker.FindAllStringSubmatch(cm.GetBody(), -1) { + keys = append(keys, m[1]) + } + } + return keys, nil +} +func (d attentionDelivery) Find(ctx context.Context, e attention.Episode) (bool, error) { + owner, name := d.c.splitRepo(e.Key.Repo) + comments, err := d.c.listIssueComments(ctx, owner, name, e.Key.Item) + if err != nil { + return false, err + } + for _, cm := range comments { + if cm != nil && (d.c.isHiveAccount(cm.GetUser()) || d.c.IsHiveAuthorLogin(cm.GetUser().GetLogin())) && strings.Contains(cm.GetBody(), e.Marker()) { + return true, nil + } + } + return false, nil +} +func (d attentionDelivery) Post(ctx context.Context, e attention.Episode, body string) error { + // Recheck the live policy immediately before the notifying write. + if decision := d.c.WritebackAllowed(e.Key.Repo, d.item, d.kind, ""); !decision.Allowed { + return fmt.Errorf("%w: %s", writeback.ErrSuppressed, decision.Reason) + } + if d.c.attentionConfig == nil || d.c.attentionConfig().Owner(e.Key.Repo) != d.c.attentionHiveID { + return writeback.ErrSuppressed + } + return d.c.CreateIssueComment(ctx, e.Key.Repo, e.Key.Item, body) // writeback:gated — live policy and admitter rechecked above +} +func attentionStatus(episodes []attention.Episode) string { + sort.Slice(episodes, func(i, j int) bool { return episodes[i].Key.Hash() < episodes[j].Key.Hash() }) + var b strings.Builder + active := 0 + for _, e := range episodes { + if e.State == attention.Resolved { + continue + } + active++ + if active > 20 { + continue + } + // Display the current owner/action without copied mentions or Markdown. + fmt.Fprintf(&b, "\n- `%s`: %s; %s → %s (since %s)", e.Key.Hash(), e.Key.Hash()[:12], e.State, statusText(e.Key.Action), statusText(e.Key.Recipient), e.FirstSeen.UTC().Format("2006-01-02T15:04Z")) + if !e.SnoozedUntil.IsZero() { + fmt.Fprintf(&b, "; snoozed until %s", e.SnoozedUntil.UTC().Format("2006-01-02T15:04Z")) + } + if e.Evidence != "" { + fmt.Fprintf(&b, "; evidence: %s", statusText(e.Evidence)) + } + if e.Baseline || e.Uncertain { + b.WriteString(" — uncertain; reconciliation required") + } + if e.WouldNotify { + b.WriteString(" — would notify") + } + b.WriteByte('\n') + } + if active > 20 { + fmt.Fprintf(&b, "\n%d further active episodes retained in the durable ledger.\n", active-20) + } + return b.String() +} + +func statusText(s string) string { + s = strings.Join(strings.Fields(s), " ") + if len(s) > 256 { + s = s[:256] + "…" + } + return strings.NewReplacer("@", "@", "`", "`", "[", "[", "]", "]", "!", "!", "*", "*", "_", "_").Replace(html.EscapeString(s)) +} diff --git a/src/pkg/github/attention_test.go b/src/pkg/github/attention_test.go new file mode 100644 index 0000000000..a8dce90e93 --- /dev/null +++ b/src/pkg/github/attention_test.go @@ -0,0 +1,130 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/attention" + "github.com/hivecommons/hive/pkg/writeback" +) + +func TestAttentionMarkerLookupPaginatesAndRequiresTrustedAuthor(t *testing.T) { + e := attention.Episode{Key: attention.Key{Repo: "o/r", Item: 5, Action: "repair", Recipient: "owner", Subject: "condition"}, Attempt: strings.Repeat("a", 32)} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + author := "untrusted" + if r.URL.Query().Get("page") == "2" { + author = "hive[bot]" + } else { + w.Header().Set("Link", "; rel=\"next\"") + } + _ = json.NewEncoder(w).Encode([]map[string]any{{"body": e.Marker(), "user": map[string]string{"login": author}}}) + })) + defer srv.Close() + c := testClient(t, srv.URL) + c.appBotLogin = "hive[bot]" + d := attentionDelivery{c: c} + found, err := d.Find(context.Background(), e) + if err != nil || !found { + t.Fatalf("found=%v err=%v", found, err) + } + keys, err := d.History(context.Background(), "o/r", 5) + if err != nil || len(keys) != 1 || keys[0] != e.Key.Hash() { + t.Fatalf("keys=%v err=%v", keys, err) + } +} + +func TestAttentionNonAdmitterOnlyFoldsStatus(t *testing.T) { + server := &statusCommentServer{} + srv := server.start(t) + c := testClient(t, srv.URL) + c.SetWritebackGate(writeback.New(writeback.Config{}, writeback.Deps{}, "")) + c.SetAttention("other-hive", func() attention.Config { return attention.Config{Admitter: map[string]string{"o/r": "owner-hive"}} }) + item := writeback.Item{Number: 5, HiveAuthored: true} + ctx := context.Background() + if _, err := c.ReportAttention(ctx, "o/r", item, writeback.KindSentinel, nil); err != nil { + t.Fatal(err) + } + o := attention.Observation{Key: attention.Key{Repo: "o/r", Item: 5, Action: "security-repair", Recipient: "@maintainer", Subject: "finding-identity/v1:new-risk"}, Actionable: true, Evidence: "new SHA", Body: "Please repair this finding"} + for i := 0; i < 3; i++ { + if _, err := c.ReportAttention(ctx, "o/r", item, writeback.KindSentinel, []attention.Observation{o}); err != nil { + t.Fatal(err) + } + } + if server.creates != 1 { + t.Fatalf("creates=%d, want only status card", server.creates) + } + for _, cm := range server.comments { + body, _ := cm["body"].(string) + if strings.Contains(body, "