oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package connect
2
3import (
4 "os"
5 "strings"
6 "testing"
7 "time"
8
9 "amadan.net/rastrillo/rastrillo/budget"
10)
11
12func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
13
14func TestChoose(t *testing.T) {
15 now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
16 claude := Candidate{ID: "claude-a", Provider: "claude", State: StateHealthy}
17 claude2 := Candidate{ID: "claude-2", Provider: "claude", State: StateHealthy}
18 codex := Candidate{ID: "codex-1", Provider: "codex", State: StateHealthy}
19 limited := func(c Candidate, until time.Time) Candidate { c.State, c.ResetsAt = StateLimited, until; return c }
20 used := func(c Candidate, u float64) Candidate { c.Used, c.Known = u, true; return c }
21 for _, tc := range []struct {
22 name string
23 cs []Candidate
24 role, current string
25 avoid []string
26 prefer string
27 want, reason string
28 }{
29 {"one", []Candidate{claude}, RoleCoordinator, "", nil, "", "claude-a", ReasonOnlyOption},
30 {"none", []Candidate{limited(claude, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "", "", ""},
31 {"configured order first", []Candidate{claude, codex}, RoleCoordinator, "", nil, "", "claude-a", ReasonHeadroom},
32 {"reported headroom before unknown", []Candidate{claude, used(codex, 0.8)}, RoleCoordinator, "", nil, "", "codex-1", ReasonHeadroom},
33 {"most headroom", []Candidate{used(claude, 0.5), used(claude2, 0.2), used(codex, 0.4)}, RoleCoordinator, "", nil, "", "claude-2", ReasonHeadroom},
34 {"sticky", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "", "codex-1", ReasonHeadroom},
35 {"failover from limited", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonOnlyOption},
36 {"failover among several", []Candidate{limited(claude, now.Add(time.Hour)), claude2, codex}, RoleCoordinator, "claude-a", nil, "", "claude-2", ReasonFailover},
37 {"reset passed", []Candidate{limited(claude, now.Add(-time.Minute)), codex}, RoleCoordinator, "claude-a", nil, "", "claude-a", ReasonHeadroom},
38 {"limited without reset never by itself", []Candidate{limited(claude, time.Time{})}, RoleCoordinator, "", nil, "", "", ""},
39 {"stickiness is a rule", []Candidate{used(claude, 0.97), used(codex, 0.1)}, RoleCoordinator, "claude-a", nil, "", "claude-a", ReasonHeadroom},
40 {"failover to the most headroom", []Candidate{limited(claude, now.Add(time.Hour)), used(claude2, 0.7), used(codex, 0.2)}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonFailover},
41 {"engineering fails over to codex", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleEngineering, "claude-a", nil, "", "codex-1", ReasonOnlyOption},
42 {"review away from engineering's on codex", []Candidate{claude, codex}, RoleReview, "", []string{"claude-a"}, "", "codex-1", ReasonOnlyOption},
43 {"avoid", []Candidate{claude, claude2}, RoleEngineering, "", []string{"claude-a"}, "", "claude-2", ReasonOnlyOption},
44 {"signed out never", []Candidate{{ID: "claude-a", Provider: "claude", State: "sign_in_again"}, codex}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonOnlyOption},
45 {"unchecked is never chosen", []Candidate{{ID: "codex-1", Provider: "codex"}}, RoleCoordinator, "", nil, "", "", ""},
46 {"preference first", []Candidate{claude, used(codex, 0.9)}, RoleCoordinator, "", nil, "codex", "codex-1", ReasonPreference},
47 {"preference takes the session back at a boundary", []Candidate{claude, codex}, RoleCoordinator, "claude-a", nil, "codex", "codex-1", ReasonPreference},
48 {"on the preference already", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "codex", "codex-1", ReasonHeadroom},
49 {"preference never overrides health", []Candidate{claude, limited(codex, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "codex", "claude-a", ReasonOnlyOption},
50 {"preference among a provider's accounts by headroom", []Candidate{used(claude, 0.6), used(claude2, 0.1), codex}, RoleCoordinator, "", nil, "claude", "claude-2", ReasonPreference},
51 {"preference nothing here can use", []Candidate{claude, claude2, codex}, RoleEngineering, "claude-a", nil, "pi", "claude-a", ReasonHeadroom},
52 {"connecting is never chosen", []Candidate{{ID: "codex-1", Provider: "codex", State: "connecting"}}, RoleCoordinator, "", nil, "", "", ""},
53 } {
54 t.Run(tc.name, func(t *testing.T) {
55 got, ok := Choose(tc.cs, tc.role, tc.current, tc.prefer, tc.avoid, now, false)
56 if ok != (tc.want != "") || got.ID != tc.want || got.Reason != tc.reason {
57 t.Fatalf("Choose = %+v %v, want %s %s", got, ok, tc.want, tc.reason)
58 }
59 })
60 }
61}
62
63func TestLimitedUntil(t *testing.T) {
64 now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
65 if at, wait := LimitedUntil(now.Add(48*time.Hour), 0, now); !at.Equal(now.Add(48*time.Hour)) || wait != 0 {
66 t.Fatalf("provider reset not kept: %v %v", at, wait)
67 }
68 var wait time.Duration
69 for i, want := range []time.Duration{15 * time.Minute, 30 * time.Minute, time.Hour, time.Hour} {
70 var at time.Time
71 at, wait = LimitedUntil(time.Time{}, wait, now)
72 if !at.Equal(now.Add(want)) {
73 t.Fatalf("refusal %d: until %v, want +%v", i, at.Sub(now), want)
74 }
75 }
76 if at := NextCheck([]Candidate{{State: StateLimited, ResetsAt: now.Add(time.Hour)}, {State: StateLimited, ResetsAt: now.Add(time.Minute)}, {State: StateHealthy}}, now); !at.Equal(now.Add(time.Minute)) {
77 t.Fatalf("NextCheck %v", at)
78 }
79}
80
81// The recorded allowed_warning event from the pinned CLI, and the same
82// event refused.
83const recorded = `{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","resetsAt":1794211200,"rateLimitType":"seven_day","utilization":0.54,"overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"unifiedWindows":{"seven_day":{"utilization":0.54,"resetsAt":1794211200,"status":"allowed"}}},"uuid":"u","session_id":"s"}`
84
85func TestClaudeRateLimit(t *testing.T) {
86 l, ok := ClaudeRateLimit([]byte(recorded))
87 if !ok || l.Limited || l.Headroom == nil || *l.Headroom.Utilization != 0.54 || l.Window != "seven_day" || l.ResetsAt.Unix() != 1794211200 || len(l.Headroom.Windows) != 1 || l.Headroom.Windows[0].Minutes != 10080 {
88 t.Fatalf("allowed_warning: %+v %v", l, ok)
89 }
90 l, ok = ClaudeRateLimit([]byte(strings.Replace(recorded, `"allowed_warning"`, `"rejected"`, 1)))
91 if !ok || !l.Limited || l.ResetsAt.Unix() != 1794211200 {
92 t.Fatalf("rejected: %+v", l)
93 }
94 if _, ok = ClaudeRateLimit([]byte(`{"type":"result","session_id":"s"}`)); ok {
95 t.Fatal("a result read as a rate limit")
96 }
97 l, _ = ClaudeRateLimit([]byte(`{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"},"session_id":"s"}`))
98 if !l.Limited || !l.ResetsAt.IsZero() || l.Headroom.ResetsAt != nil {
99 t.Fatalf("a reset time was invented: %+v", l)
100 }
101}
102
103func TestCodexRateLimits(t *testing.T) {
104 l, plan, ok := CodexRateLimits([]byte(`{"primary":{"usedPercent":40,"windowDurationMins":300,"resetsAt":1794211200},"secondary":{"usedPercent":12,"windowDurationMins":10080,"resetsAt":1794500000},"planType":"pro","limitId":null,"limitName":null,"rateLimitReachedType":null}`))
105 if !ok || l.Limited || plan != "pro" || *l.Headroom.Utilization != 0.4 || len(l.Headroom.Windows) != 2 || l.Headroom.ResetsAt != nil {
106 t.Fatalf("snapshot: %+v %s", l, plan)
107 }
108 l, _, _ = CodexRateLimits([]byte(`{"primary":{"usedPercent":100,"windowDurationMins":300,"resetsAt":1794211200},"secondary":{"usedPercent":100,"windowDurationMins":10080,"resetsAt":1794500000}}`))
109 if !l.Limited || l.ResetsAt.Unix() != 1794500000 || l.Window != "secondary" {
110 t.Fatalf("spent: %+v", l)
111 }
112 l, _, _ = CodexRateLimits([]byte(`{"primary":{"usedPercent":20},"rateLimitReachedType":"workspace_member_usage_limit_reached"}`))
113 if !l.Limited || !l.ResetsAt.IsZero() {
114 t.Fatalf("reached without a reset: %+v", l)
115 }
116 for raw, want := range map[string]string{`{"message":"x","codexErrorInfo":"usageLimitExceeded"}`: FailQuota, `{"message":"x","codexErrorInfo":"unauthorized"}`: FailAuth, `{"message":"x","codexErrorInfo":"rateLimitExceeded"}`: FailTransient, `{"message":"x","codexErrorInfo":"serverOverloaded"}`: FailTransient, `{"message":"x","codexErrorInfo":{"httpConnectionFailed":{"httpStatusCode":502}}}`: FailTransient, `{"message":"x"}`: FailTransient} {
117 if got := CodexFailure([]byte(raw)); got != want {
118 t.Fatalf("%s: %s, want %s", raw, got, want)
119 }
120 }
121 for raw, want := range map[string]string{`{"type":"assistant","message":{},"error":"authentication_failed","session_id":"s"}`: FailAuth, `{"type":"assistant","message":{},"error":"billing_error","session_id":"s"}`: FailAuth, `{"type":"assistant","message":{},"error":"server_error","session_id":"s"}`: "", `{"type":"system","subtype":"api_retry","error":"rate_limit","retry_delay_ms":500,"session_id":"s"}`: FailQuota, `{"type":"system","subtype":"api_retry","error":"server_error","session_id":"s"}`: ""} {
122 if got := ClaudeSignal([]byte(raw)); got != want {
123 t.Fatalf("%s: %q, want %q", raw, got, want)
124 }
125 }
126 if !CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":"usageLimitExceeded"}`)) || CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":"rateLimitExceeded"}`)) || CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":{"httpConnectionFailed":{}}}`)) {
127 t.Fatal("quota error")
128 }
129}
130
131// Pi on TensorX (connectors spec §4.4): Engineering and Review, never
132// the coordinator; and, metered, only for a step with leave to spend
133// (§0 decision 5: an urgent task or a released step, S3), and then only
134// when no subscription connection can run it (§7, rules 3 and 4).
135func TestChooseMetered(t *testing.T) {
136 now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC)
137 pi := Candidate{ID: "tensorx-a", Provider: "tensorx", Harness: "pi", Metered: true, State: StateHealthy}
138 claude := Candidate{ID: "c1", Provider: "claude", State: StateHealthy}
139 for _, tc := range []struct {
140 name, role string
141 cs []Candidate
142 spend bool
143 avoid []string
144 want string
145 current string
146 }{
147 // A kept session on the metered connection stays there, even
148 // with a subscription usable; unless it cannot run.
149 {"kept on metered, a subscription usable", RoleEngineering, []Candidate{claude, pi}, true, nil, "tensorx-a", "tensorx-a"},
150 {"kept on metered, refused", RoleEngineering, []Candidate{claude, {ID: "tensorx-a", Provider: "tensorx", Harness: "pi", Metered: true, State: "sign_in_again"}}, true, nil, "c1", "tensorx-a"},
151 {"no leave: never chosen", RoleReview, []Candidate{pi}, false, nil, "", ""},
152 {"no leave, alongside a subscription", RoleReview, []Candidate{pi, claude}, false, nil, "c1", ""},
153 {"leave, only option", RoleReview, []Candidate{pi}, true, nil, "tensorx-a", ""},
154 {"leave, Engineering", RoleEngineering, []Candidate{pi}, true, nil, "tensorx-a", ""},
155 {"leave, never the coordinator", RoleCoordinator, []Candidate{pi}, true, nil, "", ""},
156 {"leave, a subscription first", RoleReview, []Candidate{pi, claude}, true, nil, "c1", ""},
157 {"leave, a subscription first even with less room", RoleReview, []Candidate{{ID: "tensorx-a", Provider: "tensorx", Harness: "pi", Metered: true, State: StateHealthy, Known: true}, claude}, true, nil, "c1", ""},
158 {"leave, the subscription avoided", RoleReview, []Candidate{claude, pi}, true, []string{"c1"}, "tensorx-a", ""},
159 {"capability is the harness's, not the provider's", RoleReview, []Candidate{{ID: "x", Provider: "tensorx", Metered: true, State: StateHealthy}}, true, nil, "", ""},
160 } {
161 t.Run(tc.name, func(t *testing.T) {
162 got, ok := Choose(tc.cs, tc.role, tc.current, "", tc.avoid, now, tc.spend)
163 if got.ID != tc.want || ok != (tc.want != "") {
164 t.Fatalf("chose %+v %v, want %q", got, ok, tc.want)
165 }
166 })
167 }
168 if !Capable("pi", RoleReview) || !Capable("pi", RoleEngineering) || Capable("pi", RoleCoordinator) {
169 t.Fatal("the matrix row for Pi")
170 }
171}
172
173// OpenCode runs Engineering and Review for OpenCode Go (connectors spec
174// §4.4, slice S5), never the coordinator, and not Research.
175func TestCapableOpenCode(t *testing.T) {
176 for role, want := range map[string]bool{RoleEngineering: true, RoleReview: true, RoleCoordinator: false, RoleResearch: false} {
177 if Capable("opencode", role) != want {
178 t.Errorf("opencode for %s: %v", role, !want)
179 }
180 }
181 cs := []Candidate{{ID: "go-1", Provider: "opencode-go", Harness: "opencode", Metered: true, State: StateHealthy}}
182 if c, ok := Choose(cs, RoleReview, "", "", nil, time.Now(), true); !ok || c.ID != "go-1" {
183 t.Fatalf("review with leave: %+v %v", c, ok)
184 }
185 for _, role := range []string{RoleCoordinator, RoleResearch} {
186 if c, ok := Choose(cs, role, "", "", nil, time.Now(), true); ok {
187 t.Fatalf("%s chose %+v", role, c)
188 }
189 }
190}
191