#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# yukti — a portable local iOS-Simulator QA rig for React Native / Expo apps.
#
#   build → sign → boot → install → launch → drive.  No cloud device farm.
#
# Two ways to run tests, and AI is OPTIONAL:
#   • Deterministic flows   →  `yukti flow flows/login.json`   (zero AI, CI-ready)
#   • AI-driven exploration →  any agent (Claude Code / OpenAI computer-use)
#                              drives the primitives below (shot/ui/find/tap/type)
#
# The whole rig is Apple tools + idb. Expo/EAS is an optional adapter, not a dep.
#
# MIT licensed. https://github.com/<you>/yukti
# ─────────────────────────────────────────────────────────────────────────────
set -euo pipefail

# The environment as the user handed it over, taken before this script assigns
# a single variable of its own (#101). A flow fills ${NAME} from the
# environment, and an exported variable that shares its name with one of the
# script's - CONFIG, PY, HELD_TREE, once the colours E and R - was overwritten
# here and stayed exported, so the step got the script's value. The flow
# builder lays these values over what the environment has become by then.
_yk_env0="$(/usr/bin/python3 -c "import json,os; print(json.dumps(dict(os.environ)))" 2>/dev/null)" || _yk_env0=""

YUKTI_VERSION="0.1.0"
CONFIG="${YUKTI_CONFIG:-yukti.config.json}"
PY="/usr/bin/python3"                       # system python: reliable expat + json
NODE22="/opt/homebrew/opt/node@22/bin"      # RN/Metro pins node 22; sys node may be broken
# HOME may be unset - env -i, a container, a service unit - and under set -u a
# bare $HOME here stopped the script on this line, help and flow --check
# included, with "HOME: unbound variable" and nothing about why (#58). Each path
# built from it falls back to nothing, and the step that needs the tool then
# says the tool is missing.
IDB_BIN="${HOME:+$HOME/Library/Python/3.9/bin}"   # fb-idb CLI install location

# ── pretty ───────────────────────────────────────────────────────────────────
# The colours live under names no flow is likely to use (#101). They were R, B,
# G, Y and E: a variable of that name exported by the user was overwritten here,
# stayed exported, and the step builder - which fills ${NAME} from the
# environment - typed the escape sequence where the user's value belonged.
# Not exported either, so a name inherited from outside does not carry the
# colour to the processes this script starts.
c(){ printf '\033[%sm' "$1"; }; _yk_R=$(c 0); _yk_B=$(c '1;36'); _yk_G=$(c '1;32'); _yk_Y=$(c '1;33'); _yk_E=$(c '1;31')
export -n _yk_R _yk_B _yk_G _yk_Y _yk_E
say(){ printf '%s▸%s %s\n' "$_yk_B" "$_yk_R" "$*"; }
ok(){  printf '%s✓%s %s\n' "$_yk_G" "$_yk_R" "$*"; }
warn(){ printf '%s!%s %s\n' "$_yk_Y" "$_yk_R" "$*"; }
# A step a condition switched off. Not a warning (nothing went wrong) and not a
# pass (nothing was done), so it gets its own mark in the run.
skipped(){ printf '%s~%s %s\n' "$_yk_Y" "$_yk_R" "$*"; }
# The last words of a failing step are also the message its result entry needs,
# so keep a copy when a flow is running. The console output is unchanged.
#
# Where the step was written is part of those words. The verbs that fail most -
# tapText, waitFor, assertText, assertId, tapId, screenshot - die on their own
# and never come back with a status, so a suffix added where the status is read
# would be missing from exactly the steps a shared block is made of: the report
# would say `03 tapText Sign In` for forty-five flows and never name the one
# file to fix. The flow loop sets YUKTI_STEP_SRC for the step it is running -
# and this process owns that variable, whatever it inherited: a value left in
# the environment by a caller used to be printed after a message that belongs to
# no step at all, `no flow file 'x.json' (stale from parent)`.
YUKTI_STEP_SRC=""
die(){ local m="$*"; if [ -n "${YUKTI_STEP_SRC:-}" ]; then m="$m ($YUKTI_STEP_SRC)"; fi
  printf '%s✗%s %s\n' "$_yk_E" "$_yk_R" "$m" >&2; [ -n "${YUKTI_STEP_ERR:-}" ] && printf '%s' "$m" > "$YUKTI_STEP_ERR"; exit 1; }
# A failure of the device or of the engine itself, not of the app: the screen
# could not be read, the screenshot was not taken. Marked beside the step's
# message, in a file for the same reason - the reads that fail run in
# subshells - and the result reports it as a JUnit <error> instead of a
# <failure> (#96). Only what the engine knows for sure is marked; an element
# that is not there stays a failure even when a system dialog hid it. A read
# that succeeds takes the mark back: a step that polls may miss one read and
# still fail on what it then saw.
device_fault(){ [ -z "${YUKTI_STEP_ERR:-}" ] || { : > "$YUKTI_STEP_ERR.kind"; } 2>/dev/null || true; }

need_config(){ [ -f "$CONFIG" ] || die "no config at '$CONFIG' — run 'yukti init' or set YUKTI_CONFIG"; }

# ── config reader (dotted path; prints scalars raw, lists/objects as JSON) ─────
cfg(){ need_config; "$PY" - "$CONFIG" "$1" "${2:-}" <<'PY'
import json,sys
d=json.load(open(sys.argv[1])); default=sys.argv[3] if len(sys.argv)>3 else ""
cur=d
try:
    for k in sys.argv[2].split('.'):
        cur=cur[k]
except (KeyError,TypeError):
    print(default); sys.exit(0)
print(cur if not isinstance(cur,(list,dict)) else json.dumps(cur))
PY
}

app_dir(){ ROOT="$(cfg projectRoot .)"; cd "$ROOT" 2>/dev/null || die "projectRoot '$ROOT' not found"; }
# IDB_BIN is empty with no HOME (#58), and an empty entry in PATH is the current
# directory: a ./idb or ./xcrun in the project would run in place of the real one.
paths(){ export PATH="$NODE22:${IDB_BIN:+$IDB_BIN:}/opt/homebrew/bin:$PATH"; }
udid_file(){ echo "${TMPDIR:-/tmp}/yukti-udid"; }
booted(){ xcrun simctl list devices 2>/dev/null | grep -m1 Booted | grep -oE '[0-9A-F-]{36}' || true; }
# The platform of this run, resolved once before the command runs (bottom of the
# file). Every primitive asks this and nothing else, so one run drives one
# platform: `yukti up android-qa` and `yukti flow` on the same config could
# disagree, because the first read the variant and the second a global that
# defaulted to iOS.
is_android(){ [ "${YUKTI_PLATFORM:?the platform of this run was never resolved}" = android ]; }

# Sources, in order: the environment, the platform of the variant this
# invocation is about, the top-level "platform". The variant is the one named on
# the command line, else $YUKTI_VARIANT, which is what Studio sets when a variant
# is picked in the panel. Nothing left to ask is not an iOS run - it is a run
# that cannot know what it is driving, so it says so and stops. The answer names
# its source: which platform, and which of the three said so.
resolve_platform(){
  local v="${1:-}" p='' src='' vp='' why=''
  [ -n "$v" ] || v="${YUKTI_VARIANT:-}"
  [ -n "$v" ] && [ -f "$CONFIG" ] && vp="$(cfg "variants.$v.platform")"
  if [ -n "${YUKTI_PLATFORM:-}" ]; then
    p="$YUKTI_PLATFORM"; src='$YUKTI_PLATFORM'
    # A variant that names its own platform states a fact about that variant,
    # not a preference. When the environment pins a different one, one of the
    # two is wrong, and picking either is the silent answer this whole change
    # exists to end.
    [ -z "$vp" ] || [ "$vp" = "$p" ] || die "\$YUKTI_PLATFORM says $p and variant '$v' says $vp - they cannot both be the platform of this run"
  elif [ -f "$CONFIG" ]; then
    if [ -n "$vp" ]; then p="$vp"; src="variant '$v'"
    else p="$(cfg platform)"; [ -n "$p" ] && src="\"platform\" in $CONFIG"; fi
  fi
  if [ -z "$p" ]; then
    # Say which of the three was asked and what it answered. Assembled here and
    # not inside the message: a ${v:-...} there reads as the variant's own name.
    if [ ! -f "$CONFIG" ]; then
      why="and there is no config at '$CONFIG' - run 'yukti init' or set YUKTI_CONFIG"
    else
      if [ -z "$v" ]; then why="no variant was named (either a command that takes one, or \$YUKTI_VARIANT)"
      elif [ -z "$(cfg "variants.$v")" ]; then why="there is no variant '$v' in $CONFIG, and it"
      else why="variant '$v' does not name a platform, and $CONFIG"; fi
      [ -n "$v" ] || why="$why, and $CONFIG"
      why="$why has no top-level \"platform\""
    fi
    die "cannot tell which platform this run is for: \$YUKTI_PLATFORM is not set, $why"
  fi
  case "$p" in ios|android) ;; *) die "'$p' is not a platform - the only ones are ios and android (from $src)";; esac
  export YUKTI_PLATFORM="$p"
  # To stderr: `yukti find`, `yukti shot` and `yukti ui` put an answer on stdout
  # that a caller reads.
  say "platform: $p (from $src)" >&2; }

# ── Android backend (adb + uiautomator + gradle) ─────────────────────────────
# 1:1 mirror of the iOS path. Implemented; validate on a Mac with the Android SDK.
# Android debug APKs are auto-signed with the debug key — none of the iOS signing/
# keychain/arch pain applies. Config per variant: platform:"android", package,
# gradleTask (default assembleDebug); global android.avd for the emulator.
ANDROID_SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-${HOME:+$HOME/Library/Android/sdk}}}"
apaths(){ export PATH="$NODE22:$ANDROID_SDK/platform-tools:$ANDROID_SDK/emulator:$ANDROID_SDK/cmdline-tools/latest/bin:/opt/homebrew/bin:$PATH"; }

build_android(){ local V="$1"; app_dir; apaths
  local task apk env; task="$(cfg variants.$V.gradleTask assembleDebug)"; env="$(cfg variants.$V.envFile)"
  [ -n "$env" ] && [ -f "$env" ] && cp "$env" .env.local && ok "env: $env → .env.local"
  say "gradle $task"; ( cd android && ./gradlew "$task" ) || die "gradle build failed"
  apk="$(find android/app/build/outputs/apk -name '*.apk' 2>/dev/null | head -1)"
  [ -n "$apk" ] || die "no APK produced"; echo "$apk" > "${TMPDIR:-/tmp}/yukti-apk-$V"; ok "built: $apk"; }
boot_android(){ apaths; local avd; avd="$(cfg android.avd Pixel_7_API_34)"
  if ! adb devices 2>/dev/null | grep -q emulator; then say "starting emulator $avd"; ( "$ANDROID_SDK/emulator/emulator" -avd "$avd" -no-boot-anim >/dev/null 2>&1 & ); fi
  adb wait-for-device; until [ "$(adb shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = 1 ]; do sleep 2; done; ok "emulator booted"; }
# Where the APK comes from, in order: the path named on the command line, the
# variant's "apkPath", and last the file the build step wrote. An artifact an
# earlier CI job built never had a build step here to write that file, and there
# was no other way in - the path had to be forged into a temporary file named by
# an internal convention, so installing fell out of the runner and the job ran
# `adb install` itself.
apk_of(){ local V="$1" want="${2:-}" p='' src
  if [ -n "$want" ]; then p="$want"; src="--apk"
  else
    if [ -f "$CONFIG" ]; then p="$(cfg "variants.$V.apkPath")"; fi; src="\"apkPath\" of variant '$V'"
    # A relative path there is relative to the config that names it. Taken from
    # the current directory instead, the same config would install a different
    # file depending on where the command was typed - and CI types it from
    # somewhere else than a laptop does.
    case "$p" in ''|/*) ;; *) p="$(cd "$(dirname "$CONFIG")" && pwd)/$p";; esac
    if [ -z "$p" ]; then
      p="$(cat "${TMPDIR:-/tmp}/yukti-apk-$V" 2>/dev/null || true)"; src="the build step"
      [ -n "$p" ] || die "no APK to install for '$V': pass --apk <path>, set variants.$V.apkPath, or run 'yukti build $V' first"
    fi
  fi
  [ -f "$p" ] || die "the APK named by $src is not a file: '$p'"
  printf '%s' "$p"; }

install_android(){ apaths; local V="$1" apk; apk="$(apk_of "$V" "${2:-}")"
  adb install -r "$apk" && ok "installed $(basename "$apk")"; }
launch_android(){ apaths; local pkg; pkg="$(cfg variants.$1.package)"; adb shell monkey -p "$pkg" -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1 && ok "launched $pkg"; }
# A screenshot value is a NAME, not a path. RUNBOOK says the files land in
# $TMPDIR and that the flows only name them; they landed in whatever directory
# the run was started from, so a suite scattered pngs across the caller's tree
# while $TMPDIR stayed empty. Join a relative name to $TMPDIR. An absolute path
# is still taken as given, and a name with a directory in it gets that directory
# created rather than failing the step.
shot_path(){ local n="${1:-yukti-shot.png}"
  # A name is a name. ".." in it would write outside $TMPDIR while reading like
  # a file inside it, so refuse rather than guess what was meant.
  case "$n" in *..*) die "screenshot name must not contain '..': '$n'";; esac
  case "$n" in /*) printf '%s' "$n";; *) printf '%s/%s' "${TMPDIR:-/tmp}" "$n";; esac; }
# A refused name stops the shot here: the step calls it as `$(shot ...) || die`,
# and on the left of || bash does not stop on errors, so without the return a
# refused name went on to take a screenshot to an empty path.
ashot(){ apaths; local o; o="$(shot_path "${1:-}")" || return 1; mkdir -p "$(dirname "$o")"; if adb exec-out screencap -p > "$o"; then echo "$o"; else device_fault; return 1; fi; }
# Delete the dump before writing a new one. uiautomator refuses to dump while the
# screen is animating ("could not get idle state!"), the error was swallowed, and
# `cat` then served the tree of the PREVIOUS call: the next assert checked the
# previous screen and passed. A refusal is a normal state right after a tap, so
# retry a few times the way the iOS ui() already does, and only then give up.
# Remove, dump and read run in ONE adb round trip: a lookup used to cost two, a
# scroll_to up to eighteen.
#
# What counts as an answer is the WHOLE tree, not "some bytes". Non-empty is not
# enough:
# `cat` on a file uiautomator never wrote answers "No such file or directory" ON
# STDOUT through some adb shell protocol versions, and the daemon prints "* daemon
# started successfully *" on stdout too. Either one used to pass the emptiness
# check and reach the parser, which found no nodes and reported an absent element -
# the very confusion this retry exists to prevent. A dump cut off mid-tree does
# the same thing while looking even more like a tree, so the closing tag has to
# be there too: uiautomator writes the document in one go, and the end of it is
# the only evidence that nothing was lost on the way out.
#
# The file name carries the pid, so a dump that did not happen cannot be answered
# with the file some earlier run left on the device: `rm -f` failing silently was
# the one path back to serving a stale tree, and a per-run name closes it. The
# file is removed again after reading, in the same round trip.
# A tree held for the length of one step. A step that looks for several things
# on the SAME screen - dismiss looks for nine labels - used to read the screen
# once per thing, and every read after the first was of a screen that nothing
# had touched. A step fills this, reads as often as it likes, and empties it
# before anything taps: a held tree outliving a tap would be a step deciding
# against a screen that is no longer there. The one holder that is not a step is
# a `when` (#172): a run of skipped steps touches nothing, so the conditions in
# it answer from one read, and the next step that runs empties it.
HELD_TREE=""
# Set only around the relaunch for a blank tree (#191), never taken from the
# caller's environment: a value inherited there would switch the relaunch off.
YUKTI_UNSTICK_BUSY=""
# A flow's record; empty outside a running flow (#191 reads it to know it is in one).
FLOW_REC=""
# The tree a step read last, kept for the result of a failed flow (#94). Nearly
# every read happens inside $(...), so a variable would die with the subshell;
# a file outlives it, the way the step's message does. The step number goes
# beside it: a tap by coordinates reads no tree, and a tree two steps old must
# not be passed off as the screen of the failure. Outside a flow - `yukti ui`
# from the command line - there is nothing to keep it for.
keep_tree(){ [ -z "${YUKTI_STEP_ERR:-}" ] || rm -f "$YUKTI_STEP_ERR.kind" 2>/dev/null || true
  [ -n "${YUKTI_LAST_TREE:-}" ] || return 0
  { printf '%s' "$1" > "$YUKTI_LAST_TREE" && printf '%s' "${FLOW_IDX:-0}" > "$YUKTI_LAST_TREE.step"; } 2>/dev/null || true; }
# ── resident screen helper (Android) ─────────────────────────────────────────
# A dump costs 2.4 s on a still screen and is refused outright on a moving one
# ("could not get idle state"), and every step reads the screen at least once.
# appium-uiautomator2-server answers the same tree in 20-60 ms: it holds one
# UiAutomation open for as long as it lives instead of building one per read,
# and it can be told to wait at most half a second for the screen to settle
# (#105). It is two APKs from the project's GitHub release, pinned by version
# and sha256; nothing else of Appium is involved.
#
# The helper is a READER first: aui() asks it first and falls back to the dump
# exactly as before when it cannot answer. Taps, typing and the `scroll` step
# stay on adb; the one thing it does besides reading is the swipe of a search
# (scrollToText, tapText - see swipe_pts), which needs a finger that stops before
# it lifts, and adb has none (#107). There is one UiAutomation per device: while the helper lives, a dump -
# ours, or anybody else's - is killed on the spot. So the fallback stops the
# helper before it dumps, and the helper does not outlive the run that started
# it unless the caller asks for that (YUKTI_HELPER_KEEP=1, which a suite runner
# sets and pairs with `yukti helper stop`). It listens on every interface of the
# device, which on a phone on Wi-Fi is the screen and its taps open to the
# network for as long as it is up - one more reason not to leave it behind.
#
# Where things live: what one run learned (port, session, "do not use it here")
# in the run directory, gone when the run ends; what outlives a run (the APKs,
# which sha is installed on which device, a session a kept helper still holds,
# how many starts failed in a row) in the user's cache, keyed by serial.
UIA2_VER="v10.6.6"
UIA2_REL="https://github.com/appium/appium-uiautomator2-server/releases/download/$UIA2_VER"
UIA2_SERVER_APK="appium-uiautomator2-server-$UIA2_VER.apk"
UIA2_SERVER_SHA="8ff760a2a86b487f53090fbdcd5b0360e67d02bb811887d527a9557b0d59c80d"
UIA2_TEST_APK="appium-uiautomator2-server-debug-androidTest.apk"
UIA2_TEST_SHA="e6f729287d72351388fd66597c35b69988b9091a7011954bf92a55d416cb1e1c"
UIA2_PKG="io.appium.uiautomator2.server"
UIA2_TEST_PKG="io.appium.uiautomator2.server.test"
UIA2_PORT=6790
HELPER_WHY=""
# With neither XDG_CACHE_HOME nor HOME the cache goes under this user's own name
# in the temporary directory, not under the filesystem root. That name can be
# guessed, and in a shared /tmp another user could make it first, with links in
# it where the logs are written: the directory is made private here and used
# only if it is this user's own. Otherwise there is no cache, and the helper
# is not started, saying why.
helper_cache(){ local b="${XDG_CACHE_HOME:-${HOME:+$HOME/.cache}}" t
  if [ -n "$b" ]; then printf '%s/yukti/uia2-%s' "$b" "$UIA2_VER"; return 0; fi
  t="${TMPDIR:-/tmp}/yukti-$(id -u)"; mkdir -m 700 "$t" 2>/dev/null
  # An empty answer, not a failed one: under set -e a failed c="$(helper_cache)"
  # would end the run.
  [ -d "$t" ] && [ ! -L "$t" ] && [ -O "$t" ] || return 0
  printf '%s/uia2-%s' "$t" "$UIA2_VER"; }
# The serial names the files a device's state lives in, and picks its forward
# out of `adb forward --list`, which lists every device on the machine. adb
# itself is never told a serial here: it takes ANDROID_SERIAL like every other
# adb call of the engine.
helper_serial(){ local d s; d="$(run_dir)"
  [ -s "$d/helper-serial" ] && { cat "$d/helper-serial"; return 0; }
  s="${ANDROID_SERIAL:-}"; [ -n "$s" ] || s="$(adb get-serialno 2>/dev/null | tr -d '\r\n' || true)"
  case "$s" in ''|unknown) return 1;; esac
  printf '%s' "$s" > "$d/helper-serial"; printf '%s' "$s"; }
# The serial as part of a file name: a device on Wi-Fi is "192.168.1.5:5555".
helper_key(){ printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_'; }
file_sha(){ "$PY" -c 'import hashlib,sys
h=hashlib.sha256()
with open(sys.argv[1],"rb") as f:
    for b in iter(lambda: f.read(1<<20), b""): h.update(b)
print(h.hexdigest())' "$1" 2>/dev/null; }
# One HTTP call to the helper: helper_http <port> <GET|POST> <path> <timeout> [body]
# The status says what went wrong, because what to do next depends on it:
#   2  nothing answered - the forward or the helper is gone
#   3  no such session (404)
#   4  no answer in time
#   5  an answer, but not a tree (or another HTTP error)
# A source is printed as the tree the dump would have given: the helper names
# every element by its class (<android.widget.TextView ...>), the dump calls
# each one <node> and keeps the class in class=, and every parser here looks for
# <node>. Every tag but the root is renamed - not only android.* ones, React
# Native classes are com.facebook.react.* - and the indentation between tags
# goes, so the tree reads the way a dump does.
HELPER_PY='
import http.client, json, re, socket, sys, urllib.error, urllib.request
port, method, path, timeout = sys.argv[1], sys.argv[2], sys.argv[3], float(sys.argv[4])
body = sys.argv[5].encode() if len(sys.argv) > 5 else None
req = urllib.request.Request("http://127.0.0.1:%s%s" % (port, path), data=body, method=method)
if body: req.add_header("Content-Type", "application/json")
try:
    with urllib.request.urlopen(req, timeout=timeout) as r: raw = r.read()
except urllib.error.HTTPError as e:
    sys.exit(3 if e.code == 404 else 5)
except urllib.error.URLError as e:
    sys.exit(4 if isinstance(e.reason, socket.timeout) else 2)
except socket.timeout:
    sys.exit(4)
except (OSError, http.client.HTTPException):
    sys.exit(2)
if path.endswith("/source"):
    try: x = json.loads(raw)["value"]
    except Exception: sys.exit(5)
    if not isinstance(x, str) or "<hierarchy" not in x or "</hierarchy>" not in x: sys.exit(5)
    x = re.sub(r">\s+<", "><", x)
    x = re.sub(r"<(/?)(?!hierarchy[\s/>])[A-Za-z_][\w.$-]*", r"<\1node", x)
    sys.stdout.write(x)
elif method == "POST" and path == "/session":
    try:
        v = json.loads(raw); s = v.get("sessionId") or (v.get("value") or {}).get("sessionId")
    except Exception: sys.exit(5)
    if not s: sys.exit(5)
    sys.stdout.write(s)
'
helper_http(){ local d; d="$(run_dir)"
  "$PY" -c "$HELPER_PY" "$(cat "$d/helper-port" 2>/dev/null)" "$@" 2>/dev/null; }
# Seconds one read may take. Not less than the dump's own ceiling (it waits up
# to 10 s for the screen to settle), or a slow screen that the dump would still
# have read becomes a "failure" of the helper. Tests shorten it.
helper_read_timeout(){ printf '%s' "${YUKTI_HELPER_TIMEOUT:-12}"; }
# The forward for this device, or a new one. adb picks the local port (tcp:0)
# and prints it, so two devices on one machine never fight over a number. More
# than one forward to the helper port can exist when another tool forwarded it
# too; there is one server on the device, so the first will do. A command that
# is not a flow makes no forward for a helper that is not there.
helper_forward(){ local s p; s="$(helper_serial)" || return 1
  p="$(adb forward --list 2>/dev/null | awk -v s="$s" -v r="tcp:$UIA2_PORT" '$1==s && $3==r {sub(/^tcp:/,"",$2); print $2; exit}' || true)"
  if [ -z "$p" ]; then
    [ -n "${YUKTI_STEP_ERR:-}" ] || helper_alive || return 1
    p="$(adb forward tcp:0 "tcp:$UIA2_PORT" 2>/dev/null | tr -d '\r\n' || true)"
  fi
  case "$p" in ''|*[!0-9]*) return 1;; esac
  printf '%s' "$p"; }
helper_alive(){ [ -n "$(adb shell pidof "$UIA2_PKG" 2>/dev/null | tr -d '\r\n ' || true)" ]; }
helper_force_stop(){ adb shell "am force-stop $UIA2_PKG; am force-stop $UIA2_TEST_PKG" >/dev/null 2>&1 || true; }
# Only a flow starts the helper: it reads the screen dozens of times and earns
# back the 6-8 s a start costs. A single command reads once - `yukti ui` would
# pay the start and the stop for one look that a dump gives in 2.4 s - so it
# uses a helper that is already up and otherwise dumps. Two refusals are
# reported: a helper this run has already started once, and a device where the
# last two starts failed - an Android older than 8, a phone that puts a dialog
# in front of every install from USB, another build of the same package signed
# with another key. Such a device would pay a failed start, up to 15 s, on every
# flow of a suite. A download that failed is not the device's failure and does
# not count. The mark expires after a day, and `yukti helper stop` clears it.
helper_may_start(){ local d c f n; d="$(run_dir)"
  [ -n "${YUKTI_STEP_ERR:-}" ] || return 1
  [ ! -e "$d/helper-tried" ] || { HELPER_WHY="it stopped answering, and this run has already started it once"; return 1; }
  c="$(helper_cache)"
  [ -n "$c" ] || { HELPER_WHY="it has no cache directory - neither XDG_CACHE_HOME nor HOME is set, and ${TMPDIR:-/tmp}/yukti-$(id -u) is not this user's own"; return 1; }
  f="$c/start-fail-$(helper_key "$(helper_serial)")"
  n="$(cat "$f" 2>/dev/null || true)"
  if [ "${n:-0}" -ge 2 ] 2>/dev/null && [ -n "$(find "$f" -mmin -1440 2>/dev/null)" ]; then
    HELPER_WHY="it failed to start twice in a row on this device - 'yukti helper stop' clears that, YUKTI_HELPER=0 turns it off"
    return 1
  fi
  return 0; }
# An APK from the cache, checked against its pinned sha every time it is about
# to be installed; one that is missing or does not match is fetched again. The
# download goes to a temporary file in the cache itself and only a file that
# matches is moved into place. The pins are this project's own download of the
# release - the project publishes no checksums - so they guard against a file
# that changed after the pin, not against the first one.
helper_apk(){ local c="$1" n="$2" want="$3" p t; p="$c/$n"
  if [ -s "$p" ] && [ "$(file_sha "$p")" = "$want" ]; then printf '%s' "$p"; return 0; fi
  rm -f "$p"
  t="$(mktemp "$c/.download.XXXXXX" 2>/dev/null)" || return 1
  if curl -fsSL --proto '=https' --tlsv1.2 --connect-timeout 10 --max-time 120 -o "$t" "$UIA2_REL/$n" 2>/dev/null \
     && [ "$(file_sha "$t")" = "$want" ]; then
    mv -f "$t" "$p" && { printf '%s' "$p"; return 0; }
  fi
  rm -f "$t"; return 1; }
# What is installed is known from our own mark - which pair of sha went onto
# which serial - plus `pm path` that both packages are still there. The release
# APK's versionName is not a version we can rely on, and a check that always
# saw "another version" would reinstall 18 MB on every flow. A different build
# of the same packages installed by someone else after our mark does not clear
# it: that start fails, and the start counter above takes it from there.
# Status 2 is a download that failed or did not match - the network's fault,
# not the device's; 1 is a device that refused the install.
helper_install(){ local c="$1" k="$2" m sp tp; m="$c/installed-$k"
  if [ "$(cat "$m" 2>/dev/null || true)" = "$UIA2_SERVER_SHA $UIA2_TEST_SHA" ] \
     && [ "$(adb shell "pm path $UIA2_PKG; pm path $UIA2_TEST_PKG" 2>/dev/null | grep -c '^package:' || true)" = 2 ]; then
    return 0
  fi
  sp="$(helper_apk "$c" "$UIA2_SERVER_APK" "$UIA2_SERVER_SHA")" && tp="$(helper_apk "$c" "$UIA2_TEST_APK" "$UIA2_TEST_SHA")" \
    || { HELPER_WHY="its APK could not be fetched, or did not match the pinned sha256"; return 2; }
  rm -f "$m"
  adb install -r -g "$sp" >/dev/null 2>&1 && adb install -r -g "$tp" >/dev/null 2>&1 \
    || { HELPER_WHY="adb install refused it"; return 1; }
  printf '%s %s' "$UIA2_SERVER_SHA" "$UIA2_TEST_SHA" > "$m"; }
# The server runs inside `am instrument -w`, whose adb client has to outlive the
# flow: it goes into a session of its own, so the `timeout` a suite wraps a flow
# in kills the flow's process group and not the helper. setsid(1) is util-linux
# and a Mac has none; Python's os.setsid is everywhere this engine runs. Its
# output goes to a file: anything still holding the pipe of the $(...) the read
# runs in would keep that read waiting forever. The client returning on its own
# means the instrumentation ended - nothing is going to answer. A failed start
# is stopped by the fallback that follows it (helper_give_up).
helper_start(){ local d c k pid end r=0; d="$(run_dir)"; : > "$d/helper-tried"
  c="$(helper_cache)"; k="$(helper_key "$(helper_serial)")"
  mkdir -p "$c" 2>/dev/null && [ -w "$c" ] || { HELPER_WHY="the cache directory $c cannot be written"; return 1; }
  helper_install "$c" "$k" || r=$?
  if [ "$r" = 0 ]; then
    "$PY" -c 'import os,sys; os.setsid(); os.execvp(sys.argv[1], sys.argv[1:])' \
      adb shell am instrument -w "$UIA2_TEST_PKG/androidx.test.runner.AndroidJUnitRunner" \
      > "$c/instrument-$k.log" 2>&1 < /dev/null &
    pid=$!
    end=$(( SECONDS + 15 ))
    while [ "$SECONDS" -lt "$end" ]; do
      helper_http GET /status 2 >/dev/null && { rm -f "$c/start-fail-$k"; : > "$d/helper-ours"; return 0; }
      kill -0 "$pid" 2>/dev/null || { helper_http GET /status 2 >/dev/null && { rm -f "$c/start-fail-$k"; : > "$d/helper-ours"; return 0; }; break; }
      sleep 0.3
    done
    HELPER_WHY="it did not come up (log: $c/instrument-$k.log)"
  fi
  [ "$r" = 2 ] || echo $(( $(cat "$c/start-fail-$k" 2>/dev/null || echo 0) + 1 )) > "$c/start-fail-$k" 2>/dev/null || true
  return 1; }
# A new session forgets every setting (the server resets them per session), so
# the wait is set again each time: at most half a second for the screen to
# settle, where the server's own default is ten.
helper_session(){ local d sid; d="$(run_dir)"
  sid="$(helper_http POST /session 5 '{"capabilities":{"alwaysMatch":{"platformName":"Android"}}}')" \
    && helper_http POST "/session/$sid/appium/settings" 5 '{"settings":{"waitForIdleTimeout":500}}' >/dev/null \
    || { HELPER_WHY="it did not open a session"; return 1; }
  printf '%s' "$sid" > "$d/helper-session"
  [ "${YUKTI_HELPER_KEEP:-}" = 1 ] && { mkdir -p "$(helper_cache)" && printf '%s' "$sid" > "$(helper_cache)/session-$(helper_key "$(helper_serial)")"; } 2>/dev/null || true; }
# Port and session, found once per run and remembered in the run directory.
# They are trusted until a read fails: no "is it alive" round trip in front of
# every read. A forward found anew is checked with /status before it is used -
# adbd restarts on every `adb root`, the forward goes with it and the helper may
# or may not have survived. A kept helper's session is taken from the cache.
helper_connect(){ local d p check="" kf; d="$(run_dir)"
  if [ ! -s "$d/helper-port" ]; then
    # A flow says why it reads with the dump; a single command finding no helper
    # is the normal case and says nothing.
    p="$(helper_forward)" || {
      [ -z "${YUKTI_STEP_ERR:-}" ] || if helper_serial >/dev/null; then HELPER_WHY="adb could not forward a port to it"
        else HELPER_WHY="adb did not name the device"; fi
      return 1; }
    printf '%s' "$p" > "$d/helper-port"; check=1
  fi
  if [ ! -s "$d/helper-session" ]; then
    kf="$(helper_cache)/session-$(helper_key "$(helper_serial)")"
    [ -s "$kf" ] && cp "$kf" "$d/helper-session" 2>/dev/null || check=1
  fi
  if [ -n "$check" ] && ! helper_http GET /status 2 >/dev/null; then
    helper_may_start && helper_start || return 1
    rm -f "$d/helper-session"
  fi
  [ -s "$d/helper-session" ] || helper_session; }
# The helper is given up on for the rest of the run, and stopped, so that the
# dump that follows is not killed by it. Only a reason worth saying is said: a
# single command finding no helper, or YUKTI_HELPER=0, is the normal case.
helper_give_up(){ local d; d="$(run_dir)"; : > "$d/helper-off"
  [ -n "$HELPER_WHY" ] || return 0
  warn "screen helper: $HELPER_WHY - this run reads the screen with uiautomator dump" >&2
  printf 'x' >> "$d/helper-fallbacks"
  rm -f "$(helper_cache)/session-$(helper_key "$(helper_serial 2>/dev/null)")" 2>/dev/null || true
  helper_force_stop; }
# The tree from the helper, or a failure that sends aui() to the dump. A read
# is tried three times, as the dump is: a timeout or an answer that is not a
# tree is a failed try and not a dead helper, and on a moving screen one try
# can miss. What failed decides the repair before the next try - a lost
# forward is made again, a lost session is opened again.
# With AUI_ACTIONS=1 (a step that asks "expanded", #183) every try is a read
# with the accessibility actions of each node in it: the setting on, the tree,
# the setting off, on the session of that try - a session opened again starts
# from the server's defaults and gets the setting again with the next try.
helper_tree(){ local d out rc i; d="$(run_dir)"; HELPER_WHY=""
  [ "${YUKTI_HELPER:-1}" != 0 ] && [ -n "$d" ] && [ ! -e "$d/helper-off" ] || return 1
  helper_connect || { helper_give_up; return 1; }
  for i in 1 2 3; do
    rc=0
    if [ "${AUI_ACTIONS:-}" = 1 ]; then out="$(helper_actions_read "$(cat "$d/helper-session")")" || rc=$?
    else out="$(helper_http GET "/session/$(cat "$d/helper-session")/source" "$(helper_read_timeout)")" || rc=$?; fi
    case "$rc" in
      0) printf '%s' "$out"; return 0;;
      2) rm -f "$d/helper-port"; helper_connect || { helper_give_up; return 1; };;
      3) rm -f "$d/helper-session" "$(helper_cache)/session-$(helper_key "$(helper_serial)")"
         helper_connect || { helper_give_up; return 1; };;
    esac
  done
  HELPER_WHY="three reads in a row gave no tree"; helper_give_up; return 1; }
# One read with the actions (#183): includeA11yActionsInPageSource on, the tree,
# off again, so no other read carries them. Prints the tree and returns the
# status of the first request that failed, which helper_tree repairs by. A
# server that does not know the setting answers 200 and leaves it out of the
# tree, so a tree without any "actions" is told apart where it is read, not
# here. A session that did not take the setting back is forgotten and a new
# one is opened at once, as after the full tree (#116) - also when the read
# itself failed, so the next try of helper_tree has a session to read on.
helper_actions_read(){ local sid="$1" d out rc=0; d="$(run_dir)"
  helper_http POST "/session/$sid/appium/settings" 5 '{"settings":{"includeA11yActionsInPageSource":true}}' >/dev/null || return $?
  out="$(helper_http GET "/session/$sid/source" "$(helper_read_timeout)")" || rc=$?
  if ! helper_http POST "/session/$sid/appium/settings" 5 '{"settings":{"includeA11yActionsInPageSource":false}}' >/dev/null; then
    rm -f "$d/helper-session" "$(helper_cache)/session-$(helper_key "$(helper_serial)")" 2>/dev/null || true
    helper_connect >/dev/null 2>&1 || true
  fi
  [ "$rc" -eq 0 ] || return "$rc"
  printf '%s' "$out"; }
# The whole screen, rows below the fold included (#116). The helper leaves out
# what is not displayed, so a row below the fold is in no read at all, and a
# search can only swipe until it comes into view. Told to keep such rows
# (allowInvisibleElements), the helper gives each one its place in the content:
# the top is where the row stands in the list, the bottom is pinned to the
# bottom of the list - a box upside down, and the distance to the row. Measured
# on the app under test: 412 nodes in 196 ms against 156 in 73 ms on a long
# screen; a lazy list holds no rows below the fold, and gives the same either way.
#
# The setting is on for this one read and off again on the same session, so no
# other read sees rows that are not on the screen. The read goes past aui(): it
# is not held, not counted among the step's reads and not kept as the tree of a
# failure. Prints the tree, or returns 1 and the search goes on without it. A
# session that did not take the setting back is forgotten, here and in the
# cache, and a new one is opened at once - it starts from the server's defaults,
# and helper_session sets the wait again; the gesture that follows needs one.
helper_full_tree(){ local d sid out="" rc=0 t0 n; d="$(run_dir)"; t0="$(now)"
  sid="$(cat "$d/helper-session" 2>/dev/null || true)"; [ -n "$sid" ] || return 1
  helper_http POST "/session/$sid/appium/settings" 5 '{"settings":{"allowInvisibleElements":true}}' >/dev/null || rc=$?
  if [ "$rc" -eq 0 ]; then out="$(helper_http GET "/session/$sid/source" "$(helper_read_timeout)")" || rc=$?; fi
  if ! helper_http POST "/session/$sid/appium/settings" 5 '{"settings":{"allowInvisibleElements":false}}' >/dev/null; then
    rm -f "$d/helper-session" "$(helper_cache)/session-$(helper_key "$(helper_serial)")" 2>/dev/null || true
    helper_connect >/dev/null 2>&1 || true
  fi
  if [ "$rc" -ne 0 ]; then printf '  · full tree not read (helper: rc %s)\n' "$rc" >&2; return 1; fi
  n="$(printf '%s' "$out" | grep -o '<node' | wc -l | tr -d ' ' || true)"
  printf '  · full tree %s nodes %d ms\n' "$n" $(( ($(us_of "$(now)") - $(us_of "$t0")) / 1000 )) >&2
  printf '%s' "$out"; }
# Stop the helper on this device, remove its forwards and forget what a kept
# helper left in the cache. For a caller who reads the screen with a plain
# `uiautomator dump` after yukti, and for the end of a suite that kept it.
helper_stop(){ local s p c k; apaths; command -v adb >/dev/null 2>&1 || return 0
  helper_force_stop
  s="${ANDROID_SERIAL:-}"; [ -n "$s" ] || s="$(adb get-serialno 2>/dev/null | tr -d '\r\n' || true)"
  case "$s" in ''|unknown) return 0;; esac
  for p in $(adb forward --list 2>/dev/null | awk -v s="$s" -v r="tcp:$UIA2_PORT" '$1==s && $3==r {print $2}' || true); do
    adb forward --remove "$p" >/dev/null 2>&1 || true
  done
  c="$(helper_cache)"; k="$(helper_key "$s")"; [ -z "$c" ] || rm -f "$c/session-$k" "$c/start-fail-$k" 2>/dev/null || true; }
# At the end of the run that started it, unless the caller asked to keep it.
helper_release(){ [ -n "${YUKTI_RUN_DIR:-}" ] && [ -e "$YUKTI_RUN_DIR/helper-ours" ] || return 0
  [ "${YUKTI_HELPER_KEEP:-}" = 1 ] && return 0
  helper_stop; }
helper_cmd(){ case "${1:-}" in
    stop) helper_stop; ok "screen helper stopped";;
    *) die "usage: yukti helper stop";;
  esac; }
# What each read cost and where it came from, one line on stderr: a step's time
# is a read plus an action, and without this a slow step cannot be put on
# either. The run directory counts them for the line at the end of a flow.
us_of(){ local s="${1%%.*}" f="000000"; case "$1" in *.*) f="${1#*.}000000"; f="${f:0:6}";; esac
  printf '%s' $(( s * 1000000 + 10#$f )); }
read_note(){ local d ms; d="$(run_dir)"; ms=$(( ($(us_of "$(now)") - $(us_of "$2")) / 1000 ))
  printf '  · read %s %d ms\n' "$1" "$ms" >&2
  [ -z "$d" ] || printf 'x' >> "$d/reads-$1" 2>/dev/null || true
  # The last iOS read's cost, beside the flow's record, for the pause of a wait
  # (poll_pause): the read runs in a subshell, so a file carries it out.
  [ "$1" != idb ] || [ -z "${FLOW_REC:-}" ] || printf '%s' "$ms" > "$FLOW_REC.read-ms" 2>/dev/null || true; }
read_summary(){ local d h u f i c r b; d="$(run_dir)"; [ -n "$d" ] || return 0
  h="$(cat "$d/reads-helper" 2>/dev/null || true)"; u="$(cat "$d/reads-dump" 2>/dev/null || true)"
  f="$(cat "$d/helper-fallbacks" 2>/dev/null || true)"
  i="$(cat "$d/reads-idb" 2>/dev/null || true)"; c="$(cat "$d/idb-connects" 2>/dev/null || true)"
  r="$(cat "$d/idb-refused" 2>/dev/null || true)"
  # iOS: the connects are counted too, refused ones apart - a flow that died on
  # its first read still says what the connect did (#175).
  [ $(( ${#i} + ${#c} + ${#r} )) -eq 0 ] || say "screen reads: ${#i} by idb, ${#c} idb connect(s), ${#r} refused"
  # A relaunch for a blank tree (#191) is said at the end of the flow too, not
  # only where it happened: the count of relaunches tried, from the run directory.
  b="$(cat "$d/blank-relaunches" 2>/dev/null || true)"
  [ ${#b} -eq 0 ] || say "relaunched for a blank tree: ${#b}"
  [ $(( ${#h} + ${#u} )) -gt 0 ] || return 0
  say "screen reads: ${#h} by the helper, ${#u} by uiautomator dump, ${#f} fallback(s)"; }
# The resident helper answers first (see helper_tree); the dump below is the
# fallback, and the only reader when YUKTI_HELPER=0.
#
# The dump's own exit status never reaches this side: the status of the round
# trip is that of the last `rm`, and "Killed" goes to the device's stderr. A
# dump killed because a UiAutomation helper holds the device - ours left by a
# kept run, or anybody's Appium - looks exactly like a screen that never
# settled: three empty answers. So before giving up, look for the helper
# process, and name it when it is there.
aui(){ [ -n "$HELD_TREE" ] && { printf '%s' "$HELD_TREE"; return 0; }
  apaths; local xml i f="/sdcard/yukti-dump-$$.xml" t0
  t0="$(now)"
  if xml="$(helper_tree)"; then read_note helper "$t0"; keep_tree "$xml"; printf '%s' "$xml"; return 0; fi
  t0="$(now)"
  for i in 1 2 3; do
    xml="$(adb shell "rm -f $f; uiautomator dump $f >/dev/null 2>&1; cat $f 2>/dev/null; rm -f $f" 2>/dev/null)"
    case "$xml" in *"<hierarchy"*"</hierarchy>"*) read_note dump "$t0"; keep_tree "$xml"; printf '%s' "$xml"; return 0;; esac
    [ "$i" = 3 ] || sleep 0.6
  done
  device_fault
  helper_alive && die "uiautomator produced no usable dump after 3 tries - a UiAutomator helper ($UIA2_PKG) is running on the device and takes every dump down; stop it with 'yukti helper stop'"
  die "uiautomator produced no usable dump after 3 tries - the screen may still be animating"; }
afind(){ apaths; aui | "$PY" -c '
import sys,re,html
# Rank candidates instead of taking the first substring hit. Honors resource-id
# and prefers the interactive field over a nearby static caption — "Email" used
# to hit the "or use email" caption ~100px above the input, and "Password" hit
# the "Forgot Password?" link. A node now must be relevant (query appears in its
# text / content-desc / resource-id) AND scores highest to win; an editable /
# clickable / focusable node outranks a plain caption.
# mode="id": explicit selector. The resource-id segment (the full resource-id
# when the query names the package, ":id/" in it, #177) must match EXACTLY and
# nothing else is considered — a flow that asks for an id gets that element or fails.
# Whitespace is normalised on both sides. unescape turns &#10; into a real line
# break, and a two-line caption would otherwise be assertable only by writing the
# line break into the flow file.
norm=lambda s: " ".join(s.split())
# The oracle compares the query as written; the locator modes keep folding case,
# because a flow author naming a button does not mean its capitalisation.
q_raw=norm(sys.argv[1]); q=q_raw.lower()
mode=(sys.argv[2] if len(sys.argv)>2 else "text")
match=(sys.argv[3] if len(sys.argv)>3 else "exact")
# What to print for the winner. The centre is the tap point and the default;
# "box" asks for the corners the filters below already read, plus the screen
# rect they are judged against, so that a caller can ask for a share of the
# screen without reading the screen a second time. "why" answers in words what
# an empty answer leaves open: "on cx cy" for the winner, else "zero x1 y1 x2 y2"
# for a match of zero area, else "off x1 y1 x2 y2" for one outside the screen,
# else nothing - not in the tree. The iOS path answers the same. "state" (#103)
# prints the centre and then the selected, checked and expanded state of the
# winner: "cx cy true|false true|false|none true|false|none|both|unread" -
# "none" for a node that is not checkable, whose checked="false" says nothing
# (React Native marks a node checkable exactly when accessibilityState has
# "checked"); expanded as expanded_of below words it (#183). "count" (#47) prints how many
# elements match (see pick below). The seventh argument, an index (#46), picks
# one of them instead of the winner and prints it as above; an index past the
# last match leaves with status 5 and the number of matches on its output.
out=(sys.argv[4] if len(sys.argv)>4 else "centre")
xml=sys.stdin.read()
# Nothing arrived: the dump failed and said so on its own line. Status 1 is "the
# screen could not be read"; status 3 below is the different, quieter case where
# a tree did arrive and cannot be judged.
if not xml.strip(): sys.exit(1)
# Screen rect = the bounds of the ROOT node, i.e. the first bounds= in the dump.
# Anything whose centre falls outside it is scrolled away or parked off-screen:
# present in the tree, invisible to the user. Taking the maximum over every node
# instead would let a node larger than the viewport widen the rect - and the rows
# scrolled out of a list are exactly the ones that report such bounds, so the
# filter would loosen on the screens it was written for.
SX1=SY1=SX2=SY2=0
_m=re.search(r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\"", xml)
if _m: SX1,SY1,SX2,SY2=map(int,_m.groups())
# No usable screen rect means the off-screen filter cannot run. A tap may still be
# worth attempting, but a check that cannot check must not report success - and
# assertId is as much an oracle as assertText. tapId loses nothing by it: it does
# not scroll, and a tap outside the window is useless anyway.
#
# Status 3, not silence: an empty answer means "the element is not there", and a
# negative assertion or a `when` condition PASSES on that answer. The screen that
# cannot be judged has to say so in a way the caller can read.
if mode in ("assert","id") and not (SX2>SX1 and SY2>SY1): sys.exit(3)
# "in" (#102): an assertion limited to one element. The element is the one tapId
# would tap - the first node whose resource-id segment (or full resource-id, for
# a value with ":id/", #177) is the id, of real size,
# its centre on the screen - and the candidates are that node and the nodes that
# lie within its bounds; every other text on the screen is ignored. No such
# element is status 4: the screen was read and the element the check is about
# is not on it, which is neither "the text is missing" nor "unreadable". The iOS
# path does the same by frame.
# tapText takes the same "in" (#146): a link that is part of a longer text is
# looked for inside the element that holds the text. With "in" a candidate is
# an element whose whole text or label is the value; one that only contains it
# is a longer text, and its centre is not the link, wherever the id sits - on
# the text itself or on a view around it. When such texts are the only places
# the words are, status 11 says so (10 belongs to kb_before_swipe, a number no lookup
# returns): the words have no element of their own
# (React Native gives a nested Text one only with accessibilityRole="link"),
# and a tap on a centre would prove nothing.
# assertCountId takes it too (#47): the options inside one row, counted by id.
scope=(sys.argv[6].lower() if len(sys.argv)>6 else ""); sbox=None; part=False
if scope and mode=="text" and not (SX2>SX1 and SY2>SY1): sys.exit(3)
if scope and mode in ("assert","text","id"):
    for m in re.finditer(r"<node\b[^>]*>", xml):
        tag=m.group(0)
        r=re.search(r"resource-id=(?:\"([^\"]*)\"|\x27([^\x27]*)\x27)",tag)
        rv=norm(html.unescape(r.group(1) if r.group(1) is not None else r.group(2))).lower() if r else ""
        if not r or (rv if ":id/" in scope else rv.split("/")[-1])!=scope: continue
        b=re.search(r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\"",tag)
        if not b: continue
        x1,y1,x2,y2=map(int,b.groups())
        if not (x2>x1 and y2>y1): continue
        cx,cy=(x1+x2)//2,(y1+y2)//2
        if not (SX1<=cx<SX2 and SY1<=cy<SY2): continue
        sbox=(x1,y1,x2,y2); break
    if sbox is None: sys.exit(4)
best=None; best_box=None; best_score=0; zero=None; off=None; best_state=None
# A tree read with the rows below the fold (#116, helper_full_tree) is asked in
# two more ways. Such a row comes upside down: its top is where it stands in the
# content, its bottom is pinned to the bottom of the list. "full" looks for the
# element as always, and a match upside down counts when its centre on x is
# inside the list and its top is below the visible part of it (the fifth
# argument: "x1 x2 top bottom" of that part). Prints "on cx cy" for a match on
# the screen, else "below T" - the nearest of the best matches below, the
# search goes down - else nothing. "fullend" asks for no element: "below T" of
# the lowest row below the fold, or nothing when there is none. Boxes upside
# down anywhere else stay what they always were - of zero area.
full=out in ("full","fullend"); low=None
if full:
    C1,C2,A1,A2=map(int,sys.argv[5].split())
    def below(x1,y1,x2,y2): return x2>x1 and y2<y1 and C1<=(x1+x2)//2<C2 and y1>A2
if out=="fullend":
    for m in re.finditer(r"<node\b[^>]*>", xml):
        b=re.search(r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\"",m.group(0))
        if b and below(*map(int,b.groups())) and (low is None or int(b.group(2))>low): low=int(b.group(2))
    if low is not None: print("below",low)
    sys.exit(0)
# Corners (x1,y1,x2,y2): a lies entirely inside b and is not b itself. The iOS
# path defines the same function; keep the two identical. A tap match scores at
# least 2 and best_score starts below that, so a tie never meets an empty winner.
def inside(a,b): return b[0]<=a[0] and b[1]<=a[1] and a[2]<=b[2] and a[3]<=b[3] and a!=b
# "index" (#46) and the count (#47) ask for every match, not for the winner,
# and both read the one list built here: the candidates that pass the filters
# the winner passes (inside "in", of real size, the centre on the screen) and
# rank equally best. A tied match that holds another tied match within it is the
# frame around that control, not a second control - the tie rule of the single
# lookup, applied here in every mode: a row whose label sits on the row and on
# the text inside it is one row to a count, as it is on iOS, where the two
# arrive merged. Two tied matches with the same box are one control too (a
# wrapper the size of its child); the first in the tree stands for both. The
# list is in the order of the screen: rows top to bottom, then left
# to right by the centre of the frame. Elements are one row when their vertical
# centres differ by less than half the height of the smaller one, measured from
# the first element of the row. Dump order is not used: uiautomator returns a
# tree and idb a flat list in traversal order, and the two disagree. The iOS
# path defines the same function; keep the two identical.
def pick(cands):
    if not cands: return []
    top=max(c[0] for c in cands); ms=[c for c in cands if c[0]==top]
    ms=[c for i,c in enumerate(ms) if not any(o[1]==c[1] for o in ms[:i]) and not any(inside(o[1],c[1]) for o in ms)]
    ms.sort(key=lambda c:((c[1][1]+c[1][3])/2,(c[1][0]+c[1][2])/2))
    rows=[]
    for c in ms:
        cy=(c[1][1]+c[1][3])/2; h=c[1][3]-c[1][1]
        if rows and abs(cy-rows[-1][0])<min(h,rows[-1][1])/2: rows[-1][2].append(c)
        else: rows.append((cy,h,[c]))
    return [c for r in rows for c in sorted(r[2],key=lambda c:(c[1][0]+c[1][2])/2)]
idx=(sys.argv[7] if len(sys.argv)>7 else ""); enum=bool(idx) or out=="count"; cands=[]
# Expanded (#183) has no attribute: React Native gives an expanded node the
# action ACTION_COLLAPSE and a collapsed one ACTION_EXPAND, and the screen
# helper lists the actions of a node in "actions" only when asked to - the read
# of a step that asks "expanded" does (helper_tree). A node with no actions has
# no such attribute, so "none" - no expanded state - needs at least one in the
# tree; a tree with none at all is a read without actions (a plain dump, or a
# helper that did not know the setting): "unread". Both actions at once (a node
# that also declares them in accessibilityActions) cannot be told: "both".
ACTS=re.search(r"<node\b[^>]*\sactions=",xml) is not None
def expanded_of(v):
    acts=[x.strip() for x in v.split(",")]
    col,exp="ACTION_COLLAPSE" in acts,"ACTION_EXPAND" in acts
    if col and exp: return "both"
    if col: return "true"
    if exp: return "false"
    return "none" if ACTS else "unread"
for m in re.finditer(r"<node\b[^>]*>", xml):
    tag=m.group(0)
    def a(n):
        # uiautomator escapes &, < and >. Unescaped, assertText "Terms &
        # Conditions" fails on the very screen that shows it, and assertText
        # "amp" passes on any screen with an ampersand - markup matching through
        # the back door. A value that holds a " is not escaped: uiautomator
        # quotes it with single quotes instead (#100), so both forms are read.
        mm=re.search(n+r"=(?:\"([^\"]*)\"|\x27([^\x27]*)\x27)",tag)
        return norm(html.unescape(mm.group(1) if mm.group(1) is not None else mm.group(2))) if mm else ""
    text_raw=a("text"); desc_raw=a("content-desc")
    text=text_raw.lower(); desc=desc_raw.lower()
    rid=a("resource-id"); rid_seg=rid.split("/")[-1].lower()  # com.app:id/email -> email
    # A query that names the package (com.app:id/email, #177) is the full
    # resource-id and matches only that: it is also the precise choice when two
    # apps on the screen (a system dialog over the app) share a segment.
    rid_key=rid.lower() if ":id/" in q else rid_seg
    cls=a("class"); editable=cls.endswith("EditText")
    clickable=a("clickable")=="true"; focusable=a("focusable")=="true"
    if mode=="id":
        # An empty query must match nothing. The flow runner passes value="" for a
        # missing or misspelled key, and "" is the resource-id of most nodes: the
        # step would then report success and tapId would tap an arbitrary point.
        if not q or q!=rid_key: continue
        score=10
    elif mode=="assert":
        # An assertion is the test oracle: it may only match what a person can
        # perceive - visible text or the accessibility label. Matching a
        # resource-id, a class name or an attribute lets a step pass on markup.
        #
        # The whole label, and the case as written. A substring match made a
        # false green cheap: assertText "net" passed on a screen whose only
        # relevant row said "Network & internet", and a check that passes on
        # three letters of another sentence has not checked anything. A flow
        # that does want the old rule says so: {"match":"contains"}.
        if match=="contains":
            if not (q and (q in text or q in desc)): continue
        else:
            if not (q_raw and q_raw in (text_raw, desc_raw)): continue
        score=10
    else:
        if not (q and (q in rid_seg or q in text or q in desc)): continue
        score=0
        if q==rid_seg: score+=6
        elif q in rid_seg: score+=5
        if q==text or q==desc: score+=4
        elif q in text or q in desc: score+=2
        if editable: score+=3
        if clickable: score+=1
        if focusable: score+=1
    if score<best_score and not enum: continue
    b=re.search(r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\"",tag)
    if not b: continue
    x1,y1,x2,y2=map(int,b.groups())
    if full and below(x1,y1,x2,y2):
        if low is None or score>low[0] or (score==low[0] and y1<low[1]): low=(score,y1)
        continue
    # Outside the element named by "in": not a candidate, not even a near miss.
    if sbox and not (sbox[0]<=x1 and sbox[1]<=y1 and x2<=sbox[2] and y2<=sbox[3]): continue
    if sbox and mode=="text" and q not in (text,desc):
        if q in text or q in desc: part=True
        continue
    if not (x2>x1 and y2>y1):   # zero-area node: in the tree, not on the screen
        if zero is None: zero=(x1,y1,x2,y2)
        continue
    cx,cy=(x1+x2)//2,(y1+y2)//2
    if SX2>SX1 and SY2>SY1 and not (SX1<=cx<SX2 and SY1<=cy<SY2):   # off-screen
        if off is None: off=(x1,y1,x2,y2)
        continue
    if enum:
        cands.append((score,(x1,y1,x2,y2),(cx,cy),("true" if a("selected")=="true" else "false",
                      ("true" if a("checked")=="true" else "false") if a("checkable")=="true" else "none",
                      expanded_of(a("actions")))))
        continue
    # A tie goes to the candidate that lies inside the current winner. A dialog
    # whose whole window carries the label of the button at its bottom ranks both
    # the same, and the window, coming first, took every tap: the centre of the
    # screen was pressed, the button was not, and the step reported success.
    # Someone naming a label means the control, not the frame around it. Equal
    # matches that are not nested - the same button in every row of a list - still
    # go to the first one. The iOS path runs the same test on the same corners.
    if score==best_score and not (mode not in ("assert","id") and inside((x1,y1,x2,y2),best_box)): continue
    best=(cx,cy); best_box=(x1,y1,x2,y2); best_score=score
    best_state=("true" if a("selected")=="true" else "false",
                ("true" if a("checked")=="true" else "false") if a("checkable")=="true" else "none",
                expanded_of(a("actions")))
if enum:
    ms=pick(cands)
    if out=="count": print(len(ms)); sys.exit(0)
    # No match at all is out of range as well, with 0 - except for "why", which
    # then says whether a namesake is at zero size or off the screen, and for
    # tapText with "in" where the words are only part of a longer text: that is
    # status 11, as without an index.
    if not ms and part and not (zero or off): sys.exit(11)
    if not ms and out!="why": print(0,0); sys.exit(5)
    if ms:
        # Past the last: how many were counted, and how many matched with a
        # lower rank and were not (a caption next to the button, for tapText).
        if int(idx)>=len(ms): print(len(ms),sum(1 for c in cands if c[0]<ms[0][0])); sys.exit(5)
        _,bx,c,stt=ms[int(idx)]
        if out=="box": print(bx[0],bx[1],bx[2],bx[3],SX1,SY1,SX2,SY2)
        elif out=="why": print("on",c[0],c[1])
        elif out=="state": print(c[0],c[1],*stt)
        else: print(c[0],c[1])
        sys.exit(0)
if full:
    if best and (low is None or best_score>=low[0]): print("on",best[0],best[1])
    elif low: print("below",low[1])
elif best:
    if out=="box": print(best_box[0],best_box[1],best_box[2],best_box[3],SX1,SY1,SX2,SY2)
    elif out=="why": print("on",best[0],best[1])
    elif out=="state": print(best[0],best[1],*best_state)
    else: print(best[0],best[1])
elif part and not (zero or off): sys.exit(11)
elif out=="why":
    if zero: print("zero",*zero)
    elif off: print("off",*off)
' "$1" "${2:-text}" "${3:-exact}" "${4:-centre}" "${5:-}" "${6:-}" "${7:-}"; }
# Where a horizontal swipe should land, from the dump. A swipe across the middle
# of the screen lands on whatever is there, and an element that does not claim
# the gesture may be pressed instead of scrolled: measured on the app under test,
# a horizontal swipe across a clickable row opened that row's share sheet, and a
# search of eight swipes did it eight times. The dump says which nodes scroll, and
# one that scrolls and is wider than it is tall is what a horizontal swipe is for.
# Prints "cy x1 x2" of the widest such node, or nothing when the screen has none.
ahscroller(){ aui | "$PY" -c '
import re,sys
xml=sys.stdin.read()
best=None
for m in re.finditer(r"<node\b[^>]*>", xml):
    t=m.group(0)
    # No single quote anywhere in this snippet: it lives inside a single-quoted
    # shell string. With one, the string ended here, the rest of the code became
    # shell words, and the lookup answered nothing at all - silently, because a
    # screen with no sideways scroller is a legitimate answer.
    if re.search(r"scrollable=\"true\"", t) is None: continue
    b=re.search(r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\"", t)
    if not b: continue
    x1,y1,x2,y2=map(int,b.groups())
    w,h=x2-x1,y2-y1
    # Taller than wide is a vertical list, whatever else it is.
    if w<=h or w<80 or h<20: continue
    # The WIDEST, which is what the guide and the runbook promise. By area a
    # 900x400 carousel would win over a 1080x100 tab strip, and then the code and
    # the text would mean different things - the area is only the tie-break.
    if best is None or (w,w*h)>(best[0],best[1]): best=(w,w*h,(y1+y2)//2,x1,x2)
if best: print(best[2],best[3],best[4])
'; }
atap(){ apaths; adb shell input tap "$1" "$2"; }
asend(){ local s="$1" q
  # Quote for the ON-DEVICE shell so metacharacters can't expand. Unquoted, a *
  # in a password was glob-expanded by /system/bin/sh (an 8-char password
  # arrived as 11 chars). Single-quote the arg (escaping embedded ' as '\''),
  # then map spaces to %s which `input text` turns back into spaces.
  q=$(printf '%s' "$s" | sed "s/'/'\\\\''/g")
  q=${q// /%s}
  adb shell "input text '$q'" || die "type: the device refused the text"; }
# The focused field as `type` sees it: TPW (masked or not), TN (characters
# shown), TTX (the text). Globals, because the answer is three values and the
# caller has to be able to stop the run when there is no answer.
aread_typed(){ local out
  out="$(afield typed)" || lookup_die $? "type: no text field has focus, so what arrives cannot be checked"
  TPW="${out%%$'\x1f'*}"; out="${out#*$'\x1f'}"; TN="${out%%$'\x1f'*}"; TTX="${out#*$'\x1f'}"; }
# Does the field hold what was sent? Either on its own - the field was empty and
# showed its hint - or after what it held before. A masked field shows one dot
# per character, and the dots are compared as dots: a field that received
# nothing shows its hint, and "Password" is eight characters long. Android also
# leaves the LAST character of a password in the clear for a moment after it is
# typed (the "show passwords" setting, on by default), so dots with that
# character at the end are the same field.
DOT=$'\xe2\x80\xa2'
atyped_is(){ local start="$1" sent="$2" dots="" k
  [ "$TTX" = "$sent" ] || [ "$TTX" = "$start$sent" ] && return 0
  [ "$TPW" = true ] || return 1
  for ((k=1;k<${#sent};k++)); do dots+="$DOT"; done
  case "$TTX" in "$dots$DOT"|"$dots${sent: -1}") return 0;; esac
  return 1; }
# `input text` delivers nothing back. Under load the emulator drops characters
# and the command still exits 0: 22 went in, 15 arrived, and the step reported
# "type 22 chars" (#66). So the value goes in bursts of eight characters - a
# short burst loses less than a long one - and the field is read back once,
# after the last burst. A read costs seconds and a burst does not, so a read
# after every burst made a 22-character value cost three reads where one says
# the same (#106). A field that does not hold what was sent is emptied and typed
# again, three times, before the step fails. The failure names counts and never
# the value: the value may be a password.
atype(){ apaths; local s="$1" shows="${2:-}" e m before start pre="" v i try empty n; m=${#s}
  # What the field has to hold: what was sent, or what a field that filters
  # its input makes of it (#128).
  e="${shows:-$s}"
  # `input text` has key events for ASCII only; anything else never arrives, and
  # three attempts at it would end in counts that are not even characters.
  if printf '%s' "$s" | LC_ALL=C grep -q '[^ -~]'; then die "type: only ASCII text can be typed on Android"; fi
  aread_typed; before="$TTX"; start="$before"; v="$s"
  # Text a masked field already holds is dots, and dots cannot be typed again if
  # the value has to be retyped. Said before the first key, not after a loss:
  # the same flow must not pass on a fast device and fail on a slow one. One
  # character still in the clear is no dot, and it is typed again like any text.
  if [ "$TPW" = true ] && [ "${before//$DOT/}" != "$before" ]; then
    die "type: the masked field already holds text, and it cannot be typed again - clear the field first"
  fi
  for try in 1 2 3; do
    i=0
    while [ "$i" -lt "${#v}" ]; do asend "${v:$i:8}"; i=$((i+8)); done
    aread_typed
    # A field that renders late is not a field that lost characters.
    atyped_is "$start" "$pre$e" || { sleep 0.5; aread_typed; }
    atyped_is "$start" "$pre$e" && { [ "$try" = 1 ] || type_arrived "$try" "$shows" "$m"; return 0; }
    [ "$try" = 3 ] && break
    warn "type: attempt $try lost characters - clearing the field and typing again"
    aerase_typed "$TN"; empty="$TTX"
    # What the field showed before the first key: its hint, or text of its own.
    # Emptied, it shows the hint again, and anything else was the field's own
    # text - typed again in front of the value.
    [ "$try" = 1 ] && [ "$before" != "$empty" ] && pre="$before"
    start="$empty"; v="$pre$s"
  done
  n=0; [ "$TTX" = "$start" ] || n=$(( TN - ${#pre} )); [ "$n" -ge 0 ] || n=0
  type_lost "$n" "$shows" "$m"; }
# Empty the focused field: to the end of the text, one delete per character it
# shows and one more, then one delete as a probe. An empty field does not change
# under it; a field that still holds text does, and typing again on top of that
# would be the same wrong field under a second attempt.
aerase_typed(){ local n="$1" keys probe
  keys="$(printf ' 67%.0s' $(seq 1 $((n+1))))"
  adb shell input keyevent 123 $keys || die "type: the device refused the delete key"
  aread_typed; probe="$TTX"
  adb shell input keyevent 67 || die "type: the device refused the delete key"
  aread_typed
  [ "$TTX" = "$probe" ] || die "type: the field still holds text after deleting it - it cannot be typed again"; }
# Keys are named in the flow file, never numbered: a step that says `66` reads as
# noise and stops being true the moment the platform changes. These six names are
# the whole vocabulary - anything else stops the run instead of pressing nothing.
KEY_NAMES="back enter home delete tab escape"
akey(){ apaths; local c
  case "$1" in back) c=4;; enter) c=66;; home) c=3;; delete) c=67;; tab) c=61;; escape) c=111;;
    *) die "pressKey: no Android key code for '$1'";; esac
  adb shell input keyevent "$c"; }
# The IME's own answer about itself. A soft keyboard draws in its own window and
# never appears in the view dump the flows read, so "is it up" cannot be asked of
# the screen. Three outcomes, not two: up (0), down (1), and the device did not
# answer (2) - answering "down" to the third would let a step report success on a
# device that said nothing.
akb_shown(){ apaths; local s
  s="$(adb shell dumpsys input_method 2>/dev/null | grep -o "mInputShown=[a-z]*" | head -1 | cut -d= -f2 | tr -d "\r")"
  [ -n "$s" ] || return 2
  [ "$s" = true ]; }
# What sits under a point: its class, then its text. The rig has to be able to
# say what a field holds AFTER acting on it - a clear that is not checked is the
# same silent success this tool keeps finding elsewhere - and the class comes
# with it because "the text did not change" proves an empty field only when the
# thing under the point is a field. Aimed at a caption, it proves nothing at all.
# Two questions, one dump. "at" answers what sits under a point - the flow's own
# coordinates, before anything is touched. "focused" answers which text field
# holds focus now, and that is the field the keys will reach: after the keyboard
# opens the layout can move the field out from under the coordinates that opened
# it, and a check that kept hit-testing the old point would be reading a
# different node than the one being cleared. "typed" is "focused" as `type` needs
# it: whether the field masks its text, how many characters it shows, and the
# text itself unescaped, because the field is compared with what was typed and
# the dump writes a typed & as &amp;.
afield(){ apaths; aui | "$PY" -c '
import re,sys,html
mode=sys.argv[1]
# "atn" and "focusedn" are "at" and "focused" that also say, first, how many
# nodes on the screen carry the resource-id of the field (0 for one without):
# clearTextId takes a field by that id when it is the only one (#165).
count=mode in ("atn","focusedn")
if count: mode=mode[:-1]
x0,y0=(int(sys.argv[2]),int(sys.argv[3])) if mode=="at" else (0,0)
best=None; best_area=0; best_edit=False
xml=sys.stdin.read()
# Nothing arrived: the dump failed and aui has already said so. Status 1 is "the
# screen could not be read", and it has to leave here as 1 - status 3 below is
# "the screen was read and there is no such field", which the caller reports in
# its own words. Without this line an unreadable screen left as 3 and clearText
# blamed the point it was aimed at.
if not xml.strip(): sys.exit(1)
for m in re.finditer(r"<node[^>]*?>", xml):
    tag=m.group(0)
    b=re.search(r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\"", tag)
    if not b: continue
    x1,y1,x2,y2=map(int,b.groups())
    if not (x2>x1 and y2>y1): continue
    # Both quote forms: a value that holds a " comes in single quotes (#100), and
    # read only in "..." the field that holds it was not there at all.
    def at(n):
        mm=re.search(n+r"=(?:\"([^\"]*)\"|\x27([^\x27]*)\x27)", tag)
        return "" if mm is None else (mm.group(1) if mm.group(1) is not None else mm.group(2))
    cls=at("class"); edit="EditText" in cls
    if mode in ("focused","typed"):
        if not (edit and at("focused")=="true"): continue
    else:
        if not (x1<=x0<x2 and y1<=y0<y2): continue
    area=(x2-x1)*(y2-y1)
    # The field wins over the row that contains it; among equals, the smaller.
    if best is None or (edit and not best_edit) or (edit==best_edit and area<best_area):
        best=(cls, at("enabled"), at("focusable"), at("resource-id"),
              "%d %d %d %d"%(x1,y1,x2,y2), at("text"), at("password"))
        best_area=area; best_edit=edit
if best is None: sys.exit(3)
if mode=="typed":
    t=html.unescape(best[5])
    sys.stdout.write("%s\x1f%d\x1f%s" % (best[6], len(t), t)); sys.exit(0)
best=best[:6]
if count:
    # Both quote forms, as at() reads them. A field without an id has no
    # namesakes to tell apart and no id to be taken by: 0.
    # findall gives "" for the form that did not match, never None.
    ids=[a or b for a,b in
         re.findall(r"<node[^>]*?resource-id=(?:\"([^\"]*)\"|\x27([^\x27]*)\x27)", xml)]
    sys.stdout.write("%d\x1f" % (ids.count(best[3]) if best[3] else 0))
sys.stdout.write("%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s" % best)
' "$@"; }
# Two rectangles "x1 y1 x2 y2" with the same left and right edges and the same
# height: one field moved straight up or down, which is what a keyboard does.
same_column(){ local a1 b1 a2 b2 c1 d1 c2 d2
  read -r a1 b1 a2 b2 <<<"$1"; read -r c1 d1 c2 d2 <<<"$2"
  [ "$a1" = "$c1" ] && [ "$a2" = "$c2" ] && [ $((b2 - b1)) -eq $((d2 - d1)) ]; }
# The focused field after the tap is the field the step was given (#165): the
# same rectangle; or the same resource id and the same column, when <column> is
# 1 - a keyboard moved the field straight up; or, for clearTextId, a non-empty
# id that only this field carries on the screen, before the tap and after it.
# Then the field may have moved anywhere and changed its width (a form that
# scrolled when focus moved, a clear button that goes away with the text). An
# id that several fields share (list rows, repeated rows of a form) settles
# nothing by itself.
# same_field <vb> <column> <res> <box> <n before> <res2> <box2> <n after>
same_field(){ [ "$4" = "$7" ] && return 0
  [ "$3" = "$6" ] || return 1
  [ "$2" = 1 ] && same_column "$4" "$7" && return 0
  case "$1" in clearTextId*) [ -n "$3" ] && [ "$5" = 1 ] && [ "$8" = 1 ];; *) return 1;; esac; }
# Select all, then one delete. Forty blind deletes were a guess about how much
# was in the field and about where the caret sat; two calls are neither. The
# result is then read back, because the only fact that matters here is the state
# of the field, not that the keys were accepted.
aclear(){ apaths; local x="$1" y="$2" vb="${3:-clearText}" sdk before after probe
  sdk="$(adb shell getprop ro.build.version.sdk 2>/dev/null | tr -d "\r")"
  case "$sdk" in ""|*[!0-9]*) die "$vb: the device did not report its Android version";; esac
  # The version is the first line and it does stop the run here. What it cannot
  # cover is the line below it: on API 30 the shell answers an unknown command
  # with its usage text and exit code 0, so `|| die` after the key combination
  # is blind there. The read-back at the end is what holds if this threshold
  # ever turns out to be wrong again. No quiet fallback to deleting character by
  # character: a clear that only looks like one is what this verb exists to end.
  [ "$sdk" -ge 31 ] || die "$vb needs Android 12 (API 31) or newer - 'input keycombination' does not exist on API $sdk"
  local cls enb fcb res box out res2 box2 txt2 st pre="" prebox="" asked="" n1 n2
  # What the flow aimed at, read BEFORE the tap: a disabled or read-only field
  # takes no focus and no keys, and its text would sit there unchanged through
  # select-all, delete and the probe below - three readings agreeing on a lie.
  # The same read says which field holds focus before the tap, and clearTextId
  # has already found the field in it: one tree for everything known before the
  # first touch (#106).
  [ -n "$HELD_TREE" ] || { HELD_TREE="$(aui)" || exit 1; }
  st=0; out="$(afield atn "$x" "$y")" || st=$?
  [ "$st" -eq 0 ] || { HELD_TREE=""; lookup_die "$st" "$vb: no element at $x,$y"; }
  IFS=$'\x1f' read -r n1 cls enb fcb res box before <<<"$out"
  st=0; pre="$(afield focused)" || st=$?
  HELD_TREE=""
  case "$st" in 0) IFS=$'\x1f' read -r _ _ _ _ prebox _ <<<"$pre";; 3) ;; *) lookup_die "$st";; esac
  case "$cls" in *EditText*) ;; *) die "$vb: the element at $x,$y is a ${cls:-node with no class}, not a text field";; esac
  [ "$enb" = true ] || die "$vb: the field at $x,$y is disabled - it takes no keys"
  [ "$fcb" = true ] || die "$vb: the field at $x,$y cannot take focus - the keys would go elsewhere"
  adb shell input tap "$x" "$y" || die "$vb: the device refused the tap on the field"
  # From here on the focused field is the subject: it is the one the keys reach.
  # Which is only safe once it is the SAME field - a tap that opened a picker,
  # or landed on a keyboard the dump does not show, leaves focus where it was,
  # and clearing that field would be reported as clearing this one. Focus can
  # only stay in ANOTHER field if another field had it before the tap. Then the
  # field is asked for before any key, and a wrong one is left untouched.
  # Otherwise the read after the keys answers both questions at once (#106).
  if [ -n "$prebox" ] && [ "$prebox" != "$box" ]; then
    out="$(afield focusedn)" || die "$vb: the tap at $x,$y did not put focus in a text field"
    IFS=$'\x1f' read -r n2 cls enb fcb res2 box2 txt2 <<<"$out"
    # Two ids that differ settle it. Two that MATCH settle nothing: a resource id
    # is not unique - the rows of a list and the repeated rows of a form share
    # one. So the second question is asked every time: the same rectangle, or the
    # same text it had before the tap, or an id only this field carries (#165:
    # the form scrolled when focus moved). The column proves nothing here: focus
    # left in the field above sits in the same column. A field that is none of
    # these is another field.
    if [ -n "$res" ] && [ -n "$res2" ] && [ "$res" != "$res2" ]; then
      die "$vb: focus is in a different field ($res2), not the one at $x,$y ($res)"
    fi
    if [ "$box" != "$box2" ] && [ "$before" != "$txt2" ] \
       && ! same_field "$vb" 0 "$res" "$box" "$n1" "$res2" "$box2" "$n2"; then
      die "$vb: focus is in a different field than the one at $x,$y"
    fi
    asked=1
  fi
  adb shell input keycombination 113 29 || die "$vb: the device refused select-all (Ctrl+A)"
  adb shell input keyevent 67 || die "$vb: the device refused the delete key"
  st=0; out="$(afield focusedn)" || st=$?
  [ "$st" -eq 0 ] || lookup_die "$st" "$vb: the tap at $x,$y did not put focus in a text field"
  IFS=$'\x1f' read -r n2 cls enb fcb res2 box2 after <<<"$out"
  # Nothing else held focus before the tap, so the focused field is the one the
  # tap reached - or the one a picker it opened brought up. The ids tell them
  # apart when both have one. The rectangle does it the rest of the time: the
  # keyboard moves a field up the screen and leaves its left and right edges
  # and its height alone. The text it had cannot be the proof here, as it was
  # before the keys - the keys have just removed it.
  if [ -z "$asked" ]; then
    if [ -n "$res" ] && [ -n "$res2" ] && [ "$res" != "$res2" ]; then
      die "$vb: focus is in a different field ($res2), not the one at $x,$y ($res)"
    fi
    # A node keeps its resource id when the keyboard moves it, so a rectangle that
    # changed has to bring the same id with it - an empty one included.
    same_field "$vb" 1 "$res" "$box" "$n1" "$res2" "$box2" "$n2" \
      || die "$vb: focus is in a different field than the one at $x,$y"
  fi
  if [ "$box" != "$box2" ]; then
    warn "$vb: the field moved to $box2 after the tap (a keyboard, a scrolled form or a field that grew)"
  fi
  [ -n "$after" ] || { ok "$vb: field empty at $x,$y"; return 0; }
  # Any text left is unresolved, whatever it is and whether or not it changed:
  # an EditText with nothing in it reports its HINT in the same attribute that
  # carries its text, and a select-all that did not take leaves the delete to
  # remove ONE character - which also changes the text and would read as
  # success. One more delete separates the two: on an empty field it changes
  # nothing, on a field still holding text it takes another character.
  adb shell input keyevent 67 || die "$vb: the device refused the delete key"
  out="$(afield focused)" || lookup_die $? "$vb: nothing on the screen has focus"
  IFS=$'\x1f' read -r cls enb fcb res box probe <<<"$out"
  [ "$probe" = "$after" ] || die "$vb: the field still holds text after select-all and delete"
  ok "$vb: field empty at $x,$y"; }

# ── doctor: verify/report the toolchain ──────────────────────────────────────
doctor(){
  paths; local bad=0
  say "yukti v$YUKTI_VERSION — environment check"
  if xcrun simctl help >/dev/null 2>&1; then ok "Xcode + simctl"; else die "Full Xcode required (not just CLT). Install Xcode, then: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer"; fi
  xcrun simctl list runtimes 2>/dev/null | grep -qi ios && ok "iOS simulator runtime" || { warn "no iOS runtime — installing"; xcodebuild -downloadPlatform iOS; }
  command -v node >/dev/null && ok "node $(node -v)" || { warn "node@22 missing"; bad=1; echo "   brew install node@22"; }
  command -v pod  >/dev/null && ok "cocoapods $(pod --version)" || { warn "cocoapods missing"; bad=1; echo "   brew install cocoapods"; }
  command -v idb  >/dev/null && ok "idb (UI driver)" || { warn "idb missing"; bad=1; echo "   brew trust facebook/fb && brew install idb-companion && $PY -m pip install --user fb-idb"; }
  # Optional: setPermission needs it for camera, notifications and health (#51).
  command -v applesimutils >/dev/null && ok "applesimutils (setPermission: camera, notifications, health)" || { warn "applesimutils missing - setPermission cannot set camera, notifications or health"; echo "   brew tap wix/brew && brew install applesimutils"; }
  [ "$(cfg easEnabled false)" = "True" -o "$(cfg easEnabled false)" = "true" ] && { command -v npx >/dev/null && ok "npx (for EAS adapter)"; }
  [ $bad -eq 0 ] && ok "ready" || die "install the tools above, then re-run 'yukti doctor'"
}

# ── device-only-lib scan: static frameworks lacking an arm64-simulator slice ──
# (These break arm64 sim linking; exclude them from iOS autolinking for the rig.)
scan(){
  app_dir; say "scanning ios/Pods for device-only frameworks (no arm64-sim slice)…"
  find ios/Pods -type f -path "*.framework/*" ! -path "*.xcframework/*" 2>/dev/null | while read -r f; do
    file "$f" 2>/dev/null | grep -q "Mach-O" || continue
    lipo -info "$f" 2>/dev/null | grep -q arm64 || continue
    vtool -show-build "$f" 2>/dev/null | grep -qi SIMULATOR || echo "  device-only: $(echo "$f" | sed -E 's#.*/Pods/([^/]+)/.*#\1#')"
  done | sort -u
  warn "add the npm packages that vendor these to config .excludeIosAutolink[]"
}

# ── write react-native.config.js to drop device-only libs from iOS autolinking ─
write_rn_excludes(){
  app_dir; local ex; ex="$(cfg excludeIosAutolink '[]')"
  [ "$ex" = "[]" ] && return 0
  [ -f react-native.config.js ] && [ ! -f .yukti.rnconfig.bak ] && cp react-native.config.js .yukti.rnconfig.bak
  "$PY" - "$ex" > react-native.config.js <<'PY'
import json,sys
pkgs=json.loads(sys.argv[1])
deps=",\n".join(f"    {json.dumps(p)}: {{ platforms: {{ ios: null }} }}" for p in pkgs)
print("// AUTO-GENERATED by yukti — device-only libs w/o arm64-sim slice, excluded for sim builds.\n"
      "module.exports = {\n  dependencies: {\n"+deps+"\n  },\n};")
PY
  ok "react-native.config.js excludes: $(echo "$ex" | "$PY" -c 'import json,sys;print(", ".join(json.load(sys.stdin)))')"
}

# ── build a signed arm64 simulator .app for a variant ────────────────────────
build(){
  local V="${1:?usage: yukti build <variant>}"
  is_android && { build_android "$V"; return; }
  app_dir; paths
  local scheme cfgn env dd
  scheme="$(cfg variants.$V.scheme)";        [ -n "$scheme" ] || die "unknown variant '$V'"
  cfgn="$(cfg variants.$V.configuration)"
  env="$(cfg variants.$V.envFile)"
  dd="ios/.yukti-build/$V"
  say "building '$V'  (scheme='$scheme' config='$cfgn')"
  [ -n "$env" ] && [ -f "$env" ] && cp "$env" .env.local && ok "env: $env → .env.local" || warn "no envFile for '$V' (config .variants.$V.envFile)"
  write_rn_excludes
  ( cd ios && pod install >/dev/null 2>&1 ) && ok "pods installed"
  local appvar; appvar="$(cfg variants.$V.appVariant "$V")"
  NODE_ENV="$(cfg variants.$V.nodeEnv development)" APP_VARIANT="$appvar" EXPO_VARIANT_EXPLICIT=1 \
  xcodebuild -workspace "$(cfg workspace)" -scheme "$scheme" -configuration "$cfgn" \
    -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' -derivedDataPath "$dd" \
    ARCHS=arm64 ONLY_ACTIVE_ARCH=NO EXCLUDED_ARCHS=x86_64 \
    CODE_SIGN_IDENTITY="-" CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM="" PROVISIONING_PROFILE_SPECIFIER="" \
    build >/dev/null || die "xcodebuild failed — run without >/dev/null to see errors, or 'yukti scan' for device-only libs"
  # NB: ad-hoc CODE_SIGN_IDENTITY="-" keeps entitlements (keychain) so Firebase/auth works.
  #     CODE_SIGNING_ALLOWED=NO would strip them → -34018 keychain → login 401s.
  local app; app="$(find "$dd/Build/Products" -maxdepth 2 -name '*.app' | head -1)"
  [ -n "$app" ] || die "build produced no .app"
  echo "$app" > "${TMPDIR:-/tmp}/yukti-app-$V"
  ok "built: $app"
}

# ── pull an OFFICIAL simulator build from EAS (optional adapter) ──────────────
pull_eas(){
  local V="${1:?usage: yukti pull <variant>}"; app_dir; paths
  [ -f /tmp/expotoken ] || [ -n "${EXPO_TOKEN:-}" ] || die "set EXPO_TOKEN (or /tmp/expotoken) for the EAS adapter"
  local tok profile; tok="${EXPO_TOKEN:-$(cat /tmp/expotoken)}"; profile="$(cfg variants.$V.easProfile simulator)"
  say "triggering EAS simulator build (profile='$profile') — cloud, ~15 min"
  EXPO_TOKEN="$tok" npx eas-cli build --platform ios --profile "$profile" --non-interactive --wait || die "eas build failed (does eas.json have a '$profile' profile with ios.simulator=true?)"
  local url; url="$(EXPO_TOKEN="$tok" npx eas-cli build:list --platform ios --limit 1 --json --non-interactive 2>/dev/null | "$PY" -c 'import json,sys;print(json.load(sys.stdin)[0]["artifacts"]["applicationArchiveUrl"])')"
  say "downloading $url"; curl -sL "$url" -o /tmp/yukti-eas.tar.gz
  local out="ios/.yukti-build/eas-$V"; rm -rf "$out"; mkdir -p "$out"; tar -xzf /tmp/yukti-eas.tar.gz -C "$out"
  local app; app="$(find "$out" -maxdepth 2 -name '*.app' | head -1)"
  [ -n "$app" ] || die "EAS archive had no .app (was it a device .ipa? need a simulator profile)"
  echo "$app" > "${TMPDIR:-/tmp}/yukti-app-$V"; ok "pulled: $app"
}

# ── simulator lifecycle ──────────────────────────────────────────────────────
boot(){
  is_android && { boot_android; return; }
  paths; local dev rt u
  dev="$(cfg simulator.device 'iPhone 16 Pro')"
  u="$(xcrun simctl list devices | grep -m1 "$dev (" | grep -oE '[0-9A-F-]{36}' || true)"
  if [ -z "$u" ]; then
    rt="$(xcrun simctl list runtimes | grep -i ios | grep -oE 'com.apple.CoreSimulator.SimRuntime.iOS[^ ]*' | tail -1)"
    local dt; dt="$(xcrun simctl list devicetypes | grep -oE "com.apple.CoreSimulator.SimDeviceType.$(echo "$dev" | tr ' ' '-')" | head -1)"
    u="$(xcrun simctl create "yukti-$dev" "$dt" "$rt")"; ok "created $dev"
  fi
  xcrun simctl boot "$u" 2>/dev/null || true
  xcrun simctl bootstatus "$u" -b >/dev/null 2>&1 || true
  open -a Simulator
  echo "$u" > "$(udid_file)"; ok "booted $dev ($u)"
}
# The flag is read wherever it sits on the line, like `flow --check`: an option
# silently taken for the variant name is the kind of miss that ends as a run
# against the wrong build.
install(){ local V='' apk='' a
  while [ $# -gt 0 ]; do a="$1"; shift
    case "$a" in
      --apk) [ -z "$apk" ] || die "one --apk at a time - usage: yukti install [--apk <path>] <variant>"
             [ $# -gt 0 ] || die "--apk needs a path - usage: yukti install [--apk <path>] <variant>"
             apk="$1"; [ -n "$apk" ] || die "--apk needs a path - usage: yukti install [--apk <path>] <variant>"; shift;;
      --apk=*) [ -z "$apk" ] || die "one --apk at a time - usage: yukti install [--apk <path>] <variant>"
               apk="${a#--apk=}"; [ -n "$apk" ] || die "--apk needs a path - usage: yukti install [--apk <path>] <variant>";;
      -*) die "unknown option '$a' - usage: yukti install [--apk <path>] <variant>";;
      *) [ -z "$V" ] || die "one variant at a time - usage: yukti install [--apk <path>] <variant>"; V="$a";;
    esac
  done
  [ -n "$V" ] || die "usage: yukti install [--apk <path>] <variant>"
  is_android && { install_android "$V" "$apk"; return; }
  [ -z "$apk" ] || die "--apk installs an Android APK and this run is iOS - 'install' takes the .app that 'yukti build $V' or 'yukti pull $V' left"
  paths; local u app; u="$(cat "$(udid_file)")"; app="$(cat "${TMPDIR:-/tmp}/yukti-app-$V")"
  xcrun simctl install "$u" "$app" && ok "installed $(basename "$app")"; }
launch(){ local V="${1:?variant}"; is_android && { launch_android "$V"; return; }; paths; local u b; u="$(cat "$(udid_file)")"; b="$(cfg variants.$V.bundleId)"
  xcrun simctl launch "$u" "$b" && ok "launched $b"; }
# A flow inherits whatever the flow before it left behind - the session, the
# onboarding, cached content, a half-filled form. The same flow is then green
# alone and red in a suite, and nothing in the report says why. Nothing in the
# vocabulary dropped that state: `launch` on Android goes through `monkey`,
# which brings a RUNNING app to the front, and `install` uses `adb install -r`,
# which keeps the data of the previous install on purpose.
#
# Both steps take the variant name, the way `launch` does, so the package and
# the bundle id come from the config and never from the flow file.
# The platform of a step is the platform of the RUN. Asking the config for the
# variant alone is not that: a variant that names no platform of its own does
# not make the step iOS, and a config that names the platform once at the top
# level is legal - so a step reading the variant on its own would take the iOS
# path in the middle of an Android run. The run's platform is resolved once
# before the command starts, and that is what every drive primitive reads.
# Honour a variant that names its own platform, and otherwise follow the run.
step_platform(){ local V="$1" p; p="$(cfg "variants.$V.platform")"; printf '%s' "${p:-$YUKTI_PLATFORM}"; }
stop_app(){ local V="${1:-}" plat; [ -n "$V" ] || die "stopApp needs a variant name - the one used in $CONFIG"
  plat="$(step_platform "$V")"
  if [ "$plat" = android ]; then apaths; local pkg installed; pkg="$(cfg variants.$V.package)"
    [ -n "$pkg" ] || die "stopApp: variant '$V' has no 'package' in $CONFIG"
    # `am force-stop` prints nothing and exits zero for a package that is not
    # installed, exactly as for one that is. Without this probe the step reports
    # a stop that never happened every time the config carries a typo.
    installed="$(adb shell pm list packages 2>/dev/null | tr -d '\r')" || true
    # An empty list means the device did not answer, not that the app is gone:
    # without this the step blames the package name for an unreachable device
    # and sends the reader to fix the config.
    [ -n "$installed" ] || die "stopApp: could not read the package list from the device"
    case "
$installed
" in *"
package:$pkg
"*) ;; *) die "stopApp: '$pkg' is not installed on the device";; esac
    adb shell am force-stop "$pkg" || die "stopApp: force-stop failed for '$pkg'"
    ok "stopped $pkg"; return; fi
  paths; local u b; u="$(cat "$(udid_file)" 2>/dev/null)" || true
  [ -n "$u" ] || die "stopApp: no simulator recorded in $(udid_file) - run 'yukti up <variant>' first"
  b="$(cfg variants.$V.bundleId)"
  [ -n "$b" ] || die "stopApp: variant '$V' has no 'bundleId' in $CONFIG"
  # simctl refuses when the app is not running, and "not running" is the state
  # this step exists to reach: that refusal is a warning, not a failure.
  # Any refusal from simctl reads as "it was not running" here, including a
  # simulator that is not booted. The narrower form needs a Mac to write and to
  # check; the runbook names the gap rather than implying it is closed.
  xcrun simctl terminate "$u" "$b" 2>/dev/null && ok "stopped $b" || warn "stopApp: '$b' was not running (or the simulator refused)"; }
clear_state(){ local V="${1:-}" plat; [ -n "$V" ] || die "clearState needs a variant name - the one used in $CONFIG"
  plat="$(step_platform "$V")"
  [ "$plat" = android ] || die "clearState is Android-only for now - see RUNBOOK; on iOS reinstall the app between flows"
  apaths; local pkg out; pkg="$(cfg variants.$V.package)"
  [ -n "$pkg" ] || die "clearState: variant '$V' has no 'package' in $CONFIG"
  # `pm clear` says what happened in words, and its exit status does not agree
  # across platform versions: "Failed" comes back with status 1 on API 35 and
  # with status 0 elsewhere. The word is the evidence, so the step reads the
  # word, anchored at the start of the answer - stderr lands in the same string
  # and a warning that merely contains "Success" must not pass for one. `|| true`
  # is there for one reason: under `set -e` the step would otherwise die before
  # reading the answer, with no message at all.
  out="$(adb shell pm clear "$pkg" 2>&1 | tr -d '\r')" || true
  case "$out" in
    Success*) ok "cleared $pkg - the app is stopped now, launch it before the next step";;
    *) die "clearState: pm clear refused '$pkg': ${out:-no output}";;
  esac; }
# background, foreground, relaunch (#53). launch starts the app, stopApp stops it
# and clearState wipes it; nothing sat between. A screen rebuilt from saved state
# after a trip to the home screen, a session that survives a kill and what the
# task switcher shows all live behind these three.
#
# They act on the app of $YUKTI_VARIANT, as openUrl and setPermission do:
# background carries its seconds in "value", so the variant cannot travel there,
# and one rule for the three is easier to keep than two.
#
# Each one asks the device what happened instead of trusting the command. A Home
# that did not land, a launch that left the home screen in front, an app the
# system killed while it was away and came back as a new process - each of these
# used to be a step that passed.
bg_app(){ local verb="$1" V
  V="${YUKTI_VARIANT:-}"
  [ -n "$V" ] || die "$verb: this run does not know which app it is about - set \$YUKTI_VARIANT to the variant in $CONFIG"
  [ -n "$(cfg "variants.$V")" ] || die "$verb: there is no variant '$V' in $CONFIG"
  APP_V="$V"; APP_PLAT="$(step_platform "$V")"
  if [ "$APP_PLAT" = android ]; then apaths; APP_ID="$(cfg "variants.$V.package")"
    [ -n "$APP_ID" ] || die "$verb: variant '$V' has no 'package' in $CONFIG"
    return; fi
  paths; APP_ID="$(cfg "variants.$V.bundleId")"
  [ -n "$APP_ID" ] || die "$verb: variant '$V' has no 'bundleId' in $CONFIG"
  APP_UDID="$(cat "$(udid_file)" 2>/dev/null)" || true
  [ -n "$APP_UDID" ] || die "$verb: no simulator recorded in $(udid_file) - run 'yukti up <variant>' first"
  APP_NAME="$(ios_app_name)" || true
  [ -n "$APP_NAME" ] || die "$verb: could not read the name of '$APP_ID' from its Info.plist on the simulator - is it installed?"; }
# The name the root element of the tree carries while the app is in front: the
# display name of the installed build, else its bundle name. Read from the build
# itself, so the config holds nothing more than the bundle id.
ios_app_name(){ local dir
  dir="$(xcrun simctl get_app_container "$APP_UDID" "$APP_ID" app 2>/dev/null)" || return 1
  [ -n "$dir" ] && [ -f "$dir/Info.plist" ] || return 1
  "$PY" -c 'import plistlib, sys
with open(sys.argv[1], "rb") as fh: d = plistlib.load(fh)
n = d.get("CFBundleDisplayName") or d.get("CFBundleName") or ""
sys.stdout.write(" ".join(n.split()) if isinstance(n, str) else "")' "$dir/Info.plist"; }
# Who is in front: 0 the app of this run, 1 something else, 2 no answer. APP_SEEN
# holds what was there. Android names the window with focus by its package; a
# moment with no focused window (an animation) is no answer rather than "someone
# else", or a Home still on its way would pass for one that landed. iOS: the
# root element of the tree is the app in front, labelled with its display name,
# and " " on the home screen (measured, iOS 26.5).
app_front(){ local out line
  APP_SEEN=""
  if [ "$APP_PLAT" = android ]; then
    out="$(adb shell "dumpsys window | grep -E 'mCurrentFocus|mFocusedApp'" 2>/dev/null | tr -d '\r')" || true
    line="$(printf '%s\n' "$out" | grep -m1 'mCurrentFocus=')" || line="$(printf '%s\n' "$out" | grep -m1 'mFocusedApp=')" || return 2
    APP_SEEN="$(printf '%s\n' "${line#*=}" | sed -nE 's/.* u[0-9]+ +([A-Za-z0-9_.]+)\/.*/\1/p' | head -1)"
    [ -n "$APP_SEEN" ] || return 2
    [ "$APP_SEEN" != "$APP_ID" ] || return 0
    return 1; fi
  out="$(HELD_TREE="" ui 2>/dev/null)" || return 2
  APP_SEEN="$(printf '%s' "$out" | "$PY" -c 'import json, sys
try: t = json.load(sys.stdin)
except ValueError: sys.exit(2)
r = next((e for e in t if isinstance(e, dict) and e.get("type") == "Application"), None) if isinstance(t, list) else None
if r is None: sys.exit(2)
sys.stdout.write(" ".join(str(r.get("AXLabel") or "").split()))')" || return 2
  [ "$APP_SEEN" != "$APP_NAME" ] || return 0
  [ -n "$APP_SEEN" ] || APP_SEEN="the home screen"
  return 1; }
# Ask app_front every half second, for up to $2 seconds, until it answers $1.
app_wait(){ local want="$1" n=$(( $2 * 2 )) st
  while :; do st=0; app_front || st=$?
    [ "$st" -ne "$want" ] || return 0
    n=$((n - 1)); [ "$n" -gt 0 ] || return 1
    sleep .5; done; }
seen_words(){ [ -z "$APP_SEEN" ] || printf ' - in front: %s' "$APP_SEEN"; }
# The process of the app, nothing when it is not running. iOS lists a running app
# in launchctl as UIKitApplication:<bundle id>[...], its pid first.
app_pid(){ if [ "$APP_PLAT" = android ]; then adb shell pidof "$APP_ID" 2>/dev/null | tr -d '\r' | awk '{ print $1; exit }'
  else xcrun simctl spawn "$APP_UDID" launchctl list 2>/dev/null | awk -v l="UIKitApplication:$APP_ID[" 'index($3, l) == 1 && $1 != "-" { print $1; exit }'; fi; }
# Android: the launcher intent launch already sends, which resumes the task that
# is there. iOS: simctl launch exits 0 and prints a pid whether or not the app
# came to the front - right after Home it left the home screen in front, and a
# second launch brought the app (measured, iOS 26.5). So the front is asked after
# it, and one more launch goes when the first did not take.
bring_app(){ local verb="$1" opt="${2:-}" out
  if [ "$APP_PLAT" = android ]; then
    adb shell monkey -p "$APP_ID" -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1 || die "$verb: the device refused to start '$APP_ID'"
    app_wait 0 10 || die "$verb: $APP_ID is not in front 10 s after it was called$(seen_words)"
    return; fi
  out="$(xcrun simctl launch $opt "$APP_UDID" "$APP_ID" 2>&1)" || die "$verb: the simulator refused to launch '$APP_ID': ${out:-no output}"
  app_wait 0 3 && return 0
  out="$(xcrun simctl launch "$APP_UDID" "$APP_ID" 2>&1)" || die "$verb: the simulator refused to launch '$APP_ID': ${out:-no output}"
  app_wait 0 7 || die "$verb: $APP_ID is not in front after two launches$(seen_words)"; }
app_background(){ local s="${1:-0}"
  bg_app background
  app_wait 0 3 || die "background: $APP_ID is not in front$(seen_words) - there is nothing to send to the background"
  if [ "$APP_PLAT" = android ]; then akey home >/dev/null 2>&1 || die "background: the device refused the Home key"
  else idb ui button HOME --udid "$APP_UDID" >/dev/null 2>&1 || die "background: the simulator refused the Home button"; fi
  app_wait 1 5 || die "background: $APP_ID is still in front 5 s after Home"
  [ "$s" = 0 ] || sleep "$s"
  ok "background: $APP_ID behind $APP_SEEN for $s s"; }
# A return is a return to the same process. An app the system stopped while it
# was away would be started afresh by the same command, and the flow would go on
# checking a cold start it believes is a resumed one.
app_foreground(){ local pid now st
  bg_app foreground
  pid="$(app_pid)"
  [ -n "$pid" ] || die "foreground: $APP_ID is not running any more - it was stopped while it was away, and starting it now would be a launch, not a return"
  st=0; app_front || st=$?
  [ "$st" -ne 0 ] || die "foreground: $APP_ID is already in front - there is nothing to bring back"
  bring_app foreground
  now="$(app_pid)"
  [ "$now" = "$pid" ] || die "foreground: $APP_ID came back as a new process (pid $pid, now ${now:-none}) - it was started afresh, not resumed"
  ok "foreground: $APP_ID back in front, the same process ($pid)"; }
# Stop and start, the data kept: what a user does when they swipe the app away and
# open it again. clearState is the one that wipes. Asked of the device like the
# other two: a stop that did not happen leaves the same process in front, and
# that is a resumed app, not a restarted one.
app_relaunch(){ local pid now
  bg_app relaunch
  pid="$(app_pid)"
  if [ "$APP_PLAT" = android ]; then stop_app "$APP_V"; bring_app relaunch
  else bring_app relaunch --terminate-running-process; fi
  now="$(app_pid)"
  [ -n "$now" ] || die "relaunch: $APP_ID is in front, and the device lists no process of it"
  [ "$now" != "$pid" ] || die "relaunch: $APP_ID is the same process as before ($pid) - it was not stopped"
  ok "relaunch: $APP_ID started again as a new process (${pid:-none} -> $now), its data kept"; }
# setPermission (#51): one named permission of the app of this run, set before
# it starts. Nothing else decided what a run starts with: the device kept what
# the run before it left, a suite that grants everything up front cannot reach
# the denied branch, and a pass did not say which state it ran in. The app is
# the one of $YUKTI_VARIANT, as for openUrl; the flow names the permission by
# one name for both platforms and the engine translates it:
#   granted  allowed, no dialog
#   denied   refused, and the system does not ask again (Android: user-fixed)
#   unset    not asked yet: the app's request brings the dialog up
# Android: `pm grant` / `pm revoke` and the user-set / user-fixed flags, on the
# permissions the app's manifest asks for - a name that maps to several (location
# is fine and coarse) sets every one the app asks for, and none asked for is a
# failure: the app has no such permission to be in any state. A name with a dot
# is the platform's own (android.permission.health.READ_HEART_RATE), which is
# how a partial grant of Health Connect is written. iOS: `simctl privacy` for
# what it covers; camera, notifications and health through applesimutils, an
# optional tool that doctor reports on - without it those stop with a hint.
# A permission the platform or its version does not have is not a failure: the
# flow is skipped from this step with a "platform:" reason, out loud and in the
# report. The run itself still ends with status 0 - a flow-level "skipped" is
# #55. Android before 13 (API 33) has no pm *-permission-flags, so there only
# granted is set; denied and unset are skipped the same way. On Android the
# state is read back from dumpsys after it is set, and a permission that did not
# take the state is a failure, never a skip. Revoking kills a running app on
# both platforms, so the step goes before launch. Written from the platform
# documentation and sources, not measured on a device yet.
FLOW_PLAT_SKIP=""
set_permission(){ local name="${1:-}" state="${2:-}" V plat
  state="${state#state=}"
  [ -n "$name" ] || die "setPermission needs a permission, for instance \"notifications\""
  case "$state" in granted|denied|unset) ;; *) die "setPermission: \"state\" is granted, denied or unset, got '$state'";; esac
  V="${YUKTI_VARIANT:-}"
  [ -n "$V" ] || die "setPermission: this run does not know which app '$name' is for - set \$YUKTI_VARIANT to the variant in $CONFIG"
  [ -n "$(cfg "variants.$V")" ] || die "setPermission: there is no variant '$V' in $CONFIG"
  plat="$(step_platform "$V")"
  if [ "$plat" = android ]; then set_permission_android "$V" "$name" "$state"; else set_permission_ios "$V" "$name" "$state"; fi; }
set_permission_android(){ local V="$1" name="$2" state="$3" pkg="" api="" want="" have="" req="" p="" out="" shown="" n=0
  apaths; pkg="$(cfg variants.$V.package)"
  [ -n "$pkg" ] || die "setPermission: variant '$V' has no 'package' in $CONFIG"
  api="$(adb shell getprop ro.build.version.sdk 2>/dev/null | tr -d '\r ')"
  case "$api" in ''|*[!0-9]*) device_fault; die "setPermission: the device did not say its Android version";; esac
  local A=android.permission
  case "$name" in
    notifications) [ "$api" -ge 33 ] || { FLOW_PLAT_SKIP="platform: notifications are a permission from Android 13 (API 33), this device is API $api"; return 0; }
                   want="$A.POST_NOTIFICATIONS";;
    camera)        want="$A.CAMERA";;
    microphone)    want="$A.RECORD_AUDIO";;
    location)      want="$A.ACCESS_FINE_LOCATION $A.ACCESS_COARSE_LOCATION";;
    photos)        if [ "$api" -ge 33 ]; then want="$A.READ_MEDIA_IMAGES $A.READ_MEDIA_VIDEO"; else want="$A.READ_EXTERNAL_STORAGE"; fi;;
    contacts)      want="$A.READ_CONTACTS $A.WRITE_CONTACTS";;
    calendar)      want="$A.READ_CALENDAR $A.WRITE_CALENDAR";;
    motion)        [ "$api" -ge 29 ] || { FLOW_PLAT_SKIP="platform: motion is a permission from Android 10 (API 29), this device is API $api"; return 0; }
                   want="$A.ACTIVITY_RECOGNITION";;
    health)        [ "$api" -ge 34 ] || { FLOW_PLAT_SKIP="platform: health is a permission of the system from Android 14 (API 34), this device is API $api"; return 0; }
                   want="health";;
    reminders)     FLOW_PLAT_SKIP="platform: Android has no reminders permission"; return 0;;
    *.*)           want="$name";;
    *)             die "setPermission: unknown permission '$name'";;
  esac
  # What the manifest asks for: `pm grant` refuses the rest, and a name that
  # maps to two permissions is set on the ones the app has.
  req="$(adb shell dumpsys package "$pkg" 2>/dev/null | tr -d '\r' | "$PY" -c '
import sys
on=False; done=False; ind=0
for line in sys.stdin:
    # The rest of dumpsys is read and dropped: a reader that leaves while the
    # pipe is full makes tr fail, and pipefail would discard what is printed.
    if done: continue
    s=line.strip(); i=len(line)-len(line.lstrip())
    if s=="requested permissions:": on=True; ind=i; continue
    if on:
        if not s or i<=ind: done=True; continue
        print(s.split(":")[0])
')" || req=""
  [ -n "$req" ] || die "setPermission: the device lists no permissions for '$pkg' - is it installed?"
  if [ "$want" = health ]; then have="$(printf '%s\n' "$req" | grep '^android\.permission\.health\.' | tr '\n' ' ')"
  else for p in $want; do printf '%s\n' "$req" | grep -qxF "$p" && have="$have$p "; done; fi
  [ "$want" = "$name" ] && shown="" || shown=" ($want)"
  [ -n "$have" ] || die "setPermission: '$pkg' does not ask for $name$shown - its manifest has no such permission, so it cannot be in any state"
  # pm set-permission-flags and clear-permission-flags came with Android 13.
  # Before it a grant is all pm can do: "denied, not asked again" and "not
  # asked yet" both live in those flags, and a revoke alone would leave
  # whatever flags the run before it set.
  if [ "$api" -lt 33 ]; then
    [ "$state" = granted ] || { FLOW_PLAT_SKIP="platform: $state needs pm set-permission-flags, from Android 13 (API 33), this device is API $api"; return 0; }
    for p in $have; do
      out="$(adb shell "pm grant $pkg $p" 2>&1 | tr -d '\r')" || die "setPermission: the device refused $p for '$pkg': ${out:-no output}"
      case "$out" in *[Ee]xception*|*Error*|*"Unknown"*) die "setPermission: the device refused $p for '$pkg': $(printf '%s' "$out" | head -1)";; esac
      n=$((n+1))
    done
    perm_read_back "$pkg" "$state" "$have"
    ok "permission $name $state for $pkg ($n: ${have% })"; return 0
  fi
  for p in $have; do
    case "$state" in
      granted) out="$(adb shell "pm clear-permission-flags $pkg $p user-set user-fixed; pm grant $pkg $p" 2>&1 | tr -d '\r')";;
      denied)  out="$(adb shell "pm revoke $pkg $p; pm set-permission-flags $pkg $p user-set user-fixed" 2>&1 | tr -d '\r')";;
      unset)   out="$(adb shell "pm revoke $pkg $p; pm clear-permission-flags $pkg $p user-set user-fixed" 2>&1 | tr -d '\r')";;
    esac || die "setPermission: the device refused $p for '$pkg': ${out:-no output}"
    # pm answers nothing on success and an exception in words on a refusal,
    # with an exit status that does not agree across versions (see clearState).
    case "$out" in *[Ee]xception*|*Error*|*"Unknown"*) die "setPermission: the device refused $p for '$pkg': $(printf '%s' "$out" | head -1)";; esac
    n=$((n+1))
  done
  perm_read_back "$pkg" "$state" "$have"
  ok "permission $name $state for $pkg ($n: ${have% })"; }
# The state as the device holds it now: an answer without words from pm is not
# proof (its exit status does not agree across versions), and a permission that
# did not take the state is a failure. dumpsys lists a runtime permission as
# "<name>: granted=true|false, flags=[ USER_SET|USER_FIXED|... ]", once per
# user; the first is User 0, the one pm without --user acts on. A device with a
# work profile lists User 10 after it, and that one is not read. Several users
# are not measured on a device.
perm_read_back(){ local pkg="$1" state="$2" have="$3" got
  got="$(adb shell dumpsys package "$pkg" 2>/dev/null | tr -d '\r' | "$PY" -c '
import sys,re
state=sys.argv[1]; want=sys.argv[2].split(); seen={}
for line in sys.stdin:
    m=re.match(r"\s*([\w.]+): granted=(true|false)(?:, flags=\[([^\]]*)\])?", line)
    if m and m.group(1) in want and m.group(1) not in seen: seen[m.group(1)]=(m.group(2)=="true", set(m.group(3).replace("|"," ").split()) if m.group(3) else set())
for p in want:
    if p not in seen: print("%s: not listed" % p); continue
    g,fl=seen[p]
    if state=="granted" and not g: print("%s: not granted" % p)
    elif state=="denied" and (g or "USER_FIXED" not in fl): print("%s: %s" % (p, "still granted" if g else "not marked user-fixed"))
    elif state=="unset" and (g or fl & {"USER_SET","USER_FIXED"}): print("%s: %s" % (p, "still granted" if g else "still marked as answered"))
' "$state" "$have")" || got="the state could not be read"
  [ -z "$got" ] || die "setPermission: the device does not hold $state for '$pkg' after the step - $(printf '%s' "$got" | tr '\n' ';' | sed 's/;$//; s/;/; /g')"; }
set_permission_ios(){ local V="$1" name="$2" state="$3" u b svc act val out
  paths; u="$(cat "$(udid_file)" 2>/dev/null)" || true
  [ -n "$u" ] || die "setPermission: no simulator recorded in $(udid_file) - run 'yukti up <variant>' first"
  b="$(cfg variants.$V.bundleId)"
  [ -n "$b" ] || die "setPermission: variant '$V' has no 'bundleId' in $CONFIG"
  case "$name" in
    photos|location|contacts|calendar|microphone|motion|reminders)
      svc="$name"; case "$state" in granted) act=grant;; denied) act=revoke;; unset) act=reset;; esac
      out="$(xcrun simctl privacy "$u" "$act" "$svc" "$b" 2>&1)" || die "setPermission: the simulator refused $act $svc for '$b': ${out:-no output}"
      ok "permission $name $state for $b";;
    camera|notifications|health)
      command -v applesimutils >/dev/null 2>&1 || die "setPermission: $name on iOS needs applesimutils, which simctl privacy does not cover - brew tap wix/brew && brew install applesimutils ('yukti doctor' reports it)"
      case "$state" in granted) val=YES;; denied) val=NO;; unset) val=unset;; esac
      out="$(applesimutils --byId "$u" --bundle "$b" --setPermissions "$name=$val" 2>&1)" || die "setPermission: applesimutils refused $name=$val for '$b': ${out:-no output}"
      ok "permission $name $state for $b";;
    *.*) FLOW_PLAT_SKIP="platform: '$name' is an Android permission name, and this run is iOS"; return 0;;
    *)   die "setPermission: unknown permission '$name'";;
  esac; }
# A flow could reach a screen only by walking to it: open the app, find the tab,
# find the card. Walking is the test when the test is about navigation, and pure
# cost in every other flow - and it cannot be walked back, which is why a suite
# ends up force-stopping the app between flows to get a known screen. Measured on
# one app on one Android 15 emulator, two runs each: stopApp + launch + dismiss +
# waitForId takes 34.3 and 33.7 seconds, the same screen through an address 3.7
# and 5.2 - and the address resets the scroll position of every tab, which is the
# part a tab tap does not do.
#
# What this step promises is delivery, not arrival, and the words it reports say
# so. `am start` answers "ok" for an address the app does not route - measured:
# myapp://nope-not-a-route comes back Status: ok and the app stays where it was -
# so a step that said it opened a screen would be lying for the app. Arrival is
# also later than the step: -W returns once the launch has settled, and for an
# address delivered to an app already running it returns at once, before the app
# has navigated. The step after this one therefore waits for the screen
# (waitFor / waitForId); an assert placed there races the navigation.
#
# The app is the one this run is driving, not one named in the step: the address
# is the object here, the way the variant is the object of launch and stopApp.
# Naming the package matters, and is not decoration: a device with the dev and
# the prod build side by side has two apps claiming the same scheme, and an
# unaddressed intent then opens a chooser - a flow would sit in front of it
# until it timed out, with nothing in the report about why.
#
# And the flow says WHERE, never in which environment. A scheme written into a
# step is the environment written into the test: the day the qa build and the
# prod build stop sharing one, every flow that carries an address has to be
# edited, and a flow edited for an environment is a flow that can only be run in
# that one. So the step carries a key, the config carries the base ("urlBase" on
# the variant, or one at the top level for a project whose builds share it), and
# a project that wants the paths in one place puts them there too ("urls"), so
# that a route the app renames is one line to change instead of forty.
#
# The table is all or nothing on purpose. Once a "urls" table exists, a key that
# is not in it is a typo or a route nobody wrote down - falling back to using the
# key as the path would open the address the author did not ask for and report
# success. Without a table, the key IS the path, which is the shape a project
# starts in.
url_of(){ local V="$1" key="$2" base table path
  base="$(cfg "variants.$V.urlBase")"; [ -n "$base" ] || base="$(cfg urlBase)"
  [ -n "$base" ] || die "openUrl: nothing says which address space this run is in - put \"urlBase\" on variant '$V' in $CONFIG, or one at the top level"
  table="$(cfg urls)"
  if [ -n "$table" ] && [ "$table" != "{}" ]; then
    # The key is looked up whole. The config reader walks a dotted path, and a
    # key with a dot in it would read as missing while sitting in the table in
    # plain sight - the author would then be told to add what is already there.
    path="$(printf '%s' "$table" | "$PY" -c 'import json,sys
d=json.load(sys.stdin); v=d.get(sys.argv[1], "")
print(v if isinstance(v, str) else "")' "$key")"
    [ -n "$path" ] || die "openUrl: '$key' is not in the \"urls\" table of $CONFIG - add it there, or remove the table and let the step carry the path"
  else
    path="$key"
  fi
  printf '%s%s' "$base" "$path"; }
open_url(){ local K="${1:-}" U plat V pkg out act
  [ -n "$K" ] || die "openUrl needs a destination - the key of a screen, for instance \"home\""
  V="${YUKTI_VARIANT:-}"
  [ -n "$V" ] || die "openUrl: this run does not know which app to hand '$K' to - set \$YUKTI_VARIANT to the variant in $CONFIG"
  [ -n "$(cfg "variants.$V")" ] || die "openUrl: there is no variant '$V' in $CONFIG"
  U="$(url_of "$V" "$K")" || exit 1
  plat="$(step_platform "$V")"
  if [ "$plat" = android ]; then apaths
    # The address travels through a shell on the device, where &, ; and a space
    # are punctuation. Single quotes hold all of those; a single quote inside the
    # address is the one thing they cannot hold, and guessing at it would hand the
    # device half an address. iOS takes the address as an argument and never
    # through a shell, so the refusal belongs on this side of the branch only.
    case "$U" in *"'"*) die "openUrl: the address contains a single quote, and it cannot be passed to the device shell intact: $U";; esac
    pkg="$(cfg "variants.$V.package")"
    [ -n "$pkg" ] || die "openUrl: variant '$V' has no 'package' in $CONFIG"
    # -W waits for the launch to settle and makes `am` say what happened in
    # words. The words are the evidence: `am start` exits zero on an intent it
    # could not resolve, the same as on one it delivered, so the status alone
    # would pass a typo'd scheme. `|| true` keeps `set -e` from killing the step
    # before the answer is read.
    out="$(adb shell am start -W -a android.intent.action.VIEW -d "'$U'" "$pkg" 2>&1 | tr -d '\r')" || true
    case "$out" in
      *"Error:"*) die "openUrl: the device refused '$U': $(printf '%s' "$out" | grep -m1 'Error:')";;
    esac
    # "Warning: Activity not started, intent has been delivered to currently
    # running top-most instance" is the ordinary answer for an app already in
    # front, and it is a delivery, not a refusal. "Status: ok" is what separates
    # the two, and it is printed in both cases.
    case "$out" in
      *"Status: ok"*) ;;
      *) die "openUrl: '$U' was not delivered - the device said: $(printf '%s' "${out:-nothing}" | tr '\n' ' ')";;
    esac
    # The intent named the package, so it cannot have gone elsewhere; this reads
    # back what actually took it, so that a report says which app answered.
    act="$(printf '%s' "$out" | sed -n 's/^Activity: //p' | head -1)"
    case "${act:-$pkg/}" in
      "$pkg"/*) ;;
      *) die "openUrl: '$U' was taken by $act, not by $pkg";;
    esac
    ok "delivered $U to $pkg"; return; fi
  paths; local u; u="$(cat "$(udid_file)" 2>/dev/null)" || true
  [ -n "$u" ] || die "openUrl: no simulator recorded in $(udid_file) - run 'yukti up <variant>' first"
  # simctl resolves the scheme itself and takes no bundle id, so on iOS the
  # address goes wherever the system sends it. Two builds claiming one scheme is
  # the same hazard as on Android and there is nothing here to aim with; the
  # RUNBOOK names the gap rather than implying it is closed.
  xcrun simctl openurl "$u" "$U" >/dev/null 2>&1 || die "openUrl: the simulator refused '$U'"
  ok "delivered $U"; }
up(){ local V="${1:?usage: yukti up <variant>}"; build "$V"; boot; install "$V"; launch "$V"; ok "up: '$V' running — drive with 'yukti shot' / 'yukti flow'"; }

# ── drive primitives (used by flows AND by AI agents) ────────────────────────
U(){ cat "$(udid_file)" 2>/dev/null || booted; }
# The simulator's idb companion is connected once, not before every read (#175).
# `idb connect` took 5.4 s of a 5.6 s read on a CI runner; `describe-all` alone
# takes 0.2 s. A file beside yukti-udid says a connect was made for this
# simulator, so the next read - in this flow or the next one under the same
# TMPDIR - goes without one. A read that comes back empty forgets it and
# connects again, once per read. Only a plain udid names the file: anything
# else in yukti-udid connects before every read, as before. The file is made
# with noclobber, so a link left in its place is not followed.
idb_mark(){ case "${1:-}" in ''|*[!A-Za-z0-9-]*) return 1;; esac; printf '%s/yukti-idb-%s' "${TMPDIR:-/tmp}" "$1"; }
idb_forget(){ local f; f="$(idb_mark "${1:-}")" || return 0; rm -f "$f" 2>/dev/null || true; }
# IDB_DID: whether this call ran a connect, refused or not - a read connects
# again only when it has not connected yet.
IDB_DID=""
idb_ready(){ local u="${1:-}" f t0 ef err="" rc=0; paths; IDB_DID=""; f="$(idb_mark "$u")" || f=""
  if [ -n "$f" ] && [ -f "$f" ] && [ ! -L "$f" ]; then return 0; fi
  # idb's words go to a file, not through $(...): a pipe would hold the read
  # until every process that inherited it - a companion connect left behind -
  # let go of it.
  IDB_DID=1; t0="$(now)"; ef="$(mktemp "${TMPDIR:-/tmp}/yukti-connect-err.XXXXXX" 2>/dev/null)" || ef=""
  idb connect "$u" >/dev/null 2>"${ef:-/dev/null}" || rc=$?
  [ -z "$ef" ] || { err="$(tail -n 1 "$ef" 2>/dev/null || true)"; rm -f "$ef" 2>/dev/null || true; }
  idb_connect_note "$t0" "$rc" "${err:-}"
  if [ "$rc" -eq 0 ] && [ -n "$f" ]; then (set -C; : > "$f") 2>/dev/null || true; fi
  return 0; }
# A refused connect says so, with the last line idb wrote: without it a runner
# where every connect fails looks the same as one where each read connects once.
idb_connect_note(){ local d ms; d="$(run_dir)"; ms=$(( ($(us_of "$(now)") - $(us_of "$1")) / 1000 ))
  if [ "$2" -eq 0 ]; then printf '  · idb connect %d ms\n' "$ms" >&2; [ -z "$d" ] || printf 'x' >> "$d/idb-connects" 2>/dev/null || true
  else printf '  · idb connect %d ms - refused (exit %s): %s\n' "$ms" "$2" "$(printf '%s\n' "$3" | tail -n 1)" >&2
    [ -z "$d" ] || printf 'x' >> "$d/idb-refused" 2>/dev/null || true; fi; }
shot(){ is_android && { ashot "$@"; return; }; paths; local o; o="$(shot_path "${1:-}")" || return 1; mkdir -p "$(dirname "$o")"; if xcrun simctl io "$(U)" screenshot "$o" >/dev/null 2>&1; then echo "$o"; else device_fault; return 1; fi; }
# A blank tree (#191): the app's root alone, with no size and nothing in it,
# while the app runs and its screen is drawn. A simulator can get stuck in it:
# from one moment on every read of that app process answers it - a waitFor read
# it sixteen times in 15 s - and so does every read of every flow after it on
# the same process, until the app is started again. Such a tree is not "nothing
# on the screen" (the lookups call it status 3, a screen that cannot be judged),
# so reading again does not help; a new process of the app does.
#
# The relaunch is a workaround, not the cause: why idb gets stuck is open. It is
# done only inside a running flow and only before the flow acts - a relaunch puts
# the app back on its first screen, and a flow that had already gone somewhere
# would go on checking that first screen as if it were the one it went to, and
# could pass on it. Outside a flow (`yukti assert-id` and the other commands, an
# agent, Studio) nothing records what was done before, so nothing is relaunched.
# A flow that gets stuck once it acts fails as before, with the reason said once;
# the next flow is relaunched by its own first read. The mark goes down when an
# acting step starts, so a flow whose first step acts is not relaunched either.
# Left open by design: a flow that begins by checking what the previous flow left
# on the screen (an assertNotText, a waitForNotId) would check the first screen
# after a relaunch - flows start from a known state. Once a flow: the same tree
# after a relaunch is the app, or the simulator, and not this.
#
# The marks belong to the flow, beside its record ($FLOW_REC), not to the run
# directory: a run directory a caller shares between flows would carry one
# flow's "acted" into the next.
ios_blank(){ [ "${#1}" -lt 16384 ] || return 1
  printf '%s' "$1" | "$PY" -c '
import json,sys
try: els=json.loads(sys.stdin.read())
except ValueError: sys.exit(1)
if not isinstance(els,list): sys.exit(1)
# The size the lookups take (find_el): either spelling of the frame keys. No
# element of any size - an empty list too - is their status 3.
def n(b,*ks):
    for k in ks:
        v=b.get(k)
        if v is None: continue
        try: return float(v)
        except (TypeError,ValueError): return 0.0
    return 0.0
for e in els:
    b=(e.get("frame") or {}) if isinstance(e,dict) else {}
    if not isinstance(b,dict): continue
    if n(b,"Width","width")>0 and n(b,"Height","height")>0: sys.exit(1)
sys.exit(0)'; }
# Said once a flow: a waitFor polls, and sixteen copies of the line hide the rest.
ios_blank_say(){ local m="${FLOW_REC:-}"
  [ -n "$m" ] && [ -e "$m.blank-said" ] && return 0
  [ -z "$m" ] || : > "$m.blank-said" 2>/dev/null || true; warn "$1" >&2; }
# The stacks of the app's threads on a blank tree, before anything ends the app's
# process. Measured in one full iOS run on CI: idb answers fast and with status
# 0, the root is the app's own process - its pid is in it - and the screenshot of
# the same moment is drawn; from one read on the app never fills the tree again:
# 41 of 353 app processes, each on the first or second read after a change of
# screen, none back within 45 s. idb fills a request the app did not answer in
# time with an empty answer, and that is this root with no size and nothing in
# it. In the same run a screen stayed in its loading state for 45 s after its
# data had come in. What holds the app is in no artifact - the relaunch (#191) or
# the next flow ends the process, and the answer goes with it. So the threads are
# sampled here, into <flow>-threads-<pid>.txt beside the failure's screenshot and
# tree, once per app process a flow sees blank (a relaunch gives a new one):
# `sample` for 3 s; when it is missing, refused or gave no stacks, `sample` run
# inside the simulator, then lldb (attach, backtrace every thread, detach). A way
# counts only when its file holds stacks - "Call graph:" from sample, "thread #"
# and "frame #" from lldb: a tool can exit 0 having written elsewhere, or a line
# about why it could not. Which of them a CI runner allows is not measured yet.
# Each is capped at $THREADS_S seconds, and at the cap its whole process group is
# killed (lldb's debugserver with it); lldb killed there may leave the app
# stopped - the flow is failing by then, or about to relaunch it. lldb prints
# the values of arguments where the app has debug information, sample names
# only; the file stays among the run's artifacts, beside the tree and the
# screenshot. idb-companion's own words about the request it gave up on - its
# `ax_stall_probe` lines, numbers only (the main thread's CPU and state, the
# host's load) - go beside them, into <flow>-idb-stalls-<pid>.txt: fb-idb starts
# the companion for a simulator the first time a command names it and appends
# its stderr to /tmp/idb/logs/<udid>. Only those lines are copied: the rest of
# that log is not ours to vouch for, and a result file must not carry what a
# flow typed. A capture that fails says why in one line and changes nothing else.
THREADS_S="${YUKTI_THREADS_S:-20}"
case "$THREADS_S" in ''|*[!0-9]*|0|????*) THREADS_S=20;; esac
# ios_threads <udid> <tree> <when> [say] - adds what it took to $FLOW_REC.threads,
# a line per note ("note<TAB>words") and per file ("file<TAB>path") for the
# result; with "say", the notes also go to stderr. Prints nothing on stdout. A
# process already taken in this flow ($FLOW_REC.threads-pids) is not taken again.
ios_threads(){ local u="$1" tree="$2" when="$3" m="${FLOW_REC:-}" s got rc l t=$'\t'
  [ -n "$m" ] || return 0
  s="${FLOW_FILE##*/}"; s="${s%.*}"; [ -n "$s" ] || s=flow
  got="$(printf '%s' "$tree" | "$PY" -c '
import json, os, re, signal, subprocess, sys
udid, base, cap, when, logs, seen = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4], sys.argv[5], sys.argv[6]
def say(kind, text): sys.stdout.write("%s\t%s\n" % (kind, text))
try: els = json.loads(sys.stdin.read())
except ValueError: els = None
pid = ""
if isinstance(els, list):
    for e in els:
        if isinstance(e, dict) and e.get("type") == "Application" and str(e.get("pid", "")).isdigit():
            pid = str(e["pid"]); break
if pid and int(pid) < 2: pid = ""
# Once per process a flow: the same process seen blank again is the same stuck
# one; a new pid (a relaunch, or a flow that relaunched and got stuck itself) is
# taken again. A tree that names no process is said once.
key = pid or "none"
try:
    with open(seen, encoding="utf-8") as fh: done = fh.read().split()
except OSError: done = []
if key in done: sys.exit(0)
try:
    with open(seen, "a", encoding="utf-8") as fh: fh.write(key + "\n")
except OSError: pass
tail = "-" + pid if pid else ""
out, stalls = base + "-threads" + tail + ".txt", base + "-idb-stalls" + tail + ".txt"
def gone(*ps):
    for p in ps:
        try: os.remove(p)
        except OSError: pass
gone(out, stalls)   # a file an earlier run left must not pass for this one
def stacks(p, tool):
    try:
        with open(p, encoding="utf-8", errors="replace") as fh: text = fh.read(4 << 20)
    except OSError: return False
    if tool == "lldb": return re.search(r"thread #\d", text) is not None and "frame #" in text
    return "Call graph:" in text
why = []
if not pid:
    say("note", "threads not taken %s: the tree names no process of the app" % when)
else:
    try: os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
    except OSError as e: why.append("%s: %s" % (os.path.dirname(out), e.strerror or e))
    tries = [("sample", "sample", ["sample", pid, "3", "-file", out]),
             ("sample in the simulator", "sample", ["xcrun", "simctl", "spawn", udid, "sample", pid, "3", "-file", out]),
             ("lldb", "lldb", ["lldb", "-p", pid, "--batch", "-o", "thread backtrace all", "-o", "process detach"])]
    took, said, errs = "", out + ".said", out + ".err"
    for name, tool, cmd in tries if not why else []:
        gone(out, said, errs)   # what a way before left is not this one
        try:
            with open(said, "wb") as fo, open(errs, "wb") as fe:
                # Its own session: at the cap the whole group goes, not only
                # the tool - the debugserver of lldb with it. What simctl
                # spawn starts inside the simulator belongs to the simulator.
                p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=fo, stderr=fe, start_new_session=True)
                try: rc = p.wait(timeout=cap)
                except subprocess.TimeoutExpired:
                    try: os.killpg(p.pid, signal.SIGKILL)
                    except OSError: pass
                    p.wait(); why.append("%s: no answer in %d s" % (name, cap)); continue
        except OSError as e: why.append("%s: %s" % (name, e.strerror or e)); continue
        # sample writes its report to -file and a line or two on stdout; lldb
        # prints its own. Whichever of the two holds stacks is the file.
        for got in (out, said):
            if os.path.isfile(got) and stacks(got, tool):
                if got != out: os.replace(got, out)
                took = name; break
        if took: break
        try:
            with open(errs, encoding="utf-8", errors="replace") as fh: last = fh.read().strip().splitlines()
        except OSError: last = []
        if rc == 0: why.append("%s: exit 0, no stacks in what it gave" % name)
        else: why.append("%s: exit %d%s" % (name, rc, (" - " + " ".join(last[-1].split())[:200]) if last else ""))
    gone(said, errs)
    if took:
        say("note", "threads: %s (pid %s, by %s, %s)" % (os.path.basename(out), pid, took, when)); say("file", out)
    else:
        gone(out)
        say("note", "threads not taken %s: %s" % (when, "; ".join(why)))
log = os.path.join(logs, udid)
try:
    with open(log, encoding="utf-8", errors="replace") as fh:
        lines = [l for l in fh if "ax_stall_probe " in l]
except OSError as e:
    say("note", "idb stall lines not read: %s: %s" % (log, e.strerror or e))
else:
    if not lines: say("note", "idb stall lines: none in %s" % log)
    else:
        try:
            with open(stalls, "w", encoding="utf-8") as fh: fh.writelines(lines[-200:])
        except OSError as e: say("note", "idb stall lines not kept: %s" % (e.strerror or e))
        else:
            say("note", "idb stall lines: %s (last %d of %d)" % (os.path.basename(stalls), min(200, len(lines)), len(lines)))
            say("file", stalls)
' "$u" "$RESULTS_DIR/$s" "$THREADS_S" "$when" "${YUKTI_IDB_LOGS:-/tmp/idb/logs}" "$m.threads-pids" 2>/dev/null)" && rc=0 || rc=$?
  [ "$rc" = 0 ] || got="$(printf 'note\tthreads not taken %s: the capture itself failed' "$when")"
  [ -n "$got" ] || return 0
  printf '%s\n' "$got" >> "$m.threads" 2>/dev/null || true
  [ "${4:-}" = say ] || return 0
  printf '%s\n' "$got" | while IFS= read -r l; do
    case "$l" in "note${t}threads:"*|"note${t}idb stall lines:"*) say "${l#note$t}" >&2;; note*) warn "${l#note$t}" >&2;; esac; done
  return 0; }
# ios_unstick <udid> <tree> - prints the tree a caller is to use: this one, or
# one read after a relaunch. Everything it says goes to stderr: its output is
# the tree. The relaunch reads the screen itself (is the app in front?), and
# those reads must not come back here: YUKTI_UNSTICK_BUSY lets them through as
# they are, and a line said from inside would mark the flow as told.
ios_unstick(){ local u="$1" out="$2" m="${FLOW_REC:-}" d t0 t1 again i
  [ -z "${YUKTI_UNSTICK_BUSY:-}" ] || { printf '%s' "$out"; return 0; }
  # A read with a size after `launch`: the app has drawn, the round below is not
  # for a blank read later on (#207).
  ios_blank "$out" || { read_blank 0; [ -z "$m" ] || [ ! -e "$m.launched" ] || rm -f "$m.launched" 2>/dev/null || true; printf '%s' "$out"; return 0; }
  read_blank 1
  [ -n "$m" ] || { printf '%s' "$out"; return 0; }
  # Right after `launch` the app is still drawing, and a read then is blank too
  # (#207): 108 flows that passed in one measured run had such a first read
  # after `launch`, and 2 failed on it, where a `when` decided on that one read.
  # So once per `launch` - the step leaves a mark, the first blank read after it
  # takes it away, and so does the next action of the flow - up to 3 more reads
  # a second apart, with no relaunch. A read that took longer than a second is
  # an app that is busy, not one still drawing: no more reads then, as the
  # back-off of a wait asks (#204).
  if [ -e "$m.launched" ]; then rm -f "$m.launched" 2>/dev/null || true
    for i in 1 2 3; do sleep 1; t0="$(now)"; again="$(idb ui describe-all --udid "$u" 2>/dev/null)" || true; t1="$(now)"
      [ -n "$again" ] || continue; read_note idb "$t0"; out="$again"
      ios_blank "$out" || { read_blank 0; printf '%s' "$out"; return 0; }
      [ $(( ($(us_of "$t1") - $(us_of "$t0")) / 1000 )) -le 1000 ] || break; done; fi
  # No threads are taken on this branch: a blank read here is also the app
  # still drawing after a launch the reads above did not wait out, and stacks
  # there would cost seconds a flow and show an app that is not stuck. A flow
  # stuck past this point fails on its wait, and its threads are taken with the
  # failure (flow_results), still before the next flow relaunches the app.
  if [ -e "$m.acted" ]; then
    ios_blank_say "the app gives a blank tree (no element with a size) at or after this flow's first action: not relaunched here - the flow would go on from the app's first screen; the next flow relaunches it"
    printf '%s' "$out"; return 0; fi
  if [ -e "$m.blank-relaunched" ]; then
    ios_blank_say "the app gives a blank tree (no element with a size) after a relaunch as well"
    printf '%s' "$out"; return 0; fi
  # One more read first: a tree read while the app is still drawing is blank too,
  # and that one needs no relaunch.
  sleep 1; t0="$(now)"; again="$(idb ui describe-all --udid "$u" 2>/dev/null)" || true
  if [ -n "$again" ]; then read_note idb "$t0"; out="$again"; ios_blank "$out" || { read_blank 0; printf '%s' "$out"; return 0; }; fi
  # Blank twice a second apart: the threads of this process now, before the
  # relaunch below ends it. A relaunch that does not help is taken again below:
  # the new process has its own pid.
  ios_threads "$u" "$out" "before this flow acted, ahead of any relaunch" say
  if [ -z "${YUKTI_VARIANT:-}" ]; then
    ios_blank_say "the app gives a blank tree (no element with a size); not relaunched: this run does not know which app it is about (\$YUKTI_VARIANT)"
    printf '%s' "$out"; return 0; fi
  : > "$m.blank-relaunched" 2>/dev/null || true
  d="$(run_dir)"; [ -z "$d" ] || printf 'x' >> "$d/blank-relaunches" 2>/dev/null || true
  warn "the app gives a blank tree (no element with a size) before this flow acts on the screen: relaunching it once" >&2
  # Its own failure is said on stderr and is not the step's: the step goes on with
  # the blank tree and fails, or not, on what it asked.
  ( YUKTI_STEP_ERR=""; YUKTI_UNSTICK_BUSY=1; app_relaunch ) >&2 || {
    ios_blank_say "the app gives a blank tree (no element with a size); the relaunch did not help - its own line above says why"
    printf '%s' "$out"; return 0; }
  for i in 1 2 3 4 5 6 7 8; do sleep 1; t0="$(now)"; again="$(idb ui describe-all --udid "$u" 2>/dev/null)" || true
    [ -n "$again" ] || continue; read_note idb "$t0"; out="$again"
    ios_blank "$out" || { read_blank 0; printf '%s' "$out"; return 0; }; done
  # Blank in the new process too: its threads as well - the next flow ends it.
  ios_threads "$u" "$out" "after the relaunch, blank as well" say
  ios_blank_say "the app gives a blank tree (no element with a size) after a relaunch as well"
  printf '%s' "$out"; }
# A read is an answer with something in it, whatever idb's status: a failed read
# prints nothing on stdout. The status is not let end the script either - from
# the command line (`yukti ui`, Studio) there is no $(...) around this to keep
# set -e off it, and the tries below would never run.
ui(){ is_android && { aui; return; }; [ -n "$HELD_TREE" ] && { printf '%s' "$HELD_TREE"; return 0; }
  local u out i t0 tried; u="$(U)"; idb_ready "$u"; tried="$IDB_DID"
  for i in 1 2 3 4; do t0="$(now)"; out="$(idb ui describe-all --udid "$u" 2>/dev/null)" || true
    [ -n "$out" ] && { read_note idb "$t0"; out="$(ios_unstick "$u" "$out")"; keep_tree "$out"; printf '%s' "$out"; return 0; }
    # No answer: the marks of the read before it say nothing of this one
    # (poll_pause). Not inside a relaunch: there the blank mark must outlive the
    # reads, so a relaunch that did not help still brings the back-off (#204).
    [ -n "${YUKTI_UNSTICK_BUSY:-}" ] || { read_blank 0; [ -z "${FLOW_REC:-}" ] || : > "$FLOW_REC.read-ms" 2>/dev/null || true; }
    [ -n "$tried" ] || { idb_forget "$u"; idb_ready "$u"; tried=1; }
    sleep 0.6; done
  # An empty tree after four tries is idb failing, not a screen with nothing on
  # it: a booted simulator always reports at least its window. Returning the
  # empty string made every caller read it as "the element is not there". The
  # Android path already fails here; this is the same rule for iOS.
  idb_forget "$u"; device_fault; die "idb returned no accessibility tree after 4 tries - is the simulator booted?"; }
# The index (#46) is checked here, once for every caller: the flow builder
# checks what a flow file says, and nothing else may reach int() with a word.
find_el(){ case "${6:-}" in '') ;; *[!0-9]*|???????*) die "index must be a whole number from 0 to 999999, got '$6'";; esac
  is_android && { afind "$1" "${2:-text}" "${3:-exact}" "${4:-centre}" "" "${5:-}" "${6:-}"; return; }; paths; ui | "$PY" -c '
import json,sys,os,traceback
# A lookup must never leave with status 1: that status now means the screen
# could not be read AND the reason is already printed. Anything unforeseen in
# here is the other kind - the device answered with something this code cannot
# use - so it leaves as 2 and the caller says what that means rather than dying
# without any words. The traceback still reaches stderr: a lookup that crashes
# is a bug in this tool, not a state of the app.
def _unforeseen(t,v,tb):
    traceback.print_exception(t,v,tb); sys.stderr.flush(); os._exit(2)
sys.excepthook=_unforeseen
# Rank candidates instead of the first AXLabel/AXValue substring hit: honor the
# accessibility identifier (AXUniqueId) and prefer the actual field/control over
# a nearby static caption — same bug the Android path had ("Email" hit the "or
# use email" caption; "Password" hit the "Forgot Password?" link).
norm=lambda s: " ".join(s.split())   # a two-line caption is one query with spaces
# Same rule as the Android path: the oracle compares as written, locators fold case.
q_raw=norm(sys.argv[1]); q=q_raw.lower()
mode=(sys.argv[2] if len(sys.argv)>2 else "text")
match=(sys.argv[3] if len(sys.argv)>3 else "exact")
# The centre is the tap point and the default; "box" asks for the frame of the
# winner and the window it is judged against; "why" says why there is no
# winner; "count" how many match. An index (the sixth argument) picks one of
# the matches, status 5 past the last. Same contract as the Android path.
out=(sys.argv[4] if len(sys.argv)>4 else "centre")
raw=sys.stdin.read().strip()
if not raw: sys.exit(1)   # 1 = the tree never arrived; ui() has already said why
# Something arrived and it is not a tree: a traceback here would leave the step
# with no words of its own, so this is status 2 - answered, unreadable - the way
# ifield_probe already reports it.
try: els=json.loads(raw)
except ValueError: sys.exit(2)
def frame(e):
    # idb builds disagree on the case of the frame keys, so read both spellings.
    b=e.get("frame") or {}
    def n(*ks):
        for k in ks:
            v=b.get(k)
            if v is None: continue
            try: return float(v)
            except (TypeError,ValueError): return 0.0
        return 0.0
    return n("X","x"),n("Y","y"),n("Width","width"),n("Height","height")
# Screen rect = the window: the element idb names as the application or a window
# if there is one, else the largest frame on screen. Application is larger than
# any of its children by construction, and an iOS scroll view reports the visible
# part rather than its content, so the maximum is the window on lists too. Taking
# the FIRST framed element instead would rest on the order of a flat list, which
# idb does not promise - an alert, an overlay or the keyboard window can come
# first and shrink the rect to its own size. The Android path can rely on order
# because the dump format puts the root node first; here that guarantee is absent.
SX=SY=SW=SH=0.0; _best=(0,-1.0)
for _e in els:
    _x,_y,_w,_h=frame(_e)
    if not (_w>0 and _h>0): continue
    _t=(str(_e.get("type") or "")+" "+str(_e.get("role_description") or "")).lower()
    _rank=(1 if ("application" in _t or "window" in _t) else 0, _w*_h)
    if _rank>_best: _best=_rank; SX,SY,SW,SH=_x,_y,_w,_h
def centre(e):
    # The tap point, or None when the element is not really on screen: a11y reports
    # elements with no size and elements parked outside the window, and a check that
    # accepts them is not a check.
    x,y,w,h=frame(e)
    if not (w>0 and h>0): return None
    cx=int(x+w/2); cy=int(y+h/2)
    if SW>0 and SH>0 and not (SX<=cx<SX+SW and SY<=cy<SY+SH): return None
    return cx,cy
# Same reason as the Android path, assertId included. Note the limit of the rect
# itself: when no element is named application or window, the largest frame wins
# and it always contains itself, so on such an idb build the off-screen filter
# stops discriminating. Requiring a named window here would fail closed on every
# build that names none, which cannot be verified without a Mac.
if mode in ("assert","id") and not (SW>0 and SH>0): sys.exit(3)   # 3 = read, not judgeable
# "in" (#102), the same contract as the Android path: the element tapId would
# tap - the first with that accessibility identifier, of real size, its centre
# in the window - and only what lies within its frame counts; none is status 4.
# tapText takes it too (#146), with the Android rule: only a whole match counts,
# and only one on the screen - inside the element, nothing is searched for.
# assertCountId too (#47), by id.
scope=(sys.argv[5].lower() if len(sys.argv)>5 else ""); sbox=None; part=False
if scope and mode=="text" and not (SW>0 and SH>0): sys.exit(3)
if scope and mode in ("assert","text","id"):
    for e in els:
        if str(e.get("AXUniqueId") or e.get("identifier") or "").lower()!=scope: continue
        if centre(e) is None: continue
        x,y,w,h=frame(e); sbox=(x,y,x+w,y+h); break
    if sbox is None: sys.exit(4)
def emit(e,xy):
    # The frame in the same coordinates as the centre above it: whatever the
    # scale of this idb build, a share of the screen is the same share, and a
    # size in points is compared with a minimum written in points.
    if out=="box":
        x,y,w,h=frame(e); print(int(x),int(y),int(x+w),int(y+h),int(SX),int(SY),int(SX+SW),int(SY+SH))
    elif out=="why": print("on",xy[0],xy[1])
    elif out=="state": print(xy[0],xy[1],*state(e))
    else: print(xy[0],xy[1])
# "state" (#103), the answer of the Android path. Selected is the Selected trait
# (idb lists "traits" from v1.7.0). Checked is not a trait on iOS: React Native
# builds the accessibility value from parts joined by ", " - the role
# ("checkbox, checked", "radio button, unchecked"), then expanded, busy and the
# view own value (RCTViewComponentView.mm) - and a switch reports 1 or 0. The
# state is the one part that is checked, unchecked or mixed; none, or more than
# one, is no state. Only the English words are read: a value in another
# language reads as no state and fails by name instead of passing. Written from the idb and React Native
# sources, not run on a simulator yet (#87).
# Expanded (#183) is the part "expanded", which React Native adds only when it
# is true: a collapsed section adds nothing, the same as an element with no
# such state, so on iOS false is the absence of the word and "none" is never
# answered - a step that asks false proves something only next to one that
# asks true of the same element. A value in another language has no "expanded"
# and reads as false.
def state(e):
    tr=e.get("traits") or []
    if isinstance(tr,str): tr=tr.replace(","," ").split()
    sel="true" if any(str(t).strip().lower()=="selected" for t in tr) else "false"
    v=norm(str(e.get("AXValue") or "")).lower()
    t=(str(e.get("type") or "")+" "+str(e.get("role_description") or "")).lower()
    words=[p for p in (x.strip() for x in v.split(",")) if p in ("checked","unchecked","mixed")]
    w=words[0] if len(words)==1 else ""
    if w=="checked" or ("switch" in t and v=="1"): chk="true"
    elif w=="unchecked" or ("switch" in t and v=="0"): chk="false"
    elif w=="mixed": chk="mixed"
    else: chk="none"
    exp="true" if "expanded" in [x.strip() for x in v.split(",")] else "false"
    return sel,chk,exp
best=None; best_el=None; best_score=-1; zero=None; off=None
# Corners (x1,y1,x2,y2): a lies entirely inside b and is not b itself. The
# Android path defines the same function; keep the two identical. A tap match
# scores at least 2 and best_score starts below that, so a tie never meets an
# empty winner.
def inside(a,b): return b[0]<=a[0] and b[1]<=a[1] and a[2]<=b[2] and a[3]<=b[3] and a!=b
# "index" (#46) and the count (#47) ask for every match, not for the winner,
# and both read the one list built here: the candidates that pass the filters
# the winner passes (inside "in", of real size, the centre on the screen) and
# rank equally best. A tied match that holds another tied match within it is the
# frame around that control, not a second control - the tie rule of the single
# lookup, applied here in every mode: a row whose label sits on the row and on
# the text inside it is one row to a count, as it is on iOS, where the two
# arrive merged. Two tied matches with the same box are one control too (a
# wrapper the size of its child); the first in the tree stands for both. The
# list is in the order of the screen: rows top to bottom, then left
# to right by the centre of the frame. Elements are one row when their vertical
# centres differ by less than half the height of the smaller one, measured from
# the first element of the row. Dump order is not used: uiautomator returns a
# tree and idb a flat list in traversal order, and the two disagree. The Android
# path defines the same function; keep the two identical.
def pick(cands):
    if not cands: return []
    top=max(c[0] for c in cands); ms=[c for c in cands if c[0]==top]
    ms=[c for i,c in enumerate(ms) if not any(o[1]==c[1] for o in ms[:i]) and not any(inside(o[1],c[1]) for o in ms)]
    ms.sort(key=lambda c:((c[1][1]+c[1][3])/2,(c[1][0]+c[1][2])/2))
    rows=[]
    for c in ms:
        cy=(c[1][1]+c[1][3])/2; h=c[1][3]-c[1][1]
        if rows and abs(cy-rows[-1][0])<min(h,rows[-1][1])/2: rows[-1][2].append(c)
        else: rows.append((cy,h,[c]))
    return [c for r in rows for c in sorted(r[2],key=lambda c:(c[1][0]+c[1][2])/2)]
idx=(sys.argv[6] if len(sys.argv)>6 else ""); enum=bool(idx) or out=="count"; cands=[]
def cand(e,score,xy):
    x,y,w,h=frame(e); cands.append((score,(x,y,x+w,y+h),xy,e))
for e in els:
    label_raw=norm(str(e.get("AXLabel") or "")); label=label_raw.lower()
    value_raw=norm(str(e.get("AXValue") or "")); value=value_raw.lower()
    title_raw=norm(str(e.get("title") or "")); title=title_raw.lower()
    ident=str(e.get("AXUniqueId") or e.get("identifier") or "").lower()
    t=(str(e.get("type") or "")+" "+str(e.get("role_description") or "")).lower()
    editable=("textfield" in t) or ("securetext" in t) or ("text field" in t) or ("textview" in t) or ("textarea" in t)
    control=("button" in t) or ("link" in t)
    if mode=="id":
        # Explicit selector: the accessibility identifier must match exactly, and an
        # empty query matches nothing - the flow runner passes value="" for a missing
        # or misspelled key, and that must not resolve to the first element around.
        if not q or q!=ident: continue
        xy=centre(e)
        if xy is None:   # keep looking: a sized namesake may follow
            # No frame at all is no place at all, not a place of zero size: the
            # Android path drops a node without bounds, and the two must agree.
            if not e.get("frame"): continue
            x,y,w,h=frame(e); bx=(int(x),int(y),int(x+w),int(y+h))
            if not (w>0 and h>0):
                if zero is None: zero=bx
            elif off is None: off=bx
            continue
        if sbox:
            x,y,w,h=frame(e)
            if not (sbox[0]<=x and sbox[1]<=y and x+w<=sbox[2] and y+h<=sbox[3]): continue
        if enum: cand(e,10,xy); continue
        emit(e,xy); sys.exit(0)
    if mode=="assert":
        # See the Android path: an assertion matches perceivable text only, on an
        # element that is really on screen - real size, centre inside the window,
        # and the whole label as written unless the flow asks for "contains".
        if match=="contains":
            if not (q and (q in label or q in value or q in title)): continue
        elif not (q_raw and q_raw in (label_raw, value_raw, title_raw)): continue
        xy=centre(e)
        if xy is None: continue
        if sbox:
            x,y,w,h=frame(e)
            if not (sbox[0]<=x and sbox[1]<=y and x+w<=sbox[2] and y+h<=sbox[3]): continue
        if enum: cand(e,10,xy); continue
        emit(e,xy); sys.exit(0)
    if not (q and (q in ident or q in label or q in value or q in title)): continue
    score=0
    if q==ident: score+=6
    elif q in ident: score+=5
    if q in (label,value,title): score+=4
    elif q in label or q in value or q in title: score+=2
    if editable: score+=3
    if control: score+=1
    x,y,w,h=frame(e)
    # A zero-size element cannot be tapped: a hidden namesake used to win the
    # ranking and send the tap to (0,0). Off-screen elements stay eligible here -
    # scroll_to needs their coordinates to know which way to scroll - but a
    # candidate that is actually on screen outranks one that is not, so a namesake
    # further down a list can no longer take the tap away from the visible one.
    if sbox:
        if not (sbox[0]<=x and sbox[1]<=y and x+w<=sbox[2] and y+h<=sbox[3]): continue
        if q not in (label,value,title):
            if q in label or q in value or q in title: part=True
            continue
        # A link of no size has its element and is not on the screen, as on
        # Android: not a missing role.
        if not (w>0 and h>0):
            if zero is None: zero=(int(x),int(y),int(x+w),int(y+h))
            continue
        if centre(e) is None:
            if off is None: off=(int(x),int(y),int(x+w),int(y+h))
            continue
    if not (w>0 and h>0): continue
    if centre(e) is not None: score+=2
    # Every match counts for an index and a count, and only on the screen: the
    # Android path never ranks an element outside it.
    if enum:
        if centre(e) is not None: cand(e,score,centre(e))
        continue
    # A tie goes to the element that lies inside the current winner, as on
    # Android: the window and the button in it can carry the same label. The
    # containment test does not depend on the order of the list, which idb does
    # not promise; equal matches that are not nested still go to the first one.
    if score<best_score: continue
    if score==best_score:
        bx,by,bw,bh=frame(best_el)
        if not inside((x,y,x+w,y+h),(bx,by,bx+bw,by+bh)): continue
    best=(int(x+w/2),int(y+h/2)); best_el=e; best_score=score
if enum:
    ms=pick(cands)
    if out=="count": print(len(ms)); sys.exit(0)
    if not ms and part and not (zero or off): sys.exit(11)
    if not ms and out!="why": print(0,0); sys.exit(5)
    if ms:
        if int(idx)>=len(ms): print(len(ms),sum(1 for c in cands if c[0]<ms[0][0])); sys.exit(5)
        emit(ms[int(idx)][3],ms[int(idx)][2]); sys.exit(0)
if best: emit(best_el,best)
elif part and not (zero or off): sys.exit(11)
elif out=="why":
    if zero: print("zero",*zero)
    elif off: print("off",*off)
' "$1" "${2:-text}" "${3:-exact}" "${4:-centre}" "${5:-}" "${6:-}"; }
tap(){ is_android && { atap "$1" "$2"; return; }; paths; idb ui tap --udid "$(U)" "${1:?x}" "${2:?y}"; }
# iOS: what is really under a tap point. The lookups above judge an element by
# its own frame only - in the window, of real size - and never ask whether
# something drawn over it takes the touch. A button scrolled behind the tab bar
# passes them, and its tap opens the tab instead: a card's "Skip" (centre
# 326,833) sat under a tab button (321-402 x 785-840), dismiss took it for an
# interstitial, and every flow's first block ended on that tab (idb ui
# describe-point 326 833 answered the tab; 2026-10-28). So the point is asked:
# idb describe-point names the element that gets the touch. It is the target
# when it matches the query by find_el's own rule (id: the identifier exactly;
# text: the query inside identifier, label, value or title, case folded), or a
# part of the target: an element with no id of its own whose centre lies inside
# the target's frame (a centre, not the whole frame: a label's frame can stick
# out of its button by a point). An element with an id of its own that does not
# match is another control, even inside the target's frame, for an id query and
# a text query alike - a sticky date strip's day button lay inside a
# scrolled-under tile's frame, and the tap went to the day (2026-10-29).
# Anything else covers the target, with one exception (#189): a plain view with
# an id - GenericElement, no label, no value, traits None or Scrollable and
# nothing else - whose frame holds the target's whole frame. React Native
# answers a card that carries a testID for every point inside it, its own
# buttons included, and the touch still reaches the button. Measured on an iOS
# 26.5 simulator (2026-11-18): a disclosure, a share and a call-to-action button
# in three cards with an id all answered their card, and a tap through the
# card's answer collapsed and expanded it as on Android. Two of those cards
# carry no label and pass; the third carries one and stays covered (a limit
# below). A touchable with no role is a GenericElement too, but it is an
# accessibility element and carries the text inside it as its label, as a
# sticky strip's tabs do in a full dump of that screen, so such a tab over a
# target is read as covering it. A target under a strip that has stuck while
# scrolling was not measured.
# What else lay over a target answered as the control it is (a floating tab
# button over a card's body) and stays covered. The tree was no help: idb
# describe-all --nested lists every element of that screen as a child of the
# application, with no containers. Known limits: a plain view with an id and no
# label laid over the whole target (a backdrop, a touchable with an icon and no
# label) passes as a container - every such pass says so in the log; and a
# target that is not an
# accessibility element (a plain view with an id) holding a child with an id of
# its own answers the child at its point, and reads as covered by it; accessible
# touchables hide their children, so it needs such a container.
# Two more exceptions (#208), judged on the screen tree and the window. The app
# in its test mode lists a view with a testID as a stand-in with the frame of
# the whole view, the label of its content and its role: a card with an id, a
# label and the role button answers for the buttons inside it (29 such steps in
# one run, 2026-11-23). It passes as a holder when it is inset from both side
# edges of the window, holds the whole target, and no other control crosses the
# target's frame; a sheet or a dimming layer runs the full width of the window
# and stays a cover. And a plain view with an id that the target sticks out of
# (a tab past the window edge, a card past its screen container) passes when the
# point lies in the part of the target inside the view and the window, and no
# other control is at the point. Limits: a labelled pop-up with an id inset over
# the whole target passes as a holder, and a plain view with an id over a part of
# the target passes on that part; a control is told by its role or traits, so a
# touchable with no role (a GenericElement with an id and a label) on the target
# is not seen as one, and a pop-up made of such buttons passes as a holder too;
# each pass says so in the log, with the id.
# Answers: "ok", "covered <id or type>", "unknown" (idb gave no element); inside
# ihit also "held", "holder" and "visible" with the id, which ihit logs and turns
# into "ok".
# Only the covering element's id or type is printed, never its label: a label
# can carry what the screen shows.
IHIT_PY='
import json,os,sys
n=lambda s: " ".join(str(s or "").split()).lower()
q=n(sys.argv[1]); mode=sys.argv[2]; box=(sys.argv[3].split() if len(sys.argv)>3 else [])
# With a box the screen tree comes on stdin (#208): read it whole before any
# answer, or a tree bigger than the pipe would end the writer on SIGPIPE.
raw=sys.stdin.read() if box else ""
try: el=json.loads(os.environ.get("YUKTI_PT") or "")
except ValueError: el=None
if isinstance(el,list): el=el[0] if el else None
if not isinstance(el,dict) or not el: print("unknown"); sys.exit(0)
ident=n(el.get("AXUniqueId") or el.get("identifier"))
texts=(ident,n(el.get("AXLabel")),n(el.get("AXValue")),n(el.get("title")))
hit=(bool(q) and q==ident) if mode=="id" else (bool(q) and any(q in t for t in texts))
b=el.get("frame") or {}
if not isinstance(b,dict): b={}
def g(*ks):
    for k in ks:
        if b.get(k) is not None:
            try: return float(b[k])
            except (TypeError,ValueError): return 0.0
    return 0.0
x,y,w,h=g("X","x"),g("Y","y"),g("Width","width"),g("Height","height")
try: bx=[float(v) for v in box[:4]] if len(box)>=4 else None
except ValueError: bx=None
if not hit and bx and not ident:
    cx,cy=x+w/2,y+h/2
    hit=w>0 and h>0 and bx[0]<=cx<=bx[2] and bx[1]<=cy<=bx[3]
if hit: print("ok"); sys.exit(0)
cover=el.get("AXUniqueId") or el.get("identifier") or (str(el.get("type") or "element")+" (no id)")
tr=el.get("traits")
plain=n(el.get("type"))=="genericelement" and isinstance(tr,list) and bool(tr) and \
    all(n(t) in ("none","scrollable") for t in tr) and not texts[1] and not texts[2]
# The corners of the target come cut to whole points, the frame of the answer
# does not: a point either way.
holds=bool(bx) and bool(ident) and w>0 and h>0 and \
    x<=bx[0]+1 and y<=bx[1]+1 and x+w>=bx[2]-1 and y+h>=bx[3]-1
if plain and holds: print("held",cover); sys.exit(0)
# #208: with the frame of the target, the window (find_el hands both over) and the
# screen tree on stdin, two more answers are not covers. The point is YUKTI_XY.
try: win=[float(v) for v in box[4:8]] if len(box)>=8 else None
except ValueError: win=None
try: px,py=[float(v) for v in os.environ.get("YUKTI_XY","").split()[:2]]
except ValueError: px=py=None
if not win or px is None or not (w>0 and h>0): print("covered",cover); sys.exit(0)
# The rules below judge by the tree: without one they do not apply.
try: els=json.loads(raw)
except ValueError: els=None
if not isinstance(els,list) or not els: print("covered",cover); sys.exit(0)
def fr(e):
    f=e.get("frame") or {}
    if not isinstance(f,dict): return None
    try: a=[float(f.get(k1) if f.get(k1) is not None else f.get(k2) or 0) for k1,k2 in (("X","x"),("Y","y"),("Width","width"),("Height","height"))]
    except (TypeError,ValueError): return None
    return (a[0],a[1],a[0]+a[2],a[1]+a[3]) if a[2]>0 and a[3]>0 else None
# A control of its own: what takes a touch by its role. A plain view, a text, an
# image, the window are not.
CTRL=("button","link","textfield","securetextfield","textview","textarea","switch","slider","searchfield","toggle","checkbox","radiobutton","stepper","picker","pickerwheel","segmentedcontrol","incrementarrow","decrementarrow")
CTRL_TR=("button","link","adjustable","searchfield","keyboardkey")
def control(e):
    tr=e.get("traits"); tr=tr if isinstance(tr,list) else []
    return n(e.get("type")) in CTRL or any(n(t) in CTRL_TR for t in tr)
ans=(x,y,x+w,y+h); tgt=tuple(bx[:4])
def inside(a,b): return b[0]-1<=a[0] and b[1]-1<=a[1] and a[2]<=b[2]+1 and a[3]<=b[3]+1
def same(a,b): return all(abs(a[i]-b[i])<=1 for i in range(4))
def mine(e,f):
    # The answer, the target, what holds the target, what lies in it.
    if same(f,ans) and n(e.get("AXUniqueId") or e.get("identifier"))==ident: return True
    if same(f,tgt): return True
    if mode=="id" and n(e.get("AXUniqueId") or e.get("identifier"))==q: return True
    return inside(tgt,f) or inside(f,tgt)
others=[]; atpt=[]
for e in els:
    if not isinstance(e,dict) or not control(e): continue
    f=fr(e)
    if not f: continue
    if not mine(e,f): others.append(f)
    # At the point a control inside the target with an id of its own takes the
    # touch, as in the rule for the answer above; one with no id is a part.
    elif inside(f,tgt) and not same(f,tgt) and n(e.get("AXUniqueId") or e.get("identifier")) not in ("",q): atpt.append(f)
# A holder: a view with an id and a label of its own (React Native in its test
# mode lists a view with a testID as a stand-in carrying the label of its content and
# role), inset from both side edges of the window, that holds the whole target,
# while no other control crosses the frame of the target. A sheet or a dimming layer
# runs the full width of the window and stays a cover.
# More than a point on both axes: the corners of the target come cut to whole
# points, and a neighbour flush with it would cross it by a fraction.
cross=lambda f,b: min(f[2],b[2])-max(f[0],b[0])>1 and min(f[3],b[3])-max(f[1],b[1])>1
at=lambda f: f[0]<=px<=f[2] and f[1]<=py<=f[3]
if ident and texts[1] and holds and x-win[0]>1 and win[2]-(x+w)>1 and \
    not any(cross(f,tgt) for f in others) and not any(at(f) for f in atpt):
    print("holder",cover); sys.exit(0)
# A plain view that the target sticks out of (past the window edge or past the
# view itself): the touch reaches the target where the point lies in the part of
# it that is inside both, and no other control is at the point.
vis=(max(tgt[0],ans[0],win[0]),max(tgt[1],ans[1],win[1]),min(tgt[2],ans[2],win[2]),min(tgt[3],ans[3],win[3]))
if plain and ident and vis[0]<vis[2] and vis[1]<vis[3] and at(vis) and not any(at(f) for f in others+atpt):
    print("visible",cover); sys.exit(0)
print("covered",cover)
'
ihit(){ local q="$1" mode="$2" x="$3" y="$4" in="${5:-}" idx="${6:-}" pt v box tree
  is_android && { echo ok; return 0; }
  paths; pt="$(idb ui describe-point --udid "$(U)" "$x" "$y" 2>/dev/null)" || pt=""
  v="$(YUKTI_PT="$pt" "$PY" -c "$IHIT_PY" "$q" "$mode")" || v=unknown
  case "$v" in covered*)
    # One read serves both: the target's frame and the tree the rules look at.
    tree="$(ui 2>/dev/null)" || tree=""
    # A local, not an assignment before the call: that one would put the tree in
    # the environment of every process find_el starts, past the size a Linux
    # environment string may have.
    local HELD_TREE="${tree:-$HELD_TREE}"
    box="$(find_el "$q" "$mode" exact box "$in" "$idx" 2>/dev/null)" || box=""
    [ -n "$box" ] && { v="$(printf '%s' "$tree" | YUKTI_PT="$pt" YUKTI_XY="$x $y" "$PY" -c "$IHIT_PY" "$q" "$mode" "$box")" || v=unknown; };;
  esac
  case "$v" in
    held\ *) printf "  · '%s' at %s,%s: the point answers %s, a plain view that holds it - not covered\n" "$q" "$x" "$y" "${v#held }" >&2; v=ok;;
    holder\ *) printf "  · '%s' at %s,%s: the point answers %s, a holder (an id and a label, inset, holds it, no other control on it by frames) - not covered\n" "$q" "$x" "$y" "${v#holder }" >&2; v=ok;;
    visible\ *) printf "  · '%s' at %s,%s: the point answers %s, a plain view, on the visible part of the target - not covered\n" "$q" "$x" "$y" "${v#visible }" >&2; v=ok;;
  esac
  printf '%s\n' "${v:-unknown}"; }
# A tap that must land on its target: covered = the step fails and says by what,
# instead of tapping the element on top. No answer from idb = the tap goes ahead
# as it did before this check, with a warning.
tap_checked(){ local q="$1" mode="$2" x="$3" y="$4" v; v="$(ihit "$q" "$mode" "$x" "$y" "${5:-}" "${6:-}")"
  case "$v" in
    ok) ;;
    covered*) die "'$q' at $x,$y is covered by ${v#covered } - not tapped, the touch would go to that instead";;
    *) warn "could not read what is under '$q' at $x,$y - tapping as before";;
  esac
  tap "$x" "$y"; }
# A lookup has three outcomes, not two: coordinates, "no such element", and
# "the screen could not be read at all". The third one used to arrive as the
# second, because `die` inside aui/ui exits a command-substitution subshell and
# the status was dropped. A flow then skipped an optionalTapText, swiped eight
# times looking for a label, or blamed a missing element for a broken dump.
# Every lookup below now checks the status: an unreadable screen stops the run.
# Status 5 hands back the last sighting, which is stale by definition, so this
# verb must not tap it: an element that left the screen is an element that is not
# there, which is the answer it has always given.
# The search is scrollToText's, wait at the end of the list included, so the
# step's "timeout" sets that wait here as well.
# With an "in" id (#146) there is no search: one read, the words looked for
# inside that element, the tap on the element whose whole text or label they
# are. Like tapId it does not scroll. Words that are only a part of a longer
# text have no place of their own to tap, and that is a failure by name, not a
# tap on the centre of the text.
#
# With an index (#46) the step counts the matches on the screen as it is and
# taps that one, without scrolling: a swipe changes what the index counts. With
# "in" as well, it counts inside that element.
tap_text(){ local xy st=0 grow="${2:-$SCROLL_GROW_WAIT}" in="${3:-}" idx="${4:-}"
  [ -z "$in" ] || { xy="$(find_el "$1" text exact centre "$in" "$idx")" || st=$?
    case "$st" in
      0) ;;
      4) die "$(lookup_err 4 "$in")";;
      5) die "$(index_miss "$idx" "$xy" "'$1' in the element with id '$in'")";;
      11) die "'$1' is part of a longer text in the element with id '$in' and has no element of its own to tap - a link inside a text gets one when the app marks it as a link (accessibilityRole=\"link\")";;
      *) lookup_die "$st";;
    esac
    [ -n "$xy" ] || die "no element matching '$1' on the screen in the element with id '$in'"
    tap_checked "$1" text $xy "$in" "$idx"; return; }
  case "$grow" in ''|*[!0-9]*|0) die "tapText: timeout must be a whole number of seconds greater than zero, got '$grow'";; esac
  if [ -n "$idx" ]; then
    xy="$(find_el "$1" text exact centre "" "$idx")" || st=$?
    case "$st" in 0) ;; 5) die "$(index_miss "$idx" "$xy" "'$1'")";; *) lookup_die "$st";; esac
    [ -n "$xy" ] || die "no element matching '$1' on the screen"
    tap_checked "$1" text $xy "" "$idx"; return; fi
  xy="$(scroll_to "$1" down "" tapText "$grow")" || st=$?
  case "$st" in 0) ;; 5) die "no element matching '$1'";; 6|7|8) die "no element matching '$1' - $(scroll_miss "$st" "'$1'" down "$grow")";; *) lookup_die "$st";; esac
  [ -n "$xy" ] || die "no element matching '$1'"; tap_checked "$1" text $xy; }  # auto-scrolls off-screen elements into view
# The exception these two verbs enjoy is about an ABSENT label, and nothing else.
# A device that refuses the tap is not an absent label: the status of `tap` is
# checked here, or the step keeps its exception and reports a tap that never
# happened - the very class of lie the status check above exists to end.
# An index past the last match is the element the step names not being there,
# which is what this verb tolerates: skipped, with the number that matched.
tap_text_optional(){ local xy st=0 v idx="${2:-}"; xy="$(find_el "$1" text exact centre "" "$idx")" || st=$?
  [ "$st" -ne 5 ] || { warn "optional '$1' not present - skipped: $(index_miss "$idx" "$xy" "'$1'")"; return 0; }
  [ "$st" -eq 0 ] || lookup_die "$st"
  # Covered is not absent: say so, and leave it alone (see ihit).
  [ -n "$xy" ] && { v="$(ihit "$1" text $xy "" "$idx")"; case "$v" in
    ok) ;;
    covered*) warn "optional '$1' is covered by ${v#covered } - not tapped"; return 0;;
    *) warn "could not read what is under optional '$1' at ${xy/ /,} - tapping as before";;
  esac; }
  [ -n "$xy" ] && { tap $xy || die "optional tap '$1': the device refused the tap"; ok "optional tap '$1'"; } || warn "optional '$1' not present — skipped"; }
# Auto-dismiss the interstitials that derail flows (Save Password, notifications, promos…)
# only SAFE interstitial labels — never Cancel/Close/OK (those navigate/confirm)
DISMISS_LABELS=("Not Now" "Not now" "Maybe Later" "Later" "Skip for now" "Skip" "No thanks" "No Thanks" "Got it")
# One read per round, not one per label: the nine labels are looked for in the
# same tree, the first one found is tapped, and the next round reads the screen
# again because the tap changed it. A clean screen costs one read instead of
# nine; two stacked cost three, and the second is found whichever label it
# carries - the single pass this replaces could walk past it. The rounds are
# capped - a screen that keeps answering with another interstitial is news, and
# the step says so instead of looping. It stops after the sixth tap without
# reading the screen again, so it never claims to know what is on it.
dismiss(){ local L xy st hit v round=0
  while :; do
    HELD_TREE=""
    # ui() says why itself and leaves non-zero from the substitution; the step
    # stops here rather than deciding against a screen it could not read.
    HELD_TREE="$(ui)" || exit 1
    [ -n "$HELD_TREE" ] || die "dismiss: the screen came back empty"
    hit=""; xy=""
    for L in "${DISMISS_LABELS[@]}"; do
      st=0; xy="$(find_el "$L")" || st=$?
      [ "$st" -eq 0 ] || { HELD_TREE=""; lookup_die "$st"; }
      # A covered match is a button under something else (a card's own Skip
      # behind the tab bar), not an interstitial on top: leave it (see ihit).
      if [ -n "$xy" ]; then
        v="$(ihit "$L" text $xy)"
        case "$v" in
          ok) ;;
          covered*) warn "dismiss: '$L' is covered by ${v#covered } - not a pop-up, left alone"; xy=""; continue;;
          *) warn "dismiss: could not read what is under '$L' at ${xy/ /,} - tapping as before";;
        esac
        hit="$L"; break
      fi
    done
    HELD_TREE=""
    [ -n "$hit" ] || return 0
    tap $xy || die "dismiss: the device refused the tap on '$hit'"
    sleep 0.6; ok "dismissed '$hit'"
    round=$((round + 1))
    [ "$round" -lt 6 ] || { warn "dismiss: six interstitials tapped in a row - stopping here without reading the screen again, and leaving whatever is on it to the step that follows"; return 0; }
  done; }
type_str(){ [ -n "${1:-}" ] || die "type: the value is empty"; is_android && { atype "$1" "${2:-}"; return; }; itype "$1" "${2:-}"; }
# How `type` ends, the same words on both platforms. With "shows" (#128) the
# field filters what is typed, so the counts are of what it shows and what
# "shows" expects, not of what was sent. Counts, never the value.
type_arrived(){ if [ -n "$2" ]; then ok "type: the field shows the expected ${#2} characters on attempt $1"; else ok "type: $3 characters arrived on attempt $1"; fi; }
type_lost(){ if [ -n "$2" ]; then die "type: the field does not show what \"shows\" expects after 3 attempts (it holds $1 characters, \"shows\" has ${#2})"; fi
  die "type: arrived $1 of $3 characters after 3 attempts"; }
# The text fields of the iOS tree, and what `type` made of them. idb reports no
# focus, so the field that was typed into is the one whose value changed: the
# fields are listed before the keys ("list", as JSON in $YUKTI_FIELDS) and
# compared after them ("check", the value in $YUKTI_SENT - in the environment,
# never on a command line). A field matches when it holds what it held plus the
# value, or the value alone (it was empty, or showed its placeholder), and has
# changed - a field that held the value already proves nothing. A secure
# field is compared as dots, with its last character allowed in the clear for a
# moment, the way the Android side does it. Status 0: arrived. 4: not there,
# with how many characters did arrive - as many deletes take them back out.
# 5: more than one field changed, so there is no telling which one was typed
# into. 1 and 2 are the lookup statuses: no tree, an unreadable one.
ifields(){ paths; ui | "$PY" -c '
import json,sys,os,traceback
# Never status 1 on its own: that one means the screen could not be read and
# the reason is already out. Anything unforeseen leaves as 2, as in find_el.
def _unforeseen(t,v,tb):
    traceback.print_exception(t,v,tb); sys.stderr.flush(); os._exit(2)
sys.excepthook=_unforeseen
raw=sys.stdin.read()
if not raw.strip(): sys.exit(1)
try: els=json.loads(raw)
except ValueError: sys.exit(2)
def fields(els):
    out=[]
    for e in els:
        b=e.get("frame") or {}
        g=lambda *k: float(next((b[n] for n in k if n in b), 0) or 0)
        x,y,w,h=g("x","X"),g("y","Y"),g("width","Width"),g("height","Height")
        t=(str(e.get("type") or "")+" "+str(e.get("role_description") or "")).lower()
        if w<=0 or h<=0 or not ("field" in t or "textview" in t or "textarea" in t): continue
        out.append([int(x),int(y),int(w),int(h),str(e.get("AXValue") or "")])
    return out
now=fields(els)
if sys.argv[1]=="list":
    sys.stdout.write(json.dumps(now)); sys.exit(0)
was=json.loads(os.environ["YUKTI_FIELDS"]); sent=os.environ["YUKTI_SENT"]
DOT="\u2022"
# The same field before the keys: the same frame, or - when the keyboard or a
# scroll to the caret moved the layout between the reads - the same place in
# the column of fields of its shape, counted from the top. A move up or down
# keeps that order; a column that gained or lost a field has no answer.
def column(fs,f): return sorted((o for o in fs if (o[0],o[2],o[3])==(f[0],f[2],f[3])), key=lambda o:o[1])
def before(f):
    for o in was:
        if o[:4]==f[:4]: return o[4]
    old,new=column(was,f),column(now,f)
    return old[new.index(f)][4] if len(old)==len(new) else ""
def arrived(old,new):
    if new in (old+sent, sent): return True
    dots=DOT*(len(sent)-1)
    return new in (dots+DOT, dots+sent[-1]) or (old and set(old)<={DOT} and new in (old+dots+DOT, old+dots+sent[-1]))
changed=[]
for f in now:
    old=before(f)
    # Unchanged is not arrived: a field that already held the value says
    # nothing about where the keys went.
    if f[4]==old: continue
    if arrived(old,f[4]): sys.exit(0)
    changed.append((old,f[4]))
if len(changed)>1: sys.exit(5)
n=0
if changed:
    old,new=changed[0]
    n=len(new)-len(old) if new.startswith(old) else len(new)
sys.stdout.write("%d" % max(n,0)); sys.exit(4)
' "$1"; }
# iOS types in the same shape as Android: the status of every key kept (#28),
# and one read after the last to see that the value arrived (#106). A field that
# renders late gets one more read half a second on; a field that is still short
# loses what did arrive, and the value is typed again, three times in all - the
# deletes go from the caret, so the value is taken to have gone in at the end of
# the field, as on Android. The keys stay one at a time: idb's own bulk text
# drops characters (README), and bursts wait until they can be measured on a
# simulator. Written from the idb docs, not run on a simulator yet (#87).
itype(){ paths; local s="$1" shows="${2:-}" e m=${#1} u was st try i n=0
  e="${shows:-$s}"
  u="$(U)"
  st=0; was="$(ifields list)" || st=$?
  [ "$st" -eq 0 ] || lookup_die "$st"
  for try in 1 2 3; do
    i=0
    while [ "$i" -lt "$m" ]; do
      idb ui text --udid "$u" "${s:$i:1}" >/dev/null 2>&1 || die "type: the simulator refused a key"
      sleep 0.12; i=$((i+1))
    done
    st=0; n="$(YUKTI_FIELDS="$was" YUKTI_SENT="$e" ifields check)" || st=$?
    [ "$st" -eq 4 ] && { sleep 0.5; st=0; n="$(YUKTI_FIELDS="$was" YUKTI_SENT="$e" ifields check)" || st=$?; }
    case "$st" in
      0) [ "$try" = 1 ] || type_arrived "$try" "$shows" "$m"; return 0;;
      4) ;;
      5) die "type: more than one text field changed - there is no telling which one was typed into";;
      *) lookup_die "$st";;
    esac
    [ "$try" = 3 ] && break
    warn "type: attempt $try lost characters - clearing the field and typing again"
    for ((i=0;i<n;i++)); do idb ui key --udid "$u" 42 >/dev/null 2>&1 || die "type: the simulator refused the delete key"; done
  done
  type_lost "$n" "$shows" "$m"; }
# The right edge of the field under a point, and what it holds. Both come out of
# one dump: on iOS the caret has to be put at the end of THIS field before
# deleting, and the old code tapped a fixed x=360 - right for one screen width
# and silently wrong for every other.
ifield_probe(){ paths; ui | "$PY" -c '
import json,sys,os,traceback
# A lookup must never leave with status 1: that status now means the screen
# could not be read AND the reason is already printed. Anything unforeseen in
# here is the other kind - the device answered with something this code cannot
# use - so it leaves as 2 and the caller says what that means rather than dying
# without any words. The traceback still reaches stderr: a lookup that crashes
# is a bug in this tool, not a state of the app.
def _unforeseen(t,v,tb):
    traceback.print_exception(t,v,tb); sys.stderr.flush(); os._exit(2)
sys.excepthook=_unforeseen
x0,y0=float(sys.argv[1]),float(sys.argv[2])
def frame(e):
    b=e.get("frame") or {}
    g=lambda *k: float(next((b[n] for n in k if n in b), 0) or 0)
    return g("x","X"), g("y","Y"), g("width","Width"), g("height","Height")
best=None; best_area=0.0
try: els=json.loads(sys.stdin.read())
except ValueError: sys.exit(2)
for e in els:
    x,y,w,h=frame(e)
    if w<=0 or h<=0: continue
    if not (x<=x0<x+w and y<=y0<y+h): continue
    if best is None or w*h<best_area: best, best_area = e, w*h
if best is None: sys.exit(3)
x,y,w,h=frame(best)
v=str(best.get("AXValue") or "")
t=(str(best.get("type") or "")+" "+str(best.get("role_description") or "")).lower()
# A secure field reports what it holds as dots and, while it is empty, its
# placeholder: a value without a dot is the placeholder, not text to delete.
if "secure" in t and "\u2022" not in v: v=""
sys.stdout.write("%d\x1f%s\x1f%s" % (int(x+w-4), "field" if ("field" in t or "textview" in t or "textarea" in t) else t or "element", v.replace("\n"," ")))
' "$1" "$2"; }
# iOS has no select-all through idb, so the deletes are counted from what the
# field actually holds - measured in the dump, not a constant that was right for
# one form. The read-back after them is the same rule as on Android.
iclear(){ paths; local x="${1:?x}" y="${2:?y}" vb="${3:-clearText}" u out edge val after probe i kind
  # iOS is written from the idb docs and has not been run - see AF-USER-GUIDE.
  # The field is read before the tap: what it holds and where its edge is are
  # the same either side of it, and clearTextId has already found the field in
  # this tree - one read for both (#106). The tap stays even for an empty field:
  # the `type` that follows a clear types into the field the clear focused.
  local st=0; u="$(U)"
  out="$(ifield_probe "$x" "$y")" || st=$?
  HELD_TREE=""
  [ "$st" -eq 0 ] || lookup_die "$st" "$vb: no element at $x,$y"
  IFS=$'\x1f' read -r edge kind val <<<"$out"
  [ "$kind" = field ] || die "$vb: the element at $x,$y is a $kind, not a text field"
  idb ui tap --udid "$u" "$x" "$y" || die "$vb: the simulator refused the tap on the field"
  sleep .4
  [ -n "$val" ] || { ok "$vb: the field was already empty"; return 0; }
  idb ui tap --udid "$u" "$edge" "$y" || die "$vb: the simulator refused the tap at the end of the field"
  sleep .3
  for i in $(seq 1 ${#val}); do idb ui key --udid "$u" 42 >/dev/null 2>&1 || die "$vb: the simulator refused the delete key"; done
  out="$(ifield_probe "$x" "$y")" || lookup_die $? "$vb: no element at $x,$y any more"
  IFS=$'\x1f' read -r edge kind after <<<"$out"
  [ -n "$after" ] || { ok "$vb: field empty at $x,$y"; return 0; }
  # An empty plain field reports its placeholder as its value too, and idb names
  # no placeholder: what is left is the placeholder, or text the deletes missed.
  # One digit tells them apart - it replaces a placeholder and is added to text -
  # and is deleted again before the field is judged.
  idb ui text --udid "$u" 1 >/dev/null 2>&1 || die "$vb: the simulator refused a key"
  sleep .3
  out="$(ifield_probe "$x" "$y")" || lookup_die $? "$vb: no element at $x,$y any more"
  IFS=$'\x1f' read -r edge kind probe <<<"$out"
  [ "$probe" != "$after" ] || die "$vb: the field is not empty after ${#val} deletes, or shows a placeholder and took no digit to tell"
  idb ui key --udid "$u" 42 >/dev/null 2>&1 || die "$vb: the simulator refused the delete key"
  [ "$probe" = 1 ] || die "$vb: the field still holds text after ${#val} deletes"
  sleep .3
  out="$(ifield_probe "$x" "$y")" || lookup_die $? "$vb: no element at $x,$y any more"
  IFS=$'\x1f' read -r edge kind probe <<<"$out"
  [ "$probe" = "$after" ] || die "$vb: the digit typed to tell a placeholder from text is still in the field"
  ok "$vb: field empty at $x,$y (it shows its placeholder)"; }
clear_field(){ is_android && { aclear "$1" "$2" "${3:-}"; return; }; iclear "$1" "$2" "${3:-}"; }
# One key, by name, on either platform. iOS has no Back key at all - saying so is
# the whole point: a flow that asks for one on iOS is wrong about the platform,
# and pressing nothing would let it believe otherwise.
press_key(){ local name="${1:-}" u
  [ -n "$name" ] || die "pressKey needs a key name - one of: $KEY_NAMES"
  case " $KEY_NAMES " in *" $name "*) ;; *) die "pressKey does not know the key '$name' - use one of: $KEY_NAMES";; esac
  if is_android; then
    akey "$name" || die "pressKey '$name': the device refused the key"
  else
    paths; u="$(U)"
    case "$name" in
      back) die "pressKey 'back' is Android only - iOS has no Back key; tap the screen's own back control with tapText or tapId";;
      home)   idb ui button HOME --udid "$u" || die "pressKey 'home': the simulator refused the button";;
      enter)  idb ui key --udid "$u" 40 || die "pressKey 'enter': the simulator refused the key";;
      escape) idb ui key --udid "$u" 41 || die "pressKey 'escape': the simulator refused the key";;
      delete) idb ui key --udid "$u" 42 || die "pressKey 'delete': the simulator refused the key";;
      tab)    idb ui key --udid "$u" 43 || die "pressKey 'tab': the simulator refused the key";;
    esac
  fi
  ok "pressKey '$name'"; }
# Whether a keyboard is up, asked of iOS the only way idb allows: the tree names
# the keyboard as an element. Same three outcomes as the Android side.
# A simulator (iOS 26.5, measured) lists no element of type keyboard: only its
# keys, as plain buttons - a "delete" key and one button per letter or digit.
# The keyboard is up when the tree holds that "delete" (lower case: an app's
# own button says "Delete") and at least nine one-character buttons in its
# cluster: from the delete row up to 180 points above it - three rows of
# letters, four of a number pad. A one-character button of the app elsewhere
# on the screen (a "+" in a header) is not a key, and does not move the top of
# the keyboard.
# A numeric keypad labels its key "Delete", capital D (iPhone 17 Pro simulator,
# iOS 26.5, #145), so the lower-case rule missed it and hideKeyboard said no
# keyboard was up with the keypad over half the form. "Delete" counts only next
# to the shape of a keypad: the ten digits as buttons, of one height give or
# take 2 points, all in the bottom 40% of the window, and that "Delete" in the
# same band. An app screen with a "Delete" button and a row of one-character
# buttons of its own does not have that shape. The window is taken as find_el
# takes it - idb also lists elements parked outside it, and the lowest of them
# is not the bottom of the screen. Two limits of the shape, known and not
# solved: an app that draws its own PIN pad - ten digits and a "Delete" low on
# the screen - reads as a keyboard, and a keypad in landscape, taller than 40%
# of the window, does not.
# When the tree does list a keyboard element, its keys are the one-character
# buttons inside its frame, and neither shape is needed. A keyboard element with
# no one-character button inside it (not seen on a device yet) is measured by
# its own frame, whose top takes in the bar: the bar's Done then lies below
# "the top" and is not found.
# With "geom" it also prints where to drag to close it: the middle of the
# keys, and the top of their highest row - also when the tree lists a keyboard
# element whose frame takes in the bar above the keys, so that bar stays above
# "the top"; then the centre of the "Done" button
# of the bar on top of the keys, or "- -". That Done is tapped, so it has to be
# the keyboard bar's and nothing else: bottom edge within 80 points above the
# keys and not below their top - the keyboard's own return key, labelled Done
# for a field whose key action is done, lies in the bottom row and is Return
# by another name, which this band keeps out - the
# shape of a bar button - at most 50 high, at most a quarter of the keys wide,
# right edge within 24 points of theirs - and inside the toolbar on top of the
# keys when the tree lists one. A full-width Done riding on the keyboard is the
# form's own button and is not tapped. Of several, the lowest.
ikb_shown(){ paths; ui | "$PY" -c '
import json,sys,os,traceback
# Anything unforeseen leaves as 2, "no answer": status 1 would read as "no
# keyboard", and the close would report success.
def _unforeseen(t,v,tb):
    traceback.print_exception(t,v,tb); sys.stderr.flush(); os._exit(2)
sys.excepthook=_unforeseen
try: els=json.loads(sys.stdin.read())
except ValueError: sys.exit(2)   # an unreadable tree is not "no keyboard"
if not isinstance(els,list): sys.exit(2)
def kind(e): return (str(e.get("type") or "")+" "+str(e.get("role_description") or "")).lower()
def frame(e):
    b=e.get("frame") or {}
    g=lambda *k: float(next((b[n] for n in k if n in b), 0) or 0)
    return g("x","X"), g("y","Y"), g("width","Width"), g("height","Height")
def inside(a,b): return b[0]-1<=a[0] and a[0]+a[2]<=b[0]+b[2]+1 and b[1]-1<=a[1] and a[1]+a[3]<=b[1]+b[3]+1
kb=None; dels=[]; ones=[]; caps=[]; scr=None; rank=(0,-1.0)
for e in els:
    t=kind(e); label=str(e.get("AXLabel") or ""); f=frame(e)
    if f[2]>0 and f[3]>0:
        r=(1 if ("application" in t or "window" in t) else 0, f[2]*f[3])
        if r>rank: rank=r; scr=f
    if "keyboard" in t: kb=f
    if "button" not in t or f[2]<=0 or f[3]<=0: continue
    if label=="delete": dels.append(f)
    if label=="Delete": caps.append(f)
    if len(label)==1: ones.append((label,f))
def keypad():
    if not caps or scr is None: return []
    top=scr[1]+scr[3]*0.6; end=scr[1]+scr[3]
    band=lambda f: top<=f[1] and f[1]+f[3]<=end+1
    pad=dict((l,f) for l,f in ones if l.isdigit() and band(f))
    if len(pad)<10: return []
    hs=[f[3] for f in pad.values()]
    if max(hs)-min(hs)>2 or not any(band(f) for f in caps): return []
    return list(pad.values())+[f for f in caps if band(f)]
keys=[]
if kb is not None: keys=[k for l,k in ones if inside(k,kb)]
else:
    for d in dels:
        band=[k for l,k in ones if d[1]-180<=k[1]<=d[1]+d[3]]
        if len(band)>=9: keys=band+[d]; break
    # On a keypad the drag is measured from its keys alone: a one-character
    # button of the app higher up would move the top of the keys onto the form.
    if not keys: keys=keypad()
    if not keys: sys.exit(1)
if len(sys.argv)>1:
    if keys: left,y,right=min(k[0] for k in keys),min(k[1] for k in keys),max(k[0]+k[2] for k in keys)
    else: left,y,right=kb[0],kb[1],kb[0]+kb[2]
    bars=[f for f in (frame(e) for e in els if "toolbar" in kind(e)) if f[2]>0 and y-20<=f[1]+f[3]<=y+2]
    best=None
    for e in els:
        f=frame(e); ex,ey,ew,eh=f
        if "button" not in kind(e) or str(e.get("AXLabel") or "").strip()!="Done": continue
        if ew<=0 or eh<=0 or not (y-80<=ey+eh<=y): continue
        if eh>50 or ew>(right-left)/4 or abs(ex+ew-right)>24: continue
        if bars and not any(inside(f,b) for b in bars): continue
        if best is None or ey+eh>best[1]+best[3]: best=f
    done="%d %d" % (int(best[0]+best[2]/2), int(best[1]+best[3]/2)) if best else "- -"
    sys.stdout.write("%d %d %s" % (int((left+right)/2), int(y), done))
sys.exit(0)
' "$@"; }
# hideKeyboard is pressKey with a postcondition, which is why it is built on it
# rather than beside it. The postcondition is the verb: an Android form longer
# than one field cannot be filled while the keyboard is up, so "the keys were
# accepted" is not an answer - "the keyboard is down" is.
kb_shown(){ if is_android; then akb_shown; else ikb_shown; fi; }
hide_keyboard(){ local st=0
  kb_shown || st=$?
  if [ "$st" -eq 2 ]; then device_fault; die "hideKeyboard: the device did not report its input method state"; fi
  if [ "$st" -eq 1 ]; then ok "hideKeyboard: no keyboard was up"; return 0; fi
  kb_close hideKeyboard; }
# Closing a keyboard that is up, with the check that it closed. `who` opens every
# line it prints, so a swipe step that closes one says it in its own name.
# On Android Back comes first, and only while the input method says the
# keyboard is up: the input method takes Back while it is shown, and the key
# goes no further. (A field that handles Back before the input method does -
# onKeyPreIme - is the exception, and so is the moment right after a tap, when
# the state can say "shown" before the keyboard is drawn.) Escape is not taken
# by the input method. It reaches the window, and a dialog - a React Native
# Modal among them - takes escape as Back and closes itself with the field in
# it, so the keyboard was down and the step said so over a screen that had
# gone. Back with the keyboard already down is never pressed: measured on API
# 35, it walked the rig out of the app and, one screen later, out to the
# launcher. So the state is asked right before the key, here as well as by the
# caller. A keyboard takes a moment to go, so the answer after a key is waited
# for up to 2 s before the next key. Escape stays as the fallback for a
# keyboard Back leaves up, with the focused window read before and after it:
# a window that changed is the dialog escape closed, and that fails the step.
# akb_gone - polls the input method for up to 2 s: 0 down, 1 still up; no
# answer stops the step.
akb_gone(){ local who="$1" i st
  for i in 1 2 3 4; do
    sleep 0.5
    st=0; akb_shown || st=$?
    if [ "$st" -eq 2 ]; then device_fault; die "$who: the device did not report its input method state"; fi
    [ "$st" -eq 1 ] && return 0
  done
  return 1; }
afocus(){ adb shell "dumpsys window | grep mCurrentFocus" 2>/dev/null | head -1 | tr -d "\r" | sed "s/^ *//"; }
kb_close(){ local who="$1" st=0 was now
  is_android || { ikb_close "$who"; return; }
  akb_shown || st=$?
  if [ "$st" -eq 2 ]; then device_fault; die "$who: the device did not report its input method state"; fi
  if [ "$st" -eq 1 ]; then ok "$who: no keyboard was up any more"; return 0; fi
  akey back || die "$who: the device refused the back key"
  akb_gone "$who" && { ok "$who: keyboard closed"; return 0; }
  warn "$who: Back did not close the keyboard - trying escape, which a dialog around the field may take as Back and close"
  was="$(afocus)"
  press_key escape >/dev/null || die "$who: the device refused the escape key"
  akb_gone "$who" || die "$who: the keyboard is still up after Back and escape"
  now="$(afocus)"
  if [ -z "$was" ]; then
    warn "$who: keyboard closed (escape) - the focused window could not be read, so a dialog that closed with it would go unnoticed"; return 0
  fi
  [ "$now" = "$was" ] || die "$who: escape closed the keyboard and the window with it - focus went from '$was' to '${now:-nothing}'"
  ok "$who: keyboard closed (escape)"; }
# iOS has no key that only closes the keyboard: escape does nothing to it. The
# way that types and submits nothing, measured on a simulator (iOS 26.5), is a
# short drag down just above the keys: a scroll view that dismisses on drag
# closes it. A keyboard still up after it - or one that reaches too high for
# the drag - gets the "Done" button on the bar above the keys, when the tree
# has one: the close the app itself offers, with the same check after it.
# Return is never pressed for the flow: it can submit the form or put a
# newline into a multi-line field. There is no tap "outside the field" either:
# no point can be sure to miss every element that acts. A keyboard still up
# stops the step with what was tried, and a flow whose form may take Return
# says so with pressKey 'enter'.
# Every check reads the screen afresh: a held tree still shows the keyboard.
# Sets geo for the caller (ikb_close declares it local; bash scope reaches it).
ikb_kb(){ local st=0
  HELD_TREE=""
  geo="$(ikb_shown geom)" || st=$?
  if [ "$st" -eq 2 ]; then device_fault; die "$1: the device did not report its input method state"; fi
  [ "$st" -eq 0 ]; }
ikb_close(){ local who="$1" u geo x top dx dy tried="" skipped=""
  paths; u="$(U)"
  ikb_kb "$who" || { ok "$who: no keyboard was up any more"; return 0; }
  read -r x top dx dy <<<"$geo"
  if [ "$top" -gt 200 ]; then
    idb ui swipe --udid "$u" "$x" $((top-150)) "$x" $((top-60)) --duration 0.3 >/dev/null 2>&1 \
      || die "$who: the simulator refused the drag above the keyboard"
    sleep 0.6
    ikb_kb "$who" || { ok "$who: keyboard closed (drag)"; return 0; }
    read -r x top dx dy <<<"$geo"
    tried="a drag above it"
  else
    skipped="a drag (the keyboard reaches up to y $top, with no room above it)"
  fi
  if [ "$dx" != "-" ]; then
    idb ui tap --udid "$u" "$dx" "$dy" >/dev/null 2>&1 || die "$who: the simulator refused the tap on Done"
    sleep 0.6
    ikb_kb "$who" || { ok "$who: keyboard closed (Done above the keyboard - the app's own button, it may have acted)"; return 0; }
    tried="${tried:+$tried, }the Done button above it"
  else
    skipped="${skipped:+$skipped, }Done (no Done button above the keyboard)"
  fi
  die "$who: the keyboard is still up${tried:+ after $tried}${skipped:+ - not tried: $skipped} - if this form may take Return, close it with pressKey 'enter'"; }
# A swipe that starts on a soft keyboard is taken by the keyboard: Gboard reads a
# drag across its keys as glide typing and types a word into the focused field,
# and the list behind it does not move. So the first swipe of a step asks first.
# Up: closed, the way hideKeyboard closes it, and said in the run. Status 10 then,
# a number no lookup returns, so a search that shares its status variable reads
# the screen again - what it looks for may have been under the keys.
# Not closing, or no answer from the device, stops the step: an unanswered
# question is not "no keyboard". Closing drops focus from the field - a flow that
# types after a scroll taps the field first.
kb_before_swipe(){ local who="$1, before swiping" st=0
  kb_shown || st=$?
  if [ "$st" -eq 1 ]; then return 0; fi
  if [ "$st" -eq 2 ]; then device_fault; die "$who: the device did not report its input method state"; fi
  # A tree held from before the close still shows the keyboard, and kb_close
  # asks again after it.
  HELD_TREE=""
  kb_close "$who"
  return 10; }
# An assert must prove the element is ON SCREEN, not that the string appears
# somewhere in the dump. `ui | grep` matched invisible nodes, off-screen rows and
# attribute values, so an assertText passed on a screen that never opened. Reuse
# the same lookup taps use: relevance, ranking and real non-zero bounds.
# The match rule is part of the assertion, so the flow states it and the log
# repeats it: a green line that does not say how it matched cannot be read back.
# With an "in" id (#102) only that element and what lies within it count, and
# the two misses read apart: "no element with id" in the words of tapId, or the
# element is there and the text is not in it.
assert_text(){ local q="${1:-}" m="${2:-exact}" in="${3:-}" idx="${4:-}" xy st=0
  [ -n "$q" ] || die "assertText needs a non-empty value"
  case "$m" in exact|contains) ;; *) die "assertText: unknown match '$m' - use exact or contains";; esac
  xy="$(find_el "$q" assert "$m" centre "$in" "$idx")" || st=$?
  [ "$st" -ne 5 ] || die "assert FAILED ($m match): $(index_miss "$idx" "$xy" "'$q'${in:+ in the element with id '$in'}")"
  [ "$st" -eq 0 ] || die "assert FAILED: $(lookup_err "$st" "$in")"
  [ -z "$in" ] || { [ -n "$xy" ] && ok "assert ($m) in '$in': '$q'${idx:+ index $idx} on screen at $xy" || die "assert FAILED ($m match): '$q' not in the element with id '$in'"; return; }
  [ -n "$xy" ] && ok "assert ($m): '$q'${idx:+ index $idx} on screen at $xy" || die "assert FAILED ($m match): '$q' not on screen"; }
# Explicit-selector variants. tapText/assertText match on visible text and can
# land on a neighbouring caption; these two take an accessibility id / resource-id
# segment and match it exactly, or fail. An empty id is a failure, never a match:
# a flow step with a missing or misspelled `value` must stop the run, not tap a
# random point. Neither scrolls — use scrollToId (or scrollToText) first for a target below the fold.
# A miss by id says which of two different screens it saw (#64): nothing in the
# tree carries the id - a wrong id, or not the screen expected - or the id is
# there on a node that was dropped for having no area or lying off the screen,
# so the element exists and something clips or hides it. The words begin the
# same either way; the second case adds the node's frame, in the unit of the
# platform, worded as waitForId words the same two cases. An Android keyboard
# collapses the nodes under it to no area (a field reported as
# [116,974][564,954]), which is what the sentence names; an iOS keyboard covers
# elements instead and is not promised here. One more read of the screen, made
# only when the step has already failed - or none, when the step holds its tree.
# A second argument goes right after the id: what the id was wanted for.
# tapId with "at", swipeId and the element an "in" names word their misses
# here as well (#167); for "in" the second argument is IN_FOR, so the reader
# knows the missing id is the container's and not the one looked for in it.
IN_FOR=' (named by "in")'
id_miss(){ local q="$1" for="${2:-}" w unit
  # The step has failed already, on a read that worked: a second read that does
  # not work - the device gone in between - leaves the words as they were rather
  # than turning the miss into a device error, so its noise is not shown.
  w="$(find_el "$q" id exact why 2>/dev/null)" || w=""
  is_android && unit=pixels || unit=points
  case "$w" in
    zero\ *) set -- $w
      printf "no element with id '%s' on the screen%s - it is in the tree at zero size [%s,%s][%s,%s] (%s)" "$q" "$for" "$2" "$3" "$4" "$5" "$unit"
      if is_android; then printf ', which is what a keyboard over it looks like'; fi;;
    off\ *) set -- $w
      printf "no element with id '%s' on the screen%s - it is in the tree outside the screen at [%s,%s][%s,%s] (%s)" "$q" "$for" "$2" "$3" "$4" "$5" "$unit";;
    *) printf "no element with id '%s'%s" "$q" "$for";;
  esac
  return 0; }
tap_id(){ local q="${1:-}" idx="${4:-}"; [ -n "$q" ] || die "tapId needs a non-empty id"; [ -z "${2:-}${3:-}" ] || { tap_id_at "$q" "${2:-}" "${3:-}" "$idx"; return; }; local xy st=0; xy="$(find_el "$q" id exact centre "" "$idx")" || st=$?; [ "$st" -ne 5 ] || die "$(index_miss "$idx" "$xy" "id '$q'")"; [ "$st" -eq 0 ] || die "$(lookup_err "$st")"; [ -n "$xy" ] || die "$(id_miss "$q")"; tap_checked "$q" id $xy "" "$idx"; }
# tapId with "at" (#129): a point inside the element instead of its centre. A
# slider with stops often has one id on the whole track, or ids on its two ends
# only, so the stop in the middle can be reached only as a point on the track.
# x and y are shares of the element's width and height, from its left and top
# edge; one left out stays at the centre. A share and not pixels, so the same
# flow reaches the same stop on a phone and on a tablet. 100% is the last pixel
# inside the frame - the right edge itself belongs to the next element.
# The point has to be on the screen: a track that runs past the edge is still
# found by its centre, and a tap off the screen goes nowhere. On iOS the point
# is checked like the centre is, so a thumb with an id of its own over that
# point fails the step as covered - tap the thumb by its id then, or the track
# where the thumb is not.
# With an index (#46) the point is taken on that match: the slider of the
# second row of a list where every row has the same ids.
# tap_id_at <id> <x share or empty> <y share or empty> [index] - shares as whole numbers.
tap_id_at(){ local q="$1" xs="$2" ys="$3" idx="${4:-}" out st=0 x1 y1 x2 y2 sx1 sy1 sx2 sy2 px py v
  for v in "$xs" "$ys"; do
    case "$v" in ''|[0-9]|[1-9][0-9]|100) ;; *) die "tapId: a point is a whole share of the element from 0 to 100, got '$v'";; esac
  done
  out="$(find_el "$q" id exact box "" "$idx")" || st=$?
  [ "$st" -ne 5 ] || die "$(index_miss "$idx" "$out" "id '$q'")"
  [ "$st" -eq 0 ] || die "$(lookup_err "$st")"
  [ -n "$out" ] || die "$(id_miss "$q")"
  read -r x1 y1 x2 y2 sx1 sy1 sx2 sy2 <<<"$out"
  if [ -n "$xs" ]; then px=$(( x1 + (x2 - x1) * xs / 100 )); [ "$px" -lt "$x2" ] || px=$(( x2 - 1 )); [ "$px" -ge "$x1" ] || px=$x1; else px=$(( (x1 + x2) / 2 )); fi
  if [ -n "$ys" ]; then py=$(( y1 + (y2 - y1) * ys / 100 )); [ "$py" -lt "$y2" ] || py=$(( y2 - 1 )); [ "$py" -ge "$y1" ] || py=$y1; else py=$(( (y1 + y2) / 2 )); fi
  [ "$px" -ge "$sx1" ] && [ "$px" -lt "$sx2" ] && [ "$py" -ge "$sy1" ] && [ "$py" -lt "$sy2" ] \
    || die "'$q'${idx:+ index $idx} at ${xs:-50}% x ${ys:-50}% is $px,$py, off the screen [$sx1,$sy1][$sx2,$sy2] - not tapped"
  # Said once the tap went: a point found covered is a failed step, not a tap
  # followed by a failure.
  tap_checked "$q" id "$px" "$py" "" "$idx" || return
  ok "tap id '$q'${idx:+ index $idx} at ${xs:-50}% x ${ys:-50}% of $((x2 - x1))x$((y2 - y1)): $px,$py"; }
assert_id(){ local q="${1:-}" want="${2:-}" idx="${3:-}"; [ -n "$q" ] || die "assertId needs a non-empty id"; local xy st=0 miss
  # Expanded is read from the actions of a node, which a read carries only when asked (#183).
  case " $want " in *" expanded="*) local AUI_ACTIONS=1;; esac
  [ -z "$want" ] || { xy="$(find_el "$q" id exact state "" "$idx")" || st=$?; [ "$st" -ne 5 ] || die "assert FAILED: $(index_miss "$idx" "$xy" "id '$q'")"; [ "$st" -eq 0 ] || die "assert FAILED: $(lookup_err "$st")"
    [ -n "$xy" ] || die "assert FAILED: $(id_miss "$q")"
    miss="$(state_miss "$q" "$want" $xy)"; [ -z "$miss" ] || die "assert FAILED: $miss"
    set -- $xy; ok "assert id: '$q'${idx:+ index $idx} on screen at $1 $2, $(state_words "$want")"; return 0; }
  xy="$(find_el "$q" id exact centre "" "$idx")" || st=$?; [ "$st" -ne 5 ] || die "assert FAILED: $(index_miss "$idx" "$xy" "id '$q'")"; [ "$st" -eq 0 ] || die "assert FAILED: $(lookup_err "$st")"; [ -n "$xy" ] && ok "assert id: '$q'${idx:+ index $idx} on screen at $xy" || die "assert FAILED: $(id_miss "$q")"; }
# An index past the last match (#46): the lookup left with status 5, the number
# of matches it counted and the number that matched with a lower rank. The step
# stops and says how many there were - tapping the first one instead is the
# guess the index exists to replace. Only the best matches are counted, and the
# words say so when others were left out: a caption next to a button matches
# tapText less closely than the button does.
index_miss(){ local n="${2%% *}" less=0 w="elements match" l=""; [ "$n" = 1 ] && w="element matches"
  case "$2" in *" "*) less="${2#* }";; esac
  [ "${3#id }" = "$3" ] || { w="elements with"; [ "$n" = 1 ] && w="element with"; }
  case "$less" in 0|'') ;; 1) l=", and 1 more matches less closely and is not counted";; *) l=", and $less more match less closely and are not counted";; esac
  [ "$n" != 0 ] || { printf '%s' "index $1 is out of range: 0 $w $3 on the screen"; return; }
  printf '%s' "index $1 is out of range: $n $w $3 as closely as the best match on the screen$l (the index counts from 0, top to bottom, then left to right)"; }
# assertCount (#47): how many elements match, compared with a number. The count
# is the list the index picks from (see pick in afind): the same filters, the
# same rule for a frame around its control. The number found is in the line
# either way, so a red step says how far off it was.
assert_count(){ local q="${1:-}" kind="${2:-assert}" op="${3:-}" n="${4:-}" m="${5:-exact}" in="${6:-}" got st=0 what words held=""
  [ "$kind" = id ] && what="assertCountId needs a non-empty id" || what="assertCount needs a non-empty value"
  [ -n "$q" ] || die "$what"
  case "$kind" in assert|id) ;; *) die "usage: yukti assert-count \"<text or id>\" <assert|id> <atLeast|exact|atMost> <count> [exact|contains] [<id>]";; esac
  case "$op" in atLeast) words="at least";; exact) words="exactly";; atMost) words="at most";; *) die "assertCount: unknown op '$op' - use atLeast, exact or atMost";; esac
  case "$n" in ''|*[!0-9]*|???????*) die "assertCount: count must be a whole number from 0 to 999999, got '$n'";; esac
  n=$((10#$n))
  [ "$op" != atLeast ] || [ "$n" -gt 0 ] || die "assertCount: at least 0 passes on any screen - ask for at least 1, or use exact or atMost"
  case "$m" in exact|contains) ;; *) die "assertCount: unknown match '$m' - use exact or contains";; esac
  got="$(find_el "$q" "$kind" "$m" count "$in")" || st=$?
  [ "$st" -eq 0 ] || die "assertCount FAILED: $(lookup_err "$st" "$in")"
  case "$got" in ''|*[!0-9]*) die "assertCount FAILED: the lookup gave no count";; esac
  case "$op" in
    atLeast) [ "$got" -ge "$n" ] && held=1;;
    exact)   [ "$got" -eq "$n" ] && held=1;;
    atMost)  [ "$got" -le "$n" ] && held=1;;
  esac
  if [ "$kind" = id ]; then what="assertCount id"; [ "$got" = 1 ] && q="$got element with id '$q'" || q="$got elements with id '$q'"
  else what="assertCount ($m match)"; [ "$got" = 1 ] && q="$got element matches '$q'" || q="$got elements match '$q'"; fi
  q="$q${in:+ in the element with id '$in'}"
  [ -n "$held" ] || die "$what FAILED: $q on the screen, expected $words $n"
  ok "$what: $q on the screen, $words $n"; }
# The state a step asks of an element (#103): "selected=true checked=false", as
# the flow builder writes it. state_miss <id> <want> <cx> <cy> <selected>
# <checked> <expanded> prints what does not hold, in words, or nothing; state_words says
# what was asked. A checked state asked of an element that has none ("none":
# not checkable on Android, no checked word on iOS) is a miss, never a pass:
# checked="false" on a plain view would otherwise satisfy "checked": false.
state_miss(){ local q="$1" want="$2" sel="$5" chk="$6" exp="${7:-unread}" k v out=""
  for k in $want; do v="${k#*=}"
    case "${k%%=*}" in
      selected) [ "$sel" = "$v" ] || { [ "$v" = true ] && out="${out:+$out; }'$q' is not selected" || out="${out:+$out; }'$q' is selected"; };;
      checked) case "$chk" in
          none)  out="${out:+$out; }'$q' has no checked state - the app does not mark it as checkable";;
          mixed) out="${out:+$out; }'$q' is partly checked (mixed)";;
          *) [ "$chk" = "$v" ] || { [ "$v" = true ] && out="${out:+$out; }'$q' is not checked" || out="${out:+$out; }'$q' is checked"; };;
        esac;;
      expanded) case "$exp" in
          none)   out="${out:+$out; }'$q' has no expanded state - the app does not mark it as expandable";;
          both)   out="${out:+$out; }'$q' offers both expand and collapse - its expanded state cannot be told";;
          unread) out="${out:+$out; }'$q': the expanded state is read only through the screen helper, and this read had no actions in it";;
          *) [ "$exp" = "$v" ] || { [ "$v" = true ] && out="${out:+$out; }'$q' is not expanded" || out="${out:+$out; }'$q' is expanded"; };;
        esac;;
    esac
  done
  printf '%s' "$out"; }
state_words(){ local k out=""
  for k in $1; do case "$k" in selected=true) k="selected";; selected=false) k="not selected";; checked=true) k="checked";; checked=false) k="not checked";; expanded=true) k="expanded";; expanded=false) k="not expanded";; esac; out="${out:+$out, }$k"; done
  printf '%s' "$out"; }
# The density of the screen, for a constraint written in dp. Read once per run
# and kept: it cannot change under a run, and every box assertion would
# otherwise pay for another adb round trip. An override density wins when one is
# set - that is the density the app is actually laid out at.
ADPI=""
adpi(){
  [ -n "$ADPI" ] && { printf '%s' "$ADPI"; return 0; }
  # The lookup above ran in a command substitution, so the paths it set up died
  # with that subshell: without this, a machine whose adb is not on PATH answers
  # every dp constraint with "the device did not report its density" while every
  # other step works.
  apaths
  local out; out="$(adb shell wm density 2>/dev/null | tr -d '\r')"
  ADPI="$(printf '%s\n' "$out" | sed -n 's/^Override density: *\([0-9][0-9]*\).*/\1/p' | tail -1)"
  [ -n "$ADPI" ] || ADPI="$(printf '%s\n' "$out" | sed -n 's/^Physical density: *\([0-9][0-9]*\).*/\1/p' | tail -1)"
  [ -n "$ADPI" ] || return 1
  printf '%s' "$ADPI"; }
# ── assertBox: the geometry the lookup already read ──────────────────────────
# Every lookup reads the box of its candidates to decide whether they are on the
# screen at all, and then keeps the centre. What a layout check asks about lives
# in the numbers it drops: is this control still big enough to hit, is this
# header below the notch, did this banner go edge to edge. assertBox asks for the
# box instead and compares it with what the flow says.
#
# A constraint is written in pixels (48), in dp ("48dp") or as a share of the
# screen ("5%") - the share is of the width for the horizontal ones and of the
# height for the vertical ones, so the same flow file reads the same on a phone
# and on a tablet. dp is the unit the rules are written in: a touch target is 48
# of them on Android and 44 points on iOS, and on a 320 dpi screen 48 pixels is
# 24 dp - half the minimum, asserted as if it passed. The measured numbers go
# into the message whatever the unit: "48x50, expected height at least 96" is a
# bug report, "assert failed" is not.
#
# The spec arrives as one field of name/value pairs, packed with the two
# separators the conditions use - same reason: several of them belong to one step.
#
# A constraint can also name another element by id (#127): above, below, leftOf,
# rightOf, apart. Where that element sits depends on the device and the content,
# so "the pill is above the tab bar" written as a share of the screen is green by
# luck on one phone and red on the next; measured against the bar it holds on
# both. Edges that touch keep the relation, an overlap breaks it. Both boxes come
# from one read of the screen - two reads could compare two different frames of
# a screen that moved in between.
box_die(){ HELD_TREE=""; die "$@"; }
assert_box(){
  local q="${1:-}" kind="${2:-assert}" spec="${3:-}" idx="${4:-}" what
  [ "$kind" = id ] && what="id" || what="text"
  [ -n "$q" ] || die "assertBox needs a non-empty $what"
  # A box assertion with no constraint passes on anything that is on the screen,
  # which is what assertText and assertId already say. The builder refuses it
  # before the run; this is the same door for the command line.
  [ -n "$spec" ] || die "assertBox needs at least one constraint - minWidth, minHeight, maxWidth, maxHeight, minX, minY, maxX, maxY, or above, below, leftOf, rightOf, apart with an id"
  local dpi=""
  case "$COND_SEP$spec" in
    *"${COND_SEP}above$COND_KV"*|*"${COND_SEP}below$COND_KV"*|*"${COND_SEP}leftOf$COND_KV"*|*"${COND_SEP}rightOf$COND_KV"*|*"${COND_SEP}apart$COND_KV"*)
      HELD_TREE=""; HELD_TREE="$(ui)" || exit 1;;
  esac
  local out st=0
  # An index (#46) picks the element measured; the elements it is measured
  # against are named by id and taken as tapId takes them.
  out="$(find_el "$q" "$kind" exact box "" "$idx")" || st=$?
  [ "$st" -ne 5 ] || box_die "assert FAILED: $(index_miss "$idx" "$out" "$([ "$kind" = id ] && printf "id '%s'" "$q" || printf "'%s'" "$q")")"
  [ "$st" -eq 0 ] || box_die "assert FAILED: $(lookup_err "$st")"
  if [ -z "$out" ]; then
    [ "$what" = id ] && box_die "assert FAILED: $(id_miss "$q")"
    box_die "assert FAILED: no element with $what '$q'"
  fi
  local x1 y1 x2 y2 sx1 sy1 sx2 sy2
  read -r x1 y1 x2 y2 sx1 sy1 sx2 sy2 <<<"$out"
  local w=$((x2-x1)) h=$((y2-y1)) sw=$((sx2-sx1)) sh=$((sy2-sy1))
  local where="${w}x${h} at [$x1,$y1][$x2,$y2]" bad="" good="" pair name val px n want
  local ox1 oy1 ox2 oy2 there held
  while [ -n "$spec" ]; do
    case "$spec" in *"$COND_SEP"*) pair="${spec%%"$COND_SEP"*}"; spec="${spec#*"$COND_SEP"}";; *) pair="$spec"; spec="";; esac
    name="${pair%%"$COND_KV"*}"; val="${pair#*"$COND_KV"}"
    case "$name" in
      above|below|leftOf|rightOf|apart)
        st=0; out="$(find_el "$val" id exact box)" || st=$?
        [ "$st" -eq 0 ] || box_die "assert FAILED: $(lookup_err "$st")"
        [ -n "$out" ] || box_die "assert FAILED: $(id_miss "$val" " to compare $what '$q' with")"
        read -r ox1 oy1 ox2 oy2 _ <<<"$out"
        there="'$val' ($((ox2-ox1))x$((oy2-oy1)) at [$ox1,$oy1][$ox2,$oy2])"
        # The test sits left of && so that a relation that does not hold is an
        # answer, not the end of the step under set -e.
        held=""
        case "$name" in
          above)   [ "$y2" -le "$oy1" ] && held=1;;
          below)   [ "$y1" -ge "$oy2" ] && held=1;;
          leftOf)  [ "$x2" -le "$ox1" ] && held=1;;
          rightOf) [ "$x1" -ge "$ox2" ] && held=1;;
          apart)   { [ "$x2" -le "$ox1" ] || [ "$x1" -ge "$ox2" ] || [ "$y2" -le "$oy1" ] || [ "$y1" -ge "$oy2" ]; } && held=1;;
        esac
        if [ -n "$held" ]; then good="$good, $name '$val'"; else bad="$bad, $name $there"; fi
        continue;;
    esac
    case "$val" in
      *%) n="${val%\%}"
          # A share of the screen needs a screen. A dump that does not report its
          # own rect cannot answer "5% of the height", and a question that cannot
          # be answered must not come back as a pass.
          case "$name" in
            minWidth|maxWidth)
              [ "$sw" -gt 0 ] || box_die "assert FAILED: '$name' is a share of the screen width, and this screen does not report its own rect"
              px=$(( sw * n / 100 ));;
            minHeight|maxHeight)
              [ "$sh" -gt 0 ] || box_die "assert FAILED: '$name' is a share of the screen height, and this screen does not report its own rect"
              px=$(( sh * n / 100 ));;
            # An edge is a place, not a length: "5% down the screen" is measured
            # from where the screen starts. On Android the root rect starts at
            # 0,0 and the two readings agree; an iOS window need not, and a
            # percentage counted from zero would then point outside it.
            minX|maxX)
              [ "$sw" -gt 0 ] || box_die "assert FAILED: '$name' is a share of the screen width, and this screen does not report its own rect"
              px=$(( sx1 + sw * n / 100 ));;
            *)
              [ "$sh" -gt 0 ] || box_die "assert FAILED: '$name' is a share of the screen height, and this screen does not report its own rect"
              px=$(( sy1 + sh * n / 100 ));;
          esac;;
      *dp) n="${val%dp}"
          if is_android; then
            # A dp that cannot be converted must not pass as a pixel: 48 unread
            # would compare against 48 pixels and call half a touch target fine.
            if [ -z "$dpi" ]; then
              # Called for the variable, not for what it prints: in a command
              # substitution the cache it fills would die with the subshell, and
              # every dp constraint would go back to the device for a number
              # that cannot change under a run.
              adpi >/dev/null || box_die "assert FAILED: '$name' is written in dp and the device did not report its density"
              dpi="$ADPI"
            fi
            px=$(( n * dpi / 160 ))
          else
            # An iOS frame is already in points, which is the density-independent
            # unit: 44pt is 44 here, and the conversion is the identity.
            px="$n"
          fi;;
      *) px="$val";;
    esac
    # Both numbers, because either alone hides half the answer: "at least 48dp"
    # does not say what that is on this screen, and "at least 96" does not say
    # which line of the flow file to change.
    if [ "$px" = "$val" ]; then want="$val"; else want="$val = $px px"; fi
    case "$name" in
      minWidth)  [ "$w"  -ge "$px" ] || bad="$bad, width at least $want (is $w)";;
      maxWidth)  [ "$w"  -le "$px" ] || bad="$bad, width at most $want (is $w)";;
      minHeight) [ "$h"  -ge "$px" ] || bad="$bad, height at least $want (is $h)";;
      maxHeight) [ "$h"  -le "$px" ] || bad="$bad, height at most $want (is $h)";;
      minX)      [ "$x1" -ge "$px" ] || bad="$bad, left edge at $want or more (is $x1)";;
      maxX)      [ "$x2" -le "$px" ] || bad="$bad, right edge at $want or less (is $x2)";;
      minY)      [ "$y1" -ge "$px" ] || bad="$bad, top edge at $want or more (is $y1)";;
      maxY)      [ "$y2" -le "$px" ] || bad="$bad, bottom edge at $want or less (is $y2)";;
      *) box_die "assertBox does not know the constraint '$name'";;
    esac
  done
  HELD_TREE=""
  [ -z "$bad" ] || die "assert FAILED: $what '$q' is $where - expected ${bad#, }"
  ok "assert box: $what '$q'${idx:+ index $idx} is $where$good"
}
# ── turnWheel: turn a wheel picker by a number of rows (#120) ────────────────
# A wheel has no id, and only the rows next to the selected one are in reach: a
# tap on one moves the wheel by one row. So the step finds the wheels on the
# screen, takes the n-th (top to bottom, then left to right), and taps the row
# above or below once per row, reading the wheel after every tap.
#
# It counts rows instead of looking for a value because iOS does not show the
# value: a wheel is a slider whose value is the number of its row (measured on
# an iOS 26.5 simulator, karlmehta/yukti#120: a date's month wheel said 5002 for
# November, the day 4993 for the 3rd, the year 2025 for 2026; a UIPickerView the
# row). There every tap must move that number by exactly one in the direction
# asked - a picker that refuses a row (a date past its maximum) jumps back, and
# the step says so instead of counting the tap. Android shows the value, the
# text of the NumberPicker's EditText, and a tap must change it. What the wheel
# ends on is the flow's to check, on the screen the picker writes to.
#
# One line per wheel: "x1 y1 x2 y2<TAB>value". Android: NumberPicker nodes
# (spinner date and time pickers, number pickers); the rows next to the selected
# one are a third of its height away.
awheels(){ apaths; aui | "$PY" -c '
import sys,re,html
xml=sys.stdin.read()
if not xml.strip(): sys.exit(1)
B=r"bounds=\"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]\""
def a(tag,n):
    # Both quote forms, as everywhere else on this path (#100).
    m=re.search(n+r"=(?:\"([^\"]*)\"|\x27([^\x27]*)\x27)",tag)
    return " ".join(html.unescape(m.group(1) if m.group(1) is not None else m.group(2)).split()) if m else ""
wheels=[]; texts=[]
for m in re.finditer(r"<node\b[^>]*>", xml):
    t=m.group(0); b=re.search(B,t)
    if not b: continue
    box=tuple(map(int,b.groups()))
    if not (box[2]>box[0] and box[3]>box[1]): continue
    cls=a(t,"class")
    if cls.endswith("NumberPicker"): wheels.append(box)
    elif cls.endswith("EditText"): texts.append((box,a(t,"text")))
# A row of wheels is the wheels whose tops are within 20 px of the first.
rows=[]
for w in sorted(wheels,key=lambda b:b[1]):
    if not rows or w[1]-rows[-1][0][1]>20: rows.append([])
    rows[-1].append(w)
for w in [w for r in rows for w in sorted(r,key=lambda b:b[0])]:
    v=[x for bx,x in texts if w[0]<=(bx[0]+bx[2])//2<w[2] and w[1]<=(bx[1]+bx[3])//2<w[3]]
    print("%d %d %d %d\t%s" % (w+(v[0] if v else "",)))
'; }
# iOS: elements with the PickerElement trait - each wheel of a UIDatePicker or a
# UIPickerView is one, a slider with no id and no label; a plain slider is not.
# The selected row is in the middle of the frame and the next one 32 points away
# (rows about 31 high, measured on the same simulator).
iwheels(){ paths; ui | "$PY" -c '
import json,sys
raw=sys.stdin.read().strip()
if not raw: sys.exit(1)
try: els=json.loads(raw)
except ValueError: sys.exit(2)
def g(b,*ks):
    for k in ks:
        if b.get(k) is not None:
            try: return float(b[k])
            except (TypeError,ValueError): return 0.0
    return 0.0
out=[]
for e in els:
    tr=e.get("traits") or []
    if isinstance(tr,str): tr=tr.replace(","," ").split()
    if not any(str(t).strip()=="PickerElement" for t in tr): continue
    b=e.get("frame") or {}
    x,y,w,h=g(b,"X","x"),g(b,"Y","y"),g(b,"Width","width"),g(b,"Height","height")
    if not (w>0 and h>0): continue
    out.append((int(y),int(x),int(x+w),int(y+h)," ".join(str(e.get("AXValue") if e.get("AXValue") is not None else "").split())))
rows=[]
for o in sorted(out):
    if not rows or o[0]-rows[-1][0][0]>8: rows.append([])
    rows[-1].append(o)
for y,x,x2,y2,v in [o for r in rows for o in sorted(r,key=lambda o:o[1])]: print("%d %d %d %d\t%s" % (x,y,x2,y2,v))
'; }
IWHEEL_ROW=32
wheels(){ if is_android; then awheels; else iwheels; fi; }
turn_wheel(){ local n="$1" rows="$2" all cnt line cur first x1 y1 x2 y2 row dir=1 k i=0 st empty=0
  [ -n "$n" ] && [ -n "$rows" ] || die "turnWheel needs a wheel number and a number of rows"
  case "$rows" in -*) dir=-1; k="${rows#-}";; *) k="${rows#+}";; esac; k=$((10#$k))
  [ "$k" -gt 0 ] || die "turnWheel: $rows rows is no turn at all"
  while :; do
    st=0; all="$(wheels)" || st=$?
    [ "$st" -eq 0 ] || die "turnWheel: $(lookup_err "$st")"
    cnt="$(printf '%s' "$all" | grep -c .)"
    if [ "$n" -gt "$cnt" ]; then
      [ "$cnt" = 0 ] && die "turnWheel: there are no wheels on the screen"
      [ "$cnt" = 1 ] && die "turnWheel: no wheel $n on the screen, there is 1"
      die "turnWheel: no wheel $n on the screen, there are $cnt"
    fi
    line="$(printf '%s\n' "$all" | sed -n "${n}p")"; read -r x1 y1 x2 y2 <<<"${line%%$'\t'*}"
    # A wheel that shows nothing cannot be told from a wheel that did not move,
    # and "changed" would count it as a row. Read twice more, then say so.
    if [ -z "${line#*$'\t'}" ]; then
      empty=$((empty+1)); [ "$empty" -lt 3 ] || die "turnWheel: wheel $n shows no value$([ "$i" -eq 0 ] || echo " after row $i of $k") - nothing to count the rows by"
      sleep 0.5; continue
    fi
    empty=0
    if [ "$i" -eq 0 ]; then first="${line#*$'\t'}"
    else
      wheel_moved "$cur" "${line#*$'\t'}" "$dir" || \
        die "turnWheel: wheel $n went from '$cur' to '${line#*$'\t'}' on row $i of $k - $(wheel_miss "$cur" "${line#*$'\t'}")"
    fi
    cur="${line#*$'\t'}"
    [ "$i" -lt "$k" ] || { ok "turnWheel: wheel $n turned $rows rows, '$first' to '$cur'"; return 0; }
    if is_android; then row=$(( (y2-y1)/3 )); else row="$IWHEEL_ROW"; fi
    tap "$(( (x1+x2)/2 ))" "$(( (y1+y2)/2 + dir*row ))" || die "turnWheel: the tap on wheel $n was refused"
    i=$((i+1))
  done; }
# Did one tap move the wheel by one row? iOS: the row number, by exactly one in
# the direction asked. Android, or an iOS wheel that does not report a number:
# the value changed - a number there can wrap (31 to 1) or step by more than one
# (minutes by 5), so its direction is not checked.
wheel_moved(){ if ! is_android && is_num "$1" && is_num "$2"; then [ "$((10#$2))" -eq "$((10#$1 + $3))" ]; else [ "$1" != "$2" ]; fi; }
wheel_miss(){ if [ "$1" = "$2" ]; then echo "it did not move: the end of the wheel, or the tap missed it"
  else echo "not the next row: the picker did not take that row (a date past its minimum or maximum?) or the tap moved it further"; fi; }
is_num(){ case "$1" in ''|*[!0-9]*) return 1;; *) return 0;; esac; }

# The same emptying, addressed by id. Coordinates were the only way to name the
# field, so a flow that addresses everything else by id had no way to clear one
# at all - and `type` appends: typed into a field that already holds text it
# makes a value neither the flow nor the app ever names, and the run fails on a
# later step, far from the line that caused it. The clearing itself, and every
# check around it, is the one `clearText` does.
# The tree the field is found in is held for the clearing, which reads the same
# screen before its first touch: one read where there were two (#106).
clear_id(){ local q="${1:-}" idx="${2:-}"; [ -n "$q" ] || die "clearTextId needs a non-empty id"; local xy st=0
  HELD_TREE=""; HELD_TREE="$(ui)" || exit 1
  xy="$(find_el "$q" id exact centre "" "$idx")" || st=$?
  [ "$st" -ne 5 ] || { HELD_TREE=""; die "$(index_miss "$idx" "$xy" "id '$q'")"; }
  [ "$st" -eq 0 ] || { HELD_TREE=""; die "$(lookup_err "$st")"; }
  [ -n "$xy" ] || { xy="$(id_miss "$q")"; HELD_TREE=""; die "$xy"; }
  clear_field $xy "clearTextId '$q'"; }
# A lookup answers with coordinates, with "no such element", or with no answer at
# all - and "no answer" comes in two flavours the caller has to tell apart: the
# screen could not be read (status 1: the dump failed) and the screen was read but
# cannot be judged (status 3: it does not report its own bounds, so nothing on it
# can be called visible). Neither of them means the element is absent.
# Who says it, once. A lookup that could not read the screen at all has already
# printed the reason and recorded it for the step result - aui and ui end in
# `die`, and that `die` only kills the command substitution they run in. The
# caller adding "see the error above" printed that same line a second time, and
# on the quiet status 3 - a tree that arrived and cannot be judged, which nobody
# has spoken for - it pointed at an error that was never printed. So: stop the
# run without a word when the reason is already out, and supply the words when
# it is not.
# The caller's own words belong to status 3 alone: there the screen was read and
# the caller is the one who knows what it was looking for. Status 2 is a device
# that answered with something unreadable, which is no more the caller's fault
# than a failed dump - saying "no element at x,y" for it blames the point the
# step was aimed at.
lookup_die(){ local st="${1:-1}" msg="${2:-}"
  case "$st" in
    1) exit 1;;
    3) die "${msg:-$(lookup_err 3)}";;
    *) die "$(lookup_err "$st")";;
  esac; }
# Status 2 is the device's, wherever it is reported: the mark is set here, in
# the one place every caller passes through to word it (#96).
lookup_err(){ case "${1:-1}" in
    2) device_fault; printf '%s' "the device answered, but not with a tree that can be read";;
    # On iOS status 3 is the blank tree (ios_blank): idb answered, and the app
    # did not answer the accessibility request in time - it gave its root with
    # no size and nothing in it, or nothing at all. Said as that, not as a screen
    # without bounds: the words used to send the reader to the tree and to idb.
    # Not said: that the interface stopped - an app still drawing after a launch
    # gives the same tree; whether the app or the simulator holds it is not known
    # here either. The threads taken with the failure are the evidence.
    3) if [ "${YUKTI_PLATFORM:-}" = ios ]; then
         printf '%s' "the app did not answer the accessibility request in time: the tree has no element with a size, so nothing on the screen can be judged"
       else printf '%s' "the screen was read but does not report its own bounds, so nothing on it can be called visible"; fi;;
    # The element an "in" names is not on the screen (#102); the id comes second.
    # It says why as tapId does (#167): not in the tree, or there with no area
    # or off the screen - and that the id is the container's, not the target's.
    4) if [ -n "${2:-}" ]; then id_miss "$2" "$IN_FOR"; else printf "no element with id ''"; fi;;
    *) printf '%s' "cannot read the screen - see the error above";; esac; }
# The negative assertions. Absence is the one verdict where an EMPTY answer is the
# pass, which makes it the one verdict that a missing answer passes by accident:
# an unreadable screen has no element on it either. Both statuses are checked
# before the verdict.
#
# Neither verb scrolls, by contract: a count of swipes cannot prove that something is
# absent, and they change the state the next step is about to check. What these
# two state is "not on the screen as it is now", and the guide says so in those
# words - a flow that means "not anywhere in this list" scrolls for itself.
# By hand the constraints are written name=value: the packed form the runner
# uses is two control characters, and nobody types those.
#   yukti assert-box tab-today id minWidth=48 minHeight=48
#   yukti assert-box chat-pill id above=tab-bar
assert_box_args(){ local q="${1:-}" kind="${2:-}" spec="" pair
  # Without this, `assert-box email-input minWidth=48` reads the constraint as
  # the name of a lookup and then complains that no constraint was given.
  case "$kind" in
    assert|id) ;;
    *) die "usage: yukti assert-box \"<text or id>\" <assert|id> name=value [name=value ...]";;
  esac
  shift 2
  for pair in "$@"; do spec="${spec:+$spec$COND_SEP}${pair%%=*}$COND_KV${pair#*=}"; done
  assert_box "$q" "$kind" "$spec"; }
# A negative check that passes on a root-only tree (#201, step 1). On iOS, right
# after a screen change, the tree can come back as the app's root alone: the
# Application, labelled and with a size, and no other element with a size,
# while the screen is drawn. Unlike a blank tree (#191, no element with a size)
# the lookups read it as a screen, so "not there" passes on it although nothing
# was read. Elements of no size beside the root do not change that: the
# lookups do not count them either. The home screen's root is labelled " "
# (app_front) and is not this: a negative step after the app went away is not
# counted here. The verdict stays as it is for now: the step's line says so,
# and the flow's result counts such passes (the log's last lines and the
# property root-only-passes), so a run gives the number before the verdict is
# decided. The tree is the one the check's own lookup read, kept by every read
# ($YUKTI_LAST_TREE, set inside a flow only: outside one nothing is said).
root_only(){ is_android && return 1
  [ -n "${YUKTI_LAST_TREE:-}" ] && [ -s "$YUKTI_LAST_TREE" ] || return 1
  [ "$(wc -c < "$YUKTI_LAST_TREE")" -lt 16384 ] || return 1
  "$PY" -c '
import json,sys
try: els=json.load(open(sys.argv[1], encoding="utf-8"))
except (OSError,ValueError): sys.exit(1)
if not isinstance(els,list): sys.exit(1)
# The size the lookups take: either spelling of the frame keys (as ios_blank).
def n(b,*ks):
    for k in ks:
        v=b.get(k)
        if v is None: continue
        try: return float(v)
        except (TypeError,ValueError): return 0.0
    return 0.0
# Root-only: the Application with a size and a non-empty label, and no other
# element with a size; elements of zero size beside it do not count.
root=False
for e in els:
    if not isinstance(e,dict): continue
    b=e.get("frame") or {}
    sized=isinstance(b,dict) and n(b,"Width","width")>0 and n(b,"Height","height")>0
    if e.get("type")=="Application":
        if sized and " ".join(str(e.get("AXLabel") or "").split()): root=True
    elif sized: sys.exit(1)
sys.exit(0 if root else 1)' "$YUKTI_LAST_TREE" 2>/dev/null; }
# Prints the words a passing step adds, and counts the pass for the flow's
# result beside the flow's record: one count per flow, whatever run directory
# a caller shares between flows.
root_only_note(){ root_only || return 0
  [ -z "${FLOW_REC:-}" ] || printf 'x' >> "$FLOW_REC.root-only" 2>/dev/null || true
  printf '%s' " - passed on a root-only tree: nothing was read (#201)"; }
# With an "in" id, absence is judged inside that element, and an element that
# is not there fails the step: nothing can be absent from what is not on screen.
assert_not_text(){ local q="${1:-}" m="${2:-exact}" in="${3:-}" xy st=0
  [ -n "$q" ] || die "assertNotText needs a non-empty value"
  case "$m" in exact|contains) ;; *) die "assertNotText: unknown match '$m' - use exact or contains";; esac
  xy="$(find_el "$q" assert "$m" centre "$in")" || st=$?
  [ "$st" -eq 0 ] || die "assertNot FAILED: $(lookup_err "$st" "$in")"
  [ -z "$in" ] || { [ -z "$xy" ] || die "assertNot FAILED ($m match): '$q' IS in the element with id '$in', at $xy"
    ok "assertNot ($m) in '$in': '$q' not in that element"; return; }
  [ -z "$xy" ] || die "assertNot FAILED ($m match): '$q' IS on the screen, at $xy"
  ok "assertNot ($m): '$q' not on the current screen$(root_only_note)"; }
assert_not_id(){ local q="${1:-}" xy st=0
  [ -n "$q" ] || die "assertNotId needs a non-empty id"
  xy="$(find_el "$q" id)" || st=$?
  [ "$st" -eq 0 ] || die "assertNot FAILED: $(lookup_err "$st")"
  [ -z "$xy" ] || die "assertNot FAILED: an element with id '$q' IS on the screen, at $xy"
  ok "assertNot id: '$q' not on the current screen$(root_only_note)"; }
# The wait the other way (#104): a save sheet that closes, a spinner that goes,
# an old value that leaves. assertNotText and assertNotId look once, so a flow
# held a fixed pause in front of them - wasted on a fast device, too short on a
# slow one. These poll the same lookup until the element is gone and fail when
# it is still there at the timeout. "Gone" is what the assertNot verbs call
# absent: not on the screen as it is now, never scrolled for.
#
# The rule of the negative assertions holds here too: a screen that could not
# be read is not a disappearance - a crashed app has no element on its screen
# either. Such a read is not counted as gone; the poll keeps going, and a
# timeout whose last read failed says the screen cannot be read, as waitFor
# does. A timeout with the element still there says where it is.
#
# $SECONDS counts whole seconds, and the poll starts somewhere inside one, so a
# "less than" test ends the wait anywhere from t-1 to t seconds in - with a
# timeout of 1, after a single read. The test is "not more than" instead: the
# wait lasts at least the timeout it promises, and up to a second longer plus
# one read - poll_pause cuts its pause to the time left. waitForNot, whose test
# is "not more than", can add one more pause of 0.5 s and one more read.
# The pause between two reads of a wait. On iOS a read of a heavy screen can run
# into idb's ceiling of about 3 s and come back as the app's root with no size,
# while the app's main thread goes on answering it: in the measured run every
# sample of that thread lay under accessibility requests, and a new full read
# every 0.5 s keeps it there. So after a read that took more than a second, or
# came back blank, the next waits max(2 s, what that read took), cut to the
# time the wait has left (never under 0.5 s); a line says so. Fast reads keep
# 0.5 s, and Android, and a wait outside a flow, are as before.
read_blank(){ [ -n "${FLOW_REC:-}" ] || return 0
  if [ "$1" = 1 ]; then : > "$FLOW_REC.read-blank"; elif [ -e "$FLOW_REC.read-blank" ]; then rm -f "$FLOW_REC.read-blank"; fi 2>/dev/null || true; }
poll_pause(){ local t0="$1" t="$2" ms p left why
  if is_android || [ -z "${FLOW_REC:-}" ]; then sleep 0.5; return 0; fi
  ms="$(cat "$FLOW_REC.read-ms" 2>/dev/null || true)"; case "$ms" in ''|*[!0-9]*) ms=0;; esac
  [ "$ms" -gt 1000 ] || [ -e "$FLOW_REC.read-blank" ] || { sleep 0.5; return 0; }
  p=$ms; [ "$p" -ge 2000 ] || p=2000
  left=$(( (t - (SECONDS - t0)) * 1000 )); [ "$left" -ge 500 ] || left=500
  [ "$p" -le "$left" ] || p=$left
  why="took $ms ms"; [ ! -e "$FLOW_REC.read-blank" ] || why="$why and came back blank (no element with a size)"
  printf '  · next read in %d.%03d s: the last one %s\n' $((p / 1000)) $((p % 1000)) "$why" >&2
  sleep "$((p / 1000)).$(printf '%03d' $((p % 1000)))"; }
wait_gone(){ local q="${1:-}" t="${2:-10}" m="${3:-exact}" mode="${4:-assert}" xy="" st=0 last="" readable=0 t0 el name label
  [ "$mode" = id ] && name=waitForNotId || name=waitForNotText
  [ -n "$q" ] || die "$name needs a non-empty value"
  case "$t" in ''|*[!0-9]*|0) die "$name: timeout must be a whole number of seconds greater than zero, got '$t'";; esac
  case "$m" in exact|contains) ;; *) die "$name: unknown match '$m' - use exact or contains";; esac
  [ "$mode" = id ] && label="waitForNot id" || label="waitForNot ($m match)"
  say "$label: up to ${t}s for '$q' to leave the screen"
  t0=$SECONDS
  while :; do
    st=0; xy="$(find_el "$q" "$mode" "$m")" || st=$?
    if [ "$st" -eq 0 ]; then readable=1
      [ -n "$xy" ] || { el=$((SECONDS - t0)); ok "$label: '$q' gone from the screen after ${el}s$(root_only_note)"; return 0; }
      last="$xy"
    else readable=0; fi
    [ $((SECONDS - t0)) -le "$t" ] || break
    poll_pause "$t0" "$t"
  done
  [ "$readable" = 1 ] || die "$label FAILED after ${t}s waiting for '$q' to go: $(lookup_err "$st")"
  die "$label FAILED: '$q' still on the screen at $last after ${t}s"; }
wait_s(){ sleep "${1:-2}"; }
# `wait` is a sleep, and a sleep is the wrong tool for a screen that loads its
# content: too short and the flow goes red at random, too long and every run
# pays for it, on every flow. scrollToText retries, but it SCROLLS between the
# tries - on a screen that is still loading it swipes the content away instead
# of waiting for it.
#
# waitFor polls the same lookup the taps and the oracle use, and it never
# scrolls. The timeout is the failure: a screen that never arrives is a red
# step, not a green one and not an eight-swipe detour.
#
# An unreadable screen is not "not there yet". The poll keeps going while the
# screen cannot be read, and the timeout then says which of the two happened -
# the distinction the lookup verbs already make.
#
# By id, "not on screen" is three different states, and the timeout names the
# one it ended in, from one more read: the id is not in the tree, it is there at
# zero size (an element that grows in with an animation and stayed at its start),
# or it is there outside the screen. The words "not on screen after Ns" stay at
# the front, so a reader that looked for them still finds them.
#
# `optional` (waitForId only, the builder enforces it) turns that timeout into a
# skip: a `~` line, the step lands in the report as skipped with the same words,
# and the flow goes on. The words travel to the record in FLOW_OPT_MISS. An
# unreadable screen still stops the flow: it is not an answer either way.
#
# With an "in" id (waitFor only, #102) the poll waits for the text inside that
# element, and an element not yet on the screen is "not there yet", not an
# unreadable screen. The timeout says which of the two it ended in.
#
# With an index (#46) the poll waits for that match: fewer matches is "not
# there yet", and the timeout says how many there were.
wait_for(){ local q="${1:-}" t="${2:-10}" m="${3:-exact}" mode="${4:-assert}" opt="${5:-}" in="${6:-}" want="${7:-}" idx="${8:-}" xy readable=1 lst=1 nosc=0 t0 el label why="" msg miss="" many=""
  [ -n "$q" ] || die "waitFor needs a non-empty value"
  case " $want " in *" expanded="*) local AUI_ACTIONS=1;; esac
  case "$t" in ''|*[!0-9]*|0) die "waitFor: timeout must be a whole number of seconds greater than zero, got '$t'";; esac
  case "$m" in exact|contains) ;; *) die "waitFor: unknown match '$m' - use exact or contains";; esac
  [ "$mode" = id ] && label="waitFor id" || label="waitFor ($m match)${in:+ in '$in'}"
  [ -z "$idx" ] || label="$label, index $idx"
  say "$label: up to ${t}s for '$q'${want:+, $(state_words "$want")}"
  t0=$SECONDS
  while :; do
    if xy="$(find_el "$q" "$mode" "$m" "${want:+state}" "$in" "$idx")"; then readable=1; nosc=0; miss=""; many=""
      # With a state (#103) the element on the screen is not enough: the wait
      # goes on until it is in that state, and the last miss is what it says.
      if [ -n "$xy" ] && [ -n "$want" ]; then miss="$(state_miss "$q" "$want" $xy)"; [ -z "$miss" ] || xy=""; [ -n "$xy" ] && { set -- $xy; xy="$1 $2"; }; fi
      [ -n "$xy" ] && { el=$((SECONDS - t0)); ok "$label: '$q' on screen at $xy after ${el}s${want:+, $(state_words "$want")}"; return 0; }
    else lst=$?
      if [ "$lst" -eq 4 ]; then readable=1; nosc=1; many=""
      elif [ "$lst" -eq 5 ]; then readable=1; nosc=0; miss=""; many="$xy"
      else readable=0; fi
    fi
    [ $((SECONDS - t0)) -lt "$t" ] || break
    poll_pause "$t0" "$t"
  done
  [ "$readable" = 1 ] || die "$label FAILED after ${t}s waiting for '$q': $(lookup_err "$lst")"
  if [ -n "$miss" ]; then
    msg="$miss after ${t}s"
    if [ "$opt" = optional ]; then FLOW_OPT_MISS="$msg"; skipped "$label: $msg - optional, the flow goes on"; return 0; fi
    die "$label FAILED: $msg"
  fi
  case "$many" in "0 "*) many="";; esac
  if [ "$mode" = id ] && [ -z "$many" ]; then
    if xy="$(find_el "$q" id exact why "" "$idx")"; then
      case "$xy" in
        # It arrived between the last poll and this read: it is on the screen -
        # and with a state asked, it passes only in that state.
        on\ *)   if [ -n "$want" ]; then
                   xy="$(find_el "$q" id exact state "" "$idx")" || { lst=$?; die "$label FAILED after ${t}s waiting for '$q': $(lookup_err "$lst")"; }
                   [ -n "$xy" ] && miss="$(state_miss "$q" "$want" $xy)" || miss="'$q' left the screen"
                   if [ -n "$miss" ]; then msg="$miss after ${t}s"
                     [ "$opt" = optional ] && { FLOW_OPT_MISS="$msg"; skipped "$label: $msg - optional, the flow goes on"; return 0; }
                     die "$label FAILED: $msg"; fi
                   set -- $xy; xy="on $1 $2"
                 fi
                 el=$((SECONDS - t0)); ok "$label: '$q' on screen at ${xy#on } after ${el}s${want:+, $(state_words "$want")}"; return 0;;
        zero\ *) set -- $xy; why="at zero size [$2,$3][$4,$5]";;
        off\ *)  set -- $xy; why="outside the screen at [$2,$3][$4,$5]";;
        *)       why="not in the tree";;
      esac
    else lst=$?; [ "$lst" -eq 5 ] || die "$label FAILED after ${t}s waiting for '$q': $(lookup_err "$lst")"; case "$xy" in "0 "*) ;; *) many="$xy";; esac; fi
  fi
  if [ -n "$in" ]; then
    [ "$nosc" = 1 ] && why="$(id_miss "$in" "$IN_FOR")" || why="not in the element with id '$in'"
  fi
  [ -z "$many" ] || why="$(index_miss "$idx" "$many" "$([ "$mode" = id ] && printf "id '%s'" "$q" || printf "'%s'" "$q")${in:+ in the element with id '$in'}")"
  msg="'$q' not on screen after ${t}s${why:+ - $why}"
  if [ "$opt" = optional ]; then
    FLOW_OPT_MISS="$msg"; skipped "$label: $msg - optional, the flow goes on"; return 0
  fi
  die "$label FAILED: $msg"; }
# A direction reveals what lies that way: `down` shows what is further down the
# content, which means the finger travels up. Same for `left` and `right`.
#
# A name the tool does not know used to scroll DOWN - the `else` of a two-way
# test - so `{"do":"scroll","value":"sideways"}` swiped down and said nothing.
# The list is checked first now, and a typo stops the flow.
#
# On Android the vertical swipes used to be fixed device pixels, 700 to 300 at
# x=200. On a 1080x2400 screen that is a sixth of the height, all of it in the
# upper third, and eight of them - all scrollToText gives itself - covered about a
# screen and a third: an element further down the list failed as "not on screen
# after 8 swipes" while it was there. They are taken from the screen now, down
# the middle of its width from 70% of its height to 30% - the proportions that
# made those flows pass on a 1080x2400 emulator. Every vertical scroll goes
# further than it did; a flow that counted on a short swipe to stop near
# something wants scrollToText with "edges":"clear".
# The duration grows with the distance, 3 ms for every 4 px, which is the speed
# of the old swipe: 400 px in 300 ms. `input swipe` lets go at the speed it moved,
# so the same 300 ms over a longer distance would be a harder fling, and the list
# would keep moving after the finger is up - past rows that scrollToText reads
# only once the swipe is over. Only the distance changes, not the speed.
# When the screen size cannot be read, screen_wh answers with the recording basis
# and says so once, and the swipe is proportional to that: 349 px, a little
# shorter than the 400 it used to be.
# iOS follows the same rule in points, so a flow scrolls the same share of the
# screen on both platforms. The old iOS pair was 320 to 720 at x=200: 400 points,
# 46% of the 874-point basis. The new one is 349 points on that screen, 383 on a
# 956-point phone and 325 on an 812-point one: shorter than it was on every
# iPhone, and longer only on a screen taller than 1000 points, an iPad. This is
# the one place where the change goes against the title of #68. The duration is
# left to idb as it was.
# Written, not measured - no Mac.
# On Android the horizontal pair is computed from the screen as well: across the widest
# element that says it scrolls, from a fifth of its width to four fifths of it -
# or, when the screen has no such element, across the middle of the screen, with
# a line in the run to say that is what happened.
# A swipe between two points (#48): the gesture with no element under it and no
# fixed direction - pulling a list down from its top, dragging a sheet away. The
# points are pixels or shares of the screen, as for tap (see flow_xy). The finger
# moves at the speed of scroll on both platforms and the duration is always
# given to the tool, never left to it. Android: `input swipe` at 3 ms for every
# 4 px, the speed scroll moves at, and never under 300 ms, the old fixed scroll
# swipe: `input swipe` lets go at the speed it moved, and a short line drawn in a
# few ms is a flick (it still lets go at that speed: a swipe here can fling a
# list). iOS: iswipe, idb at IOS_SWIPE_PT_S, at least 0.3 s, as scroll - left to
# idb, a swipe often did not move the list at all, and one faster than about
# 175 pt/s flings it (see IOS_SWIPE_PT_S); at 150 it is a drag. No step asks for
# a speed: a flick cannot be written yet. Written for iOS, not
# measured - no Mac. A keyboard that is up is closed first, as for scroll: the
# keys cover the lower part of the screen and would take the touch.
# swipe_xy <x1> <y1> <x2> <y2> - the points on the device's own screen.
swipe_xy(){ local dur
  [ "$1 $2" != "$3 $4" ] || die "swipe: from $1,$2 to $3,$4 does not move - on this screen both points are the same; that is a press, not a swipe"
  kb_before_swipe swipe || :
  if is_android; then apaths
    dur="$(awk -v a="$1" -v b="$2" -v c="$3" -v d="$4" 'BEGIN{t=int(sqrt((c-a)^2+(d-b)^2)*3/4); if(t<300)t=300; print t}')"
    adb shell input swipe "$1" "$2" "$3" "$4" "$dur" || die "swipe: the device refused the swipe from $1,$2 to $3,$4"
    ok "swipe $1,$2 -> $3,$4 in $dur ms"
  else paths
    dur="$(iswipe_s "$1" "$2" "$3" "$4")" || exit 1
    iswipe "$1" "$2" "$3" "$4" || die "swipe: idb refused the swipe from $1,$2 to $3,$4"
    ok "swipe $1,$2 -> $3,$4 in ${dur} s"
  fi; }
# swipe_step <x> <y> <toX> <toY> - the points as a flow file or the command line
# writes them; a flow passes "raw" as a fifth word only from the command line.
swipe_step(){ local a b x y tx ty
  x="$(xy_word x "${1:-}" swipe)" || exit 1; y="$(xy_word y "${2:-}" swipe)" || exit 1
  tx="$(xy_word toX "${3:-}" swipe)" || exit 1; ty="$(xy_word toY "${4:-}" swipe)" || exit 1
  a="$(flow_xy "$x" "$y" "${5:-}")" || exit 1; b="$(flow_xy "$tx" "$ty" "${5:-}")" || exit 1
  swipe_xy $a $b; }
swipe_args(){ [ $# -eq 4 ] || die "usage: yukti swipe <x> <y> <toX> <toY> - pixels (200) or a share of the screen (\"50%\")"
  swipe_step "$1" "$2" "$3" "$4" raw; }
# The scroll STEP. `scroll` itself is also the blind swipe inside a search, which
# asks about the keyboard on its own, so the question lives here and not in it.
scroll_step(){
  # scroll checks the direction too; it is checked here first so that a typo
  # fails the step before a keyboard is closed for it.
  case "${1:-down}" in up|down|left|right) ;; *) die "scroll: '${1:-down}' is not a direction - use up, down, left or right";; esac
  kb_before_swipe scroll || :
  scroll "${1:-down}"; }
scroll(){ local d="${1:-down}" w h
  case "$d" in up|down|left|right) ;; *) die "scroll: '$d' is not a direction - use up, down, left or right";; esac
  if is_android; then apaths
    case "$d" in
      up|down)
        local lo hi dur
        set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
        lo=$(( h * 30 / 100 )); hi=$(( h * 70 / 100 )); dur=$(( (hi - lo) * 3 / 4 ))
        if [ "$d" = down ]; then adb shell input swipe $(( w / 2 )) "$hi" $(( w / 2 )) "$lo" "$dur"
        else adb shell input swipe $(( w / 2 )) "$lo" $(( w / 2 )) "$hi" "$dur"; fi;;
      left|right)
        local cy x1 x2 span aim ast=0
        # A dump that failed is not the same answer as a screen with nothing to
        # aim at: it used to arrive as the second, so a broken dump printed the
        # warning and swiped blind. A bare `scroll` step has no lookup in front
        # of it to catch that later, so it dies here, like every other reader of
        # the screen.
        aim="$(ahscroller)" || ast=$?
        [ "$ast" -eq 0 ] || lookup_die "$ast"
        set -- $aim; cy="${1:-}"; x1="${2:-}"; x2="${3:-}"
        if [ -z "$cy" ]; then
          # Nothing on this screen says it scrolls sideways. The swipe still goes
          # out, because a dump does not always report what an app implements -
          # but it says so once per run, since this is the case where the gesture
          # is most likely to be taken for a press.
          # To stderr, like the other line that can be printed from inside a
          # command substitution: scroll_to runs in one, so a warning on stdout
          # would arrive inside the coordinates it returns.
          [ -n "${H_WARNED:-}" ] || warn "no horizontally scrollable element in the dump - swiping across the middle of the screen, which the app may read as a press on what is there" >&2
          H_WARNED=1
          set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
          cy=$(( h / 2 )); x1=0; x2="$w"
        fi
        span=$(( x2 - x1 ))
        if [ "$d" = left ]; then adb shell input swipe $(( x1 + span / 5 )) "$cy" $(( x2 - span / 5 )) "$cy" 300
        else adb shell input swipe $(( x2 - span / 5 )) "$cy" $(( x1 + span / 5 )) "$cy" 300; fi;;
    esac
    return
  fi
  paths
  case "$d" in
    up|down)
      local lo hi
      set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
      # The finger goes down where a touch moves the list: in the middle band,
      # never at 30% of the height. A sticky header is a fixed number of points
      # tall, so on a short screen 30% lies on it and the touch scrolls nothing -
      # a screen on an iPhone SE (375x667) whose header ends near y 200: 30% is
      # 200, and `scroll up` from there moved the page 0 and 0 points, the same
      # swipe from y 300 256 and 256 (2026-10-29); on an iPhone 16 Pro 30% is 262,
      # just below the header, so it never showed there. Up therefore runs from
      # 45% to 85%, the same 40% of the height as down (70% to 30%), which
      # already starts in the middle.
      lo=$(( h * 30 / 100 )); hi=$(( h * 70 / 100 ))
      if [ "$d" = down ]; then iswipe $(( w / 2 )) "$hi" $(( w / 2 )) "$lo"
      else iswipe $(( w / 2 )) $(( h * 45 / 100 )) $(( w / 2 )) $(( h * 85 / 100 )); fi;;
    left|right)
      set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
      if [ "$d" = left ]; then iswipe $(( w / 5 )) $(( h / 2 )) $(( w * 4 / 5 )) $(( h / 2 ))
      else iswipe $(( w * 4 / 5 )) $(( h / 2 )) $(( w / 5 )) $(( h / 2 )); fi;;
  esac; }
# ── swipeId / swipeText: a swipe on an element, not on the screen (#82) ───────
# A list row that hides its actions (delete, archive) shows them only after a
# swipe across the row itself, and until then the buttons are not in the tree.
# `scroll` cannot do it: it starts away from the elements inside a list on
# purpose, so that the list gets the gesture. Here the element has to get it, and
# the list must not move.
#
# The element is found the way tapId and tapText find it, and a miss reads in
# their words. Neither scrolls - scrollToId or scrollToText first for a row below the fold.
# The direction is where the finger goes: "left" draws it from right to left
# across the row, which is the swipe that shows a delete button on its right.
# That is the other way round from `scroll`, whose direction names what comes
# into view.
#
# The stroke is a share of the element's width (of its height for up and down),
# centred on the element's centre, so it begins and ends inside it: a stroke from
# the centre over 60% of the width would leave the row at its edge and could land
# on its neighbour. 60% by default, YUKTI_SWIPE_SHARE to change it, at most 90:
# at 100 the finger goes down on the element's edge, which for a full-width row
# is the edge of the screen, where the system takes the touch for its own gesture
# (Back on Android, edge pan on iOS).
#
# Only the part of the element on the screen counts. A lookup accepts an element
# whose centre is on the screen, and its frame may run past the edge - a carousel
# wider than the screen, a tall card under the bottom - so the stroke is measured
# on what can be touched, never started off the screen.
#
# A stroke shorter than the touch slop is a tap to the app, and a tap on a row
# opens it: at least 48 pixels on Android (8 dp of slop is 24 pixels on a
# 480 dpi screen, twice that leaves a margin) and 20 points on iOS (slop ~10).
#
# swipeText finds what tapText would tap, which is often the label inside a row,
# not the row: the stroke is then a share of the label. For a row, swipeId on the
# row's container. On iOS the start point is checked like a tap point, and a
# control with an id of its own under it (a chevron, a "more" button) fails the
# step as covered.
#
# iOS: in rows with swipe actions a long swipe can perform the first action
# instead of only showing it. 60% is written, not measured on iOS: if the action
# fires earlier there, the default goes down for both platforms. The finger moves
# at IOS_SWIPE_PT_S, as in scroll - an explicit duration, never idb's own.
SWIPE_SHARE="${YUKTI_SWIPE_SHARE:-60}"
# swipe_el <id or text> <id|text> <up|down|left|right>
swipe_el(){ local q="${1:-}" mode="$2" d="${3:-}" verb what out st=0 v
  [ "$mode" = id ] && { verb=swipeId; what=id; } || { verb=swipeText; what=text; }
  [ -n "$q" ] || die "$verb needs a non-empty $what"
  case "$d" in up|down|left|right) ;; "") die "$verb needs a direction - up, down, left or right, where the finger goes";;
    *) die "$verb: '$d' is not a direction - use up, down, left or right";; esac
  # Digits only and no leading zero, as for the swipe speed; above 100 the stroke
  # leaves the element, which is what this step exists not to do.
  case "$SWIPE_SHARE" in ''|*[!0-9]*|0*) die "YUKTI_SWIPE_SHARE must be a whole share of the element from 1 to 90, with no leading zero, is '$SWIPE_SHARE'";; esac
  [ "$SWIPE_SHARE" -le 90 ] || die "YUKTI_SWIPE_SHARE must be a whole share of the element from 1 to 90, is '$SWIPE_SHARE' - above 90 the finger starts on the element's edge"
  # The row may sit under the keyboard; closing it after the lookup would move
  # the row away from the coordinates just read.
  kb_before_swipe "$verb" || :
  out="$(find_el "$q" "$mode" exact box)" || st=$?
  [ "$st" -eq 0 ] || die "$(lookup_err "$st")"
  if [ -z "$out" ]; then [ "$mode" = id ] && die "$(id_miss "$q")"; die "no element matching '$q'"; fi
  local x1 y1 x2 y2 sx1 sy1 sx2 sy2 vx1 vy1 vx2 vy2 cx cy half fx fy tx ty least
  read -r x1 y1 x2 y2 sx1 sy1 sx2 sy2 <<<"$out"
  # The part on the screen.
  vx1=$x1; vy1=$y1; vx2=$x2; vy2=$y2
  [ "$vx1" -ge "$sx1" ] || vx1=$sx1; [ "$vy1" -ge "$sy1" ] || vy1=$sy1
  [ "$vx2" -le "$sx2" ] || vx2=$sx2; [ "$vy2" -le "$sy2" ] || vy2=$sy2
  cx=$(( (vx1 + vx2) / 2 )); cy=$(( (vy1 + vy2) / 2 ))
  case "$d" in
    left|right) half=$(( (vx2 - vx1) * SWIPE_SHARE / 200 ));;
    *)          half=$(( (vy2 - vy1) * SWIPE_SHARE / 200 ));;
  esac
  is_android && least=48 || least=20
  [ $((half * 2)) -ge "$least" ] || die "$verb: '$q' is $((vx2 - vx1))x$((vy2 - vy1)) on the screen - $SWIPE_SHARE% of it is a stroke of $((half * 2)), the app would take less than $least for a tap"
  case "$d" in
    left)  fx=$((cx + half)); tx=$((cx - half)); fy=$cy; ty=$cy;;
    right) fx=$((cx - half)); tx=$((cx + half)); fy=$cy; ty=$cy;;
    up)    fy=$((cy + half)); ty=$((cy - half)); fx=$cx; tx=$cx;;
    down)  fy=$((cy - half)); ty=$((cy + half)); fx=$cx; tx=$cx;;
  esac
  # Where the finger goes down is the point that has to be the element, as for a
  # tap: something drawn over it would take the gesture.
  v="$(ihit "$q" "$mode" "$fx" "$fy")"
  case "$v" in
    ok) ;;
    covered*) die "'$q' at $fx,$fy is covered by ${v#covered } - not swiped, the touch would go to that instead";;
    *) warn "could not read what is under '$q' at $fx,$fy - swiping as before";;
  esac
  if is_android; then apaths
    # The rule of the vertical scroll: 3 ms for every 4 pixels, here at least
    # 300 ms, so a short row is not flicked.
    local dur=$(( half * 2 * 3 / 4 )); [ "$dur" -ge 300 ] || dur=300
    adb shell input swipe "$fx" "$fy" "$tx" "$ty" "$dur" || die "$verb: the device refused the swipe on '$q'"
  else paths
    iswipe "$fx" "$fy" "$tx" "$ty" || die "$verb: idb refused the swipe on '$q'"
  fi
  ok "swiped $what '$q' $d, $fx,$fy to $tx,$ty ($SWIPE_SHARE% of $((x2 - x1))x$((y2 - y1)))"; }
# a11y reports FULL-CONTENT coords; taps need ON-SCREEN coords. Scroll a label into the viewport.
# Stop on an unreadable screen instead of swiping eight times into the dark:
# a swipe changes state, and the state is what the next step is checking.
# The accepted band used to be written out as 60..840. Those are one device's
# numbers - an iPhone 16 Pro, 874 points tall - not a universal viewport. A dump
# reports coordinates in the screen's own space, so on a 720x1600 Android phone
# the bottom navigation sits at y=1497 and every tab read as off-screen: each tap
# on one paid the full eight swipes before it acted, and those swipes unload the
# rows the NEXT step asserts on, which then reads as a defect in the app.
# Keep the proportions and scale them to the screen the run is actually on. On
# the original 874-point basis the bounds come out as 60 and 840, unchanged.
# The basis those numbers were written against: the screen Studio records on, an
# iPhone 16 Pro at 402x874 points. Same env names Studio already uses for it
# (studio/server.py DEVICE_PT_W/H), so one override covers both halves.
BASIS_W="${YUKTI_DEVICE_PT_W:-402}"; BASIS_H="${YUKTI_DEVICE_PT_H:-874}"; BAND_TOP=60; BAND_BOTTOM=840
# iOS swipes move the finger at a set speed, in points a second. Left to idb (no
# --duration) a swipe often did not scroll at all: a 349-point `scroll down` on a
# React Native ScrollView moved it 0, 0 and 0 points, and `scroll up` from the
# bottom of another 0, 0, 0, 0, 31 and 206. Faster than the list's fling threshold
# the list runs on after the finger lifts: the Android rule (3 ms for every 4,
# 262 ms for those 349 points) flung it ~930 points, 0.6 s ~590, 1.0 s ~495. At
# 175 points a second and slower it moved the finger's distance less ~10 (touch
# slop), every time: 349 in 2 s and in 3 s, 140 in 1 s and in 2 s, on three
# screens (iPhone 16 Pro simulator, iOS 26.3, 2026-10-29). Points are the device-
# independent unit, so the speed is the same on every iPhone; 150 keeps a margin
# under the 175 measured. A search reads the screen after every swipe, so a slower
# finger costs time, not steps.
IOS_SWIPE_PT_S="${YUKTI_IOS_SWIPE_PT_S:-150}"
# iswipe <x1> <y1> <x2> <y2> - an idb swipe at IOS_SWIPE_PT_S, at least 0.3 s.
# iswipe_s <x1> <y1> <x2> <y2> - how long that swipe takes, in seconds.
iswipe_s(){
  # Digits only, and no leading zero: "0" is no speed, "00" divided by zero and
  # sent the swipe with no duration (the very stall this fixes), "007" read as 7.
  case "$IOS_SWIPE_PT_S" in ''|*[!0-9]*|0*) die "YUKTI_IOS_SWIPE_PT_S must be a whole number of points a second above 0, with no leading zero, is '$IOS_SWIPE_PT_S'";; esac
  awk -v a="$1" -v b="$2" -v c="$3" -v d="$4" -v v="$IOS_SWIPE_PT_S" \
    'BEGIN{s=sqrt((c-a)^2+(d-b)^2)/v; if(s<0.3)s=0.3; printf "%.2f", s}'; }
iswipe(){ local t
  t="$(iswipe_s "$1" "$2" "$3" "$4")" || exit 1
  idb ui swipe --udid "$(U)" --duration "$t" "$1" "$2" "$3" "$4"; }
# Where a per-run cache lives. Set once per invocation just before the command
# runs (see the bottom of this file) and inherited by everything the run shells
# out to. Empty when there is no such directory, and then nothing is cached at
# all: the device is asked every time and the answer is still correct, only
# slower. A placeholder path would be worse than nothing - a flow is free to
# name any directory in a screenshot step and would create it, and a cache
# under a fixed name outlives the run, which is the bug this replaced.
run_dir(){ printf '%s' "${YUKTI_RUN_DIR:-}"; }
# Screen size in the same space the dump reports. Cached in a file, not in a
# variable: every caller reads this through $( ), and an export from a command
# substitution never reaches the caller, so a variable would re-ask the device on
# every step. Asking must never be fatal and must never silently change geometry:
# on any failure the answer is the basis, which is exactly the old behaviour of
# the band. The vertical swipe reads it too, and on the basis it is 349 px, a
# little shorter than the 400 it used to be - the warning below says so.
#
# The cache belongs to the RUN, not to the device: RUN_DIR is made once per
# invocation and removed when it ends. A device-named key cannot do this job -
# an emulator's serial is its port, not its AVD, so two AVDs started one after
# the other are both emulator-5554 and the second would read the first one's
# geometry with nothing in the log to say so; a resize on a live device does not
# change the serial at all. Scoped to the run, a stale answer cannot exist:
# the run that measured it is the only run that can read it.
screen_wh(){ local d f m out w h
  d="$(run_dir)"; f=''; m=''
  # No run directory, no cache: both halves stay empty and every lookup asks.
  [ -n "$d" ] && { f="$d/screen-$YUKTI_PLATFORM"; m="$f.fallback"; }
  [ -n "$f" ] && [ -s "$f" ] && { cat "$f"; return 0; }
  out=''
  if is_android; then
    apaths   # platform-tools go into PATH here; without it adb is simply absent
    out="$(adb shell wm size 2>/dev/null | tr -d '\r' | sed -n 's/.*: *\([0-9][0-9]*\)x\([0-9][0-9]*\).*/\1 \2/p' | tail -1 || true)"
  else
    paths
    # points only: a pixel field here would silently triple every number on a 3x
    # device, so a missing key must fall through to the basis, never to pixels.
    out="$(idb describe --udid "$(U)" --json 2>/dev/null | "$PY" -c 'import json,sys
try:
    d=(json.load(sys.stdin).get("screen_dimensions") or {})
    print(int(d["width_points"]), int(d["height_points"]))
except Exception:
    pass' 2>/dev/null || true)"
  fi
  set -- $out; w="${1:-}"; h="${2:-}"
  case "$w" in ''|*[!0-9]*|0) w='';; esac
  case "$h" in ''|*[!0-9]*|0) h='';; esac
  if [ -n "$w" ] && [ -n "$h" ]; then
    if [ -n "$f" ]; then
      ( printf '%s %s' "$w" "$h" > "$f" ) 2>/dev/null || true   # only a real answer is worth remembering
      rm -f "$m" 2>/dev/null || true   # it answered: the next failure is news again
    fi
    printf '%s %s' "$w" "$h"; return 0
  fi
  # NEVER cache the fallback. A device merely slow to appear would otherwise
  # switch the band off for every later step with nothing in the log to say so.
  # The notice goes to stderr: this function is read through a substitution, and
  # a line on stdout would be parsed as the screen size.
  if [ -z "$m" ] || [ ! -f "$m" ]; then
    warn "screen size unavailable, using the recording basis ${BASIS_W}x${BASIS_H}" >&2
    [ -n "$m" ] && { ( : > "$m" ) 2>/dev/null || true; }
  fi
  printf '%s %s' "$BASIS_W" "$BASIS_H"; }
screen_w(){ set -- $(screen_wh); printf '%s' "${1:-$BASIS_W}"; }
screen_h(){ set -- $(screen_wh); printf '%s' "${2:-$BASIS_H}"; }
# The width of the strips at the sides of the screen where a swipe of the search
# must not start (#123, see list_probe): 50 dp on Android, 50 points on iOS -
# the distance from the edge at which a stack screen takes a touch as the back
# gesture - and 2 more, since the touch at 50 dp itself is still taken
# (measured: x 100 px at density 320 moved nothing). iOS is written, not
# measured - no Mac. Cached for the run like the screen size: scroll_to runs in
# a command substitution, so a variable would die with it and every search
# would ask the device again. Without the density the strip is a seventh of the width - 52 dp
# of a phone 360 dp wide, the narrowest common one, so wider than needed on any
# other, two or three times on a tablet - and that answer is not cached, as the
# screen size fallback is not.
edge_px(){ local w="$1" d f m out
  is_android || { printf '52'; return 0; }
  d="$(run_dir)"; f=''; m=''
  [ -n "$d" ] && { f="$d/edge-$YUKTI_PLATFORM"; m="$f.fallback"; }
  [ -n "$f" ] && [ -s "$f" ] && { cat "$f"; return 0; }
  if out="$(adpi)"; then
    out=$(( (52 * out + 159) / 160 ))
    [ -n "$f" ] && { ( printf '%s' "$out" > "$f" ) 2>/dev/null || true; rm -f "$m" 2>/dev/null || true; }
    printf '%s' "$out"; return 0
  fi
  if [ -z "$m" ] || [ ! -f "$m" ]; then
    warn "screen density unavailable, keeping swipes $(( w * 52 / 360 )) px off the sides of the screen" >&2
    [ -n "$m" ] && { ( : > "$m" ) 2>/dev/null || true; }
  fi
  printf '%s' $(( w * 52 / 360 )); }
# A recorded step carries a point on the screen it was recorded on. Studio records
# at BASIS_W x BASIS_H points; replayed on a 720x1600 phone the same pair lands
# somewhere else. Scale it where a recorded number ENTERS the run - not inside
# tap(), which is also fed coordinates taken straight from the device's own dump
# (tapText, tapId, dismiss) and must stay a raw primitive in the device's space.
# Set YUKTI_TAP_SCALE=0 to replay recorded pairs as-is.
scale_xy(){ local x="${1:?x}" y="${2:?y}" w h nx ny
  [ "${YUKTI_TAP_SCALE:-1}" = 0 ] && { printf '%s %s' "$x" "$y"; return 0; }
  set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
  [ "$w" = "$BASIS_W" ] && [ "$h" = "$BASIS_H" ] && { printf '%s %s' "$x" "$y"; return 0; }
  nx=$(( x * w / BASIS_W )); ny=$(( y * h / BASIS_H ))
  say "scaled $x,$y -> $nx,$ny (recorded ${BASIS_W}x${BASIS_H}, screen ${w}x${h})" >&2
  printf '%s %s' "$nx" "$ny"; }
# A point a step DESCRIBES rather than recorded (#48): "50%" of the width,
# written by hand. A share is taken of the screen the run is on - pixels on
# Android, points on iOS, the same space the dump and the tap use - and never
# goes through scale_xy, so it does not depend on the recording basis
# (YUKTI_DEVICE_PT_W/H) or on YUKTI_TAP_SCALE. A pixel does: a hand-written
# Android flow with 540 taken from an Android dump is scaled by w/402 and lands
# at 1450. Both are proportional to the screen; neither keeps a point on a
# control laid out at a fixed distance from an edge. Pixels still go through
# scale_xy, so a flow recorded in Studio replays as it did. A pair may mix the
# two; the pixel half is then scaled the way scale_xy would. 100% is the last
# pixel (point on iOS), not the one past the edge. When the screen size cannot
# be read, the share is of the recording basis, and screen_wh says so once.
# xy_word <name> <value> <who> - dies unless the value is whole pixels or a
# whole share of the screen; prints it normalised ("08" is octal in the shell).
xy_word(){ local k="$1" v="$2" who="$3" n
  case "$v" in
    ''|*[!0-9%]*|*%*%|%*|*%?*) die "$who: \"$k\" is '$v' - it has to be a whole number of pixels (200) or a whole share of the screen (\"50%\")";;
  esac
  # More digits than any screen has would wrap in the shell arithmetic below:
  # 9223372036854775808% came out negative and passed the 100% test.
  n="${v%\%}"; [ "${#n}" -le 5 ] || die "$who: \"$k\" is '$v' - more than any screen has; pixels (200) or a whole share of the screen (\"50%\")"
  n=$(( 10#$n ))
  case "$v" in *%) [ "$n" -le 100 ] || die "$who: \"$k\" is '$v' - a share of the screen cannot be more than 100%"; printf '%s%%' "$n";; *) printf '%s' "$n";; esac; }
# xy_axis <value> <screen> <basis> <scale 0|1> - one coordinate on the screen.
xy_axis(){ local v="$1" n="$2" b="$3" p
  case "$v" in
    *%) p=$(( ${v%\%} * n / 100 )); [ "$p" -lt "$n" ] || p=$(( n - 1 )); printf '%s' "$p";;
    *) if [ "$4" = 1 ]; then printf '%s' $(( v * n / b )); else printf '%s' "$v"; fi;;
  esac; }
# flow_xy <x> <y> [raw] - the point a step names, on the screen the run is on.
# "raw" is the command line: its pixels are the device's own, as `yukti tap`'s
# always were, and only a share is worked out.
flow_xy(){ local x="$1" y="$2" raw="${3:-}" w h s=1 nx ny
  case "$x$y" in *%*) ;; *) if [ "$raw" = raw ]; then printf '%s %s' "$x" "$y"; else scale_xy "$x" "$y"; fi; return;; esac
  set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
  { [ "${YUKTI_TAP_SCALE:-1}" = 0 ] || [ "$raw" = raw ]; } && s=0
  nx="$(xy_axis "$x" "$w" "$BASIS_W" "$s")"; ny="$(xy_axis "$y" "$h" "$BASIS_H" "$s")"
  # A pixel half that was scaled says so, in the words scale_xy uses.
  case "$s:$x:$y" in 1:*%:*%) say "point $x,$y -> $nx,$ny (screen ${w}x${h})" >&2;;
    1:*) say "point $x,$y -> $nx,$ny (pixels recorded ${BASIS_W}x${BASIS_H}, screen ${w}x${h})" >&2;;
    *) say "point $x,$y -> $nx,$ny (screen ${w}x${h})" >&2;; esac
  printf '%s %s' "$nx" "$ny"; }
# The command-line forms of tap and clear: the same words for a bad coordinate
# as the builder gives a flow file.
tap_args(){ local x y; [ $# -eq 2 ] || die "usage: yukti tap <x> <y> - pixels (200) or a share of the screen (\"50%\")"
  x="$(xy_word x "$1" tap)" || exit 1; y="$(xy_word y "$2" tap)" || exit 1
  tap $(flow_xy "$x" "$y" raw); }
clear_args(){ local x y; [ $# -ge 2 ] || die "usage: yukti clear <x> <y> - pixels (200) or a share of the screen (\"50%\")"
  x="$(xy_word x "$1" clear)" || exit 1; y="$(xy_word y "$2" clear)" || exit 1; shift 2
  clear_field $(flow_xy "$x" "$y" raw) "$@"; }
# How long a search may swipe, in seconds. A safety net, not the boundary of the
# search: a search on a list stops where the list ends (see scroll_to), and this
# is reached only by a list that is still moving. Eight swipes used to be the
# boundary, and eight swipes covered a few screens: a row further down failed as
# "not on screen" while it was there. Then thirty swipes - and a count is a
# different distance on every reader: a swipe with the screen helper costs about
# 1.5 s, with uiautomator dump or on iOS about 4 s. The limit is time now (#107),
# set so that the slowest reader still makes the thirty swipes it used to; with
# the helper, which also swipes a screen at a time, that is many times the
# distance. The wait at the end of a list for it to grow has its own time and is
# not counted here. YUKTI_SCROLL_BUDGET sets it, for the tests.
SCROLL_BUDGET=120
scroll_budget(){ case "${YUKTI_SCROLL_BUDGET:-}" in ''|*[!0-9]*|0) printf '%s' "$SCROLL_BUDGET";; *) printf '%s' "$YUKTI_SCROLL_BUDGET";; esac; }
# A screen whose dump shows no list keeps the old boundary. There is no end to
# find there, and swipes past the eighth learn nothing a flow is waiting for.
SCROLL_TRIES_BLIND=8
# How long a search waits at the end of a list for the list to grow, in seconds.
# A screen often lays out its lower part after the first paint - after the
# transition, after a server response, after a deferred mount - and a search that
# gets there first sees a list that stopped moving and is not finished. The step's
# "timeout" sets it; this is the default. A real end costs it once per step.
SCROLL_GROW_WAIT=5
# How much of the band counts as "the edge" when a step asks to be clear of it.
# A fifth from each side: enough to clear a sticky header or a bottom bar, which
# is what the request is for, and not so much that a short list can never satisfy
# it.
CLEAR_PCT=20
# The inset of the band on x, as a percentage of the width. The vertical band is
# measured - BAND_TOP and BAND_BOTTOM against BASIS_H - and on x there is nothing
# measured to keep: no status bar, no navigation bar. So the proportion the top
# inset comes to, 60 of 874, is applied to both sides. Written out as its own
# number because `w * BAND_TOP / BASIS_H` reads as a dimension mistake.
BAND_SIDE_PCT=7
# The direction is for FINDING the element. Once it is on the screen, which way
# to swipe is decided by where it IS: an element at the top edge has to travel
# down the screen, and a search that walked downwards to find it would push it
# out of view instead and then report it missing - a row under a sticky header is
# exactly the case `"edges":"clear"` exists for.
#
# The list a search runs along, read from the held tree. Prints one line:
#   rows f l   sx sy ex ey dur   cx cy cex cey cdur   seam over   a1 a2 c1 c2
# `rows` names the first and last row of the list that are on the screen, and f
# and l are where they stand on the axis of the search - what two reads compare.
# Then the swipe for that direction, and the control swipe: shorter, slower, from
# another point. Prints nothing when the screen has no list on that axis.
#
# `seam` and `over` are for a list that travels further than the finger (#117).
# `seam` names the labelled rows on the screen that the swipe printed here
# leaves on it: where each will stand once the list has moved the length of that
# line, inside the visible part with 3% of it to spare. Hashes of their labels,
# comma-separated, or `-` when there is none. The sixth argument is a seam from
# an earlier read, and `over` is the answer about it: 1 - this read has
# labelled rows and none of them is in it, so the list went past the gesture;
# 0 - one of them is here; `-` - no seam was given, or the read has no labelled
# row to judge by (a list read before its rows are drawn).
#
# `a1 a2` is the visible part of the list on the axis of the search, `c1 c2`
# across it: where a row below the fold is judged to be inside the list (#116).
# The seventh argument is a length in pixels: the swipe is cut to it, from the
# same start, and its seam is reckoned for the line as cut. Empty - the line
# as drawn.
#
# Which element is the list: one that scrolls along the axis. On Android that is
# `scrollable="true"`, and the class names the axis where it can: a
# HorizontalScrollView scrolls sideways, any other ScrollView or ListView up and
# down, whatever its shape - a vertical list between a header and a bar, or any
# list in landscape, is wider than it is tall. Only the rest (RecyclerView, a
# pager, a custom view) is read by shape, the way ahscroller reads it: wider than
# tall scrolls sideways. On iOS the tree does not say what
# scrolls, only what kind of element it is: scroll views, tables and collections
# are the lists. When the element was already seen, the list is the smallest one
# holding it - the one that moves it; otherwise the largest on the screen.
#
# The rows of the list are its descendants. On Android they are read from the
# tree itself, so a bar drawn over the list is not one of them: it is a sibling
# of the list, and it does not move when the list does. The iOS tree is flat, so
# there a row is anything whose centre lies inside the list - a bar drawn over it
# is counted, and a row still moves where a bar does not. Written, not measured -
# no Mac.
#
# Where the swipe starts matters more than where it goes: the element under the
# first touch is the one offered the gesture. So it starts inside the list, on a
# line of text where there is one (see anchor below), never on something inside
# it that scrolls, slides or draws a chart by itself. It starts between 15% and
# 90% of the visible part of the list, which is already clipped clear of the
# status bar and the gesture bar, and keeps at least a twentieth of it before
# the end it travels towards. Across the screen it starts clear of the strips at
# its sides, where a stack screen takes the touch as the back gesture (#123).
# The strip is asked before the pipe and with no input: `adb shell` reads its
# standard input, and on the reading side of the pipe it would swallow the tree
# (measured: the first search of a run on a device failed, the tree never came).
list_probe(){ local e; e="$(edge_px "$3" </dev/null)"; ui | "$PY" -c '
import sys,re,json,hashlib
import xml.etree.ElementTree as ET
d=sys.argv[1]; near=sys.argv[2].split(); W=int(sys.argv[3]); H=int(sys.argv[4])
top=H*int(sys.argv[5])//int(sys.argv[7]); bot=H*int(sys.argv[6])//int(sys.argv[7])
android=sys.argv[8]=="android"
far=sys.argv[9]=="far"
vert=d in ("up","down")
raw=sys.stdin.read().strip()
if not raw: sys.exit(1)   # the tree never arrived; the reader has said why
lists=[]   # (box, sideways, rows) with rows = [(box, label, takes_gesture)]
def ok_size(b):
    w,h=b[2]-b[0],b[3]-b[1]
    return max(w,h)>=80 and min(w,h)>=20
if android:
    try: root=ET.fromstring(raw)
    except ET.ParseError: sys.exit(2)   # answered, not a tree
    def box(n):
        m=re.match(r"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]", n.get("bounds") or "")
        return tuple(map(int,m.groups())) if m else None
    for n in root.iter("node"):
        if n.get("scrollable")!="true": continue
        b=box(n)
        if not b or not ok_size(b): continue
        cls=n.get("class") or ""
        if "HorizontalScrollView" in cls: side=True
        elif "ScrollView" in cls or "ListView" in cls: side=False
        else: side=b[2]-b[0]>b[3]-b[1]
        rows=[]
        for k in n.iter("node"):
            if k is n: continue
            kb=box(k)
            if not kb or not (kb[2]>kb[0] and kb[3]>kb[1]): continue
            lab=k.get("text") or k.get("content-desc") or k.get("resource-id") or ""
            kc=k.get("class") or ""
            # A chart drawn with react-native-svg takes the drag as its own and
            # says nothing about it: measured on the Progress screen of the app
            # under test, a swipe that started on one moved nothing, twice.
            grab=k.get("scrollable")=="true" or "SeekBar" in kc or "svg" in kc.lower()
            text=kc.endswith("TextView") and bool(k.get("text")) and not grab
            rows.append((kb," ".join(lab.split()),grab,text))
        lists.append((b,side,rows))
else:
    try: els=json.loads(raw)
    except ValueError: sys.exit(2)
    def fr(e):
        f=e.get("frame") or {}
        def n(*ks):
            for k in ks:
                v=f.get(k)
                if v is None: continue
                try: return float(v)
                except (TypeError,ValueError): return 0.0
            return 0.0
        x,y,w,h=n("X","x"),n("Y","y"),n("Width","width"),n("Height","height")
        return (int(x),int(y),int(x+w),int(y+h))
    def kind(e): return (str(e.get("type") or "")+" "+str(e.get("role_description") or "")).lower()
    def is_list(t): return any(k in t for k in ("scrollview","scroll view","scroll area","table","collection")) and not any(k in t for k in ("cell","row","bar"))
    for e in els:
        if not is_list(kind(e)): continue
        b=fr(e)
        if not ok_size(b): continue
        rows=[]
        for k in els:
            if k is e: continue
            kb=fr(k)
            if not (kb[2]>kb[0] and kb[3]>kb[1]): continue
            cx,cy=(kb[0]+kb[2])//2,(kb[1]+kb[3])//2
            if not (b[0]<=cx<b[2] and b[1]<=cy<b[3]): continue
            if (kb[2]-kb[0])*(kb[3]-kb[1])>=(b[2]-b[0])*(b[3]-b[1]): continue
            lab=str(k.get("AXLabel") or k.get("AXValue") or k.get("AXUniqueId") or "")
            t=kind(k)
            g=is_list(t) or "slider" in t or "adjustable" in t
            rows.append((kb," ".join(lab.split()),g,("statictext" in t or "static text" in t) and bool(lab) and not g))
        lists.append((b,b[2]-b[0]>b[3]-b[1],rows))
lists=[l for l in lists if l[1]!=vert]
if not lists: sys.exit(0)
area=lambda b:(b[2]-b[0])*(b[3]-b[1])
hold=[]
if len(near)==2:
    nx,ny=int(near[0]),int(near[1])
    hold=[l for l in lists if l[0][0]<=nx<l[0][2] and l[0][1]<=ny<l[0][3]]
b,side,rows=min(hold,key=lambda l:area(l[0])) if hold else max(lists,key=lambda l:area(l[0]))
# The part of the list that is on the screen, between the bars.
x1,y1,x2,y2=max(b[0],0),max(b[1],top),min(b[2],W),min(b[3],bot)
if not (x2>x1 and y2>y1): sys.exit(0)
a1,a2,c1,c2=(y1,y2,x1,x2) if vert else (x1,x2,y1,y2)
pos=lambda r:((r[0][1]+r[0][3])//2 if vert else (r[0][0]+r[0][2])//2)
def shown(r):
    cx,cy=(r[0][0]+r[0][2])//2,(r[0][1]+r[0][3])//2
    return x1<=cx<x2 and y1<=cy<y2
seen=[r for r in rows if shown(r)]
# Rows without a label are compared by position alone. A list of identical
# unlabelled tiles moved by exactly a whole number of tiles would read as still;
# known, and left: a real swipe does not travel an exact multiple of a row.
named=[r for r in seen if r[1]] or seen
if named:
    named.sort(key=pos); f,l=named[0],named[-1]
    rid=hashlib.md5((f[1]+"\x00"+l[1]).encode()).hexdigest()[:12]; fp,lp=pos(f),pos(l)
else: rid,fp,lp="none",0,0
grabs=[r[0] for r in rows if r[2]]
def free(x,y): return not any(g[0]<=x<g[2] and g[1]<=y<g[3] for g in grabs)
# down and right reveal what lies further on: the finger travels towards the
# start of the axis. up and left, the other way.
fwd=d in ("down","right")
# The strips at the sides of the screen (#123). A stack screen takes a touch
# that starts within 50 dp of its left edge as the back gesture - right edge
# for a right-to-left layout - and the list under it never gets the drag:
# measured on the app under test, a swipe down from x 96 px at density 320
# moved nothing six times out of six, and once at x 100; the same swipe from
# x 104 moved the list. A swipe sideways from there is the back gesture itself. So the
# finger goes down at edge or further from either side, edge being 50 dp and a
# margin of 2 (edge_px); only where it goes down counts, not where it lifts. The
# right strip is for a right-to-left stack and is not measured. A list too
# narrow for both keeps the left one alone, and a list that lies in it from
# side to side is swiped where it is.
edge=int(sys.argv[12]) if len(sys.argv)>12 and sys.argv[12] else 0
eranges=[r for r in ((max(x1,edge),min(x2,W-edge)-1),(max(x1,edge),x2-1)) if r[0]<=r[1]][:1]
def off_edge(x,b1=None,b2=None):
    if not eranges: return x
    lo,hi=eranges[0]
    if b1 is not None: lo,hi=max(lo,b1),min(hi,b2-1)
    if lo>hi: return None
    return min(max(x,lo),hi)
def line(start,travel,cross):
    s=a1+(a2-a1)*start//100; e=s-(a2-a1)*travel//100 if fwd else s+(a2-a1)*travel//100
    c=c1+(c2-c1)*cross//100
    if vert: c=off_edge(c)
    else:
        # The whole line moves with its start, and stops at the end of the list.
        k=off_edge(s)-s; s,e=s+k,min(max(e+k,a1),a2-1)
    return (c,s,c,e) if vert else (s,c,e,c)
# First choice: start on a line of text in the list. Text does not hold on to a
# drag - the list takes it - while a grid point can land on anything, and a
# chart as wide as its card covers every point of the grid. Any line of text on
# the list will do, clear of what takes the gesture: the one nearest to aim
# percent of the way along it. The travel shrinks to fit the room left before
# the end it goes towards, and a line with less room than least is passed over -
# a list whose free text sits all in its first half still moves by a real swipe,
# rather than by the control swipe alone.
def anchor(aim,travel,least,away=None):
    best=None
    for r in rows:
        if not r[3] or not shown(r): continue
        cx,cy=(r[0][0]+r[0][2])//2,(r[0][1]+r[0][3])//2
        # Out of the strips at the sides, along the same line of text; a line
        # that lies all in a strip is passed over.
        cx=off_edge(cx,r[0][0],r[0][2])
        if cx is None or not free(cx,cy): continue
        p=cy if vert else cx
        g=(p-a1)*100//(a2-a1)
        if not fwd: g=100-g
        if not (15<=g<=90): continue
        t=min(travel,g-5)
        if t<least: continue
        # Another line than the first swipe took, not merely the next one down.
        if away is not None and abs(p-away)<=max(8,(a2-a1)*3//100): continue
        if best is None or abs(g-aim)<best[0]: best=(abs(g-aim),cx,cy,t)
    if best is None: return None
    cx,cy=best[1],best[2]; s=cy if vert else cx; dl=(a2-a1)*best[3]//100
    e=s-dl if fwd else s+dl
    return (cx,s,cx,e) if vert else (s,cy,e,cy)
def pick(starts,travel,crosses,skip=None):
    for cr in crosses:
        if cr==skip: continue
        for st in starts:
            p=line(st if fwd else 100-st,travel,cr)
            if free(p[0],p[1]): return p,cr
    return None,None
# The edges of the list are in the grid too: a chart or a card rarely reaches
# the side of the screen. A point of the grid in a strip at the side of the
# screen is moved out of it by line (#123).
crosses=[50,30,70,20,80,10,90]
# A far swipe covers a screen less a fifth: it starts near the end it leaves
# and stops a fifth short of the other, so the rows at that end are read twice.
if far:
    main=anchor(88,80,40); mc=None
    if main is None: main,mc=pick([88,85,90],80,crosses)
    if main is None: main,mc=line(88 if fwd else 12,80,50),50
else:
    main=anchor(70,40,20); mc=None
    if main is None: main,mc=pick([70,60,75],40,crosses)
    if main is None: main,mc=line(70 if fwd else 30,40,50),50
# A distance to go (#116): the finger goes down where it would anyway - only
# the length changes, and never past the length of the line as drawn.
want=int(sys.argv[11]) if len(sys.argv)>11 and sys.argv[11] else 0
if want>0:
    s,e=(main[1],main[3]) if vert else (main[0],main[2])
    dl=min(want,abs(e-s)); e=s-dl if fwd else s+dl
    main=(main[0],s,main[2],e) if vert else (s,main[1],e,main[3])
ctl=anchor(60,25,15,away=main[1] if vert else main[0])
if ctl is None: ctl,_=pick([62,72],25,crosses,skip=mc)
if ctl is None: ctl=line(62 if fwd else 38,25,30 if mc!=30 else 70)
dist=abs(main[3]-main[1]) if vert else abs(main[2]-main[0])
dur=max(200,dist*3//4) if vert else 300
# The seam: rows the main swipe leaves on the screen. A row cut by the edge of
# the list stands nearer to the edge it leaves through than it really is, so its
# landing is judged early - the safe side. Two rows with one label count as one:
# a row of the same name elsewhere can hide a list that went past, never invent
# one.
hx=lambda t:hashlib.md5(t.encode()).hexdigest()[:8]
spare=(a2-a1)*3//100
seam=sorted({hx(r[1]) for r in seen if r[1] and a1+spare<=(pos(r)-dist if fwd else pos(r)+dist)<=a2-spare})
chk=[c for c in (sys.argv[10] if len(sys.argv)>10 else "").split(",") if c and c!="-"]
here={hx(r[1]) for r in seen if r[1]}
over="-" if not chk or not here else ("0" if here.intersection(chk) else "1")
print(rid,fp,lp,*main,dur,*ctl,dur*2,",".join(seam) or "-",over,a1,a2,c1,c2)
' "$1" "${2:-}" "$3" "$4" "$BAND_TOP" "$BAND_BOTTOM" "$BASIS_H" "$YUKTI_PLATFORM" "${5:-}" "${6:-}" "${7:-}" "$e"; }
# The answers:
#   0 + coordinates - it is there, and where it has to be
#   4 + coordinates - in the band, never clear of its edges while the list still
#                     moved; the position is live
#   5 + coordinates - it came into view and the swipes took it out again; the
#                     position is the LAST SIGHTING and is stale. Saying "not on
#                     screen" of an element that was on it is a false reason, and
#                     a false reason is worse than a vague one.
#   6               - the list ended in that direction and the element is not in it
#   7               - the swipes ran out and the list was still moving
#   8               - the swipes ran out on a screen whose dump shows no list, so
#                     where the list ends could not be seen
#   9 + coordinates - it is on the screen, the list ended, and it is still not
#                     clear of the edge; the position is live
#
# The end of a list is read from the list, not from the screen. Two reads of the
# whole screen that come out the same do not say the list ended: a swipe that
# starts on a carousel, a slider or a map is taken by that element, the list
# stays where it was, and the screen looks exactly like the end. And two reads
# that differ do not say it moved: on Android the dump carries the status bar,
# and its clock ticks. So each read picks the list the search runs along - the
# element that says it scrolls on that axis (list_probe) - and remembers the
# first and the last row of it that are on the screen, by label and position.
# Nothing outside that list is compared, the clock included.
#
# One swipe that moved nothing is not yet the end: it may have landed on
# something inside the list that took the gesture. The swipes start away from
# every element inside the list that scrolls on its own, and when one still moves
# nothing, a second, shorter and slower one goes out from a different point. Only
# when that one moves nothing either is it the end. A false end then needs two
# misses in a row, from two points, both inside the list and both clear of what
# scrolls inside it.
#
# A list cannot be counted, which is why the rows at its ends are compared
# instead: a long list is virtualised, and the dump holds only the rows on the
# screen. The last row on the screen and where it stands are always there.
#
# A screen whose dump shows no list gets the old search: down the middle, eight
# swipes (SCROLL_TRIES_BLIND). It says so once, and its miss says the swipes ran
# out on a screen with no list - not that the list ended.
#
# A list that stopped moving is not yet a list that ended: its lower part may not
# be laid out yet. So the end is declared only when the list stopped GROWING.
# Having reached what looks like the end, the search keeps reading the screen
# and sending the second, shorter swipe, with a second's pause, for `grow`
# seconds. The element appearing ends the wait, and so do new rows - a swipe that
# moves the list again - and the search goes on from them. Nothing within the
# budget is the end, as before. Rows added below the screen do not show in a
# read, which is why the wait swipes as well: only a swipe that moves can tell.
# One line on stderr per search: how many swipes it took and how long, for the
# same reason as the line per read.
scroll_to(){ local t0 st=0; t0="$(now)"; SCROLL_N=0; SWIPED_BY=adb; SWIPE_FAR=""
  scroll_search "$@" || st=$?
  printf '  · search %s swipes %d ms\n' "$SCROLL_N" $(( ($(us_of "$(now)") - $(us_of "$t0")) / 1000 )) >&2
  return "$st"; }
scroll_search(){ local lbl="$1" dir="${2:-down}" clear="${3:-}" verb="${4:-scrollToText}" grow="${5:-$SCROLL_GROW_WAIT}" mode="${6:-text}" xy c lo hi blo bhi m w h seen="" nudge st probe prev="" ctl=0 ended="" flat="" kb="" end0="" far t1 tn waited=0 tw="" budget exp="" lost="" backed="" nofar="" bdir dmode="" dprev="" dlen=0 dlast="" k100=100 full r e aim want dprobe dkeep dt dk above=""
  case "$dir" in up|down|left|right) ;; *) die "$verb: '$dir' is not a direction - use up, down, left or right";; esac
  case "$dir" in down) bdir=up;; up) bdir=down;; left) bdir=right;; right) bdir=left;; esac
  set -- $(screen_wh); w="${1:-$BASIS_W}"; h="${2:-$BASIS_H}"
  case "$dir" in
    # The band on y is the measured one, scaled to this screen.
    up|down)    blo=$(( h * BAND_TOP / BASIS_H )); bhi=$(( h * BAND_BOTTOM / BASIS_H ));;
    left|right) blo=$(( w * BAND_SIDE_PCT / 100 )); bhi=$(( w - blo ));;
  esac
  lo="$blo"; hi="$bhi"
  if [ "$clear" = clear ]; then
    m=$(( (bhi - blo) * CLEAR_PCT / 100 )); lo=$(( blo + m )); hi=$(( bhi - m ))
  fi
  budget=$(( $(scroll_budget) * 1000000 )); t1="$(us_of "$(now)")"
  while :; do
    # The time spent waiting at the end of the list is not the search's.
    tn="$(us_of "$(now)")"; [ -z "$tw" ] || waited=$(( waited + tn - tw )); tw=""
    [ $(( tn - t1 - waited )) -lt "$budget" ] || break
    # One read per swipe. The lookup and the list both come from it: two reads
    # would cost a second dump, and could disagree about a screen that did not
    # change in between. Emptied before the swipe, as in dismiss.
    HELD_TREE=""; HELD_TREE="$(ui)" || exit 1
    st=0; xy="$(find_el "$lbl" "$mode")" || st=$?; [ "$st" -eq 0 ] || { HELD_TREE=""; lookup_die "$st"; }
    nudge="$dir"; [ -z "$lost$above" ] || nudge="$bdir"
    if [ -n "$xy" ]; then
      # Found on the way back: the way back is over, and where to swipe now is
      # decided by where the element is, as always.
      [ -z "$lost$above" ] || { lost=""; above=""; exp=""; prev=""; ctl=0; end0=""; }
      dmode=off
      # The coordinate that decides is the one the swipe moves.
      case "$dir" in up|down) c="${xy##* }";; *) c="${xy%% *}";; esac
      seen="$xy"
      if [ "$c" -lt "$hi" ] && [ "$c" -gt "$lo" ]; then HELD_TREE=""; printf '%s' "$xy"; return 0; fi
      # Too near one end: reveal what lies on that side, which moves the element
      # towards the other. `up` and `left` reveal what is above and to the left,
      # so the element travels down and right.
      if [ "$c" -le "$lo" ]; then case "$dir" in up|down) nudge=up;; *) nudge=left;; esac
      else case "$dir" in up|down) nudge=down;; *) nudge=right;; esac; fi
    fi
    # A swipe is next. The keyboard is asked once per step, here and not before
    # the first read: a label already in view needs no swipe, and closing the
    # keyboard for it would drop the field's focus for nothing. After a close the
    # screen is read again without a swipe, and the read is not counted as one.
    # The tree of this read is still held: on iOS the question is asked of it, and
    # list_probe below reads it as well.
    if [ -z "$kb" ]; then kb=1; st=0
      kb_before_swipe "$verb" >&2 || st=$?
      [ "$st" -eq 10 ] && continue
    fi
    # A screen at a time only while the element is not on the screen, and only
    # with the helper's gesture, which leaves the list where the finger left it.
    # An element in view is brought into the band by the usual two fifths: a
    # screen-long swipe would carry it from one edge past the other and back.
    far=""; [ -z "$xy" ] && [ -z "$nofar" ] && helper_swipes && far=far
    # A list that went past the gesture (#117). The seam of the last swipe the
    # helper played is checked against this read; on the way back the seam that
    # was lost is checked instead, read after read, until it is on the screen
    # again. Either answer changes the direction, and the swipe is then drawn
    # anew from the same held tree - no second read. (The start of the list,
    # met on the way back, is the one turn that reads the screen once more:
    # it is told by two reads, below.)
    st=0; probe="$(list_probe "$nudge" "$xy" "$w" "$h" "$far" "${lost:-$exp}")" || st=$?
    if [ "$st" -eq 0 ] && [ -n "$probe" ]; then
      set -- $probe
      if [ -n "$lost" ] && [ "${15}" = 0 ]; then
        lost=""; exp=""; prev=""; ctl=0; end0=""; nudge="$dir"
        probe="$(list_probe "$nudge" "$xy" "$w" "$h" "" "")" || st=$?
      # An element on the screen is not searched for: where to swipe is decided
      # by where it is, whatever the list did to bring it there.
      # Not on a way back either, the one for a lost seam or for a lost element
      # (#122): its short swipes go against the seam.
      elif [ -z "$lost$above" ] && [ -z "$xy" ] && [ -n "$exp" ] && [ "${15}" = 1 ]; then
        if [ -z "$backed" ]; then
          printf '  · swipe went past the gesture - going back%s\n' "${dlast:+ (distance)}" >&2
          dmode=off; backed=1; nofar=1; far=""; lost="$exp"; exp=""; prev=""; ctl=0; end0=""; nudge="$bdir"
          probe="$(list_probe "$nudge" "$xy" "$w" "$h" "" "")" || st=$?
        else
          # Once per step: the swipes are short now, and a second turn back
          # could only swing between the two.
          printf '  · swipe went past the gesture\n' >&2
        fi
      fi
    fi
    # A row below the fold (#116). The helper can read the whole screen, rows
    # below the fold included (helper_full_tree), and such a row says how far
    # down it is: the search swipes that far, instead of a screen at a time until
    # the row comes into view. Only going down, with the helper's finger - the
    # one that stops where the list should - and only while the element is not
    # on the screen: that is where the far swipe goes out, and where rows below
    # the fold were measured. Its top is to stand in the middle of the band.
    #
    # The list does not travel exactly the length of the finger (measured: 0.8
    # of it), so each swipe of this kind is followed by a full read, and the
    # share the ELEMENT travelled on the last swipe divides the next distance.
    # A share outside 0.5-1.5 is not a list moving - content above the element
    # grew between the reads - and is taken as 1. A list with no row on the
    # screen cannot be told still by its rows (same_rows); a top that moved 8 px
    # or less says it instead.
    #
    # Not in the full tree either: the search goes to the lowest row below the
    # fold the same way, and looks for the element in every full read on the
    # way. A plain list and a lazy one are both a ScrollView in the tree, and a
    # lazy one may draw some rows past the edge, so a missing element is not
    # yet a missing row: the search goes on to the end and its usual end there.
    # No rows below the fold - a lazy list - and the search is as it was.
    #
    # Any doubt ends this for the step, and the search goes on as before: a
    # swipe that moved nothing (the control swipe follows), a list that went
    # past the gesture (#117, the way back follows), an element that is gone,
    # a full read that failed.
    dlast=""
    if [ "$st" -eq 0 ] && [ -n "$probe" ] && [ -n "$far" ] && [ "$dir" = down ] && [ -z "$lost" ] && [ "$dmode" != off ]; then
      set -- $probe
      if [ -n "$prev" ] && same_rows "$prev" "$1 $2 $3"; then dmode=off
      else
        r=""; e=""; dt=""; dk=""
        if full="$(helper_full_tree)"; then
          dkeep="$HELD_TREE"; HELD_TREE="$full"
          r="$(afind "$lbl" "$mode" exact full "${18} ${19} ${16} ${17}")" || r=""
          [ -n "$r" ] || [ "$dmode" = t ] || e="$(afind - text exact fullend "${18} ${19} ${16} ${17}")" || e=""
          HELD_TREE="$dkeep"
          case "$r" in below\ *) dt="${r#below }"; dk=t;; esac
          case "$e" in below\ *) dt="${e#below }"; dk=e;; esac
          # Lost (#122): the element was below the fold before the swipe, and
          # now it is neither on the screen nor below it - the swipe carried it
          # above. The search turns back with the usual short swipes, which
          # cannot jump it again, and turns forward once more at the start of
          # the list, as the way back of #117 does.
          if [ -z "$r" ] && [ "$dmode" = t ]; then
            printf '  · distance scroll lost the target - going back\n' >&2
            above=1; nofar=1; far=""; exp=""; prev=""; ctl=0; end0=""; nudge="$bdir"
          fi
          case "$r" in on\ *) printf '  · distance scroll: the full tree has the element on the screen\n' >&2;; esac
        fi
        aim=$(( ( (${16} > lo ? ${16} : lo) + (${17} < hi ? ${17} : hi) ) / 2 ))
        if [ -n "$above" ]; then dmode=off
          probe="$(list_probe "$nudge" "$xy" "$w" "$h" "" "")" || st=$?
        elif [ -z "$dk" ] || [ "$aim" -le "$(( ${16} > lo ? ${16} : lo ))" ]; then dmode=off
        elif [ "$1" = none ] && [ "$dk" = "$dmode" ] && [ -n "$dprev" ] && [ "$(( dt - dprev ))" -le 8 ] && [ "$(( dprev - dt ))" -le 8 ]; then dmode=off
        else
          k100=100
          if [ "$dk" = t ] && [ "$dmode" = t ] && [ -n "$dprev" ] && [ "$dlen" -gt 0 ]; then
            k100=$(( (dprev - dt) * 100 / dlen ))
            if [ "$k100" -lt 50 ] || [ "$k100" -gt 150 ]; then ratio_note "$k100"; k100=100; fi
          fi
          dmode="$dk"; dprev=""; want=$(( (dt - aim) * 100 / k100 ))
          # Shorter than this is no swipe - the finger would not even be taken
          # for a drag - and the element is nearly there: the usual line.
          if [ "$want" -ge 60 ]; then
            st=0; dprobe="$(list_probe "$nudge" "$xy" "$w" "$h" "$far" "${lost:-$exp}" "$want")" || st=$?
            if [ "$st" -eq 0 ] && [ -n "$dprobe" ]; then
              probe="$dprobe"; set -- $probe; dlen=$(( $5 - $7 )); dprev="$dt"; dlast=1
            fi
            st=0
          fi
        fi
      fi
    fi
    HELD_TREE=""
    [ "$st" -eq 0 ] || lookup_die "$st"
    if [ -z "$probe" ]; then
      # To stderr: scroll_to runs inside a command substitution, and a line on
      # stdout would arrive inside the coordinates it returns. A sideways search
      # has its own line for this, printed by scroll.
      case "$dir" in up|down) [ -n "$flat" ] || warn "no vertically scrollable list in the dump - swiping down the middle of the screen, where the end of the list cannot be told from the end of the swipes" >&2;; esac
      # On the way back the lost seam stays: blind swipes go back as well, and
      # their eight are the search's last.
      flat=$(( ${flat:-0} + 1 )); prev=""; ctl=0; exp=""; SCROLL_N=$(( SCROLL_N + 1 ))
      scroll "$nudge"; sleep 0.6
      [ "$flat" -ge "$SCROLL_TRIES_BLIND" ] && break
      continue
    fi
    flat=""
    set -- $probe
    if [ -n "$prev" ] && same_rows "$prev" "$1 $2 $3"; then
      if [ "$ctl" = 1 ] && [ -n "$lost$above" ]; then
        # On the way back the list stopped at its start without the lost seam
        # (or the lost element): forward again at once. No wait for growth -
        # the start of a list does not grow - and not the end of the search
        # either.
        lost=""; above=""; exp=""; prev=""; ctl=0; end0=""; continue
      fi
      if [ "$ctl" = 1 ]; then
        # Two misses in a row: the list stopped moving. With the element on the
        # screen that is the answer, as before - a row at the very end is not
        # waited for - and so is an element the swipes already took out of
        # view: it was in the list, growth would not bring it back. Otherwise wait for the list to grow. The reads of the
        # wait are not swipes of the search and do not use up its tries.
        [ -n "$xy$seen" ] && { ended=1; break; }
        [ -n "$end0" ] || end0=$SECONDS
        # SECONDS counts whole seconds, so -gt: the wait is at least `grow`.
        [ $(( SECONDS - end0 )) -gt "$grow" ] && { ended=1; break; }
        tw="$tn"; sleep 1
      fi
      ctl=1; exp=""; SWIPE_FAR=""; swipe_pts "$9" "${10}" "${11}" "${12}" "${13}"
    else
      ctl=0; end0=""; prev="$1 $2 $3"; SWIPE_FAR="$far"; swipe_pts "$4" "$5" "$6" "$7" "$8"
      # Only the helper's finger stops where the list should: `input swipe` and
      # idb let go at speed, and a list running on after them is expected.
      exp=""; [ "$SWIPED_BY" = helper ] && exp="${14}"
    fi
    [ "$SWIPED_BY" = helper ] || sleep 0.6; done
  if [ -n "$ended" ]; then
    # The read that saw the end is also the last lookup: the element in it is
    # where it is going to stay.
    if [ -n "$xy" ]; then printf '%s' "$xy"; [ "$clear" = clear ] && return 9; return 0; fi
    if [ -n "$seen" ]; then printf '%s' "$seen"; return 5; fi
    return 6
  fi
  # Out of swipes. As a locator this still answers with wherever the element is,
  # which is what tapText has always done with it - and the position is judged
  # here as it is inside the loop, because the last swipe of the loop can be the
  # one that placed it: without this test such an element would be reported as
  # "never landed clear" while sitting exactly where it was asked to be.
  st=0; xy="$(find_el "$lbl" "$mode")" || st=$?; [ "$st" -eq 0 ] || lookup_die "$st"
  if [ -n "$xy" ]; then
    printf '%s' "$xy"
    case "$dir" in up|down) c="${xy##* }";; *) c="${xy%% *}";; esac
    [ "$c" -lt "$hi" ] && [ "$c" -gt "$lo" ] && return 0
    [ "$clear" = clear ] && return 4
    return 0
  fi
  if [ -n "$seen" ]; then printf '%s' "$seen"; return 5; fi
  [ -n "$flat" ] && return 8
  return 7; }
# The share of a swipe the element travelled, when it is not one a list moves
# by (#116, scroll_search). Kept in hundredths: bash counts in whole numbers.
ratio_note(){ local v="$1" s=""; [ "$v" -ge 0 ] || { s=-; v=$(( -v )); }
  printf '  · distance scroll ratio %s%d.%02d out of range - using 1\n' "$s" $(( v / 100 )) $(( v % 100 )) >&2; }
# Two reads of one list show the same rows: the first and the last row on the
# screen carry the same labels, and neither moved more than a few pixels - the
# rounding of a dump, not a swipe. A list with no row on the screen - one child
# larger than the list, a chart canvas, a picture - gives nothing to compare, and
# two such reads are not the same rows: they count as moved, and such a list runs
# to the safety net instead of reporting an end it never saw.
same_rows(){ local a b; set -- $1 $2
  [ "$1" != none ] || return 1
  [ "$1" = "$4" ] || return 1
  a=$(( $2 - $5 )); b=$(( $3 - $6 ))
  [ "${a#-}" -le 8 ] && [ "${b#-}" -le 8 ]; }
# A swipe between two points the dump has chosen. `scroll` aims by itself and
# stays as it is: a bare scroll step has no list to aim into.
#
# On Android, while the screen helper serves this run, the swipe of a search is
# one gesture sent to it (#107): the finger goes down at the start, moves to the
# end in 300 ms, stays there 160 ms, moves once more to the same point and only
# then comes up. Android takes the speed of a finger from its last movements,
# and drops what it saw before a gap of more than 40 ms; the last movement here
# comes after such a gap and goes nowhere, so the finger leaves at speed zero
# and the list stops where the finger stopped. That is what lets a search swipe
# a screen at a time (see list_probe): `input swipe` lets go at the speed it
# moved, the list runs on, and a long swipe would carry rows past unread.
# The helper's server drops a movement of 0 ms, so the last one is 20 ms - the
# shortest it keeps. The first movement only places the finger.
# Which way each swipe went is left in SWIPED_BY: the helper's gesture leaves a
# still list, and the search does not pause after it.
SWIPE_ACTIONS='{"actions":[{"type":"pointer","id":"finger","parameters":{"pointerType":"touch"},"actions":[
{"type":"pointerMove","duration":0,"origin":"viewport","x":%d,"y":%d},
{"type":"pointerDown","button":0},
{"type":"pointerMove","duration":300,"origin":"viewport","x":%d,"y":%d},
{"type":"pause","duration":160},
{"type":"pointerMove","duration":20,"origin":"viewport","x":%d,"y":%d},
{"type":"pointerUp","button":0}]}]}'
# The helper takes this swipe: it answers reads in this run, has not been given
# up on, and has not refused the gesture twice in a row. It is asked again before
# every swipe - a helper that fell over halfway through a step leaves the rest of
# the step on adb.
helper_swipes(){ local d; d="$(run_dir)"
  is_android && [ "${YUKTI_HELPER:-1}" != 0 ] && [ -n "$d" ] && [ ! -e "$d/helper-off" ] \
    && [ ! -e "$d/gesture-off" ] \
    && [ -s "$d/helper-session" ] && [ -s "$d/helper-port" ]; }
swipe_note(){ printf '  · swipe %s %d ms%s\n' "$1" $(( ($(us_of "$(now)") - $(us_of "$2")) / 1000 )) "${3:-}" >&2; }
swipe_pts(){ local t0 rc=0 why=""; t0="$(now)"; SWIPED_BY=adb
  if is_android; then
    if helper_swipes; then
      # As long as a read may take: the gesture lasts half a second, and the
      # server answers only once it has been played. An answer that came too
      # late may still have moved the list - the swipe below then moves it a
      # second time, which can skip rows and fail the step, never pass it.
      helper_http POST "/session/$(cat "$(run_dir)/helper-session")/actions" "$(helper_read_timeout)" \
        "$(printf "$SWIPE_ACTIONS" "$1" "$2" "$3" "$4" "$3" "$4")" >/dev/null || rc=$?
      if [ "$rc" -eq 0 ]; then rm -f "$(run_dir)/gesture-refused"; SWIPED_BY=helper; SCROLL_N=$(( ${SCROLL_N:-0} + 1 )); swipe_note helper "$t0" " $1,$2 -> $3,$4"; return 0; fi
      why=" (helper: rc $rc)"
      # Nothing answered (2), or nothing in time (4): the helper is gone or hung,
      # and a read would wait for it three times over. Given up on now, for the
      # run. No session (3) leaves it to the reads.
      case "$rc" in 2|4) HELPER_WHY="it did not answer a swipe"; helper_give_up;; esac
      # A gesture that timed out (4) or came back as an error (5) may still
      # have been played: the server injects every event before it answers. The
      # same line on adb would move the list twice, so nothing more is sent -
      # the next read sees where the list is. A helper that refuses the gesture
      # twice in a row is not offered it again in this run: each refusal would
      # cost a gesture, a read and a pause for nothing.
      if [ "$rc" -eq 4 ] || [ "$rc" -eq 5 ]; then
        if [ "$rc" -eq 5 ]; then printf 'x' >> "$(run_dir)/gesture-refused"
          [ "$(wc -c < "$(run_dir)/gesture-refused")" -lt 2 ] || : > "$(run_dir)/gesture-off"; fi
        SWIPED_BY=none; swipe_note none "$t0" "$why"; return 0
      fi
      # A screen-long line was drawn for a finger that stops. `input swipe`
      # lets go at speed and the list runs on past the fifth that is read
      # twice, so on adb the line goes half as far, at the same speed.
      if [ -n "${SWIPE_FAR:-}" ]; then set -- "$1" "$2" $(( ($1 + $3) / 2 )) $(( ($2 + $4) / 2 )) $(( $5 / 2 )); fi
    fi
    SCROLL_N=$(( ${SCROLL_N:-0} + 1 ))
    apaths; adb shell input swipe "$1" "$2" "$3" "$4" "$5"; swipe_note adb "$t0" "$why"
  # iOS: the finger at IOS_SWIPE_PT_S, as in scroll - not "$5", the Android rule,
  # which is fast enough for the list to fling (see IOS_SWIPE_PT_S).
  else SCROLL_N=$(( ${SCROLL_N:-0} + 1 )); paths; iswipe "$1" "$2" "$3" "$4"; swipe_note idb "$t0"; fi; }
# The words for a miss that never saw the element, for the two verbs that search.
scroll_miss(){ case "$1" in
    6) printf "reached the end of the list going %s and it did not grow for %ss, %s is not in it" "$3" "${4:-$SCROLL_GROW_WAIT}" "$2";;
    7) printf "still moving after %ss of swiping %s, %s not found" "$(scroll_budget)" "$3" "$2";;
    8) printf "no scrollable list on screen - searched %s swipes %s, %s not found" "$SCROLL_TRIES_BLIND" "$3" "$2";;
  esac; }
# scroll_to is a locator and stays one: it is also the first half of tapText,
# which has its own words for a miss. As a STEP, though, scrollToText is a
# statement that the label is there - the flow swipes until it finds it - and a
# statement that turns out false has to fail. It did not: the swipes ended, the
# last lookup came back empty, and the step passed. The runbook recommends this
# step in front of an assertion, so the documented way to reach something below
# the fold was also the way to miss it in silence.
scroll_to_step(){ local lbl="${1:-}" dir="${2:-down}" clear="${3:-}" grow="${4:-$SCROLL_GROW_WAIT}" mode="${5:-text}" xy st=0 verb what
  # scrollToId (#181) is the same search with the element matched by its id: a
  # target below the fold is reached by its testID, not by its copy.
  verb=scrollToText; what="'$lbl'"; [ "$mode" = id ] && { verb=scrollToId; what="id '$lbl'"; }
  [ -n "$lbl" ] || die "$verb needs a non-empty value"
  case "$dir" in up|down|left|right) ;; *) die "$verb: '$dir' is not a direction - use up, down, left or right";; esac
  case "$clear" in ''|clear) ;; *) die "$verb: '$clear' is not a value for \"edges\" - the only one is clear";; esac
  # The same knob as waitFor: how long to wait, here at the end of the list.
  case "$grow" in ''|*[!0-9]*|0) die "$verb: timeout must be a whole number of seconds greater than zero, got '$grow'";; esac
  xy="$(scroll_to "$lbl" "$dir" "$clear" "$verb" "$grow" "$mode")" || st=$?
  # Neither 4, 5 nor 9 says the direction: once the element is on the screen the
  # swipes follow its position, not the direction the search came from.
  case "$st" in
    0) ;;
    4) die "$verb: $what came into view but never landed clear of the band edges in $(scroll_budget)s of swiping - it is at $xy";;
    5) die "$verb: $what came into view at $xy and the swipes took it out of view again - it is not on the screen now";;
    6|7|8) die "$verb: $(scroll_miss "$st" "$what" "$dir" "$grow")";;
    9) die "$verb: $what is at the end of the list and cannot be moved clear of the band edge - it is at $xy; content may be hidden under a fixed bar";;
    *) lookup_die "$st";;
  esac
  # Not reached today - every miss above has its own status - and kept so that a
  # new path through scroll_to cannot pass this step with nothing to show.
  [ -n "$xy" ] || die "$verb: $what not on screen"
  printf '%s\n' "$xy"; }

# ── per-flow results ─────────────────────────────────────────────────────────
# A run left console text and screenshots and nothing a tool could read: which
# flow, which step, how long, where the artifacts are. That is enough at ten
# flows and useless at a hundred - no report, no history, no way to tell a
# permanent failure from a flaky one. Every flow now also leaves one JUnit XML
# file, the format report viewers and CI already understand.
#
# Written from an EXIT trap rather than after the loop: a failing step exits the
# whole run, so a result produced only on success would be missing exactly when
# it is needed. Steps are appended as they finish; the step that started and
# never finished is the one that failed.
RESULTS_DIR="${YUKTI_RESULTS_DIR:-yukti-results}"
FLOW_IDX=0
now(){ if [ -n "${EPOCHREALTIME:-}" ]; then printf '%s' "${EPOCHREALTIME/,/.}"; else date +%s; fi; }

flow_results(){
  local st="${1:-0}" out udid="" tree t0 had ro_n
  [ -n "${FLOW_REC:-}" ] || return 0
  trap - EXIT
  # A failed flow takes a screenshot below, and the tools for it are on the PATH
  # only where paths/apaths ran - for a locator that was a subshell. Every
  # command here is guarded: -e still holds in a trap, and a capture that
  # stopped the trap would lose the result it was meant to complete.
  if [ "$st" != 0 ]; then
    if is_android; then apaths; else paths; udid="$(U 2>/dev/null)" || udid=""; fi
  fi
  # A flow that failed on a blank tree on iOS: the app's threads now, before the
  # next flow's first read relaunches it (ios_threads; once per process - one
  # taken before this flow's relaunch is not taken again). Said in the result's
  # notes. They come before the screenshot below, and the result says how long
  # they took: for an app that was still drawing, the screen may have moved on.
  if [ "$st" != 0 ] && [ -n "$udid" ] && [ -s "$FLOW_TREE" ]; then
    tree="$(cat "$FLOW_TREE" 2>/dev/null)" || tree=""
    if ios_blank "$tree"; then t0="$(now)"; had="$({ wc -c < "$FLOW_REC.threads"; } 2>/dev/null)" || had=0
      ios_threads "$udid" "$tree" "when the step failed" || true
      # Said only when this call took something: a process taken before is not
      # taken again, and the screenshot was not held up.
      [ "$({ wc -c < "$FLOW_REC.threads"; } 2>/dev/null || echo 0)" = "${had:-0}" ] ||
        printf 'after\t%s\t%s\n' "$t0" "$(now)" >> "$FLOW_REC.threads" 2>/dev/null || true; fi
  fi
  ro_n="$(cat "$FLOW_REC.root-only" 2>/dev/null || true)"; ro_n=${#ro_n}
  out="$(YUKTI_ROOT_ONLY_N="$ro_n" "$PY" - "$FLOW_FILE" "$FLOW_REC" "$FLOW_CUR" "$FLOW_ERR" "$FLOW_T0" "$(now)" "$st" "$RESULTS_DIR" "$YUKTI_PLATFORM" "$FLOW_TREE" "$udid" "$CONFIG" "${YUKTI_VARIANT:-}" <<'PY'
import os, sys, time
from xml.sax.saxutils import escape, quoteattr

flow, rec, cur, errf, t0, t1, st, outdir, plat, treef, udid, config, variant = sys.argv[1:14]
SEP = "\x1f"

def num(v, d=0.0):
    try: return float(v)
    except ValueError: return d

def read(path):
    try:
        with open(path, encoding="utf-8", errors="replace") as fh: return fh.read()
    except OSError: return ""

steps = []
# split("\n"), not splitlines(): the latter also cuts on \r and on half a dozen
# other characters, so a value carrying one of them split its own record and the
# step vanished from the report - green run, no steps in the file.
for line in read(rec).split("\n"):
    if not line: continue
    parts = line.split(SEP)
    if len(parts) < 6: continue
    i, verb, value, s0, s1, art = parts[:6]
    # The seventh field is the condition that switched the step off, empty for a
    # step that ran. The eighth is the block the step was written in, empty for
    # the flow file itself. The ninth is the step's title. The tenth is
    # "optional" when the seventh is not a condition but what an optional wait
    # found when it ended, "platform" when it is what the platform cannot do
    # (#51). Older records have six to nine fields.
    skip = parts[6] if len(parts) > 6 else ""
    src = parts[7] if len(parts) > 7 else ""
    title = parts[8] if len(parts) > 8 else ""
    kind = parts[9] if len(parts) > 9 else ""
    steps.append({"i": int(num(i)), "verb": verb, "value": value,
                  "t": max(0.0, num(s1) - num(s0)), "art": art, "skip": skip, "src": src,
                  "title": title, "kind": kind})

failing = None
if int(num(st)) != 0:
    parts = read(cur).strip("\n").split(SEP)
    if len(parts) >= 4 and parts[0] and not any(x["i"] == int(num(parts[0])) for x in steps):
        failing = {"i": int(num(parts[0])), "verb": parts[1], "value": parts[2],
                   "t": max(0.0, num(t1) - num(parts[3])), "art": "", "skip": "",
                   "src": parts[4] if len(parts) > 4 else "",
                   "title": parts[5] if len(parts) > 5 else ""}

msg = read(errf).strip() or "the run stopped with exit code %d" % int(num(st))
stem = os.path.splitext(os.path.basename(flow))[0] or "flow"

# The first question about a red step is what was on the screen (#94). The
# failed step leaves a screenshot and the last tree the flow read, next to this
# file, and the failure names both. Best effort: what cannot be captured is
# said in one line, and the failure itself is never replaced.
CAPTURE_S = 10
captured, notes = [], []

def screenshot(path):
    import subprocess
    cmd = (["adb", "exec-out", "screencap", "-p"] if plat == "android"
           else ["xcrun", "simctl", "io", udid or "booted", "screenshot", path])
    try:
        with open(path, "wb") as fh:
            r = subprocess.run(cmd, stdout=fh if plat == "android" else subprocess.DEVNULL,
                               stderr=subprocess.DEVNULL, timeout=CAPTURE_S)
        if r.returncode != 0: return "%s exited with status %d" % (cmd[0], r.returncode)
    except subprocess.TimeoutExpired: return "no answer in %d s" % CAPTURE_S
    except OSError as e: return "%s: %s" % (cmd[0], e.strerror or e)
    if os.path.getsize(path) == 0: return "the screenshot came back empty"
    return ""

# What a flow typed is a credential as often as not, and a field that lost
# characters holds what is left of it - the value with gaps, which no search
# for the whole value finds. A text field holding four characters of a typed
# value in a row, or at least half of it in order, is masked whole. The tree is masked on the text as
# the screen shows it - attributes unescaped first, because the dump writes a
# typed & as &amp; - and compared without case, because a field may have
# capitalised the first letter. A value shorter than four characters is masked
# only as the whole text of a field: masked everywhere, "72" would erase every
# reading of 72 on the screen. PNGs are not masked; RUNBOOK says so.
typed = [x["value"] for x in steps if x["verb"] == "type" and x["value"]]
if failing is not None and failing["verb"] == "type" and failing["value"]:
    typed.append(failing["value"])

def in_order(part, whole):
    it = iter(whole)
    return all(ch in it for ch in part)

def run_of(text, v, n):
    return any(v[i:i + n] in text for i in range(len(v) - n + 1))

def masked(text, secret_field, editable):
    if not text: return text
    if secret_field: return "[%d chars]" % len(text)
    low = text.lower()
    for v in typed:
        lv = v.lower(); half = max(4, len(v) // 2)
        if low == lv and (editable or len(v) >= 4): return "[typed]"
        # In a text field, four characters of the value in a row are already
        # part of a password: a field typed into again keeps pieces of every
        # attempt next to its hint (measured on a React Native input), and one
        # emptied short of the end keeps the beginning. Letters in order with
        # gaps - what dropped keys leave - count only from half the value: a
        # hint such as "Email" is also a few letters of an address in order.
        if editable and (run_of(low, lv, 4) or (len(low) >= half and in_order(low, lv))):
            return "[typed]"
    import re
    for v in typed:
        if len(v) >= 4: text = re.sub(re.escape(v), "[typed]", text, flags=re.I)
    return text

def mask_android(xml):
    import html, re
    def node(m):
        tag = m.group(0)
        secret = 'password="true"' in tag
        cm = re.search(r'class=(?:"([^"]*)"|\'([^\']*)\')', tag)
        edit = "EditText" in ((cm.group(1) if cm.group(1) is not None else cm.group(2)) if cm else "")
        # uiautomator quotes an attribute with ' when its value holds a ",
        # so both forms are read; what is written back is always "...".
        def attr(a):
            name = a.group(1)
            raw = a.group(2) if a.group(2) is not None else a.group(3)
            if name not in ("text", "content-desc", "hint", "tooltip-text"): return a.group(0)
            val = html.unescape(raw)
            new = masked(val, secret, edit and name in ("text", "content-desc"))
            return a.group(0) if new == val else '%s=%s' % (name, quoteattr(new, {'"': "&quot;"}))
        return re.sub(r'''([\w:-]+)=(?:"([^"]*)"|'([^']*)')''', attr, tag)
    return re.sub(r"<node\b[^>]*>", node, xml)

def mask_ios(text):
    import json
    def walk(o):
        if isinstance(o, list): return [walk(x) for x in o]
        if not isinstance(o, dict): return o
        t = str(o.get("type", "")).lower()
        secret = "securetext" in t
        edit = secret or "textfield" in t or "text field" in t or "textview" in t or "textarea" in t
        out = {}
        for k, v in o.items():
            if isinstance(v, str) and k in ("AXLabel", "AXValue", "title"):
                v = masked(v, secret and k == "AXValue", edit and k == "AXValue")
            elif isinstance(v, (list, dict)):
                v = walk(v)
            out[k] = v
        return out
    return json.dumps(walk(json.loads(text)), indent=1)

# A step that fails on a missing element says the same thing whether the
# element is not there or the app under test died under it (#63). Once a step
# has failed, the device is asked which of the two it was, and what it logged
# about a crash. Nothing here runs when a step passes. The app is the variant of
# this run ($YUKTI_VARIANT), the one openUrl hands its address to. The config is
# read here, not through `cfg`: a `die` inside this trap would lose the result.
# Every question shares one budget of CAPTURE_S, and a device that did not
# answer once is not asked again - a hung device costs a failed flow the
# screenshot's 10 seconds and this budget, no more.
def app_of():
    import json
    key = "package" if plat == "android" else "bundleId"
    if not variant:
        return None, "no variant for this run ($YUKTI_VARIANT is not set)"
    try:
        with open(config, encoding="utf-8") as fh: v = json.load(fh)["variants"][variant]
    except OSError:
        return None, "no config at '%s'" % config
    except ValueError:
        return None, "'%s' is not valid JSON" % config
    except (KeyError, TypeError):
        return None, "no variant '%s' in %s" % (variant, config)
    val = v.get(key) if isinstance(v, dict) else None
    if not isinstance(val, str) or not val:
        return None, "variant '%s' has no '%s' in %s" % (variant, key, config)
    return val, ""

DEADLINE = [None]
def ask(cmd):
    """(status, output) of a command on the device, or (None, why) when it did
    not answer within what is left of the budget. A device that did not answer
    is not asked again."""
    import subprocess
    if DEADLINE[0] is None: DEADLINE[0] = time.time() + CAPTURE_S
    left = DEADLINE[0] - time.time()
    if left <= 0: return None, "the device did not answer an earlier question"
    try:
        r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=left)
    except subprocess.TimeoutExpired:
        DEADLINE[0] = 0
        return None, "no answer in %d s" % round(left)
    except OSError as e:
        return None, "%s: %s" % (cmd[0], e.strerror or e)
    return r.returncode, r.stdout.decode("utf-8", "replace").replace("\r", "")

def masked_text(text):
    # The same rule as the tree, for text that has no fields: every value a
    # step typed, four characters or more, without case. Nothing else is masked.
    import re
    for v in typed:
        if len(v) >= 4: text = re.sub(re.escape(v), "[typed]", text, flags=re.I)
    return text

def keep_crash(body, ext):
    name = os.path.join(outdir, stem + "-crash." + ext)
    try:
        with open(name, "w", encoding="utf-8") as fh: fh.write(masked_text(body))
    except OSError as e:
        try: os.remove(name)
        except OSError: pass
        notes.append("crash log not kept: %s" % (e.strerror or e))
        return
    captured.append(name)
    notes.append("crash log: %s (%d lines)" % (os.path.basename(name), len(body.rstrip("\n").split("\n"))))

def stopped_by():
    # The flow stopped the app itself when the last step that starts or stops it
    # was a stop: no crash to look for.
    # setPermission is a stop when it kills a running app (#51): a revoke does,
    # denied and unset, and on iOS applesimutils restarts SpringBoard for camera,
    # notifications and health whatever the state. A grant leaves the app
    # running, so a crash after it is still looked for. The record holds the
    # step as "<name> <state>". The step that failed counts when it is one, and
    # a failed setPermission always does: it goes before launch, so the app is
    # not expected to be running, and a revoke may have gone through before the
    # step failed.
    def stops(x):
        if x["verb"] in ("stopApp", "clearState"): return True
        if x["verb"] != "setPermission": return False
        if x is failing: return True
        f = x["value"].split()
        return f[-1:] in (["denied"], ["unset"]) or \
            (plat == "ios" and f[:1] in (["camera"], ["notifications"], ["health"]))
    last = None
    for x in steps + ([failing] if failing else []):
        if not x["skip"] and (x["verb"] in ("launch", "openUrl", "foreground", "relaunch") or stops(x)): last = x
    return last["i"] if last and stops(last) else 0

def android_state(app):
    st_, out = ask(["adb", "shell", "pidof", app])
    if st_ is None: return "unread", out
    # The output decides, not the status: `adb shell` passes the status of the
    # command on the device only with shell v2.
    if not out.strip(): return "gone", ""
    st_, out = ask(["adb", "shell", "dumpsys window | grep -E 'mCurrentFocus|mFocusedApp'"])
    if st_ is None: return "unread", out
    import re
    line = next((l for l in out.split("\n") if "mCurrentFocus=" in l), "") \
        or next((l for l in out.split("\n") if "mFocusedApp=" in l), "")
    if not line: return "unread", "dumpsys window named no focus"
    val = line.split("=", 1)[1].strip()
    if not val or val == "null": return "unread", "no focused window"
    # Window{7f3a2c1 u0 com.example/com.example.MainActivity}: the package is
    # only in that form. A popup, a toast or the navigation bar has none, and
    # is not proof that another app is in front.
    m = re.search(r"\bu\d+\s+([A-Za-z0-9_.]+)/([A-Za-z0-9_.$]+)", val)
    if not m:
        name = re.sub(r"^\w+\{\S+\s+(u\d+\s+)?|\}$", "", val)
        # The activity under the system's crash dialog is still ours, which is
        # why mFocusedApp is not asked here: it would say "in front". The window
        # name is the one Android 15 shows; another name falls to the line below.
        if name == "Application Error: " + app:
            return "unread", "the system shows the crash dialog of " + app
        return "unread", "focused window has no package (%s)" % name
    return ("front", "") if m.group(1) == app else ("behind", "%s/%s" % (m.group(1), m.group(2)))

def android_crash():
    host = time.time()
    st_, out = ask(["adb", "shell", "date", "+%s"])
    host = (host + time.time()) / 2
    if st_ is None: notes.append("crash log not read: " + out); return
    try: dev = float(out.strip())
    except ValueError: notes.append("crash log not read: the device did not tell its time"); return
    # The start of the flow on the device's clock, a second early. logcat reads
    # -t as a time only with a fraction: digits alone are a number of lines.
    since = "%.3f" % (num(t0) + (dev - host) - 1)
    st_, out = ask(["adb", "logcat", "-b", "crash", "-d", "-v", "threadtime", "-t", since])
    if st_ is None: notes.append("crash log not read: " + out); return
    if st_ != 0: notes.append("crash log not read: logcat exited with status %d" % st_); return
    if not out.strip(): notes.append("crash log: none since the flow started"); return
    keep_crash(out, "txt")

def ios_state(app):
    st_, out = ask(["xcrun", "simctl", "spawn", udid or "booted", "launchctl", "list"])
    if st_ is None: return "unread", out
    if st_ != 0: return "unread", "launchctl list exited with status %d" % st_
    return ("front", "") if ("UIKitApplication:%s" % app) in out else ("gone", "")

def ios_crash(app):
    # ReportCrash writes the report on the host, seconds after the crash.
    d = os.environ.get("YUKTI_IOS_CRASH_DIR") or os.path.expanduser("~/Library/Logs/DiagnosticReports")
    best = None
    try: names = os.listdir(d)
    except OSError as e: notes.append("crash log not read: %s" % (e.strerror or e)); return
    for n in names:
        p = os.path.join(d, n)
        try:
            if not n.endswith(".ips") or os.path.getmtime(p) < num(t0) - 1: continue
            with open(p, encoding="utf-8", errors="replace") as fh: body = fh.read()
        except OSError: continue
        if app in body and (best is None or os.path.getmtime(p) > best[0]): best = (os.path.getmtime(p), body)
    if best is None: notes.append("crash log: no crash report yet in DiagnosticReports"); return
    keep_crash(best[1], "ips")

def app_check(shot_why):
    """The first line of the message when the app is not where the step needed
    it, and the type of the failure; the rest goes to notes."""
    app, why = app_of()
    if not app: notes.append("app: not checked - " + why); return "", ""
    if shot_why.startswith("no answer"):
        notes.append("app state not read: the device did not answer the screenshot")
        notes.append("crash log not read: the device did not answer the screenshot")
        return "", ""
    state, what = android_state(app) if plat == "android" else ios_state(app)
    top = kind = ""
    by = stopped_by() if state == "gone" else 0
    if state == "unread": notes.append("app state not read: " + what)
    elif state == "front": notes.append("app: %s running%s" % (app, ", in front" if plat == "android" else ""))
    elif state == "behind": top = "the app %s is running but not in front: %s" % (app, what)
    elif by: notes.append("app: %s not running - stopped by step %d" % (app, by))
    else: top, kind = "the app %s is not running: it was gone when the step failed" % app, "AppGone"
    android_crash() if plat == "android" else ios_crash(app)
    return top, kind

# A step that started is enough: a `when` that cannot read the screen stops the
# run before its step is recorded, and that is a failure on "00 flow" - the one
# where the screen is wanted most. A flow file the builder refused started no
# step and touched no device, and leaves nothing.
# The app's threads on a blank tree (ios_threads): taken with this failure, or
# before or after this flow's relaunch, and what idb-companion said about it. A
# failed flow says them with its failure; a flow that passed keeps the files and
# the lines all the same - a relaunch that helped leaves the stuck process's
# threads with a flow that went green.
tnotes, tfiles, tafter = [], [], None
for line in read(rec + ".threads").split("\n"):
    kind, _, text = line.partition("\t")
    if kind == "note" and text: tnotes.append(text)
    elif kind == "file" and text and os.path.isfile(text): tfiles.append(text)
    elif kind == "after":
        a, _, b = text.partition("\t")
        try: tafter = max(0.0, float(b) - float(a))
        except ValueError: pass
side = []
kind_of_app = ""
if failing is not None or (int(num(st)) != 0 and read(cur).strip()):
    os.makedirs(outdir, exist_ok=True)
    png = os.path.join(outdir, stem + "-fail.png")
    why = screenshot(png)
    shot_why = why
    if why:
        try: os.remove(png)
        except OSError: pass
        notes.append("screen not captured: " + why)
    else:
        captured.append(png)
        notes.append("screen: " + os.path.basename(png)
                     + ("" if tafter is None else " (taken after the app's threads, which took %.0f s)" % tafter))
    tree = read(treef) if treef else ""
    if not tree.strip():
        notes.append("tree: none - no step of this flow read the screen")
    else:
        name = os.path.join(outdir, stem + ("-fail.xml" if plat == "android" else "-fail.json"))
        try:
            body = mask_android(tree) if plat == "android" else mask_ios(tree)
            with open(name, "w", encoding="utf-8") as fh: fh.write(body)
        except (OSError, ValueError) as e:
            notes.append("tree not kept: %s" % e)
        else:
            captured.append(name)
            # The step that read it. A `when` reads before its step is counted,
            # so its tree carries the number of the step before; 0 is a read
            # before the first step.
            by = int(num(read(treef + ".step").strip()))
            line = "tree: " + os.path.basename(name)
            if by == 0: line += " (read before step 1)"
            elif failing is None or by != failing["i"]: line += " (read by step %d)" % by
            notes.append(line)
    notes.extend(tnotes); captured.extend(tfiles)
    top, kind_of_app = app_check(shot_why)
    if top: msg = top + "\n" + msg
    msg = msg + "\n" + "\n".join(notes)
    if top: notes.insert(0, top)
else:
    captured.extend(tfiles); side = tnotes

# A typed string is a credential as often as not - the flow files take
# ${TEST_PASSWORD} from the environment. The result file records how much was
# typed, never what: an artifact that leaks the password is worse than no
# artifact, and the console already prints the same count.
def shown(step):
    verb, value = step["verb"], step["value"]
    if verb in ("type", "clearText"):
        value = "%d chars" % len(value) if value else ""
    if len(value) > 60: value = value[:57] + "..."
    # A step with a title is named by it: the reader of a failed run needs what
    # the step was for, not the id it tapped. The value stays after it, shown as
    # it is without a title: a block included by two flows with different
    # values would otherwise name its steps the same in both. The block leads.
    if step["title"]:
        verb = step["title"] + (":" if value and not step["title"].endswith(":") else "")
    # A step from a block says which block, the way the console does: two flows
    # that include the same block would otherwise show its steps as their own.
    # A step of the flow file itself is named as it always was.
    if step["src"]:
        return ("%02d [%s] %s %s" % (step["i"], step["src"], verb, value)).strip()
    return ("%02d %s %s" % (step["i"], verb, value)).strip()

cases = []
for step in steps:
    if step["skip"]:
        # A step that did not run is not a step that passed. Reported as skipped,
        # with the condition in the message: a reader of the file can see which
        # part of the flow was switched off and by what. An optional wait that
        # ended without its element did run, and says so in other words.
        # A step the platform cannot do (#51) carries its reason as it is: the
        # message starts with the reason word, "platform:", and no condition
        # was involved.
        if step.get("kind") in ("platform", "blocked"): why = step["skip"]
        else:
            why = ("optional wait ended, the flow went on: " if step.get("kind") == "optional"
                   else "condition not met: ") + step["skip"]
        cases.append('    <testcase classname=%s name=%s time="%.3f">\n'
                     '      <skipped message=%s/>\n'
                     '    </testcase>'
                     % (quoteattr(stem), quoteattr(shown(step)), step["t"], quoteattr(why)))
    else:
        cases.append('    <testcase classname=%s name=%s time="%.3f"/>'
                     % (quoteattr(stem), quoteattr(shown(step)), step["t"]))
# Fix the app, or restart the device? A failure of the device or of the engine
# (device_fault: the screen could not be read, the screenshot was not taken)
# is an <error>; everything else stays a <failure>, a missing element too. The
# exit status is the same for both - only the report tells them apart.
fault = int(num(st)) != 0 and os.path.exists(errf + ".kind")
if failing is not None:
    # An app that was gone is the app's failure, not the device's: the tag stays
    # <failure>, and the type lets a report count crashes without reading text.
    tag, kind = ("error", "DeviceError") if fault else ("failure", kind_of_app or "StepFailed")
    cases.append('    <testcase classname=%s name=%s time="%.3f">\n'
                 '      <%s message=%s type="%s"/>\n'
                 '    </testcase>'
                 % (quoteattr(stem), quoteattr(shown(failing)), failing["t"], tag, quoteattr(msg), kind))
elif int(num(st)) != 0:
    # The run died before or between steps: still a failure, and a result that
    # said "all green, exit 1" would be worse than none. A `when` that could not
    # read the screen dies here too, and that is the device's.
    tag, kind = ("error", "FlowError") if fault else ("failure", "FlowFailed")
    cases.append('    <testcase classname=%s name="00 flow" time="0.000">\n'
                 '      <%s message=%s type="%s"/>\n'
                 '    </testcase>' % (quoteattr(stem), tag, quoteattr(msg), kind))

skips = sum(1 for s in steps if s["skip"])
red = int(num(st)) != 0 or failing is not None
# The flow's own outcome (#55), for a reader that counts flows rather than
# steps: passed, failed, or skipped with the reason that cut it short -
# "platform:" (#51) or "blocked:", a preparation that did not give its state.
cut = next((s["skip"] for s in steps if s.get("kind") in ("platform", "blocked")), "")
outcome = "failed" if red else ("skipped" if cut else "passed")
# A teardown that did not work does not change the outcome, and is not lost.
torn = read(errf + ".teardown").strip()
arts = [s["art"] for s in steps if s["art"]] + captured
out = [
    '<?xml version="1.0" encoding="UTF-8"?>',
    '<testsuites>',
    '  <testsuite name=%s tests="%d" failures="%d" errors="%d" skipped="%d" time="%.3f" timestamp=%s>'
    % (quoteattr(stem), len(cases), red and not fault, red and fault,
       skips, max(0.0, num(t1) - num(t0)),
       quoteattr(time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(num(t0))))),
    '    <properties>',
    '      <property name="platform" value=%s/>' % quoteattr(plat),
    '      <property name="flow" value=%s/>' % quoteattr(flow),
    '      <property name="outcome" value=%s/>' % quoteattr(outcome),
] + (['      <property name="reason" value=%s/>' % quoteattr(cut)] if outcome == "skipped" else []) + (
    # Negative checks that passed on a root-only tree (#201, step 1).
    ['      <property name="root-only-passes" value="%d"/>' % int(os.environ.get("YUKTI_ROOT_ONLY_N") or 0)]
    if (os.environ.get("YUKTI_ROOT_ONLY_N") or "0") != "0" else []) + [
    '    </properties>',
]
out.extend(cases)
if arts:
    out.append('    <system-out>' + escape("\n".join(arts)) + '</system-out>')
err = side + (["teardown: " + l for l in torn.split("\n")] if torn else [])
if err:
    out.append('    <system-err>' + escape("\n".join(err)) + '</system-err>')
out.append('  </testsuite>')
out.append('</testsuites>')

os.makedirs(outdir, exist_ok=True)
path = os.path.join(outdir, stem + ".xml")
with open(path, "w", encoding="utf-8") as fh:
    fh.write("\n".join(out) + "\n")
print(path)
for note in notes: print(note)
PY
)" || out=""
  if [ -n "$out" ]; then
    ok "results → ${out%%$'\n'*}"
    case "$out" in *$'\n'*) printf '%s\n' "${out#*$'\n'}" | while IFS= read -r l; do say "$l"; done;; esac
  else
    warn "could not write the results file to '$RESULTS_DIR'"
  fi
  [ "$ro_n" = 0 ] || say "negative checks passed on a root-only tree: $ro_n (#201)"
  rm -f "$FLOW_REC" "$FLOW_REC.root-only" "$FLOW_REC.acted" "$FLOW_REC.launched" "$FLOW_REC.blank-relaunched" "$FLOW_REC.blank-said" "$FLOW_REC.threads" "$FLOW_REC.threads-pids" "$FLOW_REC.read-ms" "$FLOW_REC.read-blank" "$FLOW_CUR" "$FLOW_ERR" "$FLOW_ERR.kind" "$FLOW_ERR.teardown" "$FLOW_TREE" "$FLOW_TREE.step"; FLOW_REC=""
  return 0
}

# ── preparation and teardown: the state of the system, not of the device (#55) ─
# launch, stopApp and clearState bring the app on the device to a known state.
# The account it signs into, its records and its flags were whatever the last run
# left, and a test that needs an account which has never seen onboarding could
# not be written at all. Preparation done by scripts outside the tool did not
# show in the report, and a preparation that failed read as the app failing.
#
# A flow file may carry "prepare" and "teardown": lists of calls to named
# fixtures. A call is a POST of its "with" as JSON to the fixtures address of the
# config plus the fixture's name; "bind" takes fields of the answer into flow
# variables, which the steps then use like any other. The address comes from the
# config and never from the flow file, the access secret from the environment
# variable the config names, and never from a file in a repository. There is no
# step that runs a command: a flow file is input, and a fixture call whose
# address it cannot choose does not turn it into code run on this machine.
#
# A flow whose preparation did not work did not run: it is "skipped" with a
# "blocked:" reason, every step listed as not run, and the run ends with status
# 0, the way a flow cut short by "platform:" does. What the author can fix - a
# fixture name, a missing address, an unset variable in the flow file - is a red,
# as any other mistake in a flow file. The teardown runs whatever the outcome; a
# teardown that failed is said on the console and in the report, and does not
# change the outcome. The step "fixture" calls one fixture in the middle of a
# flow, under the same rules, and blocks the rest of the flow when it fails.
#
# fixture_py <mode> [<name> <with as JSON>] - of the flow file being run
#   check     validate "prepare" and "teardown", put a stand-in for every bound
#             variable in $FLOW_BOUND, print "<prepare calls> <teardown calls>"
#   prepare   call them in order, each bound value into $FLOW_BOUND as it comes
#   teardown  call every one, whatever failed before
#   step      call one fixture, the step's
# Status 2: the flow file or the config is wrong. Status 3: the system did not
# give the state - blocked. The reason is on stderr; stdout says what was done.
fixture_py(){ YUKTI_ENV0="$_yk_env0" "$PY" - "$1" "$FLOW_FILE" "$CONFIG" "${YUKTI_VARIANT:-}" "${FLOW_TZ:-}" "$FLOW_BOUND" "${2:-}" "${3:-}" <<'PY'
import json, os, re, sys, urllib.error, urllib.request
from urllib.parse import quote, urlsplit

mode, flow, config, variant, tz, boundf = sys.argv[1:7]
VAR = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
NAME = re.compile(r"\A[A-Za-z_][A-Za-z0-9_]*\Z")
# A fixture name becomes the last part of an address: no slash, no "..".
FIXTURE = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9_.-]*\Z")
LOOPBACK = ("localhost", "127.0.0.1", "::1")

def wrong(msg): sys.stderr.write(msg + "\n"); sys.exit(2)
def blocked(msg): sys.stderr.write(msg + "\n"); sys.exit(3)

# What a fixture bound, and apart from it the stand-ins --check builds with: a
# teardown must never send a stand-in as if it were a value.
def bound(path=boundf):
    try:
        with open(path, encoding="utf-8") as fh: return json.load(fh)
    except (OSError, ValueError): return {}

def keep(values, path=boundf):
    b = bound(path); b.update(values)
    with open(path, "w", encoding="utf-8") as fh: json.dump(b, fh)

def scope():
    env = dict(os.environ)
    try: env.update(json.loads(env.pop("YUKTI_ENV0", "") or "{}"))
    except ValueError: pass
    env.update(bound())
    return env

# ${NAME} in every text of the body, at any depth. The names that are not set
# come back instead of a body: the caller decides whether that is a mistake in
# the flow file or a value an earlier call never bound.
def fill(v, sc, missing):
    if isinstance(v, str):
        return VAR.sub(lambda m: sc.get(m.group(1) or m.group(2)) if (m.group(1) or m.group(2)) in sc
                       else (missing.append(m.group(1) or m.group(2)) or ""), v)
    if isinstance(v, dict): return {k: fill(x, sc, missing) for k, x in v.items()}
    if isinstance(v, list): return [fill(x, sc, missing) for x in v]
    return v

def calls(doc, key):
    if key not in doc: return []
    items = doc[key]
    if not isinstance(items, list) or not items:
        wrong('"%s" is a list of fixture calls, for instance [{"fixture": "fresh-account"}]' % key)
    allowed = ("bind", "fixture", "with") if key == "prepare" else ("fixture", "with")
    out = []
    for n, it in enumerate(items, 1):
        at = "%s %d" % (key, n)
        if not isinstance(it, dict): wrong("%s is not an object" % at)
        extra = sorted(k for k in it if k not in allowed)
        if extra:
            wrong("%s: '%s' is not a key a %s call takes - those are %s%s"
                  % (at, extra[0], key, ", ".join(allowed),
                     " (a teardown binds nothing: nothing runs after it)" if extra[0] == "bind" else ""))
        name = it.get("fixture")
        if not isinstance(name, str) or not FIXTURE.match(name) or ".." in name:
            wrong('%s: "fixture" is the name of a fixture - letters, digits, ".", "_" and "-", '
                  'for instance "fresh-account"' % at)
        w = it.get("with", {})
        if not isinstance(w, dict):
            wrong('%s: "with" is an object - the body the fixture is sent' % at)
        b = it.get("bind", {})
        if not isinstance(b, dict) or not all(isinstance(k, str) and NAME.match(k) for k in b) \
                or not all(isinstance(f, str) and f.strip() for f in b.values()):
            wrong('%s: "bind" takes a field of the answer into a flow variable, for instance '
                  '{"TEST_EMAIL": "email"} or {"TEST_EMAIL": "account.email"}' % at)
        out.append((at, name, w, b))
    return out

def address():
    try:
        with open(config, encoding="utf-8") as fh: cfg = json.load(fh)
    except (OSError, ValueError) as e:
        wrong("the fixtures need the config, and %s cannot be read: %s" % (config, e))
    v = (cfg.get("variants") or {}).get(variant) if variant else None
    fx = v.get("fixtures") if isinstance(v, dict) and "fixtures" in v else cfg.get("fixtures")
    if not isinstance(fx, dict) or not isinstance(fx.get("url"), str) or not fx["url"].strip():
        wrong('nothing says where the fixtures are - put "fixtures": {"url": "https://..."} on '
              "variant '%s' in %s, or one at the top level" % (variant, config))
    url = fx["url"].strip()
    u = urlsplit(url)
    # The secret travels in a header: in clear text only to this machine.
    if not (u.scheme == "https" or (u.scheme == "http" and u.hostname in LOOPBACK)) or not u.hostname:
        wrong("the fixtures address is '%s' - it has to be https (http only to localhost)" % url)
    secret = fx.get("secret", "")
    if not isinstance(secret, str) or (secret and not NAME.match(secret)):
        wrong('"fixtures.secret" in %s is the NAME of an environment variable that holds the '
              "access secret, not the secret" % config)
    return url, secret

class Stay(urllib.request.HTTPRedirectHandler):
    # A redirect would carry the secret to an address the config never named.
    def redirect_request(self, *a, **k): return None

def call(at, name, body):
    url, secret = address()
    headers = {"Content-Type": "application/json", "Accept": "application/json"}
    if secret:
        if not os.environ.get(secret):
            blocked("%s: fixture '%s' not called - $%s, the access secret the config names, is not set" % (at, name, secret))
        headers["Authorization"] = "Bearer " + os.environ[secret]
    # A record "for today" made in the runner's zone lands, around midnight, on
    # another day than the one the device shows.
    if tz: headers["X-Device-Timezone"] = tz
    req = urllib.request.Request(url.rstrip("/") + "/" + quote(name), data=json.dumps(body).encode("utf-8"),
                                 headers=headers, method="POST")
    # The answer's body is never printed: it may hold the very credentials the
    # fixture made.
    try:
        with urllib.request.build_opener(Stay).open(req, timeout=30) as r: return r.read()
    except urllib.error.HTTPError as e:
        blocked("%s: fixture '%s' answered %d%s" % (at, name, e.code,
                " (a redirect - fixtures are not followed elsewhere)" if 300 <= e.code < 400 else
                (" - check the secret in $%s" % secret if secret else " - the config names no secret")
                if e.code in (401, 403) else ""))
    except (urllib.error.URLError, OSError, ValueError) as e:
        blocked("%s: fixture '%s' could not be reached: %s" % (at, name, getattr(e, "reason", e)))

def take(at, name, answer, b):
    try: doc = json.loads(answer.decode("utf-8"))
    except (UnicodeDecodeError, ValueError):
        blocked("%s: fixture '%s' answered with something that is not JSON - nothing to bind" % (at, name))
    got = {}
    for var, path in b.items():
        cur = doc
        for part in path.split("."):
            if not isinstance(cur, dict) or part not in cur:
                blocked("%s: fixture '%s' answered without '%s' - %s stays unset" % (at, name, path, var))
            cur = cur[part]
        if cur is None or isinstance(cur, (dict, list)):
            blocked("%s: '%s' in the answer of fixture '%s' is %s, not text or a number"
                    % (at, path, name, "null" if cur is None else type(cur).__name__))
        got[var] = cur if isinstance(cur, str) else json.dumps(cur)
    return got

if mode == "step":
    name, body = sys.argv[7], json.loads(sys.argv[8] or "{}")
    call("step", name, body)
    print("fixture '%s' called" % name)
    sys.exit(0)

try:
    with open(flow, encoding="utf-8") as fh: doc = json.load(fh)
except (OSError, ValueError):
    print("0 0"); sys.exit(0)   # the builder says what is wrong with the file
if not isinstance(doc, dict): print("0 0"); sys.exit(0)
prep, tear = calls(doc, "prepare"), calls(doc, "teardown")

if mode == "check":
    stand = {}
    for at, name, w, b in prep:
        missing = []; fill(w, dict(scope(), **stand), missing)
        if missing: wrong("%s: $%s is not set in the environment, and no call before this one binds it" % (at, missing[0]))
        for var in b: stand[var] = "<bound by fixture '%s'>" % name
    keep(stand, boundf + ".stand")
    print("%d %d" % (len(prep), len(tear)))
elif mode == "prepare":
    for at, name, w, b in prep:
        missing = []; body = fill(w, scope(), missing)
        if missing: wrong("%s: $%s is not set" % (at, missing[0]))
        answer = call(at, name, body)
        got = take(at, name, answer, b) if b else {}
        keep(got)
        print("%s: fixture '%s'%s" % (at, name, " - bound " + ", ".join(sorted(got)) if got else ""))
else:
    failed = 0
    for at, name, w, b in tear:
        missing = []; body = fill(w, scope(), missing)
        if missing:
            sys.stderr.write("%s: fixture '%s' not called - $%s was never set\n" % (at, name, missing[0]))
            failed += 1; continue
        # One teardown that did not work does not keep the next from running. The
        # reason is on stderr already.
        try: call(at, name, body); print("%s: fixture '%s'" % (at, name))
        except SystemExit: failed += 1
    sys.exit(3 if failed else 0)
PY
}
# The device's own zone, read once per flow and only when a fixture is called.
# A simulator keeps the zone of the Mac it runs on.
fixture_tz(){ [ -z "${FLOW_TZ_READ:-}" ] || return 0; FLOW_TZ_READ=1; FLOW_TZ=""
  if is_android; then apaths; FLOW_TZ="$(adb shell getprop persist.sys.timezone 2>/dev/null | tr -d '\r')" || FLOW_TZ=""
  else FLOW_TZ="${TZ:-$(readlink /etc/localtime 2>/dev/null | sed 's#.*/zoneinfo/##')}" || FLOW_TZ=""; fi
  [ -n "$FLOW_TZ" ] || warn "the device did not say its time zone - the fixtures are sent none, and a record \"for today\" may land on another day around midnight"; }
# Lines a fixture call printed, said on the console.
fixture_said(){ [ -z "$1" ] || printf '%s\n' "$1" | while IFS= read -r l; do ok "$l"; done; }
flow_prepare(){ local out st=0
  fixture_tz
  out="$(fixture_py prepare 2> "$FLOW_BOUND.err")" || st=$?
  fixture_said "$out"
  case "$st" in
    0) ;;
    3) FLOW_BLOCKED="blocked: $(head -1 "$FLOW_BOUND.err")";;
    *) die "$(cat "$FLOW_BOUND.err")";;
  esac; }
# In the EXIT trap, where -e still holds: every command is guarded, and nothing
# here may stop the trap before the results are written.
flow_teardown(){ local out st=0 l
  [ "${FLOW_TEARS:-0}" -gt 0 ] || return 0
  fixture_tz || true
  out="$(fixture_py teardown 2> "$FLOW_BOUND.err")" || st=$?
  fixture_said "$out" || true
  [ "$st" -eq 0 ] && return 0
  while IFS= read -r l; do warn "teardown: $l"; done < "$FLOW_BOUND.err" || true
  cp "$FLOW_BOUND.err" "$FLOW_ERR.teardown" 2>/dev/null || true; }
fixture_step(){ local out st=0
  fixture_tz
  out="$(fixture_py step "$1" "${2:-}" 2> "$FLOW_BOUND.err")" || st=$?
  fixture_said "$out"
  case "$st" in
    0) ;;
    3) FLOW_PLAT_SKIP="blocked: $(head -1 "$FLOW_BOUND.err")"; FLOW_PLAT_KIND=blocked;;
    *) die "$(cat "$FLOW_BOUND.err")";;
  esac; }
# ── deterministic flow runner: a JSON list of steps ──────────────────────────
# step keys: include[with]|launch|stopApp|clearState|background|foreground|relaunch|wait|waitFor[timeout,match]|waitForId[timeout]|
#            waitForNotText[timeout,match]|waitForNotId[timeout]|screenshot|
#            openUrl|setPermission[state]|tap[x,y]|tapText[timeout]|optionalTapText|tapId[at]|type|clearText[x,y]|clearTextId|pressKey|hideKeyboard|
#            scroll|swipe[x,y,toX,toY]|scrollToText[direction,edges,timeout]|scrollToId[direction,edges,timeout]|dismiss|assertText[match]|assertId|assertNotText[match]|assertNotId|
#            assertBox[box]|assertBoxId[box]|turnWheel[wheel]|swipeId[direction]|swipeText[direction]
#            any step, and an include, may carry "when": {visible|notVisible|
#            visibleId|notVisibleId|zeroSizeId|platform} - all of them have to hold;
#            waitForId may carry "optional": true - a timeout skips it instead
#
# The same names the dispatcher inside flow() knows, as a list a check can read.
# The dispatcher cannot answer "do you know this name?" without running the
# step, and one check below has to ask before the step runs. A verb added to the
# `case` has to be added here too: nothing but this comment ties the two, and
# the `*)` arm of the dispatcher stays as the backstop.
#
# `include` is deliberately in neither: the builder runs it while it reads the
# file and emits the block's steps in its place, so no record ever carries it
# and the dispatcher never sees it. `__when` is not in either list for the same
# reason from the other side: it is a record the loop answers itself, never a
# name a flow file may use - a step whose name starts with "__" is refused as
# unknown by the check above the dispatcher.
# ── step conditions (`when`) ─────────────────────────────────────────────────
# A condition has three outcomes, and only one of them is a skip:
#   it holds          - the guarded steps run, and the run says nothing about it
#   it does not hold  - they are skipped, out loud: a line each and `skipped` in
#                       the report, because a condition that quietly removes
#                       steps from a suite is a worse defect than the missing
#                       `when` it replaces
#   it cannot be answered - the run stops
#
# The third one is why conditions and the negative assertions are one change: an
# unreadable screen, or a screen that does not report its own bounds, answers
# every "is this visible?" with "no". Taken as an answer, that switches parts of
# a suite off and keeps the run green.
#
# `visible`/`notVisible` ask the ASSERTION oracle, not the tap locator. The
# locator folds case, matches substrings and looks into resource-ids, so a
# condition answered by it can be satisfied by markup - and this condition
# decides whether a step runs at all. `visibleId`/`notVisibleId` are the exact
# id selector, the rule assertId already follows. The cost is named in the
# guide: a condition is stricter than tapText, so it can skip a step tapText
# would have found - and the skip is never silent.
COND_KV=$'\x1d'; COND_SEP=$'\x1e'
# One read for a run of conditions (#172). On iOS every lookup used to read the
# screen again, at 5-6 s a read on a CI simulator, and a block that dismisses a
# few optional dialogs is twenty guarded steps that mostly do not run. The read
# happens here, in the loop's own shell - a lookup runs in $(...) and what it
# holds dies with it - and only for a condition that looks at the screen: a
# platform term needs none. A screen that cannot be read stops the run as it
# did, with the condition in the words.
cond_tree(){ [ -z "$HELD_TREE" ] || return 0
  HELD_TREE="$(ui)" || { HELD_TREE=""; die "when ($1 '$2'): $(lookup_err 1)"; }; }
cond_holds(){ local spec="$1" pair kind val xy st ro rk=""
  while [ -n "$spec" ]; do
    case "$spec" in *"$COND_SEP"*) pair="${spec%%"$COND_SEP"*}"; spec="${spec#*"$COND_SEP"}";; *) pair="$spec"; spec="";; esac
    kind="${pair%%"$COND_KV"*}"; val="${pair#*"$COND_KV"}"
    case "$kind" in
      # The platform of this run, as the engine resolved it at start-up: the
      # variant's platform, else the config's, else ios. That last fallback is
      # issue #36 and a condition inherits it, so the skip line below names the
      # platform it compared against - an author who expected android sees why
      # the step did not run instead of wondering.
      platform) [ "$val" = "${YUKTI_PLATFORM:-}" ] || return 1;;
      visible|notVisible|visibleId|notVisibleId)
        cond_tree "$kind" "$val"; st=0
        case "$kind" in
          visible|notVisible)     xy="$(find_el "$val" assert exact)" || st=$?;;
          visibleId|notVisibleId) xy="$(find_el "$val" id)" || st=$?;;
        esac
        [ "$st" -eq 0 ] || die "when ($kind '$val'): $(lookup_err "$st")"
        case "$kind" in
          visible|visibleId)       [ -n "$xy" ] || return 1;;
          notVisible|notVisibleId) [ -z "$xy" ] || return 1
            # Said once the whole condition holds (#201), not per part:
            # a later part that does not hold skips the step.
            ! root_only || rk="${rk:+$rk, }$kind '$val'";;
        esac;;
      # In the tree at zero area, where it is on the screen or not, and no
      # namesake of a real size to tap instead. `notVisibleId` holds here too,
      # and also when the id is not in the tree at all - this is the one that
      # tells the two apart.
      zeroSizeId)
        cond_tree "$kind" "$val"; st=0; xy="$(find_el "$val" id exact why)" || st=$?
        [ "$st" -eq 0 ] || die "when ($kind '$val'): $(lookup_err "$st")"
        case "$xy" in zero\ *) ;; *) return 1;; esac;;
      # The builder refuses an unknown condition before the run starts. This arm
      # is the backstop for a record that reached the loop some other way.
      *) die "when: '$kind' is not a condition this version knows";;
    esac
  done
  [ -z "$rk" ] || { ro="$(root_only_note)"; [ -z "$ro" ] || warn "when ($rk) held$ro" >&2; }
  return 0; }
# The condition in the author's words, for the line that says what was skipped.
cond_words(){ local spec="$1" pair kind val out=""
  while [ -n "$spec" ]; do
    case "$spec" in *"$COND_SEP"*) pair="${spec%%"$COND_SEP"*}"; spec="${spec#*"$COND_SEP"}";; *) pair="$spec"; spec="";; esac
    kind="${pair%%"$COND_KV"*}"; val="${pair#*"$COND_KV"}"
    case "$kind" in
      platform) out="$out${out:+ and }platform '$val' (this run: ${YUKTI_PLATFORM:-unset})";;
      *)        out="$out${out:+ and }$kind '$val'";;
    esac
  done
  printf '%s' "$out"; }
FLOW_VERBS="launch stopApp clearState background foreground relaunch openUrl setPermission fixture wait waitFor waitForId waitForNotText waitForNotId screenshot tap tapText optionalTapText tapId type clearText clearTextId pressKey hideKeyboard scroll swipe scrollToText scrollToId dismiss assertText assertId assertNotText assertNotId assertBox assertBoxId assertCount assertCountId turnWheel swipeId swipeText"
# The steps a condition switched off. They keep their numbers - the numbering is
# end to end, and a skipped step that gave its number away would move every step
# after it - they say so on the console, and they land in the report as `skipped`
# with the condition that switched them off. A nested guard inside the group is
# not a step and takes no number: it is skipped together with its group.
flow_skip(){ local n="${1:-1}" why="$2" i=0 d v xx yy mm tt dd ee ss si wc ws bx tl op t
  why="${why//[$'\n\r']/ }"
  while [ "$i" -lt "$n" ] && IFS=$'\x1f' read -r -d '' d v xx yy mm tt dd ee ss si wc ws bx tl op <&3; do
    i=$((i+1))
    if [ "$d" = "__when" ]; then continue; fi
    FLOW_IDX=$((FLOW_IDX+1)); t="$(now)"
    skipped "step $FLOW_IDX '$d'${tl:+ \"$tl\"} skipped: $why"
    printf '%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n' "$FLOW_IDX" "$d" "${v//[$'\n\r']/ }" "$t" "$t" "" "$why" "${ss//[$'\n\r']/ }" "$tl" "${FLOW_SKIP_KIND:-}" >> "$FLOW_REC"
  done; }
flow(){
  FLOW_CUT=""
  # --check builds the flow and stops there: every step is read, resolved and
  # validated, and not one of them is performed. It needs no simulator and no
  # emulator, which is what makes it the only part of a flow a CI runner can
  # look at. A step whose condition decides at run time whether it runs is
  # checked all the same - the screen is never asked, so the condition is not
  # answered here, only its spelling is.
  local chk=0 a args=""
  # The flag is read wherever it stands. Written after the file name it used to
  # be one more argument nobody looked at, so `yukti flow x.json --check` ran the
  # flow: a check that performs the steps it was asked to only inspect fails in
  # the one direction a check must not. Anything else left over is a typo, and a
  # typo that is ignored is an instruction that did not happen.
  for a in "$@"; do
    case "$a" in
      --check) chk=1;;
      -*) die "unknown option '$a' - usage: yukti flow [--check] <file.json>";;
      *) [ -z "$args" ] || die "one flow file at a time - usage: yukti flow [--check] <file.json>"
         args="$a";;
    esac
  done
  [ -n "$args" ] || die "usage: yukti flow [--check] <file.json>"
  local f="$args" st; [ -f "$f" ] || die "no flow file '$f'"; paths
  FLOW_FILE="$f"; FLOW_IDX=0; FLOW_ART=""
  FLOW_BOUND="$(mktemp)"; FLOW_BLOCKED=""; FLOW_TEARS=0; FLOW_TZ_READ=""; FLOW_PLAT_KIND=""
  if [ "$chk" = 1 ]; then
    say "checking flow: $f"
    trap 'rm -f "$FLOW_BOUND" "$FLOW_BOUND.err" "$FLOW_BOUND.stand"' EXIT
  else
    say "running flow: $f"
    FLOW_REC="$(mktemp)"; FLOW_CUR="$(mktemp)"; FLOW_ERR="$(mktemp)"; FLOW_TREE="$(mktemp)"; FLOW_T0="$(now)"
    export YUKTI_STEP_ERR="$FLOW_ERR" YUKTI_LAST_TREE="$FLOW_TREE"
    # Nothing ran, so nothing is reported: a JUnit file written by --check would
    # say a flow passed on a machine that never had a device.
    # The teardown goes first: it runs whatever the outcome, and what it says
    # belongs in the results.
    trap 'FLOW_ST=$?; flow_teardown || true; flow_results $FLOW_ST; read_summary || true; run_dir_cleanup; rm -f "$FLOW_BOUND" "$FLOW_BOUND.err" "$FLOW_BOUND.stand"' EXIT
  fi
  # Preparation (#55): checked in both modes, called only in a run, and before
  # the steps are built - a bound value reaches them like any other variable.
  # The whole flow is checked first, as --check does it, with a stand-in for
  # every bound value: a typo in a step stops the flow before anything is made
  # on the server.
  local fx ck
  fx="$(fixture_py check 2> "$FLOW_BOUND.err")" || die "$(cat "$FLOW_BOUND.err")"
  FLOW_TEARS="${fx#* }"
  if [ "$chk" = 0 ] && [ "${fx%% *}" != 0 ]; then
    ck="$(env -u YUKTI_STEP_ERR -u YUKTI_LAST_TREE "$0" flow --check "$f" 2>&1 >/dev/null)" \
      || die "$(printf '%s\n' "$ck" | sed $'s/\033\\[[0-9;]*m//g; s/^✗ //' | tail -1)"
    flow_prepare
  fi
  # The steps are built before the first one runs, and a flow file the builder
  # refuses never starts. It used to be generated straight into the loop, where
  # its status was lost with the process substitution: a flow file that is not
  # valid JSON, or one carrying a variable that is not set, produced no steps
  # and the run still ended with "flow complete".
  local steps gerr gmsg
  steps="$(mktemp)"; gerr="$(mktemp)"
  if ! YUKTI_ENV0="$_yk_env0" YUKTI_BOUND="$FLOW_BOUND" "$PY" - "$f" > "$steps" 2> "$gerr" <<'PY'
import json, os, re, sys

def fail(msg):
    sys.stderr.write(msg + "\n"); sys.exit(2)

# The same forms os.path.expandvars accepted, minus its silence: it returns the
# text unchanged when the variable is not set, so ${TEST_PASSWORD} was typed
# into whatever held focus as a literal and the log said `type 16 chars`.
VAR = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
NAME = re.compile(r"\A[A-Za-z_][A-Za-z0-9_]*\Z")
# A record ends with NUL, the fields inside it are separated by US. A newline is
# then just a character in a value: a caption that wraps on screen is what an
# author copies out of it, and the lookup already folds whitespace on both sides
# of the comparison. Line-separated records cut such a value in half, ran the
# first half as the step and read the second as a step of its own.
SEP, END = "\x1f", "\0"
KEYS = ("do", "value", "x", "y", "match", "timeout", "direction", "edges")
# A step may also carry a condition. It is not one of the fields above: it is
# answered while the run goes on, and its answer decides whether the step runs.
WHEN_KINDS = ("notVisible", "notVisibleId", "platform", "visible", "visibleId", "zeroSizeId")
# The box of an element, asserted by assertBox and assertBoxId. Like "when",
# this is a structured key: several constraints belong to one step, and they
# travel in one field rather than eight.
BOX_KINDS = ("maxHeight", "maxWidth", "maxX", "maxY",
             "minHeight", "minWidth", "minX", "minY")
# A constraint can also name another element by id: the box is then measured
# against that element's box, read from the same screen (#127).
BOX_RELATIONS = ("above", "apart", "below", "leftOf", "rightOf")
# A title says what a step is for, in the author's words. It is for the reader
# of a run and nothing else: the step runs the same with it or without it.
# "optional" lets a waitForId time out without failing the flow; no other step
# takes it.
# "in" limits a text check to one element, named by id (#102).
# "shows" is what a field that filters its input holds after `type` (#128).
# "selected" and "checked" ask an element found by id for its state (#103),
# and "expanded" (#183).
STATE_KEYS = ("selected", "checked", "expanded")
STATE_VERBS = ("assertId", "waitForId")
# "wheel" is the number of the wheel turnWheel turns, top to bottom, then
# left to right (#120).
# "state" is the state setPermission sets a permission to (#51), and the
# permission is named once for both platforms; a name with a dot is Android's own.
PERM_STATES = ("granted", "denied", "unset")
PERM_NAMES = ("notifications", "camera", "microphone", "location", "photos",
              "contacts", "calendar", "motion", "reminders", "health")
# "index" picks one of several matches, zero-based, in the order of the screen:
# top to bottom, then left to right (#46).
INDEX_VERBS = ("tapText", "optionalTapText", "tapId", "clearTextId",
               "assertText", "assertId", "assertBox", "assertBoxId",
               "waitFor", "waitForId")
# "op" and "count" are what assertCount compares the number of matches with (#47).
COUNT_VERBS = ("assertCount", "assertCountId")
COUNT_OPS = ("atLeast", "exact", "atMost")
# "at" is a point inside the element tapId taps, as shares of its box (#129).
# "toX" and "toY" are where a swipe ends (#48).
STEP_KEYS = (set(KEYS) | {"with", "when", "box", "title", "optional", "in", "shows", "wheel", "state", "at", "toX", "toY",
                          "index", "op", "count"} | set(STATE_KEYS))
# The steps that read a point, and the keys they read it from.
XY_VERBS = {"tap": ("x", "y"), "clearText": ("x", "y"), "swipe": ("x", "y", "toX", "toY")}
IN_VERBS = ("assertText", "assertNotText", "waitFor", "tapText", "assertCount", "assertCountId")
INCLUDE_KEYS = {"do", "value", "with", "when"}
# One condition is a kind and a value; several in one `when` all have to hold.
# These two characters separate them inside the single field that carries them.
KV, CSEP = "\x1d", "\x1e"
# `include` runs the steps of another flow file here. It is resolved while the
# steps are built, not while they run: the block's steps enter the stream as
# ordinary records, so the runner, the console and the JUnit file treat them
# exactly like steps written in the file itself - a failure inside the login
# block is a failed step in the report, not a silence.
#
# Blocks are built from smaller blocks: "open the account" is "open the account
# screen" + "back to a known screen" + "back to the tabs", and a flow that
# includes it is three levels down already. Two levels made authors copy steps
# or run a block as a flow of its own. The limit stays as a guard against a
# mistake, not as a rule of style: eight is deeper than any block structure we
# have seen, and a chain that reaches it is far more likely an error than a
# design. A circle is refused on its own, whatever the depth.
MAX_DEPTH = 8

def load(path, what, pre=""):
    try:
        with open(path, encoding="utf-8") as fh: doc = json.load(fh)
    except ValueError as e:
        fail("%s%s is not valid JSON: %s" % (pre, what, e))
    except OSError as e:
        fail("%s%s cannot be read: %s" % (pre, what, e))
    if not isinstance(doc, dict) or not isinstance(doc.get("steps"), list):
        fail('%s%s has no "steps" list' % (pre, what))
    if not doc["steps"]:
        fail("%s%s has no steps - it would pass without doing anything" % (pre, what))
    # The state a flow starts from belongs to the flow (#55): a block included
    # twice would prepare twice, and its teardown would run in the middle.
    for key in ("prepare", "teardown"):
        if pre and key in doc:
            fail('%s%s carries "%s" - only the flow file itself does' % (pre, what, key))
    return doc["steps"]

def when_spec(step, at, scope, src):
    if "when" not in step: return ""
    w = step["when"]
    if not isinstance(w, dict):
        fail('%s: "when" is an object of conditions, for instance '
             '{"visible": "Continue"} or {"platform": "android"}' % at)
    if not w:
        fail('%s: "when" is empty - name a condition (%s) or drop the key'
             % (at, ", ".join(WHEN_KINDS)))
    pairs = []
    for key in sorted(w):
        if key not in WHEN_KINDS:
            fail("%s: '%s' is not a condition - this version knows %s"
                 % (at, key, ", ".join(WHEN_KINDS)))
        v = w[key]
        if v is None or isinstance(v, (dict, list, bool)):
            fail("%s: condition '%s' must be text or a number" % (at, key))
        v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src)).strip()
        if not v:
            fail("%s: condition '%s' has no value" % (at, key))
        if any(ch in v for ch in (SEP, END, KV, CSEP)):
            fail("%s: condition '%s' contains a character the runner separates "
                 "fields with" % (at, key))
        # A platform nobody runs on is not a condition, it is an off switch: the
        # step would be skipped on every run and the run would stay green.
        if key == "platform" and v not in ("android", "ios"):
            fail("%s: '%s' is not a platform - use android or ios" % (at, v))
        pairs.append(key + KV + v)
    return CSEP.join(pairs)

def title_of(step, at):
    if "title" not in step: return ""
    t = step["title"]
    if t is None:
        fail('%s: "title" is null - remove the key or give it a value' % at)
    if not isinstance(t, str):
        fail('%s: "title" is text that says what the step is for, for instance '
             '"open the account screen"' % at)
    # Taken as written: no ${VARIABLE} is expanded in it. A title is words for
    # the reader, and a report that spelled out ${TEST_PASSWORD} because a title
    # mentioned it would be the leak the typed-text rule exists to prevent.
    if SEP in t or END in t:
        fail('%s: "title" contains a character the runner separates fields '
             "with" % at)
    # One line: the report and the console both print it on one.
    t = " ".join(t.split())
    if not t:
        fail('%s: "title" is empty - say what the step is for or drop the key' % at)
    return t

def state_of(step, at):
    keys = [k for k in STATE_KEYS if k in step]
    if not keys: return ""
    verb = step.get("do", "")
    # A state belongs to an element named by id; a step that ignored the key
    # would pass on an element in any state.
    if verb not in STATE_VERBS:
        fail('%s: step \'%s\' does not take "%s" - only %s do'
             % (at, verb, keys[0], ", ".join(STATE_VERBS)))
    out = []
    for k in keys:
        v = step[k]
        # A boolean and nothing else, as "optional": "false" as text is truthy.
        if not isinstance(v, bool):
            fail('%s: "%s" is true or false, got %s' % (at, k, json.dumps(v)))
        out.append("%s=%s" % (k, "true" if v else "false"))
    return " ".join(out)

def perm_of(step, at, scope, src):
    verb = step.get("do", "")
    if verb != "setPermission":
        if "state" in step:
            fail('%s: step \'%s\' does not take "state" - only setPermission does' % (at, verb))
        return ""
    v = step.get("value")
    if not isinstance(v, str) or not v.strip():
        fail('%s: "value" is the permission to set, one of %s, or an Android '
             'permission name with a dot' % (at, ", ".join(PERM_NAMES)))
    v = fill(v.strip(), scope, at, bool(src))
    if v not in PERM_NAMES and "." not in v:
        fail("%s: '%s' is not a permission the engine knows - one of %s, or an "
             "Android permission name with a dot" % (at, v, ", ".join(PERM_NAMES)))
    st = step.get("state")
    if st not in PERM_STATES:
        fail('%s: "state" is %s, got %s' % (at, ", ".join(PERM_STATES),
             json.dumps(st) if "state" in step else "nothing"))
    return "state=" + st

def optional_of(step, at):
    if "optional" not in step: return ""
    verb = step.get("do", "")
    # Only the wait by id: that is the case it was made for, and a key a step
    # ignored would be a line of the file that does not do what it says.
    if verb != "waitForId":
        fail('%s: step \'%s\' does not take "optional" - only waitForId does' % (at, verb))
    o = step["optional"]
    # A boolean and nothing else: "false" as text is truthy everywhere it could
    # be read, and a wait that was meant to fail the flow would quietly not.
    if not isinstance(o, bool):
        fail('%s: "optional" is true or false, got %s' % (at, json.dumps(o)))
    return "1" if o else ""

def in_of(step, at, scope, src):
    if "in" not in step: return ""
    verb = step.get("do", "")
    # The text checks and tapText (#146) and nothing else: a step that ignored
    # the key would tell the author its lookup was limited to an element when
    # it was not.
    if verb not in IN_VERBS:
        fail('%s: step \'%s\' does not take "in" - only %s do'
             % (at, verb, ", ".join(IN_VERBS)))
    v = step["in"]
    if v is None or isinstance(v, (dict, list, bool)):
        fail('%s: "in" is the id of the element the text has to be in, for '
             'instance "greeting-text"' % at)
    v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src)).strip()
    # Empty would mean "no element", and the lookup would fail every time with
    # words about an id nobody wrote.
    if not v:
        fail('%s: "in" is empty - name the id of the element or drop the key' % at)
    if SEP in v or END in v:
        fail('%s: "in" contains a character the runner separates fields with' % at)
    return v

def shows_of(step, at, scope, src):
    if "shows" not in step: return ""
    verb = step.get("do", "")
    # `type` reads the field back, and nothing else does: a step that ignored
    # the key would tell the author the field was checked when it was not.
    if verb != "type":
        fail('%s: step \'%s\' does not take "shows" - only type does' % (at, verb))
    v = step["shows"]
    if v is None or isinstance(v, (dict, list, bool)):
        fail('%s: "shows" is the text the field holds once the value is typed, '
             'for instance "12" for "12a!" in a digits-only field' % at)
    v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src))
    # A field that shows nothing new cannot be told from a field the keys never
    # reached: iOS finds the typed field by its change, and on Android an
    # unchanged field would pass a step whose keys went nowhere.
    if not v:
        fail('%s: "shows" is empty - a field that shows nothing new cannot be '
             'told from a field the keys never reached; type at least one '
             'character the field keeps' % at)
    if SEP in v or END in v:
        fail('%s: "shows" contains a character the runner separates fields with' % at)
    return v

def whole(v, key, at, scope, src, what):
    # A whole number from 0, as text: "02" is octal in the shell arithmetic
    # that reads it, so it is normalised here, where the author can be told.
    if v is None or isinstance(v, (dict, list, bool)):
        fail('%s: "%s" is %s' % (at, key, what))
    v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src)).strip()
    if not re.match(r"\A[0-9]+\Z", v):
        fail('%s: "%s" is \'%s\' - it has to be a whole number from 0: %s'
             % (at, key, v, what))
    # Six digits: a longer number is a typo, and the shell compares in 64 bits.
    if int(v) > 999999:
        fail('%s: "%s" is \'%s\' - at most 999999' % (at, key, v))
    return str(int(v))

def index_of(step, at, scope, src):
    if "index" not in step: return ""
    verb = step.get("do", "")
    # "Not the third one" is "fewer than three": a count, said by assertCount.
    if verb in ("assertNotText", "assertNotId"):
        fail('%s: step \'%s\' does not take "index" - to say there are fewer '
             'than N matches use %s with "op": "atMost"'
             % (at, verb, "assertCountId" if verb == "assertNotId" else "assertCount"))
    if verb not in INDEX_VERBS:
        fail('%s: step \'%s\' does not take "index" - only %s do'
             % (at, verb, ", ".join(INDEX_VERBS)))
    return whole(step["index"], "index", at, scope, src,
                 "the number of the match, from 0, counted top to bottom, then "
                 "left to right")

def count_of(step, at, scope, src):
    verb = step.get("do", "")
    keys = [k for k in ("op", "count") if k in step]
    if verb not in COUNT_VERBS:
        if keys:
            fail('%s: step \'%s\' does not take "%s" - only assertCount and '
                 "assertCountId do" % (at, verb, keys[0]))
        return "", ""
    if len(keys) < 2:
        fail('%s: %s needs "op" (atLeast, exact or atMost) and "count", for '
             'instance {"do": "%s", "value": "Item", "op": "atLeast", "count": 2}'
             % (at, verb, verb))
    op = step["op"]
    if not isinstance(op, str) or op not in COUNT_OPS:
        fail('%s: "op" is %s - use atLeast, exact or atMost' % (at, json.dumps(op)))
    n = whole(step["count"], "count", at, scope, src, "the number of matches to compare with")
    # At least none holds on every screen: a check that cannot fail.
    if op == "atLeast" and n == "0":
        fail('%s: "atLeast" 0 passes on any screen - ask for at least 1, or use '
             "exact or atMost" % at)
    return op, n

WHEEL_MAX = 150

def wheel_of(step, at, scope, src):
    verb = step.get("do", "")
    if "wheel" not in step:
        # Wheels have no ids, so the number is the only way to say which one:
        # a step without it would turn whichever wheel came first.
        if verb == "turnWheel":
            fail('%s: turnWheel needs a "wheel" - its number on the screen, top '
                 "to bottom, then left to right, from 1" % at)
        return ""
    if verb != "turnWheel":
        fail('%s: step \'%s\' does not take "wheel" - only turnWheel does' % (at, verb))
    v = step["wheel"]
    if v is None or isinstance(v, (dict, list, bool)):
        fail('%s: "wheel" is the number of the wheel on the screen, from 1' % at)
    v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src)).strip()
    # A whole number from 1, normalised as box numbers are: "02" is octal in the
    # shell arithmetic that picks the wheel.
    if not v.isdigit() or int(v) < 1:
        fail('%s: "wheel" is \'%s\' - it has to be a whole number from 1, the '
             "wheels counted top to bottom, then left to right" % (at, v))
    # How many rows to turn it: the wheel shows no value iOS can read (#120), so
    # the step counts rows. Up is minus. Zero would pass without touching it.
    r = fill(str(step.get("value", "")), scope, at, bool(src))
    if not re.match(r"\A[+-]?[0-9]+\Z", r) or int(r) == 0 or abs(int(r)) > WHEEL_MAX:
        fail('%s: "value" is \'%s\' - turnWheel takes the number of rows to turn '
             "the wheel, minus for up, plus for down, not 0 and at most %d"
             % (at, r, WHEEL_MAX))
    return str(int(v))

def point_of(step, at, scope, src):
    if "at" not in step: return ""
    verb = step.get("do", "")
    # tapId and nothing else: a step that ignored the key would tap the centre
    # and tell the author it tapped the point.
    if verb != "tapId":
        fail('%s: step \'%s\' does not take "at" - only tapId does' % (at, verb))
    p = step["at"]
    if not isinstance(p, dict) or not p:
        fail('%s: "at" is a point inside the element as shares of its box, for '
             'instance {"x": "50%%"} or {"x": "25%%", "y": "50%%"}' % at)
    out = []
    for key in sorted(p):
        if key not in ("x", "y"):
            fail("%s: '%s' is not a part of a point - \"at\" takes x and y" % (at, key))
    for key in ("x", "y"):
        if key not in p:
            out.append(""); continue
        v = p[key]
        if v is None or isinstance(v, (dict, list, bool)):
            fail('%s: "at" %s is a share of the element, for instance "50%%"' % (at, key))
        v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src)).strip()
        # A share, written with its sign: a bare 50 reads as pixels to anyone who
        # has written a `tap`, and a point in pixels inside an element is the
        # recorded coordinate this key exists to replace.
        if not re.match(r"\A[0-9]+%\Z", v):
            fail('%s: "at" %s is \'%s\' - it has to be a whole share of the '
                 'element written with %%, from "0%%" to "100%%"' % (at, key, v))
        # "08" is octal in the shell arithmetic that places the point.
        n = int(v[:-1])
        if n > 100:
            fail('%s: "at" %s is \'%s\' - a point inside the element is at most '
                 '"100%%"' % (at, key, v))
        out.append(str(n))
    return ",".join(out)

def xy_of(step, at):
    # A point is whole pixels, as recorded, or a whole share of the screen
    # (#48). Checked here, not where it runs: "abc" or "4.5" used to reach the
    # shell arithmetic and stop the run there with no step message, and a
    # missing "y" as a bare "y: parameter null or not set".
    verb = step.get("do", "")
    keys = XY_VERBS.get(verb, ())
    # A point on scroll is the mistake this step exists for: scroll has four
    # fixed directions and would swipe down the middle, saying nothing.
    if verb == "scroll":
        for k in ("x", "y", "toX", "toY"):
            if k in step:
                fail('%s: scroll takes no point ("%s") - for a swipe between two '
                     'points use swipe' % (at, k))
    for k in ("toX", "toY"):
        if k in step and verb != "swipe":
            fail('%s: step \'%s\' does not take "%s" - only swipe does' % (at, verb, k))
    out = {}
    for k in keys:
        if k not in step:
            fail('%s: %s needs "%s" - %s, each pixels (200) or a share of the '
                 'screen ("50%%")' % (at, verb, k, ", ".join('"%s"' % n for n in keys)))
        v = step[k]
        if v is None or isinstance(v, (dict, list, bool)):
            fail('%s: "%s" is %s - it has to be a whole number of pixels (200) or '
                 'a whole share of the screen ("50%%")' % (at, k, json.dumps(v)))
        v = (v if isinstance(v, str) else str(v)).strip()
        num = v[:-1] if v.endswith("%") else v
        if not re.match(r"\A[0-9]+\Z", num):
            fail('%s: "%s" is \'%s\' - it has to be a whole number of pixels (200) '
                 'or a whole share of the screen ("50%%")' % (at, k, v))
        # "08" is octal in the shell that works the point out.
        v = str(int(num)) + v[len(num):]
        if v.endswith("%") and int(num) > 100:
            fail('%s: "%s" is \'%s\' - a share of the screen cannot be more than '
                 '100%%' % (at, k, v))
        out[k] = v
    if verb == "swipe" and (out["x"], out["y"]) == (out["toX"], out["toY"]):
        fail('%s: the swipe starts and ends at %s,%s - that is a press, not a swipe'
             % (at, out["x"], out["y"]))
    return out

def box_spec(step, at, scope, src):
    verb = step.get("do", "")
    if "box" not in step:
        # A box assertion with nothing to assert is a step that passes on any
        # element that is on the screen - which assertText and assertId already
        # say, more cheaply and more honestly.
        if verb in ("assertBox", "assertBoxId"):
            fail("%s: %s needs a \"box\" - the constraints are %s, and %s "
                 "with the id of another element"
                 % (at, verb, ", ".join(BOX_KINDS), ", ".join(BOX_RELATIONS)))
        return ""
    if verb not in ("assertBox", "assertBoxId"):
        fail('%s: step \'%s\' does not take a "box" - only assertBox and '
             "assertBoxId do" % (at, verb))
    b = step["box"]
    if not isinstance(b, dict):
        fail('%s: "box" is an object of constraints, for instance '
             '{"minWidth": 48, "minHeight": 48}' % at)
    if not b:
        fail('%s: "box" is empty - name a constraint (%s, or %s with an id) '
             "or drop the step"
             % (at, ", ".join(BOX_KINDS), ", ".join(BOX_RELATIONS)))
    pairs = []
    for key in sorted(b):
        if key in BOX_RELATIONS:
            v = b[key]
            if not isinstance(v, str) or not v.strip():
                fail("%s: '%s' names another element by its id, for instance "
                     '{"%s": "card-a"}' % (at, key, key))
            v = fill(v, scope, at, bool(src)).strip()
            if not v:
                fail("%s: '%s' came out empty - it needs the id of another "
                     "element" % (at, key))
            # Measured against itself the box is always red (above, below,
            # leftOf, rightOf, apart) - a step that cannot pass is a typo.
            if verb == "assertBoxId" and v == fill(str(step.get("value", "")),
                                                   scope, at, bool(src)).strip():
                fail("%s: '%s' names the element the step measures, '%s' - "
                     "name the other element" % (at, key, v))
            pairs.append(key + KV + v)
            continue
        if key not in BOX_KINDS:
            fail("%s: '%s' is not a constraint - this version knows %s, and %s "
                 "with an id" % (at, key, ", ".join(BOX_KINDS),
                                 ", ".join(BOX_RELATIONS)))
        v = b[key]
        if v is None or isinstance(v, (dict, list, bool)):
            fail("%s: constraint '%s' must be a number, for instance 48, "
                 '"48dp" or "5%%"' % (at, key))
        v = fill(v if isinstance(v, str) else str(v), scope, at, bool(src)).strip()
        # Pixels, dp or whole percent, and nothing else: the comparison runs in
        # the shell, where "48px", "4.5" or "" are not numbers and would either
        # abort the run with an arithmetic error or, worse, compare as zero.
        num = v[:-1] if v.endswith("%") else (v[:-2] if v.endswith("dp") else v)
        if not num.isdigit():
            fail("%s: constraint '%s' is '%s' - it has to be a whole number of "
                 'pixels (48), of dp ("48dp") or a whole share of the screen '
                 '("5%%")' % (at, key, v))
        # "08" is a number here and octal in the shell, where it dies in the
        # arithmetic with no step message and no JUnit entry. Normalised while
        # it is still text and the author can still be told what was written.
        v = str(int(num)) + v[len(num):]
        num = str(int(num))
        if v.endswith("%") and int(num) > 100:
            fail("%s: constraint '%s' is '%s' - a share of the screen cannot be "
                 "more than 100%%" % (at, key, v))
        pairs.append(key + KV + v)
    return CSEP.join(pairs)

# A fixture step (#55): the name of a fixture in "value", the body of the call
# in "with", any depth, ${VARIABLE} filled in its texts. The body travels as JSON,
# which escapes the separators of the record.
FIXTURE = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9_.-]*\Z")
def fixture_of(step, at, scope, src):
    if step.get("do") != "fixture": return ""
    name = fill(str(step.get("value", "")), scope, at, bool(src))
    if not FIXTURE.match(name) or ".." in name:
        fail('%s: "value" is the name of a fixture - letters, digits, ".", "_" and '
             '"-", for instance "change-weight"' % at)
    w = step.get("with", {})
    if not isinstance(w, dict):
        fail('%s: "with" is an object - the body the fixture is sent' % at)
    def deep(v):
        if isinstance(v, str): return fill(v, scope, at, bool(src))
        if isinstance(v, dict): return {k: deep(x) for k, x in v.items()}
        if isinstance(v, list): return [deep(x) for x in v]
        return v
    return json.dumps(deep(w))

def guard(cond, span, src, idx):
    # A condition is a record of its own, not another field on the step it
    # guards: a block included under a condition may carry a condition on its
    # own first step, and two conditions do not fit in one set of fields.
    #
    # The guard says how many of the records that follow belong to it, counted
    # here, where the group is still a group - by the time the run reads them
    # they are a flat stream. One answer then switches the whole group off, and
    # the screen cannot change halfway through it, which is exactly what
    # happens if the condition is re-asked at every step of the block: the
    # first step dismisses the dialog, and the rest of the block is skipped.
    return SEP.join(["__when"] + [""] * (len(KEYS) - 1) + [src, str(idx), cond, str(span), "", "", "", ""])

def fill(v, scope, at, inside):
    missing = []
    def one(m, missing=missing):
        name = m.group(1) or m.group(2)
        if name not in scope: missing.append(name); return ""
        return scope[name]
    v = VAR.sub(one, v)
    if missing:
        fail("%s: $%s is not set %s - the step would have used the text as "
             "written" % (at, missing[0],
                          'here: pass it in "with" on the include, or set it in '
                          "the environment" if inside else "in the environment"))
    return v

recs = []

def build(path, shown, src, scope, chain, depth, pre=""):
    # A block is named relative to the file that includes it: a suite is moved,
    # copied and run from anywhere as one directory, and the working directory
    # of the run is not something the flow file can know. Through the real path,
    # not the link: one shared directory of blocks symlinked into two suites
    # resolved the blocks' own includes next to the LINK, which is where a
    # same-named file of the borrowing suite sits.
    base = os.path.dirname(os.path.realpath(path))
    for idx, step in enumerate(load(path, shown, pre), 1):
        of = " of %s" % shown if src else ""
        if not isinstance(step, dict): fail("step %d%s is not an object" % (idx, of))
        verb = step.get("do") or ""
        at = "step %d '%s'%s" % (idx, verb, of)
        # The runner's own records are named with two leading underscores. A flow
        # file that used such a name would hand the loop a record it answers
        # itself - a forged guard, i.e. a step that quietly does nothing.
        if isinstance(verb, str) and verb.startswith("__"):
            fail("%s: a step name cannot start with __ - those belong to the "
                 "runner's own records" % at)
        if "with" in step and verb not in ("include", "fixture"):
            fail('%s: "with" passes values to an include, or the body to a fixture - '
                 "only include and fixture take it" % at)
        if verb == "fixture" and "bind" in step:
            fail('%s: a fixture step binds nothing - the steps after it are built '
                 'before it runs; bind in "prepare"' % at)
        # A key nobody reads used to be mentioned by nobody. Tolerable while every
        # key did something visible; not tolerable next to a condition, where
        # `wehn` means a step that runs every time while the file says it is
        # conditional. The 45 flows this was measured against carry do, value, x
        # and y, so nothing in the suite depends on the old silence.
        if verb != "include":
            extra = sorted(k for k in step if k not in STEP_KEYS)
            if extra:
                fail("%s: '%s' is not a key a step takes - those are %s"
                     % (at, extra[0], ", ".join(sorted(STEP_KEYS))))
        cond = when_spec(step, at, scope, src)
        if verb == "include":
            # The guard is inserted after the block is built, because only then is
            # it known how many records it covers.
            pos = len(recs)
            include(step, at, base, src, scope, chain, depth)
            if cond: recs.insert(pos, guard(cond, len(recs) - pos, src, idx))
            continue
        fields = []
        for key in KEYS:
            v = step.get(key, "")
            if v is None:
                fail('%s: "%s" is null - remove the key or give it a value'
                     % (at, key))
            v = v if isinstance(v, str) else str(v)
            if key == "value":
                v = fill(v, scope, at, bool(src))
            if SEP in v or END in v:
                fail('%s: "%s" contains a character the runner separates fields '
                     "with" % (at, key))
            fields.append(v)
        # Which file the step was written in, carried so that a failure names it.
        # Empty for the flow file itself: the run already says which flow it is.
        fields.append(src)
        # And where it is in that file: the run numbers steps end to end, so the
        # number a failure prints is not the one to look for in the file.
        fields.append(str(idx))
        # The two fields a guard record uses. A step carries them empty: one
        # record shape for the loop to read, whatever the record is.
        fields.append("")
        fields.append("")
        fields.append(box_spec(step, at, scope, src))
        fields.append(title_of(step, at))
        fields.append(optional_of(step, at))
        fields.append(in_of(step, at, scope, src))
        fields.append(shows_of(step, at, scope, src))
        perm = perm_of(step, at, scope, src)
        fields.append(state_of(step, at) or perm)
        fields.append(wheel_of(step, at, scope, src))
        fields.append(point_of(step, at, scope, src))
        xy = xy_of(step, at)
        if "x" in xy:
            fields[KEYS.index("x")] = xy["x"]; fields[KEYS.index("y")] = xy["y"]
        fields.append(xy.get("toX", "") + (" " + xy["toY"] if "toY" in xy else ""))
        fields.append(index_of(step, at, scope, src))
        fields.extend(count_of(step, at, scope, src))
        fields.append(fixture_of(step, at, scope, src))
        if cond: recs.append(guard(cond, 1, src, idx))
        recs.append(SEP.join(fields))

def include(step, at, base, src, scope, chain, depth):
    for key in ("x", "y", "toX", "toY", "match", "timeout", "box"):
        if key in step:
            fail('%s: "%s" is not a key an include takes - it runs the steps '
                 "of a file, and those steps carry their own keys" % (at, key))
    extra = sorted(k for k in step if k not in INCLUDE_KEYS)
    if extra:
        fail("%s: '%s' is not a key an include takes - those are %s"
             % (at, extra[0], ", ".join(sorted(INCLUDE_KEYS))))
    name = step.get("value")
    if not isinstance(name, str) or not name.strip():
        fail('%s: "value" is the flow file to run here, for instance '
             '"blocks/login.json"' % at)
    name = fill(name.strip(), scope, at, bool(src))
    if SEP in name or END in name:
        fail('%s: "value" contains a character the runner separates fields '
             "with" % at)
    path = name if os.path.isabs(name) else os.path.join(base, name)
    real = os.path.realpath(path)
    trail = [c[1] for c in chain] + [name]
    if any(c[0] == real for c in chain):
        fail("%s: '%s' is already running - a block cannot include itself, "
             "directly or in a circle: %s" % (at, name, " -> ".join(trail)))
    if depth + 1 > MAX_DEPTH:
        fail("%s: includes may go %d blocks deep - '%s' would be block %d: %s"
             % (at, MAX_DEPTH, name, depth + 1, " -> ".join(trail)))
    with_ = step.get("with", {})
    if not isinstance(with_, dict):
        fail('%s: "with" is an object of name/value pairs, for instance '
             '{"TEST_EMAIL": "beth@example.com"}' % at)
    # The values a block is called with are read in the scope of the caller, so
    # an include can pass an environment variable on, or one of its own
    # parameters. Inside the block they shadow the environment, and only there.
    inner = dict(scope)
    for key in sorted(with_):
        v = with_[key]
        if not NAME.match(key):
            fail("%s: '%s' cannot be the name of a parameter - letters, digits "
                 "and _, not starting with a digit" % (at, key))
        if v is None or isinstance(v, (dict, list, bool)):
            fail("%s: parameter '%s' must be text or a number" % (at, key))
        v = v if isinstance(v, str) else str(v)
        inner[key] = fill(v, scope, at, bool(src))
    build(path, "block '%s'" % name, name, inner, chain + [(real, name)],
          depth + 1, "%s: " % at)

flow = sys.argv[1]
# What the user exported wins over what the script assigned since (#101); a
# variable the script added and the user never set is still there.
env = dict(os.environ)
try: env.update(json.loads(env.pop("YUKTI_ENV0", "") or "{}"))
except ValueError: pass
# A value a fixture bound (#55) wins over both: it is the state this run made.
# Under --check, and when the preparation did not get that far, it is a stand-in
# that names the fixture.
bound = env.pop("YUKTI_BOUND", "")
for path in (bound + ".stand", bound) if bound else ():
    try:
        with open(path, encoding="utf-8") as fh: env.update(json.load(fh))
    except (OSError, ValueError): pass
build(flow, "flow file", "", env,
      [(os.path.realpath(flow), os.path.basename(flow))], 0)

sys.stdout.write(END.join(recs) + (END if recs else ""))
PY
  then gmsg="$(cat "$gerr")"; rm -f "$steps" "$gerr"; die "${gmsg:-the flow file could not be read}"; fi
  rm -f "$gerr"
  # Opened and then unlinked: the loop keeps reading it, and no path is left
  # behind whichever way the flow ends.
  exec 3< "$steps"; rm -f "$steps"
  # A flow whose preparation did not work did not run: every step is listed as
  # not run, with the reason, and the flow is not a pass and not a failure.
  if [ -n "$FLOW_BLOCKED" ]; then
    skipped "flow blocked: ${FLOW_BLOCKED#blocked: } - none of its steps ran"
    FLOW_CUT="the preparation: $FLOW_BLOCKED"
    FLOW_SKIP_KIND=blocked flow_skip 1000000 "$FLOW_BLOCKED"
  fi
  # The steps are fed on FD 3, NOT stdin: steps shell out to adb/idb,
  # and `adb shell` / subprocesses read stdin — if the loop read from the same
  # pipe they'd swallow the remaining steps, so only step 1 ran (and the flow
  # still reported PASS). Reading `<&3` also keeps the loop in THIS shell (not a
  # pipe subshell), so a step's `die` (exit 1) aborts the whole flow with a
  # non-zero status instead of being lost.
  while IFS=$'\x1f' read -r -d '' do_ val x y mtch tmo dir edg src sidx wcond wspan bspec ttl opt inid shw stt whl atp to idx cop cnt fxw <&3; do
      # A guard is not a step: it takes no number of its own, and when it holds
      # the run says nothing about it - the steps that follow simply run. When it
      # does not hold, its whole group is read off the stream and every step in it
      # is recorded as skipped.
      if [ "$do_" = "__when" ]; then
        if [ -n "$src" ]; then export YUKTI_STEP_SRC="block '$src', step $sidx"
        else export YUKTI_STEP_SRC="step $sidx of this flow file"; fi
        # Answering a condition means reading the screen. --check has none, and
        # skipping the group would leave the steps inside it unchecked - the
        # steps most likely to be stale, because a condition is what keeps them
        # off most runs.
        if [ "$chk" = 1 ]; then continue; fi
        if cond_holds "$wcond"; then continue; fi
        flow_skip "${wspan:-1}" "$(cond_words "$wcond")"
        continue
      fi
      # Record the step BEFORE running it and again once it survived: the one
      # step that has a start and no end is the step that failed, and that is
      # the single fact a report cannot reconstruct from console text.
      # A step runs from here: whatever a `when` held before it is of the screen
      # this step is about to change, and the next condition reads again.
      HELD_TREE=""
      FLOW_IDX=$((FLOW_IDX+1)); FLOW_S0="$(now)"; FLOW_ART=""
      # The number the run counts and the number the author has to look for are
      # the same file only while a flow has no includes. Once it has one, step 4
      # of the run can be step 2 of the block, or step 2 of the flow file after
      # a block of three - so a failure says which file and which step in it,
      # and says nothing extra when the two numbers agree.
      if [ -n "$src" ]; then export YUKTI_STEP_SRC="block '$src', step $sidx"
      elif [ "$sidx" != "$FLOW_IDX" ]; then export YUKTI_STEP_SRC="step $sidx of this flow file"
      else export YUKTI_STEP_SRC=""; fi
      # setPermission is recorded with its state: the report tells a grant,
      # which leaves the app running, from a revoke, which stops it.
      rval="${val//[$'\n\r']/ }"; [ "$do_" = setPermission ] && rval="$rval ${stt#state=}"
      if [ "$chk" = 0 ]; then
        printf '%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n' "$FLOW_IDX" "$do_" "$rval" "$FLOW_S0" "${src//[$'\n\r']/ }" "$ttl" > "$FLOW_CUR"
        : > "$FLOW_ERR"; rm -f "$FLOW_ERR.kind"
      fi
      # The name first, the keys after it, because the order decides what a typo
      # hears. A step named `tpText` carrying a `match` would otherwise be told
      # that `tpText` does not take the key - a message that asserts the verb
      # exists and costs the author a second run to find the real mistake.
      case " $FLOW_VERBS " in *" $do_ "*) ;; *) die "unknown step '$do_' - check the flow file";; esac
      # `match` belongs to the assertion contract, so only the verb that reads
      # it may be given it. A locator that ignored the key told the flow author
      # it was honoured: tapText folds case and matches a substring whatever the
      # step says, and a suite written on that belief is weaker than it reads.
      [ -z "$mtch" ] || case "$do_" in assertText|assertNotText|assertCount|waitFor|waitForNotText) ;; *) die "step $FLOW_IDX '$do_' does not take a \"match\" - only assertText, assertNotText, assertCount, waitFor and waitForNotText do";; esac
      # Same rule for the two keys scrollToText reads: a key a step ignores is a
      # line of the flow file that does not do what it says. `scroll` carries its
      # direction in "value", the way it always has.
      [ -z "$dir" ] || case "$do_" in scrollToText|scrollToId|swipeId|swipeText) ;; *) die "step $FLOW_IDX '$do_' does not take a \"direction\" - only scrollToText, scrollToId, swipeId and swipeText do; scroll takes its direction as its \"value\"";; esac
      # A swipe on an element has no direction of its own to fall back on: left
      # shows a row's actions, right often does something else entirely.
      case "$do_" in swipeId|swipeText)
        case "$dir" in up|down|left|right) ;; "") die "step $FLOW_IDX '$do_' needs a \"direction\" - up, down, left or right, where the finger goes";;
          *) die "step $FLOW_IDX '$do_': '$dir' is not a direction - use up, down, left or right";; esac;; esac
      [ -z "$edg" ] || case "$do_" in scrollToText|scrollToId) ;; *) die "step $FLOW_IDX '$do_' does not take an \"edges\" - only scrollToText and scrollToId do";; esac
      # tapText with "in" reads the screen once and does not scroll, so the wait
      # at the end of a list that "timeout" sets is not there to set (#146).
      [ "$do_" != tapText ] || [ -z "$inid" ] || [ -z "$tmo" ] || die "step $FLOW_IDX 'tapText' takes \"in\" or \"timeout\", not both - with \"in\" it does not scroll, and the timeout is the wait at the end of a scroll"
      # Same rule, the other way round: hideKeyboard closes whatever keyboard is
      # up and has nothing to read a value with. Carrying one means the author
      # meant pressKey, and a key silently ignored is a flow that believes it
      # pressed something.
      case "$do_" in hideKeyboard) [ -z "$val" ] || die "step $FLOW_IDX 'hideKeyboard' does not take a \"value\" - it closes whatever keyboard is up; to press a named key use pressKey";; esac
      # background takes seconds and nothing else; the other two act on the app
      # of $YUKTI_VARIANT, so a value there is a variant name that would be ignored.
      case "$do_" in
        background) case "$val" in *[!0-9]*) die "step $FLOW_IDX 'background': \"value\" is how many whole seconds the app stays in the background, got '$val'";; esac
                    # A typo of a few zeros would hold the run for hours.
                    [ "${#val}" -le 3 ] && [ "${val:-0}" -le 600 ] 2>/dev/null || die "step $FLOW_IDX 'background': $val seconds - the most is 600";;
        foreground|relaunch) [ -z "$val" ] || die "step $FLOW_IDX '$do_' does not take a \"value\" - it acts on the app of \$YUKTI_VARIANT";;
      esac
      # Everything above this line is answerable without a device. Everything
      # below it touches one.
      if [ "$chk" = 1 ]; then continue; fi
      # A step with a title says so before it runs: the lines the step prints
      # itself name what it touched, the title names what it was for.
      [ -z "$ttl" ] || say "step $FLOW_IDX '$do_' \"$ttl\""
      FLOW_OPT_MISS=""
      # The flow acts from here on (#191): a blank tree is no longer relaunched
      # away (ios_unstick). Waits, checks and screenshots read the screen; a
      # fixture and a permission do not touch it.
      # The mark goes down before the step runs: a step that acts reads first and
      # acts after, and a relaunch between the two would act on the first screen.
      case "$do_" in wait|waitFor|waitForId|waitForNotText|waitForNotId|screenshot|assert*|fixture|setPermission) ;;
        *) [ -z "$FLOW_REC" ] || { : > "$FLOW_REC.acted"
             # #207: `launch` leaves the mark for one "still drawing" round of
             # reads (ios_unstick); any other action takes it away.
             if [ "$do_" = launch ]; then : > "$FLOW_REC.launched"; else rm -f "$FLOW_REC.launched"; fi; } 2>/dev/null || true;; esac
      set +e   # a step must not abort the loop by itself: the status is read
               # right after the dispatcher, so the failure is attributed to
               # THIS step and the flow stops with a message.
      case "$do_" in
        wait)        wait_s "${val:-2}";;
        waitFor)     wait_for "$val" "${tmo:-10}" "${mtch:-exact}" assert "" "$inid" "" "$idx";;
        waitForId)   wait_for "$val" "${tmo:-10}" exact id "${opt:+optional}" "" "$stt" "$idx";;
        waitForNotText) wait_gone "$val" "${tmo:-10}" "${mtch:-exact}" assert;;
        waitForNotId) wait_gone "$val" "${tmo:-10}" exact id;;
        # shot runs in a substitution, so its own die kills only that subshell:
        # the step used to report PASS with an empty path, whether the name was
        # refused or screencap itself failed. The status has to be checked here,
        # in the shell that can stop the flow.
        # A reason the shot already gave (a refused name) is kept: "screenshot
        # failed" over it would leave the result without the why.
        screenshot)  FLOW_ART="$(shot "$val")" || { [ ! -s "$FLOW_ERR" ] || exit 1; die "screenshot failed"; }
                     [ -n "$FLOW_ART" ] || die "screenshot produced no file"
                     ok "shot → $FLOW_ART";;
        tap)         tap $(flow_xy "$x" "$y");;
        tapText)     say "tap '$val'${inid:+ in '$inid'}${idx:+ index $idx}"; tap_text "$val" "$tmo" "$inid" "$idx";;
        optionalTapText) tap_text_optional "$val" "$idx";;
        scroll)      scroll_step "${val:-down}";;
        swipe)       swipe_step "$x" "$y" "${to% *}" "${to#* }";;
        scrollToText) scroll_to_step "$val" "${dir:-down}" "$edg" "$tmo" >/dev/null;;
        scrollToId)   scroll_to_step "$val" "${dir:-down}" "$edg" "$tmo" id >/dev/null;;
        dismiss)     dismiss;;
        clearText)   clear_field $(flow_xy "$x" "$y");;
        clearTextId) say "clear id '$val'${idx:+ index $idx}"; clear_id "$val" "$idx";;
        pressKey)    press_key "$val";;
        hideKeyboard) hide_keyboard;;
        type)        say "type ${#val} chars"; type_str "$val" "$shw";;
        assertText)  assert_text "$val" "${mtch:-exact}" "$inid" "$idx";;
        assertNotText) assert_not_text "$val" "${mtch:-exact}" "$inid";;
        assertNotId) assert_not_id "$val";;
        tapId)       say "tap id '$val'${idx:+ index $idx}"; tap_id "$val" "${atp%%,*}" "${atp#*,}" "$idx";;
        assertId)    assert_id "$val" "$stt" "$idx";;
        assertBox)   assert_box "$val" assert "$bspec" "$idx";;
        assertBoxId) assert_box "$val" id "$bspec" "$idx";;
        assertCount) assert_count "$val" assert "$cop" "$cnt" "${mtch:-exact}" "$inid";;
        assertCountId) assert_count "$val" id "$cop" "$cnt" exact "$inid";;
        turnWheel)   turn_wheel "$whl" "$val";;
        swipeId)     say "swipe id '$val' $dir"; swipe_el "$val" id "$dir";;
        swipeText)   say "swipe '$val' $dir"; swipe_el "$val" text "$dir";;
        launch)      launch "$val";;
        stopApp)     stop_app "$val";;
        clearState)  clear_state "$val";;
        background)  app_background "${val:-0}";;
        foreground)  app_foreground;;
        relaunch)    app_relaunch;;
        openUrl)     open_url "$val";;
        setPermission) set_permission "$val" "$stt";;
        fixture)     say "fixture '$val'"; fixture_step "$val" "$fxw";;
        # A name the dispatcher does not know is a typo in the flow file, and a
        # typo must not pass: `warn` returns zero, so this case has to die on its
        # own - reading the status below would not catch it.
        *) die "unknown step '$do_' - check the flow file";;
      esac
      st=$?
      # A step that failed without dying used to be recorded as passed: the
      # status of the dispatcher was never read. `adb` refusing a tap, a launch
      # of a package that is not installed, a clearText on a dead device - all
      # reported PASS, and the JUnit file said failures="0". Only an explicit
      # `die` could stop a flow.
      #
      # The two best-effort verbs stay the exception, by contract: they return
      # non-zero when a label is simply absent, which is the state they exist
      # to tolerate.
      case "$do_" in dismiss|optionalTapText) st=0;; esac
      [ "$st" -eq 0 ] || die "step $FLOW_IDX '$do_'${ttl:+ \"$ttl\"} failed (exit $st)"
      # A permission this platform or its version does not have (#51): the flow
      # is skipped from this step, out loud and in the report - a flow about the
      # denied branch that went on without it would prove nothing. A fixture step
      # that did not get its state (#55) does the same, with "blocked:".
      if [ -n "$FLOW_PLAT_SKIP" ]; then
        skipped "step $FLOW_IDX '$do_'${ttl:+ \"$ttl\"} skipped: $FLOW_PLAT_SKIP - the rest of the flow is skipped with it"
        printf '%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n' "$FLOW_IDX" "$do_" "$rval" "$FLOW_S0" "$(now)" "" "$FLOW_PLAT_SKIP" "${src//[$'\n\r']/ }" "$ttl" "${FLOW_PLAT_KIND:-platform}" >> "$FLOW_REC"
        FLOW_CUT="step $FLOW_IDX: $FLOW_PLAT_SKIP"
        FLOW_SKIP_KIND="${FLOW_PLAT_KIND:-platform}" flow_skip 1000000 "$FLOW_PLAT_SKIP"; FLOW_PLAT_SKIP=""; FLOW_PLAT_KIND=""
        continue
      fi
      # The eighth field is the block the step was written in, empty for the flow
      # file itself; the seventh stays empty, because this step ran - unless it
      # was an optional wait that ended without its element: then the seventh
      # holds what the wait found and the tenth says it was that kind of skip.
      # The ninth is the step's title, empty when it has none.
      printf '%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n' "$FLOW_IDX" "$do_" "$rval" "$FLOW_S0" "$(now)" "$FLOW_ART" "${FLOW_OPT_MISS//[$'\n\r']/ }" "${src//[$'\n\r']/ }" "$ttl" "${FLOW_OPT_MISS:+optional}" >> "$FLOW_REC"
  done
  exec 3<&-
  export YUKTI_STEP_SRC=""
  if [ "$chk" = 1 ]; then ok "flow checks out: $f - $FLOW_IDX steps"
  elif [ -n "${FLOW_CUT:-}" ]; then skipped "flow skipped from $FLOW_CUT - not a pass: the steps after it did not run"
  else ok "flow complete: $f"; fi
}

init(){ [ -f "$CONFIG" ] && die "$CONFIG exists"
  if [ "${1:-}" = android ] || [ "${YUKTI_PLATFORM:-}" = android ]; then cat > "$CONFIG" <<'JSON'
{
  "platform": "android",
  "projectRoot": ".",
  "android": { "avd": "Pixel_7_API_34" },
  "variants": {
    "qa":   { "platform": "android", "package": "com.you.app",     "gradleTask": "assembleDebug",   "envFile": ".env.qa" },
    "prod": { "platform": "android", "package": "com.you.app",     "gradleTask": "assembleRelease", "envFile": ".env.production" }
  }
}
JSON
  ok "wrote $CONFIG (android) — set your package, then 'yukti doctor' and 'yukti up qa'"; return; fi
  cat > "$CONFIG" <<'JSON'
{
  "platform": "ios",
  "projectRoot": ".",
  "workspace": "ios/YourApp.xcworkspace",
  "simulator": { "device": "iPhone 16 Pro" },
  "excludeIosAutolink": [],
  "easEnabled": false,
  "variants": {
    "qa":   { "platform": "ios", "scheme": "YourApp", "configuration": "Release", "bundleId": "com.you.app", "envFile": ".env.qa",         "appVariant": "development", "nodeEnv": "development", "easProfile": "simulator" },
    "prod": { "platform": "ios", "scheme": "YourApp", "configuration": "Release", "bundleId": "com.you.app", "envFile": ".env.production", "appVariant": "production",  "nodeEnv": "production",  "easProfile": "simulator" }
  }
}
JSON
  ok "wrote $CONFIG — edit it, then 'yukti doctor' and 'yukti up qa'"; }

usage(){ cat <<EOF
${_yk_B}yukti v$YUKTI_VERSION${_yk_R} — YUKTI — smart mobile-app QA automation for React Native / Expo

  yukti doctor              check/guide the toolchain (Xcode, node@22, cocoapods, idb)
  yukti init                write a starter yukti.config.json
  yukti scan                list device-only frameworks (no arm64-sim slice) to exclude
  yukti build <variant>     build a signed arm64 simulator .app (local)
  yukti pull  <variant>     pull an OFFICIAL simulator build from EAS (needs EXPO_TOKEN)
  yukti boot                create/boot the simulator
  yukti up    <variant>     build + boot + install + launch  (one shot)
  yukti install <variant> [--apk <path>]
                            install a build; on Android --apk (or the variant's
                            "apkPath") installs an APK built elsewhere, e.g. by CI
  yukti flow  <file.json>   run a deterministic flow (Talos test-case engine — no AI, CI-ready)
                            leaves \$YUKTI_RESULTS_DIR/<flow>.xml (JUnit) — per-step result
  yukti flow --check <file.json>
                            build the flow and stop: verbs, keys, conditions,
                            includes and variables, no device, nothing performed

  drive primitives (for flows or an AI agent — Claude Code / OpenAI):
  yukti shot [file]         screenshot the sim (an agent reads the PNG)
  yukti ui                  accessibility tree (JSON, coords in points)
  yukti helper stop         Android: stop the resident screen helper and remove its forward
  yukti find "<label>"      -> "x y" center of the first element matching label
  yukti tap <x> <y>         tap; each is pixels (200) or a share of the screen ("50%")
  yukti type "<text>"       type (char-by-char = reliable; idb bulk-type drops chars)
  yukti clear <x> <y>       clear a text field (pixels or a share, as tap)
  yukti swipe <x> <y> <toX> <toY>
                            swipe from one point to the other, pixels or a share of the screen
  yukti scroll <up|down|left|right>
                            scroll the screen · yukti scroll-to "<label>" [dir] [clear] [timeout] scroll a label into view, fail on a miss
                            yukti scroll-to-id "<id>" [dir] [clear] [timeout] the same, the element found by its id
  yukti dismiss             auto-dismiss common modals (Not Now / Skip / OK / Close…)
  yukti assert "<text>" [exact|contains] [<id>]
                            assert the text is on screen (perceivable text only, no scroll);
                            with an id, only in that element and what lies within it
  yukti stop-app <variant>  force-stop the app of that variant
  yukti clear-state <variant>
                            wipe the app's data (Android only) - the app stops, launch it again
  yukti open-url "<key>"    open a screen of the app under test by its key ("home", "cart")
                            the app of \$YUKTI_VARIANT; the address is that variant's "urlBase"
                            plus the key, or plus its path from the "urls" table when there is
                            one, so no flow carries an environment. It delivers the address,
                            and arrival is asynchronous - the step after it is a waitFor
  yukti wait-for "<text>" [s] [exact|contains]
                            poll until the text is on screen, fail on timeout (default 10s)
  yukti wait-for-not "<text>" [s] [exact|contains]
                            poll until the text is gone from the screen, fail on timeout (default 10s)
  yukti wait-for-not-id "<id>" [s]
                            poll until no element with this id is on the screen, fail on timeout (default 10s)
  yukti tap-id "<id>" [x%] [y%]
                            tap the element with this a11y id / resource-id segment
                            (or the full resource-id, pkg:id/name);
                            with shares, that point inside it (tap-id slider-track 50%)
  yukti clear-id "<id>"     empty the text field with this a11y id / resource-id segment
                            (or the full resource-id, pkg:id/name)
  yukti assert-id "<id>"    assert an element with this id is on screen
  yukti assert-box "<q>" <assert|id> minWidth=48dp minHeight=48dp
                            assert the box of that element: minWidth, minHeight,
                            maxWidth, maxHeight, minX, minY, maxX, maxY, written
                            in pixels (48), dp ("48dp") or a share ("5%");
                            above, below, leftOf, rightOf, apart take the id of
                            another element (above=tab-bar)
  yukti swipe-id "<id>" <up|down|left|right>
                            swipe across the element with this id, in the direction the
                            finger goes, over 60% of its width (of its height for up/down),
                            centred on it; YUKTI_SWIPE_SHARE changes the share (1-90)
  yukti swipe-text "<text>" <up|down|left|right>
                            the same for the element with this text
  yukti assert-count "<q>" <assert|id> <atLeast|exact|atMost> <n> [exact|contains] [<id>]
                            count the elements with that text (assert) or id on the
                            screen and compare: assert-count Item assert atLeast 2;
                            with an id, only inside that element
  yukti assert-not "<text>" [exact|contains] [<id>]
                            assert the text is NOT on the current screen (no scroll);
                            with an id, NOT in that element, which has to be on screen
  yukti assert-not-id "<id>"
                            assert no element with this id is on the current screen

  flow steps: wait · waitFor · waitForId · waitForNotText · waitForNotId · screenshot · tap · tapText · optionalTapText · tapId · scroll · swipe · scrollToText · scrollToId · dismiss · type · clearText · clearTextId · pressKey · hideKeyboard · assertText · assertId · assertNotText · assertNotId · assertBox · assertBoxId · assertCount · assertCountId · turnWheel · swipeId · swipeText · launch · stopApp · clearState · background · foreground · relaunch · openUrl · setPermission · fixture · include
              (clearText · clearTextId · pressKey · hideKeyboard · assertBox · assertBoxId: measured on Android, iOS not yet run;
               hideKeyboard's Back-first order on Android not yet run either;
              swipe and a share of the screen: not yet run on either platform)
              stopApp force-stops the app, clearState wipes its data (Android only); both take the variant name
              background sends the app of \$YUKTI_VARIANT to the home screen for "value" seconds (0 when none) and
              leaves it there; foreground brings it back and fails when it returns as a new process; relaunch
              stops it and starts it again with its data kept. Each checks which app is in front afterwards
              setPermission sets one permission of the app of \$YUKTI_VARIANT before it starts: "value" is
              notifications, camera, microphone, location, photos, contacts, calendar, motion, reminders,
              health, or an Android name with a dot; "state" is granted, denied or unset. A permission the
              platform does not have skips the rest of the flow with the reason
              openUrl takes the key of a screen, not an address: the address is the variant's "urlBase" plus the key
              (or plus its path from a "urls" table), so a flow says where to go and never in which environment.
              Cheaper than a restart and it resets every tab, but it promises delivery only - an address the app does
              not route still answers ok, and the app navigates after the step returns, so the step after it is
              waitFor / waitForId, not an assert
              tapId takes "at": {"x":"50%","y":"50%"} - a point inside the element as whole shares of its width and
              height from its left and top edge, either left out stays at the centre (a slider stop on the track)
              assertText matches the whole label as written; "match":"contains" asks for a substring
              tapText, optionalTapText, tapId, clearTextId, assertText, assertId, assertBox, assertBoxId,
              waitFor and waitForId take "index": which of several matches, from 0, counted top to bottom,
              then left to right ("index": 1 is the second). Only the matches that match as closely as the
              best one count - for tapText a caption next to a button matches less closely than the button;
              past the last match the step stops and says how many matched (optionalTapText skips).
              With "in" the index counts inside that element. tapText with an index does not scroll
              assertCount (text, takes "match") and assertCountId count the matches on the screen and
              compare: "op": "atLeast", "exact" or "atMost", "count": a whole number; the number found
              is in the line and in the report either way; both take "in": "<id>" to count inside one element
              assertText, assertNotText, waitFor, assertCount and assertCountId take "in": "<id>" - only the element tapId would tap
              and what lies within its bounds count; that element missing fails as "no element with id ... (named by "in")",
              with its frame when it is in the tree at zero size or outside the screen
              tapText takes "in" too: a link inside a longer text is tapped on its own element, found inside
              the one named by id by its whole words; one read, no scroll, no "timeout"; words that are only
              part of a longer text fail by name
              type takes "shows": the text a field that filters its input holds once the value is typed
              ("value":"12a!","shows":"12" in a digits-only field); the read-back and its retries check that
              assertId and waitForId take "selected", "checked" and "expanded" (true or false): the element found by the id has
              to be in that state - waitForId waits for it; a "checked" asked of an element that is not checkable fails
              by name; "expanded" is read on Android from the actions of the node, through the screen helper only,
              and on iOS false is the absence of the word "expanded" in the value, which an element without the state passes too
              waitFor polls for an element and fails on timeout ("timeout": seconds, default 10); it never scrolls.
              waitForId names on timeout which case it ended in: not in the tree, at zero size, or outside the screen;
              "optional": true on it skips the step on timeout instead of failing the flow, with those words
              tap and clearText take "x" and "y" as pixels (200), scaled from the recording screen, or a share of the
              screen ("50%"), taken of the screen the run is on and never scaled; swipe takes "x", "y", "toX", "toY"
              the same way and moves at the speed scroll does, with a set duration on both platforms
              scroll takes up, down, left or right as its "value"; scrollToText takes the same four as "direction"
              (default down) and "edges":"clear" to land the element away from the band edges, failing if it cannot;
              at the end of the list it waits for the list to grow ("timeout": seconds, default 5) before it fails
              scrollToId is the same search with the element found by its id instead of its label (#181)
              swipeId / swipeText swipe across one element to show what it hides (a row's delete): "direction"
              is where the finger goes - left reveals actions on the right, the other way round from scroll;
              the stroke is 60% of the element on the screen (YUKTI_SWIPE_SHARE, 1-90), centred on it; neither scrolls;
              swipeText takes what tapText would tap, often the label inside a row - for a row, swipeId (iOS not yet run)
              assertNotText / assertNotId state that something is NOT on the screen as it is now; they never scroll
              waitForNotText / waitForNotId poll until it is gone ("timeout": seconds, default 10) and fail when it is
              still there; an unreadable screen is never taken for gone - at the timeout it fails as unreadable
              any step, and an include, may carry "when": {"visible"|"notVisible"|"visibleId"|"notVisibleId"|"zeroSizeId"|"platform"} -
              all the conditions in one "when" have to hold; the step is skipped when they do not, and the run stops when
              they cannot be answered (unreadable screen, unknown platform). A skipped step is in the report as skipped
              include runs another flow file here as a block, path relative to the including file; "with" passes values into it,
              its steps are ordinary steps in the report, and nesting stops at a block inside a block;
              "when" on an include is answered once and covers the whole block
              a flow file may carry "prepare" and "teardown", lists of {"fixture": name, "with": body, "bind": {VAR: field}}:
              each a POST to the "fixtures" url of the config, the secret from the variable its "secret" names; a
              preparation that fails skips the flow as blocked:, the teardown runs whatever the outcome. The step
              fixture calls one in the middle of a flow (no bind)
  config: \$YUKTI_CONFIG or ./yukti.config.json  ·  cross-platform: set variant "platform":"android"
EOF
}

# One directory per run for anything measured from the device, made here and
# removed on the way out. Nested calls - the agent shelling out to `yukti tap`,
# Studio driving a flow - inherit it and share the measurement; only the shell
# that made it removes it, so a child cannot pull the floor out from under its
# parent. The alternative, naming the cache after the device, cannot tell two
# emulators apart: their serial is the port they took, not the AVD behind it.
if [ -z "${YUKTI_RUN_DIR:-}" ] || [ ! -d "${YUKTI_RUN_DIR:-}" ]; then
  YUKTI_RUN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/yukti-run.XXXXXX" 2>/dev/null || true)"
  export YUKTI_RUN_DIR
  [ -n "$YUKTI_RUN_DIR" ] && RUN_DIR_OWNED=1 || true
fi
# Not exported on purpose: a child PROCESS inherits the directory but never the
# right to delete it. A SUBSHELL is held off by something else - it does inherit
# this flag, and what saves it is that bash does not run an EXIT trap inside a
# subshell. Two different mechanisms: move this cleanup out of the trap into a
# plain call and the second one disappears without a sound.
run_dir_cleanup(){
  [ "${RUN_DIR_OWNED:-}" = 1 ] || return 0
  helper_release || true   # the helper this run started goes with it
  case "${YUKTI_RUN_DIR:-}" in */yukti-run.??????) rm -rf "$YUKTI_RUN_DIR";; esac
  return 0; }
trap run_dir_cleanup EXIT

cmd="${1:-}"; shift || true

# `install` is the one command that takes an option, and it may sit before the
# variant - `yukti install --apk build/app.apk android-qa`. Neither the option
# nor its value is a variant name, so the platform must not be resolved from
# one. Every other command still resolves from its first argument: a command
# that does not parse options must not be handed a variant it will never use,
# or `yukti up --apk x android-qa` would resolve a platform, build a variant
# called "--apk" with the default gradle task, boot a device, and only then
# stop. Refusing an unknown argument at the first step is the cheap failure.
install_variant(){ local a; while [ $# -gt 0 ]; do a="$1"; shift
    case "$a" in
      --apk) shift || true;;
      -*) ;;
      *) printf '%s' "$a"; return;;
    esac
  done; }

# Which platform this run drives is answered once, here, and only for the
# commands that drive something. init, doctor, scan and help touch no device,
# and `flow --check` reads a flow without performing any of it - all of them
# still run where there is no config at all, which is the case in CI.
case "$cmd" in
  flow) case " $* " in *" --check "*) ;; *) resolve_platform;; esac;;
  install) resolve_platform "$(install_variant "$@")";;
  build|pull|launch|up|"stop-app"|stopApp|"clear-state"|clearState) resolve_platform "${1:-}";;
  boot|shot|ui|find|tap|"tap-text"|tapText|scroll|swipe|"scroll-to"|scrollToText|"scroll-to-id"|scrollToId|dismiss|type|clear|assert|"open-url"|openUrl|\
  "tap-id"|tapId|"clear-id"|clearTextId|"assert-id"|assertId|"assert-box"|assertBox|"assert-count"|assertCount|"swipe-id"|swipeId|"swipe-text"|swipeText|"assert-not"|assertNotText|"assert-not-id"|assertNotId|"wait-for"|waitFor|\
  "wait-for-not"|waitForNotText|"wait-for-not-id"|waitForNotId)
    resolve_platform;;
  # init, doctor, scan and help drive nothing, and a command this tool does not
  # know is answered by the dispatcher below - neither is a reason to ask which
  # platform a run is for.
  *) ;;
esac

case "$cmd" in
  doctor) doctor;;
  init) init "$@";;
  scan) scan;;
  build) build "$@";;
  pull) pull_eas "$@";;
  boot) boot;;
  install) install "$@";;
  launch) launch "$@";;
  "stop-app"|stopApp) stop_app "$@";;
  "clear-state"|clearState) clear_state "$@";;
  "open-url"|openUrl) open_url "$@";;
  up) up "$@";;
  flow) flow "$@";;
  shot) shot "$@";;
  ui) ui;;
  helper) helper_cmd "$@";;
  find) find_el "$@";;
  tap) tap_args "$@";;
  # The index and "in" are keys of a flow step, not arguments here: these take
  # the arguments they took before them (#46, #146).
  "tap-text"|tapText) tap_text "${@:1:2}";;
  scroll) scroll_step "$@";;
  swipe) swipe_args "$@";;
  "scroll-to"|scrollToText) scroll_to_step "${1:-}" "${2:-down}" "${3:-}" "${4:-$SCROLL_GROW_WAIT}";;
  "scroll-to-id"|scrollToId) scroll_to_step "${1:-}" "${2:-down}" "${3:-}" "${4:-$SCROLL_GROW_WAIT}" id;;
  dismiss) dismiss;;
  type) type_str "$@";;
  clear) clear_args "$@";;
  assert) assert_text "${@:1:3}";;
  # The shares as the flow writes them, "50%", and only so: a bare 50 is refused
  # as the builder refuses it - it reads as pixels. The sign is dropped here.
  "tap-id"|tapId) for a in "${2:-}" "${3:-}"; do case "$a" in ''|*%) ;; *) die "tapId: a point is a whole share of the element written with %, for instance 50%, got '$a'";; esac; done
    a2="${2:-}"; a3="${3:-}"; tap_id "${1:-}" "${a2%\%}" "${a3%\%}";;
  "clear-id"|clearTextId) clear_id "${@:1:1}";;
  "assert-id"|assertId) assert_id "${@:1:2}";;
  "assert-box"|assertBox) assert_box_args "$@";;
  "swipe-id"|swipeId) swipe_el "${1:-}" id "${2:-}";;
  "swipe-text"|swipeText) swipe_el "${1:-}" text "${2:-}";;
  "assert-count"|assertCount) assert_count "$@";;
  "assert-not"|assertNotText) assert_not_text "$@";;
  "assert-not-id"|assertNotId) assert_not_id "$@";;
  "wait-for"|waitFor) wait_for "${@:1:7}";;
  "wait-for-not"|waitForNotText) wait_gone "${1:-}" "${2:-10}" "${3:-exact}" assert;;
  "wait-for-not-id"|waitForNotId) wait_gone "${1:-}" "${2:-10}" exact id;;
  ""|-h|--help|help) usage;;
  *) die "unknown command '$cmd' — see 'yukti help'";;
esac
