// Package advice is the instance's advice on tokens (connectors spec // 2026-11-12 rev 3.2 §9, slice S4): Compute turns recorded facts into // the advice that could be shown now, in one deterministic order, and // the rules decide which one may show. It is pure: no store, no clock, // no model. The words are the caller's fixed templates. package advice import ( "slices" "sort" "strings" "time" "amadan.net/oficina/equipo/internal/wire" ) // Version names the facts' shape and the rules below. const Version = 1 // The thresholds (§9). const ( // NearBudget: a metered connection's reported spend at or past 80% // of its day's or month's budget. NearBudget = 0.80 // NearLimit and Room: the preferred subscription has a window at or // above 0.80 whose reset is more than ResetFar away; another has // every window below 0.50. NearLimit = 0.80 Room = 0.50 ResetFar = 24 * time.Hour // WaitedLong: a low task held for a week. WaitedLong = 7 * 24 * time.Hour // Silence after the first and after a later Not now. SilenceFirst = 14 * 24 * time.Hour SilenceAgain = 60 * 24 * time.Hour ) // Roles in their fixed order for advice about a role. var Roles = []string{"coordinator", wire.SpecialistEngineering, wire.SpecialistReview} // Window is one reported rate window: used from 0 to 1 and its reset. type Window struct { Used float64 ResetsAt *time.Time } // Conn is one of the person's connections as the instance last heard. // ID is the instance's id; Runner the runner holding it. A metered // connection has its budget and reported spend in micro-units. type Conn struct { ID, Provider, Runner, State, Billing string Windows []Window SpendDay, SpendMonth int64 BudgetDay, BudgetMonth int64 BudgetRevision int64 Currency string SpendUnknown bool } // Preference is the person's preferred provider (one for every role) // and when it ends. type Preference struct { Provider string Until *time.Time Revision int64 } // Task is one of the person's own open tasks. type Task struct { ID string CreatedAt time.Time // Priority is urgent, normal or low ("" reads normal); By its // deadline. Priority string By *time.Time Revision int64 } // Step is one queued step of a task (held by the scheduler or not): // its role, the runner it was placed on ("" not yet), and its hold. type Step struct { Task, Role, Runner string // Hold is the hold's reason ("" not held), HoldResets the reset the // hold names, HeldSince when the step was first held without a break. Hold string HoldResets *time.Time HeldSince *time.Time // Housekeeping: housekeeping's attempt, which advice never moves. Housekeeping bool } // Facts are what advice is computed from. type Facts struct { Conns []Conn Preference Preference Tasks []Task Steps []Step // Primary is the person's primary runner: where the preference // applies to steps not yet placed. Primary string // Capable says whether a provider can run a role (the runner's // capability table); nil: Claude and Codex run every role. Capable func(provider, role string) bool } // TaskRef is a task an action changes, at the revision it was read at. type TaskRef struct { ID string Revision int64 } // Advice is one eligible piece of advice with what its card says and // what its one action does. type Advice struct { Kind string Subject wire.AdviceSubject Key string // Ordering within a kind: the role's place, the earliest task. roleRank int first time.Time firstTask string // budget_near: the connection, which budget (day or month), the // spend and budget now, the raised figure, and the budget's revision. Connection string Window string Spend, Budget int64 Raise int64 Currency string BudgetRevision int64 // prefer_switch: from and to providers, until when, and the // preference's revision. From, To string Until time.Time PreferenceRevision int64 // defer_tasks and held_long: the tasks and, for defer_tasks, the // reset the urgent work waits for. Tasks []TaskRef ResetsAt *time.Time } // Day and month: which budget a budget_near names. const ( BudgetDay = "day" BudgetMonth = "month" ) // key is advice's key string: its kind and subject. func key(kind string, s wire.AdviceSubject) string { switch { case len(s.Tasks) > 0: return kind + ":" + strings.Join(s.Tasks, ",") case s.Role != "": return kind + ":" + s.Role + "/" + s.Connection } return kind + ":" + s.Connection } func capable(f Facts, provider, role string) bool { if f.Capable != nil { return f.Capable(provider, role) } return wire.PreferenceProviders[provider] && provider != "" } // live are a connection's windows that have not reset by now. func live(c Conn, now time.Time) []Window { var out []Window for _, w := range c.Windows { if w.ResetsAt != nil && !w.ResetsAt.After(now) { continue } out = append(out, w) } return out } func priorityOf(t Task) string { if t.Priority == "" { return wire.PriorityNormal } return t.Priority } // Compute is every piece of advice whose facts hold now, in the order // one is chosen: the kind's arbitration order; within a kind, a // connection's id bytewise, a role's fixed place, a task set's earliest // task then its first id; then the key bytewise. The same facts give // the same list. func Compute(f Facts, now time.Time) []Advice { var out []Advice out = append(out, budgetNear(f)...) out = append(out, preferSwitch(f, now)...) out = append(out, deferTasks(f)...) out = append(out, heldLong(f, now)...) seen := map[string]bool{} out = slices.DeleteFunc(out, func(a Advice) bool { if seen[a.Key] { return true } seen[a.Key] = true return false }) sort.SliceStable(out, func(i, j int) bool { return Less(out[i], out[j]) }) return out } // Less is the deterministic order (§9, finding 24). func Less(a, b Advice) bool { ka, kb := slices.Index(wire.AdviceKinds, a.Kind), slices.Index(wire.AdviceKinds, b.Kind) if ka != kb { return ka < kb } switch a.Kind { case wire.AdviceBudgetNear: if a.Subject.Connection != b.Subject.Connection { return a.Subject.Connection < b.Subject.Connection } case wire.AdvicePreferSwitch: if a.roleRank != b.roleRank { return a.roleRank < b.roleRank } if a.Subject.Connection != b.Subject.Connection { return a.Subject.Connection < b.Subject.Connection } default: if !a.first.Equal(b.first) { return a.first.Before(b.first) } if a.firstTask != b.firstTask { return a.firstTask < b.firstTask } } return a.Key < b.Key } // budgetNear: a metered connection's reported spend at or past 80% of // its day's budget (then of its month's), when the budget can be // raised. Its action doubles that budget within the bounds; a day's // budget never passes the month's. func budgetNear(f Facts) []Advice { var out []Advice for _, c := range f.Conns { if c.Billing != wire.BillingMetered || c.SpendUnknown || c.State == wire.ConnSignedOut || c.BudgetDay <= 0 || c.BudgetMonth <= 0 { continue } a := Advice{Kind: wire.AdviceBudgetNear, Subject: wire.AdviceSubject{Connection: c.ID}, Connection: c.ID, Currency: c.Currency, BudgetRevision: c.BudgetRevision} if near(c.SpendDay, c.BudgetDay) { if raise := min(2*c.BudgetDay, c.BudgetMonth, wire.MaxBudgetDay); raise > c.BudgetDay { a.Window, a.Spend, a.Budget, a.Raise = BudgetDay, c.SpendDay, c.BudgetDay, raise } } if a.Window == "" && near(c.SpendMonth, c.BudgetMonth) { if raise := min(2*c.BudgetMonth, wire.MaxBudgetMonth); raise > c.BudgetMonth { a.Window, a.Spend, a.Budget, a.Raise = BudgetMonth, c.SpendMonth, c.BudgetMonth, raise } } if a.Window == "" { continue } a.Key = key(a.Kind, a.Subject) out = append(out, a) } return out } // near: spend at or past NearBudget of budget, in integers (no float // rounding at the line). func near(spend, budget int64) bool { return budget > 0 && spend*5 >= budget*4 } // waiting are the roles with steps held or queued, and the runners // their steps were placed on (the primary for one not yet placed). func waiting(f Facts) map[string]map[string]bool { out := map[string]map[string]bool{} for _, s := range f.Steps { if s.Housekeeping { continue } runner := s.Runner if runner == "" { runner = f.Primary } if out[s.Role] == nil { out[s.Role] = map[string]bool{} } out[s.Role][runner] = true } return out } // preferSwitch: the preferred subscription near its limit for more than // a day while another eligible subscription has room, and steps for a // role held or queued. Its action prefers the other until the // preferred one's window resets. The preference is one provider for // every role (as built); the role in the key is the first, in the fixed // order, that waits. func preferSwitch(f Facts, now time.Time) []Advice { p := f.Preference if p.Provider == "" || p.Until != nil && !p.Until.After(now) { return nil } var until time.Time held := 0 for _, c := range f.Conns { if c.Provider != p.Provider || c.Billing == wire.BillingMetered || c.State == wire.ConnSignedOut { continue } var free time.Time for _, w := range live(c, now) { if w.Used >= NearLimit && w.ResetsAt != nil && w.ResetsAt.Sub(now) > ResetFar && w.ResetsAt.After(free) { free = *w.ResetsAt } } if free.IsZero() { // One preferred connection has room: nothing to advise. return nil } held++ if until.IsZero() || free.Before(until) { until = free } } if held == 0 || until.Sub(now) > wire.MaxByAhead { return nil } roles := waiting(f) var out []Advice for rank, role := range Roles { runners := roles[role] if len(runners) == 0 { continue } for _, c := range f.Conns { 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] { continue } ws := live(c, now) if len(ws) == 0 || slices.ContainsFunc(ws, func(w Window) bool { return w.Used >= Room }) { continue } 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} a.Key = key(a.Kind, a.Subject) out = append(out, a) } } return out } // taskSet is a kind's subject: the tasks sorted by id, with the // earliest's creation for the order. func taskSet(kind string, tasks []Task) Advice { sorted := slices.Clone(tasks) sort.Slice(sorted, func(i, j int) bool { return sorted[i].ID < sorted[j].ID }) a := Advice{Kind: kind} for _, t := range sorted { a.Subject.Tasks = append(a.Subject.Tasks, t.ID) a.Tasks = append(a.Tasks, TaskRef{ID: t.ID, Revision: t.Revision}) } byAge := slices.Clone(tasks) sort.Slice(byAge, func(i, j int) bool { if !byAge[i].CreatedAt.Equal(byAge[j].CreatedAt) { return byAge[i].CreatedAt.Before(byAge[j].CreatedAt) } return byAge[i].ID < byAge[j].ID }) a.first, a.firstTask = byAge[0].CreatedAt, byAge[0].ID a.Key = key(kind, a.Subject) return a } // deferTasks: urgent or deadline work held for headroom while normal // tasks without a deadline are queued for the same role. Its action // makes them low priority, so the urgent work goes first. func deferTasks(f Facts) []Advice { tasks := map[string]Task{} for _, t := range f.Tasks { tasks[t.ID] = t } var out []Advice for _, role := range Roles { var resets *time.Time urgent := map[string]bool{} for _, s := range f.Steps { t, ok := tasks[s.Task] if !ok || s.Role != role || s.Housekeeping || s.Hold != wire.HoldHeadroom || priorityOf(t) != wire.PriorityUrgent && t.By == nil { continue } urgent[t.ID] = true if s.HoldResets != nil && (resets == nil || s.HoldResets.Before(*resets)) { at := *s.HoldResets resets = &at } } if len(urgent) == 0 { continue } var normal []Task added := map[string]bool{} for _, s := range f.Steps { t, ok := tasks[s.Task] if !ok || s.Role != role || s.Housekeeping || urgent[t.ID] || added[t.ID] || priorityOf(t) != wire.PriorityNormal || t.By != nil { continue } added[t.ID] = true normal = append(normal, t) } if len(normal) == 0 { continue } a := taskSet(wire.AdviceDeferTasks, normal) a.ResetsAt = resets out = append(out, a) } return out } // heldLong: low tasks held for a week. Its action makes them normal. func heldLong(f Facts, now time.Time) []Advice { tasks := map[string]Task{} for _, t := range f.Tasks { tasks[t.ID] = t } var long []Task added := map[string]bool{} for _, s := range f.Steps { t, ok := tasks[s.Task] if !ok || s.Hold == "" || s.HeldSince == nil || s.Housekeeping || added[t.ID] || priorityOf(t) != wire.PriorityLow || now.Sub(*s.HeldSince) < WaitedLong { continue } added[t.ID] = true long = append(long, t) } if len(long) == 0 { return nil } return []Advice{taskSet(wire.AdviceHeldLong, long)} } // Past is advice shown before, as the advice table keeps it: its key, // state, the day it first showed (its visible time) and when it was // dismissed. type Past struct { Key string State string Shown time.Time DismissedAt *time.Time } // SilencedUntil is when a key may show again: Not now silences it for // 14 days, and for 60 days from the second Not now on. Zero: it is not // silenced. func SilencedUntil(k string, past []Past) time.Time { var last time.Time n := 0 for _, p := range past { if p.Key != k || p.State != wire.AdviceDismissed || p.DismissedAt == nil { continue } n++ if p.DismissedAt.After(last) { last = *p.DismissedAt } } switch { case n == 0: return time.Time{} case n == 1: return last.Add(SilenceFirst) } return last.Add(SilenceAgain) } // ShownToday reports whether a card was already new on the person's day // of shown (in loc): at most one new card a day. func ShownToday(past []Past, shown time.Time, loc *time.Location) bool { y, m, d := shown.In(loc).Date() for _, p := range past { py, pm, pd := p.Shown.In(loc).Date() if py == y && pm == m && pd == d { return true } } return false } // Choose is the advice to show next, or nil: none while one is open, none // when a card was already new on the day it would show (shown: now, or // the end of quiet hours), and otherwise the first eligible key not // silenced. func Choose(eligible []Advice, past []Past, open bool, now, shown time.Time, loc *time.Location) *Advice { if open || ShownToday(past, shown, loc) { return nil } for i := range eligible { if until := SilencedUntil(eligible[i].Key, past); !until.IsZero() && now.Before(until) { continue } return &eligible[i] } return nil } // Holds reports whether advice with key k is still eligible: advice // whose facts stopped holding is withdrawn. func Holds(eligible []Advice, k string) (Advice, bool) { for _, a := range eligible { if a.Key == k { return a, true } } return Advice{}, false }