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 @@