From 8c86a601b0fcef61cf1b7b8fdcb4d2fb5a76340e Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 28 Oct 2026 20:07:13 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Audit=20contributor=20tier=20cha?= =?UTF-8?q?nges=20and=20refresh=20parked=20PRs'=20role=20tier=20each=20swe?= =?UTF-8?q?ep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every contributor trust-tier change (operator PUT /trust and /revoke, newcomer→contributor auto-promotion, registration) now appends {tier, prev, at, by, reason, source} to the profile's tier_history and writes a contributor-tier-changed audit event; same-tier writes are no-ops. GET /api/contributors exposes tier_history and the Contributors view shows "tier since … · by … · reason" on the tier chip. The contributor lane's prefilter path (needs-rebase/hold/excluded/draft) returned before admitContributor, so parked PRs never had a role noted and ResolveStage fell back to the role/* label a previous pass wrote, with trusted kept sticky on weak stages. The lane now notes the current registry tier on that path too, and a fresh lane tier beats a stale label unless the lane merely cannot vouch for the author. Fixes #15177 Signed-off-by: Andrew Anderson --- changelog.d/fixed-contributor-tier-history.md | 1 + src/docs/contributor-trust-and-roles.md | 19 ++ src/pkg/dashboard/audit.go | 1 + src/pkg/dashboard/contribute_admin.go | 36 ++- src/pkg/dashboard/contribute_profiles.go | 122 ++++++++- .../dashboard/contribute_tier_history_test.go | 252 ++++++++++++++++++ src/pkg/dashboard/contribute_tokens.go | 10 + src/pkg/dashboard/contribute_ws.go | 20 +- src/pkg/dashboard/static/index.html | 26 +- .../automerge/automerge_contributor_lane.go | 26 ++ ...erge_contributor_lane_tier_refresh_test.go | 133 +++++++++ src/pkg/stageengine/derive_pr_classify.go | 16 +- 12 files changed, 640 insertions(+), 22 deletions(-) create mode 100644 changelog.d/fixed-contributor-tier-history.md create mode 100644 src/pkg/dashboard/contribute_tier_history_test.go create mode 100644 src/pkg/github/automerge/automerge_contributor_lane_tier_refresh_test.go diff --git a/changelog.d/fixed-contributor-tier-history.md b/changelog.d/fixed-contributor-tier-history.md new file mode 100644 index 0000000000..4a63094376 --- /dev/null +++ b/changelog.d/fixed-contributor-tier-history.md @@ -0,0 +1 @@ +- Every contributor trust-tier change (operator trust/revoke, newcomer→contributor auto-promotion, registration) now appends `{tier, prev, at, by, reason, source}` to the contributor's `tier_history`, writes a `contributor-tier-changed` audit event, and is shown as "tier since … · by … · reason" on the Contributors view and in `GET /api/contributors`; same-tier writes are no-ops. The stage lane re-reads the author's registry tier every sweep — including for PRs parked on needs-rebase/hold/excluded labels — so a promotion or demotion reaches parked PRs on the next pass instead of sticking to the stale `role/*` label ([#15177](https://github.com/hivecommons/hive/issues/15177)). diff --git a/src/docs/contributor-trust-and-roles.md b/src/docs/contributor-trust-and-roles.md index fe552b41a0..fb10254e9a 100644 --- a/src/docs/contributor-trust-and-roles.md +++ b/src/docs/contributor-trust-and-roles.md @@ -19,6 +19,25 @@ Contributor profiles carry a `trust_tier` field. The current tier order is: | `merger` | maintainer/owner grant; it is not auto-promoted | May queue **other people's** PRs for Hive's auto-merge-on-green flow. | | `advisor` | maintainer/owner grant | Advisory/invite tier; it is not ordered above `merger` for role-claim checks. | +### Who changed a tier, when and why + +Every tier change — operator dropdown or `PUT /api/contributors/{id}/trust` +(optional `reason`), `POST /api/contributors/{id}/revoke`, the +newcomer→contributor auto-promotion, and the initial `newcomer` at +registration — appends `{tier, prev, at, by, reason, source}` to the +contributor record's `tier_history` (`by` is the operator login, +`hive:auto-promotion` or `hive:registration`; capped at the latest 50) and +writes an `audit.jsonl` event with `action: "contributor-tier-changed"` +carrying the same fields. Setting the tier a contributor already holds is a +no-op: no history entry, no audit line. `GET /api/contributors` returns +`tier_history`, and the Contributors view shows the current tier's provenance +("trusted since … · by … · reason") under and on hover of the tier chip. + +The stage lane re-reads the author's registry tier on every sweep, including +for PRs parked on `needs-rebase`/hold/excluded labels, so a promotion or +demotion reaches every open PR on the next pass instead of sticking to the +`role/*` label a previous pass wrote. + The merger tier is deliberately **never allowed to own its own merge**. Queueing a PR as `merger` or `owner` is rejected when the authenticated dashboard user matches the PR author, and the auto-merge sweep re-checks the queued-by user before merging. Task leases are also the unit for staged runs. A staged run stays on the same diff --git a/src/pkg/dashboard/audit.go b/src/pkg/dashboard/audit.go index 2c2aa46e51..12a7c729f8 100644 --- a/src/pkg/dashboard/audit.go +++ b/src/pkg/dashboard/audit.go @@ -104,6 +104,7 @@ var auditSensitiveActions = map[string]bool{ "config_governor_work_source": true, "config_review": true, "config_write_surface": true, + "contributor-tier-changed": true, "copilot_auth_logout": true, "copilot_auth_start": true, "copilot_token_missing": true, diff --git a/src/pkg/dashboard/contribute_admin.go b/src/pkg/dashboard/contribute_admin.go index 6f74f59952..50b954d9a0 100644 --- a/src/pkg/dashboard/contribute_admin.go +++ b/src/pkg/dashboard/contribute_admin.go @@ -123,18 +123,28 @@ func (s *Server) handleContributorTrust(w http.ResponseWriter, r *http.Request) return } var req struct { - Tier string `json:"tier"` + Tier string `json:"tier"` + Reason string `json:"reason,omitempty"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { jsonError(w, "Invalid request", http.StatusBadRequest) return } - validTiers := map[string]bool{"newcomer": true, "contributor": true, "trusted": true, "merger": true, "advisor": true, "revoked": true} + validTiers := map[string]bool{contributorTierNewcomer: true, contributorTierContributor: true, contributorTierTrusted: true, contributorTierMerger: true, contributorTierAdvisor: true, contributorTierRevoked: true} if !validTiers[req.Tier] { jsonError(w, "Invalid tier", http.StatusBadRequest) return } - p.TrustTier = req.Tier + reason := strings.TrimSpace(req.Reason) + if reason == "" { + reason = "operator set tier" + } + change, changed := applyContributorTierChange(p, req.Tier, requestUser(r), reason, tierChangeSourceOperator, time.Now()) + if !changed { + // Same tier: nothing to persist, no history entry, no audit event. + jsonResponse(w, map[string]any{"ok": true, "trust_tier": p.TrustTier, "unchanged": true}) + return + } // H2: admin path — adminOverride lets this change a terminal (revoked) tier and // wins the CAS reconcile against any concurrent stale WS save. The write is // server-authoritative. @@ -142,6 +152,7 @@ func (s *Server) handleContributorTrust(w http.ResponseWriter, r *http.Request) jsonError(w, "Failed to save", http.StatusInternalServerError) return } + s.auditContributorTierChange(p, change) // H2: if this change revokes access, fence any live WebSocket sessions the // contributor holds so an in-flight connection cannot keep working (or keep // saving a stale "contributor" profile) after the revoke. @@ -151,8 +162,8 @@ func (s *Server) handleContributorTrust(w http.ResponseWriter, r *http.Request) s.contributeHub.DisconnectContributor(p.ContributorID, "contribution access revoked") } } - s.logger.Info("contributor tier changed", "username", p.GitHubUsername, "tier", req.Tier) - jsonResponse(w, map[string]any{"ok": true, "trust_tier": req.Tier}) + s.logger.Info("contributor tier changed", "username", p.GitHubUsername, "tier", req.Tier, "prev", change.Prev, "by", change.By, "reason", change.Reason) + jsonResponse(w, map[string]any{"ok": true, "trust_tier": req.Tier, "tier_change": change}) } func (s *Server) handleContributorAgentRoleGrants(w http.ResponseWriter, r *http.Request) { @@ -346,7 +357,7 @@ func (s *Server) handleContributorRevoke(w http.ResponseWriter, r *http.Request) jsonError(w, "Contributor not found", http.StatusNotFound) return } - p.TrustTier = "revoked" + change, changed := applyContributorTierChange(p, contributorTierRevoked, requestUser(r), "operator revoked contribution access", tierChangeSourceOperator, time.Now()) // H2: admin path — adminOverride wins the CAS reconcile so this revoke cannot be // silently clobbered by a concurrent stale WS save, and the tier is now // server-authoritative and terminal for any later non-admin write. @@ -354,6 +365,9 @@ func (s *Server) handleContributorRevoke(w http.ResponseWriter, r *http.Request) jsonError(w, "Failed to save", http.StatusInternalServerError) return } + if changed { + s.auditContributorTierChange(p, change) + } // H2: fence live sessions — close any WebSocket connections this contributor // holds so an in-flight session cannot keep working, keep minting credentials, or // keep saving a stale non-revoked profile after the revoke lands. @@ -455,3 +469,13 @@ func (s *Server) handleContributorDelete(w http.ResponseWriter, r *http.Request) s.logger.Info("contributor deleted", "username", p.GitHubUsername) jsonResponse(w, map[string]any{"ok": true, "deleted": p.GitHubUsername}) } + +// auditContributorTierChange writes the audit.jsonl event that pairs with a +// TierHistory entry: user = who moved the tier (operator login or the hive +// writer), agent = the contributor id, detail = the same fields as the entry. +func (s *Server) auditContributorTierChange(p *ContributorProfile, change ContributorTierChange) { + if s == nil || s.audit == nil || p == nil { + return + } + s.audit.Log(change.By, auditActionContributorTierChanged, tierChangeAuditDetail(p.GitHubUsername, change), p.ContributorID) +} diff --git a/src/pkg/dashboard/contribute_profiles.go b/src/pkg/dashboard/contribute_profiles.go index f448a2678a..9da54675fb 100644 --- a/src/pkg/dashboard/contribute_profiles.go +++ b/src/pkg/dashboard/contribute_profiles.go @@ -144,12 +144,18 @@ type ContributorProfile struct { TokenRotationDue bool `json:"token_rotation_due,omitempty"` TokenPlain string `json:"registration_token_plain,omitempty"` TrustTier string `json:"trust_tier"` - PreferredRole string `json:"preferred_role,omitempty"` - CLIBackend string `json:"cli_backend,omitempty"` - Model string `json:"model,omitempty"` - ReasoningEffort string `json:"reasoning_effort,omitempty"` - KnowledgeLoaded *bool `json:"knowledge_loaded,omitempty"` - KnowledgeError string `json:"knowledge_error,omitempty"` + // TierHistory is the append-only provenance of TrustTier: one entry per + // real change (registration, operator set/revoke, auto-promotion) naming + // who moved the tier, when, from what and why. It is what answers "who + // changed this contributor to trusted?" — every writer goes through + // applyContributorTierChange, which also refuses to record a no-op. + TierHistory []ContributorTierChange `json:"tier_history,omitempty"` + PreferredRole string `json:"preferred_role,omitempty"` + CLIBackend string `json:"cli_backend,omitempty"` + Model string `json:"model,omitempty"` + ReasoningEffort string `json:"reasoning_effort,omitempty"` + KnowledgeLoaded *bool `json:"knowledge_loaded,omitempty"` + KnowledgeError string `json:"knowledge_error,omitempty"` // AdvisorModel / AdvisorEffort: the last-reported second model that // reviewed this contributor's work (hivecommons/hive#7760). Display only. AdvisorModel string `json:"advisor_model,omitempty"` @@ -401,20 +407,21 @@ func listContributorProfiles() []ContributorProfile { func createContributorProfile(username string, policies ...contributorTokenPolicy) (*ContributorProfile, string) { cid := "c-" + randomHex(6) token := randomHex(32) + now := time.Now().UTC() p := &ContributorProfile{ GitHubUsername: username, ContributorID: cid, RegistrationToken: sha256Hex(token), TokenPlain: token, - TrustTier: "newcomer", - RegisteredAt: time.Now().UTC().Format(time.RFC3339), + RegisteredAt: now.Format(time.RFC3339), RateLimits: ContributorRateLimits{ MaxConcurrent: 1, MaxPerHour: 3, MaxPerDay: 10, }, } - policyOrDefault(policies).issue(p, time.Now().UTC()) + applyContributorTierChange(p, contributorTierNewcomer, tierChangeByRegistration, "self-registered", tierChangeSourceRegistration, now) + policyOrDefault(policies).issue(p, now) _ = saveContributorProfile(p) return p, token } @@ -500,3 +507,100 @@ func reissueContributorToken(p *ContributorProfile, policies ...contributorToken } return newToken } + +// Trust tier names the registry stores. The admin handler validates against +// this set; the lane and relay read the raw string. +const ( + contributorTierNewcomer = "newcomer" + contributorTierContributor = "contributor" + contributorTierTrusted = "trusted" + contributorTierMerger = "merger" + contributorTierAdvisor = "advisor" + contributorTierRevoked = "revoked" +) + +// Actors and sources recorded on a ContributorTierChange. By is an operator +// login for operator changes; these constants cover the machine writers. +const ( + tierChangeByAutoPromotion = "hive:auto-promotion" + tierChangeByRegistration = "hive:registration" + + tierChangeSourceOperator = "operator" + tierChangeSourceAutoPromotion = "auto-promotion" + tierChangeSourceRegistration = "registration" + + // contributorTierHistoryMax bounds the per-profile history; a tier is + // changed by hand a handful of times over a contributor's life, so the + // oldest entries are dropped only under pathological churn. + contributorTierHistoryMax = 50 + // contributorTierReasonMax bounds the operator-supplied reason text. + contributorTierReasonMax = 240 +) + +// auditActionContributorTierChanged is the audit.jsonl action every tier +// change writes, alongside the TierHistory entry on the profile. +const auditActionContributorTierChanged = "contributor-tier-changed" + +// ContributorTierChange is one entry of ContributorProfile.TierHistory. +type ContributorTierChange struct { + Tier string `json:"tier"` + Prev string `json:"prev,omitempty"` + At string `json:"at"` + By string `json:"by"` + Reason string `json:"reason,omitempty"` + Source string `json:"source"` +} + +// applyContributorTierChange moves p to tier and records the change on +// TierHistory. It returns the entry and true when the tier actually changed; +// a write of the tier the profile already holds is a no-op that touches +// neither TrustTier nor the history, so repeated saves never spam it. +func applyContributorTierChange(p *ContributorProfile, tier, by, reason, source string, now time.Time) (ContributorTierChange, bool) { + if p == nil { + return ContributorTierChange{}, false + } + tier = strings.ToLower(strings.TrimSpace(tier)) + if tier == "" || tier == p.TrustTier { + return ContributorTierChange{}, false + } + reason = strings.TrimSpace(sanitizeString(reason)) + if len(reason) > contributorTierReasonMax { + reason = reason[:contributorTierReasonMax] + } + ch := ContributorTierChange{ + Tier: tier, + Prev: p.TrustTier, + At: now.UTC().Format(time.RFC3339), + By: strings.TrimSpace(by), + Reason: reason, + Source: source, + } + p.TrustTier = tier + p.TierHistory = append(p.TierHistory, ch) + if n := len(p.TierHistory); n > contributorTierHistoryMax { + p.TierHistory = append([]ContributorTierChange(nil), p.TierHistory[n-contributorTierHistoryMax:]...) + } + return ch, true +} + +// currentTierChange is the history entry that set the tier the profile holds +// now, or false when the tier predates history (legacy profile) or the +// history was rewritten past it. +func currentTierChange(p *ContributorProfile) (ContributorTierChange, bool) { + if p == nil { + return ContributorTierChange{}, false + } + for i := len(p.TierHistory) - 1; i >= 0; i-- { + if p.TierHistory[i].Tier == p.TrustTier { + return p.TierHistory[i], true + } + } + return ContributorTierChange{}, false +} + +// tierChangeAuditDetail is the audit.jsonl detail for a tier change: the +// same fields as the TierHistory entry, in the key=value form the rest of +// the log uses. +func tierChangeAuditDetail(username string, ch ContributorTierChange) string { + return auditDetail("username", username, "tier", ch.Tier, "prev", ch.Prev, "by", ch.By, "reason", ch.Reason, "source", ch.Source) +} diff --git a/src/pkg/dashboard/contribute_tier_history_test.go b/src/pkg/dashboard/contribute_tier_history_test.go new file mode 100644 index 0000000000..920a95999c --- /dev/null +++ b/src/pkg/dashboard/contribute_tier_history_test.go @@ -0,0 +1,252 @@ +package dashboard + +import ( + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// Every writer that moves a contributor's trust tier must leave a +// TierHistory entry on the profile and a contributor-tier-changed audit +// event naming who, when, from what and why — the question "who changed +// @login to trusted?" was unanswerable before (registry held only the bare +// tier; audit.jsonl had no tier event). + +func TestApplyContributorTierChangeRecordsProvenanceAndSkipsNoOps(t *testing.T) { + now := time.Date(2026, 10, 27, 13, 59, 0, 0, time.UTC) + p := &ContributorProfile{GitHubUsername: "thatguywob", TrustTier: contributorTierContributor} + + ch, changed := applyContributorTierChange(p, contributorTierTrusted, "clubanderson", "20+ verified PRs", tierChangeSourceOperator, now) + if !changed { + t.Fatal("contributor -> trusted must be a change") + } + if p.TrustTier != contributorTierTrusted || len(p.TierHistory) != 1 { + t.Fatalf("profile after change: tier=%q history=%d", p.TrustTier, len(p.TierHistory)) + } + want := ContributorTierChange{Tier: "trusted", Prev: "contributor", At: "2026-10-27T13:59:00Z", By: "clubanderson", Reason: "20+ verified PRs", Source: "operator"} + if ch != want || p.TierHistory[0] != want { + t.Fatalf("entry = %+v, want %+v", ch, want) + } + + // Writing the tier the profile already holds is a no-op: no history + // entry, no tier touch. + if _, changed := applyContributorTierChange(p, "trusted", "someone-else", "again", tierChangeSourceOperator, now.Add(time.Hour)); changed { + t.Fatal("same-tier write must not be recorded") + } + if _, changed := applyContributorTierChange(p, " Trusted ", "someone-else", "again", tierChangeSourceOperator, now.Add(time.Hour)); changed { + t.Fatal("same-tier write (case/space variant) must not be recorded") + } + if len(p.TierHistory) != 1 { + t.Fatalf("history grew on a no-op: %+v", p.TierHistory) + } + + cur, ok := currentTierChange(p) + if !ok || cur != want { + t.Fatalf("currentTierChange = %+v/%v", cur, ok) + } + if _, ok := currentTierChange(&ContributorProfile{TrustTier: "trusted"}); ok { + t.Fatal("legacy profile without history must report no provenance") + } +} + +func TestApplyContributorTierChangeBoundsHistoryAndReason(t *testing.T) { + p := &ContributorProfile{TrustTier: contributorTierNewcomer} + now := time.Now() + tiers := []string{contributorTierContributor, contributorTierNewcomer} + for i := 0; i < contributorTierHistoryMax+7; i++ { + applyContributorTierChange(p, tiers[i%2], "op", strings.Repeat("x", contributorTierReasonMax+50), tierChangeSourceOperator, now) + } + if len(p.TierHistory) != contributorTierHistoryMax { + t.Fatalf("history len = %d, want capped at %d", len(p.TierHistory), contributorTierHistoryMax) + } + if got := len(p.TierHistory[0].Reason); got != contributorTierReasonMax { + t.Fatalf("reason len = %d, want %d", got, contributorTierReasonMax) + } + // The newest entry is the last one and matches the tier held now. + if last := p.TierHistory[len(p.TierHistory)-1]; last.Tier != p.TrustTier { + t.Fatalf("last entry %+v does not match tier %q", last, p.TrustTier) + } +} + +func TestRegistrationSeedsTierHistory(t *testing.T) { + setupContributeEnv(t) + p, _ := createContributorProfile("newbie") + saved, err := loadContributorProfile(p.GitHubUsername) + if err != nil { + t.Fatal(err) + } + if saved.TrustTier != contributorTierNewcomer || len(saved.TierHistory) != 1 { + t.Fatalf("registered profile: tier=%q history=%+v", saved.TrustTier, saved.TierHistory) + } + if e := saved.TierHistory[0]; e.Tier != "newcomer" || e.Prev != "" || e.By != tierChangeByRegistration || e.Source != tierChangeSourceRegistration { + t.Fatalf("registration entry = %+v", e) + } +} + +func readAuditActions(t *testing.T, s *Server, action string) []AuditEntry { + t.Helper() + var out []AuditEntry + for _, e := range s.audit.Recent(100) { + if e.Action == action { + out = append(out, e) + } + } + return out +} + +func TestOperatorTrustChangeWritesHistoryAndAudit(t *testing.T) { + setupContributeEnv(t) + if err := saveContributorProfile(&ContributorProfile{GitHubUsername: "alice", ContributorID: "c-alice", TrustTier: "contributor"}); err != nil { + t.Fatal(err) + } + s := NewServer(0, slog.Default()) + s.registerContributeRoutes() + + put := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPut, "/api/contributors/alice/trust", strings.NewReader(body)) + req.SetPathValue("id", "alice") + req.Header.Set("X-Hive-User", "clubanderson") + markOwnerRequest(req) + w := httptest.NewRecorder() + s.handleContributorTrust(w, req) + return w + } + + if w := put(`{"tier":"trusted","reason":"20 clean PRs"}`); w.Code != http.StatusOK { + t.Fatalf("PUT trust = %d %s", w.Code, w.Body.String()) + } + p := findContributor("alice") + if p == nil || p.TrustTier != "trusted" || len(p.TierHistory) != 1 { + t.Fatalf("after PUT: %+v", p) + } + e := p.TierHistory[0] + if e.Prev != "contributor" || e.By != "clubanderson" || e.Reason != "20 clean PRs" || e.Source != tierChangeSourceOperator || e.At == "" { + t.Fatalf("history entry = %+v", e) + } + events := readAuditActions(t, s, auditActionContributorTierChanged) + if len(events) != 1 { + t.Fatalf("audit events = %+v, want exactly one", events) + } + if events[0].User != "clubanderson" || events[0].Agent != "c-alice" { + t.Fatalf("audit event = %+v", events[0]) + } + for _, want := range []string{"username=alice", "tier=trusted", "prev=contributor", "by=clubanderson", "reason=20 clean PRs", "source=operator"} { + if !strings.Contains(events[0].Detail, want) { + t.Fatalf("audit detail %q missing %q", events[0].Detail, want) + } + } + + // Same tier again: 200, nothing recorded. + if w := put(`{"tier":"trusted"}`); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"unchanged":true`) { + t.Fatalf("no-op PUT = %d %s", w.Code, w.Body.String()) + } + if p := findContributor("alice"); len(p.TierHistory) != 1 { + t.Fatalf("no-op PUT grew history: %+v", p.TierHistory) + } + if got := readAuditActions(t, s, auditActionContributorTierChanged); len(got) != 1 { + t.Fatalf("no-op PUT wrote audit: %+v", got) + } + + // GET /api/contributors exposes the history. + rec := doOwnerGet(s, "/api/contributors") + var listed struct { + Contributors []ContributorProfile `json:"contributors"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listed); err != nil { + t.Fatalf("decode: %v %s", err, rec.Body.String()) + } + if len(listed.Contributors) != 1 || len(listed.Contributors[0].TierHistory) != 1 || listed.Contributors[0].TierHistory[0].By != "clubanderson" { + t.Fatalf("GET /api/contributors = %s", rec.Body.String()) + } +} + +func TestOperatorRevokeWritesHistoryAndAudit(t *testing.T) { + setupContributeEnv(t) + if err := saveContributorProfile(&ContributorProfile{GitHubUsername: "bob", ContributorID: "c-bob", TrustTier: "trusted"}); err != nil { + t.Fatal(err) + } + s := NewServer(0, slog.Default()) + s.registerContributeRoutes() + req := httptest.NewRequest(http.MethodPost, "/api/contributors/bob/revoke", nil) + req.SetPathValue("id", "bob") + req.Header.Set("X-Hive-User", "clubanderson") + markOwnerRequest(req) + w := httptest.NewRecorder() + s.handleContributorRevoke(w, req) + if w.Code != http.StatusOK { + t.Fatalf("revoke = %d %s", w.Code, w.Body.String()) + } + p := findContributor("bob") + if p == nil || p.TrustTier != "revoked" || len(p.TierHistory) != 1 || p.TierHistory[0].Prev != "trusted" || p.TierHistory[0].By != "clubanderson" { + t.Fatalf("after revoke: %+v", p) + } + if got := readAuditActions(t, s, auditActionContributorTierChanged); len(got) != 1 || !strings.Contains(got[0].Detail, "tier=revoked") { + t.Fatalf("audit = %+v", got) + } +} + +func TestAutoPromotionWritesHistoryAndAudit(t *testing.T) { + setupContributeEnv(t) + s := NewServer(0, slog.Default()) + h := NewContributeWSHub(slog.Default(), s) + profile := &ContributorProfile{GitHubUsername: "carol", ContributorID: "c-carol", TrustTier: "newcomer", TasksWithPR: contributorAutoPromoteAt - 1} + if err := saveContributorProfile(profile); err != nil { + t.Fatal(err) + } + c := &ContributorConnection{profile: profile} + + var promotion ContributorTierChange + user, promoted, err := saveConnectionContributorProfile(c, func(p *ContributorProfile) bool { + p.TasksWithPR++ + if p.TrustTier == contributorTierNewcomer && p.TasksWithPR >= contributorAutoPromoteAt { + ch, changed := applyContributorTierChange(p, contributorTierContributor, tierChangeByAutoPromotion, "threshold", tierChangeSourceAutoPromotion, time.Now()) + promotion = ch + return changed + } + return false + }) + if err != nil || !promoted || user != "carol" { + t.Fatalf("save: user=%q promoted=%v err=%v", user, promoted, err) + } + h.auditTierChange(user, promotion) + + saved, err := loadContributorProfile("carol") + if err != nil { + t.Fatal(err) + } + if saved.TrustTier != "contributor" || len(saved.TierHistory) != 1 || saved.TierHistory[0].By != tierChangeByAutoPromotion || saved.TierHistory[0].Source != tierChangeSourceAutoPromotion { + t.Fatalf("saved = %+v", saved) + } + // The live connection's copy carries the history too. + if len(c.profile.TierHistory) != 1 { + t.Fatalf("connection profile history = %+v", c.profile.TierHistory) + } + got := readAuditActions(t, s, auditActionContributorTierChanged) + if len(got) != 1 || got[0].User != tierChangeByAutoPromotion || !strings.Contains(got[0].Detail, "prev=newcomer") { + t.Fatalf("audit = %+v", got) + } +} + +func TestSetContributorTrustTierCarriesHistoryToLiveConnections(t *testing.T) { + setupContributeEnv(t) + s := NewServer(0, slog.Default()) + h := NewContributeWSHub(slog.Default(), s) + disk := &ContributorProfile{GitHubUsername: "dave", ContributorID: "c-dave", TrustTier: "contributor"} + applyContributorTierChange(disk, "trusted", "clubanderson", "r", tierChangeSourceOperator, time.Now()) + if err := saveContributorProfileCAS(disk, true); err != nil { + t.Fatal(err) + } + live := &ContributorConnection{profile: &ContributorProfile{GitHubUsername: "dave", ContributorID: "c-dave", TrustTier: "contributor"}} + h.mu.Lock() + h.connections["conn-1"] = live + h.mu.Unlock() + + h.SetContributorTrustTier("c-dave", "trusted") + if live.profile.TrustTier != "trusted" || len(live.profile.TierHistory) != 1 || live.profile.TierHistory[0].By != "clubanderson" { + t.Fatalf("live profile = %+v", live.profile) + } +} diff --git a/src/pkg/dashboard/contribute_tokens.go b/src/pkg/dashboard/contribute_tokens.go index d152c94c22..bf6d4bb4ca 100644 --- a/src/pkg/dashboard/contribute_tokens.go +++ b/src/pkg/dashboard/contribute_tokens.go @@ -34,6 +34,16 @@ func (h *ContributeWSHub) auditRelayAs(user, agent, action string, task *WSTaskA h.server.AuditLogRecord(user, action, agentaudit.FormatAuditDetail(agentaudit.Fields(kv...)), agent, repo, number) } +// auditTierChange writes the contributor-tier-changed audit event for a tier +// the hub itself moved (auto-promotion); the operator handlers write theirs +// through Server.auditContributorTierChange. +func (h *ContributeWSHub) auditTierChange(username string, change ContributorTierChange) { + if h == nil || h.server == nil || h.server.audit == nil || username == "" || change.Tier == "" { + return + } + h.server.audit.Log(change.By, auditActionContributorTierChanged, tierChangeAuditDetail(username, change), "") +} + // auditRelayText bounds relay-supplied free text before it lands in a detail. func auditRelayText(s string) string { return sanitizeCapabilityField(sanitizeString(s)) diff --git a/src/pkg/dashboard/contribute_ws.go b/src/pkg/dashboard/contribute_ws.go index b4127838b3..0ca6e2c8c3 100644 --- a/src/pkg/dashboard/contribute_ws.go +++ b/src/pkg/dashboard/contribute_ws.go @@ -2286,8 +2286,10 @@ func (h *ContributeWSHub) SetContributorTrustTier(contributorID, tier string) { return } version := 0 + var history []ContributorTierChange if p := findContributor(contributorID); p != nil { version = p.Version + history = append([]ContributorTierChange(nil), p.TierHistory...) } h.mu.RLock() var targets []*ContributorConnection @@ -2304,6 +2306,9 @@ func (h *ContributeWSHub) SetContributorTrustTier(contributorID, tier string) { c.mu.Lock() if c.profile != nil { c.profile.TrustTier = tier + if history != nil { + c.profile.TierHistory = history + } if version != 0 { c.profile.Version = version } @@ -3127,6 +3132,7 @@ func cloneContributorProfileForSave(p *ContributorProfile) *ContributorProfile { v := *p.CurrentTask cp.CurrentTask = &v } + cp.TierHistory = append([]ContributorTierChange(nil), p.TierHistory...) cp.LabelInterests = append([]string(nil), p.LabelInterests...) cp.AgentRoleGrants = append([]string(nil), p.AgentRoleGrants...) cp.Specializations = append([]string(nil), p.Specializations...) @@ -3140,6 +3146,7 @@ func refreshConnectionContributorProfile(dst, saved *ContributorProfile) { return } dst.TrustTier = saved.TrustTier + dst.TierHistory = append([]ContributorTierChange(nil), saved.TierHistory...) dst.TasksCompleted = saved.TasksCompleted dst.TasksWithPR = saved.TasksWithPR dst.TasksFailed = saved.TasksFailed @@ -4159,6 +4166,7 @@ func (s *wsSession) handleTaskComplete(msg WSMessage) { promotedModel := s.contributor.model promotedEffort := s.contributor.reasoningEffort countCompletion := !isEvidenceLessCompletion(verifiedPR, verdict, msg.CompletionSignal) + var promotion ContributorTierChange promotedUser, promoted, saveErr := saveConnectionContributorProfile(s.contributor, func(p *ContributorProfile) bool { if countCompletion { p.TasksCompleted++ @@ -4181,9 +4189,12 @@ func (s *wsSession) handleTaskComplete(msg WSMessage) { // Completion is self-reported, so counting bare task_complete // messages — or unverified PR URLs — would hand out contents:write // and pulls:write for work that was never shown to exist. - if p.TrustTier == "newcomer" && p.TasksWithPR >= contributorAutoPromoteAt { - p.TrustTier = "contributor" - return true + if p.TrustTier == contributorTierNewcomer && p.TasksWithPR >= contributorAutoPromoteAt { + ch, changed := applyContributorTierChange(p, contributorTierContributor, tierChangeByAutoPromotion, + fmt.Sprintf("%d verified PR tasks reached the auto-promotion threshold (%d)", p.TasksWithPR, contributorAutoPromoteAt), + tierChangeSourceAutoPromotion, time.Now()) + promotion = ch + return changed } return false }) @@ -4197,7 +4208,8 @@ func (s *wsSession) handleTaskComplete(msg WSMessage) { // Read-only signalling — it changes no control behaviour and is // emitted only on the real newcomer -> contributor transition. if promoted { - h.logger.Info("[contribute-ws] auto-promoted", "username", promotedUser) + h.logger.Info("[contribute-ws] auto-promoted", "username", promotedUser, "tier", promotion.Tier, "prev", promotion.Prev, "reason", promotion.Reason) + h.auditTierChange(promotedUser, promotion) h.addActivity(promotedUser, "promoted", "contributor", promotedCLI, promotedModel, promotedEffort, "contributor") } } else { diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index ab3bbf7d7c..cb63e44bc2 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -35697,6 +35697,26 @@ return `${esc(tier || 'unknown')}`; } + // tierProvenance answers "who set this tier, when and why" from the + // contributor's tier_history (GET /api/contributors): the newest entry + // whose tier matches the current one. Empty when the registry predates + // tier history, so the chip stays plain rather than inventing a source. + function tierProvenance(c) { + const hist = Array.isArray(c && c.tier_history) ? c.tier_history : []; + const cur = String((c && c.trust_tier) || '').toLowerCase(); + for (let i = hist.length - 1; i >= 0; i--) { + const h = hist[i]; + if (!h || String(h.tier || '').toLowerCase() !== cur) continue; + const whenText = h.at ? formatDashboardDateTime(h.at, undefined, h.at) : ''; + const parts = [`${cur} since ${whenText}`]; + if (h.by) parts.push(`by ${h.by}`); + if (h.reason) parts.push(h.reason); + if (h.prev) parts.push(`(was ${h.prev})`); + return parts.join(' · '); + } + return ''; + } + /* ---- Clickable user avatars --------------------------------------- Every face on this dashboard links to that person's GitHub profile, so the avatar itself is the affordance rather than a separate glyph or a @@ -36035,15 +36055,17 @@ ? 'eligible for trusted' : ''; const login = c.github_username || ''; + const tierProv = tierProvenance(c); const initialTint = contribTintReadCache(login) || contribTintFallback(login); return `
${avatarHtml} @${esc(c.github_username)} - ${trustTierBadge(c.trust_tier)} + ${trustTierBadge(c.trust_tier)} ${trustedEligibleBadge}
+ ${tierProv ? `
${esc(tierProv)}
` : ''} ${cliLine ? `
${cliLine}${roleLine ? ' · ' + roleLine : ''}
` : (roleLine ? `
${roleLine}
` : '')}
Completed: ${c.total_tasks_completed || 0} @@ -36168,7 +36190,7 @@ const res = await fetch(`/api/contributors/${contributorId}/trust`, { method: 'PUT', headers: _inceptionAuthHeaders(), - body: JSON.stringify({ tier: tier }), + body: JSON.stringify({ tier: tier, reason: 'operator set tier from the Contributors view' }), }); if (!res.ok) { const err = await res.json().catch(() => ({})); await hiveAlert('Failed to change tier: ' + (err.error || res.statusText)); return; } fetchContributors(); diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 3ef3443014..02a2a3c787 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -641,6 +641,30 @@ func (c *Engine) admitContributor(ctx context.Context, owner, repo string, pr *g return match, err } +// noteRegistryRole records the author's CURRENT registry tier as the PR's +// role for this cycle without the deep admission pass. The lane short-cuts +// a parked PR (needs-rebase, hold, excluded label, draft) before +// admitContributor runs, and without this the stage pass fell back to the +// role/ label the PR already carried — a tier the operator changed in +// the registry never reached a parked PR, so two PRs by one author showed +// different tiers (hivecommons/hive: #14822 vs #14947). The lookup is a +// local registry read, so it is cheap enough for every sweep; an author +// with no profile notes nothing and keeps the marker/label evidence. +func (c *Engine) noteRegistryRole(owner, repo string, number int, author string, policy ContributorLanePolicy) { + if c == nil || c.contributorRegistryTier == nil { + return + } + author = strings.TrimSpace(strings.TrimPrefix(author, "@")) + if author == "" { + return + } + tier, ok := c.contributorRegistryTier(author) + if !ok { + return + } + c.noteStageRole(owner, repo, number, stagelabels.RoleFromTier(tier, policy.RequireTiers)) +} + // observedRegistryTier returns the author's raw registry tier for labelling, // regardless of whether the policy lets the registry admit them. func (c *Engine) observedRegistryTier(author string) string { @@ -1190,6 +1214,8 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own if reason := c.prefilterContributorLanePR(pr, policy); reason != "" { if reason == contributorLaneReasonAppAuthored { c.noteStageRole(owner, repo, number, stagelabels.RoleTrusted) + } else { + c.noteRegistryRole(owner, repo, number, hgithub.SafeGetLogin(pr.GetUser()), policy) } return contributorLaneEval{pr: pr}, reason, nil } diff --git a/src/pkg/github/automerge/automerge_contributor_lane_tier_refresh_test.go b/src/pkg/github/automerge/automerge_contributor_lane_tier_refresh_test.go new file mode 100644 index 0000000000..7be1deda81 --- /dev/null +++ b/src/pkg/github/automerge/automerge_contributor_lane_tier_refresh_test.go @@ -0,0 +1,133 @@ +package automerge + +import ( + "context" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// A parked contributor PR (needs-rebase, hold, excluded label) short-cuts +// the lane before admitContributor runs, so the stage pass used to fall back +// to the role/ label a previous pass wrote and a registry tier change +// never reached it: hivecommons/hive#14822 (needs-rebase, stale role) and +// #14947 (deep-evaluated each sweep, fresh role) by the same author showed +// different tiers. The lane now notes the CURRENT registry tier on the +// prefilter path too, every sweep. +func TestContributorLanePrefilteredPRNotesCurrentRegistryTierEachSweep(t *testing.T) { + fx := validContributorFixture() + fx.labels = []string{"needs-rebase", "role/contributor"} + api := newContributorLaneAPI(t, &fx) + defer api.Close() + policy := defaultContributorLanePolicy() + policy.RegistryTiersSufficient = true + clock := &contributorLaneClock{at: time.Date(2026, 10, 28, 17, 59, 0, 0, time.UTC)} + tiers := map[string]string{contributorLaneTestAuthor: "contributor"} + tracker := NewStageTracker() + engine := newContributorLaneEngine(api.URL, policy, clock, Options{ + ContributorRegistryTier: registryTiers(tiers), + StageTracker: tracker, + StageLabelPolicy: func() StageLabelPolicy { return StageLabelPolicy{Enabled: true} }, + }) + ctx := context.Background() + key := stageKey("acme", "widget", 7) + + roleNoted := func() stagelabels.Role { + tracker.mu.Lock() + defer tracker.mu.Unlock() + return tracker.details[key].Role + } + + _, reason, err := engine.trySweepContributorLanePR(ctx, "widget", "acme", "widget", 7, policy) + if err != nil || reason != "label:needs-rebase" { + t.Fatalf("parked pass reason=%q err=%v, want the prefilter short-cut", reason, err) + } + if got := roleNoted(); got != stagelabels.RoleContributor { + t.Fatalf("role noted on the parked pass = %v, want contributor (registry)", got) + } + + // The operator promotes the author in the registry. Nothing else about + // the PR changes — it is still parked on needs-rebase — yet the very + // next sweep must carry the new tier. + tiers[contributorLaneTestAuthor] = "trusted" + tracker.drain() + if _, reason, err = engine.trySweepContributorLanePR(ctx, "widget", "acme", "widget", 7, policy); err != nil || reason != "label:needs-rebase" { + t.Fatalf("second parked pass reason=%q err=%v", reason, err) + } + if got := roleNoted(); got != stagelabels.RoleTrusted { + t.Fatalf("role noted after promotion = %v, want trusted: the parked PR kept a stale tier", got) + } + + // And a demotion is picked up the same way. + tiers[contributorLaneTestAuthor] = "newcomer" + tracker.drain() + if _, _, err = engine.trySweepContributorLanePR(ctx, "widget", "acme", "widget", 7, policy); err != nil { + t.Fatal(err) + } + if got := roleNoted(); got != stagelabels.RoleNewcomer { + t.Fatalf("role noted after demotion = %v, want newcomer", got) + } + + // An author with no registry profile notes nothing on the prefilter + // path: the marker/label evidence stays authoritative for them. + delete(tiers, contributorLaneTestAuthor) + tracker.drain() + if _, _, err = engine.trySweepContributorLanePR(ctx, "widget", "acme", "widget", 7, policy); err != nil { + t.Fatal(err) + } + if got := roleNoted(); got != stagelabels.RoleNone { + t.Fatalf("role noted for an unregistered author = %v, want none", got) + } +} + +// The stage pass must let a tier a lane read from the registry THIS pass +// beat the role/ label a previous pass wrote — on weak stages too, where +// the label used to be merged first and a trusted label stuck through a +// demotion. A lane that merely cannot vouch for the author (untrusted) still +// does not override a label another lane wrote (#13637 flapping guard). +func TestResolveStageFreshLaneTierBeatsStaleRoleLabelOnWeakStage(t *testing.T) { + cases := []struct { + name string + list []stageObservation + want stagelabels.Role + }{ + { + name: "demotion: trusted label, registry now contributor", + list: []stageObservation{ + {Lane: stageLaneTrusted, Reason: "untrusted-author-role", Labels: []string{"role/trusted", "needs-rebase"}}, + {Lane: stageLaneContributor, Reason: "label:needs-rebase", Labels: []string{"role/trusted", "needs-rebase"}, Detail: stageDetail{Role: stagelabels.RoleContributor}}, + }, + want: stagelabels.RoleContributor, + }, + { + name: "promotion: contributor label, registry now trusted", + list: []stageObservation{ + {Lane: stageLaneTrusted, Reason: "untrusted-author-role", Labels: []string{"role/contributor", "needs-rebase"}}, + {Lane: stageLaneContributor, Reason: "label:needs-rebase", Labels: []string{"role/contributor", "needs-rebase"}, Detail: stageDetail{Role: stagelabels.RoleTrusted}}, + }, + want: stagelabels.RoleTrusted, + }, + { + name: "cannot-vouch does not demote a label another lane wrote", + list: []stageObservation{ + {Lane: stageLaneContributor, Reason: contributorLaneReasonNoClaim, Labels: []string{"role/trusted"}, Detail: stageDetail{Role: stagelabels.RoleUntrusted}}, + }, + want: stagelabels.RoleTrusted, + }, + { + name: "no lane tier keeps the label", + list: []stageObservation{ + {Lane: stageLaneTrusted, Reason: "untrusted-author-role", Labels: []string{"role/contributor"}}, + }, + want: stagelabels.RoleContributor, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if _, got, _ := resolveStage(tc.list); got != tc.want { + t.Fatalf("role = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/src/pkg/stageengine/derive_pr_classify.go b/src/pkg/stageengine/derive_pr_classify.go index 4aa049e61b..d211c675b5 100644 --- a/src/pkg/stageengine/derive_pr_classify.go +++ b/src/pkg/stageengine/derive_pr_classify.go @@ -547,6 +547,9 @@ func ResolveStage(list []stageObservation) (stageVerdict, stagelabels.Role, stag var best stageVerdict var bestObs stageObservation role := stagelabels.RoleNone + // weakLabelRole is the tier the PR already carries as seen by lanes + // with no owning opinion this pass. + weakLabelRole := stagelabels.RoleNone for _, o := range list { v := ClassifyStage(o) if v.Rank > best.Rank { @@ -556,13 +559,24 @@ func ResolveStage(list []stageObservation) (stageVerdict, stagelabels.Role, stag role = role.Merge(stagelabels.RoleTrusted) } if v.Rank < stageRankOwned { - role = role.Merge(stagelabels.RoleOf(o.Labels)) + weakLabelRole = weakLabelRole.Merge(stagelabels.RoleOf(o.Labels)) } // The most specific tier wins: the contributor lane knows // registry/claim tiers the trusted-author lane cannot see, so a // trusted-author "trusted" is kept but its absence is refined. role = role.Merge(o.Detail.Role) } + // A lane that merely cannot vouch for the author (untrusted: no profile, + // no claim) has nothing to say against the tier another lane wrote on + // the PR earlier — a maintainer stays role/trusted when only the + // contributor lane looked this pass. A KNOWN tier a lane read from the + // registry this pass is different evidence and is kept: it outranks the + // label a previous pass wrote, so a registry change (promotion or + // demotion) reaches the PR on the next sweep instead of the stale + // role/ sticking (hivecommons/hive #14822 vs #14947). + if role == stagelabels.RoleNone || role == stagelabels.RoleUntrusted { + role = role.Merge(weakLabelRole) + } // No lane reported a tier this pass (the contributor lane's deep // evaluation does not run every cycle): keep the tier the PR already // carries instead of dropping it, which flapped role/trusted (#13637).