Skip to content
quarry Artifact [ea284a2a7b]
Login

Artifact [ea284a2a7b]

Artifact ea284a2a7b21d491494a739e25a995299b12f850df35e2476c5a7ae39d7a98ee:


package pickupclient

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/nextstep"
)

// quarry land (RFC 0033 step 9): push this branch, open its landing, arm
// it so it lands when CI is green, as the person this machine is. It
// composes landing.list, landing.open, landing.retarget, landing.auto
// and landing.get, and follows the event stream for --wait. It sends no
// override and never pushes a protected branch itself: the forge's
// refusals are surfaced with their next, not routed around.

const landHelp = `usage: quarry land [BRANCH] [--to TARGET | --on !N] [-m MESSAGE | --message-file FILE|-]
                   [--no-arm] [--wait] [--json]
       quarry land --stack [!TOP] [--wait] [--json]

Push with zit (its saved credential; the token is never on a command
line), open the branch's landing, or find your own that is already open,
and arm it for the tip you pushed: it lands itself, as you, when every required
check is green. Nothing here overrides a failing check or pushes to a
protected branch; where the forge refuses, its reason and next step are
printed.

  BRANCH            the branch (default: this checkout's)
  --to TARGET       land onto TARGET (default: the repository's main branch)
  --on !N           stack on landing N, to land after it; on a landing that
                    is already open it moves it onto N (--to BRANCH moves it
                    back). An arm the move dropped is set again for the
                    tip you pushed, unless --no-arm
  -m MESSAGE        the landing's message: a subject, a blank line, a body
  --message-file F  the message from a file, or - for standard input
  --no-arm          open the landing and leave it unarmed (not with --wait)
  --wait            follow it until it lands, its checks fail or are
                    cancelled, it is refused or its arm lapses (one
                    deadline of ten minutes)
  --stack [!TOP]    land a whole stack now, bottom-up, up to !TOP (default:
                    the stack this branch's own landing is the top of). It
                    pushes and opens nothing: it asks the forge to land the
                    stack and says, per rung, what landed, what is armed and
                    waiting on checks, and what stopped and why. With --wait
                    it follows until every rung has landed
  --json            one JSON object on stdout

When the landing is one rung of a stack, the stack is printed bottom-up
to the branch it finally lands on, and carried in --json as stack and
finalTarget.

With no message the branch's last check-in comment is used; on a terminal
with none, an editor opens ($VISUAL or $EDITOR); off a terminal, exit 2.
zit push sends the whole repository to its saved remote, not only this
branch; the forge's branch rules still decide what it takes. A landing
that is already open keeps its message. A landing of someone else's on
the same branch is never pushed to or armed.

Exit: 0 done (with --wait: landed), 1 refused, conflicting, failed or cancelled, 2 usage,
3 --wait ran out, or the forge has not yet taken in the push (code push_unseen; run land again), 4 not logged in. With --stack: 0 the stack landed or is
armed and waiting, 1 it stopped.

Example:
  quarry land --wait
`

const (
	landDefaultTarget = "trunk"
	landSlice         = 30 * time.Second
	landPushLimit     = 5 * time.Minute
)

// landSeenWait bounds how long land waits for the forge to list the
// check-in it just pushed before judging a conflict; landSeenPoll is the
// pause between reads.
var landSeenWait, landSeenPoll = 30 * time.Second, 2 * time.Second

type landArgs struct {
	branch, to, on, message, messageFile string
	hasMessage                           bool
	noArm, wait                          bool
	stack                                bool
	top                                  string
}

type landJSON struct {
	OK      bool   `json:"ok"`
	Code    string `json:"code,omitempty"`
	Error   string `json:"error,omitempty"`
	Host    string `json:"host"`
	Repo    string `json:"repo"`
	Address string `json:"address"`
	Branch  string `json:"branch"`
	Target  string `json:"target"`
	Number  int    `json:"number"`
	ID      string `json:"id"`
	URL     string `json:"url"`
	Pushed  bool   `json:"pushed"`
	Opened  bool   `json:"opened"`
	Armed   bool   `json:"armed"`
	Changed bool   `json:"changed"`
	Say     string `json:"say"`
	Outcome string `json:"outcome,omitempty"`
	// WasArmed says the landing was armed before a retarget moved it,
	// and Rearmed that it is armed again for the pushed tip.
	WasArmed bool `json:"wasArmed,omitempty"`
	Rearmed  bool `json:"rearmed,omitempty"`
	// Stack and FinalTarget are set when the landing is a rung of a
	// stack: every rung bottom-up, and the branch the stack lands on.
	Stack       []landRung     `json:"stack,omitempty"`
	FinalTarget string         `json:"finalTarget,omitempty"`
	Waiting     statusWaiting  `json:"waiting"`
	Next        *nextstep.Next `json:"next"`
}

// forgeRefusal is a non-2xx answer with the forge's own words.
type forgeRefusal struct {
	Status int
	apiRefusal
}

func (r *forgeRefusal) Error() string {
	if r.apiRefusal.Error != "" {
		return r.apiRefusal.Error
	}
	return fmt.Sprintf("the forge answered %d", r.Status)
}

// postJSON sends one command. A 401 is errTokenDead; any other non-2xx is
// a *forgeRefusal.
func (e *Env) postJSON(ctx context.Context, base *url.URL, token, path string, body, into any) error {
	u, err := apiTarget(base, apiPrefix+path)
	if err != nil {
		return err
	}
	b, err := json.Marshal(body)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, "POST", u.String(), bytes.NewReader(b))
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	resp, err := e.Client.Do(req)
	if err != nil {
		var ue *url.Error
		if errors.As(err, &ue) {
			err = ue.Err
		}
		return err
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(io.LimitReader(resp.Body, pickupBodyMax))
	if resp.StatusCode == http.StatusUnauthorized {
		return errTokenDead
	}
	if resp.StatusCode/100 != 2 {
		r := &forgeRefusal{Status: resp.StatusCode}
		_ = json.Unmarshal(raw, &r.apiRefusal)
		return r
	}
	if into == nil {
		return nil
	}
	if json.Unmarshal(raw, into) != nil {
		return errBadAnswer
	}
	return nil
}

// checkinLine is one line of `zit timeline -F oneline`.
type checkinLine struct{ Hash, Branch, Comment string }

func parseCheckinLine(out string) (checkinLine, bool) {
	rest := strings.TrimRight(strings.SplitN(out, "\n", 2)[0], "\r")
	rest = strings.TrimPrefix(strings.TrimPrefix(rest, "M "), "  ")
	var f [3]string
	for i := range f {
		rest = strings.TrimLeft(rest, " ")
		j := strings.IndexByte(rest, ' ')
		if j < 0 {
			j = len(rest)
		}
		f[i], rest = rest[:j], rest[j:]
	}
	if f[2] == "" {
		return checkinLine{}, false
	}
	return checkinLine{Hash: f[0], Branch: f[2], Comment: strings.TrimSpace(rest)}, true
}

// localAccept finds a landing of branch that this checkout records as
// accepted while the forge does not: zit landing accept's local merge.
func (e *Env) localAccept(ctx context.Context, root string, base *url.URL, token, repo, branch string) (string, bool) {
	out, err := e.Run(ctx, root, nil, []string{"landing", "ls", "--all"})
	if err != nil {
		return "", false
	}
	for _, l := range strings.Split(out, "\n") {
		f := strings.Fields(l)
		if len(f) < 3 || f[1] != "accepted" || f[2] != branch {
			continue
		}
		var got struct {
			Landing struct {
				State string `json:"state"`
			} `json:"landing"`
		}
		err := e.getJSON(ctx, base, token, "/r/"+repo+"/landing/"+url.PathEscape(f[0]), nil, &got)
		var se statusError
		if (errors.As(err, &se) && se == 404) || (err == nil && got.Landing.State != "accepted") {
			return f[0], true
		}
	}
	return "", false
}

func checkMessage(m string) string {
	m = strings.ReplaceAll(m, "\r\n", "\n")
	m = strings.TrimSpace(m)
	if m == "" {
		return ""
	}
	if lines := strings.SplitN(m, "\n", 3); len(lines) > 1 && strings.TrimSpace(lines[1]) != "" {
		return "a message is a subject, a blank line, then a body"
	}
	return ""
}

// edit opens the person's editor on a file holding seed and returns what
// they saved, without comment lines.
func (e *Env) edit(ctx context.Context, seed string) (string, error) {
	f, err := os.CreateTemp("", "quarry-land-*.txt")
	if err != nil {
		return "", err
	}
	defer os.Remove(f.Name())
	f.WriteString(seed + "\n\n# A subject, a blank line, then a body. Lines starting with # are dropped.\n")
	f.Close()
	if e.Edit != nil {
		err = e.Edit(ctx, f.Name())
	} else {
		ed := e.Getenv("VISUAL")
		if ed == "" {
			ed = e.Getenv("EDITOR")
		}
		if ed == "" {
			return "", errors.New("neither VISUAL nor EDITOR is set")
		}
		cmd := exec.CommandContext(ctx, "sh", "-c", ed+` "$1"`, "sh", f.Name())
		cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stderr, os.Stderr
		err = cmd.Run()
	}
	if err != nil {
		return "", err
	}
	b, err := os.ReadFile(f.Name())
	if err != nil {
		return "", err
	}
	var keep []string
	for _, l := range strings.Split(string(b), "\n") {
		if !strings.HasPrefix(l, "#") {
			keep = append(keep, l)
		}
	}
	return strings.TrimSpace(strings.Join(keep, "\n")), nil
}

func (e *Env) stdinIsTerminal() bool {
	var in io.Reader = os.Stdin
	if e.Stdin != nil {
		in = e.Stdin
	}
	w, ok := in.(io.Writer)
	return ok && e.isTerminal(w)
}

// Land is quarry land.
func Land(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("land"), asJSON, nil}
	usage := func(msg string) int {
		return v.refuse(2, "usage", msg, false, &nextstep.Next{Say: "See quarry land --help.", Cmd: "quarry land --help"})
	}
	var a landArgs
	for i := 0; i < len(args); i++ {
		s := args[i]
		val := func() (string, bool) {
			if i+1 < len(args) {
				i++
				return args[i], true
			}
			return "", false
		}
		var ok bool
		switch {
		case s == "-h" || s == "--help" || s == "-help":
			fmt.Fprint(e.Stdout, landHelp)
			return 0
		case s == "--no-arm":
			a.noArm = true
		case s == "--wait":
			a.wait = true
		case s == "--stack":
			a.stack = true
		case s == "--to":
			if a.to, ok = val(); !ok {
				return usage("--to needs a target")
			}
		case s == "--on":
			if a.on, ok = val(); !ok {
				return usage("--on needs a landing, like !41")
			}
		case s == "-m":
			a.hasMessage = true
			if a.message, ok = val(); !ok {
				return usage("-m needs a message")
			}
		case s == "--message-file":
			if a.messageFile, ok = val(); !ok {
				return usage("--message-file needs a file, or - for standard input")
			}
		case strings.HasPrefix(s, "-") || a.branch != "":
			return usage("usage: quarry land [BRANCH] [--to TARGET | --on !N] [-m MESSAGE] [--no-arm] [--wait] [--json] | --stack [!TOP] (quarry land --help)")
		default:
			a.branch = s
		}
	}
	if a.stack {
		if a.branch != "" {
			if n, err := strconv.Atoi(strings.TrimPrefix(a.branch, "!")); err != nil || n < 1 || !strings.HasPrefix(a.branch, "!") {
				return usage("--stack takes the top rung as a landing number like !41")
			}
			a.top, a.branch = a.branch, ""
		}
		if a.to != "" || a.on != "" || a.hasMessage || a.messageFile != "" || a.noArm {
			return usage("--stack lands what is already open; it takes no --to, --on, --no-arm or message, only --wait and --json")
		}
	}
	if a.on != "" {
		if n, err := strconv.Atoi(strings.TrimPrefix(a.on, "!")); err != nil || n < 1 || !strings.HasPrefix(a.on, "!") {
			return usage("--on takes a landing number like !41")
		}
	}
	if a.on != "" && a.to != "" {
		return usage("--to and --on both name the target; give one")
	}
	if a.wait && a.noArm {
		return usage("--wait follows a landing that lands itself, and --no-arm leaves it unarmed; give one")
	}
	if a.hasMessage && a.messageFile != "" {
		return usage("-m and --message-file both give the message; give one")
	}

	cwd, err := e.Getwd()
	if err != nil {
		return v.refuse(1, "refused", "this directory cannot be read: "+show(err.Error()), false, nil)
	}
	kind, root := checkoutKind(cwd)
	if kind != "zit" {
		return v.refuse(1, "no_checkout", "this directory is not a zit checkout", false,
			&nextstep.Next{Say: "Run this inside a checkout; quarry repo clone O/N makes one.", Cmd: "quarry repo clone O/N"})
	}
	remote := e.checkoutRemote(ctx, kind, root)
	segs, serr := remoteSegments(remote)
	if serr != nil {
		return v.refuse(1, "no_repo", "this checkout's remote is not a repository of the forge", false,
			&nextstep.Next{Say: "Run this inside a checkout; quarry repo clone O/N makes one.", Cmd: "quarry repo clone O/N"})
	}
	base, err := e.forgeFor("", remote)
	if err != nil {
		return v.refuse(2, "usage", show(err.Error()), false, nil)
	}
	v.base = base
	// zit pushes to the checkout's remote; the API calls and the token go
	// to base. They must be the same forge.
	if !nextstep.SameOrigin(remote, base) {
		return v.refuse(1, "other_forge", "this checkout's remote is on "+show(remote.Scheme+"://"+remote.Host)+", but the forge in use is "+show(base.Scheme+"://"+base.Host)+"; a push and a landing would go to different forges", false,
			&nextstep.Next{Say: "Unset " + envHostVar + " (and drop any --host) so this checkout's own forge is used.", Help: credsHelp})
	}
	rec, ok := e.token(base)
	if !ok {
		return v.noLogin(base)
	}
	fail := func(err error) int {
		var fr *forgeRefusal
		var se statusError
		switch {
		case errors.Is(err, errBadAnswer):
			return v.refuse(1, "bad_answer", "the forge answered with something this client cannot read", false,
				&nextstep.Next{Say: "Check that the forge and this client are the same version.", Cmd: "quarry doctor"})
		case errors.Is(err, errNoSuchRepo):
			return v.refuse(1, "no_repo", "the forge has no repository "+show(strings.Join(segs, "/")), false,
				&nextstep.Next{Say: "Check the checkout's remote."})
		case errors.Is(err, errTokenDead):
			return v.refuse(exitNoLogin, noLoginCode, "the forge does not take this machine's token", false,
				&nextstep.Next{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp})
		case errors.As(err, &fr):
			code := fr.Code
			if code == "" {
				code = "refused"
			}
			return v.refuse(1, code, show(fr.Error()), false, fr.Next)
		case errors.As(err, &se):
			return v.refuse(1, "refused", show(err.Error()), false, nil)
		}
		return v.refuse(1, "unreachable", "the forge could not be reached: "+show(err.Error()), false, nil)
	}
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	short, stop := context.WithTimeout(ctx, 60*time.Second)
	defer stop()

	ref, err := e.resolveRepo(short, base, rec.Token, segs, true)
	if err != nil {
		return fail(err)
	}
	repo := ref.Key

	if a.stack {
		return e.landStackNow(ctx, short, stackCtx{a: a, v: v, base: base, token: rec.Token, repo: repo, address: ref.Address,
			root: root, asJSON: asJSON, fail: fail})
	}

	// The branch and its last comment come from the checkout.
	tl := []string{"timeline", "-n", "1", "-F", "oneline"}
	if a.branch != "" {
		tl = append(tl, "-b", a.branch)
	} else {
		tl = append(tl, "-c")
	}
	tout, terr := e.Run(ctx, root, nil, tl)
	last, found := parseCheckinLine(tout)
	if terr != nil || !found {
		if a.branch != "" {
			return v.refuse(1, "no_branch", "this checkout has no branch "+show(a.branch), false,
				&nextstep.Next{Say: "Name a branch that has a check-in here.", Cmd: "zit branch"})
		}
		return v.refuse(1, "no_branch", "this checkout's branch could not be read", false, nil)
	}
	branch := last.Branch
	target := a.to
	if a.on != "" {
		target = a.on
	}
	// TODO: the repository's main branch, when repo.get exposes it.
	if branch == landDefaultTarget && (target == "" || target == landDefaultTarget) {
		return v.refuse(1, "on_trunk", show(branch)+" is the branch work lands on; there is nothing to propose from it", false,
			&nextstep.Next{Say: "Commit the work on a branch of its own, then land that.", Cmd: "zit commit --branch NAME"})
	}

	if id, bad := e.localAccept(short, root, base, rec.Token, repo, branch); bad {
		return v.refuse(1, "local_accept", show(branch)+" was merged in this checkout by zit landing accept ("+show(id)+
			"). That merge is local: the forge's checks and branch rules were not consulted, and a protected branch here only takes green landings, so a push of it is refused.", false,
			&nextstep.Next{Say: "Undo the local merge, then land through the forge.", Cmd: "zit undo"})
	}

	me, err := e.readMe(short, base, rec.Token)
	if err != nil {
		var se statusError
		if errors.As(err, &se) && (se == 401 || se == 403) {
			err = errTokenDead
		} else if !errors.As(err, &se) {
			var ne net.Error
			if !errors.As(err, &ne) && !errors.Is(err, context.DeadlineExceeded) {
				err = errBadAnswer
			}
		}
		return fail(err)
	}
	type landingRow struct {
		ID           string `json:"id"`
		Number       int    `json:"number"`
		Branch       string `json:"branch"`
		Target       string `json:"target"`
		Author       string `json:"author"`
		SupersededBy string `json:"superseded_by"`
	}
	var list struct {
		Landings []landingRow `json:"landings"`
	}
	if err := e.getJSON(short, base, rec.Token, "/r/"+repo+"/landing", url.Values{"state": {"open"}, "limit": {"200"}}, &list); err != nil {
		var se statusError
		if errors.As(err, &se) && se == 404 {
			err = errNoSuchRepo
		}
		return fail(err)
	}
	// Mine is the open, unsuperseded landing of this branch whose author is
	// the logged-in person. Someone else's is never pushed to or armed.
	// TODO: landing.list has no branch filter and no paging past 200; a
	// landing beyond the first page is not seen, and a new one is opened.
	var open, theirs *landingRow
	for i := range list.Landings {
		l := &list.Landings[i]
		switch {
		case l.Branch != branch || l.SupersededBy != "":
		case strings.EqualFold(l.Author, me.Name):
			if open == nil {
				open = l
			}
		case theirs == nil:
			theirs = l
		}
	}
	if open == nil && theirs != nil {
		return v.refuse(1, "not_yours", "!"+strconv.Itoa(theirs.Number)+" on "+show(branch)+" is "+show(theirs.Author)+"'s landing, not yours; pushing and arming it would be acting on their work", false,
			&nextstep.Next{Say: "Commit your work on a branch of your own and land that, or ask " + theirs.Author + " to land theirs.", Cmd: "zit commit --branch NAME"})
	}

	var message string
	if open == nil {
		switch {
		case a.hasMessage:
			message = a.message
		case a.messageFile == "-":
			if e.Stdin == nil {
				e.Stdin = os.Stdin
			}
			s, err := readCapped(e.Stdin, "the message")
			if err != nil {
				return usage(show(err.Error()))
			}
			message = s
		case a.messageFile != "":
			s, err := readFileCapped(a.messageFile)
			if err != nil {
				return usage(show(err.Error()))
			}
			message = s
		default:
			message = last.Comment
			if strings.TrimSpace(message) == "" {
				if !e.isTerminal(e.Stdout) || !e.stdinIsTerminal() {
					return usage("no message: the branch has no check-in comment to use, and this is not a terminal; give -m or --message-file")
				}
				m, err := e.edit(ctx, "")
				if err != nil {
					return v.refuse(1, "no_message", "the editor did not give a message: "+show(err.Error()), false, nil)
				}
				message = m
			}
		}
		if strings.TrimSpace(message) == "" {
			return usage("the message is empty")
		}
		if bad := checkMessage(message); bad != "" {
			return usage(bad)
		}
	}

	// Push, as the person: zit uses the checkout's saved credential, so
	// nothing of the token is on this command line or in its environment.
	pctx, pstop := context.WithTimeout(ctx, landPushLimit)
	pushOut, perr := e.Run(pctx, root, nil, []string{"push"})
	pstop()
	if perr != nil {
		why := strings.TrimSpace(scrubber(rec.Token)(tail(pushOut, 400)))
		if why == "" {
			why = perr.Error()
		}
		return v.refuse(1, "push_failed", "zit push did not take "+show(branch)+": "+show(why), false,
			&nextstep.Next{Say: "Fix what the forge said, then run this again. A protected branch takes a landing, not a push.", Cmd: "quarry land"})
	}

	res := landJSON{Host: base.Host, Repo: repo, Address: ref.Address, Branch: branch, Pushed: true}
	say := func(f string, x ...any) {
		if !asJSON {
			fmt.Fprintf(e.Stdout, f, x...)
		}
	}
	say("Pushed %s to %s.\n", show(branch), show(ref.Address))

	step, stopStep := context.WithTimeout(ctx, 60*time.Second)
	defer stopStep()
	if open == nil {
		body := map[string]any{"branch": branch, "message": message}
		if target != "" {
			body["target"] = target
		}
		var made struct {
			ID     string `json:"id"`
			Number int    `json:"number"`
		}
		if err := e.postJSON(step, base, rec.Token, "/r/"+repo+"/landing", body, &made); err != nil {
			return fail(err)
		}
		res.ID, res.Number, res.Opened, res.Target = made.ID, made.Number, true, target
	} else {
		res.ID, res.Number, res.Target = open.ID, open.Number, open.Target
		// --on !M names a landing, and the row's target is that landing's
		// branch: already stacked there is already where it was asked to go.
		moved := target != "" && target != open.Target
		if n, err := strconv.Atoi(strings.TrimPrefix(a.on, "!")); err == nil && a.on != "" {
			for _, l := range list.Landings {
				if l.Number == n && l.Branch == open.Target {
					moved = false
				}
			}
		}
		if moved {
			// A move can drop the arm, which was for the landing as it
			// stood: read it first so it can be set again.
			before, err := e.readLanding(step, base, rec.Token, repo, open.ID)
			if err != nil {
				return fail(err)
			}
			if err := e.postJSON(step, base, rec.Token, "/r/"+repo+"/landing/"+url.PathEscape(open.ID)+"/retarget", map[string]string{"to": target}, nil); err != nil {
				return fail(err)
			}
			res.Target = target
			if before.Landing.AutoBy != "" {
				after, err := e.readLanding(step, base, rec.Token, repo, open.ID)
				if err != nil {
					return fail(err)
				}
				res.WasArmed = after.Landing.AutoBy == ""
			}
		}
	}
	if res.Target == "" {
		res.Target = landDefaultTarget
	}
	name := "!" + strconv.Itoa(res.Number)
	res.URL = base.JoinPath("r", ref.Address, "landing", strconv.Itoa(res.Number)).String()
	if res.Opened {
		say("Opened %s  %s -> %s\n", name, show(branch), show(res.Target))
	} else {
		say("%s is already open  %s -> %s; the push is on it.\n", name, show(branch), show(res.Target))
	}

	// After the landing exists a refusal is reported with its facts.
	stuck := func(err error) int {
		var fr *forgeRefusal
		if !errors.As(err, &fr) || !asJSON {
			return fail(err)
		}
		res.Code, res.Error, res.Next = fr.Code, show(fr.Error()), fr.Next
		if res.Code == "" {
			res.Code = "refused"
		}
		v.print(res)
		return 1
	}
	// A landing that cannot merge is not armed: the fix is a push, and a
	// push lapses any arm anyway. Say so and stop, with the forge's step.
	// The conflict is judged only once the forge lists the check-in just
	// pushed: read before then, it is the old tip's conflict, which the
	// push may well have resolved. Unseen after landSeenWait, nothing is
	// armed: exit 3, and running land again picks it up.
	if !a.noArm {
		pre, err := e.readLanding(step, base, rec.Token, repo, res.ID)
		if err != nil {
			return stuck(err)
		}
		for waited := time.Duration(0); !pre.hasTip(last.Hash) && waited < landSeenWait; waited += landSeenPoll {
			if e.Sleep(step, landSeenPoll) != nil {
				break
			}
			if pre, err = e.readLanding(step, base, rec.Token, repo, res.ID); err != nil {
				return stuck(err)
			}
		}
		if !pre.hasTip(last.Hash) && pre.Tip != "" {
			// The forge has a tip for the branch and it is not this
			// check-in: someone pushed after you, the branch has another
			// leaf, or the checkout is not at the branch tip. Waiting will
			// not change that, so say it now.
			if res.WasArmed {
				say("NOT armed: the retarget dropped the arm.\n")
			}
			res.Code = "branch_moved"
			res.Error = "the forge's tip for " + show(branch) + " is " + show(shortTip(pre.Tip)) + ", not the check-in you pushed (" + show(shortTip(last.Hash)) + ")"
			res.Next = &nextstep.Next{Say: "Pull, look at what is on the branch, then land again.", Cmd: "zit pull"}
			say("Not armed: %s.\n", res.Error)
			say("  %s\n", res.URL)
			say("  next  %s\n", show(res.Next.Say))
			say("  run   %s\n", res.Next.Cmd)
			if asJSON {
				v.print(res)
			}
			return 1
		}
		if !pre.hasTip(last.Hash) {
			if res.WasArmed {
				say("NOT armed: the retarget dropped the arm.\n")
			}
			res.Code, res.Error = "push_unseen", "the push has not shown up on the forge yet"
			res.Next = &nextstep.Next{Say: "Give the forge a moment, then run land again; it arms once it has the push.", Cmd: "quarry land"}
			say("Not armed: the push has not shown up on the forge yet.\n")
			say("  %s\n", res.URL)
			say("  next  %s\n", show(res.Next.Say))
			say("  run   %s\n", res.Next.Cmd)
			if asJSON {
				v.print(res)
			}
			return 3
		}
		if pre.Waiting.On == "conflict" {
			res.Waiting, res.Next = pre.Waiting, pre.Waiting.Next
			res.Code, res.Error = "conflict", show(pre.Waiting.Say)
			say("Not armed: %s cannot merge yet.\n", name)
			say("  %s\n", res.URL)
			if pre.Waiting.Say != "" {
				say("  %s\n", show(pre.Waiting.Say))
			}
			if n := pre.Waiting.Next; n != nil {
				say("  next  %s\n", show(n.Say))
				if n.Cmd != "" && !strings.ContainsAny(n.Cmd, "\r\n") {
					say("  run   %s\n", show(n.Cmd))
				}
			}
			if asJSON {
				v.print(res)
			}
			return 1
		}
	}
	if !a.noArm {
		var armed struct {
			Armed   bool   `json:"armed"`
			Changed bool   `json:"changed"`
			Say     string `json:"say"`
		}
		if err := e.postJSON(step, base, rec.Token, "/r/"+repo+"/landing/"+url.PathEscape(res.ID)+"/auto", map[string]any{"on": true, "tip": last.Hash}, &armed); err != nil {
			if res.WasArmed {
				say("NOT armed: the retarget dropped the arm, and the forge refused to arm it again.\n")
			}
			var fr *forgeRefusal
			if errors.As(err, &fr) && strings.Contains(strings.ToLower(fr.apiRefusal.Error), "moved") {
				err = &forgeRefusal{Status: fr.Status, apiRefusal: apiRefusal{Code: "branch_moved",
					Error: "someone pushed to this branch after you; review and run quarry land again",
					Next:  &nextstep.Next{Say: "Look at what changed, then land again.", Cmd: "quarry land"}}}
			}
			return stuck(err)
		}
		res.Armed, res.Changed, res.Say = armed.Armed, armed.Changed, show(armed.Say)
		res.Rearmed = res.WasArmed && armed.Armed
		if res.Rearmed {
			say("Re-armed: the retarget had dropped the arm, and it is set again for the tip you pushed.\n")
		}
		if armed.Armed {
			say("Armed. %s\n", res.Say)
		} else {
			say("Not armed. %s\n", res.Say)
		}
	} else {
		if res.WasArmed {
			say("Not armed (--no-arm): the retarget dropped the arm it had.\n")
		}
		say("Not armed (--no-arm).\n")
	}
	say("  %s\n", res.URL)

	got, err := e.readLanding(step, base, rec.Token, repo, res.ID)
	if err != nil {
		return stuck(err)
	}
	res.Waiting = got.Waiting
	if rungs := got.Stack.rungs(); len(rungs) > 1 {
		res.Stack, res.FinalTarget = rungs, got.finalTarget()
		say("  stack  %s\n", show(stackLine(rungs, res.FinalTarget)))
	}
	show1 := func() {
		if got.Waiting.Say != "" {
			say("  %s\n", show(got.Waiting.Say))
		}
		if n := got.Waiting.Next; n != nil {
			say("  next  %s\n", show(n.Say))
			if n.Cmd != "" && !strings.ContainsAny(n.Cmd, "\r\n") {
				say("  run   %s\n", show(n.Cmd))
			}
		}
	}
	show1()
	res.Next = got.Waiting.Next

	code := 0
	if a.wait {
		limit := e.WaitMax
		if limit <= 0 {
			limit = apiWaitLimit
		}
		wctx, wstop := context.WithTimeout(ctx, limit)
		defer wstop()
		lastSay := got.Waiting.Say
		for {
			res.Outcome = landOutcome(got, last.Hash)
			if res.Outcome != "" {
				break
			}
			sctx, sstop := context.WithTimeout(wctx, landSlice)
			werr := e.apiWaitEvent(sctx, base, rec.Token, "/r/"+repo+"/events/stream")
			sstop()
			if wctx.Err() != nil {
				res.Outcome = "timeout"
				break
			}
			if werr != nil && sctx.Err() == nil {
				if e.Sleep(wctx, 3*time.Second) != nil {
					res.Outcome = "timeout"
					break
				}
			}
			rctx, rstop := context.WithTimeout(wctx, 30*time.Second)
			got, err = e.readLanding(rctx, base, rec.Token, repo, res.ID)
			rstop()
			if err != nil {
				if wctx.Err() != nil {
					res.Outcome = "timeout"
					break
				}
				return stuck(err)
			}
			if got.Waiting.Say != "" && got.Waiting.Say != lastSay {
				lastSay = got.Waiting.Say
				say("  %s\n", show(lastSay))
			}
		}
		res.Waiting, res.Next = got.Waiting, got.Waiting.Next
		switch res.Outcome {
		case "landed":
			say("Landed %s.\n", name)
		case "failed":
			code = 1
			say("Not landing %s: %s.\n", name, show(failWord(got)))
			show1()
		case "stopped":
			code = 1
			say("Not landing %s yet: a check run on your check-in was cancelled, so no answer is coming.\n", name)
			say("  next  Re-run it from the landing page, or push again; it stays armed.\n")
		case "unarmed":
			code = 1
			why := got.AutoLapsed
			if why == "" {
				why = got.Waiting.Say
			}
			res.Say = show(why)
			say("Not landing %s: it is no longer armed. %s\n", name, show(why))
			show1()
		case "timeout":
			code = 3
			say("Still waiting on %s after %s; it is armed.\n", name, limit)
			say("  next  quarry status %s --watch\n", name)
		}
	}
	res.OK = code == 0
	if asJSON {
		v.print(res)
	}
	return code
}

type landingState struct {
	Landing struct {
		ID     string `json:"id"`
		Number int    `json:"number"`
		Branch string `json:"branch"`
		Target string `json:"target"`
		State  string `json:"state"`
		CI     string `json:"ci"`
		AutoBy string `json:"autoBy"`
		Author string `json:"author"`
	} `json:"landing"`
	Stale        bool   `json:"stale"`
	Untested     bool   `json:"untested"`
	AutoLapsed   string `json:"autoLapsed"`
	StackArmedBy string `json:"stackArmedBy"`
	Checks       []struct {
		Checkin string `json:"checkin"`
		Pair    string `json:"pair"`
		Status  string `json:"status"`
	} `json:"checks"`
	Waiting statusWaiting `json:"waiting"`
	LandsOn string        `json:"landsOn"`
	Stack   landStrata    `json:"stack"`
	// Tip is the check-in the branch is at on the forge, so a caller can
	// tell whether a push it just made has been taken in.
	Tip string `json:"tip"`
}

// hasTip says the forge's tip for the branch is the check-in tip names
// (a full hash or a prefix of it).
func (g landingState) hasTip(tip string) bool {
	return tip != "" && strings.HasPrefix(g.Tip, tip)
}

func (e *Env) readLanding(ctx context.Context, base *url.URL, token, repo, id string) (landingState, error) {
	var g landingState
	err := e.getJSON(ctx, base, token, "/r/"+repo+"/landing/"+url.PathEscape(id), nil, &g)
	return g, err
}

// failedOn says a failed run is on tip: its check-in, or the branch tip a
// pair run (pair:BRANCHTIP:TARGETTIP) merged.
func (g landingState) failedOn(tip string) bool {
	for _, c := range g.Checks {
		switch c.Status {
		case "failed", "failure", "error":
			if tip != "" && (strings.Contains(c.Checkin, tip) || strings.Contains(c.Pair, tip)) {
				return true
			}
		}
	}
	return false
}

// stoppedOn says a run on tip was cancelled and nothing on tip is still
// going: no answer is coming without a re-run. With no tip it reads every
// run the landing lists (a stack's rungs, whose tips are not known here).
func (g landingState) stoppedOn(tip string) bool {
	stopped := false
	for _, c := range g.Checks {
		if tip != "" && !strings.Contains(c.Checkin, tip) && !strings.Contains(c.Pair, tip) {
			continue
		}
		switch c.Status {
		case "cancelled", "canceled":
			stopped = true
		case "completed", "succeeded", "success", "failed", "failure", "error", "errored":
		default:
			return false
		}
	}
	return stopped
}

// landOutcome is "landed", "failed", "stopped", "unarmed" or "" (still
// going). A failure ends the wait only when it is a run on the tip pushed
// and the verdict is not stale: the forge re-runs stale checks on an
// armed stack. A cancelled run on the tip, with nothing else going, is
// "stopped": waiting would only run out the clock.
func landOutcome(g landingState, tip string) string {
	switch {
	case g.Landing.State == "accepted":
		return "landed"
	case g.Landing.State != "" && g.Landing.State != "open":
		return "failed"
	case g.Landing.CI == "ci-fail" && !g.Stale && !g.Untested && g.failedOn(tip):
		return "failed"
	case g.Landing.CI != "ci-pass" && !g.Stale && g.stoppedOn(tip):
		return "stopped"
	case g.Landing.AutoBy == "" && g.StackArmedBy == "":
		return "unarmed"
	}
	return ""
}

func failWord(g landingState) string {
	if g.Landing.State != "" && g.Landing.State != "open" {
		return "it is " + g.Landing.State
	}
	return "a check failed"
}

// shortTip is a check-in hash cut to the twelve characters people read.
func shortTip(h string) string {
	if len(h) > 12 {
		return h[:12]
	}
	return h
}