oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package advice
2
3import (
4 "math/rand/v2"
5 "os"
6 "slices"
7 "testing"
8 "time"
9
10 "amadan.net/rastrillo/rastrillo/budget"
11
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
16
17var now = time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
18
19func at(d time.Duration) *time.Time {
20 t := now.Add(d)
21 return &t
22}
23
24// The four fixtures: each makes exactly one kind of advice hold.
25func fixtures() map[string]Facts {
26 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"}
27 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)}}}
28 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)}}}
29 quietClaude := claude
30 quietClaude.Windows = []Window{{Used: 0.40, ResetsAt: at(50 * time.Hour)}}
31 return map[string]Facts{
32 wire.AdviceBudgetNear: {Conns: []Conn{tx}, Primary: "r1"},
33 wire.AdvicePreferSwitch: {Conns: []Conn{claude, codex}, Primary: "r1", Preference: Preference{Provider: wire.ProviderClaude, Revision: 3},
34 Tasks: []Task{{ID: "tk9", CreatedAt: now.Add(-time.Hour), Priority: wire.PriorityNormal, Revision: 2}},
35 Steps: []Step{{Task: "tk9", Role: wire.SpecialistEngineering, Runner: "r1"}}},
36 wire.AdviceDeferTasks: {Conns: []Conn{quietClaude}, Primary: "r1",
37 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}},
38 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}}},
39 wire.AdviceHeldLong: {Conns: []Conn{quietClaude}, Primary: "r1",
40 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}},
41 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)}}},
42 }
43}
44
45// From the fixtures each kind fires once, and only it, with its action's
46// facts.
47func TestEachKindFiresOnce(t *testing.T) {
48 for kind, f := range fixtures() {
49 got := Compute(f, now)
50 if len(got) != 1 || got[0].Kind != kind {
51 t.Fatalf("%s: %+v", kind, got)
52 }
53 a := got[0]
54 switch kind {
55 case wire.AdviceBudgetNear:
56 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 {
57 t.Fatalf("budget_near: %+v", a)
58 }
59 case wire.AdvicePreferSwitch:
60 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 {
61 t.Fatalf("prefer_switch: %+v", a)
62 }
63 case wire.AdviceDeferTasks:
64 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)) {
65 t.Fatalf("defer_tasks: %+v", a)
66 }
67 case wire.AdviceHeldLong:
68 if a.Key != "held_long:tk5" || !slices.Equal(a.Tasks, []TaskRef{{"tk5", 3}}) {
69 t.Fatalf("held_long: %+v", a)
70 }
71 }
72 }
73}
74
75// Each kind's line, one fact at a time: just short of it, nothing.
76func TestEachKindsLine(t *testing.T) {
77 fx := fixtures()
78 none := func(what string, f Facts) {
79 t.Helper()
80 if got := Compute(f, now); len(got) != 0 {
81 t.Fatalf("%s: %+v", what, got)
82 }
83 }
84 // budget_near: 79% is not near; the month at 80% is; spend unknown
85 // never is; a day budget already at the month's raises the month.
86 f := fx[wire.AdviceBudgetNear]
87 f.Conns[0].SpendDay = 790_000
88 none("79% of the day", f)
89 f.Conns[0].SpendMonth = 8_000_000
90 if got := Compute(f, now); len(got) != 1 || got[0].Window != BudgetMonth || got[0].Raise != 20_000_000 {
91 t.Fatalf("month: %+v", got)
92 }
93 f.Conns[0].SpendUnknown = true
94 none("spend unknown", f)
95 f = fixtures()[wire.AdviceBudgetNear]
96 f.Conns[0].BudgetMonth, f.Conns[0].SpendMonth = 1_000_000, 840_000
97 if got := Compute(f, now); len(got) != 1 || got[0].Window != BudgetMonth || got[0].Raise != 2_000_000 {
98 t.Fatalf("day at the month's budget: %+v", got)
99 }
100
101 // prefer_switch: a reset within a day, a target at 0.50, no waiting
102 // step, an expired preference, Automatic, a target on another runner.
103 for what, change := range map[string]func(*Facts){
104 "reset within a day": func(f *Facts) { f.Conns[0].Windows[0].ResetsAt = at(23 * time.Hour) },
105 "preferred below 0.80": func(f *Facts) { f.Conns[0].Windows[0].Used = 0.79 },
106 "target at 0.50": func(f *Facts) { f.Conns[1].Windows[1].Used = 0.50 },
107 "target reports none": func(f *Facts) { f.Conns[1].Windows = nil },
108 "nothing waits": func(f *Facts) { f.Steps = nil },
109 "automatic": func(f *Facts) { f.Preference.Provider = "" },
110 "expired": func(f *Facts) { f.Preference.Until = at(0) },
111 "target limited": func(f *Facts) { f.Conns[1].State = wire.ConnLimited },
112 "another runner": func(f *Facts) { f.Conns[1].Runner = "r2" },
113 "not capable": func(f *Facts) {
114 f.Capable = func(p, r string) bool { return p != wire.ProviderCodex }
115 },
116 } {
117 f := fixtures()[wire.AdvicePreferSwitch]
118 change(&f)
119 none("prefer_switch, "+what, f)
120 }
121
122 // defer_tasks: the urgent work not held for headroom, or no normal
123 // task without a deadline, or the normal one has a deadline.
124 for what, change := range map[string]func(*Facts){
125 "urgent not held": func(f *Facts) { f.Steps[0].Hold = "" },
126 "held for the budget": func(f *Facts) { f.Steps[0].Hold = wire.HoldBudget },
127 "another role": func(f *Facts) { f.Steps[1].Role, f.Steps[2].Role = wire.SpecialistReview, wire.SpecialistReview },
128 "normal ones by dates": func(f *Facts) { f.Tasks[1].By, f.Tasks[2].By = at(48*time.Hour), at(48*time.Hour) },
129 "housekeeping's": func(f *Facts) { f.Steps[1].Housekeeping, f.Steps[2].Housekeeping = true, true },
130 } {
131 f := fixtures()[wire.AdviceDeferTasks]
132 change(&f)
133 none("defer_tasks, "+what, f)
134 }
135 // A deadline counts as urgent work.
136 f = fixtures()[wire.AdviceDeferTasks]
137 f.Tasks[0].Priority, f.Tasks[0].By = wire.PriorityNormal, at(48*time.Hour)
138 if got := Compute(f, now); len(got) != 1 || got[0].Key != "defer_tasks:tk2,tk3" {
139 t.Fatalf("deadline work: %+v", got)
140 }
141
142 // held_long: a day short of a week, normal priority, no longer held.
143 for what, change := range map[string]func(*Facts){
144 "six days": func(f *Facts) { f.Steps[0].HeldSince = at(-6 * 24 * time.Hour) },
145 "normal": func(f *Facts) { f.Tasks[0].Priority = wire.PriorityNormal },
146 "not held": func(f *Facts) { f.Steps[0].Hold = "" },
147 "no held day": func(f *Facts) { f.Steps[0].HeldSince = nil },
148 } {
149 f := fixtures()[wire.AdviceHeldLong]
150 change(&f)
151 none("held_long, "+what, f)
152 }
153}
154
155// Ties pick the same card on every run: all four kinds and several of
156// each eligible at once, the facts shuffled every time.
157func TestTiesPickTheSameCard(t *testing.T) {
158 fx := fixtures()
159 var all Facts
160 all.Primary, all.Preference = "r1", fx[wire.AdvicePreferSwitch].Preference
161 for _, kind := range wire.AdviceKinds {
162 f := fx[kind]
163 all.Conns = append(all.Conns, f.Conns...)
164 all.Tasks = append(all.Tasks, f.Tasks...)
165 all.Steps = append(all.Steps, f.Steps...)
166 }
167 // A second metered connection near its budget, a second room target,
168 // review waiting too.
169 tx2 := all.Conns[0]
170 tx2.ID = "cn_ta"
171 cx2 := fx[wire.AdvicePreferSwitch].Conns[1]
172 cx2.ID = "cn_ca"
173 all.Conns = append(all.Conns, tx2, cx2)
174 all.Steps = append(all.Steps, Step{Task: "tk1", Role: wire.SpecialistReview, Runner: "r1"})
175 // The quiet Claude copies are duplicates of cn_cl: keep one Claude.
176 all.Conns = slices.DeleteFunc(all.Conns, func(c Conn) bool {
177 return c.ID == "cn_cl" && c.Windows[0].Used < NearLimit
178 })
179 first := Compute(all, now)
180 if len(first) < 6 || first[0].Key != "budget_near:cn_ta" {
181 t.Fatalf("first: %d, %+v", len(first), first)
182 }
183 var keys []string
184 for _, a := range first {
185 keys = append(keys, a.Key)
186 }
187 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"}
188 if !slices.Equal(keys, want) {
189 t.Fatalf("order %v", keys)
190 }
191 rng := rand.New(rand.NewPCG(1, 2))
192 for i := 0; i < 500; i++ {
193 f := all
194 f.Conns, f.Tasks, f.Steps = slices.Clone(all.Conns), slices.Clone(all.Tasks), slices.Clone(all.Steps)
195 rng.Shuffle(len(f.Conns), func(a, b int) { f.Conns[a], f.Conns[b] = f.Conns[b], f.Conns[a] })
196 rng.Shuffle(len(f.Tasks), func(a, b int) { f.Tasks[a], f.Tasks[b] = f.Tasks[b], f.Tasks[a] })
197 rng.Shuffle(len(f.Steps), func(a, b int) { f.Steps[a], f.Steps[b] = f.Steps[b], f.Steps[a] })
198 var got []string
199 for _, a := range Compute(f, now) {
200 got = append(got, a.Key)
201 }
202 if !slices.Equal(got, want) {
203 t.Fatalf("run %d: %v", i, got)
204 }
205 if c := Choose(Compute(f, now), nil, false, now, now, time.UTC); c == nil || c.Key != want[0] {
206 t.Fatalf("run %d chose %+v", i, c)
207 }
208 }
209 // Within a task set, the earliest task decides, then its id.
210 a := taskSet(wire.AdviceDeferTasks, []Task{{ID: "tkb", CreatedAt: now}})
211 b := taskSet(wire.AdviceDeferTasks, []Task{{ID: "tka", CreatedAt: now.Add(time.Second)}})
212 if !Less(a, b) || Less(b, a) {
213 t.Fatal("the earliest task does not decide")
214 }
215}
216
217// Not now silences a key for 14 days, and for 60 after a second Not now;
218// another key is not silenced.
219func TestNotNowSilences(t *testing.T) {
220 eligible := Compute(fixtures()[wire.AdviceBudgetNear], now)
221 k := eligible[0].Key
222 once := []Past{{Key: k, State: wire.AdviceDismissed, Shown: now, DismissedAt: at(0)}}
223 for _, c := range []struct {
224 days int
225 show bool
226 }{{1, false}, {13, false}, {14, true}, {30, true}} {
227 later := now.Add(time.Duration(c.days) * 24 * time.Hour)
228 if got := Choose(eligible, once, false, later, later, time.UTC); (got != nil) != c.show {
229 t.Fatalf("one Not now, day %d: %+v", c.days, got)
230 }
231 }
232 twice := append(slices.Clone(once), Past{Key: k, State: wire.AdviceDismissed, Shown: now.Add(15 * 24 * time.Hour), DismissedAt: at(15 * 24 * time.Hour)})
233 for _, c := range []struct {
234 days int
235 show bool
236 }{{16, false}, {29, false}, {74, false}, {75, true}} {
237 later := now.Add(time.Duration(c.days) * 24 * time.Hour)
238 if got := Choose(eligible, twice, false, later, later, time.UTC); (got != nil) != c.show {
239 t.Fatalf("two Not nows, day %d: %+v", c.days, got)
240 }
241 }
242 if !SilencedUntil("budget_near:other", twice).IsZero() {
243 t.Fatal("another key was silenced")
244 }
245 // Acted or withdrawn advice silences nothing.
246 acted := []Past{{Key: k, State: wire.AdviceActed, Shown: now}, {Key: k, State: wire.AdviceWithdrawn, Shown: now}}
247 if !SilencedUntil(k, acted).IsZero() {
248 t.Fatal("acted advice silenced its key")
249 }
250}
251
252// No day shows two cards, and none shows while one is open: a card new
253// today (even one already acted on or withdrawn) keeps every other away
254// until tomorrow, in the person's zone; a card made in quiet hours
255// counts for the day it shows.
256func TestNoDayShowsTwoCards(t *testing.T) {
257 eligible := Compute(fixtures()[wire.AdvicePreferSwitch], now)
258 if Choose(eligible, nil, true, now, now, time.UTC) != nil {
259 t.Fatal("a card while one is open")
260 }
261 for _, state := range []string{wire.AdviceActed, wire.AdviceWithdrawn, wire.AdviceDismissed} {
262 past := []Past{{Key: "budget_near:cn_tx", State: state, Shown: now.Add(-2 * time.Hour)}}
263 if c := Choose(eligible, past, false, now, now, time.UTC); c != nil {
264 t.Fatalf("a second card the same day after %s", state)
265 }
266 tomorrow := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)
267 if c := Choose(eligible, past, false, tomorrow, tomorrow, time.UTC); c == nil {
268 t.Fatalf("no card the next day after %s", state)
269 }
270 }
271 // Made at 23:00, shown at 08:00 tomorrow: tomorrow's one card.
272 night := time.Date(2026, 11, 12, 23, 0, 0, 0, time.UTC)
273 morning := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)
274 past := []Past{{Key: "x", State: wire.AdviceOpen, Shown: morning}}
275 if c := Choose(eligible, past, false, morning.Add(time.Hour), morning.Add(time.Hour), time.UTC); c != nil {
276 t.Fatal("two cards the morning a night card showed")
277 }
278 if c := Choose(eligible, nil, false, night, morning, time.UTC); c == nil {
279 t.Fatal("no card for tomorrow from tonight's facts")
280 }
281 // The day is the person's: in a zone where it is already tomorrow.
282 east := time.FixedZone("east", 3*3600)
283 late := time.Date(2026, 11, 12, 22, 30, 0, 0, time.UTC)
284 past = []Past{{Key: "x", State: wire.AdviceActed, Shown: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)}}
285 if c := Choose(eligible, past, false, late, late, east); c == nil {
286 t.Fatal("the person's next day had no card")
287 }
288 // And one shown just after their midnight is that day's card.
289 past = []Past{{Key: "x", State: wire.AdviceActed, Shown: time.Date(2026, 11, 12, 21, 30, 0, 0, time.UTC)}}
290 if c := Choose(eligible, past, false, late, late, east); c != nil {
291 t.Fatal("two cards on the person's day")
292 }
293}
294