Skip to content
quarry Artifact [3a360bb962]
Login

Artifact [3a360bb962]

Artifact 3a360bb962c77b270a9b2cfcb8af9389275cbcc4d560d7312432811d494221ef:


package pickupclient

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

// statusForge answers the ops quarry status composes. Landings are
// served exactly as set; the client may not add words to them.
type statusForge struct {
	srv      *httptest.Server
	mu       sync.Mutex
	landings []map[string]any // landing.get answers, with "author"
	rows     []map[string]any
	count    *int // /me/inbox/count, when set
	paths    []string
	methods  map[string]bool
	noInfo   bool // repo.get is missing: every /info is a 404
	garbage  bool // landing.list answers a body that is not JSON
}

func newStatusForge(t *testing.T) *statusForge {
	f := &statusForge{methods: map[string]bool{}}
	f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f.mu.Lock()
		defer f.mu.Unlock()
		f.paths = append(f.paths, r.URL.RequestURI())
		f.methods[r.Method] = true
		if r.Header.Get("Authorization") != "Bearer "+apiTestToken {
			w.WriteHeader(401)
			return
		}
		p := strings.TrimPrefix(r.URL.Path, "/api/v1")
		switch {
		case p == "/me":
			w.Write([]byte(`{"name":"alex","token":{"label":"mac","may":"m","mayNot":[]},"repos":[]}`))
		case f.noInfo && strings.HasSuffix(p, "/info"):
			w.WriteHeader(404)
		case f.garbage && strings.HasSuffix(p, "/landing"):
			w.Write([]byte("<html>not json"))
		case p == "/r/gone/landing":
			w.WriteHeader(404)
		case p == "/r/alex/site/info" || p == "/r/site/info":
			w.Write([]byte(`{"name":"site","handle":"site","namespace":"alex","address":"alex/site"}`))
		case p == "/r/alex/gone/info" || p == "/r/gone/info":
			w.WriteHeader(404)
		case p == "/r/site/landing", p == "/r/alex/site/landing":
			var ls []map[string]any
			for _, l := range f.landings {
				lv := l["landing"].(map[string]any)
				if lv["state"] != "open" {
					continue
				}
				ls = append(ls, map[string]any{"id": lv["id"], "number": lv["number"], "branch": lv["branch"], "author": lv["author"]})
			}
			json.NewEncoder(w).Encode(map[string]any{"landings": ls})
		case strings.HasPrefix(p, "/r/site/landing/"), strings.HasPrefix(p, "/r/alex/site/landing/"):
			id := p[strings.LastIndex(p, "/landing/")+len("/landing/"):]
			for _, l := range f.landings {
				lv := l["landing"].(map[string]any)
				if lv["id"] == id || fmt.Sprint(lv["number"]) == id {
					json.NewEncoder(w).Encode(l)
					return
				}
			}
			w.WriteHeader(404)
		case strings.HasSuffix(p, "/log"):
			w.Write([]byte(`{"runId":"9153","status":"failed","steps":[{"step":"s-ok","failed":false,"text":"fine"},{"step":"s-bad","failed":true,"text":"line one\nline two"}]}`))
		case p == "/me/inbox":
			json.NewEncoder(w).Encode(map[string]any{"rows": f.rows})
		case p == "/me/inbox/count" && f.count != nil:
			json.NewEncoder(w).Encode(map[string]any{"unread": *f.count})
		default:
			w.WriteHeader(404)
		}
	}))
	t.Cleanup(f.srv.Close)
	return f
}

func landingAnswer(id string, number int, author, on, say, nextSay, cmd, ci string) map[string]any {
	return map[string]any{
		"landing": map[string]any{"id": id, "number": number, "branch": "br-" + id, "target": "trunk",
			"title": "t", "state": "open", "ci": ci, "author": author},
		"checks":  []map[string]any{{"runId": "9153", "pipeline": "test"}},
		"waiting": map[string]any{"on": on, "say": say, "who": "", "next": map[string]any{"say": nextSay, "cmd": cmd, "ask": false}},
	}
}

func (f *statusForge) run(t *testing.T, args ...string) (int, string, string) {
	t.Helper()
	return f.runAt(t, "/r/alex/site", args...)
}

func (f *statusForge) runAt(t *testing.T, remotePath string, args ...string) (int, string, string) {
	t.Helper()
	dir := t.TempDir()
	os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
	st := &fakeStore{}
	st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
	var out, errw bytes.Buffer
	e := loginEnv(t, &out, &errw, st)
	e.Getwd = func() (string, error) { return dir, nil }
	e.Run = func(context.Context, string, []string, []string) (string, error) {
		return f.srv.URL + remotePath + "\n", nil
	}
	code := Status(context.Background(), args, e)
	return code, out.String(), errw.String()
}

func (f *statusForge) object(t *testing.T, args ...string) map[string]any {
	t.Helper()
	code, out, errw := f.run(t, append(args, "--json")...)
	if code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw)
	}
	var m map[string]any
	if err := json.Unmarshal([]byte(out), &m); err != nil || strings.Count(strings.TrimSpace(out), "\n") != 0 {
		t.Fatalf("FAIL: stdout is not exactly one object: %q", out)
	}
	return m
}

var allWaits = []string{"checks", "conflict", "stale", "never_ran", "stack", "protection", "nothing"}

func TestStatusPrintsTheServersWordsForEachState(t *testing.T) {
	f := newStatusForge(t)
	for i, on := range allWaits {
		f.landings = append(f.landings, landingAnswer(fmt.Sprintf("id%d", i), 40+i, "alex", on,
			"SAY-"+on, "NEXT-"+on, "run-"+on, ""))
	}
	code, out, errw := f.run(t)
	if code != 0 {
		t.Fatalf("FAIL: exit %d (%s)", code, errw)
	}
	for _, on := range allWaits {
		for _, w := range []string{"SAY-" + on, "NEXT-" + on, "run-" + on} {
			if !strings.Contains(out, w) {
				t.Errorf("FAIL: the forge's %q is not printed", w)
			}
		}
	}
	for i := range allWaits {
		if !strings.Contains(out, fmt.Sprintf("!%d", 40+i)) {
			t.Errorf("FAIL: landing %d is not named", 40+i)
		}
	}
	if strings.Contains(out, apiTestToken) {
		t.Errorf("FAIL: the token was printed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestStatusListsOnlyMyLandingsAndASelectorPicksAnyone(t *testing.T) {
	f := newStatusForge(t)
	f.landings = []map[string]any{
		landingAnswer("a", 41, "alex", "nothing", "SAY-a", "n", "", ""),
		landingAnswer("b", 42, "sam", "checks", "SAY-b", "n", "", ""),
	}
	m := f.object(t)
	ls := m["landings"].([]any)
	if len(ls) != 1 || ls[0].(map[string]any)["number"].(float64) != 41 {
		t.Errorf("FAIL: landings %v", ls)
	}
	m = f.object(t, "!42")
	ls = m["landings"].([]any)
	if len(ls) != 1 || ls[0].(map[string]any)["branch"] != "br-b" {
		t.Errorf("FAIL: !42 gave %v", ls)
	}
	m = f.object(t, "br-a")
	if ls = m["landings"].([]any); len(ls) != 1 {
		t.Errorf("FAIL: a branch selector gave %v", ls)
	}
	if code, _, _ := f.run(t, "!99"); code != 1 {
		t.Errorf("FAIL: an unknown landing exits %d, want 1", code)
	}
}

func TestStatusJSONShape(t *testing.T) {
	f := newStatusForge(t)
	f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "quarry status !41 --log", "ci-fail")}
	m := f.object(t)
	for _, k := range []string{"ok", "host", "repo", "account", "landings", "inbox", "next"} {
		if _, ok := m[k]; !ok {
			t.Errorf("FAIL: no key %q in %v", k, m)
		}
	}
	if m["ok"] != true || m["repo"] != "site" || m["address"] != "alex/site" || m["account"] != "alex" {
		t.Errorf("FAIL: %v", m)
	}
	l := m["landings"].([]any)[0].(map[string]any)
	for _, k := range []string{"number", "id", "branch", "target", "title", "state", "ci", "waiting"} {
		if _, ok := l[k]; !ok {
			t.Errorf("FAIL: landing has no key %q", k)
		}
	}
	w := l["waiting"].(map[string]any)
	for _, k := range []string{"on", "say", "who", "next"} {
		if _, ok := w[k]; !ok {
			t.Errorf("FAIL: waiting has no key %q", k)
		}
	}
	if n := m["next"].(map[string]any); n["say"] != "NEXT" {
		t.Errorf("FAIL: top next is %v, want the first landing's", n)
	}
	in := m["inbox"].(map[string]any)
	if _, ok := in["unread"]; !ok || in["rows"] == nil {
		t.Errorf("FAIL: inbox %v", in)
	}
}

func inboxRow(id, repo string, read bool) map[string]any {
	return map[string]any{"id": id, "reason": "mention", "repo": repo, "from": "sam", "summary": "S-" + id,
		"link": "/r/" + repo + "/x", "at": "t", "read": read}
}

func TestStatusEmptyInboxAndNothingWaiting(t *testing.T) {
	f := newStatusForge(t)
	m := f.object(t)
	in := m["inbox"].(map[string]any)
	if rows := in["rows"].([]any); len(rows) != 0 || in["unread"].(float64) != 0 {
		t.Errorf("FAIL: inbox %v", in)
	}
	if ls := m["landings"].([]any); ls == nil || len(ls) != 0 {
		t.Errorf("FAIL: landings %v", m["landings"])
	}
	f.rows = []map[string]any{inboxRow("r1", "alex/site", true)}
	code, out, _ := f.run(t)
	if code != 0 || strings.Contains(out, "S-r1") {
		t.Errorf("FAIL: exit %d; a read row was listed: %q", code, out)
	}
	if m = f.object(t); m["inbox"].(map[string]any)["unread"].(float64) != 0 {
		t.Errorf("FAIL: a read row counted as unread")
	}
}

func TestStatusInboxIsCappedAtFiveThisRepositorysFirstAndNeverMarksRead(t *testing.T) {
	f := newStatusForge(t)
	for i := 0; i < 4; i++ {
		f.rows = append(f.rows, inboxRow(fmt.Sprintf("o%d", i), "sam/other", false))
	}
	f.rows = append(f.rows, inboxRow("done", "alex/site", true))
	for i := 0; i < 3; i++ {
		f.rows = append(f.rows, inboxRow(fmt.Sprintf("h%d", i), "alex/site", false))
	}
	m := f.object(t)
	in := m["inbox"].(map[string]any)
	rows := in["rows"].([]any)
	if len(rows) != 5 || in["unread"].(float64) != 7 {
		t.Fatalf("FAIL: %d rows, unread %v", len(rows), in["unread"])
	}
	for i := 0; i < 3; i++ {
		if r := rows[i].(map[string]any); r["repo"] != "alex/site" {
			t.Errorf("FAIL: row %d is %v, this repository's come first", i, r["repo"])
		}
	}
	for _, r := range rows {
		if r.(map[string]any)["id"] == "done" {
			t.Errorf("FAIL: a read row is listed")
		}
	}
	_, out, _ := f.run(t)
	if strings.Count(out, "S-") != 5 || !strings.Contains(out, "/r/alex/site/x") {
		t.Errorf("FAIL: text lists %d rows: %q", strings.Count(out, "S-"), out)
	}
	for _, p := range f.paths {
		if strings.Contains(p, "mark") {
			t.Errorf("FAIL: %s was called", p)
		}
	}
	if len(f.methods) != 1 || !f.methods["GET"] {
		t.Errorf("FAIL: methods used %v, want GET only", f.methods)
	}
}

func TestStatusLogPrintsFailedStepsOnly(t *testing.T) {
	f := newStatusForge(t)
	f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "", "ci-fail")}
	_, out, _ := f.run(t)
	if strings.Contains(out, "line one") {
		t.Errorf("FAIL: a log without --log")
	}
	m := f.object(t, "--log")
	logs := m["landings"].([]any)[0].(map[string]any)["logs"].([]any)
	if len(logs) != 1 || logs[0].(map[string]any)["step"] != "s-bad" || logs[0].(map[string]any)["runId"] != "9153" {
		t.Errorf("FAIL: logs %v", logs)
	}
	_, out, _ = f.run(t, "--log")
	if !strings.Contains(out, "line two") || strings.Contains(out, "fine") {
		t.Errorf("FAIL: log text %q", out)
	}
	if !strings.Contains(strings.Join(f.paths, " "), "tail=20") {
		t.Errorf("FAIL: the log was not asked for a tail")
	}
}

func TestStatusErrors(t *testing.T) {
	f := newStatusForge(t)
	if code, _, _ := f.run(t, "--nope"); code != 2 {
		t.Errorf("FAIL: usage exits %d", code)
	}
	if code, _, _ := f.run(t, "a", "b"); code != 2 {
		t.Errorf("FAIL: two selectors exit %d", code)
	}
	// No login: exit 4 and nothing sent.
	dir := t.TempDir()
	os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
	var out, errw bytes.Buffer
	e := loginEnv(t, &out, &errw, &fakeStore{})
	e.Getwd = func() (string, error) { return dir, nil }
	e.Run = func(context.Context, string, []string, []string) (string, error) {
		return f.srv.URL + "/r/alex/site\n", nil
	}
	f.paths = nil
	if code := Status(context.Background(), nil, e); code != 4 || len(f.paths) != 0 {
		t.Errorf("FAIL: no login exits %d with %d calls", code, len(f.paths))
	}
	// Not a checkout: refused before any call.
	e.Getwd = func() (string, error) { return t.TempDir(), nil }
	if code := Status(context.Background(), nil, e); code != 1 || len(f.paths) != 0 {
		t.Errorf("FAIL: no checkout exits %d", code)
	}
}

// Every non-answer is exit 1 with ok:false under --json, never a 0.
func TestStatusEveryRefusalExitsNonZeroAndJSONSaysNotOK(t *testing.T) {
	f := newStatusForge(t)
	f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "", "ci-fail")}
	refuse := func(name string, env func(*Env), want int, args ...string) {
		t.Helper()
		for _, asJSON := range []bool{false, true} {
			dir := t.TempDir()
			os.WriteFile(filepath.Join(dir, ".zit-checkout"), nil, 0o600)
			st := &fakeStore{}
			st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
			var out, errw bytes.Buffer
			e := loginEnv(t, &out, &errw, st)
			e.Getwd = func() (string, error) { return dir, nil }
			e.Run = func(context.Context, string, []string, []string) (string, error) {
				return f.srv.URL + "/r/alex/site\n", nil
			}
			env(e)
			a := args
			if asJSON {
				a = append(append([]string{}, args...), "--json")
			}
			if code := Status(context.Background(), a, e); code != want {
				t.Errorf("FAIL: %s json=%v: exit %d, want %d", name, asJSON, code, want)
			}
			if asJSON {
				var m map[string]any
				if err := json.Unmarshal(out.Bytes(), &m); err != nil || m["ok"] != false || m["code"] == nil {
					t.Errorf("FAIL: %s: stdout %q is not one ok:false object", name, out.String())
				}
			}
		}
	}
	refuse("outside a checkout", func(e *Env) { e.Getwd = func() (string, error) { return t.TempDir(), nil } }, 1)
	refuse("remote is not a forge repository", func(e *Env) {
		e.Run = func(context.Context, string, []string, []string) (string, error) {
			return f.srv.URL + "/elsewhere\n", nil
		}
	}, 1)
	refuse("unknown landing", func(*Env) {}, 1, "!99")
	refuse("bad token", func(e *Env) {
		st := &fakeStore{}
		st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: "wrong", Account: "alex"})
		e.Keys = st
	}, 4)
	refuse("no login", func(e *Env) { e.Keys = &fakeStore{} }, 4)
	refuse("usage", func(*Env) {}, 2, "--nope")
	refuse("forge unreachable", func(e *Env) {
		st := &fakeStore{}
		st.Put("127.0.0.1:1", Record{Token: apiTestToken, Account: "alex"})
		e.Keys = st
		e.Run = func(context.Context, string, []string, []string) (string, error) {
			return "http://127.0.0.1:1/r/alex/site\n", nil
		}
	}, 1)
}

func TestStatusAcceptsFlatAndNamespacedRemotesAndUsesTheKey(t *testing.T) {
	f := newStatusForge(t)
	f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "", "")}
	for _, remote := range []string{"/r/site", "/r/alex/site"} {
		f.paths = nil
		code, out, errw := f.runAt(t, remote, "--json")
		if code != 0 {
			t.Fatalf("FAIL: %s exits %d (%s)", remote, code, errw)
		}
		var m map[string]any
		json.Unmarshal([]byte(out), &m)
		if m["repo"] != "site" || m["address"] != "alex/site" {
			t.Errorf("FAIL: %s gave repo %v address %v", remote, m["repo"], m["address"])
		}
		for _, p := range f.paths {
			if strings.Contains(p, "/r/alex/site/landing") || strings.Contains(p, "/r/alex/site/ci") {
				t.Errorf("FAIL: %s: a call used the address, not the key: %s", remote, p)
			}
		}
		_, text, _ := f.runAt(t, remote)
		if !strings.HasPrefix(text, "alex/site on ") {
			t.Errorf("FAIL: %s: the address is not shown: %q", remote, text)
		}
	}
}

func TestStatusUnknownAndHostileRemotes(t *testing.T) {
	f := newStatusForge(t)
	for _, remote := range []string{"/r/gone", "/r/alex/gone"} {
		if code, _, _ := f.runAt(t, remote); code != 1 {
			t.Errorf("FAIL: %s exits %d, want 1", remote, code)
		}
		m := map[string]any{}
		_, out, _ := f.runAt(t, remote, "--json")
		json.Unmarshal([]byte(out), &m)
		if m["ok"] != false || m["code"] != "no_repo" {
			t.Errorf("FAIL: %s: %s", remote, out)
		}
	}
	f.paths = nil
	for _, remote := range []string{"/r/a%2Fb", "/r/alex/s%20x", "/r/alex/site%3Fx=1", "/r/a%2e%2e/site", "/r/alex/.site", "/r/alex/site/more", "/r/", "/other"} {
		if code, _, _ := f.runAt(t, remote); code != 1 {
			t.Errorf("FAIL: %s exits %d, want 1", remote, code)
		}
	}
	for _, p := range f.paths {
		if strings.Contains(p, "/info") || strings.Contains(p, "landing") {
			t.Errorf("FAIL: a hostile remote reached the forge: %s", p)
		}
	}
}

// A forge that does not say what a landing waits on shows the landing's
// own fields, and invents no sentence.
func TestStatusWithoutWaitingShowsTheForgesFieldsOnly(t *testing.T) {
	f := newStatusForge(t)
	l := landingAnswer("a", 41, "alex", "", "", "", "", "ci-fail")
	delete(l, "waiting")
	f.landings = []map[string]any{l}
	m := f.object(t)
	got := m["landings"].([]any)[0].(map[string]any)
	if w := got["waiting"].(map[string]any); w["say"] != "" || w["next"] != nil {
		t.Errorf("FAIL: a sentence was made up: %v", w)
	}
	facts := got["facts"].([]any)
	if len(facts) == 0 || !strings.Contains(fmt.Sprint(facts), "ci-fail") {
		t.Errorf("FAIL: facts %v", facts)
	}
	if code, out, _ := f.run(t); code != 0 || !strings.Contains(out, "ci-fail") {
		t.Errorf("FAIL: exit %d, %q", code, out)
	}
}

func TestStatusHidesSettledRowsAndCountsOnlyUnsettledUnread(t *testing.T) {
	f := newStatusForge(t)
	for i := 0; i < 3; i++ {
		r := inboxRow(fmt.Sprintf("s%d", i), "alex/site", false)
		r["settled"] = true
		f.rows = append(f.rows, r)
	}
	for i := 0; i < 7; i++ {
		r := inboxRow(fmt.Sprintf("u%d", i), "sam/other", false)
		r["settled"] = false
		f.rows = append(f.rows, r)
	}
	m := f.object(t)
	in := m["inbox"].(map[string]any)
	rows := in["rows"].([]any)
	if len(rows) != 5 || in["unread"].(float64) != 7 {
		t.Fatalf("FAIL: %d rows, unread %v", len(rows), in["unread"])
	}
	for _, r := range rows {
		if id := r.(map[string]any)["id"].(string); strings.HasPrefix(id, "s") {
			t.Errorf("FAIL: settled row %s is listed", id)
		}
	}
	_, out, _ := f.run(t)
	if strings.Contains(out, "S-s0") {
		t.Errorf("FAIL: a settled row is printed")
	}
}

// The unread number is the forge's count over the whole inbox, the
// badge's number, not the rows on the newest page.
func TestStatusUnreadIsTheForgesCount(t *testing.T) {
	f := newStatusForge(t)
	for i := 0; i < 7; i++ {
		f.rows = append(f.rows, inboxRow(fmt.Sprintf("u%d", i), "sam/other", false))
	}
	n := 28
	f.count = &n
	in := f.object(t)["inbox"].(map[string]any)
	if len(in["rows"].([]any)) != 5 || in["unread"].(float64) != 28 {
		t.Errorf("FAIL: %v rows, unread %v", len(in["rows"].([]any)), in["unread"])
	}
	// A count below the rows in hand is not believed.
	n = 2
	if in := f.object(t)["inbox"].(map[string]any); in["unread"].(float64) != 7 {
		t.Errorf("FAIL: unread %v", in["unread"])
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An older forge has no settled field: every unread row shows, as before.
func TestStatusAgainstAForgeWithoutSettledShowsEveryUnreadRow(t *testing.T) {
	f := newStatusForge(t)
	for i := 0; i < 3; i++ {
		f.rows = append(f.rows, inboxRow(fmt.Sprintf("o%d", i), "alex/site", false))
	}
	m := f.object(t)
	if in := m["inbox"].(map[string]any); len(in["rows"].([]any)) != 3 || in["unread"].(float64) != 3 {
		t.Errorf("FAIL: %v", in)
	}
}

// A flat remote on a forge with no /info shows the key as the address;
// a repository the forge does not know is refused by the first real call.
func TestStatusFlatRemoteWithoutInfoFallsBackToTheKey(t *testing.T) {
	f := newStatusForge(t)
	f.noInfo = true
	f.landings = []map[string]any{landingAnswer("a", 41, "alex", "checks", "SAY", "NEXT", "", "")}
	m := func() map[string]any {
		code, out, errw := f.runAt(t, "/r/site", "--json")
		if code != 0 {
			t.Fatalf("FAIL: exit %d (%s)", code, errw)
		}
		var o map[string]any
		json.Unmarshal([]byte(out), &o)
		return o
	}()
	if m["repo"] != "site" || m["address"] != "site" {
		t.Errorf("FAIL: repo %v address %v", m["repo"], m["address"])
	}
	code, out, _ := f.runAt(t, "/r/gone", "--json")
	var o map[string]any
	json.Unmarshal([]byte(out), &o)
	if code != 1 || o["ok"] != false || o["code"] != "no_repo" {
		t.Errorf("FAIL: an unknown repository exits %d: %s", code, out)
	}
}

func TestStatusMalformedAnswerIsABadAnswerNotUnreachable(t *testing.T) {
	f := newStatusForge(t)
	f.garbage = true
	code, out, _ := f.runAt(t, "/r/alex/site", "--json")
	var o map[string]any
	json.Unmarshal([]byte(out), &o)
	if code != 1 || o["ok"] != false || o["code"] != "bad_answer" {
		t.Errorf("FAIL: exit %d: %s", code, out)
	}
}

// A selector naming a landing that settled answers for it, exit 0; only
// a number naming nothing is a refusal.
func TestStatusSelectorAnswersForASettledLanding(t *testing.T) {
	f := newStatusForge(t)
	done := landingAnswer("z", 87, "alex", "nothing", "", "", "", "")
	lv := done["landing"].(map[string]any)
	lv["state"], lv["updated"], lv["settled_by"] = "accepted", "2026-11-22T10:00:00.123", "reply1"
	done["landedTip"] = "61e6e2cab2463c49903efad7b586699a3a9b3633fe18e86a1c153d215671ad4b"
	f.landings = []map[string]any{done}
	m := f.object(t, "!87")
	ls := m["landings"].([]any)
	if len(ls) != 1 {
		t.Fatalf("FAIL: !87 gave %v", ls)
	}
	l := ls[0].(map[string]any)
	if l["state"] != "accepted" || l["settled_by"] != "reply1" || l["updated"] == "" || l["landedTip"] != done["landedTip"] {
		t.Errorf("FAIL: settled landing %v", l)
	}
	code, out, _ := f.run(t, "!87")
	// The text names the check-in it landed as, and not the reply hash.
	if code != 0 || !strings.Contains(out, "61e6e2cab246") || strings.Contains(out, "reply1") {
		t.Errorf("FAIL: exit %d out %q", code, out)
	}
	code, out, _ = f.run(t, "!99", "--json")
	if code != 1 || !strings.Contains(out, `"no_landing"`) {
		t.Errorf("FAIL: unknown number exit %d out %q", code, out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// stacked adds landing.get's `stack` to answers that are rungs of one
// strata, bottom-up, and who armed each.
func stacked(ls []map[string]any, armed map[string]string) {
	var segs []map[string]any
	for i, l := range ls {
		lv := l["landing"].(map[string]any)
		segs = append(segs, map[string]any{"id": lv["id"], "number": lv["number"], "branch": lv["branch"],
			"target": "trunk", "state": "open", "position": i + 1, "ci": lv["ci"]})
	}
	for _, l := range ls {
		lv := l["landing"].(map[string]any)
		lv["autoBy"] = armed[lv["id"].(string)]
		l["stack"] = map[string]any{"base": "a", "top": "c", "segments": segs}
	}
}

func TestStatusListsEveryRungOfAStackBottomUp(t *testing.T) {
	f := newStatusForge(t)
	ls := []map[string]any{
		landingAnswer("a", 40, "alex", "checks", "A-SAY", "A-NEXT", "quarry status !40", "ci-run"),
		landingAnswer("b", 41, "alex", "stack", "B-SAY", "B-NEXT", "quarry status !41", "ci-pass"),
		landingAnswer("c", 42, "alex", "stack", "C-SAY", "C-NEXT", "quarry status !42", "ci-pass"),
	}
	stacked(ls, map[string]string{"c": "alex"})
	f.landings = ls
	m := f.object(t, "!42")
	l := m["landings"].([]any)[0].(map[string]any)
	if l["finalTarget"] != "trunk" {
		t.Errorf("FAIL: finalTarget %v", l["finalTarget"])
	}
	rungs, _ := l["stack"].([]any)
	if len(rungs) != 3 {
		t.Fatalf("FAIL: stack %v", l["stack"])
	}
	want := []struct {
		n     float64
		armed string
		next  string
	}{{40, "", "A-NEXT"}, {41, "", "B-NEXT"}, {42, "alex", "C-NEXT"}}
	for i, w := range want {
		r := rungs[i].(map[string]any)
		for _, k := range []string{"position", "number", "id", "branch", "target", "state", "ci", "armedBy", "waiting"} {
			if _, ok := r[k]; !ok {
				t.Errorf("FAIL: rung %d lacks %q", i, k)
			}
		}
		next, _ := r["waiting"].(map[string]any)["next"].(map[string]any)
		if r["number"] != w.n || r["armedBy"] != w.armed || next["say"] != w.next || r["position"] != float64(i+1) {
			t.Errorf("FAIL: rung %d is %v", i, r)
		}
	}
	code, out, _ := f.run(t, "!42")
	at := -1
	for _, b := range []string{"br-a", "br-b", "br-c"} {
		i := strings.Index(out[max(at, 0):], b)
		if code != 0 || i < 0 {
			t.Fatalf("FAIL: exit %d, no %s after the one before it:\n%s", code, b, out)
		}
		at += i + 1
	}
	// A landing on its own carries no stack.
	f2 := newStatusForge(t)
	f2.landings = []map[string]any{landingAnswer("s", 50, "alex", "checks", "S", "N", "quarry status", "ci-run")}
	one := f2.object(t, "!50")["landings"].([]any)[0].(map[string]any)
	if _, ok := one["stack"]; ok {
		t.Errorf("FAIL: a lone landing has a stack: %v", one["stack"])
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A push to an armed landing disarms it by design; status says the arm
// lapsed and why, and the next step is quarry land, which re-arms the
// tip now pushed. A landing never armed carries no such field.
func TestStatusSaysWhyAnArmLapsed(t *testing.T) {
	f := newStatusForge(t)
	lapsed := landingAnswer("a", 41, "alex", "nothing", "SAY", "Arm it.", "quarry status !41", "ci-pass")
	lapsed["landing"].(map[string]any)["autoBy"] = ""
	lapsed["autoLapsed"] = "a check-in was pushed after the arm"
	plain := landingAnswer("p", 42, "alex", "checks", "SAY", "NEXT", "quarry status !42", "ci-run")
	f.landings = []map[string]any{lapsed, plain}
	m := f.object(t)
	ls := m["landings"].([]any)
	l := ls[0].(map[string]any)
	if l["armLapsed"] != "a check-in was pushed after the arm" {
		t.Errorf("FAIL: armLapsed = %v", l["armLapsed"])
	}
	next, _ := l["waiting"].(map[string]any)["next"].(map[string]any)
	if next["cmd"] != "quarry land br-a" {
		t.Errorf("FAIL: next cmd = %v; want quarry land br-a", next["cmd"])
	}
	if _, ok := ls[1].(map[string]any)["armLapsed"]; ok {
		t.Errorf("FAIL: a landing that never lapsed has armLapsed")
	}
	if n, _ := m["next"].(map[string]any); n["cmd"] != "quarry land br-a" {
		t.Errorf("FAIL: top next = %v", m["next"])
	}

	// Each rung of a stack says for itself.
	f = newStatusForge(t)
	rs := []map[string]any{
		landingAnswer("a", 40, "alex", "checks", "A", "A-NEXT", "quarry status !40", "ci-run"),
		landingAnswer("b", 41, "alex", "stack", "B", "Arm it.", "quarry status !41", "ci-pass"),
		landingAnswer("c", 42, "alex", "stack", "C", "C-NEXT", "quarry status !42", "ci-pass"),
	}
	stacked(rs, map[string]string{"c": "alex"})
	rs[1]["autoLapsed"] = "pushed after the arm"
	f.landings = rs
	st := f.object(t, "!42")["landings"].([]any)[0].(map[string]any)
	for i, r := range st["stack"].([]any) {
		r := r.(map[string]any)
		lapsedHere := i == 1
		if got := r["armLapsed"]; lapsedHere != (got == "pushed after the arm") {
			t.Errorf("FAIL: rung %d armLapsed = %v", i, got)
		}
		if lapsedHere {
			if nx, _ := r["waiting"].(map[string]any)["next"].(map[string]any); nx["cmd"] != "quarry land br-b" {
				t.Errorf("FAIL: rung next = %v", nx)
			}
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}