package connect import ( "os" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } func TestChoose(t *testing.T) { now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) claude := Candidate{ID: "claude-a", Provider: "claude", State: StateHealthy} claude2 := Candidate{ID: "claude-2", Provider: "claude", State: StateHealthy} codex := Candidate{ID: "codex-1", Provider: "codex", State: StateHealthy} limited := func(c Candidate, until time.Time) Candidate { c.State, c.ResetsAt = StateLimited, until; return c } used := func(c Candidate, u float64) Candidate { c.Used, c.Known = u, true; return c } for _, tc := range []struct { name string cs []Candidate role, current string avoid []string prefer string want, reason string }{ {"one", []Candidate{claude}, RoleCoordinator, "", nil, "", "claude-a", ReasonOnlyOption}, {"none", []Candidate{limited(claude, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "", "", ""}, {"configured order first", []Candidate{claude, codex}, RoleCoordinator, "", nil, "", "claude-a", ReasonHeadroom}, {"reported headroom before unknown", []Candidate{claude, used(codex, 0.8)}, RoleCoordinator, "", nil, "", "codex-1", ReasonHeadroom}, {"most headroom", []Candidate{used(claude, 0.5), used(claude2, 0.2), used(codex, 0.4)}, RoleCoordinator, "", nil, "", "claude-2", ReasonHeadroom}, {"sticky", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "", "codex-1", ReasonHeadroom}, {"failover from limited", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonOnlyOption}, {"failover among several", []Candidate{limited(claude, now.Add(time.Hour)), claude2, codex}, RoleCoordinator, "claude-a", nil, "", "claude-2", ReasonFailover}, {"reset passed", []Candidate{limited(claude, now.Add(-time.Minute)), codex}, RoleCoordinator, "claude-a", nil, "", "claude-a", ReasonHeadroom}, {"limited without reset never by itself", []Candidate{limited(claude, time.Time{})}, RoleCoordinator, "", nil, "", "", ""}, {"stickiness is a rule", []Candidate{used(claude, 0.97), used(codex, 0.1)}, RoleCoordinator, "claude-a", nil, "", "claude-a", ReasonHeadroom}, {"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}, {"engineering fails over to codex", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleEngineering, "claude-a", nil, "", "codex-1", ReasonOnlyOption}, {"review away from engineering's on codex", []Candidate{claude, codex}, RoleReview, "", []string{"claude-a"}, "", "codex-1", ReasonOnlyOption}, {"avoid", []Candidate{claude, claude2}, RoleEngineering, "", []string{"claude-a"}, "", "claude-2", ReasonOnlyOption}, {"signed out never", []Candidate{{ID: "claude-a", Provider: "claude", State: "sign_in_again"}, codex}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonOnlyOption}, {"unchecked is never chosen", []Candidate{{ID: "codex-1", Provider: "codex"}}, RoleCoordinator, "", nil, "", "", ""}, {"preference first", []Candidate{claude, used(codex, 0.9)}, RoleCoordinator, "", nil, "codex", "codex-1", ReasonPreference}, {"preference takes the session back at a boundary", []Candidate{claude, codex}, RoleCoordinator, "claude-a", nil, "codex", "codex-1", ReasonPreference}, {"on the preference already", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "codex", "codex-1", ReasonHeadroom}, {"preference never overrides health", []Candidate{claude, limited(codex, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "codex", "claude-a", ReasonOnlyOption}, {"preference among a provider's accounts by headroom", []Candidate{used(claude, 0.6), used(claude2, 0.1), codex}, RoleCoordinator, "", nil, "claude", "claude-2", ReasonPreference}, {"preference nothing here can use", []Candidate{claude, claude2, codex}, RoleEngineering, "claude-a", nil, "pi", "claude-a", ReasonHeadroom}, {"connecting is never chosen", []Candidate{{ID: "codex-1", Provider: "codex", State: "connecting"}}, RoleCoordinator, "", nil, "", "", ""}, } { t.Run(tc.name, func(t *testing.T) { got, ok := Choose(tc.cs, tc.role, tc.current, tc.prefer, tc.avoid, now, false) if ok != (tc.want != "") || got.ID != tc.want || got.Reason != tc.reason { t.Fatalf("Choose = %+v %v, want %s %s", got, ok, tc.want, tc.reason) } }) } } func TestLimitedUntil(t *testing.T) { now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) if at, wait := LimitedUntil(now.Add(48*time.Hour), 0, now); !at.Equal(now.Add(48*time.Hour)) || wait != 0 { t.Fatalf("provider reset not kept: %v %v", at, wait) } var wait time.Duration for i, want := range []time.Duration{15 * time.Minute, 30 * time.Minute, time.Hour, time.Hour} { var at time.Time at, wait = LimitedUntil(time.Time{}, wait, now) if !at.Equal(now.Add(want)) { t.Fatalf("refusal %d: until %v, want +%v", i, at.Sub(now), want) } } 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)) { t.Fatalf("NextCheck %v", at) } } // The recorded allowed_warning event from the pinned CLI, and the same // event refused. const 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"}` func TestClaudeRateLimit(t *testing.T) { l, ok := ClaudeRateLimit([]byte(recorded)) 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 { t.Fatalf("allowed_warning: %+v %v", l, ok) } l, ok = ClaudeRateLimit([]byte(strings.Replace(recorded, `"allowed_warning"`, `"rejected"`, 1))) if !ok || !l.Limited || l.ResetsAt.Unix() != 1794211200 { t.Fatalf("rejected: %+v", l) } if _, ok = ClaudeRateLimit([]byte(`{"type":"result","session_id":"s"}`)); ok { t.Fatal("a result read as a rate limit") } l, _ = ClaudeRateLimit([]byte(`{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"},"session_id":"s"}`)) if !l.Limited || !l.ResetsAt.IsZero() || l.Headroom.ResetsAt != nil { t.Fatalf("a reset time was invented: %+v", l) } } func TestCodexRateLimits(t *testing.T) { 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}`)) if !ok || l.Limited || plan != "pro" || *l.Headroom.Utilization != 0.4 || len(l.Headroom.Windows) != 2 || l.Headroom.ResetsAt != nil { t.Fatalf("snapshot: %+v %s", l, plan) } l, _, _ = CodexRateLimits([]byte(`{"primary":{"usedPercent":100,"windowDurationMins":300,"resetsAt":1794211200},"secondary":{"usedPercent":100,"windowDurationMins":10080,"resetsAt":1794500000}}`)) if !l.Limited || l.ResetsAt.Unix() != 1794500000 || l.Window != "secondary" { t.Fatalf("spent: %+v", l) } l, _, _ = CodexRateLimits([]byte(`{"primary":{"usedPercent":20},"rateLimitReachedType":"workspace_member_usage_limit_reached"}`)) if !l.Limited || !l.ResetsAt.IsZero() { t.Fatalf("reached without a reset: %+v", l) } 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} { if got := CodexFailure([]byte(raw)); got != want { t.Fatalf("%s: %s, want %s", raw, got, want) } } 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"}`: ""} { if got := ClaudeSignal([]byte(raw)); got != want { t.Fatalf("%s: %q, want %q", raw, got, want) } } if !CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":"usageLimitExceeded"}`)) || CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":"rateLimitExceeded"}`)) || CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":{"httpConnectionFailed":{}}}`)) { t.Fatal("quota error") } } // Pi on TensorX (connectors spec §4.4): Engineering and Review, never // the coordinator; and, metered, only for a step with leave to spend // (§0 decision 5: an urgent task or a released step, S3), and then only // when no subscription connection can run it (§7, rules 3 and 4). func TestChooseMetered(t *testing.T) { now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) pi := Candidate{ID: "tensorx-a", Provider: "tensorx", Harness: "pi", Metered: true, State: StateHealthy} claude := Candidate{ID: "c1", Provider: "claude", State: StateHealthy} for _, tc := range []struct { name, role string cs []Candidate spend bool avoid []string want string current string }{ // A kept session on the metered connection stays there, even // with a subscription usable; unless it cannot run. {"kept on metered, a subscription usable", RoleEngineering, []Candidate{claude, pi}, true, nil, "tensorx-a", "tensorx-a"}, {"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"}, {"no leave: never chosen", RoleReview, []Candidate{pi}, false, nil, "", ""}, {"no leave, alongside a subscription", RoleReview, []Candidate{pi, claude}, false, nil, "c1", ""}, {"leave, only option", RoleReview, []Candidate{pi}, true, nil, "tensorx-a", ""}, {"leave, Engineering", RoleEngineering, []Candidate{pi}, true, nil, "tensorx-a", ""}, {"leave, never the coordinator", RoleCoordinator, []Candidate{pi}, true, nil, "", ""}, {"leave, a subscription first", RoleReview, []Candidate{pi, claude}, true, nil, "c1", ""}, {"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", ""}, {"leave, the subscription avoided", RoleReview, []Candidate{claude, pi}, true, []string{"c1"}, "tensorx-a", ""}, {"capability is the harness's, not the provider's", RoleReview, []Candidate{{ID: "x", Provider: "tensorx", Metered: true, State: StateHealthy}}, true, nil, "", ""}, } { t.Run(tc.name, func(t *testing.T) { got, ok := Choose(tc.cs, tc.role, tc.current, "", tc.avoid, now, tc.spend) if got.ID != tc.want || ok != (tc.want != "") { t.Fatalf("chose %+v %v, want %q", got, ok, tc.want) } }) } if !Capable("pi", RoleReview) || !Capable("pi", RoleEngineering) || Capable("pi", RoleCoordinator) { t.Fatal("the matrix row for Pi") } } // OpenCode runs Engineering and Review for OpenCode Go (connectors spec // §4.4, slice S5), never the coordinator, and not Research. func TestCapableOpenCode(t *testing.T) { for role, want := range map[string]bool{RoleEngineering: true, RoleReview: true, RoleCoordinator: false, RoleResearch: false} { if Capable("opencode", role) != want { t.Errorf("opencode for %s: %v", role, !want) } } cs := []Candidate{{ID: "go-1", Provider: "opencode-go", Harness: "opencode", Metered: true, State: StateHealthy}} if c, ok := Choose(cs, RoleReview, "", "", nil, time.Now(), true); !ok || c.ID != "go-1" { t.Fatalf("review with leave: %+v %v", c, ok) } for _, role := range []string{RoleCoordinator, RoleResearch} { if c, ok := Choose(cs, role, "", "", nil, time.Now(), true); ok { t.Fatalf("%s chose %+v", role, c) } } }