diff --git a/changelog.d/added-15951-hub-activity-api.md b/changelog.d/added-15951-hub-activity-api.md new file mode 100644 index 0000000000..e406c92d7b --- /dev/null +++ b/changelog.d/added-15951-hub-activity-api.md @@ -0,0 +1 @@ +- Spokes can attach a bounded, read-only activity digest to their hub heartbeat, and the hub serves it per user and per hive on `GET /api/hub/activity` with ETag polling: 100 items by default under a hard 250-item server-side ceiling, private-repository items excluded unless the spoke opts in (always counted in totals), truncation and stale, not-reporting or missing hives disclosed, and digests kept in hub memory only. Nothing populates the digest yet and no rollout or participation setting changes ([#15951](https://github.com/hivecommons/hive/issues/15951), RFC [#15861](https://github.com/hivecommons/hive/issues/15861)). diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 27e15153fd..1d60681c1b 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -33,34 +33,35 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/hub/clusters` | Hub auth | List Clusters | `pkg/hub/saas.go:531` | | `GET` | `/api/hub/image-pulls` | Hub auth | Per-Release Image Pull Series | `pkg/hub/saas.go:377` | | `GET` | `/api/reach` | Hub admin | PR Reach Report (?pr=NNN or ?recent=K) | `pkg/hub/saas.go:522` | -| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1769` | -| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1770` | -| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1707` | -| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1708` | -| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1709` | -| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat | `pkg/hub/server.go:1710` | -| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1711` | -| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1719` | -| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1720` | -| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1721` | -| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1722` | +| `GET` | `/fleet` | Hub handler-specific | My-Hives Fleet Page (static; data via `/api/saas/my-hives`) | `pkg/hub/server.go:1773` | +| `GET` | `/my-hives` | Hub handler-specific | 301 redirect to `/fleet` (query preserved) | `pkg/hub/server.go:1774` | +| `POST` | `/api/shared-agent-pool/leases` | Hub handler-specific | Acquire or renew a shared CLI session lease | `pkg/hub/server.go:1708` | +| `PUT` | `/api/shared-agent-pool/leases` | Hub handler-specific | Renew an active shared CLI session lease | `pkg/hub/server.go:1709` | +| `DELETE` | `/api/shared-agent-pool/leases` | Hub handler-specific | Release a shared CLI session lease | `pkg/hub/server.go:1710` | +| `POST` | `/api/heartbeat` | Hub handler-specific | Heartbeat | `pkg/hub/server.go:1711` | +| `POST` | `/api/task-status` | Hub handler-specific | Task Status | `pkg/hub/server.go:1712` | +| `GET` | `/api/registry` | Hub handler-specific | Registry | `pkg/hub/server.go:1720` | +| `GET` | `/api/hub/leaderboard` | Hub handler-specific | Leaderboard | `pkg/hub/server.go:1721` | +| `GET` | `/api/hub/stats` | Hub handler-specific | Stats | `pkg/hub/server.go:1722` | +| `GET` | `/api/fleet-stats` | Hub handler-specific | Fleet Stats | `pkg/hub/server.go:1723` | | `GET` | `/api/hub/evidence` | Hub admin | Read-only cross-hive evidence drill-down from each spoke's stored heartbeat `evidence` summary ([#12116](https://github.com/hivecommons/hive/issues/12116)); non-admins get `403`. Returns `spokes`, `reporting`, pooled `calibration` (bucket 0–5 → `{n, bad, rate, lo, hi}`; the hub view folds the six buckets into four reviewer-confidence ranges), `findings[]` (the plain-language *What this says* sentences, generated from the same fields; [#12456](https://github.com/hivecommons/hive/issues/12456)), `by_acmm_level` (`level`, `hives`, `merged_90d`, `revert_rate`, and `time_to_merge` — `median_of_hive_medians_s`, `hives`, `n` — the median of the level's per-hive median time-to-merge, omitted when no hive at the level reports one; [#12464](https://github.com/hivecommons/hive/issues/12464)), `family_false_approve_rate` (`same`/`cross`/`mixed`, hives classed by their reviewer vs author family sets), fleet `record_coverage` (merged PRs with an evidence record over `prs_merged_90d`), fleet panels ([#12370](https://github.com/hivecommons/hive/issues/12370)) `outcomes_by_author_kind[]` (`kind`, `hives`, `n`, `merged`, `reverted`, `merge_rate`, `revert_rate`), `write_counters[]` (`tier`, `hives`, `attempted`, `blocked`, `block_rate`) and `shadow_gate` (`review_gate` / `intent` → `held` / `passed` outcomes with `revert_rate`), each omitted while no spoke reports it and repeated per `by_acmm_level[]` row, and per hive `hives[]` with `acmm_level`, `prs_merged_90d`, `record_coverage`, `family_mix`, false-approve / false-block / revert rates, families, a calibration series the raw `counts` behind them (including `by_author_kind`) so the drill-down can re-pool a hive / ACMM-level selection client-side, and `criteria[]`: the per-axis criteria table derived hub-side from the quadrant criteria (`axis`, `label`, `scored`, `criteria[]` with `name`, `label`, `status` `met`/`unmet`/`not_reported`, `display`/`score` when measured, `reason` otherwise; offline, evidence-less or unscored hives are `not_reported`, never `unmet`; [#12463](https://github.com/hivecommons/hive/issues/12463)). Every rate is `{n, rate, lo, hi}` with a 95% Wilson interval; `rate`/`lo`/`hi` are null when `n` < 10. Window selection ([RFC #12062](https://github.com/hivecommons/hive/issues/12062)): `?hours=24|168|720` pools each hive's matching heartbeat `windows` block instead of its 90-day block (any other or absent `hours` → 90 days); `?from=YYYY-MM-DD|RFC3339[&to=…]` (date-only `to` is inclusive, `to` defaults to now, `to` ≥ `from`, span ≤ 366 days, else `400`) is served from the smallest reported window that reaches back to `from` and flagged `window.approximate`. The response carries `window` (`hours`, `key`, `label`, `from`, `to`, `approximate`, `coverage_available` — `record_coverage` is only computed for the 90-day window because `prs_merged_90d` is a 90-day count), `window_unreported` and per-hive `window_unreported` for hives whose spoke predates per-window reporting. `?hive=[,…]` (repeatable) and `?level=` restrict the registry server-side to those hives / that ACMM level before pooling. Hub admins open it from the Fleet quadrant card or its **🔬 Evidence** button ([#12117](https://github.com/hivecommons/hive/issues/12117)), pick a window (24h / 7d / 30d / 90d / custom), filter it by hive and ACMM level and read each section's ⓘ explainer; the per-hive author-kind revert counts behind the *Revert rate by author kind* panel are `hives[].counts.by_author_kind` ([#12326](https://github.com/hivecommons/hive/issues/12326)). Never consulted by merge decisions | `pkg/hub/evidence.go` | | `GET` | `/api/hub/evidence/report` | Hub admin | Plain-language report of the hub evidence view ([#12456](https://github.com/hivecommons/hive/issues/12456)), rendered server-side from the same `EvidenceView` as `/api/hub/evidence` so every figure reconciles with the modal; non-admins get `403`. Same `hours=` / `from=` / `to=` window and `hive=` / `level=` filter parameters. `format=md` (default, `text/markdown`) or `format=html` (standalone page, inline CSS, no scripts or external assets, hive names escaped); any other value → `400`. `download=1` sets `Content-Disposition: attachment; filename="hive-evidence---.md|html"`, otherwise inline. Sections: Summary (the generated findings), What we measured and why, The numbers, How to read these, What is not reported yet and why, Grade per section, footer link to `review-evidence.md`. `Cache-Control: no-store`. Read-only; never consulted by merge decisions | `pkg/hub/evidence_report.go` | -| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1727` | -| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1737` | -| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1738` | -| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1739` | -| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1740` | -| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1741` | -| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1742` | -| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1743` | -| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1744` | -| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1747` | -| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1750` | -| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1751` | -| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1758` | -| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1759` | -| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1760` | -| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1777` | -| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1782` | -| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1784` | +| `GET` | `/api/hub/activity` | Signed-in user | Read-only hub-wide activity view ([#15951](https://github.com/hivecommons/hive/issues/15951), RFC [#15861](https://github.com/hivecommons/hive/issues/15861)) merged from each spoke's heartbeat `activity` digest, held in hub memory only. Authorization is per user and per hive before aggregation: hub admins see every registered hive; everyone else only hives they own or hold an unexpired grant for; anonymous → `401`. Returns `hives[]` (`hive_id`, `name`, `status` `ok`/`stale`/`not_reporting`/`missing`, `reporting`, `stale` once the block is older than two heartbeats, `last_heartbeat`, `received_at`, `generated_at`, `totals` — `items`, `by_stage`, `by_modifier`, counting private and truncated items too — and `truncated`), `items[]` (`hive_id`, `repo`, `n`, `kind`, `title`, `author_kind`, `stage`, `stage_n`, `since`, `mods`, `private`) ordered needs-human/needs-decision, stalled, furthest stage, oldest, and a response-level `truncated` (cap 2000). Each digest carries at most 100 items by default and never more than the 250-item hub ceiling; private-repository items appear only when the spoke opts in. Filters: `hive`, `repo`, `stage`, `mod`, `author_kind`, `q` (title substring or `#`), each ≤ 200 characters (else `400`). `ETag` + `If-None-Match` → `304`; `Cache-Control: private, no-cache`, `Vary: Cookie, Authorization`. No actions | `pkg/hub/activity.go` | +| `GET` | `/api/hub/version` | Hub handler-specific | Hub Version | `pkg/hub/server.go:1731` | +| `DELETE` | `/api/hub/registry/{id}` | Hub handler-specific | Registry Delete | `pkg/hub/server.go:1741` | +| `POST` | `/api/contribute/register` | Hub handler-specific | Contribute Proxy | `pkg/hub/server.go:1742` | +| `GET` | `/api/contribute/status` | Hub handler-specific | Contribute Status | `pkg/hub/server.go:1743` | +| `GET` | `/api/contribute/ws` | Hub handler-specific | Contribute WSProxy | `pkg/hub/server.go:1744` | +| `POST` | `/api/github/webhook` | Hub handler-specific | GitHub Webhook | `pkg/hub/server.go:1745` | +| `GET` | `/gh-setup` | Hub handler-specific | GitHub App Setup Router | `pkg/hub/server.go:1746` | +| `GET` | `/learn` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1747` | +| `GET` | `/get-started` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1748` | +| `GET` | `/api/docs` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1751` | +| `GET` | `/api/reading-list` | Hub handler-specific | Reading List | `pkg/hub/server.go:1754` | +| `GET` | `/reading` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1755` | +| `GET` | `/cncf-reference-architecture` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1762` | +| `GET` | `/cncf-reference-architecture/console` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1763` | +| `GET` | `/cncf-reference-architecture/bluefin` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1764` | +| `GET` | `/{$}` | Hub handler-specific | Static HTML page | `pkg/hub/server.go:1781` | +| `GET` | `/og-card.png` | Hub handler-specific | OGCard | `pkg/hub/server.go:1786` | +| `GET` | `/` | Public | Static asset fallback (`http.FileServerFS` over the embedded `static/` tree) for any path no other route claims | `pkg/hub/server.go:1788` | diff --git a/src/pkg/hub/activity.go b/src/pkg/hub/activity.go new file mode 100644 index 0000000000..c5826b4867 --- /dev/null +++ b/src/pkg/hub/activity.go @@ -0,0 +1,382 @@ +package hub + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/hivecommons/hive/pkg/dashboard/webstatic" + "github.com/hivecommons/hive/pkg/hubactivity" +) + +// Hub-wide Activity Monitor, first slice (RFC hivecommons/hive#15861, +// child #15951). Spokes attach a bounded hubactivity.Digest to their +// heartbeat; the hub keeps the latest one per hive IN MEMORY ONLY (never in +// the persisted registry) and serves a merged, per-user scoped view on +// GET /api/hub/activity with ETag polling. The hub is visibility-only: the +// endpoint is read-only and offers no actions. + +const ( + activityPath = "/api/hub/activity" + + // activityHeartbeatInterval mirrors the spoke's heartbeatSendInterval + // (pkg/dashboard). A hive whose activity block is older than two + // intervals is stale. + activityHeartbeatInterval = 2 * time.Minute + activityStaleAfter = 2 * activityHeartbeatInterval + + // activityForgetAfter drops a hive's block from memory once it has not + // been refreshed for this long, so hives that stopped reporting (or left + // the registry) cannot pin memory forever. + activityForgetAfter = 24 * time.Hour + + // maxActivityResponseItems bounds the merged response no matter how many + // hives a viewer can see; overflow is disclosed in Truncated. + maxActivityResponseItems = 8 * hubactivity.MaxItemsCeiling + + // maxActivityFilterRunes bounds each query filter value. + maxActivityFilterRunes = 200 +) + +// Hive status values in the activity view, most severe first. +const ( + activityStatusMissing = "missing" // granted but unknown to the registry + activityStatusNotReporting = "not_reporting" // heartbeats, but sends no activity block + activityStatusStale = "stale" // block older than two heartbeats + activityStatusOK = "ok" +) + +// storedActivity is one hive's latest accepted digest. +type storedActivity struct { + digest hubactivity.Digest + receivedAt time.Time +} + +// activityStore holds the latest digest per hive. It is a leaf lock: never +// take s.mu while holding it. The zero value is ready to use. +type activityStore struct { + mu sync.Mutex + byHive map[string]storedActivity +} + +// record applies a heartbeat's activity block and returns the etag the hub +// now holds for the hive (the acknowledgement), or "" when it holds none. +// +// - nil block: the spoke is too old or not participating; nothing changes. +// - unchanged marker with the held etag: the block is refreshed in place. +// - unchanged marker with any other etag: ignored; the returned (held or +// empty) etag tells the spoke to send its full digest next beat. +// - full digest: sanitized against the hub's ceilings and stored. +func (st *activityStore) record(hiveID string, block *hubactivity.Digest, now time.Time) string { + st.mu.Lock() + defer st.mu.Unlock() + st.forgetOldLocked(now) + held, ok := st.byHive[hiveID] + if block == nil { + if ok { + return held.digest.ETag + } + return "" + } + if block.IsUnchangedMarker() { + // Compare in the stored (cleaned) form, or a marker whose etag + // changes under cleaning would never match and wedge the handshake. + if !ok || held.digest.ETag != hubactivity.CleanETag(block.ETag) { + if ok { + return held.digest.ETag + } + return "" + } + held.receivedAt = now + if !block.GeneratedAt.IsZero() { + held.digest.GeneratedAt = block.GeneratedAt.UTC() + } + st.byHive[hiveID] = held + return held.digest.ETag + } + // The spoke's etag is kept as the handshake identity rather than + // recomputed: a spoke that lies about it only misleads its own + // freshness, and recomputing would make every marker miss. + clean := hubactivity.Sanitize(*block) + if clean.ETag == "" { + clean.ETag = hubactivity.ContentETag(clean) + } + if st.byHive == nil { + st.byHive = map[string]storedActivity{} + } + st.byHive[hiveID] = storedActivity{digest: clean, receivedAt: now} + return clean.ETag +} + +func (st *activityStore) forgetOldLocked(now time.Time) { + for id, a := range st.byHive { + if now.Sub(a.receivedAt) > activityForgetAfter { + delete(st.byHive, id) + } + } +} + +// snapshot copies the blocks of the given hives only, so data of hives the +// viewer cannot see is never even copied out of the store. +func (st *activityStore) snapshot(hiveIDs []string) map[string]storedActivity { + st.mu.Lock() + defer st.mu.Unlock() + out := make(map[string]storedActivity, len(hiveIDs)) + for _, id := range hiveIDs { + if a, ok := st.byHive[id]; ok { + out[id] = a + } + } + return out +} + +// activityHive is the registry slice the view needs. +type activityHive struct { + ID string + Name string + Owner string + LastHeartbeat string + Missing bool +} + +// visibleActivityHives returns the hives username may see, applying the +// same rule as the My Hives page (buildMyHivesResponse): hub admins see +// every registered hive; everyone else sees hives they own or hold an +// unexpired grant for. A granted hive the registry does not know is +// returned with Missing set so the view can disclose it. +func visibleActivityHives(username string, user *SaaSUser, registry []activityHive, now time.Time) []activityHive { + if username == "" { + return nil + } + isAdmin := isHubAdmin(username) + granted := map[string]bool{} + if user != nil { + for id, role := range user.Hives { + if role == "" || accessGrantExpired(user.HiveExpiry[id], now) { + continue + } + granted[id] = true + } + } + var out []activityHive + seen := map[string]bool{} + for _, h := range registry { + if isAdmin || granted[h.ID] || canonicalEqual(h.Owner, username) { + out = append(out, h) + seen[h.ID] = true + } + } + for id := range granted { + if !seen[id] { + out = append(out, activityHive{ID: id, Missing: true}) + } + } + slices.SortFunc(out, func(a, b activityHive) int { return strings.Compare(a.ID, b.ID) }) + return out +} + +// activityFilter is the parsed, bounded query string. +type activityFilter struct { + Hive, Repo, Stage, Mod, AuthorKind, Q string + // qLower is Q lowercased once; qNumber is Q read as an item number + // ("123" or "#123"), or 0. + qLower string + qNumber int +} + +func parseActivityFilter(q url.Values) (activityFilter, error) { + var f activityFilter + fields := []struct { + key string + dst *string + }{ + {"hive", &f.Hive}, {"repo", &f.Repo}, {"stage", &f.Stage}, + {"mod", &f.Mod}, {"author_kind", &f.AuthorKind}, {"q", &f.Q}, + } + for _, fl := range fields { + v := strings.TrimSpace(q.Get(fl.key)) + if !utf8.ValidString(v) || utf8.RuneCountInString(v) > maxActivityFilterRunes { + return activityFilter{}, fmt.Errorf("invalid %s filter", fl.key) + } + *fl.dst = v + } + f.qLower = strings.ToLower(f.Q) + if n, err := strconv.Atoi(strings.TrimPrefix(f.Q, "#")); err == nil && n > 0 { + f.qNumber = n + } + return f, nil +} + +func (f activityFilter) matches(hiveID string, it hubactivity.Item) bool { + switch { + case f.Hive != "" && f.Hive != hiveID: + return false + case f.Repo != "" && !strings.EqualFold(f.Repo, it.Repo): + return false + case f.Stage != "" && f.Stage != it.Stage: + return false + case f.AuthorKind != "" && f.AuthorKind != it.AuthorKind: + return false + case f.Mod != "" && !slices.Contains(it.Mods, f.Mod): + return false + } + if f.Q == "" { + return true + } + if f.qNumber > 0 && it.Number == f.qNumber { + return true + } + return strings.Contains(strings.ToLower(it.Title), f.qLower) +} + +// ActivityHiveView is one visible hive's freshness and totals. +type ActivityHiveView struct { + HiveID string `json:"hive_id"` + Name string `json:"name,omitempty"` + // Status is ok, stale, not_reporting ("upgrade to report activity") or + // missing (granted, but the hub has no registry entry for it). + Status string `json:"status"` + Reporting bool `json:"reporting"` + Stale bool `json:"stale"` + LastHeartbeat string `json:"last_heartbeat,omitempty"` + ReceivedAt *time.Time `json:"received_at,omitempty"` + GeneratedAt *time.Time `json:"generated_at,omitempty"` + Totals *hubactivity.Totals `json:"totals,omitempty"` + // Truncated is how many of this hive's items its digest left out. + Truncated int `json:"truncated,omitempty"` +} + +// ActivityViewItem is one merged item tagged with its hive. +type ActivityViewItem struct { + HiveID string `json:"hive_id"` + hubactivity.Item +} + +// ActivityView is the GET /api/hub/activity body. +type ActivityView struct { + Hives []ActivityHiveView `json:"hives"` + Items []ActivityViewItem `json:"items"` + // Truncated is how many matching items the response cap left out, on + // top of what each hive's own digest already left out. + Truncated int `json:"truncated,omitempty"` +} + +// buildActivityView merges the blocks of the visible hives only. Hives must +// already be authorized for the viewer. +func buildActivityView(hives []activityHive, blocks map[string]storedActivity, f activityFilter, now time.Time) ActivityView { + view := ActivityView{Hives: []ActivityHiveView{}, Items: []ActivityViewItem{}} + for _, h := range hives { + hv := ActivityHiveView{HiveID: h.ID, Name: h.Name, LastHeartbeat: h.LastHeartbeat} + block, ok := blocks[h.ID] + switch { + case h.Missing: + hv.Status = activityStatusMissing + case !ok: + hv.Status = activityStatusNotReporting + default: + hv.Reporting = true + hv.Stale = now.Sub(block.receivedAt) > activityStaleAfter + hv.Status = activityStatusOK + if hv.Stale { + hv.Status = activityStatusStale + } + recv := block.receivedAt.UTC() + hv.ReceivedAt = &recv + if gen := block.digest.GeneratedAt; !gen.IsZero() { + hv.GeneratedAt = &gen + } + hv.Totals = block.digest.Totals + hv.Truncated = block.digest.Truncated + for _, it := range block.digest.Items { + if f.matches(h.ID, it) { + view.Items = append(view.Items, ActivityViewItem{HiveID: h.ID, Item: it}) + } + } + } + if f.Hive == "" || f.Hive == h.ID { + view.Hives = append(view.Hives, hv) + } + } + slices.SortStableFunc(view.Items, func(a, b ActivityViewItem) int { + if c := hubactivity.CompareUrgency(a.Item, b.Item); c != 0 { + return c + } + return strings.Compare(a.HiveID, b.HiveID) + }) + if len(view.Items) > maxActivityResponseItems { + view.Truncated = len(view.Items) - maxActivityResponseItems + view.Items = view.Items[:maxActivityResponseItems] + } + return view +} + +// handleHubActivity serves GET /api/hub/activity. It is mounted behind +// requireAuth; authorization to each hive is decided here BEFORE any block +// is read, so another hive's data never enters the response or its etag. +func (s *HubServer) handleHubActivity(w http.ResponseWriter, r *http.Request) { + username := s.getAuthUser(r) + if username == "" { + writeJSONError(w, http.StatusUnauthorized, "not authenticated") + return + } + f, err := parseActivityFilter(r.URL.Query()) + if err != nil { + writeJSONError(w, http.StatusBadRequest, err.Error()) + return + } + now := time.Now().UTC() + s.mu.RLock() + registry := make([]activityHive, 0, len(s.registry.Hives)) + for _, h := range s.registry.Hives { + name := h.ProjectName + if name == "" { + name = h.Name + } + registry = append(registry, activityHive{ID: h.ID, Name: name, Owner: h.Owner, LastHeartbeat: h.LastHeartbeat}) + } + s.mu.RUnlock() + + hives := visibleActivityHives(username, loadSaaSUser(username), registry, now) + ids := make([]string, len(hives)) + for i, h := range hives { + ids[i] = h.ID + } + view := buildActivityView(hives, s.activity.snapshot(ids), f, now) + body, err := json.Marshal(view) + if err != nil { + s.logger.Error("hub activity: encode view", "error", err) + writeJSONError(w, http.StatusInternalServerError, "internal error") + return + } + etag := webstatic.ETagFor(body) + h := w.Header() + h.Set("Content-Type", "application/json") + // Per-user data: never stored by a shared cache, always revalidated. + h.Set("Cache-Control", "private, no-cache") + h.Set("Vary", "Cookie, Authorization") + h.Set("ETag", etag) + if activityETagMatches(r.Header.Get("If-None-Match"), etag) { + w.WriteHeader(http.StatusNotModified) + return + } + _, _ = w.Write(body) +} + +// activityETagMatches is the RFC 9110 weak comparison of If-None-Match. +func activityETagMatches(header, etag string) bool { + want := strings.TrimPrefix(etag, "W/") + for _, tag := range strings.Split(header, ",") { + tag = strings.TrimSpace(tag) + if tag == "*" || strings.TrimPrefix(tag, "W/") == want { + return true + } + } + return false +} diff --git a/src/pkg/hub/activity_test.go b/src/pkg/hub/activity_test.go new file mode 100644 index 0000000000..f5a95f05d6 --- /dev/null +++ b/src/pkg/hub/activity_test.go @@ -0,0 +1,503 @@ +package hub + +import ( + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/hub/spoke" + "github.com/hivecommons/hive/pkg/hubactivity" +) + +var activityT0 = time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC) + +func activityDigest(repo string, numbers ...int) *hubactivity.Digest { + items := make([]hubactivity.Item, 0, len(numbers)) + for _, n := range numbers { + items = append(items, hubactivity.Item{Repo: repo, Number: n, Kind: "pr", Title: fmt.Sprintf("%s #%d", repo, n), Stage: "ci_review", StageNumber: 70}) + } + d := hubactivity.Build(items, hubactivity.BuildOptions{Now: activityT0}) + return &d +} + +func newActivityHub() *HubServer { + return &HubServer{ + logger: slog.Default(), + hubSecret: testHubSecret, + keyGenerations: legacyGenerationSet(testHubSecret), + saveCh: make(chan struct{}, 1), + hubGitHash: "abc1234", + hubGitBranch: "v5", + clusters: map[string]ClusterConfig{"hive-oke": {ID: "hive-oke", Domain: "hive.example.test"}}, + heartbeatHealth: make(map[string]*HeartbeatHealthEntry), + heartbeatUpgrade: make(map[string]string), + heartbeatSwitchTag: make(map[string]string), + pendingWebhooks: make(map[string]*pendingWebhookEntry), + pendingGitHubAppConfigs: make(map[string]*HeartbeatGitHubAppConfig), + pendingGateways: make(map[string]*HeartbeatGatewayConfig), + hubBanners: make(map[string]*HubBannerEntry), + } +} + +func postActivityHeartbeat(t *testing.T, s *HubServer, hiveID string, d *hubactivity.Digest) HeartbeatResponse { + t.Helper() + body, err := json.Marshal(spoke.HeartbeatPayload{HiveID: hiveID, Org: "o", PrimaryRepo: "r", Repos: []string{"r"}, Activity: d}) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPost, "/api/heartbeat", strings.NewReader(string(body))) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", heartbeatBearer(testHubSecret, hiveID)) + rec := httptest.NewRecorder() + s.handleHeartbeat(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("heartbeat %s: status %d body=%s", hiveID, rec.Code, rec.Body.String()) + } + var resp HeartbeatResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + return resp +} + +func getActivity(t *testing.T, s *HubServer, user, query, ifNoneMatch string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, activityPath+query, nil) + if user != "" { + req.AddCookie(testAuthCookie(user)) + } + if ifNoneMatch != "" { + req.Header.Set("If-None-Match", ifNoneMatch) + } + rec := httptest.NewRecorder() + s.requireAuth(s.handleHubActivity)(rec, req) + return rec +} + +func decodeActivity(t *testing.T, rec *httptest.ResponseRecorder) ActivityView { + t.Helper() + if rec.Code != http.StatusOK { + t.Fatalf("status %d body=%s", rec.Code, rec.Body.String()) + } + var v ActivityView + if err := json.Unmarshal(rec.Body.Bytes(), &v); err != nil { + t.Fatal(err) + } + return v +} + +func activityHiveIDs(v ActivityView) map[string]bool { + out := map[string]bool{} + for _, it := range v.Items { + out[it.HiveID] = true + } + return out +} + +// Acceptance (#15861): two spokes heartbeating to one hub; a user granted +// only one of them sees only that hive's rows, an admin sees both. +func TestHubActivity_TwoSpokesPerUserScoping(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + s := newActivityHub() + + ackA := postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1, 2)) + postActivityHeartbeat(t, s, "hive-b", activityDigest("o/b", 3)) + if ackA.ActivityETag == "" { + t.Fatalf("heartbeat response must acknowledge the stored activity etag") + } + + if err := saveSaaSUser(&SaaSUser{GitHubUsername: "alice", Hives: map[string]string{"hive-a": "viewer"}}); err != nil { + t.Fatal(err) + } + mkUser(t, "root") + + v := decodeActivity(t, getActivity(t, s, "alice", "", "")) + if got := activityHiveIDs(v); !got["hive-a"] || got["hive-b"] { + t.Fatalf("alice sees hives %v, want only hive-a", got) + } + for _, h := range v.Hives { + if h.HiveID == "hive-b" { + t.Fatalf("alice must not even see hive-b's freshness row: %+v", v.Hives) + } + } + if len(v.Items) != 2 { + t.Fatalf("alice items = %d, want 2", len(v.Items)) + } + + admin := decodeActivity(t, getActivity(t, s, "root", "", "")) + if got := activityHiveIDs(admin); !got["hive-a"] || !got["hive-b"] { + t.Fatalf("admin sees hives %v, want both", got) + } +} + +func TestHubActivity_RequiresAuthentication(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + s := newActivityHub() + + rec := getActivity(t, s, "", "", "") + + if rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous status = %d, want 401", rec.Code) + } +} + +func TestHubActivity_UserWithNoGrantsSeesNothing(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + s := newActivityHub() + postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1)) + mkUser(t, "mallory") + + v := decodeActivity(t, getActivity(t, s, "mallory", "", "")) + + if len(v.Items) != 0 || len(v.Hives) != 0 { + t.Fatalf("ungranted user saw %+v", v) + } +} + +// Acceptance: with share_private false a private-repo PR never reaches the +// hub API, but it is counted in totals. +func TestHubActivity_PrivateItemsNeverServedButCounted(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + s := newActivityHub() + d := hubactivity.Build([]hubactivity.Item{ + {Repo: "o/public", Number: 1, Kind: "pr", Title: "public", Stage: "ci_review"}, + {Repo: "o/secret", Number: 2, Kind: "pr", Title: "secret title", Stage: "ci_review", Private: true}, + }, hubactivity.BuildOptions{Now: activityT0}) + postActivityHeartbeat(t, s, "hive-a", &d) + mkUser(t, "root") + + rec := getActivity(t, s, "root", "", "") + v := decodeActivity(t, rec) + + if strings.Contains(rec.Body.String(), "o/secret") || strings.Contains(rec.Body.String(), "secret title") { + t.Fatalf("private item leaked: %s", rec.Body.String()) + } + if len(v.Hives) != 1 || v.Hives[0].Totals == nil || v.Hives[0].Totals.Items != 2 { + t.Fatalf("totals must count the private item: %+v", v.Hives) + } +} + +func TestHubActivity_ETagPolling(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + s := newActivityHub() + postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1)) + mkUser(t, "root") + + first := getActivity(t, s, "root", "", "") + etag := first.Header().Get("ETag") + if etag == "" || first.Header().Get("Cache-Control") != "private, no-cache" || first.Header().Get("Vary") != "Cookie, Authorization" { + t.Fatalf("headers = %v", first.Header()) + } + again := getActivity(t, s, "root", "", etag) + if again.Code != http.StatusNotModified || again.Body.Len() != 0 { + t.Fatalf("matching If-None-Match: status %d body %q, want 304 empty", again.Code, again.Body.String()) + } + + postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1, 2)) + changed := getActivity(t, s, "root", "", etag) + if changed.Code != http.StatusOK || changed.Header().Get("ETag") == etag { + t.Fatalf("changed content must return 200 with a new etag, got %d %q", changed.Code, changed.Header().Get("ETag")) + } +} + +func TestHubActivity_ExpiredGrantServesNothing(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + s := newActivityHub() + postActivityHeartbeat(t, s, "hive-a", activityDigest("o/a", 1)) + if err := saveSaaSUser(&SaaSUser{ + GitHubUsername: "bob", + Hives: map[string]string{"hive-a": "read"}, + HiveExpiry: map[string]string{"hive-a": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)}, + }); err != nil { + t.Fatal(err) + } + + v := decodeActivity(t, getActivity(t, s, "bob", "", "")) + + if len(v.Items) != 0 || len(v.Hives) != 0 { + t.Fatalf("expired grant still served %+v", v) + } +} + +// A beat without an activity block (older spoke, or one that skipped a +// beat) keeps the held digest and still acknowledges its etag. +func TestHubActivity_BeatWithoutBlockKeepsDigest(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + s := newActivityHub() + full := activityDigest("o/a", 1) + postActivityHeartbeat(t, s, "hive-a", full) + + resp := postActivityHeartbeat(t, s, "hive-a", nil) + + if resp.ActivityETag != full.ETag { + t.Fatalf("ack = %q, want held %q", resp.ActivityETag, full.ETag) + } + if got := s.activity.snapshot([]string{"hive-a"})["hive-a"]; len(got.digest.Items) != 1 { + t.Fatalf("held digest lost: %+v", got) + } +} + +func TestHubActivity_RejectsOversizedFilter(t *testing.T) { + cleanup := helperSetupTempDirs(t) + defer cleanup() + s := newActivityHub() + mkUser(t, "alice") + + rec := getActivity(t, s, "alice", "?q="+url.QueryEscape(strings.Repeat("x", maxActivityFilterRunes+1)), "") + + if rec.Code != http.StatusBadRequest { + t.Fatalf("oversized filter status = %d, want 400", rec.Code) + } +} + +func TestActivityStore_RecordSemantics(t *testing.T) { + var st activityStore + full := activityDigest("o/a", 1) + + if ack := st.record("h", nil, activityT0); ack != "" { + t.Fatalf("nil block on empty store acked %q", ack) + } + ack := st.record("h", full, activityT0) + if ack != full.ETag { + t.Fatalf("ack = %q, want %q", ack, full.ETag) + } + + // Matching unchanged marker refreshes freshness, keeps items. + later := activityT0.Add(3 * time.Minute) + if got := st.record("h", &hubactivity.Digest{ETag: full.ETag, GeneratedAt: later}, later); got != full.ETag { + t.Fatalf("marker ack = %q", got) + } + snap := st.snapshot([]string{"h"})["h"] + if !snap.receivedAt.Equal(later) || len(snap.digest.Items) != 1 { + t.Fatalf("marker must refresh in place: %+v", snap) + } + + // Mismatched marker is ignored and acks the held etag. + if got := st.record("h", &hubactivity.Digest{ETag: `W/"other"`, GeneratedAt: later}, later); got != full.ETag { + t.Fatalf("mismatched marker ack = %q, want held %q", got, full.ETag) + } + if len(st.snapshot([]string{"h"})["h"].digest.Items) != 1 { + t.Fatalf("mismatched marker must not clear content") + } + + // A marker whose etag only differs by what cleaning strips still matches. + if got := st.record("h", &hubactivity.Digest{ETag: " " + full.ETag + "\n"}, later); got != full.ETag { + t.Fatalf("dirty marker etag ack = %q, want %q", got, full.ETag) + } + + // A marker for an unknown hive acks nothing, so the spoke resends full. + if got := st.record("new", &hubactivity.Digest{ETag: full.ETag}, later); got != "" { + t.Fatalf("marker for unknown hive acked %q", got) + } +} + +func TestActivityStore_EnforcesHubCeiling(t *testing.T) { + var st activityStore + d := hubactivity.Digest{ETag: `W/"big"`, Totals: &hubactivity.Totals{Items: hubactivity.MaxItemsCeiling + 30}} + for i := 1; i <= hubactivity.MaxItemsCeiling+30; i++ { + d.Items = append(d.Items, hubactivity.Item{Repo: "o/r", Number: i}) + } + + st.record("h", &d, activityT0) + + got := st.snapshot([]string{"h"})["h"].digest + if len(got.Items) != hubactivity.MaxItemsCeiling || got.Truncated != 30 { + t.Fatalf("stored %d items truncated %d, want %d/30", len(got.Items), got.Truncated, hubactivity.MaxItemsCeiling) + } +} + +func TestActivityStore_ForgetsLongSilentHives(t *testing.T) { + var st activityStore + st.record("old", activityDigest("o/a", 1), activityT0) + + st.record("other", activityDigest("o/b", 1), activityT0.Add(activityForgetAfter+time.Minute)) + + if _, ok := st.snapshot([]string{"old"})["old"]; ok { + t.Fatalf("a block silent for longer than activityForgetAfter must be dropped") + } +} + +// Acceptance: a stopped spoke is stale after two missed heartbeats; a spoke +// that sends no block shows as not reporting; a granted hive the registry +// does not know is disclosed as missing. +func TestBuildActivityView_FreshnessDisclosure(t *testing.T) { + now := activityT0.Add(10 * time.Minute) + hives := []activityHive{{ID: "fresh"}, {ID: "gone"}, {ID: "old-spoke"}, {ID: "ghost", Missing: true}} + blocks := map[string]storedActivity{ + "fresh": {digest: *activityDigest("o/a", 1), receivedAt: now.Add(-activityHeartbeatInterval)}, + "gone": {digest: *activityDigest("o/b", 2), receivedAt: now.Add(-activityStaleAfter - time.Second)}, + } + + v := buildActivityView(hives, blocks, activityFilter{}, now) + + want := map[string]string{"fresh": activityStatusOK, "gone": activityStatusStale, "old-spoke": activityStatusNotReporting, "ghost": activityStatusMissing} + if len(v.Hives) != len(want) { + t.Fatalf("hives = %+v", v.Hives) + } + for _, h := range v.Hives { + if h.Status != want[h.HiveID] { + t.Errorf("%s status = %q, want %q", h.HiveID, h.Status, want[h.HiveID]) + } + if h.HiveID == "old-spoke" && h.Reporting { + t.Errorf("old spoke must report reporting=false") + } + } + if len(v.Items) != 2 { + t.Fatalf("stale hive rows stay visible with their status: %d items", len(v.Items)) + } +} + +func TestBuildActivityView_FiltersAndResponseCap(t *testing.T) { + now := activityT0 + var big []int + for i := 1; i <= hubactivity.MaxItemsCeiling; i++ { + big = append(big, i) + } + hives := make([]activityHive, 0, 9) + blocks := map[string]storedActivity{} + for i := 0; i < 9; i++ { + id := fmt.Sprintf("h%d", i) + hives = append(hives, activityHive{ID: id}) + d := hubactivity.Build(itemsFor("o/"+id, big), hubactivity.BuildOptions{Now: now, MaxItems: hubactivity.MaxItemsCeiling}) + blocks[id] = storedActivity{digest: d, receivedAt: now} + } + + all := buildActivityView(hives, blocks, activityFilter{}, now) + if len(all.Items) != maxActivityResponseItems || all.Truncated != hubactivity.MaxItemsCeiling { + t.Fatalf("items %d truncated %d, want %d/%d", len(all.Items), all.Truncated, maxActivityResponseItems, hubactivity.MaxItemsCeiling) + } + + f, err := parseActivityFilter(url.Values{"hive": {"h3"}, "q": {"#7"}}) + if err != nil { + t.Fatal(err) + } + one := buildActivityView(hives, blocks, f, now) + if len(one.Items) != 1 || one.Items[0].HiveID != "h3" || one.Items[0].Number != 7 || len(one.Hives) != 1 { + t.Fatalf("hive+number filter = %+v", one) + } +} + +// A numeric q matches the item number OR a title containing it. +func TestActivityFilter_NumericQueryAlsoMatchesTitles(t *testing.T) { + f, err := parseActivityFilter(url.Values{"q": {"2024"}}) + if err != nil { + t.Fatal(err) + } + if !f.matches("h", hubactivity.Item{Repo: "o/r", Number: 2024, Title: "x"}) { + t.Errorf("number match failed") + } + if !f.matches("h", hubactivity.Item{Repo: "o/r", Number: 1, Title: "Roadmap 2024"}) { + t.Errorf("title match failed") + } + if f.matches("h", hubactivity.Item{Repo: "o/r", Number: 1, Title: "nope"}) { + t.Errorf("unrelated item matched") + } +} + +func itemsFor(repo string, numbers []int) []hubactivity.Item { + out := make([]hubactivity.Item, 0, len(numbers)) + for _, n := range numbers { + out = append(out, hubactivity.Item{Repo: repo, Number: n, Kind: "issue", Title: fmt.Sprintf("t%d", n), Stage: "actionable", StageNumber: 10}) + } + return out +} + +func TestVisibleActivityHives_ExpiredGrantIsNotVisible(t *testing.T) { + cleanup := helperSetupTempDirs(t) // isHubAdmin also reads the granted-admins file + defer cleanup() + t.Setenv(hubAdminsEnv, "github:root") + now := activityT0 + user := &SaaSUser{ + GitHubUsername: "alice", + Hives: map[string]string{"live": "viewer", "expired": "viewer", "ghost": "viewer"}, + HiveExpiry: map[string]string{"expired": now.Add(-time.Hour).Format(time.RFC3339)}, + } + registry := []activityHive{{ID: "live"}, {ID: "expired"}, {ID: "owned", Owner: "alice"}, {ID: "other"}} + + got := visibleActivityHives("alice", user, registry, now) + + ids := map[string]bool{} + for _, h := range got { + ids[h.ID] = true + if h.ID == "ghost" && !h.Missing { + t.Errorf("granted hive unknown to the registry must be marked missing") + } + } + if !ids["live"] || !ids["owned"] || !ids["ghost"] || ids["expired"] || ids["other"] { + t.Fatalf("visible = %v", ids) + } + if len(visibleActivityHives("", user, registry, now)) != 0 { + t.Fatalf("anonymous viewer must see nothing") + } +} + +func TestActivityETagMatches(t *testing.T) { + cases := []struct { + header string + want bool + }{ + {`"abc"`, true}, + {`W/"abc"`, true}, + {`"x", "abc"`, true}, + {`*`, true}, + {`"x"`, false}, + {``, false}, + } + for _, c := range cases { + if got := activityETagMatches(c.header, `"abc"`); got != c.want { + t.Errorf("activityETagMatches(%q) = %v, want %v", c.header, got, c.want) + } + } +} + +// The spoke's activity block and ack decode field-for-field on the hub. +func TestSpokeActivityWireCompat(t *testing.T) { + in := spoke.HeartbeatPayload{HiveID: "h", Activity: activityDigest("o/a", 1)} + raw, err := json.Marshal(in) + if err != nil { + t.Fatal(err) + } + var out HeartbeatPayload + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatal(err) + } + if out.Activity == nil || out.Activity.ETag != in.Activity.ETag || len(out.Activity.Items) != 1 || out.Activity.Items[0].Repo != "o/a" { + t.Fatalf("activity lost on the wire: %+v", out.Activity) + } + + // A spoke predating the block sends nothing: the field stays nil. + raw, err = json.Marshal(spoke.HeartbeatPayload{HiveID: "h"}) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), `"activity"`) { + t.Fatalf("an empty activity block must be omitted: %s", raw) + } + + ackRaw, err := json.Marshal(HeartbeatResponse{OK: true, ActivityETag: `W/"e"`}) + if err != nil { + t.Fatal(err) + } + var ack spoke.HeartbeatResponse + if err := json.Unmarshal(ackRaw, &ack); err != nil || ack.ActivityETag != `W/"e"` { + t.Fatalf("spoke did not decode the ack: %+v err=%v", ack, err) + } +} diff --git a/src/pkg/hub/heartbeat.go b/src/pkg/hub/heartbeat.go index 3725b885ea..9f6ce240af 100644 --- a/src/pkg/hub/heartbeat.go +++ b/src/pkg/hub/heartbeat.go @@ -8,6 +8,7 @@ import ( "github.com/hivecommons/hive/crux" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/hub/spoke" + "github.com/hivecommons/hive/pkg/hubactivity" "github.com/hivecommons/hive/pkg/inferencehealth" "github.com/hivecommons/hive/pkg/nous" "github.com/hivecommons/hive/pkg/tracing" @@ -353,6 +354,10 @@ type HeartbeatPayload struct { Evidence *HeartbeatEvidence `json:"evidence,omitempty"` // SelfExperimentsOptIn is local consent; absent or false means opted out. SelfExperimentsOptIn bool `json:"self_experiments_opt_in,omitempty"` + // Activity is the optional bounded activity digest (#15861/#15951). + // Absent from older or non-participating spokes; the hub re-sanitizes it + // and keeps it in memory only (activityStore). + Activity *hubactivity.Digest `json:"activity,omitempty"` } const ( @@ -467,6 +472,10 @@ type HeartbeatResponse struct { SigVersion int `json:"sig_v,omitempty"` // SelfExperimentFlag is authoritative: nil/absent withdraws any prior assignment. SelfExperimentFlag *nous.SelfFlagAssignment `json:"self_experiment_flag,omitempty"` + // ActivityETag acknowledges the activity digest the hub now holds for + // this hive ("" = none). A spoke whose etag differs sends its full + // digest instead of an unchanged marker on the next beat. + ActivityETag string `json:"activity_etag,omitempty"` } // HubBanner is a message from the hub admin displayed on spoke dashboards. diff --git a/src/pkg/hub/server.go b/src/pkg/hub/server.go index 6d1aec9212..41afe151ce 100644 --- a/src/pkg/hub/server.go +++ b/src/pkg/hub/server.go @@ -999,6 +999,7 @@ type HubServer struct { registry Registry mu sync.RWMutex logger *slog.Logger + activity activityStore // per-hive activity digests, memory only (#15951); leaf lock saveCh chan struct{} githubActivityFeed *GitHubActivityFeed githubActivityMu sync.Mutex @@ -1722,6 +1723,9 @@ func NewHubServer(port int, logger *slog.Logger, gitHash, gitBranch string) *Hub s.mux.HandleFunc("GET /api/fleet-stats", s.handleFleetStats) s.mux.HandleFunc("GET "+complianceRollupPath, s.requireAdmin(s.handleComplianceRollup)) s.mux.HandleFunc("GET "+evidencePath, s.requireAdmin(s.handleEvidence)) + // Hub-wide activity (#15951): any signed-in user, scoped per hive inside + // the handler; read-only. + s.mux.HandleFunc("GET "+activityPath, s.requireAuth(s.handleHubActivity)) s.mux.HandleFunc("GET "+evidenceReportPath, s.requireAdmin(s.handleEvidenceReport)) s.mux.HandleFunc("GET /api/gh-rate-limits", s.requireAdmin(s.handleGHRateLimits)) s.mux.HandleFunc("GET /api/hub/version", s.handleHubVersion) @@ -2728,6 +2732,10 @@ func (s *HubServer) handleHeartbeat(w http.ResponseWriter, r *http.Request) { s.registry.UpdatedAt = time.Now().UTC().Format(time.RFC3339) s.mu.Unlock() + // Activity digest (#15951): stored after s.mu is released (leaf lock), + // only once the beat is authenticated and accepted into the registry. + activityAck := s.activity.record(payload.HiveID, payload.Activity, time.Now().UTC()) + // Timeline: record whatever changed on this beat. Nothing is written when // nothing changed, which is the common case — at ~2 min per beat and 42 // hives, an event per beat would be pure noise. @@ -2815,6 +2823,7 @@ func (s *HubServer) handleHeartbeat(w http.ResponseWriter, r *http.Request) { LatestSHA: latestSHA, } resp.SelfExperimentFlag = s.selfExperimentFlagForHeartbeat(payload.HiveID, payload.SelfExperimentsOptIn) + resp.ActivityETag = activityAck if entry.IsPublic != payload.IsPublic { resp.IsPublic = &entry.IsPublic diff --git a/src/pkg/hub/spoke/heartbeat.go b/src/pkg/hub/spoke/heartbeat.go index 7cb5a851bf..efd0ab086b 100644 --- a/src/pkg/hub/spoke/heartbeat.go +++ b/src/pkg/hub/spoke/heartbeat.go @@ -26,6 +26,7 @@ import ( "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/fleetreport" "github.com/hivecommons/hive/pkg/hivestate" + "github.com/hivecommons/hive/pkg/hubactivity" "github.com/hivecommons/hive/pkg/inferencehealth" "github.com/hivecommons/hive/pkg/nous" spokesig "github.com/hivecommons/hive/pkg/spoke" @@ -1161,6 +1162,10 @@ type HeartbeatPayload struct { FreshAgentStats bool `json:"fresh_agent_stats,omitempty"` // SelfExperimentsOptIn is local consent; absent or false means opted out. SelfExperimentsOptIn bool `json:"self_experiments_opt_in,omitempty"` + // Activity is the optional bounded activity digest for the hub-wide + // Activity Monitor (#15861/#15951). Nil until the publisher (#15963) + // populates it; omitempty keeps the beat unchanged meanwhile. + Activity *hubactivity.Digest `json:"activity,omitempty"` } const ( @@ -2856,6 +2861,9 @@ type HeartbeatResponse struct { SigVersion int `json:"sig_v,omitempty"` // SelfExperimentFlag is authoritative: nil/absent withdraws any prior assignment. SelfExperimentFlag *nous.SelfFlagAssignment `json:"self_experiment_flag,omitempty"` + // ActivityETag is the activity digest etag the hub acknowledged ("" = + // it holds none), decoded from hub.HeartbeatResponse.ActivityETag. + ActivityETag string `json:"activity_etag,omitempty"` } // HubBanner is a message from the hub admin displayed on spoke dashboards. diff --git a/src/pkg/hubactivity/hubactivity.go b/src/pkg/hubactivity/hubactivity.go new file mode 100644 index 0000000000..97bb2f7acd --- /dev/null +++ b/src/pkg/hubactivity/hubactivity.go @@ -0,0 +1,366 @@ +// Package hubactivity is the wire contract for the bounded, read-only +// activity digest a spoke attaches to its hub heartbeat (RFC +// hivecommons/hive#15861, first slice #15951). Both ends import it, so the +// spoke's builder and the hub's re-validation share one set of ceilings and +// one urgency order. +// +// The digest is visibility-only: it names items (repo, number, title, +// stage, modifiers) the spoke tracker already shows, never tokens, pane text +// or settings. Private-repository items are dropped by the builder unless +// the spoke opts in, but they are always counted in Totals so the numbers +// stay honest. The hub enforces the same ceilings again (Sanitize) because a +// spoke's payload is untrusted input. +package hubactivity + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "regexp" + "slices" + "strconv" + "strings" + "time" + "unicode" +) + +const ( + // DefaultMaxItems is the item cap when the spoke configures none. + DefaultMaxItems = 100 + // MaxItemsCeiling is the finite server-side ceiling: no configuration + // can make a digest carry more items, and the hub truncates anything + // beyond it on receipt. + MaxItemsCeiling = 250 + // MaxTitleRunes bounds an item title. + MaxTitleRunes = 200 + // MaxModsPerItem bounds the modifier pills on one item. + MaxModsPerItem = 8 + // MaxTotalsKeys bounds each Totals breakdown map. + MaxTotalsKeys = 64 + // maxTokenRunes bounds short identifier fields (repo, kind, stage, mod). + maxTokenRunes = 120 + // maxCount bounds every spoke-claimed integer so totals cannot + // overflow or go negative. + maxCount = 1_000_000_000 +) + +var ( + // repoPattern is GitHub's owner/name shape; rows naming anything else + // are dropped so a consumer can build links from Repo safely. + repoPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$`) + // slugPattern bounds stage and modifier slugs. + slugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]{0,63}$`) + allowedKinds = []string{"issue", "pr"} + allowedAuthorKinds = []string{"human", "clanker", "hive"} +) + +// Modifier names that drive urgency ordering. They match the stage +// tracker's modifier pills. +const ( + ModNeedsHuman = "needs-human" + ModNeedsDecision = "needs-decision" + ModStalled = "stalled" +) + +// Item is one open issue or PR in the digest. +type Item struct { + Repo string `json:"repo"` + Number int `json:"n"` + Kind string `json:"kind"` + Title string `json:"title"` + // AuthorKind is human / clanker / hive ("" = unknown). + AuthorKind string `json:"author_kind,omitempty"` + // Stage is the stage slug; StageNumber its pipeline number, used to + // order "furthest stage first" when the cap bites. + Stage string `json:"stage"` + StageNumber int `json:"stage_n,omitempty"` + Since *time.Time `json:"since,omitempty"` + Mods []string `json:"mods,omitempty"` + Private bool `json:"private,omitempty"` +} + +// Totals counts every tracked item, including private ones and ones the +// cap dropped. +type Totals struct { + Items int `json:"items"` + ByStage map[string]int `json:"by_stage,omitempty"` + ByModifier map[string]int `json:"by_modifier,omitempty"` +} + +// Digest is the heartbeat `activity` block. A digest carrying only ETag and +// GeneratedAt is an "unchanged" marker: the spoke's content matches the +// etag the hub last acknowledged. +type Digest struct { + GeneratedAt time.Time `json:"generated_at"` + ETag string `json:"etag"` + Totals *Totals `json:"totals,omitempty"` + Items []Item `json:"items,omitempty"` + // Truncated is how many eligible items the cap left out. + Truncated int `json:"truncated,omitempty"` +} + +// IsUnchangedMarker reports whether d only re-asserts a previously sent +// etag. +func (d Digest) IsUnchangedMarker() bool { + return d.ETag != "" && d.Totals == nil && len(d.Items) == 0 && d.Truncated == 0 +} + +// BuildOptions configures Build. +type BuildOptions struct { + // MaxItems is the item cap; <= 0 means DefaultMaxItems and values above + // MaxItemsCeiling are clamped to it. + MaxItems int + // SharePrivate keeps private-repository items (still marked Private). + SharePrivate bool + Now time.Time +} + +// EffectiveMaxItems clamps a configured cap to (0, MaxItemsCeiling]. +func EffectiveMaxItems(configured int) int { + if configured <= 0 { + return DefaultMaxItems + } + return min(configured, MaxItemsCeiling) +} + +// Build produces a bounded digest from the spoke's tracked items. It does +// not modify items. +func Build(items []Item, opts BuildOptions) Digest { + totals := countTotals(items) + eligible := make([]Item, 0, len(items)) + seen := map[string]bool{} + for _, it := range items { + if it.Private && !opts.SharePrivate { + continue + } + if n, ok := normalizeItem(it); ok && !seen[itemKey(n)] { + seen[itemKey(n)] = true + eligible = append(eligible, n) + } + } + slices.SortStableFunc(eligible, CompareUrgency) + limit := EffectiveMaxItems(opts.MaxItems) + truncated := 0 + if len(eligible) > limit { + truncated = len(eligible) - limit + eligible = eligible[:limit] + } + d := Digest{GeneratedAt: opts.Now.UTC(), Totals: totals, Items: eligible, Truncated: truncated} + d.ETag = ContentETag(d) + return d +} + +// Sanitize re-applies every ceiling to a digest received from a spoke. It +// drops malformed rows (repo not owner/name, no number) and duplicate +// repo#n rows, truncates to MaxItemsCeiling and adds the overflow to +// Truncated, bounds titles, tokens, modifiers and every integer, and caps +// the Totals maps. The input is not modified. +func Sanitize(d Digest) Digest { + out := Digest{GeneratedAt: d.GeneratedAt.UTC(), ETag: CleanETag(d.ETag), Truncated: clampCount(d.Truncated)} + if d.Totals != nil { + out.Totals = &Totals{ + Items: clampCount(d.Totals.Items), + ByStage: boundCounts(d.Totals.ByStage), + ByModifier: boundCounts(d.Totals.ByModifier), + } + } + seen := map[string]bool{} + for _, it := range d.Items { + n, ok := normalizeItem(it) + if !ok || seen[itemKey(n)] { + continue + } + seen[itemKey(n)] = true + if len(out.Items) == MaxItemsCeiling { + out.Truncated = clampCount(out.Truncated + 1) + continue + } + out.Items = append(out.Items, n) + } + return out +} + +// CleanETag bounds a spoke-supplied etag the same way Sanitize stores it, +// so an unchanged marker compares against the stored form. +func CleanETag(etag string) string { + return cleanToken(etag) +} + +// ContentETag is a weak etag over a digest's content, independent of +// GeneratedAt so an unchanged tracker keeps its etag across beats. +func ContentETag(d Digest) string { + body, err := json.Marshal(struct { + Totals *Totals `json:"t"` + Items []Item `json:"i"` + Truncated int `json:"x"` + }{d.Totals, d.Items, d.Truncated}) + if err != nil { + // Marshalling plain structs cannot fail; never emit an etag that + // could match a different body. + return "" + } + sum := sha256.Sum256(body) + return `W/"` + hex.EncodeToString(sum[:8]) + `"` +} + +func countTotals(items []Item) *Totals { + byStage := map[string]int{} + byMod := map[string]int{} + for _, it := range items { + if s := slug(it.Stage); s != "" { + byStage[s]++ + } + for _, m := range it.Mods { + if m = slug(m); m != "" { + byMod[m]++ + } + } + } + return &Totals{Items: len(items), ByStage: boundCounts(byStage), ByModifier: boundCounts(byMod)} +} + +// boundCounts copies m keeping at most MaxTotalsKeys sanitized keys (the +// lexically smallest, so the result is deterministic). +func boundCounts(m map[string]int) map[string]int { + keys := make([]string, 0, len(m)) + for k := range m { + if cleanToken(k) != "" { + keys = append(keys, k) + } + } + if len(keys) == 0 { + return nil + } + slices.Sort(keys) + out := make(map[string]int, min(len(keys), MaxTotalsKeys)) + for _, k := range keys { + ck := cleanToken(k) + if _, seen := out[ck]; !seen && len(out) == MaxTotalsKeys { + break + } + out[ck] = clampCount(out[ck] + clampCount(m[k])) + } + return out +} + +func clampCount(n int) int { + return min(max(n, 0), maxCount) +} + +func itemKey(it Item) string { + return strings.ToLower(it.Repo) + "#" + strconv.Itoa(it.Number) +} + +// normalizeItem bounds and validates one row; ok is false for a row that +// must be dropped (repo not owner/name, or no positive number). +func normalizeItem(it Item) (Item, bool) { + out := it + out.Repo = cleanToken(it.Repo) + if !repoPattern.MatchString(out.Repo) || it.Number <= 0 || it.Number > maxCount { + return Item{}, false + } + out.Kind = oneOf(cleanToken(it.Kind), allowedKinds) + out.AuthorKind = oneOf(cleanToken(it.AuthorKind), allowedAuthorKinds) + out.Stage = slug(it.Stage) + out.StageNumber = clampCount(it.StageNumber) + out.Title = cleanText(it.Title, MaxTitleRunes) + if it.Since != nil { + s := it.Since.UTC() + out.Since = &s + } + out.Mods = nil + for _, m := range it.Mods { + if len(out.Mods) == MaxModsPerItem { + break + } + if m = slug(m); m != "" { + out.Mods = append(out.Mods, m) + } + } + return out, true +} + +// oneOf returns v when it is one of allowed, else "". +func oneOf(v string, allowed []string) string { + if slices.Contains(allowed, v) { + return v + } + return "" +} + +// slug returns s when it is a valid stage/modifier slug, else "". +func slug(s string) string { + s = strings.TrimSpace(s) + if slugPattern.MatchString(s) { + return s + } + return "" +} + +// urgencyRank: 0 needs a human or a decision, 1 stalled, 2 everything else. +func urgencyRank(it Item) int { + rank := 2 + for _, m := range it.Mods { + switch m { + case ModNeedsHuman, ModNeedsDecision: + return 0 + case ModStalled: + rank = 1 + } + } + return rank +} + +// CompareUrgency orders items most urgent first: needs-human or +// needs-decision, then stalled, then furthest stage, then oldest in stage, +// then repo and number so the order is total and deterministic. +func CompareUrgency(a, b Item) int { + if ra, rb := urgencyRank(a), urgencyRank(b); ra != rb { + return ra - rb + } + if a.StageNumber != b.StageNumber { + return b.StageNumber - a.StageNumber + } + if c := compareSince(a.Since, b.Since); c != 0 { + return c + } + if c := strings.Compare(a.Repo, b.Repo); c != 0 { + return c + } + return a.Number - b.Number +} + +// compareSince orders older first; an unknown time sorts last. +func compareSince(a, b *time.Time) int { + switch { + case a == nil && b == nil: + return 0 + case a == nil: + return 1 + case b == nil: + return -1 + } + return a.Compare(*b) +} + +func cleanToken(s string) string { + return cleanText(strings.TrimSpace(s), maxTokenRunes) +} + +// cleanText drops control and format characters and caps the rune count. +// Titles are rendered as text on the hub; this only bounds them. +func cleanText(s string, maxRunes int) string { + var b strings.Builder + n := 0 + for _, r := range s { + if n == maxRunes { + break + } + if unicode.IsControl(r) || unicode.In(r, unicode.Cf, unicode.Zl, unicode.Zp) { + continue + } + b.WriteRune(r) + n++ + } + return b.String() +} diff --git a/src/pkg/hubactivity/hubactivity_test.go b/src/pkg/hubactivity/hubactivity_test.go new file mode 100644 index 0000000000..8f5f110fce --- /dev/null +++ b/src/pkg/hubactivity/hubactivity_test.go @@ -0,0 +1,221 @@ +package hubactivity + +import ( + "fmt" + "strings" + "testing" + "time" +) + +var t0 = time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC) + +func item(repo string, n int, stage string, stageN int, mods ...string) Item { + since := t0.Add(-time.Duration(n) * time.Minute) + return Item{Repo: repo, Number: n, Kind: "pr", Title: fmt.Sprintf("item %d", n), Stage: stage, StageNumber: stageN, Since: &since, Mods: mods} +} + +func numbers(items []Item) []int { + out := make([]int, len(items)) + for i, it := range items { + out[i] = it.Number + } + return out +} + +func TestBuild_DefaultCapIs100AndDisclosesTruncation(t *testing.T) { + var in []Item + for i := 1; i <= 143; i++ { + in = append(in, item("o/r", i, "actionable", 10)) + } + + d := Build(in, BuildOptions{Now: t0}) + + if len(d.Items) != DefaultMaxItems { + t.Fatalf("items = %d, want %d", len(d.Items), DefaultMaxItems) + } + if d.Truncated != 43 { + t.Fatalf("truncated = %d, want 43", d.Truncated) + } + if d.Totals == nil || d.Totals.Items != 143 || d.Totals.ByStage["actionable"] != 143 { + t.Fatalf("totals = %+v, want 143 actionable", d.Totals) + } +} + +func TestBuild_MaxItemsIsClampedToCeiling(t *testing.T) { + var in []Item + for i := 1; i <= MaxItemsCeiling+50; i++ { + in = append(in, item("o/r", i, "actionable", 10)) + } + + d := Build(in, BuildOptions{Now: t0, MaxItems: MaxItemsCeiling * 10}) + + if len(d.Items) != MaxItemsCeiling || d.Truncated != 50 { + t.Fatalf("items=%d truncated=%d, want %d/50", len(d.Items), d.Truncated, MaxItemsCeiling) + } +} + +func TestBuild_UrgencyOrdering(t *testing.T) { + in := []Item{ + item("o/r", 1, "pr_open", 50), + item("o/r", 2, "ci_review", 70), + item("o/r", 3, "actionable", 10, ModStalled), + item("o/r", 4, "actionable", 10, ModNeedsDecision), + item("o/r", 5, "triage", 15, ModNeedsHuman), + } + + d := Build(in, BuildOptions{Now: t0, MaxItems: 4}) + + // needs-human/needs-decision first (furthest stage within the rank: 5 is + // at 15, 4 at 10), then stalled, then furthest stage. + got := numbers(d.Items) + want := []int{5, 4, 3, 2} + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("order = %v, want %v", got, want) + } + if d.Truncated != 1 { + t.Fatalf("truncated = %d, want 1", d.Truncated) + } +} + +func TestBuild_PrivateItemsDroppedButCounted(t *testing.T) { + priv := item("o/secret", 9, "ci_review", 70) + priv.Private = true + in := []Item{item("o/r", 1, "actionable", 10), priv} + + d := Build(in, BuildOptions{Now: t0}) + + for _, it := range d.Items { + if it.Private || it.Repo == "o/secret" { + t.Fatalf("private item leaked into digest: %+v", it) + } + } + if d.Totals.Items != 2 || d.Totals.ByStage["ci_review"] != 1 { + t.Fatalf("totals must count private items: %+v", d.Totals) + } + if d.Truncated != 0 { + t.Fatalf("a private drop is not truncation, got %d", d.Truncated) + } +} + +func TestBuild_SharePrivateKeepsPrivateItems(t *testing.T) { + priv := item("o/secret", 9, "ci_review", 70) + priv.Private = true + + d := Build([]Item{priv}, BuildOptions{Now: t0, SharePrivate: true}) + + if len(d.Items) != 1 || !d.Items[0].Private { + t.Fatalf("share_private should keep the item marked private: %+v", d.Items) + } +} + +func TestBuild_ETagStableAcrossTimeAndChangesWithContent(t *testing.T) { + in := []Item{item("o/r", 1, "actionable", 10)} + + a := Build(in, BuildOptions{Now: t0}) + b := Build(in, BuildOptions{Now: t0.Add(time.Hour)}) + in[0].Stage = "ci_review" + c := Build(in, BuildOptions{Now: t0}) + + if a.ETag == "" || !strings.HasPrefix(a.ETag, `W/"`) { + t.Fatalf("etag %q is not a weak etag", a.ETag) + } + if a.ETag != b.ETag { + t.Fatalf("etag must not depend on generated_at: %q vs %q", a.ETag, b.ETag) + } + if a.ETag == c.ETag { + t.Fatalf("etag must change when content changes") + } +} + +func TestBuild_DoesNotMutateInput(t *testing.T) { + in := []Item{item("o/r", 2, "actionable", 10), item("o/r", 1, "ci_review", 70)} + in[0].Title = strings.Repeat("x", MaxTitleRunes+10) + + Build(in, BuildOptions{Now: t0}) + + if in[0].Number != 2 || len(in[0].Title) != MaxTitleRunes+10 { + t.Fatalf("Build mutated its input: %+v", in[0]) + } +} + +func TestSanitize_EnforcesHubCeilingAndBounds(t *testing.T) { + d := Digest{GeneratedAt: t0, ETag: `W/"x"`, Totals: &Totals{Items: 1}} + for i := 1; i <= MaxItemsCeiling+7; i++ { + it := item("o/r", i, "actionable", 10) + it.Title = "a\x00b\nc" + strings.Repeat("é", MaxTitleRunes) + it.Mods = []string{"m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8", "m9", "m10"} + d.Items = append(d.Items, it) + } + d.Items = append(d.Items, Item{Repo: "", Number: 1}, Item{Repo: "o/r", Number: 0}) + + got := Sanitize(d) + + if len(got.Items) != MaxItemsCeiling { + t.Fatalf("items = %d, want ceiling %d", len(got.Items), MaxItemsCeiling) + } + // 7 over the ceiling; the 2 malformed rows are discarded, not counted. + if got.Truncated != 7 { + t.Fatalf("truncated = %d, want 7", got.Truncated) + } + it := got.Items[0] + if strings.ContainsAny(it.Title, "\x00\n") { + t.Fatalf("control characters survived: %q", it.Title) + } + if n := len([]rune(it.Title)); n > MaxTitleRunes { + t.Fatalf("title runes = %d, want <= %d", n, MaxTitleRunes) + } + if len(it.Mods) != MaxModsPerItem { + t.Fatalf("mods = %d, want %d", len(it.Mods), MaxModsPerItem) + } + if len(d.Items[0].Mods) != 10 { + t.Fatalf("Sanitize mutated its input") + } +} + +func TestSanitize_ValidatesTokensAndDedupes(t *testing.T) { + d := Digest{ETag: `W/"x"`, Truncated: -5, Totals: &Totals{Items: -1, ByStage: map[string]int{"a": maxCount}, ByModifier: map[string]int{"m": -3}}} + d.Items = []Item{ + {Repo: "o/r", Number: 1, Kind: "pr", AuthorKind: "hive", Stage: "ci_review", Mods: []string{"stalled", "", "Bad Mod"}, StageNumber: -9}, + {Repo: "O/R", Number: 1, Kind: "pr"}, // duplicate of o/r#1 + {Repo: "javascript:alert(1)", Number: 2, Kind: "pr"}, // not owner/name + {Repo: "o/../x", Number: 3}, // not owner/name + {Repo: "o/r", Number: 4, Kind: "