oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "slices"
8 "strings"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15const adviceOwner = "owner@example.com"
16
17// adviceRig is the metered rig with one clock for the store and the
18// housekeeping loop, and the TensorX connection's spend set.
19type adviceRig struct {
20 *meteredRig
21 at time.Time
22 ctx context.Context
23}
24
25func newAdviceRig(t *testing.T) *adviceRig {
26 r := &adviceRig{meteredRig: newMeteredRig(t), at: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC), ctx: context.Background()}
27 r.s.now = func() time.Time { return r.at }
28 r.s.SetHousekeepingClock(func() time.Time { return r.at })
29 r.spend(840_000, 6_200_000)
30 // The person's primary runner, at the current protocol.
31 for _, q := range []string{
32 "CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)",
33 "INSERT INTO runners(id, person, role) VALUES ('RUNNER1', 'owner@example.com', 'primary')",
34 } {
35 if err := r.s.db.G.Exec(q).Error; err != nil {
36 t.Fatal(err)
37 }
38 }
39 if err := r.s.db.G.Create(&runnerSessionRecord{RunnerID: "RUNNER1", Generation: 1, Connected: true, Protocol: wire.ProtocolCurrent, SeenAt: r.at}).Error; err != nil {
40 t.Fatal(err)
41 }
42 return r
43}
44
45func (r *adviceRig) spend(day, month int64) {
46 r.t.Helper()
47 raw := asJSON(wire.Spend{Day: day, Month: month, Currency: "USD"})
48 if err := r.s.db.G.Exec("UPDATE chat_connections SET spend = ? WHERE id = 'cn_made'", raw).Error; err != nil {
49 r.t.Fatal(err)
50 }
51}
52
53func (r *adviceRig) refresh() {
54 r.t.Helper()
55 if err := r.s.RefreshAdvice(r.ctx, adviceOwner); err != nil {
56 r.t.Fatal(err)
57 }
58}
59
60func (r *adviceRig) rows() []adviceRecord {
61 r.t.Helper()
62 var rows []adviceRecord
63 if err := r.s.db.G.Where("person = ?", adviceOwner).Order("created_at, id").Find(&rows).Error; err != nil {
64 r.t.Fatal(err)
65 }
66 return rows
67}
68
69func (r *adviceRig) card(id string) cardRecord {
70 r.t.Helper()
71 var c cardRecord
72 if err := r.s.db.G.Where("id = ?", id).First(&c).Error; err != nil {
73 r.t.Fatal(err)
74 }
75 return c
76}
77
78func (r *adviceRig) commands(kind string) []commandRecord {
79 var cs []commandRecord
80 r.s.db.G.Where("kind = ?", kind).Order("seq").Find(&cs)
81 return cs
82}
83
84// budget_near end to end in the store: one card, at the top of the
85// day's advice and as one quiet conversation card that is never Needs
86// you; a stale revision acts on nothing; its action is the ordinary
87// budget call at the budget's revision, in the advice's transaction,
88// audited as the call and as advice with its key; no day shows two.
89func TestAdviceStoreActsThroughTheOrdinaryCall(t *testing.T) {
90 r := newAdviceRig(t)
91 r.refresh()
92 r.refresh()
93 rows := r.rows()
94 if len(rows) != 1 || rows[0].Kind != wire.AdviceBudgetNear || rows[0].Key != "budget_near:cn_made" || rows[0].State != wire.AdviceOpen || rows[0].VisibleAt != nil {
95 t.Fatalf("rows %+v", rows)
96 }
97 a := rows[0]
98 c := r.card(a.CardID)
99 if c.Kind != wire.CardAdvice || c.State != wire.CardOpen || c.Held || c.TaskID != "" || c.Options != `["act","dismiss"]` {
100 t.Fatalf("card %+v", c)
101 }
102 if !strings.HasPrefix(a.Act, "advice.budget_near.raise_day") || !strings.HasPrefix(a.Dismiss, "advice.leave_it") {
103 t.Fatalf("words %q %q", a.Act, a.Dismiss)
104 }
105 list, err := r.s.Advice(r.ctx, adviceOwner)
106 if err != nil || len(list.Items) != 1 || list.Items[0].ID != a.ID || list.Items[0].Subject.Connection != "cn_made" {
107 t.Fatalf("list %+v %v", list, err)
108 }
109 if needs, err := r.s.NeedsYou(r.ctx, adviceOwner); err != nil || len(needs.Items) != 0 {
110 t.Fatalf("advice was Needs you: %+v %v", needs.Items, err)
111 }
112 // The coordinator has no write: no tool names advice.
113 for _, tool := range append(slices.Clone(wire.ConverseTools), wire.WriteTools...) {
114 if strings.Contains(tool, "advice") {
115 t.Fatalf("the coordinator has %s", tool)
116 }
117 }
118 r.audits = nil
119 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision + 1}); !errors.Is(err, ErrConflict) {
120 t.Fatalf("a stale revision: %v", err)
121 }
122 if _, err := r.s.ActAdvice(r.ctx, "member@example.com", a.ID, wire.AdviceAction{Revision: a.Revision}); !errors.Is(err, ErrNotFound) {
123 t.Fatalf("another person's act: %v", err)
124 }
125 if len(r.commands(wire.FrameBudget)) != 0 || len(r.audits) != 0 {
126 t.Fatal("a refused act changed something")
127 }
128 // Facts that stopped holding since the last look act on nothing.
129 r.spend(100_000, 1_000_000)
130 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); !errors.Is(err, ErrConflict) || len(r.commands(wire.FrameBudget)) != 0 {
131 t.Fatalf("acted on facts that no longer hold: %v", err)
132 }
133 r.spend(840_000, 6_200_000)
134 out, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision})
135 if err != nil || out.State != wire.AdviceActed {
136 t.Fatalf("act: %+v %v", out, err)
137 }
138 cmds := r.commands(wire.FrameBudget)
139 var cmd wire.BudgetCommand
140 if len(cmds) != 1 || json.Unmarshal([]byte(cmds[0].Body), &cmd) != nil || cmd.Budget.Day != 2_000_000 || cmd.Budget.Month != 10_000_000 || cmd.Budget.Revision != 2 {
141 t.Fatalf("budget frames %+v", cmds)
142 }
143 if !slices.Contains(r.audits, adviceOwner+" connection.budget cn_made@2") || !slices.Contains(r.audits, adviceOwner+" advice.act source=advice id="+a.ID+" key=budget_near:cn_made") {
144 t.Fatalf("audits %v", r.audits)
145 }
146 if c := r.card(a.CardID); c.State != wire.CardAnswered || c.Choice != wire.ChoiceAct {
147 t.Fatalf("card after act %+v", c)
148 }
149 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: out.Revision}); !errors.Is(err, ErrConflict) {
150 t.Fatalf("acted twice: %v", err)
151 }
152 // Still near the month's budget later that day: no second card today.
153 r.spend(840_000, 9_000_000)
154 r.at = r.at.Add(3 * time.Hour)
155 r.refresh()
156 if n := len(r.rows()); n != 1 {
157 t.Fatalf("%d cards in a day", n)
158 }
159 r.at = r.at.Add(21 * time.Hour)
160 r.refresh()
161 if rows := r.rows(); len(rows) != 2 || rows[1].Key != "budget_near:cn_made" {
162 t.Fatalf("the next day: %+v", rows)
163 }
164}
165
166// Not now silences the key for 14 days, then 60 after a second Not now;
167// advice whose facts stop holding is withdrawn without a word (its card
168// resolved, nothing said) and still counts as the day's card.
169func TestAdviceStoreNotNowAndWithdrawal(t *testing.T) {
170 r := newAdviceRig(t)
171 r.refresh()
172 a := r.rows()[0]
173 if _, err := r.s.DismissAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); err != nil {
174 t.Fatal(err)
175 }
176 if c := r.card(a.CardID); c.State != wire.CardAnswered || c.Choice != wire.ChoiceDismiss {
177 t.Fatalf("card %+v", c)
178 }
179 if !slices.Contains(r.audits, adviceOwner+" advice.dismiss source=advice id="+a.ID+" key=budget_near:cn_made") {
180 t.Fatalf("audits %v", r.audits)
181 }
182 day := func(d int) {
183 r.at = time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC).AddDate(0, 0, d)
184 r.refresh()
185 }
186 day(1)
187 day(13)
188 if n := len(r.rows()); n != 1 {
189 t.Fatalf("shown again within 14 days: %d", n)
190 }
191 day(14)
192 rows := r.rows()
193 if len(rows) != 2 {
194 t.Fatalf("not shown after 14 days: %d", len(rows))
195 }
196 if _, err := r.s.DismissAdvice(r.ctx, adviceOwner, rows[1].ID, wire.AdviceAction{Revision: rows[1].Revision}); err != nil {
197 t.Fatal(err)
198 }
199 day(28)
200 day(73)
201 if n := len(r.rows()); n != 2 {
202 t.Fatalf("shown again within 60 days of the second Not now: %d", n)
203 }
204 day(74)
205 rows = r.rows()
206 if len(rows) != 3 {
207 t.Fatalf("not shown 60 days after the second Not now: %d", len(rows))
208 }
209 // The facts stop holding: withdrawn, its card resolved, and no
210 // other card that day.
211 events := func() int64 {
212 var n int64
213 r.s.db.G.Model(&eventRecord{}).Where("type = ?", wire.EventCard).Count(&n)
214 return n
215 }
216 r.spend(100_000, 1_000_000)
217 before := events()
218 r.refresh()
219 rows = r.rows()
220 if rows[2].State != wire.AdviceWithdrawn || len(rows) != 3 {
221 t.Fatalf("withdrawal %+v", rows)
222 }
223 if c := r.card(rows[2].CardID); c.State != wire.CardResolved || c.Choice != "" {
224 t.Fatalf("withdrawn card %+v", c)
225 }
226 if events() != before+1 {
227 t.Fatal("the withdrawal said more than its card's change")
228 }
229 if list, _ := r.s.Advice(r.ctx, adviceOwner); len(list.Items) != 0 {
230 t.Fatalf("withdrawn advice listed %+v", list.Items)
231 }
232 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, rows[2].ID, wire.AdviceAction{Revision: rows[2].Revision}); !errors.Is(err, ErrConflict) {
233 t.Fatalf("withdrawn advice acted: %v", err)
234 }
235 r.spend(900_000, 1_000_000)
236 r.refresh()
237 if n := len(r.rows()); n != 3 {
238 t.Fatalf("a second card the day one was withdrawn: %d", n)
239 }
240}
241
242// Quiet hours (housekeeping's VisibleAt): a card made at 23:00 waits,
243// held, until 08:00; it is not listed or answerable before then, and the
244// loop's minute shows it.
245func TestAdviceStoreQuietHours(t *testing.T) {
246 r := newAdviceRig(t)
247 // Today's card came and went this morning; tonight's facts may make
248 // tomorrow's card, held until 08:00.
249 r.refresh()
250 first := r.rows()[0]
251 if _, err := r.s.DismissAdvice(r.ctx, adviceOwner, first.ID, wire.AdviceAction{Revision: first.Revision}); err != nil {
252 t.Fatal(err)
253 }
254 r.s.db.G.Exec("UPDATE chat_advice SET key = 'budget_near:older', state = 'acted' WHERE id = ?", first.ID)
255 r.at = time.Date(2026, 11, 12, 23, 0, 0, 0, time.UTC)
256 r.refresh()
257 rows := r.rows()[1:]
258 morning := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)
259 if len(rows) != 1 || rows[0].VisibleAt == nil || !rows[0].VisibleAt.Equal(morning) || !rows[0].ShownAt.Equal(morning) {
260 t.Fatalf("rows %+v", rows)
261 }
262 if c := r.card(rows[0].CardID); !c.Held {
263 t.Fatal("the card was not held for quiet hours")
264 }
265 if list, _ := r.s.Advice(r.ctx, adviceOwner); len(list.Items) != 0 {
266 t.Fatal("listed in quiet hours")
267 }
268 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, rows[0].ID, wire.AdviceAction{Revision: rows[0].Revision}); !errors.Is(err, ErrConflict) {
269 t.Fatalf("acted in quiet hours: %v", err)
270 }
271 r.at = morning.Add(time.Minute)
272 if err := r.s.HousekeepingTick(r.ctx); err != nil {
273 t.Fatal(err)
274 }
275 if c := r.card(rows[0].CardID); c.Held {
276 t.Fatal("still held after quiet hours")
277 }
278 if list, _ := r.s.Advice(r.ctx, adviceOwner); len(list.Items) != 1 {
279 t.Fatal("not listed after quiet hours")
280 }
281 r.at = morning.Add(time.Hour)
282 r.refresh()
283 if n := len(r.rows()); n != 2 {
284 t.Fatalf("the morning brought a second card: %d", n)
285 }
286}
287
288// A hold's start is kept while the step stays held, whatever the runner
289// says of it again; it goes with the hold, and a new hold starts anew.
290func TestAcceptHoldKeepsHeldSince(t *testing.T) {
291 t0 := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
292 s := stepRecord{State: wire.StepQueued}
293 report := func(h *wire.StepHold, at time.Time) {
294 acceptHold(&s, &wire.StepReport{State: wire.StepRunning, Hold: h}, at)
295 }
296 wake := t0.Add(time.Hour)
297 report(&wire.StepHold{Reason: wire.HoldHeadroom, StepRevision: 1}, t0)
298 report(&wire.StepHold{Reason: wire.HoldHeadroom, WakeAt: &wake, StepRevision: 1}, t0.Add(2*time.Hour))
299 report(&wire.StepHold{Reason: wire.HoldBudget, StepRevision: 1}, t0.Add(48*time.Hour))
300 if s.HeldAt == nil || !s.HeldAt.Equal(t0) {
301 t.Fatalf("held since %v", s.HeldAt)
302 }
303 report(nil, t0.Add(49*time.Hour))
304 if s.HeldAt != nil || s.Hold != "" {
305 t.Fatal("the hold's start stayed after the hold")
306 }
307 report(&wire.StepHold{Reason: wire.HoldHeadroom, StepRevision: 2}, t0.Add(50*time.Hour))
308 if s.HeldAt == nil || !s.HeldAt.Equal(t0.Add(50*time.Hour)) {
309 t.Fatalf("a new hold since %v", s.HeldAt)
310 }
311}
312
313// defer_tasks and held_long act task by task through the priority call,
314// each at the revision the advice read; a task that moved since acts on
315// nothing, the others included.
316func TestAdviceStoreTaskActions(t *testing.T) {
317 r := newAdviceRig(t)
318 r.spend(0, 0)
319 g := r.s.db.G
320 now := r.at
321 if err := g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
322 t.Fatal(err)
323 }
324 reset := now.Add(50 * time.Hour)
325 held := asJSON(wire.StepHold{Reason: wire.HoldHeadroom, Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1})
326 for i, k := range []taskRecord{
327 {ID: "tk1", Priority: wire.PriorityUrgent, Revision: 4},
328 {ID: "tk2", Priority: wire.PriorityNormal, Revision: 7},
329 {ID: "tk3", Revision: 1},
330 } {
331 k.ProjectID, k.Title, k.Stage, k.Creator, k.CreatedAt, k.UpdatedAt = "p_1", k.ID, wire.StageInProgress, adviceOwner, now.Add(time.Duration(i)*time.Minute), now
332 if err := g.Create(&k).Error; err != nil {
333 t.Fatal(err)
334 }
335 s := stepRecord{ID: "s" + k.ID, TaskID: k.ID, Idx: 1, Specialist: wire.SpecialistEngineering, Person: adviceOwner, State: wire.StepQueued, Attempt: 1, RunnerID: "RUNNER1", Revision: 1, CreatedAt: now, UpdatedAt: now}
336 if k.ID != "tk3" {
337 s.Hold, s.HeldAt = held, &now
338 }
339 if err := g.Create(&s).Error; err != nil {
340 t.Fatal(err)
341 }
342 }
343 r.refresh()
344 rows := r.rows()
345 if len(rows) != 1 || rows[0].Key != "defer_tasks:tk2,tk3" || !strings.HasPrefix(rows[0].Text, "advice.defer_tasks.many") {
346 t.Fatalf("rows %+v", rows)
347 }
348 a := rows[0]
349 // tk3 moved after the advice read it: nothing changes, tk2 included.
350 g.Exec("UPDATE chat_tasks SET revision = 2 WHERE id = 'tk3'")
351 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); !errors.Is(err, ErrConflict) {
352 t.Fatalf("a moved task: %v", err)
353 }
354 var tk2 taskRecord
355 g.Where("id = 'tk2'").First(&tk2)
356 if tk2.Priority != wire.PriorityNormal {
357 t.Fatal("a refused act changed a task")
358 }
359 // The next look follows the facts (a new revision); then it acts.
360 r.refresh()
361 a = r.rows()[0]
362 if a.Revision != 2 {
363 t.Fatalf("revision %d", a.Revision)
364 }
365 r.audits = nil
366 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); err != nil {
367 t.Fatal(err)
368 }
369 for _, id := range []string{"tk2", "tk3"} {
370 var k taskRecord
371 g.Where("id = ?", id).First(&k)
372 if k.Priority != wire.PriorityLow || k.PrioritySetBy != wire.PrioritySetByPerson {
373 t.Fatalf("%s: %+v", id, k)
374 }
375 }
376 if !slices.Contains(r.audits, adviceOwner+" task.priority tk2@low") || !slices.Contains(r.audits, adviceOwner+" task.priority tk3@low") || !slices.Contains(r.audits, adviceOwner+" advice.act source=advice id="+a.ID+" key=defer_tasks:tk2,tk3") {
377 t.Fatalf("audits %v", r.audits)
378 }
379
380 // A week later, the low tasks still held: held_long, Make them
381 // normal through the card in the conversation.
382 r.at = now.AddDate(0, 0, 8)
383 g.Exec("UPDATE chat_steps SET hold = ?, held_at = ? WHERE task_id IN ('tk2','tk3')", held, now)
384 g.Exec("UPDATE chat_steps SET hold = '', held_at = NULL WHERE task_id = 'tk1'")
385 r.refresh()
386 rows = r.rows()
387 if len(rows) != 2 || rows[1].Key != "held_long:tk2,tk3" {
388 t.Fatalf("rows %+v", rows)
389 }
390 c := r.card(rows[1].CardID)
391 if _, _, err := r.s.Answer(r.ctx, adviceOwner, c.ID, wire.AnswerCard{Choice: wire.ChoiceAct, Revision: c.Revision}); err != nil {
392 t.Fatal(err)
393 }
394 for _, id := range []string{"tk2", "tk3"} {
395 var k taskRecord
396 g.Where("id = ?", id).First(&k)
397 if k.Priority != wire.PriorityNormal {
398 t.Fatalf("%s: %s", id, k.Priority)
399 }
400 }
401 if rows := r.rows(); rows[1].State != wire.AdviceActed {
402 t.Fatalf("after the card: %+v", rows[1])
403 }
404}
405
406// prefer_switch acts as PUT /connections/preference with an end: the
407// other provider until the preferred one's window resets, revision-
408// checked, sent to the runner.
409func TestAdviceStorePreferSwitch(t *testing.T) {
410 r := newAdviceRig(t)
411 r.spend(0, 0)
412 g := r.s.db.G
413 now := r.at
414 resets, soon := now.Add(50*time.Hour), now.Add(3*time.Hour)
415 for _, c := range []connectionRecord{
416 {ID: "cn_cl", Person: adviceOwner, RunnerID: "RUNNER1", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: asJSON(wire.Headroom{Windows: []wire.Window{{Name: "seven_day", UsedPercent: 85, Minutes: 10080, ResetsAt: &resets}}}), Revision: 1, CreatedAt: now, UpdatedAt: now},
417 {ID: "cn_cx", Person: adviceOwner, RunnerID: "RUNNER1", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: asJSON(wire.Headroom{Windows: []wire.Window{{Name: "primary", UsedPercent: 20, Minutes: 300, ResetsAt: &soon}}}), Revision: 1, CreatedAt: now, UpdatedAt: now},
418 } {
419 if err := g.Create(&c).Error; err != nil {
420 t.Fatal(err)
421 }
422 }
423 pref, err := r.s.SetPreference(r.ctx, adviceOwner, wire.Preferences{Provider: wire.ProviderClaude})
424 if err != nil {
425 t.Fatal(err)
426 }
427 if err := g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
428 t.Fatal(err)
429 }
430 g.Create(&taskRecord{ID: "tk1", ProjectID: "p_1", Title: "T", Stage: wire.StageInProgress, Creator: adviceOwner, Revision: 1, CreatedAt: now, UpdatedAt: now})
431 g.Create(&stepRecord{ID: "s1", TaskID: "tk1", Idx: 1, Specialist: wire.SpecialistEngineering, Person: adviceOwner, State: wire.StepQueued, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now})
432 r.refresh()
433 rows := r.rows()
434 if len(rows) != 1 || rows[0].Key != "prefer_switch:engineering/cn_cx" {
435 t.Fatalf("rows %+v", rows)
436 }
437 a := rows[0]
438 if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); err != nil {
439 t.Fatal(err)
440 }
441 got, _ := r.s.Preference(r.ctx, adviceOwner)
442 if got.Provider != wire.ProviderCodex || got.Until == nil || !got.Until.Equal(resets) || got.Revision != pref.Revision+1 {
443 t.Fatalf("preference %+v", got)
444 }
445 var cmd wire.PreferenceCommand
446 cmds := r.commands(wire.FramePreference)
447 if len(cmds) == 0 || json.Unmarshal([]byte(cmds[len(cmds)-1].Body), &cmd) != nil || cmd.Provider != wire.ProviderCodex || cmd.Until == nil {
448 t.Fatalf("preference frames %+v", cmds)
449 }
450}
451