oficina / equipo Public

advice: Compute and its rules, pure (connectors spec 9)

The four kinds with their triggers, the deterministic order and keys,
at most one open and one new card a day in the person's zone, and Not
now silencing a key for 14 days, then 60. Each kind fires once from its
fixture; ties pick the same card over 500 shuffles.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev dc2903885f8d940a89174c829a3cb16a076885c5 parent e52eb75
2 files changed, +807 −0
  • internal/advice/advice.go +514 −0
  • internal/advice/advice_test.go +293 −0
diff --git a/internal/advice/advice.go b/internal/advice/advice.go
new file mode 100644
index 00000000..5578843f
--- /dev/null
+++ b/internal/advice/advice.go
@@ -0,0 +1,514 @@
+// 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
+}
diff --git a/internal/advice/advice_test.go b/internal/advice/advice_test.go
new file mode 100644
index 00000000..4f53f387
--- /dev/null
+++ b/internal/advice/advice_test.go
@@ -0,0 +1,293 @@
+package advice
+
+import (
+ "math/rand/v2"
+ "os"
+ "slices"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/budget"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+var now = time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
+
+func at(d time.Duration) *time.Time {
+ t := now.Add(d)
+ return &t
+}
+
+// The four fixtures: each makes exactly one kind of advice hold.
+func fixtures() map[string]Facts {
+ tx := Conn{ID: "cn_tx", Provider: wire.ProviderTensorX, Runner: "r1", State: wire.ConnHealthy, Billing: wire.BillingMetered, SpendDay: 840_000, SpendMonth: 6_200_000, BudgetDay: 1_000_000, BudgetMonth: 10_000_000, BudgetRevision: 2, Currency: "USD"}
+ claude := Conn{ID: "cn_cl", Provider: wire.ProviderClaude, Runner: "r1", State: wire.ConnHealthy, Billing: wire.BillingSubscription, Windows: []Window{{Used: 0.85, ResetsAt: at(50 * time.Hour)}}}
+ codex := Conn{ID: "cn_cx", Provider: wire.ProviderCodex, Runner: "r1", State: wire.ConnHealthy, Billing: wire.BillingSubscription, Windows: []Window{{Used: 0.20, ResetsAt: at(3 * time.Hour)}, {Used: 0.30, ResetsAt: at(100 * time.Hour)}}}
+ quietClaude := claude
+ quietClaude.Windows = []Window{{Used: 0.40, ResetsAt: at(50 * time.Hour)}}
+ return map[string]Facts{
+ wire.AdviceBudgetNear: {Conns: []Conn{tx}, Primary: "r1"},
+ wire.AdvicePreferSwitch: {Conns: []Conn{claude, codex}, Primary: "r1", Preference: Preference{Provider: wire.ProviderClaude, Revision: 3},
+ Tasks: []Task{{ID: "tk9", CreatedAt: now.Add(-time.Hour), Priority: wire.PriorityNormal, Revision: 2}},
+ Steps: []Step{{Task: "tk9", Role: wire.SpecialistEngineering, Runner: "r1"}}},
+ wire.AdviceDeferTasks: {Conns: []Conn{quietClaude}, Primary: "r1",
+ Tasks: []Task{{ID: "tk1", CreatedAt: now.Add(-3 * time.Hour), Priority: wire.PriorityUrgent, Revision: 4}, {ID: "tk3", CreatedAt: now.Add(-2 * time.Hour), Revision: 1}, {ID: "tk2", CreatedAt: now.Add(-time.Hour), Priority: wire.PriorityNormal, Revision: 7}},
+ Steps: []Step{{Task: "tk1", Role: wire.SpecialistEngineering, Hold: wire.HoldHeadroom, HoldResets: at(50 * time.Hour), HeldSince: at(-time.Hour)}, {Task: "tk2", Role: wire.SpecialistEngineering, Hold: wire.HoldHeadroom, HeldSince: at(-time.Hour)}, {Task: "tk3", Role: wire.SpecialistEngineering}}},
+ wire.AdviceHeldLong: {Conns: []Conn{quietClaude}, Primary: "r1",
+ Tasks: []Task{{ID: "tk5", CreatedAt: now.Add(-9 * 24 * time.Hour), Priority: wire.PriorityLow, Revision: 3}, {ID: "tk6", CreatedAt: now.Add(-24 * time.Hour), Priority: wire.PriorityLow, Revision: 1}},
+ Steps: []Step{{Task: "tk5", Role: wire.SpecialistReview, Hold: wire.HoldHeadroom, HeldSince: at(-8 * 24 * time.Hour)}, {Task: "tk6", Role: wire.SpecialistReview, Hold: wire.HoldHeadroom, HeldSince: at(-24 * time.Hour)}}},
+ }
+}
+
+// From the fixtures each kind fires once, and only it, with its action's
+// facts.
+func TestEachKindFiresOnce(t *testing.T) {
+ for kind, f := range fixtures() {
+ got := Compute(f, now)
+ if len(got) != 1 || got[0].Kind != kind {
+ t.Fatalf("%s: %+v", kind, got)
+ }
+ a := got[0]
+ switch kind {
+ case wire.AdviceBudgetNear:
+ if a.Key != "budget_near:cn_tx" || a.Window != BudgetDay || a.Spend != 840_000 || a.Budget != 1_000_000 || a.Raise != 2_000_000 || a.BudgetRevision != 2 {
+ t.Fatalf("budget_near: %+v", a)
+ }
+ case wire.AdvicePreferSwitch:
+ if a.Key != "prefer_switch:engineering/cn_cx" || a.From != wire.ProviderClaude || a.To != wire.ProviderCodex || !a.Until.Equal(*at(50 * time.Hour)) || a.PreferenceRevision != 3 {
+ t.Fatalf("prefer_switch: %+v", a)
+ }
+ case wire.AdviceDeferTasks:
+ if a.Key != "defer_tasks:tk2,tk3" || !slices.Equal(a.Tasks, []TaskRef{{"tk2", 7}, {"tk3", 1}}) || a.ResetsAt == nil || !a.ResetsAt.Equal(*at(50 * time.Hour)) {
+ t.Fatalf("defer_tasks: %+v", a)
+ }
+ case wire.AdviceHeldLong:
+ if a.Key != "held_long:tk5" || !slices.Equal(a.Tasks, []TaskRef{{"tk5", 3}}) {
+ t.Fatalf("held_long: %+v", a)
+ }
+ }
+ }
+}
+
+// Each kind's line, one fact at a time: just short of it, nothing.
+func TestEachKindsLine(t *testing.T) {
+ fx := fixtures()
+ none := func(what string, f Facts) {
+ t.Helper()
+ if got := Compute(f, now); len(got) != 0 {
+ t.Fatalf("%s: %+v", what, got)
+ }
+ }
+ // budget_near: 79% is not near; the month at 80% is; spend unknown
+ // never is; a day budget already at the month's raises the month.
+ f := fx[wire.AdviceBudgetNear]
+ f.Conns[0].SpendDay = 790_000
+ none("79% of the day", f)
+ f.Conns[0].SpendMonth = 8_000_000
+ if got := Compute(f, now); len(got) != 1 || got[0].Window != BudgetMonth || got[0].Raise != 20_000_000 {
+ t.Fatalf("month: %+v", got)
+ }
+ f.Conns[0].SpendUnknown = true
+ none("spend unknown", f)
+ f = fixtures()[wire.AdviceBudgetNear]
+ f.Conns[0].BudgetMonth, f.Conns[0].SpendMonth = 1_000_000, 840_000
+ if got := Compute(f, now); len(got) != 1 || got[0].Window != BudgetMonth || got[0].Raise != 2_000_000 {
+ t.Fatalf("day at the month's budget: %+v", got)
+ }
+
+ // prefer_switch: a reset within a day, a target at 0.50, no waiting
+ // step, an expired preference, Automatic, a target on another runner.
+ for what, change := range map[string]func(*Facts){
+ "reset within a day": func(f *Facts) { f.Conns[0].Windows[0].ResetsAt = at(23 * time.Hour) },
+ "preferred below 0.80": func(f *Facts) { f.Conns[0].Windows[0].Used = 0.79 },
+ "target at 0.50": func(f *Facts) { f.Conns[1].Windows[1].Used = 0.50 },
+ "target reports none": func(f *Facts) { f.Conns[1].Windows = nil },
+ "nothing waits": func(f *Facts) { f.Steps = nil },
+ "automatic": func(f *Facts) { f.Preference.Provider = "" },
+ "expired": func(f *Facts) { f.Preference.Until = at(0) },
+ "target limited": func(f *Facts) { f.Conns[1].State = wire.ConnLimited },
+ "another runner": func(f *Facts) { f.Conns[1].Runner = "r2" },
+ "not capable": func(f *Facts) {
+ f.Capable = func(p, r string) bool { return p != wire.ProviderCodex }
+ },
+ } {
+ f := fixtures()[wire.AdvicePreferSwitch]
+ change(&f)
+ none("prefer_switch, "+what, f)
+ }
+
+ // defer_tasks: the urgent work not held for headroom, or no normal
+ // task without a deadline, or the normal one has a deadline.
+ for what, change := range map[string]func(*Facts){
+ "urgent not held": func(f *Facts) { f.Steps[0].Hold = "" },
+ "held for the budget": func(f *Facts) { f.Steps[0].Hold = wire.HoldBudget },
+ "another role": func(f *Facts) { f.Steps[1].Role, f.Steps[2].Role = wire.SpecialistReview, wire.SpecialistReview },
+ "normal ones by dates": func(f *Facts) { f.Tasks[1].By, f.Tasks[2].By = at(48*time.Hour), at(48*time.Hour) },
+ "housekeeping's": func(f *Facts) { f.Steps[1].Housekeeping, f.Steps[2].Housekeeping = true, true },
+ } {
+ f := fixtures()[wire.AdviceDeferTasks]
+ change(&f)
+ none("defer_tasks, "+what, f)
+ }
+ // A deadline counts as urgent work.
+ f = fixtures()[wire.AdviceDeferTasks]
+ f.Tasks[0].Priority, f.Tasks[0].By = wire.PriorityNormal, at(48*time.Hour)
+ if got := Compute(f, now); len(got) != 1 || got[0].Key != "defer_tasks:tk2,tk3" {
+ t.Fatalf("deadline work: %+v", got)
+ }
+
+ // held_long: a day short of a week, normal priority, no longer held.
+ for what, change := range map[string]func(*Facts){
+ "six days": func(f *Facts) { f.Steps[0].HeldSince = at(-6 * 24 * time.Hour) },
+ "normal": func(f *Facts) { f.Tasks[0].Priority = wire.PriorityNormal },
+ "not held": func(f *Facts) { f.Steps[0].Hold = "" },
+ "no held day": func(f *Facts) { f.Steps[0].HeldSince = nil },
+ } {
+ f := fixtures()[wire.AdviceHeldLong]
+ change(&f)
+ none("held_long, "+what, f)
+ }
+}
+
+// Ties pick the same card on every run: all four kinds and several of
+// each eligible at once, the facts shuffled every time.
+func TestTiesPickTheSameCard(t *testing.T) {
+ fx := fixtures()
+ var all Facts
+ all.Primary, all.Preference = "r1", fx[wire.AdvicePreferSwitch].Preference
+ for _, kind := range wire.AdviceKinds {
+ f := fx[kind]
+ all.Conns = append(all.Conns, f.Conns...)
+ all.Tasks = append(all.Tasks, f.Tasks...)
+ all.Steps = append(all.Steps, f.Steps...)
+ }
+ // A second metered connection near its budget, a second room target,
+ // review waiting too.
+ tx2 := all.Conns[0]
+ tx2.ID = "cn_ta"
+ cx2 := fx[wire.AdvicePreferSwitch].Conns[1]
+ cx2.ID = "cn_ca"
+ all.Conns = append(all.Conns, tx2, cx2)
+ all.Steps = append(all.Steps, Step{Task: "tk1", Role: wire.SpecialistReview, Runner: "r1"})
+ // The quiet Claude copies are duplicates of cn_cl: keep one Claude.
+ all.Conns = slices.DeleteFunc(all.Conns, func(c Conn) bool {
+ return c.ID == "cn_cl" && c.Windows[0].Used < NearLimit
+ })
+ first := Compute(all, now)
+ if len(first) < 6 || first[0].Key != "budget_near:cn_ta" {
+ t.Fatalf("first: %d, %+v", len(first), first)
+ }
+ var keys []string
+ for _, a := range first {
+ keys = append(keys, a.Key)
+ }
+ want := []string{"budget_near:cn_ta", "budget_near:cn_tx", "prefer_switch:engineering/cn_ca", "prefer_switch:engineering/cn_cx", "prefer_switch:review/cn_ca", "prefer_switch:review/cn_cx", "defer_tasks:tk2,tk3,tk9", "held_long:tk5"}
+ if !slices.Equal(keys, want) {
+ t.Fatalf("order %v", keys)
+ }
+ rng := rand.New(rand.NewPCG(1, 2))
+ for i := 0; i < 500; i++ {
+ f := all
+ f.Conns, f.Tasks, f.Steps = slices.Clone(all.Conns), slices.Clone(all.Tasks), slices.Clone(all.Steps)
+ rng.Shuffle(len(f.Conns), func(a, b int) { f.Conns[a], f.Conns[b] = f.Conns[b], f.Conns[a] })
+ rng.Shuffle(len(f.Tasks), func(a, b int) { f.Tasks[a], f.Tasks[b] = f.Tasks[b], f.Tasks[a] })
+ rng.Shuffle(len(f.Steps), func(a, b int) { f.Steps[a], f.Steps[b] = f.Steps[b], f.Steps[a] })
+ var got []string
+ for _, a := range Compute(f, now) {
+ got = append(got, a.Key)
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("run %d: %v", i, got)
+ }
+ if c := Choose(Compute(f, now), nil, false, now, now, time.UTC); c == nil || c.Key != want[0] {
+ t.Fatalf("run %d chose %+v", i, c)
+ }
+ }
+ // Within a task set, the earliest task decides, then its id.
+ a := taskSet(wire.AdviceDeferTasks, []Task{{ID: "tkb", CreatedAt: now}})
+ b := taskSet(wire.AdviceDeferTasks, []Task{{ID: "tka", CreatedAt: now.Add(time.Second)}})
+ if !Less(a, b) || Less(b, a) {
+ t.Fatal("the earliest task does not decide")
+ }
+}
+
+// Not now silences a key for 14 days, and for 60 after a second Not now;
+// another key is not silenced.
+func TestNotNowSilences(t *testing.T) {
+ eligible := Compute(fixtures()[wire.AdviceBudgetNear], now)
+ k := eligible[0].Key
+ once := []Past{{Key: k, State: wire.AdviceDismissed, Shown: now, DismissedAt: at(0)}}
+ for _, c := range []struct {
+ days int
+ show bool
+ }{{1, false}, {13, false}, {14, true}, {30, true}} {
+ later := now.Add(time.Duration(c.days) * 24 * time.Hour)
+ if got := Choose(eligible, once, false, later, later, time.UTC); (got != nil) != c.show {
+ t.Fatalf("one Not now, day %d: %+v", c.days, got)
+ }
+ }
+ twice := append(slices.Clone(once), Past{Key: k, State: wire.AdviceDismissed, Shown: now.Add(15 * 24 * time.Hour), DismissedAt: at(15 * 24 * time.Hour)})
+ for _, c := range []struct {
+ days int
+ show bool
+ }{{16, false}, {29, false}, {74, false}, {75, true}} {
+ later := now.Add(time.Duration(c.days) * 24 * time.Hour)
+ if got := Choose(eligible, twice, false, later, later, time.UTC); (got != nil) != c.show {
+ t.Fatalf("two Not nows, day %d: %+v", c.days, got)
+ }
+ }
+ if !SilencedUntil("budget_near:other", twice).IsZero() {
+ t.Fatal("another key was silenced")
+ }
+ // Acted or withdrawn advice silences nothing.
+ acted := []Past{{Key: k, State: wire.AdviceActed, Shown: now}, {Key: k, State: wire.AdviceWithdrawn, Shown: now}}
+ if !SilencedUntil(k, acted).IsZero() {
+ t.Fatal("acted advice silenced its key")
+ }
+}
+
+// No day shows two cards, and none shows while one is open: a card new
+// today (even one already acted on or withdrawn) keeps every other away
+// until tomorrow, in the person's zone; a card made in quiet hours
+// counts for the day it shows.
+func TestNoDayShowsTwoCards(t *testing.T) {
+ eligible := Compute(fixtures()[wire.AdvicePreferSwitch], now)
+ if Choose(eligible, nil, true, now, now, time.UTC) != nil {
+ t.Fatal("a card while one is open")
+ }
+ for _, state := range []string{wire.AdviceActed, wire.AdviceWithdrawn, wire.AdviceDismissed} {
+ past := []Past{{Key: "budget_near:cn_tx", State: state, Shown: now.Add(-2 * time.Hour)}}
+ if c := Choose(eligible, past, false, now, now, time.UTC); c != nil {
+ t.Fatalf("a second card the same day after %s", state)
+ }
+ tomorrow := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)
+ if c := Choose(eligible, past, false, tomorrow, tomorrow, time.UTC); c == nil {
+ t.Fatalf("no card the next day after %s", state)
+ }
+ }
+ // Made at 23:00, shown at 08:00 tomorrow: tomorrow's one card.
+ night := time.Date(2026, 11, 12, 23, 0, 0, 0, time.UTC)
+ morning := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)
+ past := []Past{{Key: "x", State: wire.AdviceOpen, Shown: morning}}
+ if c := Choose(eligible, past, false, morning.Add(time.Hour), morning.Add(time.Hour), time.UTC); c != nil {
+ t.Fatal("two cards the morning a night card showed")
+ }
+ if c := Choose(eligible, nil, false, night, morning, time.UTC); c == nil {
+ t.Fatal("no card for tomorrow from tonight's facts")
+ }
+ // The day is the person's: in a zone where it is already tomorrow.
+ east := time.FixedZone("east", 3*3600)
+ late := time.Date(2026, 11, 12, 22, 30, 0, 0, time.UTC)
+ past = []Past{{Key: "x", State: wire.AdviceActed, Shown: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)}}
+ if c := Choose(eligible, past, false, late, late, east); c == nil {
+ t.Fatal("the person's next day had no card")
+ }
+ // And one shown just after their midnight is that day's card.
+ past = []Past{{Key: "x", State: wire.AdviceActed, Shown: time.Date(2026, 11, 12, 21, 30, 0, 0, time.UTC)}}
+ if c := Choose(eligible, past, false, late, late, east); c != nil {
+ t.Fatal("two cards on the person's day")
+ }
+}