reputation.gno
9.63 Kb · 376 lines
1package agentmarketplace
2
3import (
4 "chain"
5 "strconv"
6 "time"
7
8 "gno.land/p/nt/avl/v0"
9)
10
11// Reputation tunables.
12const (
13 minRatedForTrust = 3
14 halfLifeDays = 45
15 posterCapBps = 2000 // 20% target cap; raised to 1/N when fewer posters
16 weightUnit = 1000 // reviewer weight scale; 1000 = 1.0
17 decayScale = 1000000
18 scoreScale = 1000 // milli-stars; 5000 = 5.000
19 maxRatings = 20000
20 maxReviewerBonus = 2000 // extra weight cap in weightUnit
21)
22
23var (
24 nextRatingID = 1
25
26 ratings = avl.NewTree() // padID(id) -> *Rating
27 ratingsByAgent = avl.NewTree() // agent + "/" + padID(id) -> *Rating
28 ratingByTask = avl.NewTree() // padID(taskID) -> ratingID
29 scores = avl.NewTree() // agent.String() -> *AgentScore
30 scoreboard = avl.NewTree() // scoreKey -> agent address
31 posterStats = avl.NewTree() // poster.String() -> *PosterStats
32 posterAgents = avl.NewTree() // poster + "/" + agent -> true
33)
34
35// Rate records the task poster's 1-5 review of a settled job. Only the
36// poster may rate, only after escrow has paid out, only once, and never
37// their own agent. The score is weighted by the task budget, the poster's
38// reviewer weight, a 45-day half-life, and a 20% cap on any one poster's
39// influence on the agent.
40func Rate(cur realm, taskID, score int, comment string) int {
41 caller := mustUserCall(cur)
42 t := mustGetTask(taskID)
43 if t.Status != StatusCompleted || !t.Settled {
44 panic("only a settled, completed task can be rated")
45 }
46 if t.Poster != caller {
47 panic("only the task poster can rate this job")
48 }
49 if t.Winner == caller {
50 panic("you cannot rate your own agent")
51 }
52 if ratingByTask.Get(padID(taskID)) != nil {
53 panic("this task has already been rated")
54 }
55 checkScore(score)
56 checkComment(comment)
57 if ratings.Size() >= maxRatings {
58 panic("the rating board is full")
59 }
60
61 now := time.Now()
62 wt := currentReviewerWeight(caller)
63 r := &Rating{
64 ID: nextRatingID,
65 TaskID: taskID,
66 Agent: t.Winner,
67 Poster: caller,
68 Score: score,
69 Comment: comment,
70 BudgetUgnot: t.BudgetUgnot,
71 ReviewerWt: wt,
72 RatedAt: now,
73 }
74 nextRatingID++
75 ratings.Set(padID(r.ID), r)
76 ratingsByAgent.Set(r.Agent.String()+"/"+padID(r.ID), r)
77 ratingByTask.Set(padID(taskID), r.ID)
78
79 chain.Emit("RatingCast",
80 "id", strconv.Itoa(r.ID),
81 "task", strconv.Itoa(taskID),
82 "agent", r.Agent.String(),
83 "poster", caller.String(),
84 "score", strconv.Itoa(score),
85 "budgetUgnot", strconv.FormatInt(t.BudgetUgnot, 10),
86 )
87 recomputeAndStore(r.Agent, now)
88 return r.ID
89}
90
91// RefreshScore recomputes an agent's trust score at the current block
92// time, applying half-life decay. Anyone may call it.
93func RefreshScore(cur realm, agent address) {
94 mustUserCall(cur)
95 if !agent.IsValid() {
96 panic("invalid address")
97 }
98 recomputeAndStore(agent, time.Now())
99}
100
101// ScoreOf returns a live reputation lookup: rating count, trust score in
102// milli-stars (1000-5000), unweighted average in milli-stars, and whether
103// the score is still provisional (fewer than 3 rated jobs). Unrated agents
104// return (0, 0, 0, true).
105func ScoreOf(agent address) (int, int64, int64, bool) {
106 s := liveScore(agent, time.Now())
107 return s.RatedCount, s.TrustMilli, s.RawMilli, s.Provisional
108}
109
110// RatingCount is the number of ratings stored in the realm.
111func RatingCount() int { return ratings.Size() }
112
113// ReputationSummary is a one-line text score, or "" if the agent is unrated.
114func ReputationSummary(agent address) string {
115 s := liveScore(agent, time.Now())
116 if s.RatedCount == 0 {
117 return ""
118 }
119 label := "trusted"
120 if s.Provisional {
121 label = "provisional"
122 }
123 jobs := strconv.Itoa(s.RatedCount) + " jobs"
124 if s.RatedCount == 1 {
125 jobs = "1 job"
126 }
127 return fmtScore(s.TrustMilli) + " / 5 (" + label + ", " + jobs + ", raw " + fmtScore(s.RawMilli) + ")"
128}
129
130// ---------------------------------------------------------------------------
131// internals
132
133type posterBucket struct {
134 poster address
135 weight int64
136 points int64
137}
138
139func liveScore(agent address, now time.Time) *AgentScore {
140 out := &AgentScore{Agent: agent, Provisional: true}
141 var buckets []posterBucket
142 var rawSum int64
143 var last time.Time
144 prefix := agent.String() + "/"
145 ratingsByAgent.Iterate(prefix, prefix+"~", func(_ string, v any) bool {
146 r := v.(*Rating)
147 out.RatedCount++
148 rawSum += int64(r.Score)
149 if last.IsZero() || r.RatedAt.After(last) {
150 last = r.RatedAt
151 }
152 w := ratingWeight(r, now)
153 if w <= 0 {
154 return false
155 }
156 i := findBucket(buckets, r.Poster)
157 if i < 0 {
158 buckets = append(buckets, posterBucket{poster: r.Poster, weight: w, points: w * int64(r.Score)})
159 } else {
160 buckets[i].weight += w
161 buckets[i].points += w * int64(r.Score)
162 }
163 return false
164 })
165 out.LastRatedAt = last
166 if out.RatedCount == 0 {
167 return out
168 }
169 out.RawMilli = (rawSum * scoreScale) / int64(out.RatedCount)
170 out.Provisional = out.RatedCount < minRatedForTrust
171 capBuckets(buckets)
172 var denom, sum int64
173 for _, b := range buckets {
174 denom += b.weight
175 sum += b.points
176 }
177 if denom > 0 {
178 out.TrustMilli = (sum * scoreScale) / denom
179 }
180 return out
181}
182
183func ratingWeight(r *Rating, now time.Time) int64 {
184 age := now.Sub(r.RatedAt)
185 if age < 0 {
186 age = 0
187 }
188 // weight = budget * (reviewerWt / 1000) * (decay / 1e6)
189 w := r.BudgetUgnot
190 if r.ReviewerWt > 0 {
191 w = w * r.ReviewerWt / weightUnit
192 }
193 d := decayPPM(age)
194 if d <= 0 {
195 return 0
196 }
197 return w * d / decayScale
198}
199
200// decayPPM is 1e6 * 0.5^(age / 45 days), computed in integer math at
201// the current block time.
202func decayPPM(age time.Duration) int64 {
203 const halfLife = time.Duration(halfLifeDays) * 24 * time.Hour
204 if age <= 0 {
205 return decayScale
206 }
207 n := int64(age / halfLife)
208 if n >= 40 {
209 return 0
210 }
211 ppm := int64(decayScale)
212 for i := int64(0); i < n; i++ {
213 ppm /= 2
214 }
215 rem := age % halfLife
216 if rem == 0 || ppm == 0 {
217 return ppm
218 }
219 // 0.5^(rem/halfLife) ≈ 1 - ln2 f + (ln2^2/2) f^2 - (ln2^3/6) f^3
220 // with f in 1e6 and coefficients in 1e6.
221 // Convert to seconds first: rem * 1e6 overflows int64 in nanoseconds.
222 f := int64(rem/time.Second) * decayScale / int64(halfLife/time.Second)
223 const ln2 = int64(693147)
224 const c2 = int64(240226)
225 const c3 = int64(55504)
226 f2 := f * f / decayScale
227 f3 := f2 * f / decayScale
228 adj := decayScale - (ln2*f)/decayScale + (c2*f2)/decayScale - (c3*f3)/decayScale
229 if adj < decayScale/2 {
230 adj = decayScale / 2
231 }
232 if adj > decayScale {
233 adj = decayScale
234 }
235 return ppm * adj / decayScale
236}
237
238func findBucket(bs []posterBucket, poster address) int {
239 for i, b := range bs {
240 if b.poster == poster {
241 return i
242 }
243 }
244 return -1
245}
246
247// capBuckets caps one poster's share of the pre-cap weight mass. The
248// target is 20%, but the cap is also at least 1/N so two or three honest
249// posters are not all flattened to the same ceiling (a hard 20% cap cannot
250// be satisfied by five or fewer equal raters). A sole poster is uncapped.
251// Measuring against the original total (not leftover "others") keeps a
252// 1 ugnot smear from becoming the scale a trusted poster's weight is
253// measured against.
254func capBuckets(bs []posterBucket) {
255 if len(bs) < 2 {
256 return
257 }
258 var total int64
259 for _, b := range bs {
260 total += b.weight
261 }
262 if total <= 0 {
263 return
264 }
265 n := int64(len(bs))
266 maxBps := int64(posterCapBps)
267 if inv := 10000 / n; inv > maxBps {
268 maxBps = inv
269 }
270 // maxW = maxBps of the pre-cap total, rounded up
271 maxW := (total*maxBps + 9999) / 10000
272 if maxW < 1 {
273 maxW = 1
274 }
275 for i, b := range bs {
276 if b.weight > maxW {
277 if b.weight > 0 {
278 bs[i].points = bs[i].points * maxW / b.weight
279 }
280 bs[i].weight = maxW
281 }
282 }
283}
284
285func currentReviewerWeight(poster address) int64 {
286 w := int64(weightUnit)
287 v := posterStats.Get(poster.String())
288 if v == nil {
289 return w
290 }
291 ps := v.(*PosterStats)
292 d := int64(ps.DistinctAgents)
293 if d > 20 {
294 d = 20
295 }
296 w += d * 100
297 gnot := ps.SettledUgnot / ugnotPerGnot
298 if gnot > maxReviewerBonus {
299 gnot = maxReviewerBonus
300 }
301 w += gnot
302 if w > weightUnit+maxReviewerBonus {
303 w = weightUnit + maxReviewerBonus
304 }
305 return w
306}
307
308func recordPosterPayment(poster, agent address, budget int64) {
309 v := posterStats.Get(poster.String())
310 var ps *PosterStats
311 if v == nil {
312 ps = &PosterStats{Owner: poster}
313 posterStats.Set(poster.String(), ps)
314 } else {
315 ps = v.(*PosterStats)
316 }
317 key := poster.String() + "/" + agent.String()
318 if posterAgents.Get(key) == nil {
319 posterAgents.Set(key, true)
320 ps.DistinctAgents++
321 }
322 ps.SettledJobs++
323 ps.SettledUgnot += budget
324}
325
326func recomputeAndStore(agent address, now time.Time) *AgentScore {
327 s := liveScore(agent, now)
328 if prev := scores.Get(agent.String()); prev != nil {
329 old := prev.(*AgentScore)
330 scoreboard.Remove(scoreKey(old.TrustMilli, old.RatedCount, agent))
331 }
332 if s.RatedCount > 0 {
333 scores.Set(agent.String(), s)
334 scoreboard.Set(scoreKey(s.TrustMilli, s.RatedCount, agent), agent)
335 } else {
336 scores.Remove(agent.String())
337 }
338 chain.Emit("ScoreUpdated",
339 "agent", agent.String(),
340 "ratedCount", strconv.Itoa(s.RatedCount),
341 "trustMilli", strconv.FormatInt(s.TrustMilli, 10),
342 "rawMilli", strconv.FormatInt(s.RawMilli, 10),
343 "provisional", strconv.FormatBool(s.Provisional),
344 )
345 return s
346}
347
348// scoreKey sorts the highest trust first, then the most ratings, then
349// lowest address for a stable tie-break.
350func scoreKey(trustMilli int64, count int, agent address) string {
351 const ceiling = int64(9999999)
352 inv := strconv.FormatInt(ceiling-trustMilli, 10)
353 for len(inv) < 7 {
354 inv = "0" + inv
355 }
356 c := strconv.Itoa(1000000 - count)
357 for len(c) < 7 {
358 c = "0" + c
359 }
360 return inv + "/" + c + "/" + agent.String()
361}
362
363func fmtScore(milli int64) string {
364 if milli < 0 {
365 milli = 0
366 }
367 whole := milli / scoreScale
368 frac := milli % scoreScale
369 // two decimal places
370 frac = frac / 10
371 f := strconv.FormatInt(frac, 10)
372 for len(f) < 2 {
373 f = "0" + f
374 }
375 return strconv.FormatInt(whole, 10) + "." + f
376}