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") } }