package thin import ( "context" "encoding/json" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // fixRig is a runner with two healthy Claude connections of the // person's (claude-1 nearly spent, claude-2 roomy) and Engineering's // kept session of round 0, made on claude-1, for commit fixBase. type fixRig struct { t *testing.T state *State conns *Conns e *Engineer kept string } const fixBase = "0123456789abcdef0123456789abcdef01234567" func newFixRig(t *testing.T) *fixRig { dir := t.TempDir() bindings := filepath.Join(dir, "bindings.json") if err := os.MkdirAll(filepath.Join(dir, "state"), 0700); err != nil { t.Fatal(err) } state, err := OpenState(context.Background(), filepath.Join(dir, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) var bs []map[string]any for _, id := range []string{"claude-1", "claude-2"} { home := filepath.Join(dir, "accounts", id) if err := os.MkdirAll(home, 0700); err != nil { t.Fatal(err) } identity := map[string]string{"account_id": id + "@example.com", "home_id": "h-" + id, "provider_version": "1"} bs = append(bs, map[string]any{"id": id, "local_id": id, "label": id, "person_id": connPerson, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": id + "@example.com", "provider_home": home, "kind": "subscription", "expected_identity": identity}) } raw, _ := json.Marshal(bs) if err := os.WriteFile(bindings, raw, 0600); err != nil { t.Fatal(err) } cfg := runner.Config{AccountBindingsPath: bindings, ClaudePath: "/bin/true", CodexPath: "/bin/true"} conns := &Conns{Runner: cfg, State: state} for id, used := range map[string]float64{"claude-1": 0.9, "claude-2": 0.1} { conns.Validated(id) conns.Observe(id, connect.Limit{Headroom: &wire.Headroom{Utilization: &used}}, "") } r := &fixRig{t: t, state: state, conns: conns, kept: filepath.Join(dir, "sessions", "steps", "s0")} r.e = &Engineer{O: ClaudeOptions{Runner: cfg, State: state, SessionRoot: filepath.Join(dir, "sessions")}, Conns: conns} round0 := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "s0", Attempt: 1, Specialist: wire.SpecialistEngineering}} if err := state.keepSession(context.Background(), round0, wire.SpecialistEngineering, "claude-1", "", "", "sess-0", r.kept, fixBase, 10); err != nil { t.Fatal(err) } path := keptTranscript(r.kept, "sess-0") if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte(`{"type":"user"}`+"\n"), 0600); err != nil { t.Fatal(err) } return r } // round is the dispatch of Engineering's fix round 1 on fixBase. func fixRound() stepRow { return stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "s1", Attempt: 1, Specialist: wire.SpecialistEngineering, Round: 1, BaseSHA: fixBase, Feedback: "Fix round 1 of 2. Review asked for changes."}, Base: fixBase} } // plan is where the round runs and whether it resumes. func (r *fixRig) plan(row stepRow, avoid []string) (string, bool) { r.t.Helper() kept, ok := r.e.fixSession(context.Background(), row, row.Base) b, resume, hold, _, err := r.e.fixPlan(context.Background(), row, avoid, kept, ok) if err != nil { r.t.Fatal(err) } if hold != nil { r.t.Fatalf("held: %+v", hold) } if resume && kept.SessionID != "sess-0" { r.t.Fatalf("resumes %+v", kept) } return b.LocalID, resume } // A fix round resumes the kept session of the round that made its // commit, on that session's connection, while that connection is // healthy, even when another has more headroom (the warm cache). When // the connection cannot run it, the session is gone or the round is // not one a session can carry, it starts fresh where Choose puts it. func TestFixRoundResumesOnlyOnItsHealthyConnection(t *testing.T) { r := newFixRig(t) if on, resume := r.plan(fixRound(), nil); on != "claude-1" || !resume { t.Fatalf("healthy: on %s resume %v", on, resume) } // Refused in this attempt already (it failed over): fresh, elsewhere. if on, resume := r.plan(fixRound(), []string{"claude-1"}); on != "claude-2" || resume { t.Fatalf("after a refusal: on %s resume %v", on, resume) } // Not a round a session carries: no feedback (an older instance), a // rebase, a republish, the first round, another commit. for name, change := range map[string]func(*stepRow){ "no feedback": func(s *stepRow) { s.Feedback = "" }, "rebase": func(s *stepRow) { s.Rebase = true }, "republish": func(s *stepRow) { s.Republish = true }, "round 0": func(s *stepRow) { s.Round = 0 }, "other base": func(s *stepRow) { s.Base = strings.Repeat("f", 40) }, } { row := fixRound() change(&row) if on, resume := r.plan(row, nil); on != "claude-2" || resume { t.Fatalf("%s: on %s resume %v", name, on, resume) } } // Another task's or person's session is never resumed. row := fixRound() row.TaskID = "tk2" if _, resume := r.plan(row, nil); resume { t.Fatal("resumed another task's session") } // The kept connection limited: failover wins over the cache. r.conns.Limit("claude-1", connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) if on, resume := r.plan(fixRound(), nil); on != "claude-2" || resume { t.Fatalf("limited: on %s resume %v", on, resume) } r.conns.Observe("claude-1", connect.Limit{}, "") if on, resume := r.plan(fixRound(), nil); on != "claude-1" || !resume { t.Fatalf("back: on %s resume %v", on, resume) } // Signed out (sign in again): fresh, elsewhere. r.conns.SignInAgain("claude-1") if on, resume := r.plan(fixRound(), nil); on != "claude-2" || resume { t.Fatalf("sign in again: on %s resume %v", on, resume) } r.conns.Validated("claude-1") // Unhealthy by the last refresh: fresh. r.e.Healthy = func(id string) bool { return id != "claude-1" } if _, resume := r.plan(fixRound(), nil); resume { t.Fatal("resumed on an unhealthy connection") } r.e.Healthy = nil // The session gone: fresh. if err := os.Remove(keptTranscript(r.kept, "sess-0")); err != nil { t.Fatal(err) } if on, resume := r.plan(fixRound(), nil); on != "claude-2" || resume { t.Fatalf("session gone: on %s resume %v", on, resume) } } // The resumed message carries the feedback and the same rules and // reply, not the whole brief again. func TestFixPromptIsTheNextMessage(t *testing.T) { e := &Engineer{} row := fixRound() row.Brief, row.Branch = "The original brief.", "equipo/tk1-x" p := e.fixPrompt(row, claude.LinuxWorkspaceRoot) for _, want := range []string{"[Equipo: engineering]", row.Feedback, "equipo/tk1-x", "do not run git", "Headline: "} { if !strings.Contains(p, want) { t.Fatalf("prompt lacks %q:\n%s", want, p) } } if strings.Contains(p, row.Brief) { t.Fatalf("prompt repeats the brief:\n%s", p) } }