//go:build e2elive package e2elivetest import ( "context" "encoding/json" "io" "log/slog" "net" "os" "os/exec" "path/filepath" "regexp" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" ) // This seam exists only in a test binary. The served instance has no test routes. func TestCoordinatorE2ELive(t *testing.T) { if os.Getenv("EQUIPO_E2E_LIVE") != "1" { t.Skip("run make e2e-live") } ctx := context.Background() root := t.TempDir() liveSelfHealDiagnostics(t, root) env := liveEnvironment(t, root) stage := "build" check := func(err error) { t.Helper() if err != nil { t.Fatalf("stage %s: %v", stage, err) } } instance := filepath.Join(root, "equipo") runnerBin := filepath.Join(root, "equipo-runner") stage = "instance bootstrap" listener, err := net.Listen("tcp", "127.0.0.1:0") check(err) addr := listener.Addr().String() check(listener.Close()) origin, saveRecording := liveRecordingProxy(t, "http://"+addr) env["EQUIPO_ORIGIN"] = origin env["EQUIPO_EXECUTION_ENABLED"] = "1" env["EQUIPO_ALLOW_LOGGED_MAIL"] = "1" env["EQUIPO_INSTANCE_KEY"] = "scratch-e2e-instance-key" env["EQUIPO_OWNERS"] = "paul@tito.io" env["EQUIPO_EXECUTION_MARKER_PATH"] = filepath.Join(root, "marker", "execution") logger := slog.New(slog.NewTextHandler(io.Discard, nil)) path := filepath.Join(root, "instance.db") d, err := db.Open(path, logger) check(err) t.Cleanup(func() { d.Close() }) _, err = migrate.Apply(ctx, d, equipo.BootSchema) check(err) s := equipo.NewStore(d) cfg, err := equipo.LoadConfig(func(k string) string { return env[k] }) check(err) x, err := equipo.OpenExecution(ctx, d, path, cfg, s) check(err) t.Cleanup(func() { x.Close() }) // Two coordinator turns and one isolated implementation turn per full run. stage = "runner enrolment" code, key := beginDevice(t, s) approveDevice(t, s, code, "paul@tito.io") credential := claimDevice(t, s, code, key) env["EQUIPO_INSTANCE_ID"] = code.InstanceID raw, err := json.Marshal(runnerproto.CredentialRotation{Bearer: credential}) check(err) check(os.WriteFile(filepath.Join(env["EQUIPO_RUNNER_STATE_DIR"], "credentials.json"), raw, 0600)) check(x.Close()) liveBuild(t, instance, "./cmd/equipo") liveBuild(t, runnerBin, "./cmd/equipo-runner") if os.Getenv("EQUIPO_OWNER_IMPLEMENT_ONLY") == "1" { runLiveImplement(t, root, env) return } instanceLog := liveStart(t, root, env, instance, "-addr", addr, "-db", path) c := signinClient(t, origin) liveWait(t, "instance HTTP", 20*time.Second, func() bool { r, e := c.Get(origin + "/signin") if e != nil { return false } r.Body.Close() return r.StatusCode == 200 }) stage = "person sign-in" beginEmail(t, c, origin, origin, "paul@tito.io") var link string liveWait(t, stage, 5*time.Second, func() bool { b, _ := os.ReadFile(instanceLog) link = regexp.MustCompile(`http://127\.0\.0\.1:[0-9]+/auth/verify\?[^\\\s"]+`).FindString(string(b)) return link != "" }) m := &capturingMailer{bodies: []string{link}} response := confirmEmail(t, c, origin, origin, m) response.Body.Close() if response.StatusCode != 303 { t.Fatalf("stage %s: HTTP %d", stage, response.StatusCode) } stage = "runner heartbeat and owner mode" runnerLog, stopRunner := liveProcess(t, root, env, runnerBin, "run") t.Cleanup(func() { if t.Failed() { raw, _ := os.ReadFile(runnerLog) t.Logf("runner diagnostics: %s", raw) } }) liveWait(t, stage, 90*time.Second, func() bool { var reports string if d.Writer().QueryRow("SELECT reports_json FROM connections WHERE local_id='claude-a'").Scan(&reports) != nil { return false } var r []runnerproto.ConnectionReport check(json.Unmarshal([]byte(reports), &r)) if len(r) > 0 && !r[0].Available { t.Fatalf("stage heartbeat owner mode: %s, policy %s", r[0].UnavailableReason, r[0].IsolationConfigHash) } return len(r) == 1 && r[0].Available && r[0].ReadIsolation && r[0].OwnerMode }) stopRunner() t.Cleanup(func() { rows, err := d.Writer().Query("SELECT state,generation,sequence,claim FROM coordinator_turns ORDER BY sequence,id") if err != nil { return } defer rows.Close() for rows.Next() { var state, raw string var generation, sequence int64 if rows.Scan(&state, &generation, &sequence, &raw) != nil { continue } var claim runnerproto.CoordinatorClaim _ = json.Unmarshal([]byte(raw), &claim) t.Logf("local turn: state=%s generation=%d sequence=%d pending=%v recent=%v", state, generation, sequence, claim.Context.Pending, claim.Context.Recent) } }) liveSelfHeal(t, c, origin, d, func() { runnerLog, stopRunner = liveProcess(t, root, env, runnerBin, "run") }) var defaults int check(d.Writer().QueryRow("SELECT count(*) FROM budget_records").Scan(&defaults)) if defaults != 1 { t.Fatal("owner defaults absent") } saveRecording() var turns int check(d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE job_id>0").Scan(&turns)) if turns != 2 { t.Fatalf("stage turn budget: got %d claims", turns) } stopRunner() } func runLiveImplement(t *testing.T, root string, env map[string]string) { t.Helper() check := func(err error) { t.Helper() if err != nil { t.Fatal(err) } } raw, err := json.Marshal(env) check(err) harnessPath := filepath.Join(root, "harness.json") check(os.WriteFile(harnessPath, raw, 0600)) cmd := exec.Command("go", "test", "-tags", "e2elive", "./internal/runner/ownerlive", "-run", "^TestOwnerImplementE2ELive$", "-count=1", "-timeout=4m", "-v") cmd.Dir = "../.." cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "EQUIPO_OWNER_HARNESS="+harnessPath) output, err := cmd.CombinedOutput() t.Log(string(output)) check(err) }