From 2ccf4a9efa3b081465de30e55e79e5e66ca207be Mon Sep 17 00:00:00 2001 From: mendezr Date: Mon, 2 Nov 2026 19:20:53 +0000 Subject: [PATCH 01/13] =?UTF-8?q?=E2=9C=A8=20feature:=20persist=20single-a?= =?UTF-8?q?dmitter=20condition=20episodes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add opt-in per-repo attention ownership, durable producer-independent episodes, quiet baseline recovery, and exact-attempt reconciliation before uncertain POST retries. Keep existing writers, reviews, commands and holds unchanged for the separate pilot. Hive-Run: hivecommons/hive#16267 Hive-Plan: RFC-16075/phase-3-condition-episodes Hive-Spec: RFC-16075#2 Signed-off-by: mendezr --- changelog.d/added-condition-episodes.md | 1 + src/cmd/hive/github_client_config.go | 2 + src/docs/attention-episodes.md | 90 +++++ src/pkg/attention/config_test.go | 56 ++++ src/pkg/attention/episodes.go | 424 ++++++++++++++++++++++++ src/pkg/attention/episodes_test.go | 283 ++++++++++++++++ src/pkg/config/config.go | 3 + src/pkg/config/validate.go | 3 + src/pkg/github/attention.go | 149 +++++++++ src/pkg/github/attention_test.go | 130 ++++++++ src/pkg/github/client.go | 3 + src/pkg/writeback/gate.go | 23 +- 12 files changed, 1166 insertions(+), 1 deletion(-) create mode 100644 changelog.d/added-condition-episodes.md create mode 100644 src/docs/attention-episodes.md create mode 100644 src/pkg/attention/config_test.go create mode 100644 src/pkg/attention/episodes.go create mode 100644 src/pkg/attention/episodes_test.go create mode 100644 src/pkg/github/attention.go create mode 100644 src/pkg/github/attention_test.go 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..41cec2109d --- /dev/null +++ b/src/docs/attention-episodes.md @@ -0,0 +1,90 @@ +# 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. + +On missing/corrupt state, the first **complete inventory per item** is a recovery +baseline: list trusted Hive attention/status markers and seed current conditions +without sending. A successful empty inventory establishes a baseline too. 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. A subsequent genuinely +new condition can notify immediately. 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. Capacity errors +fail closed and retain history instead of evicting an active incident and +replaying it. Operators must reconcile/archive old resolved 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..a750ecdad9 --- /dev/null +++ b/src/pkg/attention/episodes.go @@ -0,0 +1,424 @@ +// 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 trusted +// hive marker keys (including 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() +} + +// Report accepts the full current condition snapshot for one item. The first +// snapshot after state loss seeds WITHOUT sending. A successful empty snapshot +// establishes a baseline so genuinely new risks can notify on the next report. +// 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") + } + } + baseline := !s.state.Items[itemKey] + historical := map[string]bool{} + if baseline { + 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: s.now().UTC(), Baseline: true} + } + } + } + now := s.now().UTC() + 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: 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..26873fd6aa --- /dev/null +++ b/src/pkg/attention/episodes_test.go @@ -0,0 +1,283 @@ +package attention + +import ( + "context" + "errors" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +type forge struct { + posts []Episode + landed map[string]bool + history []string + fail bool + finds int + findErr error +} + +func (f *forge) History(context.Context, string, int) ([]string, error) { return f.history, nil } +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{} + report(t, s, f, "owner") // Initial inventory is empty: establish recovery baseline. + 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) + f := &forge{} + o := observation() + es := report(t, s, f, "owner", o) + report(t, s, f, "owner", o) + if len(f.posts) != 0 || !es[0].Baseline { + t.Fatal("history replayed", es) + } + // A genuinely new urgent risk is independent of the baseline CI episode. + risk := o + risk.Key.Action = "urgent-security" + risk.Key.Subject = "new-rule:file:location" + report(t, s, f, "owner", o, risk) + if len(f.posts) != 1 || f.posts[0].Key.Action != "urgent-security" { + t.Fatal("new security risk suppressed") + } + }) + } +} +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 TestUncertainLandedPOSTReconcilesAfterRestart(t *testing.T) { + path := filepath.Join(t.TempDir(), "state") + s := openStore(t, path) + f := &forge{fail: true} + report(t, s, f, "owner") + _, 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} + report(t, s, f, "owner") + _, _ = 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} + report(t, s, f, "owner") + _, _ = 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 } + report(t, s, f, "owner") + 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{} + report(t, s, f, "other") + 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{} + report(t, s, f, "owner") + 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{} + report(t, s, f, "owner") + 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{} + report(t, s, f, "owner") + 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") + // 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/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/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/github/attention.go b/src/pkg/github/attention.go new file mode 100644 index 0000000000..0cbca48ba0 --- /dev/null +++ b/src/pkg/github/attention.go @@ -0,0 +1,149 @@ +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. Call with an empty +// inventory after recovery to establish a baseline before observing new risks. +// 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 +} + +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) +} +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, "`) +// 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) From e5e13a79ac8421d19f7ac348ea9c1ecbcf24d9ea Mon Sep 17 00:00:00 2001 From: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:56:08 -0500 Subject: [PATCH 05/13] =?UTF-8?q?=F0=9F=93=9D=20docs:=20link=20attention?= =?UTF-8?q?=20episodes=20page,=20separate=20top-level=20decls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/documentation-map.md | 1 + src/pkg/attention/config_test.go | 2 ++ src/pkg/attention/episodes.go | 5 +++++ src/pkg/attention/episodes_test.go | 19 +++++++++++++++++++ src/pkg/github/attention.go | 3 +++ src/pkg/github/attention_test.go | 4 ++++ 6 files changed, 34 insertions(+) diff --git a/src/docs/documentation-map.md b/src/docs/documentation-map.md index 891e87c3cc..9b6bc19869 100644 --- a/src/docs/documentation-map.md +++ b/src/docs/documentation-map.md @@ -105,6 +105,7 @@ Documentation for the current Hive line (branch `v5`; the code and docs live und - [Security notes](security.md) — log scrubbing and secret redaction guarantees/limits. - [Token collection and usage tracking](token-tracking.md) — session JSONL, `/api/cost`, and hub usage rollups. - [Notifications](notifications.md) — ntfy, Slack, and Discord alert channels, plus the two-way [Discord bot](../../discord/README.md). +- [Attention episodes](attention-episodes.md) — single-admitter condition episodes, flap window, and the `github.attention` rollout controls. - [State-triggered hooks](hooks.md) — declarative `transition → action` rules, the transition catalog, the vetted action set, and the security model (RFC #4001). - [CEL-based agent triggers](cel-triggers.md) — the `triggers:` config key: declarative CEL rules that kick an agent on a normalized source-control event, additive to built-in label/governor triggering, the `event.*` field reference, and the fail-closed compile/runtime contract. diff --git a/src/pkg/attention/config_test.go b/src/pkg/attention/config_test.go index ea22abaaf4..f2a2395696 100644 --- a/src/pkg/attention/config_test.go +++ b/src/pkg/attention/config_test.go @@ -30,6 +30,7 @@ func TestConfigValidation(t *testing.T) { 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) @@ -45,6 +46,7 @@ func TestFindingIdentityUsesExistingKey(t *testing.T) { 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 { diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go index 88f225f5cd..4719757ddb 100644 --- a/src/pkg/attention/episodes.go +++ b/src/pkg/attention/episodes.go @@ -38,6 +38,7 @@ func (c Config) Owner(repo string) string { } return "" } + func (c Config) Validate() error { if c.FlapWindow < 0 { return errors.New("github.attention.flap_window must not be negative") @@ -59,6 +60,7 @@ func (c Config) Validate() error { } return nil } + func (c Config) Window() time.Duration { if c.FlapWindow > 0 { return c.FlapWindow @@ -89,6 +91,7 @@ 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) } @@ -149,6 +152,7 @@ type disk struct { Items map[string]bool `json:"items"` Episodes map[string]*Episode `json:"episodes"` } + type Store struct { mu sync.Mutex path string @@ -390,6 +394,7 @@ func (s *Store) Report(ctx context.Context, cfg Config, hiveID, repo string, ite } return s.snapshot(repo, item), nil } + func (s *Store) snapshot(repo string, item int) []Episode { out := []Episode{} for _, e := range s.state.Episodes { diff --git a/src/pkg/attention/episodes_test.go b/src/pkg/attention/episodes_test.go index 35a4f10890..b6daa0c9ec 100644 --- a/src/pkg/attention/episodes_test.go +++ b/src/pkg/attention/episodes_test.go @@ -24,10 +24,12 @@ type forge struct { 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 { @@ -45,6 +47,7 @@ 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) @@ -53,6 +56,7 @@ func openStore(t *testing.T, path string) *Store { } 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) @@ -61,6 +65,7 @@ func report(t *testing.T, s *Store, f *forge, owner string, obs ...Observation) } return es } + func TestAcrossProducersPushesAndRestart(t *testing.T) { path := filepath.Join(t.TempDir(), "episodes.json") s := openStore(t, path) @@ -78,6 +83,7 @@ func TestAcrossProducersPushesAndRestart(t *testing.T) { 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) { @@ -106,6 +112,7 @@ func TestEmptyAndCorruptStateNeverReplay(t *testing.T) { }) } } + func TestRecoveryRetainsMarkersNotInFirstInventory(t *testing.T) { s := openStore(t, filepath.Join(t.TempDir(), "state")) o := observation() @@ -116,6 +123,7 @@ func TestRecoveryRetainsMarkersNotInFirstInventory(t *testing.T) { t.Fatal("marker history replayed") } } + func TestFirstReportOfNewItemPagesOnce(t *testing.T) { path := filepath.Join(t.TempDir(), "state") s := openStore(t, path) @@ -130,6 +138,7 @@ func TestFirstReportOfNewItemPagesOnce(t *testing.T) { t.Fatal("restart replayed") } } + func TestResolvedEpisodesPrunedAfterWindow(t *testing.T) { s := openStore(t, "") f := &forge{} @@ -156,6 +165,7 @@ func TestResolvedEpisodesPrunedAfterWindow(t *testing.T) { t.Fatal("aged resolution retained") } } + func TestUncertainLandedPOSTReconcilesAfterRestart(t *testing.T) { path := filepath.Join(t.TempDir(), "state") s := openStore(t, path) @@ -174,6 +184,7 @@ func TestUncertainLandedPOSTReconcilesAfterRestart(t *testing.T) { t.Fatalf("reconciliation failed: %+v", es) } } + func TestUncertainAbsentRetryKeepsAttempt(t *testing.T) { s := openStore(t, "") f := &forge{fail: true} @@ -185,6 +196,7 @@ func TestUncertainAbsentRetryKeepsAttempt(t *testing.T) { t.Fatal("retry minted another episode/attempt") } } + func TestFailedLookupNeverRetries(t *testing.T) { s := openStore(t, "") f := &forge{fail: true} @@ -195,6 +207,7 @@ func TestFailedLookupNeverRetries(t *testing.T) { t.Fatal("retried without successful reconciliation") } } + func TestFlappingAndGenuineRecurrence(t *testing.T) { s := openStore(t, "") f := &forge{} @@ -220,6 +233,7 @@ func TestFlappingAndGenuineRecurrence(t *testing.T) { t.Fatal("genuine recurrence did not start a new episode") } } + func TestNonAdmitterAndUnset(t *testing.T) { s := openStore(t, "") f := &forge{} @@ -232,6 +246,7 @@ func TestNonAdmitterAndUnset(t *testing.T) { t.Fatal("unset admitter changed behavior") } } + func TestConcurrentProducers(t *testing.T) { s := openStore(t, "") f := &forge{} @@ -251,6 +266,7 @@ func TestConcurrentProducers(t *testing.T) { t.Fatalf("posts=%d", len(f.posts)) } } + func TestAckAndSnoozeDoNotResetDelivery(t *testing.T) { s := openStore(t, "") f := &forge{} @@ -266,6 +282,7 @@ func TestAckAndSnoozeDoNotResetDelivery(t *testing.T) { t.Fatal("acknowledged request paged") } } + func TestCapacityFailsClosedAcrossRestart(t *testing.T) { path := filepath.Join(t.TempDir(), "state") s := openStore(t, path) @@ -282,6 +299,7 @@ func TestCapacityFailsClosedAcrossRestart(t *testing.T) { t.Fatal("capacity evicted delivery history") } } + func TestPersistenceFailureNeverPosts(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "state") @@ -300,6 +318,7 @@ func TestPersistenceFailureNeverPosts(t *testing.T) { t.Fatal("posted without durable reservation") } } + func TestIdentityDimensions(t *testing.T) { k := observation().Key same := k diff --git a/src/pkg/github/attention.go b/src/pkg/github/attention.go index 39cb083857..d0b2c432d3 100644 --- a/src/pkg/github/attention.go +++ b/src/pkg/github/attention.go @@ -86,6 +86,7 @@ func (d attentionDelivery) History(ctx context.Context, repo string, item int) ( } 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) @@ -99,6 +100,7 @@ func (d attentionDelivery) Find(ctx context.Context, e attention.Episode) (bool, } 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 { @@ -109,6 +111,7 @@ func (d attentionDelivery) Post(ctx context.Context, e attention.Episode, body s } 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 diff --git a/src/pkg/github/attention_test.go b/src/pkg/github/attention_test.go index a8dce90e93..ba1658dca8 100644 --- a/src/pkg/github/attention_test.go +++ b/src/pkg/github/attention_test.go @@ -65,6 +65,7 @@ func TestAttentionNonAdmitterOnlyFoldsStatus(t *testing.T) { } } } + func TestAttentionUnsetDoesNotWriteOrCreateLedger(t *testing.T) { server := &statusCommentServer{} srv := server.start(t) @@ -77,6 +78,7 @@ func TestAttentionUnsetDoesNotWriteOrCreateLedger(t *testing.T) { t.Fatal("unset admitter changed existing behavior") } } + func TestAttentionRespectsWritebackPause(t *testing.T) { server := &statusCommentServer{} srv := server.start(t) @@ -90,6 +92,7 @@ func TestAttentionRespectsWritebackPause(t *testing.T) { t.Fatal("paused repo received a comment") } } + func TestAttentionOwnerCreatesOneEventAcrossReports(t *testing.T) { server := &statusCommentServer{} srv := server.start(t) @@ -118,6 +121,7 @@ func TestAttentionOwnerCreatesOneEventAcrossReports(t *testing.T) { t.Fatalf("attention comments=%d", count) } } + func TestAttentionStatusBoundedAndMentionSafe(t *testing.T) { var episodes []attention.Episode for i := 0; i < 30; i++ { From f8254880ee2bb55f7f4fcb6db958670d095cb133 Mon Sep 17 00:00:00 2001 From: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:08:12 -0500 Subject: [PATCH 06/13] =?UTF-8?q?=F0=9F=90=9B=20fix:=20reconcile=20uncerta?= =?UTF-8?q?in=20resolved=20episodes,=20page=20first=20reopen,=20prune=20it?= =?UTF-8?q?ems?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hive-Fix-Attempt: 2/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/pkg/attention/episodes.go | 31 ++++++++++++++++++-- src/pkg/attention/recovery_test.go | 47 +++++++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go index 4719757ddb..7bf061391b 100644 --- a/src/pkg/attention/episodes.go +++ b/src/pkg/attention/episodes.go @@ -241,7 +241,7 @@ func (s *Store) save() error { // 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 +// refusing every report. Uncertain episodes stay until reconciled, items drop once they have no episodes, 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 { @@ -249,6 +249,16 @@ func (s *Store) prune(now time.Time, window time.Duration) { delete(s.state.Episodes, k) } } + live := map[string]bool{} + for _, e := range s.state.Episodes { + live[fmt.Sprintf("%s#%d", canonical(e.Key.Repo), e.Key.Item)] = true + } + // Re-seeding a dropped item through History on its next report is replay-safe. + for k := range s.state.Items { + if !live[k] { + delete(s.state.Items, k) + } + } } // Report accepts the full current condition snapshot for one item. The first @@ -313,8 +323,8 @@ func (s *Store) Report(ctx context.Context, cfg Config, hiveID, repo string, ite s.state.Episodes[hash] = e } else { e.State = Observed - e.QuietReopen = true if !e.PagedAt.IsZero() { + e.QuietReopen = true e.State = Notified } if !e.AckedAt.IsZero() { @@ -345,6 +355,23 @@ func (s *Store) Report(ctx context.Context, cfg Config, hiveID, repo string, ite } for _, o := range observations { e := s.state.Episodes[o.Key.Hash()] + if o.Resolved && e.Uncertain && e.Attempt != "" && owner == hiveID && hiveID != "" { + // Reconcile an uncertain POST once its condition resolved so the episode can be pruned. + found, err := d.Find(ctx, *e) + if err != nil { + return nil, err + } + if found { + e.PagedAt = now + e.PagedTo = e.Key.Recipient + } + e.Uncertain = false + e.WouldNotify = false + if err = s.save(); err != nil { + return nil, err + } + continue + } if !e.WouldNotify || o.Resolved || e.Baseline || owner != hiveID || hiveID == "" { continue } diff --git a/src/pkg/attention/recovery_test.go b/src/pkg/attention/recovery_test.go index 6cede3e40b..aeb49c77c6 100644 --- a/src/pkg/attention/recovery_test.go +++ b/src/pkg/attention/recovery_test.go @@ -99,7 +99,8 @@ func TestRecoveryFailuresFenceDelivery(t *testing.T) { f.historyErr = errors.New("history unavailable") case "items": for i := 0; i < MaxItems; i++ { - s.state.Items[fmt.Sprint(i)] = true + s.state.Items[fmt.Sprintf("org/other#%d", i+1)] = true + s.state.Episodes[fmt.Sprint(i)] = &Episode{Key: Key{Repo: "org/other", Item: i + 1}} } case "recovery": for i := 0; i < MaxEpisodes; i++ { @@ -206,3 +207,47 @@ func TestDecisionSubjectTrimsIdentity(t *testing.T) { t.Fatal(got) } } + +func TestUncertainResolvedEpisodeReconcilesAndPrunes(t *testing.T) { + s := openStore(t, "") + f := &forge{fail: true} + ctx := context.Background() + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, []Observation{observation()}, f); err == nil { + t.Fatal("expected uncertain POST") + } + o := observation() + o.Resolved = true + es, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, []Observation{o}, f) + if err != nil { + t.Fatal(err) + } + if f.finds != 1 || es[0].Uncertain || es[0].PagedAt.IsZero() { + t.Fatalf("uncertain POST not reconciled on resolve: %+v", es) + } + s.now = func() time.Time { return time.Now().Add(2 * testConfig.Window()) } + s.prune(s.now().UTC(), testConfig.Window()) + if len(s.state.Episodes) != 0 || len(s.state.Items) != 0 { + t.Fatal("resolved episode and item not pruned") + } +} + +func TestFirstActionableReopenOfNeverPagedEpisodePages(t *testing.T) { + s := openStore(t, "") + f := &forge{} + ctx := context.Background() + o := observation() + o.Actionable = false + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, []Observation{o}, f); err != nil { + t.Fatal(err) + } + o.Resolved = true + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, []Observation{o}, f); err != nil { + t.Fatal(err) + } + if _, err := s.Report(ctx, testConfig, "owner", "org/repo", 1, []Observation{observation()}, f); err != nil { + t.Fatal(err) + } + if len(f.posts) != 1 { + t.Fatalf("never-paged reopen not paged: %d", len(f.posts)) + } +} From eebe6ed25d97fa1b9ccdf270b7ef121cb0d76ef1 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:08:54 -0500 Subject: [PATCH 07/13] =?UTF-8?q?=F0=9F=8C=B1=20chore(writeback):=20annota?= =?UTF-8?q?te=20status-comment=20forge=20plumbing=20for=20the=20direct-wri?= =?UTF-8?q?te=20ratchet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merging v5 (#16319, #16321) moved the hive status comment's edit/create/ delete into prstatus.Forge adapters in automerge_stage_labels.go and pr_status_comment.go without updating the write-back ratchet, so TestDirectWriteRatchet failed on every PR's merge commit. Mark the forge adapter calls writeback:gated — they are plumbing under prstatus.Write and the write-back decision lives at the ratcheted entry points — and lower the automerge_stage_labels.go baseline now that the old in-place edit is gone. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/pkg/github/automerge/automerge_stage_labels.go | 11 +++++++---- src/pkg/github/pr_status_comment.go | 12 ++++++++---- .../writeback/testdata/direct-writes-baseline.txt | 2 +- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index a4b5f3be5f..083918958d 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -1499,7 +1499,10 @@ func (c *Engine) writeStatusSection(ctx context.Context, owner, repo string, num } // engineStatusForge adapts the engine's comment calls on one PR to -// prstatus.Forge. +// prstatus.Forge. It is plumbing under prstatus.Write, reached only from +// postStageNote: the write-back decision for a stage note is made (and +// ratcheted) at that entry point, and the forge's edit/delete touch only the +// hive's own status comment, so its calls carry writeback:gated. type engineStatusForge struct { e *Engine owner string @@ -1524,19 +1527,19 @@ func (f *engineStatusForge) ListComments(ctx context.Context) ([]prstatus.Commen } func (f *engineStatusForge) EditComment(ctx context.Context, id int64, body string) error { - if _, _, err := f.e.gh.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + if _, _, err := f.e.gh.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated return fmt.Errorf("editing hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } return nil } func (f *engineStatusForge) CreateComment(ctx context.Context, body string) error { - _, _, err := f.e.gh.Issues.CreateComment(ctx, f.owner, f.repo, f.number, &gh.IssueComment{Body: gh.Ptr(body)}) + _, _, err := f.e.gh.Issues.CreateComment(ctx, f.owner, f.repo, f.number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated return err } func (f *engineStatusForge) DeleteComment(ctx context.Context, id int64) error { - if _, err := f.e.gh.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { + if _, err := f.e.gh.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { // writeback:gated return fmt.Errorf("deleting hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } return nil diff --git a/src/pkg/github/pr_status_comment.go b/src/pkg/github/pr_status_comment.go index e5e3e8f188..c047704a61 100644 --- a/src/pkg/github/pr_status_comment.go +++ b/src/pkg/github/pr_status_comment.go @@ -31,7 +31,11 @@ func (c *Client) UpsertPRStatusSection(ctx context.Context, repo string, number // clientStatusForge adapts the client's comment calls on one item to // prstatus.Forge. Creates go through CreateIssueComment (canary gate, -// effects journal, created tally); edits are tallied as edited. +// effects journal, created tally); edits are tallied as edited. It is +// plumbing under prstatus.Write, reached only from UpsertPRStatusSection: +// the write-back decision belongs to that entry point's callers, and the +// forge's edit/delete touch only the hive's own status comment, so its +// calls carry writeback:gated. type clientStatusForge struct { c *Client owner string @@ -55,7 +59,7 @@ func (f *clientStatusForge) ListComments(ctx context.Context) ([]prstatus.Commen } func (f *clientStatusForge) EditComment(ctx context.Context, id int64, body string) error { - if _, _, err := f.c.client.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { + if _, _, err := f.c.client.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated return fmt.Errorf("editing hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } f.c.noteCommentEdited() @@ -63,11 +67,11 @@ func (f *clientStatusForge) EditComment(ctx context.Context, id int64, body stri } func (f *clientStatusForge) CreateComment(ctx context.Context, body string) error { - return f.c.CreateIssueComment(ctx, f.owner+"/"+f.repo, f.number, body) + return f.c.CreateIssueComment(ctx, f.owner+"/"+f.repo, f.number, body) // writeback:gated } func (f *clientStatusForge) DeleteComment(ctx context.Context, id int64) error { - if _, err := f.c.client.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { + if _, err := f.c.client.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { // writeback:gated return fmt.Errorf("deleting hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } return nil diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 670a7f79ba..e6a08e41d3 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -15,7 +15,7 @@ raw pkg/github/automerge/automerge_held_runs.go 3 raw pkg/github/automerge/automerge_merge_commit.go 1 raw pkg/github/automerge/automerge_merge_forward.go 1 raw pkg/github/automerge/automerge_stage_human.go 1 -raw pkg/github/automerge/automerge_stage_labels.go 3 +raw pkg/github/automerge/automerge_stage_labels.go 2 raw pkg/github/automerge/automerge_sweep_queued.go 3 raw pkg/github/automerge/automerge_sweep_trusted.go 4 raw pkg/github/automerge/automerge_unauthorized.go 3 From 642e5262c04c4d4a25e5e351096d8954d7712b6d Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:13:46 -0500 Subject: [PATCH 08/13] =?UTF-8?q?=F0=9F=8C=B1=20chore(notifications):=20in?= =?UTF-8?q?ventory=20attentionDelivery.Post=20and=20the=20status-comment?= =?UTF-8?q?=20forge=20create?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestNotificationWriteSitesInventory (v5, #16321) flags two untagged notification-capable writes on this branch's merge commit: attentionDelivery.Post, this PR's condition-episode page (attention), and clientStatusForge.CreateComment from #16319's status writer (status, passthrough to its caller). Tag both and mirror the rows in src/docs/notifications.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/notifications.md | 2 ++ src/pkg/github/notification_write_sites.go | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/docs/notifications.md b/src/docs/notifications.md index c611aec27c..81cf14d1be 100644 --- a/src/docs/notifications.md +++ b/src/docs/notifications.md @@ -414,6 +414,7 @@ without a class. Review submissions and review requests are always counted as | `github.(*Client).PostNoteOrFold` | `status` | passthrough wrapper; attributed to its caller | | `github.(*Client).SweepLegacyFleetReportIssues` | `status` | | | `github.(*Client).UpsertIssueMarkerComment` | `status` | passthrough wrapper; attributed to its caller | +| `github.(*clientStatusForge).CreateComment` | `status` | passthrough wrapper (status-comment forge under `prstatus.Write`); attributed to its caller | | `github.(*Client).closeDecomposedParent` | `status` | | | `github.(*Client).closeIssueForMergedPRClaimWithIssue` | `status` | | | `github.(*Client).closeSupersededPRDecision` | `status` | | @@ -448,6 +449,7 @@ without a class. Review submissions and review requests are always counted as | `github.(*Client).parkClankerRequestedPR` | `attention` | | | `github.(*Client).redirectToExistingPR` | `attention` | | | `github.(*Client).resolveDuplicateFixGroup` | `attention` | | +| `github.attentionDelivery.Post` | `attention` | condition-episode page; live write-back policy rechecked before the write | | `main.(*repoForgeRouter).CreateIssueComment` | `attention` | passthrough wrapper; attributed to its caller | | `main.claimEscalationLookup` | `attention` | | | `main.liveTriageCommenter.CreateIssueComment` | `attention` | passthrough wrapper; attributed to its caller | diff --git a/src/pkg/github/notification_write_sites.go b/src/pkg/github/notification_write_sites.go index b764528475..5cee988c5b 100644 --- a/src/pkg/github/notification_write_sites.go +++ b/src/pkg/github/notification_write_sites.go @@ -27,6 +27,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "main.(*repoForgeRouter).CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "main.liveTriageCommenter.CreateIssueComment": {Class: NotificationClassAttention, Passthrough: true}, "github.(*Client).UpsertIssueMarkerComment": {Class: NotificationClassStatus, Passthrough: true}, + "github.(*clientStatusForge).CreateComment": {Class: NotificationClassStatus, Passthrough: true}, // status: bookkeeping readable on demand. "dashboard.(*ContributeWSHub).markAlreadyDoneIssue": {Class: NotificationClassStatus}, @@ -81,6 +82,7 @@ var notificationWriteSites = map[string]NotificationWriteSite{ "github.(*Client).parkClankerRequestedPR": {Class: NotificationClassAttention}, "github.(*Client).redirectToExistingPR": {Class: NotificationClassAttention}, "github.(*Client).resolveDuplicateFixGroup": {Class: NotificationClassAttention}, + "github.attentionDelivery.Post": {Class: NotificationClassAttention}, "main.claimEscalationLookup": {Class: NotificationClassAttention}, "main.maintainHeldPRMergeability": {Class: NotificationClassAttention}, "main.rfcCoverageForge.CreateComment": {Class: NotificationClassAttention}, From e1aef497106755afd72ec1d9fed24159e304b36a Mon Sep 17 00:00:00 2001 From: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:24:53 -0500 Subject: [PATCH 09/13] fix(attention): mark acknowledged reopen quiet Hive-Fix-Attempt: 3/6 Signed-off-by: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/pkg/attention/episodes.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go index 7bf061391b..109e1bec2e 100644 --- a/src/pkg/attention/episodes.go +++ b/src/pkg/attention/episodes.go @@ -328,6 +328,7 @@ func (s *Store) Report(ctx context.Context, cfg Config, hiveID, repo string, ite e.State = Notified } if !e.AckedAt.IsZero() { + e.QuietReopen = true e.State = Acknowledged } } From 1b2a63187b895d921febbfc61a43781aae62691b Mon Sep 17 00:00:00 2001 From: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:18:27 -0500 Subject: [PATCH 10/13] =?UTF-8?q?=F0=9F=90=9B=20fix:=20expire=20stale=20hi?= =?UTF-8?q?story=20baselines=20and=20report=20status-comment=20writes=20as?= =?UTF-8?q?=20ungated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hive-Fix-Attempt: 4/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: architect <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/pkg/attention/episodes.go | 5 ++++- src/pkg/github/automerge/automerge_stage_labels.go | 11 ++++------- src/pkg/github/pr_status_comment.go | 12 ++++-------- .../writeback/testdata/direct-writes-baseline.txt | 2 +- 4 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/pkg/attention/episodes.go b/src/pkg/attention/episodes.go index 109e1bec2e..46b9a23e36 100644 --- a/src/pkg/attention/episodes.go +++ b/src/pkg/attention/episodes.go @@ -242,11 +242,14 @@ func (s *Store) save() error { // 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, items drop once they have no episodes, and -// history-seeded hash-only baselines stay as the replay guard. +// history-seeded hash-only baselines (no Key, never observed) are dropped once +// the window has passed, when a recurrence would start a fresh episode anyway. 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) + } else if e.Baseline && e.State == Observed && e.Key == (Key{}) && now.Sub(e.FirstSeen) > window { + delete(s.state.Episodes, k) } } live := map[string]bool{} diff --git a/src/pkg/github/automerge/automerge_stage_labels.go b/src/pkg/github/automerge/automerge_stage_labels.go index 083918958d..a4b5f3be5f 100644 --- a/src/pkg/github/automerge/automerge_stage_labels.go +++ b/src/pkg/github/automerge/automerge_stage_labels.go @@ -1499,10 +1499,7 @@ func (c *Engine) writeStatusSection(ctx context.Context, owner, repo string, num } // engineStatusForge adapts the engine's comment calls on one PR to -// prstatus.Forge. It is plumbing under prstatus.Write, reached only from -// postStageNote: the write-back decision for a stage note is made (and -// ratcheted) at that entry point, and the forge's edit/delete touch only the -// hive's own status comment, so its calls carry writeback:gated. +// prstatus.Forge. type engineStatusForge struct { e *Engine owner string @@ -1527,19 +1524,19 @@ func (f *engineStatusForge) ListComments(ctx context.Context) ([]prstatus.Commen } func (f *engineStatusForge) EditComment(ctx context.Context, id int64, body string) error { - if _, _, err := f.e.gh.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + if _, _, err := f.e.gh.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { return fmt.Errorf("editing hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } return nil } func (f *engineStatusForge) CreateComment(ctx context.Context, body string) error { - _, _, err := f.e.gh.Issues.CreateComment(ctx, f.owner, f.repo, f.number, &gh.IssueComment{Body: gh.Ptr(body)}) // writeback:gated + _, _, err := f.e.gh.Issues.CreateComment(ctx, f.owner, f.repo, f.number, &gh.IssueComment{Body: gh.Ptr(body)}) return err } func (f *engineStatusForge) DeleteComment(ctx context.Context, id int64) error { - if _, err := f.e.gh.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { // writeback:gated + if _, err := f.e.gh.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { return fmt.Errorf("deleting hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } return nil diff --git a/src/pkg/github/pr_status_comment.go b/src/pkg/github/pr_status_comment.go index c047704a61..e5e3e8f188 100644 --- a/src/pkg/github/pr_status_comment.go +++ b/src/pkg/github/pr_status_comment.go @@ -31,11 +31,7 @@ func (c *Client) UpsertPRStatusSection(ctx context.Context, repo string, number // clientStatusForge adapts the client's comment calls on one item to // prstatus.Forge. Creates go through CreateIssueComment (canary gate, -// effects journal, created tally); edits are tallied as edited. It is -// plumbing under prstatus.Write, reached only from UpsertPRStatusSection: -// the write-back decision belongs to that entry point's callers, and the -// forge's edit/delete touch only the hive's own status comment, so its -// calls carry writeback:gated. +// effects journal, created tally); edits are tallied as edited. type clientStatusForge struct { c *Client owner string @@ -59,7 +55,7 @@ func (f *clientStatusForge) ListComments(ctx context.Context) ([]prstatus.Commen } func (f *clientStatusForge) EditComment(ctx context.Context, id int64, body string) error { - if _, _, err := f.c.client.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { // writeback:gated + if _, _, err := f.c.client.Issues.EditComment(ctx, f.owner, f.repo, id, &gh.IssueComment{Body: gh.Ptr(body)}); err != nil { return fmt.Errorf("editing hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } f.c.noteCommentEdited() @@ -67,11 +63,11 @@ func (f *clientStatusForge) EditComment(ctx context.Context, id int64, body stri } func (f *clientStatusForge) CreateComment(ctx context.Context, body string) error { - return f.c.CreateIssueComment(ctx, f.owner+"/"+f.repo, f.number, body) // writeback:gated + return f.c.CreateIssueComment(ctx, f.owner+"/"+f.repo, f.number, body) } func (f *clientStatusForge) DeleteComment(ctx context.Context, id int64) error { - if _, err := f.c.client.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { // writeback:gated + if _, err := f.c.client.Issues.DeleteComment(ctx, f.owner, f.repo, id); err != nil { return fmt.Errorf("deleting hive status comment on %s/%s#%d: %w", f.owner, f.repo, f.number, err) } return nil diff --git a/src/pkg/writeback/testdata/direct-writes-baseline.txt b/src/pkg/writeback/testdata/direct-writes-baseline.txt index 6f2d6ff7d9..fd121804ef 100644 --- a/src/pkg/writeback/testdata/direct-writes-baseline.txt +++ b/src/pkg/writeback/testdata/direct-writes-baseline.txt @@ -15,7 +15,7 @@ raw pkg/github/automerge/automerge_held_runs.go 3 raw pkg/github/automerge/automerge_merge_commit.go 1 raw pkg/github/automerge/automerge_merge_forward.go 1 raw pkg/github/automerge/automerge_stage_human.go 1 -raw pkg/github/automerge/automerge_stage_labels.go 2 +raw pkg/github/automerge/automerge_stage_labels.go 5 raw pkg/github/automerge/automerge_sweep_queued.go 3 raw pkg/github/automerge/automerge_sweep_trusted.go 4 raw pkg/github/automerge/automerge_unauthorized.go 3 From 53e73679f67e56473628b4ed6ee661381539333b Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:19:55 -0500 Subject: [PATCH 11/13] =?UTF-8?q?=F0=9F=93=96=20docs:=20list=20attention-e?= =?UTF-8?q?pisodes.md=20in=20the=20documentation=20map=20and=20docs=20READ?= =?UTF-8?q?ME?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #16330 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/docs/README.md b/src/docs/README.md index 4b873d0413..4f2c046d60 100644 --- a/src/docs/README.md +++ b/src/docs/README.md @@ -56,6 +56,7 @@ A terminal agent is a power tool: you hold it, aim it, and it stops when you sto - [Integrations](integrations.md) — backends, trackers, forges and sandboxes Hive works with, at a glance. - [Getting started](getting-started.md) - [Operator reference](operator-reference.md) +- [Attention episodes](attention-episodes.md) — single-admitter condition episodes, flap window, and the `github.attention` rollout controls. - [GitHub webhooks: cadence, patch and reconcile](webhooks.md) — polling fallback, webhook patch and reconcile, and the state-accuracy guarantees. - [Dashboard sections explained](dashboard-sections.md) — what each dashboard section shows and what to do about it. - [Activity monitor copy inventory](dashboard-copy-inventory.md) — every operator-visible string builder in the activity monitor, with before/after word counts and the hover budget. From 1d4c0bee8bc9b25f9013c2bdd6bdfc4b0df07855 Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:19:56 -0500 Subject: [PATCH 12/13] =?UTF-8?q?=F0=9F=8C=B1=20chore(settingsparity):=20c?= =?UTF-8?q?ollect=20pkg/attention=20so=20github.attention=20leaves=20are?= =?UTF-8?q?=20enumerated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #16331 Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/internal/settingsparity/settingsparity.go | 1 + .../settingsparity/settingsparity_test.go | 21 +++++++++++++++++++ .../dashboard/settings_parity_allowlist.txt | 3 ++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/internal/settingsparity/settingsparity.go b/src/internal/settingsparity/settingsparity.go index 2fde9da793..e10dd84e96 100644 --- a/src/internal/settingsparity/settingsparity.go +++ b/src/internal/settingsparity/settingsparity.go @@ -50,6 +50,7 @@ func ConfigLeaves(repoRoot string) ([]Leaf, error) { filepath.Join("crux", "config"), filepath.Join("pkg", "dashboard", "theme"), filepath.Join("pkg", "writeback"), + filepath.Join("pkg", "attention"), } { if err := c.collect(fset, repoRoot, rel); err != nil { return nil, err diff --git a/src/internal/settingsparity/settingsparity_test.go b/src/internal/settingsparity/settingsparity_test.go index 7e9a7fd158..17780e153c 100644 --- a/src/internal/settingsparity/settingsparity_test.go +++ b/src/internal/settingsparity/settingsparity_test.go @@ -159,6 +159,27 @@ func TestConfigLeavesRealRepo(t *testing.T) { } } +// github.attention is typed attention.Config (pkg/attention); its sub-keys +// must be enumerated rather than collapsing into one opaque leaf. +func TestConfigLeavesRealRepoEnumeratesAttention(t *testing.T) { + leaves, err := ConfigLeaves(filepath.Join("..", "..", "..")) + if err != nil { + t.Fatalf("ConfigLeaves on the real repo: %v", err) + } + got := map[string]bool{} + for _, leaf := range leaves { + got[leaf.Path] = true + } + for _, want := range []string{"github.attention.admitter.", "github.attention.flap_window"} { + if !got[want] { + t.Errorf("leaf %q must be enumerated", want) + } + } + if got["github.attention"] { + t.Error("github.attention must not be an opaque leaf") + } +} + func TestAllowlist(t *testing.T) { path := filepath.Join(t.TempDir(), "allow.txt") writeFile(t, path, "# header comment\n\n a.b \nc.d # why it is allowed\n") diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index c10cc800ae..14a946f391 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -192,7 +192,8 @@ 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.attention.admitter. # single-admitter ownership and flap window are YAML-only rollout controls; see src/docs/attention-episodes.md +github.attention.flap_window # 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) From f95df3d602ddd412562f8ca61403d02eaa82632d Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:24:49 -0500 Subject: [PATCH 13/13] =?UTF-8?q?=F0=9F=8C=B1=20chore:=20retrigger=20CI=20?= =?UTF-8?q?after=20transient=20npm=20registry=20outage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit build/docker jobs failed in the Dockerfile cline install step with "No matching version found for @ai-sdk/openai@4.0.108"; the version is present on the registry, so this was a transient fetch failure. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com>