Skip to content
quarry Artifact [44468e9abd]
Login

Artifact [44468e9abd]

Artifact 44468e9abda079f605a889ae2e912d5781ccc42f8f189d97fe88b25aa033a9ca:


package pickupclient

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"
)

// landForge answers the ops quarry land composes and records what it was
// sent. gets is the sequence landing.get answers (the last one repeats).
type landForge struct {
	srv        *httptest.Server
	mu         sync.Mutex
	open       []map[string]any // landing.list rows
	gets       []map[string]any
	getN       int
	posts      map[string]map[string]any // path -> body
	refuse     map[string]int            // path suffix -> status of a refusal
	refuseBody map[string]string         // path suffix -> its body (default: a branch rule)
	streams    chan struct{}             // one event per receive on the stream
	byID       map[string]map[string]any // landing.get by id, for the local-accept check
}

func newLandForge(t *testing.T) *landForge {
	f := &landForge{posts: map[string]map[string]any{}, refuse: map[string]int{}, refuseBody: map[string]string{}, streams: make(chan struct{}, 8), byID: map[string]map[string]any{}}
	f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Authorization") != "Bearer "+apiTestToken {
			w.WriteHeader(401)
			return
		}
		f.mu.Lock()
		defer f.mu.Unlock()
		p := strings.TrimPrefix(r.URL.Path, "/api/v1")
		if r.Method == "POST" {
			var b map[string]any
			json.NewDecoder(r.Body).Decode(&b)
			f.posts[p] = b
			for suffix, st := range f.refuse {
				if strings.HasSuffix(p, suffix) {
					w.WriteHeader(st)
					body := `{"code":"branch_rule","error":"trunk takes green landings only","next":{"say":"Wait for green.","cmd":"quarry status","ask":false}}`
					if b, ok := f.refuseBody[suffix]; ok {
						body = b
					}
					w.Write([]byte(body))
					return
				}
			}
			switch {
			case p == "/r/site/landing":
				w.Write([]byte(`{"id":"abcd1234","number":41}`))
			case strings.HasSuffix(p, "/auto"):
				w.Write([]byte(`{"armed":true,"changed":true,"say":"It lands itself when build and test are green."}`))
			default:
				w.Write([]byte(`{}`))
			}
			return
		}
		switch {
		case p == "/me":
			w.Write([]byte(`{"name":"alex","token":{"label":"mac","may":"m","mayNot":[]},"repos":[]}`))
		case p == "/r/alex/site/info":
			w.Write([]byte(`{"name":"site","address":"alex/site"}`))
		case p == "/r/site/landing":
			json.NewEncoder(w).Encode(map[string]any{"landings": f.open})
		case p == "/r/site/events/stream":
			w.Header().Set("Content-Type", "text/event-stream")
			w.Write([]byte("event: live\ndata: {}\n\n"))
			w.(http.Flusher).Flush()
			f.mu.Unlock()
			select {
			case <-f.streams:
				w.Write([]byte("id: 1\nevent: landing.accepted\ndata: {}\n\n"))
				w.(http.Flusher).Flush()
			case <-r.Context().Done():
			}
			f.mu.Lock()
		case strings.HasPrefix(p, "/r/site/landing/"):
			id := strings.TrimPrefix(p, "/r/site/landing/")
			if g, ok := f.byID[id]; ok {
				json.NewEncoder(w).Encode(g)
				return
			}
			if len(f.gets) == 0 {
				w.WriteHeader(404)
				return
			}
			g := f.gets[min(f.getN, len(f.gets)-1)]
			f.getN++
			json.NewEncoder(w).Encode(g)
		default:
			w.WriteHeader(404)
		}
	}))
	t.Cleanup(f.srv.Close)
	f.gets = []map[string]any{landGet("open", "ci-run", "build and test are running")}
	return f
}

func landGet(state, ci, say string) map[string]any {
	return map[string]any{
		"landing": map[string]any{"id": "abcd1234", "number": 41, "state": state, "ci": ci, "autoBy": "alex"},
		"checks":  []map[string]any{{"runId": "9153", "checkin": "cfe8ad17dab2aaaa", "status": "failed"}},
		"waiting": map[string]any{"on": "checks", "say": say, "who": "", "next": map[string]any{"say": "Nothing to do.", "cmd": "quarry status !41", "ask": false}},
	}
}

type landCall struct {
	args []string
	env  []string
}

type landRun struct {
	forge    *landForge
	calls    []landCall
	push     func() (string, error)
	timeline string
	local    string // zit landing ls --all
	getenv   map[string]string
}

func (l *landRun) env(t *testing.T, out, errw *bytes.Buffer) *Env {
	dir := t.TempDir()
	os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
	st := &fakeStore{}
	st.Put(strings.TrimPrefix(l.forge.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
	e := loginEnv(t, out, errw, st)
	e.Getwd = func() (string, error) { return dir, nil }
	e.Getenv = func(k string) string { return l.getenv[k] }
	e.WaitMax = 5 * time.Second
	e.Run = func(_ context.Context, _ string, env []string, args []string) (string, error) {
		l.calls = append(l.calls, landCall{args, env})
		switch args[0] {
		case "remote":
			return l.forge.srv.URL + "/r/alex/site\n", nil
		case "timeline":
			return l.timeline, nil
		case "landing":
			return l.local, nil
		case "push":
			if l.push != nil {
				return l.push()
			}
			return "", nil
		}
		return "", errors.New("unexpected zit " + args[0])
	}
	return e
}

func newLandRun(t *testing.T) *landRun {
	return &landRun{forge: newLandForge(t), timeline: "M cfe8ad17dab2  2026-11-21T16:02:30  parse-fix  fix the parser\n"}
}

func (l *landRun) land(t *testing.T, args ...string) (int, string, string) {
	t.Helper()
	var out, errw bytes.Buffer
	code := Land(context.Background(), args, l.env(t, &out, &errw))
	return code, out.String(), errw.String()
}

func (l *landRun) pushes() int {
	n := 0
	for _, c := range l.calls {
		if c.args[0] == "push" {
			n++
		}
	}
	return n
}

func TestLandOpensArmsAndTheTokenIsNeverGivenToZit(t *testing.T) {
	l := newLandRun(t)
	code, out, errw := l.land(t)
	if code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw)
	}
	open := l.forge.posts["/r/site/landing"]
	if open["branch"] != "parse-fix" || open["message"] != "fix the parser" || len(open) != 2 {
		t.Errorf("FAIL: open body %v", open)
	}
	if auto := l.forge.posts["/r/site/landing/abcd1234/auto"]; auto["on"] != true || auto["tip"] != "cfe8ad17dab2" || len(auto) != 2 {
		t.Errorf("FAIL: auto body %v", auto)
	}
	if l.pushes() != 1 {
		t.Errorf("FAIL: %d pushes", l.pushes())
	}
	for _, c := range l.calls {
		if strings.Contains(strings.Join(c.args, " "), apiTestToken) || strings.Contains(strings.Join(c.env, " "), apiTestToken) {
			t.Errorf("FAIL: the token reached zit: %v", c)
		}
	}
	for _, want := range []string{"!41", "lands itself when build and test are green", "build and test are running", "/r/alex/site/landing/41"} {
		if !strings.Contains(out, want) {
			t.Errorf("FAIL: output lacks %q:\n%s", want, out)
		}
	}
}

func TestLandUpdatesAnOpenLandingWithoutOpeningAnother(t *testing.T) {
	l := newLandRun(t)
	l.forge.open = []map[string]any{{"id": "abcd1234", "number": 41, "branch": "parse-fix", "target": "trunk", "author": "alex"}}
	code, _, errw := l.land(t)
	if code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw)
	}
	if _, ok := l.forge.posts["/r/site/landing"]; ok {
		t.Error("FAIL: a second landing was opened")
	}
	if _, ok := l.forge.posts["/r/site/landing/abcd1234/retarget"]; ok {
		t.Error("FAIL: retargeted with no --to")
	}
	if l.pushes() != 1 || l.forge.posts["/r/site/landing/abcd1234/auto"]["on"] != true {
		t.Errorf("FAIL: pushes %d, posts %v", l.pushes(), l.forge.posts)
	}
}

func TestLandNoArmLeavesItUnarmed(t *testing.T) {
	l := newLandRun(t)
	code, _, errw := l.land(t, "--no-arm")
	if code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw)
	}
	if _, ok := l.forge.posts["/r/site/landing/abcd1234/auto"]; ok {
		t.Error("FAIL: armed under --no-arm")
	}
}

func TestLandOnStacksAndRetargetsAnOpenOne(t *testing.T) {
	l := newLandRun(t)
	if code, _, errw := l.land(t, "--on", "!40"); code != 0 || l.forge.posts["/r/site/landing"]["target"] != "!40" {
		t.Errorf("FAIL: exit %d (%s) body %v", code, errw, l.forge.posts["/r/site/landing"])
	}
	l = newLandRun(t)
	l.forge.open = []map[string]any{{"id": "abcd1234", "number": 41, "branch": "parse-fix", "target": "trunk", "author": "alex"}}
	if code, _, errw := l.land(t, "--on", "!40"); code != 0 || l.forge.posts["/r/site/landing/abcd1234/retarget"]["to"] != "!40" {
		t.Errorf("FAIL: exit %d (%s) posts %v", code, errw, l.forge.posts)
	}
	if code, _, _ := l.land(t, "--on", "!40", "--to", "x"); code != 2 {
		t.Errorf("FAIL: --on with --to exit %d", code)
	}
}

func TestLandHardStopsAreTheForgesAndSurfaced(t *testing.T) {
	l := newLandRun(t)
	l.forge.refuse["/auto"] = 403
	code, out, errw := l.land(t)
	if code != 1 || !strings.Contains(errw, "green landings only") || !strings.Contains(errw, "quarry status") {
		t.Errorf("FAIL: exit %d err %q", code, errw)
	}
	if strings.Contains(out, "Armed") {
		t.Errorf("FAIL: claimed armed: %s", out)
	}
	for p, b := range l.forge.posts {
		if _, ok := b["override"]; ok {
			t.Errorf("FAIL: override sent to %s", p)
		}
	}

	l = newLandRun(t)
	l.push = func() (string, error) { return "server: trunk is protected\n", errors.New("exit 1") }
	code, _, errw = l.land(t)
	if code != 1 || !strings.Contains(errw, "protected") {
		t.Errorf("FAIL: push refusal exit %d err %q", code, errw)
	}
	if _, ok := l.forge.posts["/r/site/landing"]; ok {
		t.Error("FAIL: opened a landing after a refused push")
	}

	l = newLandRun(t)
	l.forge.refuse["/auto"] = 403
	_, out, _ = l.land(t, "--json")
	var m map[string]any
	if json.Unmarshal([]byte(out), &m) != nil || m["ok"] != false || m["code"] != "branch_rule" || m["number"] != float64(41) {
		t.Errorf("FAIL: refusal json %s", out)
	}
}

func TestLandRefusesALocalAccept(t *testing.T) {
	l := newLandRun(t)
	l.local = "9a8b7c6d5e4f accepted parse-fix -> trunk fix the parser\n"
	l.forge.byID["9a8b7c6d5e4f"] = landGet("open", "", "")
	code, _, errw := l.land(t)
	if code != 1 || !strings.Contains(errw, "zit undo") || l.pushes() != 0 {
		t.Errorf("FAIL: exit %d pushes %d err %q", code, l.pushes(), errw)
	}
	l = newLandRun(t)
	l.local = "9a8b7c6d5e4f accepted parse-fix -> trunk fix the parser\n"
	l.forge.byID["9a8b7c6d5e4f"] = landGet("accepted", "", "")
	if code, _, errw := l.land(t); code != 0 {
		t.Errorf("FAIL: a forge-accepted landing was refused: %d %s", code, errw)
	}
}

func TestLandMessageIsTheCommentEvenWhenItRepeatsTheBranchName(t *testing.T) {
	l := newLandRun(t)
	l.timeline = "  cfe8ad17dab2  2026-11-21T16:02:30  fix  fix the fix parser\n"
	if code, _, errw := l.land(t); code != 0 || l.forge.posts["/r/site/landing"]["message"] != "fix the fix parser" {
		t.Errorf("FAIL: exit %d body %v (%s)", code, l.forge.posts["/r/site/landing"], errw)
	}
}

func TestLandMessageRules(t *testing.T) {
	l := newLandRun(t)
	l.timeline = "M cfe8ad17dab2  2026-11-21T16:02:30  parse-fix  \n"
	code, _, errw := l.land(t)
	if code != 2 || l.pushes() != 0 || !strings.Contains(errw, "message") {
		t.Errorf("FAIL: exit %d pushes %d err %q", code, l.pushes(), errw)
	}
	if code, _, _ := l.land(t, "-m", "subject\nbody without a blank line"); code != 2 {
		t.Errorf("FAIL: bad shape exit %d", code)
	}
	if code, _, _ := l.land(t, "-m", "subject\n\nthe body"); code != 0 || l.forge.posts["/r/site/landing"]["message"] != "subject\n\nthe body" {
		t.Errorf("FAIL: exit %d body %v", code, l.forge.posts["/r/site/landing"])
	}

	// The editor only on a terminal.
	var out, errw2 bytes.Buffer
	e := l.env(t, &out, &errw2)
	e.IsTerminal = func(io.Writer) bool { return true }
	e.Edit = func(_ context.Context, path string) error {
		return os.WriteFile(path, []byte("edited subject\n\nedited body\n# dropped\n"), 0o600)
	}
	if code := Land(context.Background(), nil, e); code != 0 || l.forge.posts["/r/site/landing"]["message"] != "edited subject\n\nedited body" {
		t.Errorf("FAIL: editor exit %d body %v (%s)", code, l.forge.posts["/r/site/landing"], errw2.String())
	}
}

func TestLandWaitLanded(t *testing.T) {
	l := newLandRun(t)
	l.forge.gets = []map[string]any{landGet("open", "ci-run", "build is running"), landGet("accepted", "ci-pass", "")}
	l.forge.streams <- struct{}{}
	code, out, errw := l.land(t, "--wait")
	if code != 0 || !strings.Contains(out, "Landed !41") {
		t.Errorf("FAIL: exit %d out %q err %q", code, out, errw)
	}
}

func TestLandWaitCIFailed(t *testing.T) {
	l := newLandRun(t)
	l.forge.gets = []map[string]any{landGet("open", "ci-run", "build is running"), landGet("open", "ci-fail", "check test failed")}
	l.forge.streams <- struct{}{}
	code, out, _ := l.land(t, "--wait", "--json")
	var m map[string]any
	if json.Unmarshal([]byte(out), &m) != nil || code != 1 || m["outcome"] != "failed" || m["ok"] != false {
		t.Errorf("FAIL: exit %d %s", code, out)
	}
	l = newLandRun(t)
	l.forge.gets = []map[string]any{landGet("rejected", "", "")}
	if code, _, _ := l.land(t, "--wait"); code != 1 {
		t.Errorf("FAIL: refused landing exit %d", code)
	}
}

func TestLandWaitTimesOutWithThree(t *testing.T) {
	l := newLandRun(t)
	var out, errw bytes.Buffer
	e := l.env(t, &out, &errw)
	e.WaitMax = 150 * time.Millisecond
	code := Land(context.Background(), []string{"--wait", "--json"}, e)
	var m map[string]any
	if code != 3 || json.Unmarshal(out.Bytes(), &m) != nil || m["outcome"] != "timeout" || m["ok"] != false {
		t.Errorf("FAIL: exit %d %s", code, out.String())
	}
}

func TestLandJSONShape(t *testing.T) {
	l := newLandRun(t)
	code, out, errw := l.land(t, "--json")
	if code != 0 || strings.Count(strings.TrimSpace(out), "\n") != 0 {
		t.Fatalf("FAIL: exit %d out %q err %q", code, out, errw)
	}
	var m map[string]any
	if err := json.Unmarshal([]byte(out), &m); err != nil {
		t.Fatal(err)
	}
	for _, k := range []string{"ok", "host", "repo", "address", "branch", "target", "number", "id", "url", "pushed", "opened", "armed", "changed", "say", "waiting", "next"} {
		if _, ok := m[k]; !ok {
			t.Errorf("FAIL: json lacks %q: %s", k, out)
		}
	}
	if m["ok"] != true || m["opened"] != true || m["armed"] != true || m["number"] != float64(41) || m["branch"] != "parse-fix" {
		t.Errorf("FAIL: json %s", out)
	}
	if w, _ := m["waiting"].(map[string]any); w["on"] != "checks" {
		t.Errorf("FAIL: waiting %v", m["waiting"])
	}
}

// A zit on PATH: the real process seam, argv and environment recorded.
func TestLandRunsARealZitWithoutTheToken(t *testing.T) {
	l := newLandRun(t)
	bin, rec := t.TempDir(), filepath.Join(t.TempDir(), "calls.txt")
	script := "#!/bin/sh\n{ echo \"ARGV $*\"; env; } >> " + rec + "\ncase \"$1\" in\n" +
		"remote) echo '" + l.forge.srv.URL + "/r/alex/site';;\n" +
		"timeline) echo 'M cfe8ad17dab2  2026-11-21T16:02:30  parse-fix  fix the parser';;\n" +
		"esac\n"
	if err := os.WriteFile(filepath.Join(bin, "zit"), []byte(script), 0o755); err != nil {
		t.Fatal(err)
	}
	t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
	t.Setenv("ZIT_PASSWORD", apiTestToken)
	var out, errw bytes.Buffer
	e := l.env(t, &out, &errw)
	e.Run = nil
	if code := Land(context.Background(), nil, e); code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw.String())
	}
	b, _ := os.ReadFile(rec)
	if !strings.Contains(string(b), "ARGV push") {
		t.Errorf("FAIL: zit never pushed: %s", b)
	}
	if strings.Contains(string(b), apiTestToken) {
		t.Error("FAIL: the token reached zit's argv or environment")
	}
}

func TestLandRefusesWhenTheAPIHostIsNotTheRemotes(t *testing.T) {
	l := newLandRun(t)
	other := httptest.NewServer(http.NotFoundHandler())
	defer other.Close()
	l.getenv = map[string]string{"QUARRY_HOST": other.URL}
	var out, errw bytes.Buffer
	e := l.env(t, &out, &errw)
	e.Keys.(*fakeStore).Put(strings.TrimPrefix(other.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
	code := Land(context.Background(), []string{"--json"}, e)
	var m map[string]any
	if code != 1 || json.Unmarshal(out.Bytes(), &m) != nil || m["code"] != "other_forge" || m["next"] == nil {
		t.Errorf("FAIL: exit %d %s", code, out.String())
	}
	if l.pushes() != 0 || len(l.forge.posts) != 0 {
		t.Errorf("FAIL: pushed %d, posts %v", l.pushes(), l.forge.posts)
	}
}

func TestLandArmsForThePushedTip(t *testing.T) {
	l := newLandRun(t)
	if code, _, errw := l.land(t); code != 0 || l.forge.posts["/r/site/landing/abcd1234/auto"]["tip"] != "cfe8ad17dab2" {
		t.Errorf("FAIL: exit %d (%s) auto %v", code, errw, l.forge.posts["/r/site/landing/abcd1234/auto"])
	}
	l = newLandRun(t)
	l.forge.refuse["/auto"] = 400
	l.forge.refuseBody["/auto"] = `{"code":"invalid","error":"the branch has moved since cfe8ad17dab2: it is at 0123456789ab now"}`
	code, _, errw := l.land(t)
	if code != 1 || !strings.Contains(errw, "pushed to this branch after you") || !strings.Contains(errw, "quarry land") {
		t.Errorf("FAIL: exit %d err %q", code, errw)
	}
}

func TestLandNeverAdoptsSomeoneElsesLanding(t *testing.T) {
	l := newLandRun(t)
	l.forge.open = []map[string]any{{"id": "ffff0000", "number": 7, "branch": "parse-fix", "target": "trunk", "author": "sam"}}
	code, _, errw := l.land(t)
	if code != 1 || !strings.Contains(errw, "sam") || !strings.Contains(errw, "!7") || l.pushes() != 0 || len(l.forge.posts) != 0 {
		t.Errorf("FAIL: exit %d pushes %d posts %v err %q", code, l.pushes(), l.forge.posts, errw)
	}
	// Mine, among theirs, is the one used; a superseded one of mine is not.
	l = newLandRun(t)
	l.forge.open = []map[string]any{
		{"id": "ffff0000", "number": 7, "branch": "parse-fix", "target": "trunk", "author": "sam"},
		{"id": "abcd1234", "number": 41, "branch": "parse-fix", "target": "trunk", "author": "ALEX"},
	}
	if code, _, errw := l.land(t); code != 0 || l.forge.posts["/r/site/landing/abcd1234/auto"] == nil {
		t.Errorf("FAIL: exit %d posts %v (%s)", code, l.forge.posts, errw)
	}
	l = newLandRun(t)
	l.forge.open = []map[string]any{{"id": "ffff0000", "number": 7, "branch": "parse-fix", "target": "trunk", "author": "alex", "superseded_by": "abcd9999"}}
	if code, _, errw := l.land(t); code != 0 || l.forge.posts["/r/site/landing"] == nil {
		t.Errorf("FAIL: a superseded landing was adopted: exit %d (%s)", code, errw)
	}
}

func TestLandWaitEndsWhenTheArmLapses(t *testing.T) {
	l := newLandRun(t)
	lapsed := landGet("open", "ci-run", "the branch moved")
	lapsed["landing"].(map[string]any)["autoBy"] = ""
	lapsed["autoLapsed"] = "a check-in was pushed after the arm"
	l.forge.gets = []map[string]any{landGet("open", "ci-run", "running"), lapsed}
	l.forge.streams <- struct{}{}
	code, out, _ := l.land(t, "--wait", "--json")
	var m map[string]any
	if code != 1 || json.Unmarshal([]byte(out), &m) != nil || m["outcome"] != "unarmed" || strings.Contains(out, "stays armed") {
		t.Errorf("FAIL: exit %d %s", code, out)
	}
	// --wait on a landing nothing will land does not start.
	l = newLandRun(t)
	if code, _, _ := l.land(t, "--wait", "--no-arm"); code != 2 || l.pushes() != 0 {
		t.Errorf("FAIL: --wait --no-arm exit %d pushes %d", code, l.pushes())
	}
}

func TestLandWaitEndsOnACancelledRun(t *testing.T) {
	cancelled := landGet("open", "ci-run", "build was cancelled")
	cancelled["checks"] = []map[string]any{{"runId": "9154", "checkin": "cfe8ad17dab2aaaa", "status": "cancelled"}}
	l := newLandRun(t)
	l.forge.gets = []map[string]any{landGet("open", "ci-run", "running"), cancelled}
	l.forge.streams <- struct{}{}
	code, out, _ := l.land(t, "--wait", "--json")
	var m map[string]any
	if code != 1 || json.Unmarshal([]byte(out), &m) != nil || m["outcome"] != "stopped" {
		t.Errorf("FAIL: exit %d %s", code, out)
	}
	// A cancelled run beside one still going, or a stale verdict, keeps waiting.
	going := landGet("open", "ci-run", "re-running")
	going["checks"] = []map[string]any{{"runId": "9154", "checkin": "cfe8ad17dab2aaaa", "status": "cancelled"}, {"runId": "9155", "checkin": "cfe8ad17dab2aaaa", "status": "running"}}
	stale := landGet("open", "ci-run", "re-running")
	stale["checks"] = cancelled["checks"]
	stale["stale"] = true
	l = newLandRun(t)
	l.forge.gets = []map[string]any{going, stale, landGet("accepted", "ci-pass", "")}
	l.forge.streams <- struct{}{}
	l.forge.streams <- struct{}{}
	if code, out, _ := l.land(t, "--wait"); code != 0 || !strings.Contains(out, "Landed") {
		t.Errorf("FAIL: exit %d %s", code, out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLandWaitDoesNotEndOnAStaleOrOldFailure(t *testing.T) {
	stale := landGet("open", "ci-fail", "re-running")
	stale["stale"] = true
	old := landGet("open", "ci-fail", "failed on the old tip")
	old["checks"] = []map[string]any{{"runId": "1", "checkin": "pair:99999999aaaa:bbbb", "status": "failed"}}
	l := newLandRun(t)
	l.forge.gets = []map[string]any{stale, old, landGet("accepted", "ci-pass", "")}
	l.forge.streams <- struct{}{}
	l.forge.streams <- struct{}{}
	if code, out, _ := l.land(t, "--wait"); code != 0 || !strings.Contains(out, "Landed") {
		t.Errorf("FAIL: exit %d %s", code, out)
	}
}

func TestLandEditorNeedsStdinAndStdoutOnATerminal(t *testing.T) {
	l := newLandRun(t)
	l.timeline = "M cfe8ad17dab2  2026-11-21T16:02:30  parse-fix  \n"
	var out, errw bytes.Buffer
	e := l.env(t, &out, &errw)
	e.Stdin = strings.NewReader("")
	e.IsTerminal = func(w io.Writer) bool { return w == io.Writer(&out) }
	e.Edit = func(context.Context, string) error {
		t.Error("FAIL: the editor opened without a terminal on stdin")
		return nil
	}
	if code := Land(context.Background(), nil, e); code != 2 {
		t.Errorf("FAIL: exit %d", code)
	}
}