| 1 | // Package advice is the instance's advice on tokens (connectors spec |
| 2 | // 2026-11-12 rev 3.2 §9, slice S4): Compute turns recorded facts into |
| 3 | // the advice that could be shown now, in one deterministic order, and |
| 4 | // the rules decide which one may show. It is pure: no store, no clock, |
| 5 | // no model. The words are the caller's fixed templates. |
| 6 | package advice |
| 7 | |
| 8 | import ( |
| 9 | "slices" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | ) |
| 16 | |
| 17 | // Version names the facts' shape and the rules below. |
| 18 | const Version = 1 |
| 19 | |
| 20 | // The thresholds (§9). |
| 21 | const ( |
| 22 | // NearBudget: a metered connection's reported spend at or past 80% |
| 23 | // of its day's or month's budget. |
| 24 | NearBudget = 0.80 |
| 25 | // NearLimit and Room: the preferred subscription has a window at or |
| 26 | // above 0.80 whose reset is more than ResetFar away; another has |
| 27 | // every window below 0.50. |
| 28 | NearLimit = 0.80 |
| 29 | Room = 0.50 |
| 30 | ResetFar = 24 * time.Hour |
| 31 | // WaitedLong: a low task held for a week. |
| 32 | WaitedLong = 7 * 24 * time.Hour |
| 33 | // Silence after the first and after a later Not now. |
| 34 | SilenceFirst = 14 * 24 * time.Hour |
| 35 | SilenceAgain = 60 * 24 * time.Hour |
| 36 | ) |
| 37 | |
| 38 | // Roles in their fixed order for advice about a role. |
| 39 | var Roles = []string{"coordinator", wire.SpecialistEngineering, wire.SpecialistReview} |
| 40 | |
| 41 | // Window is one reported rate window: used from 0 to 1 and its reset. |
| 42 | type Window struct { |
| 43 | Used float64 |
| 44 | ResetsAt *time.Time |
| 45 | } |
| 46 | |
| 47 | // Conn is one of the person's connections as the instance last heard. |
| 48 | // ID is the instance's id; Runner the runner holding it. A metered |
| 49 | // connection has its budget and reported spend in micro-units. |
| 50 | type Conn struct { |
| 51 | ID, Provider, Runner, State, Billing string |
| 52 | Windows []Window |
| 53 | SpendDay, SpendMonth int64 |
| 54 | BudgetDay, BudgetMonth int64 |
| 55 | BudgetRevision int64 |
| 56 | Currency string |
| 57 | SpendUnknown bool |
| 58 | } |
| 59 | |
| 60 | // Preference is the person's preferred provider (one for every role) |
| 61 | // and when it ends. |
| 62 | type Preference struct { |
| 63 | Provider string |
| 64 | Until *time.Time |
| 65 | Revision int64 |
| 66 | } |
| 67 | |
| 68 | // Task is one of the person's own open tasks. |
| 69 | type Task struct { |
| 70 | ID string |
| 71 | CreatedAt time.Time |
| 72 | // Priority is urgent, normal or low ("" reads normal); By its |
| 73 | // deadline. |
| 74 | Priority string |
| 75 | By *time.Time |
| 76 | Revision int64 |
| 77 | } |
| 78 | |
| 79 | // Step is one queued step of a task (held by the scheduler or not): |
| 80 | // its role, the runner it was placed on ("" not yet), and its hold. |
| 81 | type Step struct { |
| 82 | Task, Role, Runner string |
| 83 | // Hold is the hold's reason ("" not held), HoldResets the reset the |
| 84 | // hold names, HeldSince when the step was first held without a break. |
| 85 | Hold string |
| 86 | HoldResets *time.Time |
| 87 | HeldSince *time.Time |
| 88 | // Housekeeping: housekeeping's attempt, which advice never moves. |
| 89 | Housekeeping bool |
| 90 | } |
| 91 | |
| 92 | // Facts are what advice is computed from. |
| 93 | type Facts struct { |
| 94 | Conns []Conn |
| 95 | Preference Preference |
| 96 | Tasks []Task |
| 97 | Steps []Step |
| 98 | // Primary is the person's primary runner: where the preference |
| 99 | // applies to steps not yet placed. |
| 100 | Primary string |
| 101 | // Capable says whether a provider can run a role (the runner's |
| 102 | // capability table); nil: Claude and Codex run every role. |
| 103 | Capable func(provider, role string) bool |
| 104 | } |
| 105 | |
| 106 | // TaskRef is a task an action changes, at the revision it was read at. |
| 107 | type TaskRef struct { |
| 108 | ID string |
| 109 | Revision int64 |
| 110 | } |
| 111 | |
| 112 | // Advice is one eligible piece of advice with what its card says and |
| 113 | // what its one action does. |
| 114 | type Advice struct { |
| 115 | Kind string |
| 116 | Subject wire.AdviceSubject |
| 117 | Key string |
| 118 | // Ordering within a kind: the role's place, the earliest task. |
| 119 | roleRank int |
| 120 | first time.Time |
| 121 | firstTask string |
| 122 | |
| 123 | // budget_near: the connection, which budget (day or month), the |
| 124 | // spend and budget now, the raised figure, and the budget's revision. |
| 125 | Connection string |
| 126 | Window string |
| 127 | Spend, Budget int64 |
| 128 | Raise int64 |
| 129 | Currency string |
| 130 | BudgetRevision int64 |
| 131 | |
| 132 | // prefer_switch: from and to providers, until when, and the |
| 133 | // preference's revision. |
| 134 | From, To string |
| 135 | Until time.Time |
| 136 | PreferenceRevision int64 |
| 137 | |
| 138 | // defer_tasks and held_long: the tasks and, for defer_tasks, the |
| 139 | // reset the urgent work waits for. |
| 140 | Tasks []TaskRef |
| 141 | ResetsAt *time.Time |
| 142 | } |
| 143 | |
| 144 | // Day and month: which budget a budget_near names. |
| 145 | const ( |
| 146 | BudgetDay = "day" |
| 147 | BudgetMonth = "month" |
| 148 | ) |
| 149 | |
| 150 | // key is advice's key string: its kind and subject. |
| 151 | func key(kind string, s wire.AdviceSubject) string { |
| 152 | switch { |
| 153 | case len(s.Tasks) > 0: |
| 154 | return kind + ":" + strings.Join(s.Tasks, ",") |
| 155 | case s.Role != "": |
| 156 | return kind + ":" + s.Role + "/" + s.Connection |
| 157 | } |
| 158 | return kind + ":" + s.Connection |
| 159 | } |
| 160 | |
| 161 | func capable(f Facts, provider, role string) bool { |
| 162 | if f.Capable != nil { |
| 163 | return f.Capable(provider, role) |
| 164 | } |
| 165 | return wire.PreferenceProviders[provider] && provider != "" |
| 166 | } |
| 167 | |
| 168 | // live are a connection's windows that have not reset by now. |
| 169 | func live(c Conn, now time.Time) []Window { |
| 170 | var out []Window |
| 171 | for _, w := range c.Windows { |
| 172 | if w.ResetsAt != nil && !w.ResetsAt.After(now) { |
| 173 | continue |
| 174 | } |
| 175 | out = append(out, w) |
| 176 | } |
| 177 | return out |
| 178 | } |
| 179 | |
| 180 | func priorityOf(t Task) string { |
| 181 | if t.Priority == "" { |
| 182 | return wire.PriorityNormal |
| 183 | } |
| 184 | return t.Priority |
| 185 | } |
| 186 | |
| 187 | // Compute is every piece of advice whose facts hold now, in the order |
| 188 | // one is chosen: the kind's arbitration order; within a kind, a |
| 189 | // connection's id bytewise, a role's fixed place, a task set's earliest |
| 190 | // task then its first id; then the key bytewise. The same facts give |
| 191 | // the same list. |
| 192 | func Compute(f Facts, now time.Time) []Advice { |
| 193 | var out []Advice |
| 194 | out = append(out, budgetNear(f)...) |
| 195 | out = append(out, preferSwitch(f, now)...) |
| 196 | out = append(out, deferTasks(f)...) |
| 197 | out = append(out, heldLong(f, now)...) |
| 198 | seen := map[string]bool{} |
| 199 | out = slices.DeleteFunc(out, func(a Advice) bool { |
| 200 | if seen[a.Key] { |
| 201 | return true |
| 202 | } |
| 203 | seen[a.Key] = true |
| 204 | return false |
| 205 | }) |
| 206 | sort.SliceStable(out, func(i, j int) bool { return Less(out[i], out[j]) }) |
| 207 | return out |
| 208 | } |
| 209 | |
| 210 | // Less is the deterministic order (§9, finding 24). |
| 211 | func Less(a, b Advice) bool { |
| 212 | ka, kb := slices.Index(wire.AdviceKinds, a.Kind), slices.Index(wire.AdviceKinds, b.Kind) |
| 213 | if ka != kb { |
| 214 | return ka < kb |
| 215 | } |
| 216 | switch a.Kind { |
| 217 | case wire.AdviceBudgetNear: |
| 218 | if a.Subject.Connection != b.Subject.Connection { |
| 219 | return a.Subject.Connection < b.Subject.Connection |
| 220 | } |
| 221 | case wire.AdvicePreferSwitch: |
| 222 | if a.roleRank != b.roleRank { |
| 223 | return a.roleRank < b.roleRank |
| 224 | } |
| 225 | if a.Subject.Connection != b.Subject.Connection { |
| 226 | return a.Subject.Connection < b.Subject.Connection |
| 227 | } |
| 228 | default: |
| 229 | if !a.first.Equal(b.first) { |
| 230 | return a.first.Before(b.first) |
| 231 | } |
| 232 | if a.firstTask != b.firstTask { |
| 233 | return a.firstTask < b.firstTask |
| 234 | } |
| 235 | } |
| 236 | return a.Key < b.Key |
| 237 | } |
| 238 | |
| 239 | // budgetNear: a metered connection's reported spend at or past 80% of |
| 240 | // its day's budget (then of its month's), when the budget can be |
| 241 | // raised. Its action doubles that budget within the bounds; a day's |
| 242 | // budget never passes the month's. |
| 243 | func budgetNear(f Facts) []Advice { |
| 244 | var out []Advice |
| 245 | for _, c := range f.Conns { |
| 246 | if c.Billing != wire.BillingMetered || c.SpendUnknown || c.State == wire.ConnSignedOut || c.BudgetDay <= 0 || c.BudgetMonth <= 0 { |
| 247 | continue |
| 248 | } |
| 249 | a := Advice{Kind: wire.AdviceBudgetNear, Subject: wire.AdviceSubject{Connection: c.ID}, Connection: c.ID, Currency: c.Currency, BudgetRevision: c.BudgetRevision} |
| 250 | if near(c.SpendDay, c.BudgetDay) { |
| 251 | if raise := min(2*c.BudgetDay, c.BudgetMonth, wire.MaxBudgetDay); raise > c.BudgetDay { |
| 252 | a.Window, a.Spend, a.Budget, a.Raise = BudgetDay, c.SpendDay, c.BudgetDay, raise |
| 253 | } |
| 254 | } |
| 255 | if a.Window == "" && near(c.SpendMonth, c.BudgetMonth) { |
| 256 | if raise := min(2*c.BudgetMonth, wire.MaxBudgetMonth); raise > c.BudgetMonth { |
| 257 | a.Window, a.Spend, a.Budget, a.Raise = BudgetMonth, c.SpendMonth, c.BudgetMonth, raise |
| 258 | } |
| 259 | } |
| 260 | if a.Window == "" { |
| 261 | continue |
| 262 | } |
| 263 | a.Key = key(a.Kind, a.Subject) |
| 264 | out = append(out, a) |
| 265 | } |
| 266 | return out |
| 267 | } |
| 268 | |
| 269 | // near: spend at or past NearBudget of budget, in integers (no float |
| 270 | // rounding at the line). |
| 271 | func near(spend, budget int64) bool { return budget > 0 && spend*5 >= budget*4 } |
| 272 | |
| 273 | // waiting are the roles with steps held or queued, and the runners |
| 274 | // their steps were placed on (the primary for one not yet placed). |
| 275 | func waiting(f Facts) map[string]map[string]bool { |
| 276 | out := map[string]map[string]bool{} |
| 277 | for _, s := range f.Steps { |
| 278 | if s.Housekeeping { |
| 279 | continue |
| 280 | } |
| 281 | runner := s.Runner |
| 282 | if runner == "" { |
| 283 | runner = f.Primary |
| 284 | } |
| 285 | if out[s.Role] == nil { |
| 286 | out[s.Role] = map[string]bool{} |
| 287 | } |
| 288 | out[s.Role][runner] = true |
| 289 | } |
| 290 | return out |
| 291 | } |
| 292 | |
| 293 | // preferSwitch: the preferred subscription near its limit for more than |
| 294 | // a day while another eligible subscription has room, and steps for a |
| 295 | // role held or queued. Its action prefers the other until the |
| 296 | // preferred one's window resets. The preference is one provider for |
| 297 | // every role (as built); the role in the key is the first, in the fixed |
| 298 | // order, that waits. |
| 299 | func preferSwitch(f Facts, now time.Time) []Advice { |
| 300 | p := f.Preference |
| 301 | if p.Provider == "" || p.Until != nil && !p.Until.After(now) { |
| 302 | return nil |
| 303 | } |
| 304 | var until time.Time |
| 305 | held := 0 |
| 306 | for _, c := range f.Conns { |
| 307 | if c.Provider != p.Provider || c.Billing == wire.BillingMetered || c.State == wire.ConnSignedOut { |
| 308 | continue |
| 309 | } |
| 310 | var free time.Time |
| 311 | for _, w := range live(c, now) { |
| 312 | if w.Used >= NearLimit && w.ResetsAt != nil && w.ResetsAt.Sub(now) > ResetFar && w.ResetsAt.After(free) { |
| 313 | free = *w.ResetsAt |
| 314 | } |
| 315 | } |
| 316 | if free.IsZero() { |
| 317 | // One preferred connection has room: nothing to advise. |
| 318 | return nil |
| 319 | } |
| 320 | held++ |
| 321 | if until.IsZero() || free.Before(until) { |
| 322 | until = free |
| 323 | } |
| 324 | } |
| 325 | if held == 0 || until.Sub(now) > wire.MaxByAhead { |
| 326 | return nil |
| 327 | } |
| 328 | roles := waiting(f) |
| 329 | var out []Advice |
| 330 | for rank, role := range Roles { |
| 331 | runners := roles[role] |
| 332 | if len(runners) == 0 { |
| 333 | continue |
| 334 | } |
| 335 | for _, c := range f.Conns { |
| 336 | if c.Provider == p.Provider || c.Billing == wire.BillingMetered || c.State != wire.ConnHealthy || !wire.PreferenceProviders[c.Provider] || !capable(f, c.Provider, role) || !runners[c.Runner] { |
| 337 | continue |
| 338 | } |
| 339 | ws := live(c, now) |
| 340 | if len(ws) == 0 || slices.ContainsFunc(ws, func(w Window) bool { return w.Used >= Room }) { |
| 341 | continue |
| 342 | } |
| 343 | a := Advice{Kind: wire.AdvicePreferSwitch, Subject: wire.AdviceSubject{Role: role, Connection: c.ID}, roleRank: rank, Connection: c.ID, From: p.Provider, To: c.Provider, Until: until, PreferenceRevision: p.Revision} |
| 344 | a.Key = key(a.Kind, a.Subject) |
| 345 | out = append(out, a) |
| 346 | } |
| 347 | } |
| 348 | return out |
| 349 | } |
| 350 | |
| 351 | // taskSet is a kind's subject: the tasks sorted by id, with the |
| 352 | // earliest's creation for the order. |
| 353 | func taskSet(kind string, tasks []Task) Advice { |
| 354 | sorted := slices.Clone(tasks) |
| 355 | sort.Slice(sorted, func(i, j int) bool { return sorted[i].ID < sorted[j].ID }) |
| 356 | a := Advice{Kind: kind} |
| 357 | for _, t := range sorted { |
| 358 | a.Subject.Tasks = append(a.Subject.Tasks, t.ID) |
| 359 | a.Tasks = append(a.Tasks, TaskRef{ID: t.ID, Revision: t.Revision}) |
| 360 | } |
| 361 | byAge := slices.Clone(tasks) |
| 362 | sort.Slice(byAge, func(i, j int) bool { |
| 363 | if !byAge[i].CreatedAt.Equal(byAge[j].CreatedAt) { |
| 364 | return byAge[i].CreatedAt.Before(byAge[j].CreatedAt) |
| 365 | } |
| 366 | return byAge[i].ID < byAge[j].ID |
| 367 | }) |
| 368 | a.first, a.firstTask = byAge[0].CreatedAt, byAge[0].ID |
| 369 | a.Key = key(kind, a.Subject) |
| 370 | return a |
| 371 | } |
| 372 | |
| 373 | // deferTasks: urgent or deadline work held for headroom while normal |
| 374 | // tasks without a deadline are queued for the same role. Its action |
| 375 | // makes them low priority, so the urgent work goes first. |
| 376 | func deferTasks(f Facts) []Advice { |
| 377 | tasks := map[string]Task{} |
| 378 | for _, t := range f.Tasks { |
| 379 | tasks[t.ID] = t |
| 380 | } |
| 381 | var out []Advice |
| 382 | for _, role := range Roles { |
| 383 | var resets *time.Time |
| 384 | urgent := map[string]bool{} |
| 385 | for _, s := range f.Steps { |
| 386 | t, ok := tasks[s.Task] |
| 387 | if !ok || s.Role != role || s.Housekeeping || s.Hold != wire.HoldHeadroom || priorityOf(t) != wire.PriorityUrgent && t.By == nil { |
| 388 | continue |
| 389 | } |
| 390 | urgent[t.ID] = true |
| 391 | if s.HoldResets != nil && (resets == nil || s.HoldResets.Before(*resets)) { |
| 392 | at := *s.HoldResets |
| 393 | resets = &at |
| 394 | } |
| 395 | } |
| 396 | if len(urgent) == 0 { |
| 397 | continue |
| 398 | } |
| 399 | var normal []Task |
| 400 | added := map[string]bool{} |
| 401 | for _, s := range f.Steps { |
| 402 | t, ok := tasks[s.Task] |
| 403 | if !ok || s.Role != role || s.Housekeeping || urgent[t.ID] || added[t.ID] || priorityOf(t) != wire.PriorityNormal || t.By != nil { |
| 404 | continue |
| 405 | } |
| 406 | added[t.ID] = true |
| 407 | normal = append(normal, t) |
| 408 | } |
| 409 | if len(normal) == 0 { |
| 410 | continue |
| 411 | } |
| 412 | a := taskSet(wire.AdviceDeferTasks, normal) |
| 413 | a.ResetsAt = resets |
| 414 | out = append(out, a) |
| 415 | } |
| 416 | return out |
| 417 | } |
| 418 | |
| 419 | // heldLong: low tasks held for a week. Its action makes them normal. |
| 420 | func heldLong(f Facts, now time.Time) []Advice { |
| 421 | tasks := map[string]Task{} |
| 422 | for _, t := range f.Tasks { |
| 423 | tasks[t.ID] = t |
| 424 | } |
| 425 | var long []Task |
| 426 | added := map[string]bool{} |
| 427 | for _, s := range f.Steps { |
| 428 | t, ok := tasks[s.Task] |
| 429 | if !ok || s.Hold == "" || s.HeldSince == nil || s.Housekeeping || added[t.ID] || priorityOf(t) != wire.PriorityLow || now.Sub(*s.HeldSince) < WaitedLong { |
| 430 | continue |
| 431 | } |
| 432 | added[t.ID] = true |
| 433 | long = append(long, t) |
| 434 | } |
| 435 | if len(long) == 0 { |
| 436 | return nil |
| 437 | } |
| 438 | return []Advice{taskSet(wire.AdviceHeldLong, long)} |
| 439 | } |
| 440 | |
| 441 | // Past is advice shown before, as the advice table keeps it: its key, |
| 442 | // state, the day it first showed (its visible time) and when it was |
| 443 | // dismissed. |
| 444 | type Past struct { |
| 445 | Key string |
| 446 | State string |
| 447 | Shown time.Time |
| 448 | DismissedAt *time.Time |
| 449 | } |
| 450 | |
| 451 | // SilencedUntil is when a key may show again: Not now silences it for |
| 452 | // 14 days, and for 60 days from the second Not now on. Zero: it is not |
| 453 | // silenced. |
| 454 | func SilencedUntil(k string, past []Past) time.Time { |
| 455 | var last time.Time |
| 456 | n := 0 |
| 457 | for _, p := range past { |
| 458 | if p.Key != k || p.State != wire.AdviceDismissed || p.DismissedAt == nil { |
| 459 | continue |
| 460 | } |
| 461 | n++ |
| 462 | if p.DismissedAt.After(last) { |
| 463 | last = *p.DismissedAt |
| 464 | } |
| 465 | } |
| 466 | switch { |
| 467 | case n == 0: |
| 468 | return time.Time{} |
| 469 | case n == 1: |
| 470 | return last.Add(SilenceFirst) |
| 471 | } |
| 472 | return last.Add(SilenceAgain) |
| 473 | } |
| 474 | |
| 475 | // ShownToday reports whether a card was already new on the person's day |
| 476 | // of shown (in loc): at most one new card a day. |
| 477 | func ShownToday(past []Past, shown time.Time, loc *time.Location) bool { |
| 478 | y, m, d := shown.In(loc).Date() |
| 479 | for _, p := range past { |
| 480 | py, pm, pd := p.Shown.In(loc).Date() |
| 481 | if py == y && pm == m && pd == d { |
| 482 | return true |
| 483 | } |
| 484 | } |
| 485 | return false |
| 486 | } |
| 487 | |
| 488 | // Choose is the advice to show next, or nil: none while one is open, none |
| 489 | // when a card was already new on the day it would show (shown: now, or |
| 490 | // the end of quiet hours), and otherwise the first eligible key not |
| 491 | // silenced. |
| 492 | func Choose(eligible []Advice, past []Past, open bool, now, shown time.Time, loc *time.Location) *Advice { |
| 493 | if open || ShownToday(past, shown, loc) { |
| 494 | return nil |
| 495 | } |
| 496 | for i := range eligible { |
| 497 | if until := SilencedUntil(eligible[i].Key, past); !until.IsZero() && now.Before(until) { |
| 498 | continue |
| 499 | } |
| 500 | return &eligible[i] |
| 501 | } |
| 502 | return nil |
| 503 | } |
| 504 | |
| 505 | // Holds reports whether advice with key k is still eligible: advice |
| 506 | // whose facts stopped holding is withdrawn. |
| 507 | func Holds(eligible []Advice, k string) (Advice, bool) { |
| 508 | for _, a := range eligible { |
| 509 | if a.Key == k { |
| 510 | return a, true |
| 511 | } |
| 512 | } |
| 513 | return Advice{}, false |
| 514 | } |
| 515 | |