oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build e2elive
2
3package e2elivetest
4
5import (
6 "context"
7 "encoding/json"
8 "io"
9 "log/slog"
10 "net"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "regexp"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/equipo"
19 "amadan.net/oficina/equipo/internal/runnerproto"
20 "amadan.net/rastrillo/rastrillo/db"
21 "amadan.net/rastrillo/rastrillo/migrate"
22)
23
24// This seam exists only in a test binary. The served instance has no test routes.
25func TestCoordinatorE2ELive(t *testing.T) {
26 if os.Getenv("EQUIPO_E2E_LIVE") != "1" {
27 t.Skip("run make e2e-live")
28 }
29 ctx := context.Background()
30 root := t.TempDir()
31 liveSelfHealDiagnostics(t, root)
32 env := liveEnvironment(t, root)
33 stage := "build"
34 check := func(err error) {
35 t.Helper()
36 if err != nil {
37 t.Fatalf("stage %s: %v", stage, err)
38 }
39 }
40 instance := filepath.Join(root, "equipo")
41 runnerBin := filepath.Join(root, "equipo-runner")
42
43 stage = "instance bootstrap"
44 listener, err := net.Listen("tcp", "127.0.0.1:0")
45 check(err)
46 addr := listener.Addr().String()
47 check(listener.Close())
48 origin, saveRecording := liveRecordingProxy(t, "http://"+addr)
49 env["EQUIPO_ORIGIN"] = origin
50 env["EQUIPO_EXECUTION_ENABLED"] = "1"
51 env["EQUIPO_ALLOW_LOGGED_MAIL"] = "1"
52 env["EQUIPO_INSTANCE_KEY"] = "scratch-e2e-instance-key"
53 env["EQUIPO_OWNERS"] = "paul@tito.io"
54 env["EQUIPO_EXECUTION_MARKER_PATH"] = filepath.Join(root, "marker", "execution")
55 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
56 path := filepath.Join(root, "instance.db")
57 d, err := db.Open(path, logger)
58 check(err)
59 t.Cleanup(func() { d.Close() })
60 _, err = migrate.Apply(ctx, d, equipo.BootSchema)
61 check(err)
62 s := equipo.NewStore(d)
63 cfg, err := equipo.LoadConfig(func(k string) string { return env[k] })
64 check(err)
65 x, err := equipo.OpenExecution(ctx, d, path, cfg, s)
66 check(err)
67 t.Cleanup(func() { x.Close() })
68 // Two coordinator turns and one isolated implementation turn per full run.
69 stage = "runner enrolment"
70 code, key := beginDevice(t, s)
71 approveDevice(t, s, code, "paul@tito.io")
72 credential := claimDevice(t, s, code, key)
73 env["EQUIPO_INSTANCE_ID"] = code.InstanceID
74 raw, err := json.Marshal(runnerproto.CredentialRotation{Bearer: credential})
75 check(err)
76 check(os.WriteFile(filepath.Join(env["EQUIPO_RUNNER_STATE_DIR"], "credentials.json"), raw, 0600))
77 check(x.Close())
78 liveBuild(t, instance, "./cmd/equipo")
79 liveBuild(t, runnerBin, "./cmd/equipo-runner")
80 if os.Getenv("EQUIPO_OWNER_IMPLEMENT_ONLY") == "1" {
81 runLiveImplement(t, root, env)
82 return
83 }
84 instanceLog := liveStart(t, root, env, instance, "-addr", addr, "-db", path)
85 c := signinClient(t, origin)
86 liveWait(t, "instance HTTP", 20*time.Second, func() bool {
87 r, e := c.Get(origin + "/signin")
88 if e != nil {
89 return false
90 }
91 r.Body.Close()
92 return r.StatusCode == 200
93 })
94 stage = "person sign-in"
95 beginEmail(t, c, origin, origin, "paul@tito.io")
96 var link string
97 liveWait(t, stage, 5*time.Second, func() bool {
98 b, _ := os.ReadFile(instanceLog)
99 link = regexp.MustCompile(`http://127\.0\.0\.1:[0-9]+/auth/verify\?[^\\\s"]+`).FindString(string(b))
100 return link != ""
101 })
102 m := &capturingMailer{bodies: []string{link}}
103 response := confirmEmail(t, c, origin, origin, m)
104 response.Body.Close()
105 if response.StatusCode != 303 {
106 t.Fatalf("stage %s: HTTP %d", stage, response.StatusCode)
107 }
108 stage = "runner heartbeat and owner mode"
109 runnerLog, stopRunner := liveProcess(t, root, env, runnerBin, "run")
110 t.Cleanup(func() {
111 if t.Failed() {
112 raw, _ := os.ReadFile(runnerLog)
113 t.Logf("runner diagnostics: %s", raw)
114 }
115 })
116 liveWait(t, stage, 90*time.Second, func() bool {
117 var reports string
118 if d.Writer().QueryRow("SELECT reports_json FROM connections WHERE local_id='claude-a'").Scan(&reports) != nil {
119 return false
120 }
121 var r []runnerproto.ConnectionReport
122 check(json.Unmarshal([]byte(reports), &r))
123 if len(r) > 0 && !r[0].Available {
124 t.Fatalf("stage heartbeat owner mode: %s, policy %s", r[0].UnavailableReason, r[0].IsolationConfigHash)
125 }
126 return len(r) == 1 && r[0].Available && r[0].ReadIsolation && r[0].OwnerMode
127 })
128 stopRunner()
129 t.Cleanup(func() {
130 rows, err := d.Writer().Query("SELECT state,generation,sequence,claim FROM coordinator_turns ORDER BY sequence,id")
131 if err != nil {
132 return
133 }
134 defer rows.Close()
135 for rows.Next() {
136 var state, raw string
137 var generation, sequence int64
138 if rows.Scan(&state, &generation, &sequence, &raw) != nil {
139 continue
140 }
141 var claim runnerproto.CoordinatorClaim
142 _ = json.Unmarshal([]byte(raw), &claim)
143 t.Logf("local turn: state=%s generation=%d sequence=%d pending=%v recent=%v", state, generation, sequence, claim.Context.Pending, claim.Context.Recent)
144 }
145 })
146 liveSelfHeal(t, c, origin, d, func() {
147 runnerLog, stopRunner = liveProcess(t, root, env, runnerBin, "run")
148 })
149 var defaults int
150 check(d.Writer().QueryRow("SELECT count(*) FROM budget_records").Scan(&defaults))
151 if defaults != 1 {
152 t.Fatal("owner defaults absent")
153 }
154 saveRecording()
155 var turns int
156 check(d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE job_id>0").Scan(&turns))
157 if turns != 2 {
158 t.Fatalf("stage turn budget: got %d claims", turns)
159 }
160 stopRunner()
161
162}
163
164func runLiveImplement(t *testing.T, root string, env map[string]string) {
165 t.Helper()
166 check := func(err error) {
167 t.Helper()
168 if err != nil {
169 t.Fatal(err)
170 }
171 }
172
173 raw, err := json.Marshal(env)
174 check(err)
175 harnessPath := filepath.Join(root, "harness.json")
176 check(os.WriteFile(harnessPath, raw, 0600))
177 cmd := exec.Command("go", "test", "-tags", "e2elive", "./internal/runner/ownerlive", "-run", "^TestOwnerImplementE2ELive$", "-count=1", "-timeout=4m", "-v")
178 cmd.Dir = "../.."
179 cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "EQUIPO_OWNER_HARNESS="+harnessPath)
180 output, err := cmd.CombinedOutput()
181 t.Log(string(output))
182 check(err)
183
184}
185