| 1 | //go:build testbuild |
| 2 | |
| 3 | package headless |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/rand" |
| 8 | "database/sql" |
| 9 | "debug/elf" |
| 10 | "encoding/base64" |
| 11 | "encoding/json" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "net/http" |
| 16 | "net/url" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "path/filepath" |
| 20 | "strconv" |
| 21 | "strings" |
| 22 | "syscall" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 27 | "amadan.net/oficina/equipo/internal/runner/mac/proc" |
| 28 | "amadan.net/oficina/equipo/internal/runner/thin" |
| 29 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 30 | "amadan.net/oficina/equipo/internal/thintest" |
| 31 | "amadan.net/oficina/equipo/internal/wire" |
| 32 | ) |
| 33 | |
| 34 | const woodstar, panes = "amadan.net/woodstar/woodstar", "amadan.net/woodstar/panes" |
| 35 | |
| 36 | // addWoodstar adds an iOS app to the local forge: it has a shared scheme |
| 37 | // and edge swipe does nothing. Its gate runs scripts/test, which runs |
| 38 | // xcodebuild test, so its base does not say it needs a Mac: Engineering |
| 39 | // runs on the Linux primary and a change to its Swift files is checked on |
| 40 | // a Mac. Panes is the same app whose gate runs xcodebuild itself, so |
| 41 | // everything about it is Mac work (Engineering waits for a Mac that can |
| 42 | // make changes, 2026-11-28). |
| 43 | func addWoodstar(t *testing.T, root string, f *localForge) { |
| 44 | t.Helper() |
| 45 | xcode := "xcodebuild test -scheme Woodstar -destination 'platform=iOS Simulator,name=iPhone 16 Pro'\n" |
| 46 | seedIOS(t, root, f, woodstar, map[string]string{".amadan/ci": "#!/bin/sh\nset -e\nexec ./scripts/test\n", "scripts/test": "#!/bin/sh\nset -e\n" + xcode}) |
| 47 | seedIOS(t, root, f, panes, map[string]string{".amadan/ci": "#!/bin/sh\nset -e\n" + xcode}) |
| 48 | } |
| 49 | |
| 50 | func seedIOS(t *testing.T, root string, f *localForge, repo string, gate map[string]string) { |
| 51 | t.Helper() |
| 52 | work := filepath.Join(root, "seed-"+filepath.Base(repo)) |
| 53 | files := map[string]string{ |
| 54 | "README.md": "# Woodstar\n\nAn iOS reading app with sliding panes.\n", |
| 55 | ".gitignore": "build/\n", |
| 56 | ".equipo/gates.json": "{\"version\":1,\"files\":[]}\n", |
| 57 | "Woodstar/Swipe.swift": "let edgeSwipe = false\n", |
| 58 | "Woodstar/About.swift": "let about = \"An iOS reading app\"\n", |
| 59 | "Woodstar.xcodeproj/xcshareddata/xcschemes/Woodstar.xcscheme": "<Scheme/>\n", |
| 60 | } |
| 61 | for p, body := range gate { |
| 62 | files[p] = body |
| 63 | } |
| 64 | for p, body := range files { |
| 65 | if err := os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0700); err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | mode := os.FileMode(0600) |
| 69 | if p == ".amadan/ci" || p == "scripts/test" { |
| 70 | mode = 0700 |
| 71 | } |
| 72 | if err := os.WriteFile(filepath.Join(work, p), []byte(body), mode); err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | } |
| 76 | gitRun(t, work, "init", "-q", "-b", "main") |
| 77 | gitRun(t, work, "add", "-A") |
| 78 | gitRun(t, work, "commit", "-q", "-m", "seed") |
| 79 | gitRun(t, root, "clone", "-q", "--bare", work, f.path(repo)) |
| 80 | f.mu.Lock() |
| 81 | f.repos = append(f.repos, repo) |
| 82 | f.mu.Unlock() |
| 83 | } |
| 84 | |
| 85 | // macWorker is the fake Mac worker: the real thin runner of the test |
| 86 | // build with EQUIPO_FAKE_PLATFORM, enrolled as the owner's second runner |
| 87 | // (a worker), its own roots, the fake xcodebuild first on its gates' |
| 88 | // PATH, run as a process so it can be killed. It plays a Mac whose |
| 89 | // probe P2 denied (checks labelled seatbelt). Worker checks are diagnostic |
| 90 | // until they certify immutable base gates, so the person chooses Merge. |
| 91 | // |
| 92 | // Since slice F it is also a Mac that makes changes: its home is root |
| 93 | // (the runner user's, 0700), with its own config dir, bindings and |
| 94 | // accounts root, which its home guard checks; the pinned gitleaks sits |
| 95 | // beside its gate's tools; it holds one Claude token connection of its |
| 96 | // own (macClaude), which only it can use. |
| 97 | func macWorker(t *testing.T, inst *thintest.Instance, primary *localRunner) (*localRunner, string) { |
| 98 | t.Helper() |
| 99 | w, xcodebuild := macWorkerAs(t, inst.EnrolRunner(t), primary) |
| 100 | w.inst = inst |
| 101 | return w, xcodebuild |
| 102 | } |
| 103 | |
| 104 | // macWorkerAs is macWorker enrolled as cred (on an instance that may run |
| 105 | // in another process: set inst or instanceDB before start). |
| 106 | func macWorkerAs(t *testing.T, cred runnerproto.RunnerCredential, primary *localRunner) (*localRunner, string) { |
| 107 | t.Helper() |
| 108 | root := private(t, filepath.Join(primary.root, "mac")) |
| 109 | bin := private(t, filepath.Join(root, "bin")) |
| 110 | copyExecutable(t, filepath.Join(bin, "xcodebuild")) |
| 111 | pinnedGitleaks(t, filepath.Join(bin, "gitleaks")) |
| 112 | state := private(t, filepath.Join(root, "state")) |
| 113 | if err := thintest.WriteRunnerCredential(state, cred); err != nil { |
| 114 | t.Fatal(err) |
| 115 | } |
| 116 | config := private(t, filepath.Join(root, "config")) |
| 117 | cfg := primary.cfg |
| 118 | cfg.StateDir, cfg.WorkspaceRoot, cfg.ScratchRoot, cfg.MachineLabel = state, filepath.Join(root, "work"), filepath.Join(root, "scratch"), "Tito Studio" |
| 119 | cfg.AccountBindingsPath = filepath.Join(config, "bindings.json") |
| 120 | writeJSON(t, cfg.AccountBindingsPath, []map[string]any{}) |
| 121 | w := &localRunner{root: root, cfg: cfg, subprocess: true, scope: strings.ToLower(rand.Text()), runnerID: cred.RunnerID, opts: thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), FakePlatform: "darwin/arm64", FakeBin: bin, FakeSandbox: wire.SandboxSeatbelt, Claude: primary.opts.Claude, AccountsRoot: private(t, filepath.Join(root, "accounts")), MaxStep: time.Minute}} |
| 122 | w.addToken(t, macClaude, "mac@example.com") |
| 123 | t.Cleanup(func() { |
| 124 | w.stop(t) |
| 125 | if t.Failed() { |
| 126 | // The worker process's own log (warnings: why a step stopped). |
| 127 | if raw, err := os.ReadFile(filepath.Join(root, "runner.log")); err == nil { |
| 128 | t.Logf("worker log:\n%s", raw[max(0, len(raw)-8000):]) |
| 129 | } |
| 130 | } |
| 131 | }) |
| 132 | return w, filepath.Join(bin, "xcodebuild") |
| 133 | } |
| 134 | |
| 135 | // refusePushes makes the local forge refuse every push to bare until |
| 136 | // refuse(false), as a hub that is down would. |
| 137 | func refusePushes(t *testing.T, bare string) (refuse func(bool)) { |
| 138 | t.Helper() |
| 139 | flag := filepath.Join(bare, "refuse-pushes") |
| 140 | hook := filepath.Join(bare, "hooks", "pre-receive") |
| 141 | if err := os.MkdirAll(filepath.Dir(hook), 0700); err != nil { |
| 142 | t.Fatal(err) |
| 143 | } |
| 144 | if err := os.WriteFile(hook, []byte("#!/bin/sh\n[ -e '"+flag+"' ] && { echo refused >&2; exit 1; }\nexit 0\n"), 0700); err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | refuse = func(on bool) { |
| 148 | if !on { |
| 149 | os.Remove(flag) |
| 150 | return |
| 151 | } |
| 152 | if err := os.WriteFile(flag, nil, 0600); err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | } |
| 156 | refuse(true) |
| 157 | t.Cleanup(func() { refuse(false) }) |
| 158 | return refuse |
| 159 | } |
| 160 | |
| 161 | // macAskPin is the Engineering attempt and session the instance froze on |
| 162 | // a question, and the session the worker kept for that attempt. |
| 163 | func macAskPin(t *testing.T, inst *thintest.Instance, worker *localRunner, question string) (attempt int64, session, kept string) { |
| 164 | t.Helper() |
| 165 | var step string |
| 166 | if err := inst.DB.Writer().QueryRow("SELECT step_id, coalesce(eng_attempt, 0), coalesce(eng_session, '') FROM chat_questions WHERE id = ?", question).Scan(&step, &attempt, &session); err != nil { |
| 167 | t.Fatal(err) |
| 168 | } |
| 169 | d, err := sql.Open("sqlite", "file:"+filepath.Join(worker.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| 170 | if err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | defer d.Close() |
| 174 | _ = d.QueryRow("SELECT session_id FROM kept_sessions WHERE step_id=? AND attempt=?", step, attempt).Scan(&kept) |
| 175 | return attempt, session, kept |
| 176 | } |
| 177 | |
| 178 | // engineeringProcs are the live processes of worker's Mac Engineering |
| 179 | // launches: the darwin launch marks them EQUIPO_ATTEMPT=engineering-<key>, |
| 180 | // and the fake's stand-in puts them in its scope. |
| 181 | func engineeringProcs(worker *localRunner) []string { |
| 182 | var out []string |
| 183 | entries, _ := os.ReadDir("/proc") |
| 184 | for _, p := range entries { |
| 185 | raw, err := os.ReadFile(filepath.Join("/proc", p.Name(), "environ")) |
| 186 | if err != nil || !strings.Contains(string(raw), "EQUIPO_ATTEMPT=engineering-") || !strings.Contains(string(raw), proc.ScopeEnv+"="+worker.scope+"\x00") { |
| 187 | continue |
| 188 | } |
| 189 | if stat, err := os.ReadFile(filepath.Join("/proc", p.Name(), "stat")); err == nil && !strings.Contains(string(stat), ") Z ") { |
| 190 | out = append(out, p.Name()) |
| 191 | } |
| 192 | } |
| 193 | return out |
| 194 | } |
| 195 | |
| 196 | // macCaps is the capability report of runner's newest hello, as the |
| 197 | // instance keeps it (what the Machines page reads). |
| 198 | func macCaps(t *testing.T, inst *thintest.Instance, runner string) wire.Capabilities { |
| 199 | t.Helper() |
| 200 | var raw string |
| 201 | if err := inst.DB.Writer().QueryRow("SELECT hello FROM runner_sessions WHERE runner_id = ?", runner).Scan(&raw); err != nil { |
| 202 | t.Fatal(err) |
| 203 | } |
| 204 | var h wire.Hello |
| 205 | if err := json.Unmarshal([]byte(raw), &h); err != nil || h.Capabilities == nil { |
| 206 | t.Fatalf("hello %s: %v", raw, err) |
| 207 | } |
| 208 | return *h.Capabilities |
| 209 | } |
| 210 | |
| 211 | // woodstarCredentials gives the primary forge credentials that name the |
| 212 | // Woodstar repositories, as a real primary's do: a publication's file |
| 213 | // list is screened against them before it leaves (without them it is |
| 214 | // withheld). |
| 215 | func woodstarCredentials(t *testing.T, primary *localRunner) { |
| 216 | t.Helper() |
| 217 | creds := map[string]any{"agent": "equipo-test", "repositories": map[string]any{woodstar: map[string]string{"api": "amk_test_woodstar", "git": "git_test_woodstar"}, panes: map[string]string{"api": "amk_test_panes", "git": "git_test_panes"}}} |
| 218 | writeJSON(t, primary.cfg.AmadanCredentialPath, creds) |
| 219 | } |
| 220 | |
| 221 | // pinnedGitleaks puts at dst a gitleaks the fake worker's scan can start |
| 222 | // in its empty bubblewrap (no libraries, no loader): this test binary |
| 223 | // when it is statically linked (CGO_ENABLED=0, as make builds it), |
| 224 | // else gitleaks built static from the module cache (nothing is |
| 225 | // downloaded). With a gitleaks that cannot start, every scan "could not |
| 226 | // tell" and the worker refuses every candidate, secret_in_candidate. |
| 227 | func pinnedGitleaks(t *testing.T, dst string) { |
| 228 | t.Helper() |
| 229 | self, err := os.Executable() |
| 230 | if err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | if staticBinary(self) { |
| 234 | copyExecutable(t, dst) |
| 235 | return |
| 236 | } |
| 237 | build := exec.Command("go", "build", "-trimpath", "-o", dst, "github.com/zricethezav/gitleaks/v8") |
| 238 | build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOFLAGS=-mod=readonly", "GOPROXY=off") |
| 239 | if out, err := build.CombinedOutput(); err != nil { |
| 240 | t.Fatalf("the fake Mac worker's gitleaks: this test binary is dynamically linked (built with cgo), so it cannot start in the scan's bubblewrap, and a static gitleaks could not be built (%v): %s\nRun with CGO_ENABLED=0, as make does.", err, out) |
| 241 | } |
| 242 | if !staticBinary(dst) { |
| 243 | t.Fatalf("the fake Mac worker's gitleaks at %s is not statically linked", dst) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | // staticBinary: an ELF executable with no program interpreter (a static |
| 248 | // Go binary). Anything unreadable is not. |
| 249 | func staticBinary(path string) bool { |
| 250 | f, err := elf.Open(path) |
| 251 | if err != nil { |
| 252 | return false |
| 253 | } |
| 254 | defer f.Close() |
| 255 | for _, p := range f.Progs { |
| 256 | if p.Type == elf.PT_INTERP { |
| 257 | return false |
| 258 | } |
| 259 | } |
| 260 | return true |
| 261 | } |
| 262 | |
| 263 | // procIdentity is a process by pid and start time (/proc's starttime): |
| 264 | // a pid used again is another process. |
| 265 | type procIdentity struct { |
| 266 | PID int |
| 267 | Start string |
| 268 | } |
| 269 | |
| 270 | func startTime(pid int) string { |
| 271 | raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) |
| 272 | if err != nil { |
| 273 | return "" |
| 274 | } |
| 275 | end := strings.LastIndexByte(string(raw), ')') |
| 276 | f := strings.Fields(string(raw[end+1:])) |
| 277 | if end < 0 || len(f) < 20 || f[0] == "Z" { |
| 278 | return "" |
| 279 | } |
| 280 | return f[19] |
| 281 | } |
| 282 | |
| 283 | func (p procIdentity) alive() bool { return p.PID > 0 && startTime(p.PID) == p.Start } |
| 284 | |
| 285 | // lingering is the launch's lingering child (the fake CLI's linger:), |
| 286 | // once it has said its pid (in this test's own file), checked to carry |
| 287 | // the attempt's Engineering marker. |
| 288 | func lingering(t *testing.T, pidfile string) procIdentity { |
| 289 | t.Helper() |
| 290 | for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(50 * time.Millisecond) { |
| 291 | raw, err := os.ReadFile(pidfile) |
| 292 | if pid, perr := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && perr == nil { |
| 293 | env, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "environ")) |
| 294 | if !strings.Contains(string(env), "EQUIPO_ATTEMPT=engineering-") { |
| 295 | t.Fatalf("the lingering child %d is not the attempt's", pid) |
| 296 | } |
| 297 | return procIdentity{PID: pid, Start: startTime(pid)} |
| 298 | } |
| 299 | if time.Now().After(deadline) { |
| 300 | t.Fatal("the launch's lingering child never started") |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // workedIn is the directory a fake CLI's reply says it worked in |
| 306 | // (saycwd). |
| 307 | func workedIn(summary string) string { |
| 308 | _, rest, ok := strings.Cut(summary, "Working in ") |
| 309 | if !ok { |
| 310 | return "" |
| 311 | } |
| 312 | dir, _, _ := strings.Cut(rest, " ") |
| 313 | return strings.TrimSuffix(dir, ".") |
| 314 | } |
| 315 | |
| 316 | // workerKept is the sessions the worker keeps for a step, from its own |
| 317 | // state. |
| 318 | func workerKept(t *testing.T, worker *localRunner, step string) []string { |
| 319 | t.Helper() |
| 320 | d, err := sql.Open("sqlite", "file:"+filepath.Join(worker.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| 321 | if err != nil { |
| 322 | t.Fatal(err) |
| 323 | } |
| 324 | defer d.Close() |
| 325 | rows, err := d.Query("SELECT session_id FROM kept_sessions WHERE step_id = ? ORDER BY attempt", step) |
| 326 | if err != nil { |
| 327 | t.Fatal(err) |
| 328 | } |
| 329 | defer rows.Close() |
| 330 | var out []string |
| 331 | for rows.Next() { |
| 332 | var sid string |
| 333 | _ = rows.Scan(&sid) |
| 334 | out = append(out, sid) |
| 335 | } |
| 336 | return out |
| 337 | } |
| 338 | |
| 339 | // macClaude is the fake Mac's own Claude token connection. |
| 340 | const macClaude = "mac-claude" |
| 341 | |
| 342 | // macDispatches counts the Engineering dispatches the instance queued |
| 343 | // for runner, acked or not. |
| 344 | func macDispatches(t *testing.T, inst *thintest.Instance, runner string) int { |
| 345 | t.Helper() |
| 346 | var n int |
| 347 | if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND kind = ? AND instr(body, ?) > 0", runner, wire.FrameDispatch, `"specialist":"engineering"`).Scan(&n); err != nil { |
| 348 | t.Fatal(err) |
| 349 | } |
| 350 | return n |
| 351 | } |
| 352 | |
| 353 | // changeDiff is the person API's patch of one changed file of a task's |
| 354 | // candidate. |
| 355 | func (s *session) changeDiff(t *testing.T, id, sha, path string) wire.ChangeDiff { |
| 356 | t.Helper() |
| 357 | c := s.env.Client |
| 358 | req, err := http.NewRequestWithContext(s.ctx, http.MethodGet, c.Origin+"/api/v1/tasks/"+id+"/changes/diff?candidate_sha="+sha+"&path="+url.QueryEscape(path), nil) |
| 359 | if err != nil { |
| 360 | t.Fatal(err) |
| 361 | } |
| 362 | req.Header.Set("Authorization", "Bearer "+c.Token) |
| 363 | resp, err := c.HTTP.Do(req) |
| 364 | if err != nil { |
| 365 | t.Fatal(err) |
| 366 | } |
| 367 | defer resp.Body.Close() |
| 368 | var out wire.ChangeDiff |
| 369 | if resp.StatusCode != http.StatusOK || json.NewDecoder(resp.Body).Decode(&out) != nil { |
| 370 | t.Fatalf("change diff of %s: %s", path, resp.Status) |
| 371 | } |
| 372 | return out |
| 373 | } |
| 374 | |
| 375 | // stepKinds is a task's steps in one line, for a failure message. |
| 376 | func stepKinds(k wire.Task) string { |
| 377 | var out []string |
| 378 | for _, st := range k.Steps { |
| 379 | out = append(out, fmt.Sprintf("%s[r%d a%d %s %s %s rebase=%v pushed=%v pub=%s on=%s]", st.Specialist, st.Round, st.Attempt, st.State, firstOf(st.Checks, st.Verdict), st.Reason, st.Rebase, st.Pushed, st.Publication, st.RunnerLabel)) |
| 380 | } |
| 381 | return strings.Join(out, " ") |
| 382 | } |
| 383 | |
| 384 | func stepOf(k wire.Task, specialist string, n int) wire.Step { |
| 385 | for _, s := range k.Steps { |
| 386 | if s.Specialist == specialist { |
| 387 | if n == 0 { |
| 388 | return s |
| 389 | } |
| 390 | n-- |
| 391 | } |
| 392 | } |
| 393 | return wire.Step{} |
| 394 | } |
| 395 | |
| 396 | // mergeWorkerPass verifies that a worker pass cannot grant merge authority, |
| 397 | // then exercises the person's explicit decision on that exact candidate. |
| 398 | func (s *session) mergeWorkerPass(t *testing.T, id string, timeout time.Duration) wire.Task { |
| 399 | t.Helper() |
| 400 | s.wait(t, "worker checks and review finished", timeout, func(c *thintest.Conversation) bool { |
| 401 | k := c.Tasks[id] |
| 402 | return k.Stage == wire.StageReadyToMerge || k.Stage == wire.StageDone || k.Stage == wire.StageCancelled |
| 403 | }) |
| 404 | k, err := s.env.Client.Task(s.ctx, id) |
| 405 | if err != nil { |
| 406 | t.Fatal(err) |
| 407 | } |
| 408 | if k.Stage != wire.StageReadyToMerge || k.Checks != wire.ChecksPassed || k.Verdict != wire.VerdictApprove || k.Merged != nil || k.MergeDecision == nil || k.MergeDecision.Class != "ask" { |
| 409 | t.Fatalf("worker pass granted automatic authority or did not finish: %+v", k) |
| 410 | } |
| 411 | missingBase := false |
| 412 | for _, reason := range k.MergeDecision.Reasons { |
| 413 | if reason.Name == "trusted_base_checks" && !reason.OK { |
| 414 | missingBase = true |
| 415 | } |
| 416 | } |
| 417 | if !missingBase { |
| 418 | t.Fatalf("missing trusted-base evidence not recorded: %+v", k.MergeDecision) |
| 419 | } |
| 420 | for _, step := range k.Steps { |
| 421 | // A merge of an earlier candidate (one that conflicted) is history. |
| 422 | if step.Specialist == wire.SpecialistMerge && step.CandidateSHA == k.CandidateSHA { |
| 423 | t.Fatal("merge dispatched before the person's decision") |
| 424 | } |
| 425 | } |
| 426 | if main := forgeHead(t, s.env.ForgePath(k.Repo), "main"); main != k.BaseSHA { |
| 427 | t.Fatalf("main moved before the person's decision: %s != %s", main, k.BaseSHA) |
| 428 | } |
| 429 | card := s.mergeCard(t, id) |
| 430 | if card.State != wire.CardOpen { |
| 431 | t.Fatalf("merge card not open: %+v", card) |
| 432 | } |
| 433 | if _, err := s.env.Client.Answer(s.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { |
| 434 | t.Fatal(err) |
| 435 | } |
| 436 | s.wait(t, "merged after the person's decision", time.Minute, func(c *thintest.Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| 437 | merged, err := s.env.Client.Task(s.ctx, id) |
| 438 | if err != nil { |
| 439 | t.Fatal(err) |
| 440 | } |
| 441 | if merged.CandidateSHA != k.CandidateSHA || merged.MergeDecision == nil || !strings.HasPrefix(merged.MergeDecision.DecidedBy, "person:") { |
| 442 | t.Fatalf("merge did not preserve person authority and candidate: %+v", merged) |
| 443 | } |
| 444 | mergedOnForge(t, s.env.ForgePath(k.Repo), merged) |
| 445 | return merged |
| 446 | } |
| 447 | |
| 448 | // TestMacWorker runs the Mac worker scenarios of the spec (§6, M1, M2, |
| 449 | // M4, M5) against a local instance, the primary runner with the fake CLI |
| 450 | // in real bubblewrap, and the fake Mac worker. |
| 451 | func TestMacWorker(t *testing.T) { |
| 452 | env, inst, primary := localEnv(t) |
| 453 | addWoodstar(t, primary.root, primary.opts.Forge.(*localForge)) |
| 454 | woodstarCredentials(t, primary) |
| 455 | primary.start(t) |
| 456 | worker, xcodebuild := macWorker(t, inst, primary) |
| 457 | worker.start(t) |
| 458 | s := open(t, env) |
| 459 | s.keep() |
| 460 | s.wait(t, "the worker online", 30*time.Second, func(c *thintest.Conversation) bool { |
| 461 | for _, r := range c.Runners { |
| 462 | if r.Role == wire.RoleWorker && r.Online && r.Label == "Tito Studio" { |
| 463 | return true |
| 464 | } |
| 465 | } |
| 466 | return false |
| 467 | }) |
| 468 | |
| 469 | // Mac work: Panes' gate runs xcodebuild, so its Engineering never runs |
| 470 | // on the Linux primary, and with EQUIPO_MAC_ENGINEERING unset (M9f) |
| 471 | // the Mac worker takes only checks: it waits, saying why, under Needs |
| 472 | // you. |
| 473 | t.Run("M0", func(t *testing.T) { |
| 474 | sent := s.send(t, "tool:record_task:woodstar/panes|Pane titles|Say what each pane is for.\ntool:start_task:$task|edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with titled panes") |
| 475 | id := s.taskOf(t, sent.Turn.ID) |
| 476 | k := s.settled(t, id, 2*time.Minute) |
| 477 | eng := stepOf(k, wire.SpecialistEngineering, 0) |
| 478 | if k.NeedsYou != wire.NeedsMacEngineering || eng.State != wire.StepQueued || eng.Placement != wire.PlacementMacEngineering || eng.RunnerID != "" { |
| 479 | t.Fatalf("Mac engineering %+v / %+v", k, eng) |
| 480 | } |
| 481 | // M9f: the switch is off, so nothing reaches the worker, though |
| 482 | // it could take it (its report says ready, claude). |
| 483 | if n := macDispatches(t, inst, worker.runnerID); n != 0 { |
| 484 | t.Fatalf("switch off: %d Engineering dispatches queued for the worker", n) |
| 485 | } |
| 486 | if _, err := env.Client.CancelTask(s.ctx, id); err != nil { |
| 487 | t.Fatal(err) |
| 488 | } |
| 489 | }) |
| 490 | |
| 491 | // M5: the fake gate fails on the worker (a Swift change, judged on a |
| 492 | // Mac); the fix round works from its output; the new candidate's |
| 493 | // checks pass on the worker. |
| 494 | t.Run("M5", func(t *testing.T) { |
| 495 | sent := s.send(t, "tool:record_task:woodstar/woodstar|Describe the panes|Say what the panes are for.\ntool:start_task:$task|edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with sliding panes") |
| 496 | id := s.taskOf(t, sent.Turn.ID) |
| 497 | k := s.mergeWorkerPass(t, id, 4*time.Minute) |
| 498 | first, second := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistChecks, 1) |
| 499 | if first.Checks != wire.ChecksFailed || first.ExitCode == nil || *first.ExitCode != 65 || first.RunnerLabel != "Tito Studio" || k.FixRounds != 1 || second.Checks != wire.ChecksPassed || second.CandidateSHA != k.CandidateSHA { |
| 500 | t.Fatalf("fix round from the worker's output: %+v / %+v / rounds %d", first, second, k.FixRounds) |
| 501 | } |
| 502 | }) |
| 503 | |
| 504 | // M1: an iOS change; its checks are placed on the worker, the |
| 505 | // candidate relayed as a pack, xcodebuild passes there; review stays on |
| 506 | // the primary; the person then chooses Merge. |
| 507 | t.Run("M1", func(t *testing.T) { |
| 508 | sent := s.send(t, "tool:record_task:woodstar/woodstar|iOS edge swipe|Swipe back from the edge feels late.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = true|edgeSwipe = true // from the edge") |
| 509 | id := s.taskOf(t, sent.Turn.ID) |
| 510 | k := s.mergeWorkerPass(t, id, 3*time.Minute) |
| 511 | checks, review := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistReview, 0) |
| 512 | if checks.RunnerLabel != "Tito Studio" || checks.Checks != wire.ChecksPassed || checks.Gate != ".amadan/ci" || checks.ExitCode == nil || *checks.ExitCode != 0 || checks.TerminationKind != wire.TerminationProcessGroup || strings.Join(checks.Needs, ",") != "macos,xcode,ios_simulator" || checks.CandidateSHA != k.CandidateSHA { |
| 513 | t.Fatalf("checks %+v", checks) |
| 514 | } |
| 515 | if review.RunnerID == checks.RunnerID || review.Verdict != wire.VerdictApprove || review.TerminationKind != wire.TerminationNamespace { |
| 516 | t.Fatalf("review %+v", review) |
| 517 | } |
| 518 | log, err := env.Client.StepLog(s.ctx, checks.ID) |
| 519 | if err != nil || !strings.Contains(log.Tail, "** TEST SUCCEEDED **") { |
| 520 | t.Fatalf("checks log %+v %v", log, err) |
| 521 | } |
| 522 | if k.Merged == nil || k.Merged.WithoutChecks || k.EngineeringRunner == checks.RunnerID { |
| 523 | t.Fatalf("merge %+v", k) |
| 524 | } |
| 525 | }) |
| 526 | |
| 527 | // M2: the worker is offline; checks wait (no dispatch anywhere), then |
| 528 | // run when it is back. A second task waits 30 minutes (a fake clock) |
| 529 | // and resolves as not run, runner_offline, never a pass; review goes on. |
| 530 | t.Run("M2", func(t *testing.T) { |
| 531 | worker.stop(t) |
| 532 | s.wait(t, "the worker offline", 30*time.Second, func(c *thintest.Conversation) bool { |
| 533 | for _, r := range c.Runners { |
| 534 | if r.Role == wire.RoleWorker && !r.Online { |
| 535 | return true |
| 536 | } |
| 537 | } |
| 538 | return false |
| 539 | }) |
| 540 | sent := s.send(t, "tool:record_task:woodstar/woodstar|About while away|Name the app.\ntool:start_task:$task|edit:Woodstar/About.swift|reading app|reading app (m2a)") |
| 541 | id := s.taskOf(t, sent.Turn.ID) |
| 542 | s.wait(t, "checks waiting", 2*time.Minute, func(c *thintest.Conversation) bool { |
| 543 | for _, st := range c.Tasks[id].Steps { |
| 544 | if st.Specialist == wire.SpecialistChecks && st.Placement == wire.PlacementWaiting { |
| 545 | return true |
| 546 | } |
| 547 | } |
| 548 | return false |
| 549 | }) |
| 550 | worker.start(t) |
| 551 | k := s.mergeWorkerPass(t, id, 3*time.Minute) |
| 552 | if c := stepOf(k, wire.SpecialistChecks, 0); c.Checks != wire.ChecksPassed || c.RunnerLabel != "Tito Studio" { |
| 553 | t.Fatalf("checks after reconnect %+v", c) |
| 554 | } |
| 555 | |
| 556 | worker.stop(t) |
| 557 | sent = s.send(t, "tool:record_task:woodstar/woodstar|About, worker gone|Name it again.\ntool:start_task:$task|edit:Woodstar/About.swift|reading app (m2a)|reading app (m2b)") |
| 558 | late := s.taskOf(t, sent.Turn.ID) |
| 559 | s.wait(t, "checks waiting", 2*time.Minute, func(c *thintest.Conversation) bool { |
| 560 | for _, st := range c.Tasks[late].Steps { |
| 561 | if st.Specialist == wire.SpecialistChecks && st.Placement == wire.PlacementWaiting { |
| 562 | return true |
| 563 | } |
| 564 | } |
| 565 | return false |
| 566 | }) |
| 567 | later := time.Now().UTC().Add(chat.OfflineLimit + time.Minute) |
| 568 | inst.Store.Chat().SetClock(func() time.Time { return later }) |
| 569 | if err := inst.Store.Chat().Place(context.Background()); err != nil { |
| 570 | t.Fatal(err) |
| 571 | } |
| 572 | inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) |
| 573 | k = s.settled(t, late, 2*time.Minute) |
| 574 | c := stepOf(k, wire.SpecialistChecks, 0) |
| 575 | if c.Checks != wire.ChecksCannotRun || c.Reason != "runner_offline" || k.Checks == wire.ChecksPassed || k.Stage != wire.StageReadyToMerge || stepOf(k, wire.SpecialistReview, 0).Verdict != wire.VerdictApprove { |
| 576 | t.Fatalf("offline checks %+v task %+v", c, k) |
| 577 | } |
| 578 | }) |
| 579 | |
| 580 | // M4: the worker is SIGKILLed while xcodebuild runs. Its gate's process |
| 581 | // group outlives it; on restart the worker kills what is left, proves |
| 582 | // the end by process group, and only then does Retry run the checks |
| 583 | // again, which pass. |
| 584 | t.Run("M4", func(t *testing.T) { |
| 585 | // Its own precondition: the worker running, started here. |
| 586 | worker.stop(t) |
| 587 | worker.start(t) |
| 588 | if err := os.WriteFile(xcodebuild+".hang", nil, 0600); err != nil { |
| 589 | t.Fatal(err) |
| 590 | } |
| 591 | t.Cleanup(func() { os.Remove(xcodebuild + ".hang") }) |
| 592 | sent := s.send(t, "tool:record_task:woodstar/woodstar|Killed mid checks|Tighten the summary line.\ntool:start_task:$task|create:Woodstar/Summary.swift|let summaryTitle = 4\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| 593 | id := s.taskOf(t, sent.Turn.ID) |
| 594 | s.wait(t, "checks running on the worker", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 595 | for _, st := range c.Tasks[id].Steps { |
| 596 | if st.Specialist == wire.SpecialistChecks && st.State == wire.StepRunning && st.StartedAt != nil { |
| 597 | return true |
| 598 | } |
| 599 | } |
| 600 | return false |
| 601 | }) |
| 602 | time.Sleep(time.Second) |
| 603 | worker.kill(t) |
| 604 | if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 { |
| 605 | t.Fatalf("retry before the worker proved termination: %v", err) |
| 606 | } |
| 607 | os.Remove(xcodebuild + ".hang") |
| 608 | worker.start(t) |
| 609 | k := s.settled(t, id, 2*time.Minute) |
| 610 | c := stepOf(k, wire.SpecialistChecks, 0) |
| 611 | if c.State != wire.StepFailed || c.Reason != "runner_restarted" || !c.Terminated || c.TerminationKind != wire.TerminationProcessGroup || k.NeedsYou != wire.NeedsRetry { |
| 612 | t.Fatalf("after the kill %+v", c) |
| 613 | } |
| 614 | // Nothing of the killed attempt is left running (no checks run now). |
| 615 | entries, _ := os.ReadDir("/proc") |
| 616 | for _, e := range entries { |
| 617 | env, err := os.ReadFile(filepath.Join("/proc", e.Name(), "environ")) |
| 618 | if err == nil && strings.Contains(string(env), "EQUIPO_ATTEMPT=checks/") && strings.Contains(string(env), proc.ScopeEnv+"="+worker.scope+"\x00") { |
| 619 | cmdline, _ := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline")) |
| 620 | t.Fatalf("process %s of the killed attempt survived: %q", e.Name(), strings.ReplaceAll(string(cmdline), "\x00", " ")) |
| 621 | } |
| 622 | } |
| 623 | if _, err := env.Client.RetryTask(s.ctx, id); err != nil { |
| 624 | t.Fatal(err) |
| 625 | } |
| 626 | k = s.mergeWorkerPass(t, id, 3*time.Minute) |
| 627 | if c := stepOf(k, wire.SpecialistChecks, 0); c.Attempt != 2 || c.Checks != wire.ChecksPassed || c.RunnerLabel != "Tito Studio" { |
| 628 | t.Fatalf("checks after Retry %+v", c) |
| 629 | } |
| 630 | }) |
| 631 | |
| 632 | // Mac Engineering (slice F): EQUIPO_MAC_ENGINEERING is set from here. |
| 633 | inst.Store.Chat().SetMacEngineering(true) |
| 634 | |
| 635 | // M9a: Panes is Woodstar-shaped (an .xcodeproj with a shared scheme, |
| 636 | // a gate that runs xcodebuild), so its Engineering is Mac work. The |
| 637 | // primary prepares the base, the attempt goes to the worker with the |
| 638 | // inbound pack, the fake CLI edits a Swift file there (darwin launch, |
| 639 | // the pinned stand-in, the worker's own Claude connection), and the |
| 640 | // worker scans, commits and uploads a thin pack the primary pushes. |
| 641 | // The change's files and diffs show, checks run on the worker, review |
| 642 | // on the primary, and Ready to merge asks: a Mac-made candidate is |
| 643 | // never merged by policy. |
| 644 | t.Run("M9a", func(t *testing.T) { |
| 645 | sent := s.send(t, "tool:record_task:woodstar/panes|Edge swipe on the Mac|Swipe back from the edge feels late.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| 646 | id := s.taskOf(t, sent.Turn.ID) |
| 647 | s.wait(t, "Engineering placed on the worker", 2*time.Minute, func(c *thintest.Conversation) bool { |
| 648 | e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| 649 | return e.RunnerID == worker.runnerID || e.State == wire.StepFailed |
| 650 | }) |
| 651 | k, err := env.Client.Task(s.ctx, id) |
| 652 | if err != nil { |
| 653 | t.Fatal(err) |
| 654 | } |
| 655 | eng := stepOf(k, wire.SpecialistEngineering, 0) |
| 656 | if eng.RunnerID != worker.runnerID || eng.RunnerLabel != "Tito Studio" { |
| 657 | t.Fatalf("Engineering not on the worker: %+v", eng) |
| 658 | } |
| 659 | s.wait(t, "the worker's candidate published", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 660 | e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| 661 | return e.Pushed || e.State == wire.StepFailed |
| 662 | }) |
| 663 | if k, err = env.Client.Task(s.ctx, id); err != nil { |
| 664 | t.Fatal(err) |
| 665 | } |
| 666 | eng = stepOf(k, wire.SpecialistEngineering, 0) |
| 667 | if eng.State != wire.StepDone || !eng.Pushed || eng.Account != macClaude || eng.TerminationKind != wire.TerminationProcessGroup || !eng.Terminated || eng.XcodeAccess != wire.XcodeAccessSandboxed || k.EngineeringRunner != worker.runnerID { |
| 668 | t.Fatalf("Engineering on the worker %+v (task runner %q)", eng, k.EngineeringRunner) |
| 669 | } |
| 670 | if f := eng.ChangeFiles; f == nil || f.SHA != eng.CandidateSHA || len(f.Entries) != 1 || f.Entries[0].Path != "Woodstar/Swipe.swift" { |
| 671 | t.Fatalf("change files %+v", eng.ChangeFiles) |
| 672 | } |
| 673 | if d := s.changeDiff(t, id, eng.CandidateSHA, "Woodstar/Swipe.swift"); !strings.Contains(d.Patch, "+let edgeSwipe = true") { |
| 674 | t.Fatalf("diff %+v", d) |
| 675 | } |
| 676 | // The primary pushed exactly the worker's commit, made as Equipo. |
| 677 | bare := env.ForgePath(panes) |
| 678 | if head := forgeHead(t, bare, k.Branch); head != eng.CandidateSHA { |
| 679 | t.Fatalf("branch %s at %s, want %s", k.Branch, head, eng.CandidateSHA) |
| 680 | } |
| 681 | if who := forgeShow(t, bare, "-s", "--format=%an <%ae>", eng.CandidateSHA); !strings.Contains(who, "Equipo") { |
| 682 | t.Fatalf("candidate author %q", who) |
| 683 | } |
| 684 | k = s.mergeWorkerPass(t, id, 4*time.Minute) |
| 685 | checks, review := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistReview, 0) |
| 686 | if checks.RunnerID != worker.runnerID || checks.Checks != wire.ChecksPassed || checks.CandidateSHA != eng.CandidateSHA || review.RunnerID == worker.runnerID || review.Verdict != wire.VerdictApprove { |
| 687 | t.Fatalf("checks %+v review %+v", checks, review) |
| 688 | } |
| 689 | if k.Merged == nil || k.Merged.WithoutChecks { |
| 690 | t.Fatalf("merge %+v", k) |
| 691 | } |
| 692 | }) |
| 693 | |
| 694 | // M9b: the new pane's test fails on the worker; the fix round works |
| 695 | // from that output on the worker, resuming the session that made the |
| 696 | // candidate (in a new worktree: each attempt checks out its own). The |
| 697 | // first publication's push fails (the forge refuses it), and Retry |
| 698 | // publishes the same commit again without running Engineering. |
| 699 | var paneTask string |
| 700 | t.Run("M9b", func(t *testing.T) { |
| 701 | bare := env.ForgePath(panes) |
| 702 | refuse := refusePushes(t, bare) |
| 703 | before := macDispatches(t, inst, worker.runnerID) |
| 704 | // The first round also leaves a file its commit ignores (build/), |
| 705 | // and says where it worked; the fix round (from the checks' |
| 706 | // output) says where it works and whether that file is there. |
| 707 | sent := s.send(t, "tool:record_task:woodstar/panes|Pane back gesture|Add the back gesture to the panes.\ntool:start_task:$task|create:Woodstar/Pane.swift|let paneBack = false\ncreate:build/leftover.txt|left by the first round\nsaycwd") |
| 708 | id := s.taskOf(t, sent.Turn.ID) |
| 709 | paneTask = id |
| 710 | s.wait(t, "the publication refused", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 711 | e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| 712 | return e.Publication == wire.PublicationFailed || e.State == wire.StepFailed || e.Pushed |
| 713 | }) |
| 714 | k, err := env.Client.Task(s.ctx, id) |
| 715 | if err != nil { |
| 716 | t.Fatal(err) |
| 717 | } |
| 718 | first := stepOf(k, wire.SpecialistEngineering, 0) |
| 719 | if first.Publication != wire.PublicationFailed || first.Pushed || first.CandidateSHA == "" || first.RunnerID != worker.runnerID || forgeHead(t, bare, k.Branch) != "" { |
| 720 | t.Fatalf("refused publication %+v", first) |
| 721 | } |
| 722 | refuse(false) |
| 723 | if acc, err := env.Client.RetryTask(s.ctx, id); err != nil || acc.Attempt != 1 { |
| 724 | t.Fatalf("retry the publication: %+v %v", acc, err) |
| 725 | } |
| 726 | s.wait(t, "published again", 2*time.Minute, func(c *thintest.Conversation) bool { |
| 727 | return stepOf(c.Tasks[id], wire.SpecialistEngineering, 0).Pushed |
| 728 | }) |
| 729 | k = s.settled(t, id, 4*time.Minute) |
| 730 | again := stepOf(k, wire.SpecialistEngineering, 0) |
| 731 | if again.ID != first.ID || again.Attempt != 1 || again.CandidateSHA != first.CandidateSHA || forgeShow(t, bare, "-s", "--format=%H", again.CandidateSHA) != first.CandidateSHA+"\n" { |
| 732 | t.Fatalf("republished %+v, first %+v", again, first) |
| 733 | } |
| 734 | failed, fix, passed := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistEngineering, 1), stepOf(k, wire.SpecialistChecks, 1) |
| 735 | if failed.Checks != wire.ChecksFailed || failed.RunnerID != worker.runnerID || failed.CandidateSHA != first.CandidateSHA { |
| 736 | t.Fatalf("checks of the first candidate %+v", failed) |
| 737 | } |
| 738 | if fix.Round != 1 || fix.RunnerID != worker.runnerID || fix.BaseSHA != first.CandidateSHA || !fix.Pushed || !strings.Contains(fix.Summary, "(resumed session)") || fix.Account != macClaude { |
| 739 | t.Fatalf("fix round %+v", fix) |
| 740 | } |
| 741 | // The very session of the first round, resumed in a fresh tree |
| 742 | // of its commit: another directory, without the file the first |
| 743 | // round left uncommitted. |
| 744 | var s0, s1 string |
| 745 | db := inst.DB.Writer() |
| 746 | if err := db.QueryRow("SELECT coalesce(session_id, '') FROM chat_steps WHERE id = ?", first.ID).Scan(&s0); err != nil || s0 == "" { |
| 747 | t.Fatalf("the first round's session %q %v", s0, err) |
| 748 | } |
| 749 | if err := db.QueryRow("SELECT coalesce(session_id, '') FROM chat_steps WHERE id = ?", fix.ID).Scan(&s1); err != nil || s1 != s0 { |
| 750 | t.Fatalf("the fix round resumed session %q, the first round's was %q (%v)", s1, s0, err) |
| 751 | } |
| 752 | if kept := workerKept(t, worker, fix.ID); len(kept) != 1 || kept[0] != s0 { |
| 753 | t.Fatalf("the worker kept %v for the fix round, want [%s]", kept, s0) |
| 754 | } |
| 755 | dir0, dir1 := workedIn(first.Summary), workedIn(fix.Summary) |
| 756 | if dir0 == "" || dir1 == "" || dir0 == dir1 || !strings.Contains(dir0, "/worker-steps/") || !strings.Contains(dir1, "/worker-steps/") { |
| 757 | t.Fatalf("worktrees %q then %q (%q / %q)", dir0, dir1, first.Summary, fix.Summary) |
| 758 | } |
| 759 | if !strings.Contains(first.Summary, "Created build/leftover.txt.") || !strings.Contains(fix.Summary, "No build/leftover.txt.") { |
| 760 | t.Fatalf("the fix round's tree is not fresh: %q / %q", first.Summary, fix.Summary) |
| 761 | } |
| 762 | if passed.Checks != wire.ChecksPassed || passed.CandidateSHA != fix.CandidateSHA || k.Stage != wire.StageReadyToMerge || k.CandidateSHA != fix.CandidateSHA { |
| 763 | t.Fatalf("after the fix round %+v / %+v", passed, k) |
| 764 | } |
| 765 | // Engineering went to the worker twice: the first round and the |
| 766 | // fix round. Retry of the publication sent it nothing. |
| 767 | if n := macDispatches(t, inst, worker.runnerID) - before; n != 2 { |
| 768 | t.Fatalf("%d Engineering dispatches to the worker, want 2", n) |
| 769 | } |
| 770 | }) |
| 771 | |
| 772 | // M9c: main moves under the ready task with a conflicting change, so |
| 773 | // the person's Merge conflicts; the rebase round runs on the worker |
| 774 | // (pinned), resolves the conflict, and its candidate is checked on |
| 775 | // the worker and reviewed on the primary again. |
| 776 | t.Run("M9c", func(t *testing.T) { |
| 777 | if paneTask == "" { |
| 778 | t.Skip("needs M9b's task") |
| 779 | } |
| 780 | id, bare := paneTask, env.ForgePath(panes) |
| 781 | work := t.TempDir() |
| 782 | gitRun(t, work, "clone", "-q", bare, "w") |
| 783 | if err := os.WriteFile(filepath.Join(work, "w", "Woodstar", "Pane.swift"), []byte("let paneBack = true // from main\n"), 0600); err != nil { |
| 784 | t.Fatal(err) |
| 785 | } |
| 786 | gitRun(t, work+"/w", "add", "-A") |
| 787 | gitRun(t, work+"/w", "commit", "-q", "-m", "main moves") |
| 788 | gitRun(t, work+"/w", "push", "-q", "origin", "main") |
| 789 | moved := forgeHead(t, bare, "main") |
| 790 | card := s.mergeCard(t, id) |
| 791 | if _, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { |
| 792 | t.Fatal(err) |
| 793 | } |
| 794 | defer func() { |
| 795 | if t.Failed() { |
| 796 | k, _ := env.Client.Task(context.Background(), id) |
| 797 | t.Logf("task %s %s needs %q: %s", k.Stage, k.CandidateSHA, k.NeedsYou, stepKinds(k)) |
| 798 | } |
| 799 | }() |
| 800 | // The rebase keeps the task's side of its first commit (the pane's |
| 801 | // test failing), so its checks fail on the worker and a fix round |
| 802 | // there mends it: ready to merge once review approves that. |
| 803 | s.wait(t, "the rebase round judged", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 804 | k := c.Tasks[id] |
| 805 | rebased := false |
| 806 | for _, st := range k.Steps { |
| 807 | rebased = rebased || st.Rebase && st.Pushed |
| 808 | if st.Rebase && st.State == wire.StepFailed { |
| 809 | return true |
| 810 | } |
| 811 | } |
| 812 | last := k.Steps[len(k.Steps)-1] |
| 813 | return rebased && k.Stage == wire.StageReadyToMerge && last.Specialist == wire.SpecialistReview && last.CandidateSHA == k.CandidateSHA || k.Stage == wire.StageDone || k.Stage == wire.StageCancelled |
| 814 | }) |
| 815 | k := s.mergeWorkerPass(t, id, 4*time.Minute) |
| 816 | var rebase wire.Step |
| 817 | for _, st := range k.Steps { |
| 818 | if st.Rebase { |
| 819 | rebase = st |
| 820 | } |
| 821 | if st.Specialist == wire.SpecialistEngineering && st.RunnerID != worker.runnerID { |
| 822 | t.Fatalf("Engineering off the pinned worker: %s", stepKinds(k)) |
| 823 | } |
| 824 | } |
| 825 | if !rebase.Rebase || rebase.RunnerID != worker.runnerID || rebase.BaseSHA != moved || !rebase.Pushed || k.BaseSHA != moved { |
| 826 | t.Fatalf("rebase round %+v (task base %s, main %s)", rebase, k.BaseSHA, moved) |
| 827 | } |
| 828 | if parent := strings.TrimSpace(forgeShow(t, bare, "-s", "--format=%P", rebase.CandidateSHA)); parent != moved { |
| 829 | t.Fatalf("rebased candidate's parent %s, want %s", parent, moved) |
| 830 | } |
| 831 | if src := forgeShow(t, bare, "main:Woodstar/Pane.swift"); strings.Contains(src, "<<<<<<<") { |
| 832 | t.Fatalf("main after the rebase: %s", src) |
| 833 | } |
| 834 | }) |
| 835 | |
| 836 | // M9e: the worker is SIGKILLed while the CLI works, so the turn's |
| 837 | // record never gets its final note. On restart the worker ends what |
| 838 | // the launch left and, holding the Mac's turn, reads the runner |
| 839 | // user's processes (task 9's idle clearance, on the fake's scoped |
| 840 | // table): only the runner and what existed before the turn are left, |
| 841 | // and nothing the record names is alive, so the end is proven by |
| 842 | // process group. Retry runs Engineering again on the same worker, to |
| 843 | // done; nobody clears anything by hand. |
| 844 | var killedTask string |
| 845 | t.Run("M9e", func(t *testing.T) { |
| 846 | hold := filepath.Join(t.TempDir(), "hold") |
| 847 | if err := os.WriteFile(hold, nil, 0600); err != nil { |
| 848 | t.Fatal(err) |
| 849 | } |
| 850 | // The CLI also starts a child in a session of its own that ignores |
| 851 | // SIGTERM and SIGHUP and keeps the attempt's marker: it outlives |
| 852 | // the runner, and only the restart's recovery may end it. |
| 853 | linger := filepath.Join(t.TempDir(), "linger.pid") |
| 854 | sent := s.send(t, "tool:record_task:woodstar/panes|Killed mid Engineering|Name the app in About.\ntool:start_task:$task|linger:"+linger+" stepwait:"+hold+" edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with panes\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| 855 | id := s.taskOf(t, sent.Turn.ID) |
| 856 | killedTask = id |
| 857 | defer func() { |
| 858 | if t.Failed() { |
| 859 | k, _ := env.Client.Task(context.Background(), id) |
| 860 | t.Logf("task %s needs %q: %s; the Mac's report: %+v", k.Stage, k.NeedsYou, stepKinds(k), macCaps(t, inst, worker.runnerID).Engineering) |
| 861 | } |
| 862 | }() |
| 863 | s.wait(t, "Engineering running on the worker", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 864 | e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| 865 | return e.RunnerID == worker.runnerID && e.State == wire.StepRunning && e.StartedAt != nil |
| 866 | }) |
| 867 | // The CLI is in its turn: it has started its lingering child, |
| 868 | // which carries the attempt's marker. |
| 869 | child := lingering(t, linger) |
| 870 | t.Cleanup(func() { |
| 871 | // Whatever the assertions found: it never outlives the test. |
| 872 | if child.alive() { |
| 873 | _ = syscall.Kill(child.PID, syscall.SIGKILL) |
| 874 | } |
| 875 | }) |
| 876 | worker.kill(t) |
| 877 | if !child.alive() { |
| 878 | t.Fatalf("the launch's lingering child %+v did not outlive the runner", child) |
| 879 | } |
| 880 | if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 { |
| 881 | t.Fatalf("retry before the worker proved the end: %v", err) |
| 882 | } |
| 883 | if err := os.Remove(hold); err != nil { |
| 884 | t.Fatal(err) |
| 885 | } |
| 886 | worker.start(t) |
| 887 | s.wait(t, "the end proven", 2*time.Minute, func(c *thintest.Conversation) bool { |
| 888 | e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| 889 | return e.State == wire.StepFailed && e.Terminated |
| 890 | }) |
| 891 | k, err := env.Client.Task(s.ctx, id) |
| 892 | if err != nil { |
| 893 | t.Fatal(err) |
| 894 | } |
| 895 | e := stepOf(k, wire.SpecialistEngineering, 0) |
| 896 | if e.Reason != "runner_restarted" || e.TerminationKind != wire.TerminationProcessGroup || e.RunnerID != worker.runnerID || k.NeedsYou != wire.NeedsRetry { |
| 897 | t.Fatalf("after the restart %+v (needs %q)", e, k.NeedsYou) |
| 898 | } |
| 899 | // Recovery ended it, by its identity, before the end was proven |
| 900 | // (and so before the clearance and any Retry). |
| 901 | if child.alive() { |
| 902 | t.Fatalf("the launch's lingering child %+v survived the restart, and the end was proven", child) |
| 903 | } |
| 904 | if left := engineeringProcs(worker); len(left) > 0 { |
| 905 | t.Fatalf("processes %v of the killed attempt survived the restart", left) |
| 906 | } |
| 907 | if _, err := os.Stat(filepath.Join(worker.cfg.StateDir, "mac-gate.lock.owed")); err == nil { |
| 908 | if raw, _ := os.ReadFile(filepath.Join(worker.cfg.StateDir, "mac-gate.lock.owed")); strings.Contains(string(raw), "engineering-") { |
| 909 | t.Fatalf("the killed attempt still owes after the clearance: %s", raw) |
| 910 | } |
| 911 | } |
| 912 | s.wait(t, "the Mac ready again", time.Minute, func(*thintest.Conversation) bool { |
| 913 | caps := macCaps(t, inst, worker.runnerID) |
| 914 | return caps.Unproven == "" && caps.Engineering != nil && caps.Engineering.State == wire.EngineeringReady |
| 915 | }) |
| 916 | before := macDispatches(t, inst, worker.runnerID) |
| 917 | if _, err := env.Client.RetryTask(s.ctx, id); err != nil { |
| 918 | t.Fatal(err) |
| 919 | } |
| 920 | s.wait(t, "the second attempt judged", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 921 | k := c.Tasks[id] |
| 922 | e := stepOf(k, wire.SpecialistEngineering, 0) |
| 923 | last := k.Steps[len(k.Steps)-1] |
| 924 | return e.Attempt == 2 && e.State == wire.StepFailed || e.Attempt == 2 && e.Pushed && k.Stage == wire.StageReadyToMerge && last.Specialist == wire.SpecialistReview && last.CandidateSHA == k.CandidateSHA |
| 925 | }) |
| 926 | if k, err = env.Client.Task(s.ctx, id); err != nil { |
| 927 | t.Fatal(err) |
| 928 | } |
| 929 | e = stepOf(k, wire.SpecialistEngineering, 0) |
| 930 | if e.Attempt != 2 || e.State != wire.StepDone || !e.Pushed || e.RunnerID != worker.runnerID || k.Stage != wire.StageReadyToMerge || macDispatches(t, inst, worker.runnerID) != before+1 { |
| 931 | t.Fatalf("Engineering after Retry %+v (task %s: %s)", e, k.Stage, stepKinds(k)) |
| 932 | } |
| 933 | }) |
| 934 | |
| 935 | // M9d: the person asks Engineering about its work on the killed and |
| 936 | // retried task: the worker answers from the session its second |
| 937 | // attempt kept, on that commit. A question pinned to the first |
| 938 | // attempt (which kept nothing: it was killed) or to a session the |
| 939 | // worker did not keep is refused; with the worker stopped, Ask says |
| 940 | // it is offline and queues nothing. |
| 941 | t.Run("M9d", func(t *testing.T) { |
| 942 | if killedTask == "" { |
| 943 | t.Skip("needs M9e's task") |
| 944 | } |
| 945 | id := killedTask |
| 946 | k, err := env.Client.Task(s.ctx, id) |
| 947 | if err != nil { |
| 948 | t.Fatal(err) |
| 949 | } |
| 950 | eng := stepOf(k, wire.SpecialistEngineering, 0) |
| 951 | if !eng.Askable { |
| 952 | t.Fatalf("Engineering kept no session: %+v", eng) |
| 953 | } |
| 954 | q, _ := s.asked(t, id, "What did you change and why? ask:git ask:read:Woodstar/About.swift", wire.SpecialistEngineering, time.Minute) |
| 955 | if q.State != wire.QuestionAnswered || q.StepID != eng.ID || !strings.HasPrefix(q.Answer, "From my session:") || !strings.Contains(q.Answer, "The change: +") || !strings.Contains(q.Answer, "with panes") { |
| 956 | t.Fatalf("answer from the worker %+v", q) |
| 957 | } |
| 958 | if attempt, session, kept := macAskPin(t, inst, worker, q.ID); attempt != 2 || session == "" || session != kept { |
| 959 | t.Fatalf("pinned to attempt %d session %q; the worker kept %q", attempt, session, kept) |
| 960 | } |
| 961 | // The instance names what it asks about; the worker answers only |
| 962 | // for what it kept (the pins are forged on the instance's step). |
| 963 | forge := func(column string, value any) func() { |
| 964 | db := inst.DB.Writer() |
| 965 | var old any |
| 966 | if err := db.QueryRow("SELECT "+column+" FROM chat_steps WHERE id = ?", eng.ID).Scan(&old); err != nil { |
| 967 | t.Fatal(err) |
| 968 | } |
| 969 | if _, err := db.Exec("UPDATE chat_steps SET "+column+" = ? WHERE id = ?", value, eng.ID); err != nil { |
| 970 | t.Fatal(err) |
| 971 | } |
| 972 | return func() { |
| 973 | if _, err := db.Exec("UPDATE chat_steps SET "+column+" = ? WHERE id = ?", old, eng.ID); err != nil { |
| 974 | t.Fatal(err) |
| 975 | } |
| 976 | } |
| 977 | } |
| 978 | restore := forge("attempt", 1) |
| 979 | gone, _ := s.asked(t, id, "And the first time?", wire.SpecialistEngineering, time.Minute) |
| 980 | restore() |
| 981 | if gone.State != wire.QuestionFailed || gone.Reason != "session_gone" { |
| 982 | t.Fatalf("asked about the killed attempt: %+v", gone) |
| 983 | } |
| 984 | restore = forge("session_id", "00000000-0000-4000-8000-0000000000ff") |
| 985 | other, _ := s.asked(t, id, "And in another session?", wire.SpecialistEngineering, time.Minute) |
| 986 | restore() |
| 987 | if other.State != wire.QuestionFailed || other.Reason != "policy_rejected" { |
| 988 | t.Fatalf("asked about a session the worker did not keep: %+v", other) |
| 989 | } |
| 990 | worker.stop(t) |
| 991 | s.wait(t, "the worker offline", 30*time.Second, func(c *thintest.Conversation) bool { |
| 992 | for _, r := range c.Runners { |
| 993 | if r.ID == worker.runnerID { |
| 994 | return !r.Online |
| 995 | } |
| 996 | } |
| 997 | return false |
| 998 | }) |
| 999 | var n int |
| 1000 | inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_questions WHERE task_id = ?", id).Scan(&n) |
| 1001 | if _, err := env.Client.Ask(s.ctx, id, "Still there?", wire.SpecialistEngineering, key()); thintest.Status(err) != 409 || !strings.Contains(err.Error(), "runner_offline") { |
| 1002 | t.Fatalf("ask while the worker is offline: %v", err) |
| 1003 | } |
| 1004 | var after int |
| 1005 | inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_questions WHERE task_id = ?", id).Scan(&after) |
| 1006 | if after != n { |
| 1007 | t.Fatalf("an offline ask queued a question (%d, then %d)", n, after) |
| 1008 | } |
| 1009 | worker.start(t) |
| 1010 | if _, err := env.Client.CancelTask(s.ctx, id); err != nil { |
| 1011 | t.Fatal(err) |
| 1012 | } |
| 1013 | }) |
| 1014 | |
| 1015 | // M9h: the change holds a secret (a GitHub token in a new file, by |
| 1016 | // bytes the prompt does not show): the worker's scan refuses it |
| 1017 | // before anything leaves, so nothing is uploaded or pushed. |
| 1018 | t.Run("M9h", func(t *testing.T) { |
| 1019 | secret := base64.StdEncoding.EncodeToString([]byte("let token = \"ghs_" + strings.Repeat("k7Qm", 9) + "\"\n")) |
| 1020 | sent := s.send(t, "tool:record_task:woodstar/panes|Add the sync token|Sync the panes.\ntool:start_task:$task|bytes:Woodstar/Sync.swift|"+secret) |
| 1021 | id := s.taskOf(t, sent.Turn.ID) |
| 1022 | k := s.settled(t, id, 3*time.Minute) |
| 1023 | e := stepOf(k, wire.SpecialistEngineering, 0) |
| 1024 | if e.State != wire.StepFailed || e.Reason != wire.ReasonSecretInCandidate || e.Pushed || e.CandidateSHA != "" || e.RunnerID != worker.runnerID || e.Askable { |
| 1025 | t.Fatalf("secret in the candidate %+v", e) |
| 1026 | } |
| 1027 | if head := forgeHead(t, env.ForgePath(panes), k.Branch); head != "" { |
| 1028 | t.Fatalf("pushed %s", head) |
| 1029 | } |
| 1030 | for _, st := range k.Steps { |
| 1031 | if st.Specialist != wire.SpecialistEngineering { |
| 1032 | t.Fatalf("a step after the refusal: %s", stepKinds(k)) |
| 1033 | } |
| 1034 | } |
| 1035 | if _, err := env.Client.CancelTask(s.ctx, id); err != nil { |
| 1036 | t.Fatal(err) |
| 1037 | } |
| 1038 | }) |
| 1039 | |
| 1040 | // M9i: the step runs out of time on the worker (its limit is a |
| 1041 | // minute) with its change made: the worker commits it as unfinished |
| 1042 | // work, the primary publishes it, and it is never shown as finished |
| 1043 | // work (step_timeout through publication; Review is told). |
| 1044 | t.Run("M9i", func(t *testing.T) { |
| 1045 | hold := filepath.Join(t.TempDir(), "hold") |
| 1046 | if err := os.WriteFile(hold, nil, 0600); err != nil { |
| 1047 | t.Fatal(err) |
| 1048 | } |
| 1049 | sent := s.send(t, "tool:record_task:woodstar/panes|Slow pane titles|Title each pane.\ntool:start_task:$task|edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with titled panes afterwait:"+hold) |
| 1050 | id := s.taskOf(t, sent.Turn.ID) |
| 1051 | s.wait(t, "the unfinished work published", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 1052 | e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| 1053 | return e.Pushed || e.State == wire.StepFailed || e.State == wire.StepCancelled |
| 1054 | }) |
| 1055 | k, err := env.Client.Task(s.ctx, id) |
| 1056 | if err != nil { |
| 1057 | t.Fatal(err) |
| 1058 | } |
| 1059 | e := stepOf(k, wire.SpecialistEngineering, 0) |
| 1060 | if e.State != wire.StepDone || !e.Pushed || e.Reason != "step_timeout" || e.RunnerID != worker.runnerID || e.Publication != wire.PublicationPublished { |
| 1061 | t.Fatalf("unfinished work %+v", e) |
| 1062 | } |
| 1063 | if msg := forgeShow(t, env.ForgePath(panes), "-s", "--format=%B", e.CandidateSHA); !strings.Contains(msg, "ran out of time before it finished") { |
| 1064 | t.Fatalf("commit message %q", msg) |
| 1065 | } |
| 1066 | k = s.settled(t, id, 3*time.Minute) |
| 1067 | if e := stepOf(k, wire.SpecialistEngineering, 0); e.Reason != "step_timeout" || k.Stage == wire.StageDone || k.Merged != nil { |
| 1068 | t.Fatalf("shown as finished %+v / %s", e, stepKinds(k)) |
| 1069 | } |
| 1070 | if _, err := env.Client.CancelTask(s.ctx, id); err != nil { |
| 1071 | t.Fatal(err) |
| 1072 | } |
| 1073 | }) |
| 1074 | |
| 1075 | } |
| 1076 | |