#!/usr/bin/env python3
# summary: List and manage the computers in your fleet.
# verb-help: start status sync log recovery-code recover
"""starchaser fleet: list and manage the computers in your fleet.

The fleet includes all your computers. Manage them in Mission Control.
To pair with or join another Starchaser computer from the terminal, run: starchaser link pair|join ADDRESS

Common commands
  list                             show the fleet as JSON (also used when no command is given)
  add --address A [--user U] [--port P] [--label L]
                                   record a computer's address for Mission Control
                                   (the computer isn't contacted)
  rename <id> <label>              change a computer's name ("" uses its own name again)
  remove <id> [--lost]             remove a computer from the whole fleet;
                                   --lost also removes its access without contacting it
  set-address <id> <address>       change the address used to reach a computer
  sync                             share the latest fleet list with the other computers now
  doctor                           check why other computers cannot see this one

Use a computer's id from list. Run starchaser fleet COMMAND --help for all its options.
Commands print JSON, a text format used by apps and scripts.

Advanced
  start                            start a new fleet on this computer
  settings-sync                    share settings you follow with the other computers now
  merge <keep-id> <drop-id>        combine two entries for the same computer
  manage-request <id>              ask a computer to allow management from Mission Control
  manage-consent on|off            allow or stop fleet management of this computer
  share-prompts on|off             share AI prompt text with the fleet (off by default)
  fleet-trust only-mine-manages|ask-both-ways|ask-once-for-fleet on|off
                                   change who can manage computers and when to ask permission
  update-address <id> <address>    save an automatically found address
  update <id> [options]            save details found about a computer
  forget-device <device-id>        remove a Starchaser computer and its access, using its device id
  manage-state <id> <state>        save this account's Mission Control connection status
  manage-key                       create this account's sign-in key if needed
  authkeys add|remove|list --tag T [--key K]
                                   manage saved remote sign-in keys
  run-managed -- <cmd> [args]      run a command only while fleet management is allowed (exit 4 otherwise)
  relay-keys                       update sign-in keys on computers added by address
  migrate                          convert an older fleet list (also done automatically)
  fleet-access <id> [all|mine]     which computers manage a computer added by address: every fleet computer
                                   (all) or only this one (mine); with no choice, show the current answer
  stop                             undo start while no other computer has joined

The list (schema version 2, ~/.config/starchaser/fleet.json; docs/fleet.md has the whole contract)
  {"version": 2, "self": {"id": "dev-<this device id>"}, "fleet": {"tag": "<8 hex>", "born", "lone"},   (display only;
                                  a joining computer takes the fleet's tag; two fleets keep the older one)
   "machines": [entry...],        never this computer; screens put "This computer" first themselves
   "removed": [tombstone...],     removed computers, kept so a removal wins everywhere and nothing comes back
   "suggestions": [{"keep", "drop", "why"}],   possible duplicates nobody proved are the same computer
   "local": {...}}                this computer's own settings, never sent to other computers

  entry: id ("dev-<16 hex>" for a Starchaser computer, "m-<12 hex>" otherwise; never changes), label, hostname,
         kind, os {id, label}, starchaser, addresses {last, lan[], mdns, tailscale}, chosenAddress, user, port,
         link {device, key, hostKeys[], paired} or null, managePub, manageable, managers[], macs[],
         checkedHostKeys[] (an m- entry: the host keys a person confirmed by fingerprint),
         addedVia, added, aliases[], gen, rev, by, frev, fby, updated,
         vouch[] (the paths it reached this computer by; see "who vouches for an entry" below the helpers),
         manage {state, since} and desktop {...} (this computer only),
         name and ip (the label and best address, for readers of the old list; never read them back)

How the list stays the same everywhere
  Each computer keeps the whole list. A change on one is sent to every computer it is paired with over the paired
  link (starchaser link's forced-command key, verb fleet-sync), and each one that learned something new passes it on,
  so a computer that is only paired with one other still hears everything. A computer that was off catches up the
  next time it exchanges the list (at start and every 10 minutes, from either side).
  Conflicts resolve the same way on every computer, whatever order changes arrive in:
    gen    goes up when a removed computer is added again. A higher gen wins over everything with a lower one.
    a removal at the same gen wins over any change to the entry, so an edit made by a computer that hadn't heard
           of the removal yet can't bring it back
    rev    counts changes someone chose (label, typed address, user, port); the higher one wins, then the writer's id
    frev   counts changes to facts a computer reports about itself or a probe found (hostname, addresses, OS,
           host keys); kept apart from rev, so a new address never undoes a rename made at the same time
  The link key and the host key the code verified change only by pairing again (a new gen), and a computer's own
  entry is only ever taken from the computers that paired it, never from itself.
  A removed (or lost) computer is refused: its fleet-sync is answered "removed" and its key is dropped, and an
  entry is only trusted again when someone adds it again on purpose (pairing it with the code).

Python API (load this file with importlib, as starchaser link does; every write takes the lock)
  load() -> doc                       read (and convert or absorb an older writer's change); never None
  get(id) -> entry | None             a live entry by id or alias
  self_id() -> "dev-..."              this computer's id
  add_machine(address, user, port, label, via, os_label, os_id) -> entry
  upsert_paired(peer, address, via)   pairing finished (starchaser link remember)
  observe(id, facts, by)              facts a status call or probe found
  rename(id, label), set_address(id, address), manage_state(id, state), merge_pair(keep, drop)
  tombstone(id, revoked) -> tombstone record (local only; remove_flow() does the network part)
  payload(self_facts) -> dict         what fleet-sync sends
  merge_in(payload, sender) -> bool   what fleet-sync received; raises Refused for a removed sender
  is_removed(device_id) -> bool
  reconcile(link)                     make keys, pinned host keys and paired devices match the list
  authkeys(op, tag, key)              locked ~/.ssh/authorized_keys edits
"""
import argparse
import base64
import contextlib
import fcntl
import hashlib
import ipaddress
import json
import os
import pwd
import re
import secrets
import shlex
import signal
import socket
import stat
import subprocess
import sys
import tempfile
import threading
import time
import unicodedata
import uuid
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import CommandParser, safe_streams
from starchaser_system_defaults import tool_path

safe_streams()

HOME = Path.home()
CONF = HOME / ".config/starchaser"
FLEET = CONF / "fleet.json"
STATE_DIR = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser"
LOCK = STATE_DIR / "fleet.lock"
SSH_LOCK = STATE_DIR / "ssh-files.lock"         # ~/.ssh/authorized_keys and known_hosts: link, the fleet and Mission Control
DEVICES = HOME / ".local/share/starchaser/devices"
IDFILE = DEVICES / "device-id"
PEERS = DEVICES / "peers.json"
SSH_DIR = HOME / ".ssh"
AUTH = SSH_DIR / "authorized_keys"
KNOWN_HOSTS = SSH_DIR / "known_hosts"
ME = pwd.getpwuid(os.getuid()).pw_name
VERSION = 2
MAX_COUNTER = 2 ** 31                          # gen / rev / frev: larger is not a real count (and would pin a winner)
MAX_REMOVED = 500
MANAGE_TAG = "starchaser-manage:"               # authorized_keys: a fleet computer's personal key (full sign-in)
HOSTS_TAG = "starchaser-fleet:"                 # known_hosts: host keys the fleet verified
MC_HOSTS_TAG = "starchaser-mc:"                 # Mission Control's pin for a computer that isn't a paired one
MANAGE_STATES = ("ready", "asked", "declined", "needs-key", "needs-bridge", "none", "unknown")
VIAS = ("pairing", "mission-control", "welcome", "procedure", "migrated", "fleet")
LOCAL_KEYS = ("manage", "desktop", "name", "ip")   # per computer: never sent, never taken from another computer
FACT_KEYS = ("hostname", "kind", "os", "starchaser", "addresses", "macs", "managePub", "manageable", "managers",
             "checkedHostKeys", "recovery")
PERSON_KEYS = ("label", "chosenAddress", "user", "port", "link", "addedVia", "addedBy", "onlyMineManages", "fleetAccess",
               "added", "aliases", "helpOwner")
# An m- machine's fleetAccess, the person's answer when it was added (decision 2026-10-19 #16): "all" = every fleet
# computer gets its key there (and ones that join later); "mine" = only the computer that added it; "ask" = no answer
# yet, so only the adding computer, until the person says OK. "" = added before the question existed (the password
# sign-in was the OK then): it follows onlyMineManages, as before.
FLEET_ACCESS = ("all", "mine", "ask")
TRUST_OPTIONS = {"only-mine-manages": "onlyMineManages", "ask-both-ways": "askBothWays", "ask-once-for-fleet": "askOnceForFleet"}
NO_SPAWN = os.environ.get("STARCHASER_FLEET_NO_SPAWN") == "1"   # tests: never start a background sync

ID_RE = re.compile(r"dev-[0-9a-f]{16}|m-[0-9a-f]{12}")
DEV_RE = re.compile(r"[0-9a-f]{16}")
USER_RE = re.compile(r"[a-z_][a-z0-9_-]{0,31}")
HOST_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?")
KEY_RE = re.compile(r"(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)) [A-Za-z0-9+/]+={0,3}")
MAC_RE = re.compile(r"([0-9a-f]{2}:){5}[0-9a-f]{2}")
ALIAS_RE = re.compile(r"[\w-]{1,64}")
TAG_RE = re.compile(r"[0-9a-f]{8}")                   # the fleet's tag (display only: which nearby computers share a fleet)
RELAY_STATE = STATE_DIR / "relay.json"           # when this computer last tried to pass keys on to each machine
# Fleet v2 (docs/fleet/rules.md 36.4): once this computer applies a fleet state, the fleet service writes this file, and
# from then on the personal manage keys, relay-keys, manage consent and trust switches here are retired: the signed key
# list replaces them, and both never run side by side.
MOVED = Path(os.environ.get("STARCHASER_FLEET_MOVED_FILE") or "/etc/starchaser/fleet/moved.json")
FLEET_KNOWN = Path(os.environ.get("STARCHASER_FLEET_KNOWN_FILE") or "/etc/starchaser/fleet/ssh/known_hosts")
MOVED_TEXT = ("This computer moved to fleet accounts: your fleet's rules and SSH keys decide this now. "
              "See starchaser fleet list rules and starchaser fleet list keys.")

# Names that never reach the screen (the upstream web console's, the two big desktops', one distribution's), spelled
# with character classes so this file never contains them.
_DISTRO = re.compile(r"\bc[a]chy\s?os\b", re.I)
_DESKTOP_PAREN = re.compile(r"\s*\((?:[^()]*\b(?:[K]DE|[G]NOME|[K]\s?Plasma)\b[^()]*)\)", re.I)
_ANY_LEFT = re.compile(r"\b(?:c[o]ckpit|[G]NOME|[K]DE|c[a]chy\s?os)\b", re.I)


class Refused(Exception):
    """A fleet-sync from a computer that was removed from the fleet."""


# ---------------------------------------------------------------------------------------------- small helpers
def scrub(text) -> str:
    s = _DISTRO.sub("Arch-based Linux", str(text or ""))
    s = _DESKTOP_PAREN.sub("", s)
    return _ANY_LEFT.sub("", s).strip()


def safe_label(name, limit: int = 60) -> str:
    s = "".join(c for c in str(name or "") if not unicodedata.category(c).startswith("C"))
    return s.strip()[:limit].strip()


def valid_ip(a) -> bool:
    if not isinstance(a, str) or not a or len(a) > 64:
        return False
    try:
        ipaddress.ip_address(a)
        return True
    except ValueError:
        return False


def valid_host(a) -> bool:
    """An address to reach a computer at: an IP address or a host name (never starting with "-")."""
    return valid_ip(a) or (isinstance(a, str) and bool(HOST_RE.fullmatch(a)))


def counter(v) -> int:
    return v if isinstance(v, int) and not isinstance(v, bool) and 0 <= v < MAX_COUNTER else 0


def moved() -> bool:
    """Rule 36.4: has this computer moved to fleet v2's accounts? Then today's manage keys are retired here."""
    try:
        return isinstance(json.loads(MOVED.read_bytes()).get("time"), int)
    except (OSError, ValueError, AttributeError):
        return False


def fleet_known_keys() -> set:
    """The host keys fleet v2's signed list covers (rule 36.4: today's known_hosts lines for them go)."""
    try:
        return {" ".join(line.split()[1:3]) for line in FLEET_KNOWN.read_text().splitlines()
                if line.strip() and not line.startswith(("#", "@"))}
    except OSError:
        return set()


def manage_consent_on() -> bool:
    """Does this computer, right now, let the fleet manage it? Read fresh from disk every time (a Mission Control
    session that was already open when consent went off must not keep working), and False on anything unreadable.
    Retired, so always False, once this computer moved to fleet accounts (rule 36.4)."""
    if moved():
        return False
    try:
        local = json.loads(FLEET.read_bytes()).get("local")
        return isinstance(local, dict) and local.get("manageConsent") is True and not local.get("left")
    except (OSError, ValueError, AttributeError):
        return False


NOT_ALLOWED = ("This computer isn't letting your fleet manage it. To allow it, open Settings here, choose Fleet, "
               "and turn on Let your fleet manage this computer.")


def run_managed(job: list) -> int:
    """The one door every Mission Control job on a managed computer goes through. Consent is read fresh from disk
    each time (failing closed), so turning it off stops the next job even in a session that was already open. Off:
    nothing runs, exit 4 and the plain words. On: the job replaces this process (same input, output and exit
    status)."""
    if job and job[0] == "--":
        job = job[1:]
    if not job:
        print("starchaser fleet: run-managed needs a command after --", file=sys.stderr)
        return 2
    if not manage_consent_on():
        print(NOT_ALLOWED, file=sys.stderr)
        return 4
    try:
        os.execvp(job[0], job)
    except OSError as e:
        print(f"starchaser fleet: can't run {job[0]}: {e.strerror or e}", file=sys.stderr)
        return 127


def settings_context() -> dict:
    """Read-only membership for the settings engine; never migrate, repair, or create an identity.

    Settings must fail closed when the list or paired accounts cannot be read. Keep these reads in the
    registry owner so the settings engine cannot grow its own interpretation of the on-disk list.
    """
    from starchaser_settings_schema import DEVICE, loads, require

    doc = loads(FLEET.read_bytes(), limit=4 * 1024 * 1024)
    peers = loads(PEERS.read_bytes(), limit=4 * 1024 * 1024)
    identity = IDFILE.read_text().strip()
    require(bool(DEV_RE.fullmatch(identity)))
    me = "dev-" + identity
    require(isinstance(doc, dict) and doc.get("version") == VERSION and doc.get("self") == {"id": me})
    require(isinstance(doc.get("machines"), list) and isinstance(doc.get("removed"), list) and isinstance(peers, list))
    removed = {}
    for entry in doc["removed"]:
        require(isinstance(entry, dict) and isinstance(entry.get("id"), str))
        require(type(entry.get("gen")) is int and 0 <= entry["gen"] < MAX_COUNTER)
        removed[entry["id"]] = max(removed.get(entry["id"], -1), entry["gen"])
    accounts = {}
    for peer in peers:
        require(isinstance(peer, dict) and isinstance(peer.get("id"), str) and isinstance(peer.get("user"), str))
        require(bool(DEV_RE.fullmatch(peer["id"])))
        require(peer["id"] not in accounts)
        accounts[peer["id"]] = peer["user"]
    local = doc.get("local") if isinstance(doc.get("local"), dict) else {}
    writers, paired, seen = {me}, set(), set()
    if local.get("left"):
        # This computer was removed from the fleet: nothing from the old members applies here any more.
        return {"self": me, "user": ME, "writers": writers, "paired": paired}
    for entry in doc["machines"]:
        require(isinstance(entry, dict) and isinstance(entry.get("id"), str) and entry["id"] not in seen)
        seen.add(entry["id"])
        require(type(entry.get("gen")) is int and 0 <= entry["gen"] < MAX_COUNTER)
        if not DEVICE.fullmatch(entry["id"]) or removed.get(entry["id"], -1) >= entry["gen"]:
            continue
        require(isinstance(entry.get("user"), str))
        if entry["user"] != ME:
            continue
        writers.add(entry["id"])
        link = entry.get("link")
        if isinstance(link, dict) and link.get("paired") and accounts.get(entry["id"][4:]) == ME:
            paired.add(entry["id"])
    return {"self": me, "user": ME, "writers": writers, "paired": paired}


def now() -> int:
    return int(time.time())


def sh(*cmd, timeout=10, input=None) -> subprocess.CompletedProcess:
    if NO_SPAWN and cmd[:2] == ("loginctl", "terminate-session"):
        return subprocess.CompletedProcess(cmd, 1, "", "Session control disabled in test mode")
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, input=input)
    except subprocess.TimeoutExpired:
        return subprocess.CompletedProcess(cmd, 124, "", "timed out")
    except OSError as e:
        return subprocess.CompletedProcess(cmd, 1, "", str(e))


def write_atomic(path: Path, text: str, mode: int | None = None) -> None:
    """A temp file next to it with a name of its own, fsync, then rename over it: a reader never sees half a file."""
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode if mode is not None else 0o644)
    try:
        with os.fdopen(fd, "w") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        if mode is not None:
            os.chmod(tmp, mode)
        tmp.replace(path)
    except BaseException:
        with contextlib.suppress(OSError):
            tmp.unlink()
        raise


_HELD = threading.local()


@contextlib.contextmanager
def _flock(path: Path, name: str):
    """One writer at a time across processes (flock) and threads; taken again by the same thread, it's held already.
    Never held across a network call."""
    depth = getattr(_HELD, name, 0)
    if depth:
        setattr(_HELD, name, depth + 1)
        try:
            yield
        finally:
            setattr(_HELD, name, getattr(_HELD, name) - 1)
        return
    path.parent.mkdir(parents=True, exist_ok=True)
    fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX)
        setattr(_HELD, name, 1)
        try:
            yield
        finally:
            setattr(_HELD, name, 0)
    finally:
        os.close(fd)


def fleet_lock():
    return _flock(LOCK, "fleet")


def ssh_lock():
    return _flock(SSH_LOCK, "ssh")


def device_id() -> str:
    """This computer's link device id (starchaser link makes the same file the same way)."""
    try:
        d = IDFILE.read_text().strip()
        if DEV_RE.fullmatch(d):
            return d
    except OSError:
        pass
    DEVICES.mkdir(parents=True, exist_ok=True)
    d = uuid.uuid4().hex[:16]
    try:
        fd = os.open(IDFILE, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "w") as f:
            f.write(d + "\n")
    except FileExistsError:
        return IDFILE.read_text().strip()
    return d


def self_id() -> str:
    return "dev-" + device_id()


def new_machine_id() -> str:
    return "m-" + secrets.token_hex(6)


def v1_machine_id(ip: str, name: str, user: str, port: int) -> str:
    """The id an old-list entry without one gets: worked out from what the old list says about it, so every computer
    that converts the same old list gives the machine the same id (a random one here would add it to the fleet a
    second time when this computer's list meets the others')."""
    text = json.dumps(["v1", ip.strip().lower(), (name or "").strip().lower(), user or "", port], separators=(",", ":"))
    return "m-" + hashlib.sha256(text.encode()).hexdigest()[:12]


# ---------------------------------------------------------------------------------------------- one entry
def clean_addresses(a) -> dict:
    a = a if isinstance(a, dict) else {}
    lan = [x for x in (a.get("lan") or []) if valid_ip(x)][:8] if isinstance(a.get("lan"), list) else []
    return {"last": a.get("last") if valid_host(a.get("last")) else "",
            "lan": list(dict.fromkeys(lan)),
            "mdns": a.get("mdns") if valid_host(a.get("mdns")) else "",
            "tailscale": a.get("tailscale") if valid_ip(a.get("tailscale")) else ""}


def clean_keys(keys, limit: int = 6) -> list:
    out = []
    for k in keys if isinstance(keys, list) else []:
        if isinstance(k, str):
            k = " ".join(k.split()[:2])
            if KEY_RE.fullmatch(k) and k not in out:
                out.append(k)
    return out[:limit]


def clean_link(link):
    if not isinstance(link, dict) or not DEV_RE.fullmatch(str(link.get("device", ""))):
        return None
    key = " ".join(str(link.get("key") or "").split()[:2])
    out = {"device": link["device"], "key": key if re.fullmatch(r"ssh-ed25519 [A-Za-z0-9+/]+={0,3}", key) else "",
           "hostKeys": clean_keys(link.get("hostKeys"))}
    if isinstance(link.get("paired"), int):
        out["paired"] = link["paired"]
    return out


def clean_entry(e) -> dict | None:
    """An entry in the shape this version writes, with every value checked (entries come from other computers and
    from older writers). None when it isn't one."""
    if not isinstance(e, dict) or not isinstance(e.get("id"), str) or not ID_RE.fullmatch(e["id"]):
        return None
    os_ = e.get("os") if isinstance(e.get("os"), dict) else {}
    link = clean_link(e.get("link"))
    if e["id"].startswith("dev-") and (not link or link["device"] != e["id"][4:]):
        return None                                     # a Starchaser entry is its link device, always
    if e["id"].startswith("m-"):
        link = None
    pub = " ".join(str(e.get("managePub") or "").split()[:2])
    out = {
        "id": e["id"],
        "label": safe_label(e.get("label")),
        "hostname": e.get("hostname") if isinstance(e.get("hostname"), str) and HOST_RE.fullmatch(e["hostname"]) else "",
        "kind": e.get("kind") if isinstance(e.get("kind"), str) and re.fullmatch(r"[a-z-]{1,20}", e["kind"]) else "",
        "os": {"id": os_.get("id") if isinstance(os_.get("id"), str) and re.fullmatch(r"[a-z0-9._-]{1,32}", os_["id"]) else "",
               "label": scrub(safe_label(os_.get("label")))},
        "starchaser": bool(e.get("starchaser")) or link is not None,
        "addresses": clean_addresses(e.get("addresses")),
        "chosenAddress": e.get("chosenAddress") if valid_host(e.get("chosenAddress")) else "",
        "user": e.get("user") if isinstance(e.get("user"), str) and USER_RE.fullmatch(e["user"]) else "",
        "port": e.get("port") if isinstance(e.get("port"), int) and 1 <= e["port"] <= 65535 else 22,
        "link": link,
        "managePub": pub if KEY_RE.fullmatch(pub) else "",
        "manageable": bool(e.get("manageable")),
        "managers": sorted({m for m in (e.get("managers") or []) if isinstance(m, str) and DEV_RE.fullmatch(m)})[:64]
        if isinstance(e.get("managers"), list) else [],
        # a computer that isn't a paired Starchaser one: the host keys a person checked by their fingerprint (Mission
        # Control's Add a machine), so every computer in the fleet knows it without asking again (a paired one's are in
        # link.hostKeys, verified by the code)
        "checkedHostKeys": clean_keys(e.get("checkedHostKeys")) if e["id"].startswith("m-") else [],
        "macs": list(dict.fromkeys(m.lower() for m in (e.get("macs") or []) if isinstance(m, str) and MAC_RE.fullmatch(m.lower())))[:8]
        if isinstance(e.get("macs"), list) else [],
        "addedVia": e.get("addedVia") if e.get("addedVia") in VIAS else "migrated",
        "addedBy": e.get("addedBy") if isinstance(e.get("addedBy"), str) and DEV_RE.fullmatch(e["addedBy"]) else "",
        "helpOwner": e.get("helpOwner") if DEV_RE.fullmatch(str(e.get("helpOwner", ""))) else "",
        "onlyMineManages": e.get("onlyMineManages") is True,
        "fleetAccess": e.get("fleetAccess") if e["id"].startswith("m-") and e.get("fleetAccess") in FLEET_ACCESS else "",
        "added": counter(e.get("added")) or 0,
        "aliases": [a for a in (e.get("aliases") or []) if isinstance(a, str) and ALIAS_RE.fullmatch(a)][:8]
        if isinstance(e.get("aliases"), list) else [],
        "gen": counter(e.get("gen")), "rev": counter(e.get("rev")), "frev": counter(e.get("frev")),
        "by": e.get("by") if isinstance(e.get("by"), str) and DEV_RE.fullmatch(e["by"]) else "",
        "fby": e.get("fby") if isinstance(e.get("fby"), str) and DEV_RE.fullmatch(e["fby"]) else "",
        "updated": counter(e.get("updated")),
        # who vouches for it here: the paths it reached this computer by (vouch_chains; [] = checked here, by its code
        # or by the person). An entry written before there were paths counts as checked here.
        "vouch": clean_vouch(e.get("vouch")) if "vouch" in e else [[]],
    }
    m = e.get("manage") if isinstance(e.get("manage"), dict) else {}
    out["manage"] = {"state": m.get("state") if m.get("state") in MANAGE_STATES else "none", "since": counter(m.get("since"))}
    if isinstance(e.get("desktop"), dict):
        d = e["desktop"]
        out["desktop"] = {"sunshine": d.get("sunshine") if d.get("sunshine") in ("unknown", "ready", "absent") else "unknown",
                          "moonlightPaired": bool(d.get("moonlightPaired"))}
    recovery = e.get("recovery")
    if isinstance(recovery, dict) and link and recovery.get("target") == link["device"] and re.fullmatch(r"[0-9a-f]{64}", str(recovery.get("enrollment", ""))):
        out["recovery"] = {"target": recovery["target"], "enrollment": recovery["enrollment"], "allowErase": recovery.get("allowErase") is True,
                           "allowed": [x for x in recovery.get("allowed", []) if isinstance(x, str) and DEV_RE.fullmatch(x)][:64] if isinstance(recovery.get("allowed"), list) else []}
    return with_compat(out)


def clean_tombstone(t) -> dict | None:
    if not isinstance(t, dict) or not isinstance(t.get("id"), str) or not ID_RE.fullmatch(t["id"]):
        return None
    pub = " ".join(str(t.get("managePub") or "").split()[:2])
    out = {"id": t["id"], "gen": counter(t.get("gen")), "rev": counter(t.get("rev")),
            "by": t.get("by") if isinstance(t.get("by"), str) and DEV_RE.fullmatch(t["by"]) else "",
            "removed": counter(t.get("removed")), "revoked": bool(t.get("revoked")),
            "label": safe_label(t.get("label")),
            # its personal key, so the computers that pass keys on can take it off machines that aren't paired ones
            "managePub": pub if KEY_RE.fullmatch(pub) else "",
            "aliases": [a for a in (t.get("aliases") or []) if isinstance(a, str) and ALIAS_RE.fullmatch(a)][:8]
            if isinstance(t.get("aliases"), list) else []}

    request = t.get("recovery")
    if isinstance(request, dict) and isinstance(request.get("signature"), str) and len(request["signature"]) <= 8192:
        try:
            body = recovery_client().core().validate_body(request.get("body"))
            if t["id"] == "dev-" + body["target"]:
                out["recovery"] = {"body": dict(body), "signature": request["signature"]}
        except ValueError:
            pass
    return out



# ---------------------------------------------------------------------------------------------- who vouches for an entry
# Signed introductions prove modern membership independently of the delivery path. Legacy unsigned entries keep
# the authenticated relays they came through; a path through any removed device stops counting. The second hop
# field is retained for compatibility, but timestamps never decide trust. A signed introduction survives its
# sponsor's removal only if that exact proof was known when the removal was signed.
VOUCH_MAX, VOUCH_LEN = 16, 8


def clean_vouch(v) -> list:
    if not isinstance(v, list):
        return []
    out = []
    for c in v[:32]:
        if not isinstance(c, list) or len(c) > VOUCH_LEN:
            continue
        if all(isinstance(h, list) and len(h) == 2 and isinstance(h[0], str) and DEV_RE.fullmatch(h[0]) for h in c):
            out.append([[h[0], counter(h[1])] for h in c])
    return merge_chains([], out)


def merge_chains(old: list, new: list) -> list:
    """The paths of both, one per run of computers (the lowest stored count at each step), the shortest first. The same
    paths give the same result, so passing them back and forth settles."""
    best = {}
    for c in list(old) + list(new):
        k = tuple(h[0] for h in c)
        best[k] = [[d, min(a[1], b[1])] for d, a, b in zip(k, best[k], c)] if k in best else [list(h) for h in c]
    return [best[k] for k in sorted(best, key=lambda k: (len(k), k))[:VOUCH_MAX]]


def _chain_ok(chain: list, eid: str, me: str, gone: dict, dropped: set) -> bool:
    devs = [h[0] for h in chain]
    if me[4:] in devs or (eid.startswith("dev-") and eid[4:] in devs):
        return False                                    # back through this computer, or vouching for itself
    for d, _count in chain:
        if d in dropped or d in gone:
            return False                                # an unsigned path through a removed computer
    return True


def _gone_from(tombs, live_ids) -> dict:
    """Removed devices that have not been added again. Only membership in this mapping decides trust."""
    return {t["id"][4:]: t["gen"] for t in tombs if t["id"].startswith("dev-") and t["id"] not in live_ids}


def _removal_records(doc: dict) -> list:
    return doc["removed"] + [clean_tombstone(r["body"]["value"]["tombstone"])
                              for r in doc["security"]["records"] if r["body"]["kind"] == "remove"]


def _gone(doc: dict) -> dict:
    return _gone_from(_removal_records(doc), {e["id"] for e in doc["machines"]})


def _dropped_devs(doc: dict) -> set:
    return {k[4:] for k in (doc["local"].get("dropped") or {}) if k.startswith("dev-")}


def _vouched(doc: dict, me: str, gone: dict, dset: set) -> dict:
    """Resolve membership outward from code-checked devices and valid signed introductions. An unsigned path
    cannot pass through a removed device or depend only on a circle of devices vouching for each other."""
    live = {e["id"] for e in doc["machines"] if e["id"].startswith("dev-")}
    certified = _security_members(doc)
    byid = {e["id"]: e for e in doc["machines"]}

    def counts(c, eid, good):
        if certified_identity(certified.get(eid), byid.get(eid)):
            return True
        if not _chain_ok(c, eid, me, gone, dset):
            return False
        if not c:
            return True
        d, _count = c[-1]
        return ("dev-" + d) not in live or ("dev-" + d) in good

    good = {}
    grew = True
    while grew:
        grew = False
        for e in doc["machines"]:
            if e["id"] in good:
                continue
            v = e.get("vouch") or []
            ok = [c for c in v if counts(c, e["id"], good)] if v else []
            if ok or not v:                             # (no paths at all: from before there were, as if checked here)
                good[e["id"]] = ok
                grew = True
    byid = {e["id"]: e for e in doc["machines"]}
    return {i: [c for c in byid[i].get("vouch") or [] if counts(c, i, good)] for i in good}


def prune_vouched(doc: dict, me: str) -> list:
    """Drop (in place) every entry that no path vouches for any more (_vouched), again and again (an entry only a
    dropped one passed on goes too). Each is noted in local "dropped", so reconcile takes back every trust in it and
    says so on screen once. Returns the dropped entries."""
    out = []
    rec = doc["local"].setdefault("dropped", {})
    gone = _gone(doc)
    names = {t["id"][4:]: t.get("label") or "" for t in doc["removed"] if t["id"].startswith("dev-")}
    while True:
        dset = _dropped_devs(doc)
        good = _vouched(doc, me, gone, dset)
        drop = [e for e in doc["machines"] if e["id"] not in good]
        for e in doc["machines"]:
            if e["id"] in good and (e.get("vouch") or []) and good[e["id"]] != e["vouch"]:
                e["vouch"] = good[e["id"]]
        if not drop:
            break
        for e in drop:
            v = e.get("vouch") or []
            why = sorted({h[0] for c in v for h in c if h[0] in gone or h[0] in dset})
            doc["machines"].remove(e)
            rec[e["id"]] = {"at": now(), "label": display_name(e), "gen": e.get("gen", 0), "noted": False,
                            "managePub": e.get("managePub") or "",
                            "because": [names.get(d) or (rec.get("dev-" + d) or {}).get("label") or "a removed computer" for d in why]}
            out.append(e)
    if len(rec) > 200:
        doc["local"]["dropped"] = dict(sorted(rec.items(), key=lambda kv: -kv[1].get("at", 0))[:200])
    return out


def best_address(e: dict) -> str:
    a = e.get("addresses") or {}
    for x in [e.get("chosenAddress"), a.get("last")] + list(a.get("lan") or []) + [a.get("mdns"), a.get("tailscale"), e.get("hostname")]:
        if x:
            return x
    return ""


def display_name(e: dict) -> str:
    return e.get("label") or e.get("hostname") or best_address(e) or "A computer"


def with_compat(e: dict) -> dict:
    """name and ip: what readers of the old list (the top panel's Fleet tab, older Mission Control pages, the firewall
    question) read. Written from the real fields every time; a change to them is read as an older writer's edit."""
    e["name"] = display_name(e)
    e["ip"] = best_address(e)
    return e


def strip_local(e: dict) -> dict:
    out = {k: v for k, v in e.items() if k not in LOCAL_KEYS}
    if out.get("link"):
        out["link"] = {k: v for k, v in out["link"].items() if k != "paired"}
    return out


# ---------------------------------------------------------------------------------------------- merging
def _digest(e: dict, keys) -> str:
    return hashlib.sha256(json.dumps({k: e.get(k) for k in keys}, sort_keys=True).encode()).hexdigest()


def _person_key(e):
    # the content's digest last: two versions with the same count and writer (it reported twice while two others
    # passed it on) still pick the same one everywhere
    x = strip_local(e)
    if x.get("link"):
        x["link"] = {k: v for k, v in x["link"].items() if k != "hostKeys"}     # (host keys are facts)
    return (e.get("rev", 0), e.get("by", ""), _digest(x, PERSON_KEYS))


def _facts_key(e):
    hk = (e.get("link") or {}).get("hostKeys")
    return (e.get("frev", 0), e.get("fby", ""), _digest(dict(e, hostKeys=hk), FACT_KEYS + ("hostKeys",)))


def rank(x: dict, tomb: bool) -> tuple:
    """Which version of one computer wins. A higher gen always wins; at the same gen a removal wins over any edit."""
    return (x.get("gen", 0), 1 if tomb else 0)


def merge_live(a: dict, b: dict) -> dict:
    """Two live versions of one entry at the same gen: the chosen fields from the higher rev, the facts from the
    higher frev. a is the local copy: its per-computer fields are kept."""
    person = a if _person_key(a) >= _person_key(b) else b
    facts = a if _facts_key(a) >= _facts_key(b) else b
    out = {k: v for k, v in person.items() if k not in FACT_KEYS}
    for k in FACT_KEYS:
        if k != "recovery" or facts.get(k) is not None:
            out[k] = facts.get(k)
    out["frev"], out["fby"] = facts.get("frev", 0), facts.get("fby", "")
    out["rev"], out["by"] = person.get("rev", 0), person.get("by", "")
    out["updated"] = max(a.get("updated", 0), b.get("updated", 0))
    if person.get("link") and facts.get("link"):
        # host keys are facts the computer reports about itself; the link key is chosen at pairing
        out["link"] = dict(person["link"], hostKeys=facts["link"].get("hostKeys") or person["link"].get("hostKeys") or [])
    if a.get("link") and out.get("link"):
        # The link key and the host key the code verified (the first one) belong to this gen: only pairing again (a
        # new gen) changes them, so no other computer's edit can swap them, however high its count. Honest copies
        # always agree on them, so this never stops the copies from ending up the same.
        pinned = (a["link"].get("hostKeys") or [])[:1]
        out["link"] = dict(out["link"], key=a["link"].get("key", ""),
                           hostKeys=(pinned + [k for k in out["link"].get("hostKeys") or [] if k not in pinned])[:6])
    if a["id"].startswith("m-"):
        # the host keys a person checked: only ever added to by a merge, never replaced (another computer's list can't
        # swap the key this one trusts for a machine; a person checks a new one by its fingerprint, which adds it)
        mine = a.get("checkedHostKeys") or []
        out["checkedHostKeys"] = (mine + [k for k in out.get("checkedHostKeys") or [] if k not in mine])[:6]
    out["vouch"] = a.get("vouch") or []
    for k in LOCAL_KEYS:
        if k in a:
            out[k] = a[k]
    if a.get("link") and out.get("link") and "paired" in a["link"]:
        out["link"]["paired"] = a["link"]["paired"]
    return with_compat(out)


def merge_docs(doc: dict, machines: list, removed: list, me: str, sender: str = "") -> bool:
    """Bring another computer's list into doc (in place). True when anything changed here (only who vouches for an
    entry changing isn't news: it is saved, and passed on with the next exchange). sender: the device id the list came
    from (from the link key it signed in with), the last step of every path it passes on."""
    live = {e["id"]: e for e in doc["machines"]}
    tombs = {t["id"]: t for t in doc["removed"]}
    changed = False
    local = doc["local"]
    for t in removed:
        if t["id"] == me:
            previous = local.get("left") or {}
            if t["gen"] >= local.get("selfGen", 0) and (not previous or (t["gen"], t["rev"], t["by"]) > (previous.get("gen", 0), previous.get("rev", 0), previous.get("by", ""))):
                who = live.get("dev-" + t["by"]) if t.get("by") else None
                local["left"] = {"by": t["by"], "byName": display_name(who) if who else "", "at": now(),
                                 "revoked": t["revoked"], "gen": t["gen"], "rev": t["rev"], "noted": False, **({"recovery": t["recovery"]} if t.get("recovery") else {})}
                local["manageConsent"] = False          # consent was given to that fleet, never to the next one
                changed = True
            continue
        cur_l, cur_t = live.get(t["id"]), tombs.get(t["id"])
        if cur_l:
            if rank(t, True) <= rank(cur_l, False):
                continue                                # it was added again after this removal
            del live[t["id"]]
            changed = True
            if not t.get("managePub") and cur_l.get("managePub"):
                t = dict(t, managePub=cur_l["managePub"])   # (a removal record from an older writer)
        if not cur_t or (t["gen"], t["rev"], t["by"]) > (cur_t["gen"], cur_t["rev"], cur_t["by"]):
            win = dict(t)
            if not win.get("managePub") and cur_t and cur_t.get("managePub"):
                win["managePub"] = cur_t["managePub"]
            if cur_t and cur_t["gen"] == t["gen"]:
                win["revoked"] = t["revoked"] or cur_t["revoked"]     # "lost" sticks, whichever record wins
            tombs[t["id"]] = win
            changed = True
        elif cur_t["gen"] == t["gen"] and t["revoked"] and not cur_t["revoked"]:
            tombs[t["id"]] = dict(cur_t, revoked=True)
            changed = True
    relay_count = 0
    certified = _security_members(doc)
    gone = _gone_from(tombs.values(), set(live))
    dset = _dropped_devs(doc)
    readded = {}
    dropped = local.setdefault("dropped", {})
    vouched = False
    for e in machines:
        if e["id"] == me:
            if e["gen"] > local.get("selfGen", 0):
                local["selfGen"] = e["gen"]
                changed = True
            continue
        t = tombs.get(e["id"])
        if t and rank(t, True) >= rank(e, False):
            continue                                    # removed: an edit from before the removal can't bring it back
        chains = [c + [[sender, relay_count]] for c in e.get("vouch") or []] if sender else list(e.get("vouch") or [])
        chains = [c for c in chains if len(c) <= VOUCH_LEN and (certified_identity(certified.get(e["id"]), e)
                                                                   or _chain_ok(c, e["id"], me, gone, dset))]
        cur = live.get(e["id"])
        if cur is None:
            if not chains:
                continue                                # nobody that still counts vouches for it
            live[e["id"]] = with_compat({**e, "vouch": merge_chains([], chains), "manage": {"state": "none", "since": 0}})
            if t:
                readded[e["id"]] = tombs.pop(e["id"])   # added again on purpose (a higher gen)
            dropped.pop(e["id"], None)
            changed = True
        elif rank(e, False) > rank(cur, False):
            if not chains:
                continue
            new = {**e, "vouch": merge_chains([], chains), **{k: cur[k] for k in LOCAL_KEYS if k in cur}}
            if cur["id"].startswith("m-"):              # (checked host keys are only ever added to)
                mine = cur.get("checkedHostKeys") or []
                new["checkedHostKeys"] = (mine + [k for k in new.get("checkedHostKeys") or [] if k not in mine])[:6]
            live[e["id"]] = with_compat(new)
            changed = True
        elif rank(e, False) < rank(cur, False):
            continue                                    # an older incarnation (before it was paired again)
        else:
            merged = merge_live(cur, e)
            if cur["id"].startswith("dev-") and sender:
                # a Starchaser computer's personal key and host keys come only from that computer itself (its own
                # report, merge_in) or with its pairing (a new gen): a list passed on can't swap or add one, so a
                # removed computer can't slip its key in under a member's name through one that hasn't heard yet
                merged["managePub"] = cur.get("managePub") or ""
                if merged.get("link") and cur.get("link"):
                    merged["link"] = dict(merged["link"], hostKeys=list(cur["link"].get("hostKeys") or []))
                merged = with_compat(merged)
            if cur["id"].startswith("m-") and cur.get("addedBy"):
                # Who added a machine, and whether only they manage it, belong to the adder: another computer's
                # edit (or an older version's rename, which drops both fields) can't clear or change them.
                merged["addedBy"] = cur["addedBy"]
                if merged.get("by") != "" and merged.get("by") != cur["addedBy"]:
                    merged["onlyMineManages"] = cur.get("onlyMineManages") is True
                    merged["fleetAccess"] = cur.get("fleetAccess") or ""
            if cur["id"].startswith("m-") and cur.get("fleetAccess") and not merged.get("fleetAccess"):
                # the person's answer about which computers manage it never goes back to "" (the older, wider default)
                # because an older version, that doesn't know the field, edited the entry
                merged["fleetAccess"] = cur["fleetAccess"]
                merged = with_compat(merged)
            if strip_local(merged) != strip_local(cur):
                live[e["id"]] = merged
                changed = True
            v = merge_chains(cur.get("vouch") or [], chains)
            if v != (cur.get("vouch") or []):
                live[e["id"]] = dict(live[e["id"]], vouch=v)
                vouched = True
    if changed or vouched:
        doc["machines"] = sorted(live.values(), key=lambda x: x["id"])
        doc["removed"] = sorted(tombs.values(), key=lambda x: -x["removed"])[:MAX_REMOVED]
    gone_now = prune_vouched(doc, me)
    if gone_now:
        changed = True
        # added again by a path that didn't count after all: its removal record stays
        back = [readded[e["id"]] for e in gone_now if e["id"] in readded]
        if back:
            doc["removed"] = sorted(doc["removed"] + back, key=lambda x: -x["removed"])[:MAX_REMOVED]
    if merge_twins(doc, me):
        changed = True
    return changed


def _norm_name(e: dict) -> str:
    return (e.get("label") or e.get("hostname") or "").strip().lower()


def twins(a: dict, b: dict) -> bool:
    """Two entries (not Starchaser computers: those are their link device, so never twice) that are one machine
    under two ids: a host key a person checked in common, or (when one came from converting an old list, which had
    no ids to match by) the same address, name, port and account. A checked host key that differs says they aren't."""
    if a["id"] == b["id"] or not (a["id"].startswith("m-") and b["id"].startswith("m-")):
        return False
    if a.get("port", 22) != b.get("port", 22) or (a.get("user") and b.get("user") and a["user"] != b["user"]):
        return False
    ka, kb = set(a.get("checkedHostKeys") or []), set(b.get("checkedHostKeys") or [])
    if ka and kb:
        return bool(ka & kb)
    if "migrated" not in (a.get("addedVia"), b.get("addedVia")):
        return False
    addr = best_address(a).lower()
    return bool(addr) and addr == best_address(b).lower() and bool(_norm_name(a)) and _norm_name(a) == _norm_name(b)


def merge_twins(doc: dict, me: str) -> bool:
    """Every pair of twins() in doc merged (in place), the way `merge` does it: the older entry (then the smaller id)
    keeps its id and takes the other's old ids, and the other is removed everywhere. Every computer picks the same
    one, so the fleet ends up with one entry whichever computer sees the pair first. True when anything merged."""
    ms = sorted((e for e in doc["machines"] if e["id"].startswith("m-")), key=lambda e: (e.get("added") or 0, e["id"]))
    merged = False
    gone = set()
    for i, k in enumerate(ms):
        if k["id"] in gone:
            continue
        for d in ms[i + 1:]:
            if d["id"] in gone or not twins(k, d):
                continue
            gone.add(d["id"])
            k["label"] = k["label"] or d["label"]
            k["aliases"] = list(dict.fromkeys(k["aliases"] + [d["id"]] + d["aliases"]))[:8]
            k["user"] = k["user"] or d["user"]
            _bump(k, me)
            keys = list(dict.fromkeys((k.get("checkedHostKeys") or []) + (d.get("checkedHostKeys") or [])))[:6]
            if keys != (k.get("checkedHostKeys") or []):
                k["checkedHostKeys"] = keys
                _fbump(k, me)
            if (k.get("manage") or {}).get("state") in (None, "none", "unknown") and \
                    (d.get("manage") or {}).get("state") not in (None, "none", "unknown"):
                k["manage"] = dict(d["manage"])         # what this computer learned about managing it, under either id
            with_compat(k)
            old = next((t for t in doc["removed"] if t["id"] == d["id"]), None)
            if old:
                doc["removed"].remove(old)
            doc["removed"].insert(0, {"id": d["id"], "gen": d["gen"], "rev": max(d["rev"], old["rev"] if old else 0) + 1,
                                      "by": me[4:], "removed": now(), "revoked": False, "label": display_name(d),
                                      "aliases": d["aliases"], "managePub": d.get("managePub") or ""})
            merged = True
    if merged:
        doc["machines"] = [e for e in doc["machines"] if e["id"] not in gone]
        doc["removed"] = doc["removed"][:MAX_REMOVED]
        doc["suggestions"] = [s for s in doc.get("suggestions") or [] if s["keep"] not in gone and s["drop"] not in gone]
    return merged


# ---------------------------------------------------------------------------------------------- the file
def empty_doc() -> dict:
    return {"version": VERSION, "self": {"id": self_id()}, "fleet": {"tag": ""}, "machines": [], "removed": [], "suggestions": [],
            "security": {"sequence": 0, "anchors": {}, "records": []},
            "local": {"manageConsent": False, "sharePrompts": False, "onlyMineManages": False,
                      "askBothWays": True, "askOnceForFleet": False, "left": None, "selfGen": 0, "known": {}}}


def clean_fleet(f, own: bool = False) -> dict:
    """{"tag", "born", "lone", "formed"}: the tag, when it was made, whether it is one computer's own (made by a
    computer on its own, no other Starchaser computer in its list yet), and when it first became a fleet of more than
    one computer. "formed" is left out while the tag is one computer's own, and when it isn't known: a copy passed
    on by an older Starchaser (it drops the field) says nothing about it. own: this computer's own saved list, where
    a fleet's tag from before this field counts as formed when it was made (once, when it is first read).
    {"tag": ""} when there is none."""
    if not isinstance(f, dict) or not isinstance(f.get("tag"), str) or not TAG_RE.fullmatch(f["tag"]):
        return {"tag": ""}
    out = {"tag": f["tag"], "born": counter(f.get("born")), "lone": bool(f.get("lone"))}
    if not out["lone"]:
        if isinstance(f.get("formed"), int) and not isinstance(f.get("formed"), bool) and f["formed"] >= 0:
            out["formed"] = counter(f["formed"])
        elif own:
            out["formed"] = out["born"]
    return out


def ensure_tag(doc: dict) -> bool:
    """The fleet's tag, made the first time this computer is in a fleet (or starts one). It only says which nearby
    computers share a fleet (it is announced with them, unauthenticated): trust never comes from it. True when made.
    Call it before adding the other computer, so a tag made by a computer on its own says so."""
    if TAG_RE.fullmatch((doc.get("fleet") or {}).get("tag") or ""):
        return False
    lone = not any(e.get("link") for e in doc["machines"])
    t = now()
    doc["fleet"] = {"tag": secrets.token_hex(4), "born": t, "lone": lone}
    if not lone:
        doc["fleet"]["formed"] = t
    return True


_UNKNOWN = float("inf")


def _tag_rank(f: dict) -> tuple:
    # a fleet of several computers wins over one computer's own; then the one that became a fleet first ("formed",
    # never "born": two computers on their own that pair today form a new fleet today, however old their tags are,
    # so they never take over a fleet that was already there; a fleet whose "formed" isn't known yet comes after
    # every one whose is); then the older tag; then the smaller. A tag's rank only ever improves (one computer's own
    # -> formed not known -> formed -> formed earlier: copies of it combine by the earliest "formed" known), so the
    # best one wins everywhere whatever order the lists arrive in.
    if f.get("lone"):
        return (1, _UNKNOWN, f.get("born", 0), f["tag"])
    return (0, f.get("formed", _UNKNOWN), f.get("born", 0), f["tag"])


def merge_tag(doc: dict, theirs) -> bool:
    """Two fleets that became one: a computer on its own takes the fleet's tag (it joined that fleet), and two fleets
    keep the one that became a fleet first (then the older, then the smaller), so every computer ends with the same
    one whatever order the lists arrive in, and a joining computer (or two that just paired on their own) never
    changes an existing fleet's tag. A tag that came in from another computer is shared by two or more now, so it
    isn't one computer's own any more: it is formed now, unless a "formed" is known for it (the earliest known
    wins; a copy without one, from an older Starchaser, changes nothing). True when this computer's tag changed."""
    t = clean_fleet(theirs)
    if not t["tag"]:
        return False
    mine = clean_fleet(doc.get("fleet"))
    if not mine["tag"]:
        win = t
    elif mine["tag"] == t["tag"]:
        win = {"tag": mine["tag"], "born": min(mine["born"], t["born"]), "lone": mine["lone"] and t["lone"]}
        known = [x["formed"] for x in (mine, t) if "formed" in x]
        if known:
            win.update(lone=False, formed=min(known))
    else:
        win = min(mine, t, key=_tag_rank)
    new = dict(win, lone=False)
    if win["lone"]:
        new["formed"] = now()
    if new != doc.get("fleet"):
        doc["fleet"] = new
        return True
    return False


def _read_raw():
    try:
        return json.loads(FLEET.read_text())
    except FileNotFoundError:
        return None
    except (OSError, ValueError, RecursionError):
        return False                                    # there but unreadable: never written over


def _normalize(raw) -> tuple:
    """(doc, changed): raw as a version 2 doc. Converts an old list, and takes in what an older writer did to a version
    2 list (Mission Control writing name/ip, adding a bare entry, or splicing one out) as the edits they were."""
    if raw is None:                                     # no list yet: start it from the paired devices, if any
        return (migrate({}), True) if PEERS.exists() else (empty_doc(), False)
    if not isinstance(raw, dict) or raw.get("version") != VERSION:
        return migrate(raw if isinstance(raw, dict) else {}), True
    me = self_id()
    doc = empty_doc()
    loc = raw.get("local") if isinstance(raw.get("local"), dict) else {}
    if isinstance(raw.get("security"), dict):
        doc["security"] = raw["security"]
    doc["local"].update({k: loc[k] for k in ("manageConsent", "sharePrompts", "onlyMineManages", "askBothWays", "askOnceForFleet", "remoteOwnFleet", "sharedClipboard",
                                             "left", "selfGen", "known", "syncedAt",
                                             "revokePending", "dropped", "joinedAt", "removedAt", "sessionRevokePending", "recoveryCounter", "lostComputers", "rootPairing") if k in loc})
    doc["removed"] = [t for t in (clean_tombstone(t) for t in raw.get("removed") or []) if t]
    doc["suggestions"] = [s for s in raw.get("suggestions") or [] if isinstance(s, dict)
                          and isinstance(s.get("keep"), str) and isinstance(s.get("drop"), str)]
    doc["fleet"] = clean_fleet(raw.get("fleet"), own=True)
    changed = False
    seen = set()
    for m in raw.get("machines") or []:
        if not isinstance(m, dict):
            continue
        if "gen" not in m:                              # an older writer's new entry
            e = from_v1(m, me)
            if e is None:
                continue
            e["addedVia"] = "mission-control" if m.get("addedBy") == "mission-control" else e["addedVia"]
            changed = True
        else:
            e = clean_entry(m)
            if e is None or e["id"] == me:
                changed = True
                continue
            # an older writer changed the old fields: a rename / a typed address
            if isinstance(m.get("name"), str) and m["name"].strip() and m["name"] != e["name"] and m["name"] != display_name(e):
                e["label"], e["rev"], e["by"], e["updated"] = safe_label(m["name"]), e["rev"] + 1, me[4:], now()
                changed = True
            if isinstance(m.get("ip"), str) and m["ip"] != e["ip"] and valid_host(m["ip"]):
                e["chosenAddress"] = e["addresses"]["last"] = m["ip"]
                e["rev"], e["by"], e["updated"] = e["rev"] + 1, me[4:], now()
                changed = True
            with_compat(e)
        if e["id"] in seen:
            changed = True
            continue
        seen.add(e["id"])
        doc["machines"].append(e)
    # an entry that was in the list this program last wrote and is gone now was removed by an older writer
    tomb_ids = {t["id"] for t in doc["removed"]}
    known = doc["local"].get("known")
    known = known if isinstance(known, dict) else {}
    for gone, gen in [(i, g) for i, g in known.items() if ID_RE.fullmatch(str(i)) and i not in seen and i not in tomb_ids]:
        doc["removed"].insert(0, {"id": gone, "gen": counter(gen), "rev": 1, "by": me[4:], "removed": now(),
                                  "revoked": False, "label": "", "aliases": [], "managePub": ""})
        changed = True
    if raw.get("self") != {"id": me}:
        changed = True
    # a list written before fleets had a tag: this computer is in a fleet, so it gets one (two computers that make
    # one each agree on the smaller as soon as they exchange lists)
    if doc["machines"] and not doc["local"].get("left") and ensure_tag(doc):
        changed = True
    try:
        peers = json.loads(PEERS.read_text())
    except (OSError, ValueError):
        peers = []
    for peer in peers if isinstance(peers, list) else []:
        if not isinstance(peer, dict) or peer.get("adopted") or peer.get("role") in ("helper", "help-target"):
            continue
        e = find(doc, "dev-" + str(peer.get("id", "")))
        if e and e.get("link") and peer.get("key") == e["link"].get("key"):
            if doc["security"]["anchors"].get(peer["id"]) != peer["key"]:
                doc["security"]["anchors"][peer["id"]] = peer["key"]
                changed = True
    return doc, changed


def from_v1(m: dict, me: str) -> dict | None:
    """One entry of the old list ({"name", "ip", "id"?, "user"?, "port"?, "os"?}) as a version 2 entry."""
    ip = str(m.get("ip") or "").strip()
    if not valid_host(ip):
        return None
    old = m.get("id") if isinstance(m.get("id"), str) and ALIAS_RE.fullmatch(m["id"]) else ""
    user = m.get("user") if isinstance(m.get("user"), str) and USER_RE.fullmatch(m["user"]) else ""
    port = m.get("port") if isinstance(m.get("port"), int) and 1 <= m["port"] <= 65535 else 22
    name = m.get("name") if isinstance(m.get("name"), str) else ""
    mid = old if old and ID_RE.fullmatch(old) and old.startswith("m-") else v1_machine_id(ip, name, user, port)
    addresses = {"last": ip, "lan": [ip] if valid_ip(ip) else [], "mdns": ip if ip.endswith(".local") else "", "tailscale": ""}
    os_label = scrub(safe_label(m.get("os"))) if isinstance(m.get("os"), str) else ""
    os_id = re.sub(r"[^a-z0-9._-]", "", os_label.split()[0].lower())[:32] if os_label else ""
    e = clean_entry({
        "id": mid, "label": m.get("name") or "", "hostname": "" if valid_ip(ip) or ip.endswith(".local") else ip,
        "os": {"id": os_id, "label": os_label}, "addresses": addresses,
        "user": m.get("user") or "", "port": m.get("port") if isinstance(m.get("port"), int) else 22,
        "addedVia": "migrated", "added": now(), "aliases": [old] if old and old != mid else [],
        "gen": 0, "rev": 1, "by": me[4:], "frev": 0, "fby": "", "updated": now(),
        "manage": {"state": "unknown", "since": 0},
    })
    return e


def known_host_keys(address: str) -> list:
    """The host keys ~/.ssh/known_hosts has for an address (hashed lines too), as "type base64" strings."""
    if not KNOWN_HOSTS.exists() or not valid_host(address):
        return []
    r = sh("ssh-keygen", "-F", address, "-f", str(KNOWN_HOSTS), timeout=5)
    out = []
    for line in r.stdout.splitlines():
        parts = line.split()
        if line.startswith("#") or len(parts) < 3:
            continue
        if parts[0].startswith("@"):
            parts = parts[1:]
        k = " ".join(parts[1:3])
        if KEY_RE.fullmatch(k):
            out.append(k)
    return out


def my_addresses() -> set:
    try:
        data = json.loads(sh("ip", "-j", "addr", timeout=4).stdout or "[]")
    except ValueError:
        data = []
    out = {"localhost", "127.0.0.1", "::1", socket.gethostname(), socket.gethostname() + ".local"}
    for d in data if isinstance(data, list) else []:
        for a in d.get("addr_info", []) if isinstance(d, dict) else []:
            if isinstance(a, dict) and a.get("local"):
                out.add(a["local"])
    return out


def migrate(raw: dict) -> dict:
    """The old list (and peers.json) as a version 2 doc. The old file is kept as fleet.json.v1.bak."""
    me = self_id()
    doc = empty_doc()
    if FLEET.exists():
        bak = FLEET.with_name("fleet.json.v1.bak")
        if not bak.exists():
            with contextlib.suppress(OSError):
                write_atomic(bak, FLEET.read_text())
    mine = my_addresses()
    devs = {}
    try:
        peers = json.loads(PEERS.read_text())
    except (OSError, ValueError, RecursionError):
        peers = []
    for p in peers if isinstance(peers, list) else []:
        if not isinstance(p, dict) or p.get("role") in ("helper", "help-target") or not DEV_RE.fullmatch(str(p.get("id", ""))):
            continue
        e = entry_from_peer(p, p.get("address") or "", "migrated", me)
        if e:
            devs[e["id"]] = e
    ms = []
    for m in raw.get("machines") or [] if isinstance(raw.get("machines"), list) else []:
        if not isinstance(m, dict):
            continue
        e = from_v1(m, me)
        if e is None:
            continue
        if e["addresses"]["last"] in mine or (e["hostname"] and e["hostname"] == socket.gethostname()):
            continue                                    # this computer: never stored
        if any(x["id"] == e["id"] for x in ms):
            continue                                    # the same line twice in the old list
        ms.append(e)
    suggestions = []
    for e in ms:
        addr = e["addresses"]["last"]
        keys = set(known_host_keys(addr))
        proven = next((d for d in devs.values() if keys and keys & set(d["link"]["hostKeys"])), None)
        if proven and (e["port"] != proven["port"] or (e["user"] and proven["user"] and e["user"] != proven["user"])):
            # the same computer, but another account or port: both kept, and offered as a possible duplicate
            suggestions.append({"keep": proven["id"], "drop": e["id"], "why": "same computer, another login"})
            doc["machines"].append(e)
            continue
        if proven:                                      # the same computer, proven by its host key
            proven["label"] = proven["label"] or e["label"]
            proven["aliases"] = list(dict.fromkeys(proven["aliases"] + [e["id"]] + e["aliases"]))[:8]
            if not proven["user"]:
                proven["user"] = e["user"]
            with_compat(proven)
            continue
        same = next((d for d in devs.values() if addr and (addr == d["addresses"]["last"] or addr in d["addresses"]["lan"]
                                                           or addr == d["addresses"]["tailscale"]
                                                           or (e["label"] and e["label"].lower() == d["hostname"].lower()))), None)
        if same:                                        # only an address or a name in common: ask, never merge
            suggestions.append({"keep": same["id"], "drop": e["id"], "why": "same address" if addr else "same name"})
        doc["machines"].append(e)
    doc["machines"] += list(devs.values())
    doc["machines"].sort(key=lambda x: x["id"])
    doc["suggestions"] = suggestions
    if doc["machines"]:
        ensure_tag(doc)
    return doc


def entry_from_peer(p: dict, address: str, via: str, me: str) -> dict | None:
    hk = p.get("hostKeys") if isinstance(p.get("hostKeys"), list) else []
    return clean_entry({
        "id": "dev-" + p["id"], "label": "", "hostname": p.get("name") if isinstance(p.get("name"), str) and HOST_RE.fullmatch(p.get("name") or "") else "",
        "kind": p.get("kind") or "", "starchaser": True,
        "addresses": {"last": address if valid_host(address) else "", "lan": p.get("addresses") or ([address] if valid_ip(address) else []),
                      "mdns": (p["name"] + ".local") if isinstance(p.get("name"), str) and HOST_RE.fullmatch(p["name"]) else "",
                      "tailscale": p.get("tailscale") or ""},
        "user": p.get("user") or "",
        "link": {"device": p["id"], "key": p.get("key") or "", "hostKeys": ([p["hostkey"]] if p.get("hostkey") else []) + hk,
                 "paired": p.get("paired") if isinstance(p.get("paired"), int) else now()},
        "managePub": p.get("managePub") or "", "macs": p.get("macs") or [], "addedVia": via, "added": now(),
        "gen": 0, "rev": 1, "by": me[4:], "frev": 1, "fby": me[4:], "updated": now(),
    })


# A lost-computer request still waiting for its computer (starchaser fleet safety retry tries those): while one is,
# this mark exists, and starchaser-fleet-recovery.service starts only then (ConditionPathExists, checked by systemd
# itself), so its timer starts nothing on a computer with nothing to retry.
RECOVERY_PENDING = STATE_DIR / "fleet-recovery-pending"
RECOVERY_SETTLED = ("removed", "off", "failed", "erase-started", "permission-changed")


def note_recovery_pending(doc: dict) -> None:
    rows = (doc.get("local") or {}).get("lostComputers") or []
    want = any(isinstance(r, dict) and r.get("request") and r.get("peer") and r.get("state") not in RECOVERY_SETTLED
               for r in rows)
    try:
        if want and not RECOVERY_PENDING.exists():
            RECOVERY_PENDING.parent.mkdir(parents=True, exist_ok=True)
            RECOVERY_PENDING.touch()
        elif not want and RECOVERY_PENDING.exists():
            RECOVERY_PENDING.unlink()
    except OSError:
        pass


def save(doc: dict) -> None:
    """Write doc (call with the lock held). Keeps the list of live ids, so a later splice by an older writer reads
    as a removal."""
    doc["version"] = VERSION
    doc["self"] = {"id": self_id()}
    doc["machines"] = [with_compat(e) for e in sorted(doc["machines"], key=lambda x: x["id"])]
    doc["local"]["known"] = {e["id"]: e["gen"] for e in doc["machines"]}
    write_atomic(FLEET, json.dumps(doc, indent=1) + "\n")
    note_recovery_pending(doc)


def load() -> dict:
    """The fleet as it is now (converted and saved first if an older writer touched it). Never None: an unreadable
    file reads as an empty fleet, and is never written over."""
    raw = _read_raw()
    if raw is False:
        d = empty_doc()
        d["unreadable"] = True
        return d
    doc, changed = _normalize(raw)
    if changed:
        with fleet_lock():
            raw = _read_raw()
            if raw is False:
                return doc
            doc, changed = _normalize(raw)
            if changed:
                save(doc)
    note_recovery_pending(doc)          # (a request saved before the mark existed)
    return doc


@contextlib.contextmanager
def editing():
    """Read, change and write the list as one step under the lock. Yields the doc; it's written when the block ends
    without an error (and never over a file that didn't read)."""
    with fleet_lock():
        raw = _read_raw()
        if raw is False:
            raise OSError(f"{FLEET} doesn't read as a fleet list; it was left as it is")
        doc, _ = _normalize(raw)
        before = json.dumps(doc, sort_keys=True)
        yield doc
        if json.dumps(doc, sort_keys=True) != before:
            save(doc)


def find(doc: dict, ident: str) -> dict | None:
    for e in doc["machines"]:
        if e["id"] == ident or ident in e.get("aliases", []) or (e.get("link") and e["link"]["device"] == ident):
            return e
    return None


def get(ident: str) -> dict | None:
    return find(load(), ident)


def is_removed(dev: str) -> bool:
    """A Starchaser device that was removed from the fleet (or dropped: only a removed one vouched for it) and not
    added again."""
    ident = dev if dev.startswith("dev-") else "dev-" + dev
    doc = load()
    if doc.get("unreadable"):
        raise OSError("Fleet membership couldn't be read.")
    return (any(t["id"] == ident for t in _removal_records(doc)) or ident in (doc["local"].get("dropped") or {})) \
        and not find(doc, ident)


def is_member(dev: str, key: str) -> bool:
    """A live fleet computer with this link key, in a list this computer is still in: checked again (under the device
    lock) right before trusting it, so a reconcile working from a list read a moment ago can't put back a computer a
    newer exchange has removed or dropped since."""
    doc = load()
    if doc.get("unreadable") or doc["local"].get("left"):
        return False
    e = find(doc, "dev-" + dev)
    return bool(e and e.get("link") and e["link"].get("device") == dev and e["link"].get("key") == key)


def _bump(e: dict, me: str) -> None:
    e["rev"], e["by"], e["updated"] = e.get("rev", 0) + 1, me[4:], now()


def _fbump(e: dict, me: str) -> None:
    e["frev"], e["fby"], e["updated"] = e.get("frev", 0) + 1, me[4:], now()


def _next_gen(doc: dict, ident: str) -> int:
    t = next((t for t in doc["removed"] if t["id"] == ident), None)
    if t:
        doc["removed"].remove(t)
        return t["gen"] + 1
    return 0


# ---------------------------------------------------------------------------------------------- signed membership and removals
# Records travel over the joining port as well as SSH. Their signatures, anchored in a code-checked member's
# link key, are the authority; neither the delivery address nor the sender's claimed identity grants trust.
# Sequence numbers belong to the signing computer. A removal freezes what that computer had vouched for at the
# sequence the remover had seen, so different wall clocks cannot revoke an earlier legitimate introduction.
SECURITY_NAMESPACE = "starchaser-fleet-membership-v1"


def _signed_bytes(body: dict) -> str:
    return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def _signed_record(record: dict) -> dict:
    """Keep the signed body and signature; courier metadata has no identity or authority."""
    return {"body": record["body"], "signature": record.get("signature")}


def _sign_record(doc: dict, kind: str, value: dict, fleet_root: str = "") -> dict:
    if not (DEVICES / "id_ed25519").exists():
        DEVICES.mkdir(parents=True, exist_ok=True)
        made = sh("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "starchaser-link", "-f", str(DEVICES / "id_ed25519"))
        if made.returncode:
            raise OSError("Couldn't make the fleet signing key.")
    sec = doc["security"]
    sec["sequence"] = counter(sec.get("sequence")) + 1
    body = {"kind": kind, "issuer": device_id(), "generation": counter(doc["local"].get("selfGen")), "sequence": sec["sequence"], "value": value}
    root = fleet_root or (sec.get("identity") or {}).get("certificate", {}).get("body", {}).get("rootKey")
    if root: body["fleetRoot"] = root
    r = sh("ssh-keygen", "-Y", "sign", "-n", SECURITY_NAMESPACE, "-f", str(DEVICES / "id_ed25519"),
           input=_signed_bytes(body))
    if r.returncode or not r.stdout.startswith("-----BEGIN SSH SIGNATURE-----"):
        raise OSError("Couldn't sign the fleet change. Nothing was removed.")
    record = {"body": body, "signature": r.stdout}
    sec["records"].append(record)
    return record


_SIGNATURE_CACHE = {}


def _verify_record(record, key: str, namespace: str = SECURITY_NAMESPACE) -> bool:
    if not isinstance(record, dict) or not isinstance(record.get("body"), dict):
        return False
    sig = record.get("signature")
    if not isinstance(sig, str) or len(sig) > 4096 or not KEY_RE.fullmatch(key):
        return False
    cache_key = (_signed_bytes(record["body"]), sig, key, namespace)
    if cache_key in _SIGNATURE_CACHE: return _SIGNATURE_CACHE[cache_key]
    with tempfile.TemporaryDirectory(prefix="fleet-signature-") as root:
        allowed, signature = Path(root) / "allowed", Path(root) / "signature"
        allowed.write_text("member " + key + "\n")
        signature.write_text(sig)
        result = sh("ssh-keygen", "-Y", "verify", "-f", str(allowed), "-I", "member", "-n", namespace,
                    "-s", str(signature), input=cache_key[0]).returncode == 0
    if len(_SIGNATURE_CACHE) >= 4096: _SIGNATURE_CACHE.pop(next(iter(_SIGNATURE_CACHE)))
    _SIGNATURE_CACHE[cache_key] = result
    return result


FLEET_IDENTITY_NAMESPACE = "starchaser-fleet-identity-v1"


def _identity_signature(key: Path, body: dict) -> str:
    result = sh("ssh-keygen", "-Y", "sign", "-n", FLEET_IDENTITY_NAMESPACE, "-f", str(key), input=_signed_bytes(body))
    if result.returncode or not result.stdout.startswith("-----BEGIN SSH SIGNATURE-----"):
        raise OSError("Couldn't sign this fleet's identity.")
    return result.stdout


def ensure_fleet_identity(doc: dict) -> dict:
    if doc["security"].get("identity"):
        identity = doc["security"]["identity"]
        _bridge_root(doc, identity["certificate"]["body"]["rootKey"], identity)
        return identity
    ensure_tag(doc)
    DEVICES.mkdir(parents=True, exist_ok=True)
    root_tag = DEVICES / "fleet-signing.tag"
    if (DEVICES / "fleet-signing").exists() and (not root_tag.exists() or root_tag.read_text().strip() != doc["fleet"]["tag"]):
        (DEVICES / "fleet-signing").unlink(missing_ok=True)
        (DEVICES / "fleet-signing.pub").unlink(missing_ok=True)
    for path in (DEVICES / "id_ed25519", DEVICES / "fleet-signing"):
        if not path.exists():
            result = sh("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(path))
            if result.returncode:
                raise OSError("Couldn't make this fleet's signing identity.")
        path.chmod(0o600)
    root = " ".join((DEVICES / "fleet-signing.pub").read_text().split()[:2])
    member = " ".join((DEVICES / "id_ed25519.pub").read_text().split()[:2])
    body = {"kind": "fleet-founder", "fleetTag": doc["fleet"]["tag"], "founder": device_id(),
            "founderKey": member, "rootKey": root, "founderGeneration": counter(doc["local"].get("selfGen"))}
    identity = {"certificate": {"body": body, "signature": _identity_signature(DEVICES / "fleet-signing", body)},
                "endorsement": _identity_signature(DEVICES / "id_ed25519", body)}
    write_atomic(root_tag, doc["fleet"]["tag"] + "\n", 0o600)
    doc["security"]["identity"] = identity
    _bridge_root(doc, root, identity)
    _seal_legacy(doc)
    return identity


def verify_fleet_identity(identity) -> bool:
    try:
        certificate = identity["certificate"]
        body = certificate["body"]
        if body.get("kind") != "fleet-founder" or not DEV_RE.fullmatch(body.get("founder", "")) or not TAG_RE.fullmatch(body.get("fleetTag", "")):
            return False
        if type(body.get("founderGeneration", 0)) is not int or not 0 <= body.get("founderGeneration", 0) < MAX_COUNTER:
            return False
        return (_verify_record(certificate, body["rootKey"], FLEET_IDENTITY_NAMESPACE)
                and _verify_record({"body": body, "signature": identity["endorsement"]}, body["founderKey"], FLEET_IDENTITY_NAMESPACE))
    except (KeyError, TypeError, AttributeError, ValueError):
        return False


def accept_fleet_identity(doc: dict, identity, sender: str) -> bool:
    # Root choice is only accepted through an authenticated live member and its existing certificate chain.
    # The public courier never calls this function. Helpers and managed-only machines have no membership key.
    sender_entry = find(doc, "dev-" + sender)
    if not sender_entry or not sender_entry.get("link") or not verify_fleet_identity(identity):
        return False
    body = identity["certificate"]["body"]
    keys, members = _security_keys(doc, doc["security"].get("records") or [], legacy=True)
    if keys.get(body["founder"]) != body["founderKey"]:
        return False
    current = doc["security"].get("identity")
    current_body = (current or {}).get("certificate", {}).get("body", {})
    founder = body["founder"]
    approved_generation = max(counter((find(doc, "dev-" + founder) or {}).get("gen")),
                              counter((members.get("dev-" + founder) or {}).get("gen")),
                              counter(doc["local"].get("selfGen")) if founder == device_id() else 0,
                              counter(current_body.get("founderGeneration")) if current_body.get("founder") == founder else 0)
    if counter(body.get("founderGeneration")) > approved_generation:
        return False
    incoming_root = body["rootKey"]
    old_root = current_body.get("rootKey", "")
    changed = False
    if current and old_root != incoming_root:
        changed = _bridge_root(doc, old_root, identity) or changed
        changed = _bridge_root(doc, incoming_root, current) or changed
    if not current or incoming_root < old_root:
        probe = dict(doc, security=dict(doc["security"], identity=identity))
        own = DEVICES / "id_ed25519.pub"
        if own.exists() and _security_keys(probe, doc["security"]["records"])[0].get(device_id()) == " ".join(own.read_text().split()[:2]):
            doc["security"]["identity"] = identity
            (DEVICES / "fleet-web-ca" / "authority.key").unlink(missing_ok=True)
            root_pub = DEVICES / "fleet-signing.pub"
            if root_pub.exists() and " ".join(root_pub.read_text().split()[:2]) != incoming_root:
                for name in ("fleet-signing", "fleet-signing.pub", "fleet-signing.tag"):
                    (DEVICES / name).unlink(missing_ok=True)
            changed = True
    _bridge_root(doc, doc["security"]["identity"]["certificate"]["body"]["rootKey"], doc["security"]["identity"])
    _seal_legacy(doc)
    return changed


def _bridge_root(doc, root, identity):
    for record in doc["security"]["records"]:
        body = record["body"]
        if body["kind"] == "bridge" and body.get("fleetRoot") == root and body["value"] == identity and body["issuer"] == device_id() and counter(body.get("generation")) == counter(doc["local"].get("selfGen")):
            return False
    _sign_record(doc, "bridge", identity, fleet_root=root)
    return True


def _seal_legacy(doc):
    hashes = sorted({hashlib.sha256(_signed_bytes(r).encode()).hexdigest() for r in doc["security"]["records"] if not r["body"].get("fleetRoot")})
    if not hashes: return
    root = doc["security"]["identity"]["certificate"]["body"]["rootKey"]
    sealed = {value for r in doc["security"]["records"] if r["body"]["kind"] == "legacy" and r["body"].get("fleetRoot") == root for value in r["body"]["value"]}
    if not set(hashes) <= sealed: _sign_record(doc, "legacy", hashes)


def _security_cutoffs(records: list) -> dict:
    out = {}
    for r in records:
        b = r["body"]
        if b.get("kind") == "remove":
            v = b["value"]
            if v["tombstone"]["id"].startswith("dev-"):
                d = v["tombstone"]["id"][4:]
                out[d] = min(out.get(d, MAX_COUNTER), counter(v.get("seen")))
    return out


def _security_allowed(record: dict, records: list) -> bool:
    b = record["body"]
    removals = [r["body"] for r in records if r["body"]["kind"] == "remove"
                and r["body"]["value"]["tombstone"]["id"] == "dev-" + b["issuer"]
                and counter(b.get("generation")) <= r["body"]["value"]["tombstone"]["gen"]]
    if not removals:
        return True
    digest = hashlib.sha256(_signed_bytes(record).encode()).hexdigest()
    # Preserve a mutual removal even if its counter-removal arrived first. This exception is limited to the
    # removing member itself: a revoked signer has no authority to remove an uninvolved third computer.
    # All other records must be in the exact set frozen when this signing generation was removed.
    return all((b["sequence"] <= r["value"]["seen"] and digest in r["value"].get("allowed", []))
               or (b["kind"] == "remove" and b["value"]["tombstone"]["id"] == "dev-" + r["issuer"]
                   and b["value"]["tombstone"]["gen"] <= counter(r.get("generation")))
               for r in removals)


def _security_graph(doc: dict, records: list, legacy=False) -> tuple:
    identity = doc["security"].get("identity")
    roots, hashes = {}, set()
    if identity and not legacy:
        if not verify_fleet_identity(identity): return {}, {}, {}, set()
        founder = identity["certificate"]["body"]
        roots[founder["rootKey"]] = identity
        keys = {founder["founder"]: founder["founderKey"]}
    else:
        keys = dict(doc["security"].get("anchors") or {})
        own = DEVICES / "id_ed25519.pub"
        if own.exists(): keys[device_id()] = " ".join(own.read_text().split()[:2])
    members = {}
    for _ in range(VOUCH_LEN + 1):
        grew = False
        for r in records:
            b = r["body"]
            if b["issuer"] not in keys or not _security_allowed(r, records): continue
            scoped = legacy or not identity or b.get("fleetRoot") in roots or hashlib.sha256(_signed_bytes(r).encode()).hexdigest() in hashes
            if not scoped and not (b["kind"] == "bridge" and b.get("fleetRoot") == b["value"]["certificate"]["body"]["rootKey"]): continue
            if b["kind"] == "bridge":
                foreign = b["value"]
                if not verify_fleet_identity(foreign) or not _verify_record(r, keys[b["issuer"]]): continue
                body = foreign["certificate"]["body"]
                if body["rootKey"] not in roots:
                    roots[body["rootKey"]] = foreign
                    # A bridge permits a certificate scope, not an invisible signing member. Its founder
                    # still needs a member certificate from the already authenticated delegation graph.
                    grew = True
                continue
            if b["kind"] == "legacy":
                if not _verify_record(r, keys[b["issuer"]]): continue
                extra = set(b["value"]) - hashes
                if extra: hashes.update(extra); grew = True
                continue
            if b["kind"] != "member": continue
            e = clean_entry(b["value"])
            if not e or not e.get("link"): continue
            d = e["link"]["device"]
            if d not in keys:
                keys[d] = e["link"]["key"]; grew = True
            if keys[d] == e["link"]["key"] and (e["id"] not in members or e["gen"] >= members[e["id"]]["gen"]):
                previous = members.get(e["id"])
                if not previous or e["gen"] > previous["gen"] or _person_key(e) >= _person_key(previous):
                    members[e["id"]] = dict(e, vouch=[[[b["issuer"], b["sequence"]]]])
        if not grew: break
    return keys, members, roots, hashes


def _security_keys(doc: dict, records: list, legacy=False) -> tuple:
    return _security_graph(doc, records, legacy)[:2]


def certified_identity(cert, entry) -> bool:
    return bool(cert and entry and cert["gen"] == entry["gen"] and cert.get("link") and entry.get("link")
                and cert["link"]["key"] == entry["link"]["key"])


def _security_members(doc: dict) -> dict:
    return _security_keys(doc, doc["security"].get("records") or [])[1]


def certify_member(doc: dict, entry: dict) -> None:
    """Only after a direct code check or the member's authenticated self report, never for a relayed list."""
    key = entry["link"]["key"]
    doc["security"]["anchors"][entry["link"]["device"]] = key
    value = strip_local(entry)
    previous = [r["body"]["value"] for r in doc["security"]["records"]
                if r["body"].get("kind") == "member" and r["body"].get("issuer") == device_id()
                and r["body"]["value"].get("id") == entry["id"]]
    # Addresses, labels and status continue to travel in the list. Certificates pin identity and incarnation.
    def identity(e):
        return (e.get("gen"), (e.get("link") or {}).get("key"), (e.get("link") or {}).get("hostKeys"), e.get("managePub"), e.get("label"), e.get("rev"))
    if not previous or identity(previous[-1]) != identity(value):
        _sign_record(doc, "member", value)


def security_payload() -> dict:
    doc = load()
    if doc.get("unreadable"):
        raise OSError("Fleet membership couldn't be read.")
    return {"records": doc["security"].get("records") or [], "identity": doc["security"].get("identity")}


def accept_security(bundle, authenticated=False) -> bool:
    """Validate an untrusted courier's records against pinned keys and signed introductions. Persist removals
    indefinitely, including across restarts. No trust, consent or metadata is taken from an unsigned envelope."""
    if not isinstance(bundle, dict) or not isinstance(bundle.get("records"), list) or len(bundle["records"]) > 4000:
        raise ValueError("not signed fleet records")
    if load()["local"].get("left"):
        with contextlib.suppress(OSError, ValueError):
            recovery_client().apply_bundle(bundle)
        return False
    with editing() as doc:
        if doc["local"].get("left"):
            return False
        sec = doc["security"]
        boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
        pair_grants = {ident: grant for ident, grant in (doc["local"].get("rootPairing") or {}).items()
                       if isinstance(grant, dict) and grant.get("boot") == boot and type(grant.get("until")) in (int, float)
                       and grant["until"] > time.monotonic() and (sec.get("anchors") or {}).get(ident) == grant.get("key")}
        if pair_grants or "rootPairing" in doc["local"]:
            doc["local"]["rootPairing"] = pair_grants
        upgrade_exchange = bool(authenticated or pair_grants)
        stored = sec.get("records") or []
        # A courier may repeat a valid signature thousands of times in one envelope. Deduplicate both the
        # envelope and the stored history, including files written before this check existed.
        accepted = list({_signed_bytes(_signed_record(r)): _signed_record(r) for r in stored}.values())
        known = {_signed_bytes(r) for r in accepted}
        pending = []
        for r in bundle["records"]:
            if not isinstance(r, dict) or not isinstance(r.get("body"), dict):
                continue
            b = r["body"]
            if not DEV_RE.fullmatch(str(b.get("issuer", ""))) or type(b.get("sequence")) is not int or not 0 < b["sequence"] < MAX_COUNTER:
                continue
            v = b.get("value")
            if b.get("kind") == "member":
                e = clean_entry(v)
                if not e or not e.get("link") or not e["link"].get("key") or e["id"] == "dev-" + b["issuer"]:
                    continue
            elif b.get("kind") == "remove":
                if not isinstance(v, dict) or not clean_tombstone(v.get("tombstone")) or type(v.get("seen")) is not int or not isinstance(v.get("allowed"), list):
                    continue
                if v["tombstone"].get("by") != b["issuer"]:
                    continue
            elif b.get("kind") == "bridge":
                if not verify_fleet_identity(v): continue
            elif b.get("kind") == "legacy":
                if not isinstance(v, list) or len(v) > 4000 or any(not isinstance(h, str) or not re.fullmatch("[0-9a-f]{64}", h) for h in v): continue
            else:
                continue
            if b.get("fleetRoot") and not KEY_RE.fullmatch(str(b["fleetRoot"])): continue
            r = _signed_record(r)
            encoded = _signed_bytes(r)
            if encoded not in known:
                known.add(encoded)
                pending.append(r)
        changed = accepted != stored
        for _ in range(VOUCH_LEN + 1):
            keys, members, roots, legacy_hashes = _security_graph(doc, accepted, legacy=upgrade_exchange)
            grew = False
            for r in list(pending):
                b = r["body"]
                issuer = b["issuer"]
                root_proof = b["kind"] == "bridge" and b.get("fleetRoot") == b["value"]["certificate"]["body"]["rootKey"]
                if not upgrade_exchange and sec.get("identity") and b.get("fleetRoot") not in roots and hashlib.sha256(_signed_bytes(r).encode()).hexdigest() not in legacy_hashes and not root_proof:
                    continue
                founder_body = (sec.get("identity") or {}).get("certificate", {}).get("body", {})
                founder_gen = counter(founder_body.get("founderGeneration")) if founder_body.get("founder") == issuer else 0
                direct = find(doc, "dev-" + issuer) if issuer in sec.get("anchors", {}) else None
                approved_gen = max(founder_gen, (direct or {}).get("gen", 0), (members.get("dev-" + issuer) or {}).get("gen", 0),
                                   counter(doc["local"].get("selfGen")) if issuer == device_id() else 0)
                # Starting an independent fleet retires this computer's old signing scope. A courier must not
                # replay our own former introductions to merge the household we deliberately left back in.
                if issuer == device_id() and counter(b.get("generation")) != counter(doc["local"].get("selfGen")):
                    continue
                if issuer not in keys or counter(b.get("generation")) > approved_gen or not _security_allowed(r, accepted):
                    continue
                if not _verify_record(r, keys[issuer]):
                    pending.remove(r)
                    continue
                accepted.append(r)
                pending.remove(r)
                grew = changed = True
            if not grew:
                break
        # A removal's signer may have been revoked later in this same envelope. Verify the complete set before
        # applying any tombstones, and repair tombstones persisted by an older writer with the same mistake.
        refused = [r for r in accepted if r["body"]["kind"] == "remove" and not _security_allowed(r, accepted)]
        if refused:
            refused_bytes = {_signed_bytes(r) for r in refused}
            accepted = [r for r in accepted if _signed_bytes(r) not in refused_bytes]
            bad_tombs = {(r["body"]["value"]["tombstone"]["id"], r["body"]["value"]["tombstone"]["gen"],
                          r["body"]["issuer"]) for r in refused}
            doc["removed"] = [t for t in doc["removed"] if (t["id"], t["gen"], t["by"]) not in bad_tombs]
            changed = True
        sec["records"] = accepted
        own_key = DEVICES / "id_ed25519.pub"
        own_public = " ".join(own_key.read_text().split()[:2]) if own_key.exists() else ""
        approvals = [r for r in accepted if r["body"]["kind"] == "member" and r["body"]["issuer"] in pair_grants
                     and r["body"]["value"].get("id") == self_id() and (r["body"]["value"].get("link") or {}).get("key") == own_public
                     and _security_allowed(r, accepted)]
        if approvals:
            approval = max(approvals, key=lambda r: counter(r["body"]["value"].get("gen")))
            generation = counter(approval["body"]["value"].get("gen"))
            if generation > counter(doc["local"].get("selfGen")):
                doc["local"]["selfGen"] = generation
                ensure_fleet_identity(doc)
                paired = find(doc, "dev-" + approval["body"]["issuer"])
                if paired: _sign_record(doc, "member", strip_local(paired))
            for r in approvals: pair_grants.pop(r["body"]["issuer"], None)
        if authenticated:
            # A new code check may authorize a newer incarnation of this formerly removed computer. Read that
            # signed certificate before rebuilding its root path; its former generation stays frozen.
            own_upgrade = _security_keys(doc, accepted, legacy=True)[1].get(self_id())
            if own_upgrade:
                doc["local"]["selfGen"] = max(counter(doc["local"].get("selfGen")), own_upgrade["gen"])
            if sec.get("identity"): ensure_fleet_identity(doc)
            if bundle.get("identity"): accept_fleet_identity(doc, bundle["identity"], authenticated)
        certified = _security_members(doc)
        tombs = [clean_tombstone(r["body"]["value"]["tombstone"]) for r in accepted if r["body"]["kind"] == "remove"]
        own = certified.get(self_id())
        if own:
            doc["local"]["selfGen"] = max(counter(doc["local"].get("selfGen")), own["gen"])
        machines = []
        for ident, e in certified.items():
            if ident == self_id():
                continue
            cur = find(doc, ident)
            if cur is None or cur["gen"] < e["gen"]:
                machines.append(e)
        changed = merge_docs(doc, machines, tombs, self_id()) or changed
        if doc["local"].get("left"):
            doc["local"]["manageConsent"] = False
            write_atomic(FLEET.with_name("fleet.json.left.bak"), json.dumps(doc, indent=1) + "\n")
            doc["machines"], doc["removed"], doc["suggestions"] = [], [], []
            doc["fleet"] = {"tag": ""}
            doc["local"]["dropped"], doc["local"]["revokePending"] = {}, {}
        return changed


# ---------------------------------------------------------------------------------------------- changes
def add_machine(address: str, user: str = "", port: int = 22, label: str = "", via: str = "mission-control",
                os_label: str = "", os_id: str = "") -> dict:
    if not valid_host(address):
        raise ValueError("That address has characters an address can't have.")
    if user and not USER_RE.fullmatch(user):
        raise ValueError("That login name has characters a login name can't have.")
    if not 1 <= int(port) <= 65535:
        raise ValueError("The port must be a number from 1 to 65535.")
    me = self_id()
    if address in my_addresses():
        raise ValueError("That's this computer.")
    with editing() as doc:
        for e in doc["machines"]:                       # the same address, login and port: the same entry
            a = e["addresses"]
            if address in (e["chosenAddress"], a["last"], a["mdns"], a["tailscale"], e["hostname"], *a["lan"]) and e["user"] == (user or e["user"]) \
                    and e["port"] == int(port):
                if label and label != e["label"]:
                    e["label"] = safe_label(label)
                    _bump(e, me)
                return e
        e = clean_entry({
            "id": new_machine_id(), "label": label, "hostname": "" if valid_ip(address) or address.endswith(".local") else address,
            "os": {"id": os_id, "label": os_label},
            "addresses": {"last": address, "lan": [address] if valid_ip(address) else [], "mdns": address if address.endswith(".local") else ""},
            "user": user, "port": int(port), "addedVia": via if via in VIAS else "mission-control", "added": now(),
            "addedBy": me[4:], "onlyMineManages": doc["local"].get("onlyMineManages") is True,
            # only this computer's key goes there until the person says which computers may manage it (fleet-access)
            "fleetAccess": "mine" if doc["local"].get("onlyMineManages") is True else "ask",
            "gen": 0, "rev": 1, "by": me[4:], "updated": now(),
        })
        doc["machines"].append(e)
        ensure_tag(doc)
    changed()
    return e


def upsert_paired(peer: dict, address: str, via: str = "pairing") -> dict | None:
    """Pairing finished: the paired device's entry, made or brought up to date (the keys pairing verified win). A
    device removed before gets a higher gen: pairing it again with the code is adding it again on purpose."""
    me = self_id()
    ident = "dev-" + peer["id"]
    if ident == me:
        return None
    with editing() as doc:
        # (the device may be in the list already: the link writes its paired devices first, and a list made from them
        # just now holds it)
        alone = not any(x.get("link") and x["id"] != ident for x in doc["machines"])
        if alone:
            # this computer was on its own: it is the one joining (its own fleet's members don't say "just joined")
            doc["local"]["joinedAt"] = now()
        # checked again with its code (reinstalled, or a pairing repeated): the two of them are a fleet already (the
        # list as it was saved, not one just made from the paired devices, had a fleet's tag, and this one was paired
        # in it), and the fleet keeps its age
        raw = _read_raw()
        saved = raw if isinstance(raw, dict) and raw.get("version") == VERSION else {}
        was = clean_fleet(saved.get("fleet"))
        was_in = any(isinstance(x, dict) and x.get("id") == ident and (x.get("link") or {}).get("paired")
                     for x in (saved.get("machines") if isinstance(saved.get("machines"), list) else []))
        again = bool(was["tag"]) and not was["lone"] and was_in
        ensure_tag(doc)
        if alone and not again and doc["fleet"].get("tag"):
            # its tag is one computer's own: the other one's fleet keeps its tag
            doc["fleet"]["lone"] = True
            doc["fleet"].pop("formed", None)
        (doc["local"].get("dropped") or {}).pop(ident, None)       # checked here, by its code: it counts again
        e = find(doc, ident)
        hostkeys = clean_keys(([peer.get("hostkey")] if peer.get("hostkey") else []) + list(peer.get("hostKeys") or []))
        if e is None:
            gen = _next_gen(doc, ident)
            e = entry_from_peer(dict(peer, hostKeys=hostkeys), address, via if via in VIAS else "pairing", me)
            if e is None:
                return None
            e["gen"] = gen
            doc["machines"].append(e)
            doc["local"]["left"] = None                 # paired again: back in a fleet
        else:
            link = e.get("link") or {}
            # compared with the pinned key (the first), not the whole list: the computer's own report may already
            # have added its new key after the pinned one, and a reinstall then kept the old pin forever
            if link.get("key") != peer.get("key") or (hostkeys and hostkeys[0] != ((link.get("hostKeys") or [""])[0])):
                # other keys: as far as anyone can tell another computer (reinstalled, or replaced). A new gen, so an
                # edit to the old one, made anywhere, can never bring the old keys back; the name chosen for it stays.
                new = entry_from_peer(dict(peer, hostKeys=hostkeys), address, via if via in VIAS else "pairing", me)
                if new is None:
                    return None
                new.update(label=e["label"], aliases=e["aliases"], gen=e["gen"] + 1, added=e["added"] or now())
                doc["machines"][doc["machines"].index(e)] = with_compat(new)
                doc["local"]["left"] = None
                e = new
            else:
                e["link"]["paired"] = link.get("paired") or now()
                e["vouch"] = merge_chains(e.get("vouch") or [], [[]])     # checked here now
            if valid_host(address) and e["addresses"]["last"] != address:
                e["addresses"]["last"] = address
                _fbump(e, me)
            with_compat(e)
            doc["local"]["left"] = None
        if KEY_RE.fullmatch(str(peer.get("managePub") or "")) and peer["managePub"] != e["link"]["key"]:
            e["managePub"] = peer["managePub"]
        e["gen"] = max(e["gen"], counter(peer.get("generation")))  # incarnation checked with the pairing code
        ensure_fleet_identity(doc)
        certify_member(doc, e)
        grants = doc["local"].setdefault("rootPairing", {})
        grants[peer["id"]] = {"key": peer["key"], "boot": Path("/proc/sys/kernel/random/boot_id").read_text().strip(), "until": time.monotonic() + 600}
        while len(grants) > 64: grants.pop(next(iter(grants)))
    changed()
    return e


def observe(ident: str, facts: dict, by: str = "") -> bool:
    """Facts a status call (or a probe) found about a computer. Only what differs is written, so a steady computer
    never churns the list."""
    me = self_id()
    with editing() as doc:
        e = find(doc, ident)
        if e is None:
            return False
        new = apply_facts(e, facts)
        if new == e:
            return False
        e.clear()
        e.update(new)
        e["frev"], e["fby"], e["updated"] = e.get("frev", 0) + 1, (by or me[4:]), now()
        with_compat(e)
    changed()
    return True


def apply_facts(e: dict, facts: dict) -> dict:
    """e with facts laid over it, every value checked; e itself is left as it was."""
    probe = dict(e)
    for k in ("hostname", "kind", "managePub", "recovery"):
        if k in facts:
            probe[k] = facts[k]
    if isinstance(facts.get("os"), dict) and facts["os"]:
        # a status call knows only the label: the id the computer reported stays
        probe["os"] = {"id": facts["os"].get("id") or e["os"]["id"], "label": facts["os"].get("label") or e["os"]["label"]}
    if "addresses" in facts and isinstance(facts["addresses"], dict):
        a = dict(e["addresses"])
        a.update({k: v for k, v in facts["addresses"].items() if k in ("last", "lan", "mdns", "tailscale")})
        probe["addresses"] = a
    for k in ("macs", "managers"):
        if k in facts:
            probe[k] = facts[k]
    if "manageable" in facts:
        probe["manageable"] = facts["manageable"]
    if "hostKeys" in facts and e.get("link"):
        keys = clean_keys(facts["hostKeys"])
        old = e["link"].get("hostKeys") or []
        # the key pairing pinned stays (only the computer's own authenticated report can add the other types)
        probe["link"] = dict(e["link"], hostKeys=list(dict.fromkeys(old[:1] + keys)) if keys else old)
    if "checkedHostKeys" in facts and e["id"].startswith("m-"):
        # a key a person checked by its fingerprint is added to the ones checked before (a computer has one per type)
        probe["checkedHostKeys"] = list(dict.fromkeys(clean_keys(facts["checkedHostKeys"]) + (e.get("checkedHostKeys") or [])))
    cleaned = clean_entry(probe)
    if cleaned is None:
        return e
    # a value that didn't check out is ignored, never stored as "unknown" over what was known
    for k in ("hostname", "kind", "managePub"):
        if facts.get(k) and not cleaned[k]:
            cleaned[k] = e[k]
    if isinstance(facts.get("addresses"), dict):
        for k in ("last", "mdns", "tailscale"):
            if facts["addresses"].get(k) and not cleaned["addresses"][k]:
                cleaned["addresses"][k] = e["addresses"][k]
    for k in LOCAL_KEYS:
        if k in e:
            cleaned[k] = e[k]
    if e.get("link") and cleaned.get("link") and "paired" in e["link"]:
        cleaned["link"]["paired"] = e["link"]["paired"]
    return with_compat(cleaned)


def rename(ident: str, label: str) -> dict:
    me = self_id()
    with editing() as doc:
        e = find(doc, ident)
        if e is None:
            raise KeyError(ident)
        e["label"] = safe_label(label)
        _bump(e, me)
        with_compat(e)
        if (e.get("link") or {}).get("paired"):
            certify_member(doc, e)
    changed()
    return e


def set_address(ident: str, address: str) -> dict:
    if not valid_host(address):
        raise ValueError("That address has characters an address can't have.")
    me = self_id()
    with editing() as doc:
        e = find(doc, ident)
        if e is None:
            raise KeyError(ident)
        e["chosenAddress"] = address                    # a choice (rev): a found address never replaces it
        e["addresses"]["last"] = address
        if valid_ip(address) and address not in e["addresses"]["lan"]:
            e["addresses"]["lan"] = [address] + e["addresses"]["lan"][:7]
        _bump(e, me)
        _fbump(e, me)
        with_compat(e)
    changed()
    return e


def manage_state(ident: str, state: str) -> dict:
    if state not in MANAGE_STATES:
        raise ValueError(f"state is one of {', '.join(MANAGE_STATES)}")
    with editing() as doc:
        e = find(doc, ident)
        if e is None:
            raise KeyError(ident)
        if e["manage"]["state"] != state:
            e["manage"] = {"state": state, "since": now()}
    return e


def merge_pair(keep: str, drop: str) -> dict:
    """Two entries are one computer (the person said so): the kept one takes the dropped one's name and old ids,
    and the dropped one is removed everywhere."""
    me = self_id()
    with editing() as doc:
        k, d = find(doc, keep), find(doc, drop)
        if k is None or d is None or k is d:
            raise KeyError(f"{keep} / {drop}")
        k["label"] = k["label"] or d["label"]
        k["aliases"] = list(dict.fromkeys(k["aliases"] + [d["id"]] + d["aliases"]))[:8]
        k["user"] = k["user"] or d["user"]
        if k["id"].startswith("m-") and d["id"].startswith("m-"):
            # one machine: the narrower answer about which computers manage it wins
            narrow = {"mine": 0, "ask": 1, "": 2, "all": 3}
            k["fleetAccess"] = min(k.get("fleetAccess") or "", d.get("fleetAccess") or "", key=lambda v: narrow.get(v, 0))
        _bump(k, me)
        with_compat(k)
        doc["machines"].remove(d)
        doc["removed"].insert(0, {"id": d["id"], "gen": d["gen"], "rev": d["rev"] + 1, "by": me[4:], "removed": now(),
                                  "revoked": False, "label": display_name(d), "aliases": d["aliases"], "managePub": d.get("managePub") or ""})
        doc["suggestions"] = [s for s in doc["suggestions"] if drop not in (s["keep"], s["drop"])]
    changed()
    return k


def access_names(doc: dict) -> list:
    """The computers that get their own sign-in key on a machine whose person said "all": this one, then every live
    fleet computer (by name). Computers that join the fleet later get one too."""
    others = sorted((display_name(e) for e in doc["machines"] if e.get("link")), key=str.casefold)
    return ["This computer"] + others


def fleet_access(ident: str, value: str | None = None) -> dict:
    """Which computers manage a machine that isn't a paired Starchaser one: the person's answer, asked when it is
    added (decision 2026-10-19 #16). value None only reports. "all" puts every fleet computer's key there (relay),
    "mine" keeps (or takes back to) only this computer's. Only the computer that added it records the answer, and
    "all" is refused while Settings › Fleet says only that computer manages machines it adds."""
    me = self_id()
    with editing() as doc:
        e = find(doc, ident)
        if e is None:
            raise KeyError(ident)
        if not e["id"].startswith("m-"):
            raise ValueError("Only a computer added over SSH has this choice. A paired Starchaser computer asks on its own screen.")
        owner = e.get("addedBy") or ""
        mine = owner == me[4:]
        limited = e.get("onlyMineManages") is True or (mine and doc["local"].get("onlyMineManages") is True)
        if value is not None:
            if value not in ("all", "mine"):
                raise ValueError("Choose all or mine.")
            if owner and not mine:
                other = find(doc, "dev-" + owner)
                raise ValueError(f"Only {display_name(other) if other else 'the computer that added it'} can change who manages {display_name(e)}.")
            if value == "all" and limited:
                raise ValueError("Settings > Fleet says only this computer manages computers it adds, so the rest of your fleet can't get access.")
            if e.get("fleetAccess") != value or (not owner and value == "mine"):
                e["fleetAccess"] = value
                if not owner:
                    e["addedBy"] = me[4:]                # (an unknown adder: the person answering here takes it on)
                _bump(e, me)
                with_compat(e)
                changed_now = True
            else:
                changed_now = False
        else:
            changed_now = False
        state = e.get("fleetAccess") or ("mine" if limited else "all")
        res = {"ok": True, "id": e["id"], "name": display_name(e), "fleetAccess": e.get("fleetAccess") or "",
               "state": state, "onlyMine": limited, "canChange": mine or not owner,
               "fleet": access_names(doc)}         # (who gets access with "all", now; later members too)
    if changed_now:
        changed()
        maybe_relay()
    return res


def tombstone(ident: str, revoked: bool = False, recovery=None, expected=None) -> dict:
    """Remove a computer from the list here (a removal record that wins everywhere). remove_flow() also tells the
    others and takes back its keys."""
    me = self_id()
    with editing() as doc:
        e = find(doc, ident)
        old = next((t for t in doc["removed"] if t["id"] == ident), None)
        if expected is not None and (not e or (e["gen"], e.get("added")) != expected):
            raise ValueError("This computer changed since removal was scheduled. Nothing was removed.")
        if e is None and old is None:
            raise KeyError(ident)
        if e is not None:
            doc["machines"].remove(e)
            t = {"id": e["id"], "gen": e["gen"], "rev": e["rev"] + 1, "by": me[4:], "removed": now(), "revoked": revoked,
                 "label": display_name(e), "aliases": e["aliases"], "managePub": e.get("managePub") or ""}
            doc["removed"] = [x for x in doc["removed"] if x["id"] != e["id"]]
        else:
            t = dict(old, rev=old["rev"] + 1, by=me[4:], revoked=old["revoked"] or revoked, removed=now())
            doc["removed"].remove(old)
        if recovery is not None:
            checked = clean_tombstone(dict(t, recovery=recovery))
            if not checked or "recovery" not in checked:
                raise ValueError("That recovery request is invalid. Nothing was removed.")
            t["recovery"] = checked["recovery"]
        records = doc["security"]["records"]
        seen = max((r["body"]["sequence"] for r in records if r["body"]["issuer"] == ident.removeprefix("dev-")), default=0)
        allowed = [hashlib.sha256(_signed_bytes(r).encode()).hexdigest() for r in records
                   if r["body"]["issuer"] == ident.removeprefix("dev-")]
        _sign_record(doc, "remove", {"tombstone": t, "seen": seen, "allowed": allowed})
        doc["removed"].insert(0, t)
        doc["suggestions"] = [s for s in doc["suggestions"] if t["id"] not in (s["keep"], s["drop"])]
        prune_vouched(doc, me)                          # what only it passed on after its removal (none, removed here)
    changed()
    return t


def set_local(**kw) -> dict:
    with editing() as doc:
        doc["local"].update(kw)
        return dict(doc["local"])


def set_trust(option: str, enabled: bool) -> dict:
    """Keep the local choice, and share its policy on SSH machines this computer added. Unknown owners keep the
    default. A revision makes a changed policy reach members that were offline when the switch changed."""
    field = TRUST_OPTIONS[option]
    me = self_id()
    with editing() as doc:
        doc["local"][field] = enabled
        if field == "onlyMineManages":
            for e in doc["machines"]:
                if e["id"].startswith("m-") and e.get("addedBy") == me[4:] and e.get(field) != enabled:
                    e[field] = enabled
                    _bump(e, me)
    changed()
    if field == "onlyMineManages":
        maybe_relay()
    return {"ok": True, field: enabled}


def changed() -> None:
    """Something here changed: send it to the rest of the fleet in the background (never waits on the network)."""
    if NO_SPAWN:
        return
    link = link_path()
    if not link:
        return
    with contextlib.suppress(OSError):
        subprocess.Popen([sys.executable, link, "fleet-sync"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


# ---------------------------------------------------------------------------------------------- what's sent
def host_keys() -> list:
    out = []
    for f in sorted(Path("/etc/ssh").glob("ssh_host_*_key.pub")):
        with contextlib.suppress(OSError):
            k = " ".join(f.read_text().split()[:2])
            if KEY_RE.fullmatch(k):
                out.append(k)
    ed = [k for k in out if k.startswith("ssh-ed25519 ")]
    return ed + [k for k in out if k not in ed]         # the one pairing pins first


def personal_pub() -> str:
    for n in ("id_ed25519", "id_ecdsa", "id_rsa"):
        with contextlib.suppress(OSError):
            k = " ".join((SSH_DIR / f"{n}.pub").read_text().split()[:2])
            if KEY_RE.fullmatch(k):
                return k
    return ""


def ensure_personal_key() -> tuple:
    """(public key, made now): this account's own sign-in key, which Mission Control uses. Made (without a passphrase,
    like the link's own key) only when the account has none."""
    pub = personal_pub()
    if pub:
        return pub, False
    SSH_DIR.mkdir(mode=0o700, exist_ok=True)
    key = SSH_DIR / "id_ed25519"
    if key.exists():
        r = sh("ssh-keygen", "-y", "-f", str(key), timeout=10)
        if r.returncode == 0 and KEY_RE.fullmatch(" ".join(r.stdout.split()[:2])):
            write_atomic(key.with_suffix(".pub"), r.stdout.strip() + "\n", 0o644)
            return " ".join(r.stdout.split()[:2]), True
        return "", False
    r = sh("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", f"{ME}@{socket.gethostname()} (Starchaser fleet)", "-f", str(key), timeout=20)
    return (personal_pub(), True) if r.returncode == 0 else ("", False)


def authorized_managers() -> list:
    """The fleet computers whose personal key may sign in here (their device ids)."""
    try:
        lines = AUTH.read_text().splitlines()
    except OSError:
        return []
    return sorted({m.group(1) for line in lines if (m := re.search(re.escape(MANAGE_TAG) + r"([0-9a-f]{16})\s*$", line))})


def os_facts() -> dict:
    try:
        osr = dict(line.split("=", 1) for line in Path("/etc/os-release").read_text().splitlines() if "=" in line)
    except OSError:
        osr = {}
    return {"id": osr.get("ID", "").strip('"')[:32], "label": scrub(osr.get("PRETTY_NAME", "").strip('"'))[:60]}


_RECOVERY_CLIENT = None


class _FleetModule:
    def __getattr__(self, name):
        try:
            return globals()[name]
        except KeyError:
            raise AttributeError(name) from None


def recovery_client():
    global _RECOVERY_CLIENT
    if _RECOVERY_CLIENT is None:
        import importlib.machinery
        import importlib.util
        path = Path(__file__).resolve().with_name("starchaser-fleet-safety")
        loader = importlib.machinery.SourceFileLoader("fleet_recovery_client", str(path))
        spec = importlib.util.spec_from_loader(loader.name, loader)
        _RECOVERY_CLIENT = importlib.util.module_from_spec(spec)
        loader.exec_module(_RECOVERY_CLIENT)
        _RECOVERY_CLIENT._F = _FleetModule()
    return _RECOVERY_CLIENT


def self_facts(link=None) -> dict:
    """What this computer says about itself to the rest of the fleet (each one trusts it because it came over the
    paired link, pinned to this computer's host key)."""
    host = socket.gethostname()
    lan, ts, macs, kind = [], "", [], ""
    if link is not None:
        lan, ts = link.lan_addresses(), link.tailscale_ip()
        macs = [w["mac"] for w in link.wake_info() if isinstance(w, dict) and link.valid_mac(w.get("mac"))]
        kind = link.kind()
    doc = load()
    return {"hostname": host if HOST_RE.fullmatch(host) else "", "kind": kind, "os": os_facts(),
            "addresses": {"lan": lan, "tailscale": ts, "mdns": f"{host}.local" if HOST_RE.fullmatch(host) else ""},
            "macs": macs, "hostKeys": host_keys(), "managePub": personal_pub(), "recovery": recovery_client().capability(),
            "manageable": bool(doc["local"].get("manageConsent")), "managers": authorized_managers() if doc["local"].get("manageConsent") else []}


def payload(facts: dict | None = None) -> dict:
    doc = load()
    return {"v": VERSION, "from": self_id(), "self": facts or {}, "fleet": doc.get("fleet") or {"tag": ""},
            "machines": [strip_local(e) for e in doc["machines"]], "removed": doc["removed"], "security": security_payload(), "fleetIdentity": doc["security"].get("identity")}


def merge_in(data, sender: str) -> bool:
    """A list another fleet computer sent (sender: its device id, known from the link key it signed in with). True
    when anything changed here. Raises Refused when the sender was removed from the fleet."""
    if not isinstance(data, dict) or data.get("v") != VERSION:
        raise ValueError("not a fleet list")
    if "security" in data:
        was_left = load()["local"].get("left")
        trusted_sender = find(load(), "dev-" + sender)
        accept_security(data["security"], authenticated=sender if trusted_sender and trusted_sender.get("link") else False)
        if not was_left and load()["local"].get("left"):
            return True
    sid = "dev-" + sender
    me = self_id()
    if not DEV_RE.fullmatch(sender):
        raise ValueError("not a device id")
    # A computer never vouches for its own entry (no computer stores itself, so an honest list never holds it): its
    # facts come in "self", and its gen, keys and name only from the computers that paired it. Otherwise a computer
    # that was just reported lost could raise its own gen on a computer that hadn't heard yet and outrank the removal.
    machines = [e for e in (clean_entry(x) for x in (data.get("machines") or [])[:2000]) if e and e["id"] != sid]
    signed_removals = { _signed_bytes(clean_tombstone(r["body"]["value"]["tombstone"]))
                       for r in load()["security"]["records"] if r["body"]["kind"] == "remove" }
    removed = [t for t in (clean_tombstone(x) for x in (data.get("removed") or [])[:2000])
               if t and t["id"] != sid and (t["id"].startswith("m-") or _signed_bytes(t) in signed_removals)]
    for e in machines:                                  # never another computer's per-computer fields
        for k in LOCAL_KEYS:
            e.pop(k, None)
        if e.get("link"):
            e["link"].pop("paired", None)
    with editing() as doc:
        if doc["local"].get("left"):
            raise Refused("this computer was removed from its fleet")
        if (any(t["id"] == sid for t in doc["removed"]) or sid in (doc["local"].get("dropped") or {})) and not find(doc, sid):
            raise Refused("removed")
        changed_ = merge_docs(doc, machines, removed, me, sender)
        # a removal still to reach some computers: this one has heard of it now
        rp = doc["local"].get("revokePending")
        if isinstance(rp, dict):
            heard = {t["id"] for t in removed}
            for tid in list(rp):
                if tid in heard:
                    rp[tid] = [x for x in rp[tid] if not (isinstance(x, dict) and x.get("id") == sender)]
                if not rp[tid]:
                    del rp[tid]
        if doc["local"].get("left"):
            # this computer was removed from the fleet: it isn't in one any more (the old list is kept aside)
            with contextlib.suppress(OSError):
                write_atomic(FLEET.with_name("fleet.json.left.bak"), json.dumps(doc, indent=1) + "\n")
            doc["machines"], doc["removed"], doc["suggestions"] = [], [], []
            doc["fleet"] = {"tag": ""}
            doc["local"]["dropped"], doc["local"]["revokePending"] = {}, {}
            return True
        changed_ = merge_tag(doc, data.get("fleet")) or changed_
        if data.get("fleetIdentity"):
            changed_ = accept_fleet_identity(doc, data["fleetIdentity"], sender) or changed_
        e = find(doc, sid)
        facts = data.get("self") if isinstance(data.get("self"), dict) else {}
        if e is not None and facts:
            new = apply_facts(e, {k: v for k, v in facts.items() if k != "managers" or isinstance(v, list)})
            if strip_local(new) != strip_local(e):
                new["frev"], new["fby"], new["updated"] = e.get("frev", 0) + 1, sender, now()
                doc["machines"][doc["machines"].index(e)] = with_compat(new)
                changed_ = True
        doc["local"].setdefault("syncedAt", {})[sender] = now()
    return changed_


# ---------------------------------------------------------------------------------------------- ~/.ssh files
def authkeys(op: str, tag: str, key: str = "", options: str = "") -> list:
    """Add (replacing any line with the same tag), remove or list tagged lines of ~/.ssh/authorized_keys, under the
    lock starchaser link and Mission Control share (two writers without it lose each other's lines)."""
    if not re.fullmatch(r"[\w.:@-]{1,80}", tag):
        raise ValueError("bad tag")
    with ssh_lock():
        try:
            lines = AUTH.read_text().splitlines()
        except FileNotFoundError:
            lines = []
        mine = [line for line in lines if line.rstrip().endswith(" " + tag)]
        if op == "list":
            return mine
        keep = [line for line in lines if line not in mine]
        if op == "add":
            k = " ".join(key.split()[:2])
            if not KEY_RE.fullmatch(k):
                raise ValueError("bad key")
            keep.append(f"{options + ' ' if options else ''}{k} {tag}")
        elif op != "remove":
            raise ValueError("op is add, remove or list")
        if keep != lines:
            SSH_DIR.mkdir(mode=0o700, exist_ok=True)
            write_atomic(AUTH, "\n".join(keep) + ("\n" if keep else ""), 0o600)
        return [line for line in keep if line.rstrip().endswith(" " + tag)]


def end_fleet_sessions() -> dict:
    """Logind does not record which SSH key opened a session. Close this account's SSH sessions when access is
    withdrawn; other accounts and the local desktop are left alone. Keep failures pending for the next reconcile."""
    listing = sh("loginctl", "list-sessions", "--no-legend")
    complete, ended = listing.returncode == 0, 0
    for row in listing.stdout.splitlines():
        fields = row.split()
        if not fields or not re.fullmatch(r"[\w-]+", fields[0]):
            continue
        sid = fields[0]
        result = sh("loginctl", "show-session", sid, "-p", "User", "-p", "Service")
        info = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
        if result.returncode or "User" not in info or "Service" not in info:
            complete = False
        elif info.get("User") == str(os.getuid()) and info.get("Service") == "sshd":
            if sh("loginctl", "terminate-session", sid).returncode:
                complete = False
            else:
                ended += 1
    set_local(sessionRevokePending=not complete)
    return {"ended": ended, "complete": complete}


def other_signin_keys() -> list:
    try:
        lines = AUTH.read_text().splitlines()
    except FileNotFoundError:
        return []
    return [fp(m.group(0)) for line in lines if not line.lstrip().startswith("#") and "starchaser-" not in line
            and (m := KEY_RE.search(line))]


def authorized_key_public(line: str) -> str:
    """The actual public key, excluding quoted SSH options and comments."""
    try:
        words = shlex.split(line, comments=True)
    except ValueError:
        return ""
    for index in range(min(2, len(words) - 1)):  # the key starts the line or follows one SSH-options field
        key = " ".join(words[index:index + 2])
        if KEY_RE.fullmatch(key):
            return key
    return ""


ACTIVITY = STATE_DIR / "fleet-activity.json"


def activity() -> list:
    try:
        value = json.loads(ACTIVITY.read_text())
        return value.get("events", [])[:200] if isinstance(value, dict) else []
    except (OSError, ValueError):
        return []


def record_activity(source_id: str, name: str, action: str) -> dict:
    name, action = safe_label(name, 80), safe_label(action, 120)
    if not name or not action or not re.fullmatch(r"[0-9a-f]{16}|mission-control", source_id):
        raise ValueError("That isn't a fleet activity record.")
    stamp = now()
    day = time.strftime("%Y-%m-%d", time.localtime(stamp))
    with _flock(STATE_DIR / "fleet-activity.lock", "activity"):
        try:
            document = json.loads(ACTIVITY.read_text())
        except (OSError, ValueError):
            document = {}
        events = document.get("events", []) if isinstance(document, dict) else []
        first = not any(e.get("day") == day and e.get("sourceId") == source_id and e.get("source") == name for e in events)
        event = {"time": stamp, "day": day, "sourceId": source_id, "source": name, "action": action}
        # Polling is recorded at most once a day; actions are always recorded.
        if action != "Signed in" or first:
            write_atomic(ACTIVITY, json.dumps({"events": [event, *events][:200]}) + "\n", 0o600)
    member = find(load(), "dev-" + source_id)
    joined = (member.get("link") or {}).get("paired", member.get("added", 0)) if member else 0
    if first and stamp - joined >= 600:
        token = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-notifications" / "token"
        try:
            with token.open() as credential:
                subprocess.Popen([tool_path("starchaser-notify"), f"--credential-fd={credential.fileno()}", "-a", "Starchaser", "-i", "network-workgroup",
                                  "-h", "string:x-starchaser-settings:fleet", f"{name} connected to this computer",
                                  "It's in your fleet. Settings › Fleet shows what it did."],
                                 pass_fds=(credential.fileno(),), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except OSError:
            pass
    return {"ok": True, "firstToday": first}


def signin_address() -> str:
    """The remote address OpenSSH gives the session (SSH_CONNECTION: client, client port, server, server port)."""
    words = os.environ.get("SSH_CONNECTION", "").split()
    return words[0] if words and valid_ip(words[0]) else ""


def notify_saved_key_signin(row: dict, address: str) -> None:
    """A sign-in with a key that belongs to no fleet computer. Once a day per key and address, a notice names the
    address and offers to remove the key. The waiting notice runs in the user manager, outside the SSH session, so
    removing the key (which ends this account's SSH sessions) does not end the notice first."""
    day = time.strftime("%Y-%m-%d", time.localtime(now()))
    seen = f"{row['fingerprint']} {address or '-'}"
    with _flock(STATE_DIR / "signin-usage.lock", "sign-in history"):
        target = STATE_DIR / "signin-notices.json"
        try:
            notices = json.loads(target.read_text())
        except (OSError, ValueError):
            notices = {}
        notices = {key: value for key, value in (notices if isinstance(notices, dict) else {}).items() if value == day}
        if seen in notices:
            return
        notices[seen] = day
        write_atomic(target, json.dumps(notices) + "\n", 0o600)
    if NO_SPAWN:
        return
    helper = [sys.executable, str(Path(__file__).resolve()), "_signin-notice", row["fingerprint"], address or "-"]
    if sh("systemd-run", "--user", "--collect", "--quiet", "--property=RuntimeMaxSec=1d", "--", *helper).returncode:
        with contextlib.suppress(OSError):
            subprocess.Popen(helper, start_new_session=True, stdin=subprocess.DEVNULL,
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def saved_key_notice_words(name: str, address: str) -> tuple:
    where = f" from {address}" if address and address != "-" else ""
    body = f"The key is named “{name}”. If this wasn't you, remove the key." if name and name != "Unnamed sign-in key" \
        else "If this wasn't you, remove the key."
    return f"Someone signed in to this computer{where} with a saved key", body


def signin_notice(fingerprint: str, address: str) -> int:
    """Show the saved-key notice and remove the key if its button is chosen."""
    row = next((r for r in signin_keys() if r["fingerprint"] == fingerprint), None)
    if not row:
        return 0
    title, body = saved_key_notice_words(row["name"], address)
    token = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-notifications" / "token"

    def notice(*words, wait=False):
        with token.open() as credential:
            return subprocess.run([tool_path("starchaser-notify"), f"--credential-fd={credential.fileno()}", "-a", "Starchaser",
                                   "-i", "security-medium", *(["-w", "-A", "remove=Remove this key"] if wait else []), *words],
                                  pass_fds=(credential.fileno(),), capture_output=True, text=True, timeout=86400).stdout.strip()
    try:
        if notice(title, body, wait=True) != "remove":
            return 0
    except (OSError, subprocess.SubprocessError):
        return 1
    try:
        remove_signin_key(fingerprint)
        done = ("Key removed", "It can't sign in to this computer anymore. Remote sign-ins to this account were ended.")
    except (OSError, ValueError) as error:
        done = ("Couldn't remove the key", str(error) or "Open Settings and remove it from Who can sign in here.")
    with contextlib.suppress(OSError, subprocess.SubprocessError):
        notice(*done)
    return 0


def record_signin(auth_info: Path, address: str = "") -> dict:
    """OpenSSH supplies this user-owned file after successful authentication; only public key use is recorded.
    A fleet computer's key goes to fleet activity; any other saved key gets its own notice (P2-11)."""
    path = Path(auth_info)
    with path.open() as stream:
        info = os.fstat(stream.fileno())
        if info.st_uid != os.getuid() or not stat.S_ISREG(info.st_mode) or info.st_size > 65536 or info.st_mode & 0o077:
            raise ValueError("That isn't this account's private SSH authentication record.")
        lines = stream.read(65537).splitlines()
    used = []
    for line in lines:
        key = authorized_key_public(line.removeprefix("publickey ")) if line.startswith("publickey ") else ""
        if key:
            used.append(fp(key))
    rows = {r["fingerprint"]: r for r in signin_keys()}
    with _flock(STATE_DIR / "signin-usage.lock", "sign-in history"):
        target = STATE_DIR / "signin-usage.json"
        try:
            known = json.loads(target.read_text())
        except (OSError, ValueError):
            known = {}
        for fingerprint in used:
            if fingerprint in rows:
                known[fingerprint] = now()
        known = {key: value for key, value in known.items() if key in rows}
        write_atomic(target, json.dumps(known) + "\n", 0o600)
    for fingerprint in used:
        row = rows.get(fingerprint)
        if row and row["machine"]:
            record_activity(row["machine"].removeprefix("dev-") if row["machine"].startswith("dev-") else "mission-control", row["name"], "Signed in")
        elif row:
            notify_saved_key_signin(row, address)
    return {"ok": True}


def signin_keys() -> list:
    """One row per actual public key, including untagged copies. Last use is explicit when not recorded."""
    doc = load()
    if doc.get("unreadable"):
        raise OSError("The fleet list couldn't be read.")
    lines = AUTH.read_text().splitlines() if AUTH.exists() else []
    rows = {}
    try:
        usage = json.loads((STATE_DIR / "signin-usage.json").read_text())
    except (OSError, ValueError):
        usage = {}
    recovery_names = {}
    if any("starchaser-recovery:" in line for line in lines):
        with contextlib.suppress(OSError, ValueError):
            recovery_names = {source["key"]: source for source in recovery_client().status().get("sources") or []}
    for line in lines:
        key = authorized_key_public(line)
        if not key:
            continue
        fingerprint = fp(key)
        if fingerprint in rows:
            rows[fingerprint]["copies"] += 1
            continue
        machine = next((e for e in doc["machines"] if key in (e.get("managePub"), (e.get("link") or {}).get("key"))), None)
        comment = safe_label(line.rsplit(key, 1)[-1].strip(), 100)
        restricted = bool(re.search(r'(?:^|,)command="', line.split(key, 1)[0]))
        rows[fingerprint] = {"fingerprint": fingerprint, "name": display_name(machine) if machine else (recovery_names.get(key) or {}).get("name") or comment or "Unnamed sign-in key",
                             "machine": machine["id"] if machine else "", "recoverySource": (recovery_names.get(key) or {}).get("id", ""), "copies": 1, "lastUsed": usage.get(fingerprint),
                             "scope": "Temporary help" if "starchaser-help:" in line else "Lost-computer recovery" if "starchaser-recovery:" in line else "Fleet connection" if restricted else "Full control"}
    return list(rows.values())


def remove_signin_key(fingerprint: str) -> dict:
    row = next((r for r in signin_keys() if r["fingerprint"] == fingerprint), None)
    if not row:
        raise ValueError("That sign-in key is no longer here.")
    if row["machine"]:
        return remove_flow(row["machine"])
    if row["scope"] == "Temporary help":
        return {"ok": True, "sessions": load_link().end_help()}
    if row.get("recoverySource"):
        recovery_client().post("revoke", source=row["recoverySource"])
    with ssh_lock():
        lines = AUTH.read_text().splitlines() if AUTH.exists() else []
        keep = [line for line in lines if not (key := authorized_key_public(line)) or fp(key) != fingerprint]
        write_atomic(AUTH, "\n".join(keep) + ("\n" if keep else ""), 0o600)
    return {"ok": True, "sessions": end_fleet_sessions()}


def reconcile_manage_keys() -> bool:
    """With consent on: exactly one manage line per live fleet computer that has a personal key; off: none. The list
    is read under the lock, so a reconcile that started before consent was turned off (or a computer removed) can't
    put its keys back afterward."""
    with ssh_lock():
        doc = load()
        want = {}
        links = {e["link"]["key"] for e in doc["machines"] if e.get("link") and e["link"].get("key")}
        retired = moved()                               # rule 36.4: no starchaser-manage: line stays
        if doc["local"].get("manageConsent") and not doc["local"].get("left") and not doc.get("unreadable") \
                and not retired:
            for e in doc["machines"]:
                # never a link key: that one is only ever allowed the forced command
                if e.get("link") and e.get("managePub") and e["managePub"] not in links:
                    want[e["link"]["device"]] = e["managePub"]
        try:
            lines = AUTH.read_text().splitlines()
        except FileNotFoundError:
            lines = []
        removed_ids = {t["id"] for t in _removal_records(doc)} - {e["id"] for e in doc["machines"]}
        banned = {t.get("managePub") for t in _removal_records(doc) if t["id"] in removed_ids and t.get("managePub")}
        for record in doc["security"]["records"]:
            body = record["body"]
            if body["kind"] == "member" and body["value"]["id"] in removed_ids:
                banned.update(clean_keys([(body["value"].get("link") or {}).get("key", ""), body["value"].get("managePub", "")]))
        if not doc["local"].get("manageConsent") or doc["local"].get("left") or retired:
            banned.update(e["managePub"] for e in doc["machines"]
                          if e.get("link") and e.get("managePub") and e["managePub"] not in links)
        want = {dev: key for dev, key in want.items() if key not in banned}
        keep, have = [], {}
        revoked_copy = False
        for line in lines:
            if authorized_key_public(line) in banned:
                revoked_copy = True
                continue
            m = re.search(re.escape(MANAGE_TAG) + r"([0-9a-f]{16})\s*$", line)
            if not m:
                keep.append(line)
                continue
            dev = m.group(1)
            k = " ".join(line.split()[-3:-1])
            if want.get(dev) == k and dev not in have:
                have[dev] = k
                keep.append(line)
        for dev, k in sorted(want.items()):
            if dev not in have:
                keep.append(f"{k} {MANAGE_TAG}{dev}")
        if keep != lines:
            SSH_DIR.mkdir(mode=0o700, exist_ok=True)
            write_atomic(AUTH, "\n".join(keep) + ("\n" if keep else ""), 0o600)
            if revoked_copy:
                set_local(sessionRevokePending=True)
            for line in lines:
                match = re.search(re.escape(MANAGE_TAG) + r"([0-9a-f]{16})\s*$", line)
                if match and want.get(match.group(1)) != " ".join(line.split()[-3:-1]):
                    set_local(sessionRevokePending=True)
                    break
            return True
    return False


def reconcile_known_hosts() -> bool:
    """For every fleet computer that lets this one manage it: its verified host keys under each name it is reached by,
    tagged, so Mission Control's sign-in never asks about a fingerprint. Lines for computers that left go. (The list
    is read under the lock, like reconcile_manage_keys.)"""
    me = device_id()
    covered = fleet_known_keys() if moved() else set()    # rule 36.4: the fleet's known hosts cover these now
    with ssh_lock():
        doc = load()
        if doc.get("unreadable"):
            return False
        want = []
        for e in doc["machines"]:
            if doc["local"].get("left"):
                break
            if e["id"].startswith("m-"):
                # a computer that isn't a paired one: the keys a person checked by fingerprint on any fleet computer,
                # so Mission Control here never asks "is this the right computer?" again
                keys = e.get("checkedHostKeys") or []
                if not keys:
                    continue
            else:
                keys = (e.get("link") or {}).get("hostKeys") or []
                if not keys or not e.get("manageable") or me not in e.get("managers", []):
                    continue
            a = e["addresses"]
            names = list(dict.fromkeys(x for x in [e.get("chosenAddress"), a["last"], *a["lan"], a["mdns"], a["tailscale"], e["hostname"]] if x))
            if e["hostname"] and "." not in e["hostname"]:
                names.append(e["hostname"] + ".local")
            names = list(dict.fromkeys(names))
            if e["id"].startswith("m-") and e.get("port", 22) != 22:
                names = [f"[{n}]:{e['port']}" for n in names]      # (how ssh names a host on another port)
            if not names:
                continue
            for k in keys:
                if k not in covered:
                    want.append(f"{','.join(names)} {k} {HOSTS_TAG}{e['id']}")
        try:
            lines = KNOWN_HOSTS.read_text().splitlines()
        except FileNotFoundError:
            lines = []
        # Mission Control pins the key of a computer that isn't a paired Starchaser one under its own tag
        # (starchaser-mc:<id>): those lines go too once the computer is removed, on every computer the removal reaches
        gone = {r["id"] for r in doc.get("removed", []) if r.get("id")}
        gone |= {a for r in doc.get("removed", []) for a in (r.get("aliases") or [])}
        gone |= {k for k in (doc["local"].get("dropped") or {}) if not find(doc, k)}     # (dropped: as if removed)
        mc_gone = re.compile(r"\s" + re.escape(MC_HOSTS_TAG) + r"(\S+)\s*$")
        keep = [line for line in lines if not re.search(re.escape(HOSTS_TAG) + r"\S+\s*$", line)
                and not ((m := mc_gone.search(line)) and m.group(1) in gone)] + want
        # ssh itself adds the computer's other key types under the same names, untagged (UpdateHostKeys, on any
        # sign-in that the tagged line let through): those go with the tagged ones, or a removed (lost) computer
        # was still trusted at its address
        dropped = {n for line in lines if line not in keep and (re.search(re.escape(HOSTS_TAG) + r"\S+\s*$", line)
                                                                 or mc_gone.search(line))
                   for n in line.split()[0].split(",")} - {n for line in want for n in line.split()[0].split(",")}
        if dropped:
            keep = [line for line in keep if line in want or re.search(r"\s(?:" + re.escape(HOSTS_TAG) + "|" + re.escape(MC_HOSTS_TAG) + r")\S+\s*$", line)
                    or line.lstrip().startswith("#") or not line.split()
                    or not set(line.split()[0].split(",")) & dropped]
        if keep != lines:
            SSH_DIR.mkdir(mode=0o700, exist_ok=True)
            write_atomic(KNOWN_HOSTS, "\n".join(keep) + ("\n" if keep else ""), 0o644)
            return True
    return False


def say_on_screen(link, doc: dict) -> None:
    """What the fleet did here by itself that the person should hear about, each said once: this computer was removed
    from its fleet, or a computer was dropped because only a removed one ever vouched for it."""
    if not hasattr(link, "notify_desktop") or not hasattr(link, "session_env"):
        return
    left = doc["local"].get("left")
    notes = []
    if isinstance(left, dict) and not left.get("noted"):
        who = left.get("byName") or "another of your computers"
        notes.append(("This computer left your fleet",
                      f"It was removed on {who}, so your other computers no longer trust it. To use it with them again, "
                      "join your fleet again in Settings > Fleet." if not left.get("revoked") else
                      "It was reported sold, lost or stolen on another of your computers, so they no longer trust it."))
    drops = {k: v for k, v in (doc["local"].get("dropped") or {}).items() if isinstance(v, dict) and not v.get("noted")}
    for v in drops.values():
        why = " and ".join(v.get("because") or []) or "a removed computer"
        notes.append((f"{v.get('label') or 'A computer'} was taken out of your fleet",
                      f"Only {why}, which was removed from your fleet, ever vouched for it, so your computers no longer "
                      "trust it. If it's yours, join it to your fleet again in Settings > Fleet."))
    if not notes:
        return
    with editing() as d:
        if isinstance(d["local"].get("left"), dict):
            d["local"]["left"]["noted"] = True
        for k in drops:
            if isinstance((d["local"].get("dropped") or {}).get(k), dict):
                d["local"]["dropped"][k]["noted"] = True
    env = link.session_env()
    for title, body in notes:
        with contextlib.suppress(Exception):
            link.notify_desktop(env, "network-workgroup", html_escape(title), html_escape(body))


def html_escape(t: str) -> str:
    return str(t).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def reconcile(link=None) -> dict:
    """Make this computer match the list: paired devices for every Starchaser computer in the fleet (and none for one
    that was removed), the manage keys this computer allows, the host keys it trusts, and this account's Mission
    Control state for each computer. Safe to run any time; it only changes what differs."""
    done = {"adopted": [], "forgot": [], "keys": False, "hosts": False}
    doc = load()
    if doc.get("unreadable"):
        return done
    # Reapply the verified local history without routing it through the untrusted envelope's record limit.
    accept_security({"records": []})
    doc = load()
    me = device_id()
    if link is not None and link.peers_file_ok():       # (a file that didn't read lists nobody: never act on that)
        peers = {p["id"]: p for p in link.load_peers()}
        left = doc["local"].get("left")
        if left and left.get("recovery") and not left.get("recoveryDelivered"):
            try:
                outcome = recovery_client().receive_document(left["recovery"])
                if outcome.get("ok") is not False:
                    with editing() as current:
                        if current["local"].get("left"):
                            current["local"]["left"]["recoveryDelivered"] = True
            except (OSError, ValueError):
                pass
        removed = {t["id"][4:]: t for t in doc["removed"] if t["id"].startswith("dev-")}
        live = {e["link"]["device"]: e for e in doc["machines"] if e.get("link")}
        dropped = _dropped_devs(doc)
        for pid in list(peers):
            if peers[pid].get("role") in ("helper", "help-target"):
                continue
            if left or ((pid in removed or pid in dropped) and pid not in live):
                # (dropped: nobody that still counts vouches for it, so it is trusted nowhere, as if removed)
                if not left:
                    with contextlib.suppress(OSError, ValueError):
                        recovery_client().post("revoke", source=pid)
                link.forget_device(pid, revoked=bool(left and left.get("revoked")) or bool(removed.get(pid, {}).get("revoked"))
                                   or pid in dropped)
                done["forgot"].append(pid)
        joined_at = counter(doc["local"].get("joinedAt"))
        if not left:
            for pid, e in live.items():
                if pid == me or not e["link"].get("key"):
                    continue
                ed = next((k for k in e["link"]["hostKeys"] if k.startswith("ssh-ed25519 ")), "")
                p = peers.get(pid)
                if not ed or not e.get("user"):
                    continue
                if p is None or p.get("key") != e["link"]["key"] or p.get("hostkey") != ed:
                    # a computer that was in the fleet before this one joined it didn't "just join": no notification
                    # about it on the computer that joined (in its first hour)
                    old = bool(joined_at) and now() - joined_at < 3600 and 0 < e.get("added", 0) < joined_at
                    peer = {"id": pid, "name": e["hostname"] or display_name(e), "shown": display_name(e), "user": e["user"], "kind": e["kind"],
                            "key": e["link"]["key"], "hostkey": ed}
                    try:
                        link.adopt(peer, best_address(e), quiet=old)
                    except TypeError:                   # (an older link without quiet)
                        link.adopt(peer, best_address(e))
                    done["adopted"].append(pid)
                elif hasattr(link, "learn_addresses"):      # moved: where the rest of the fleet (or the person) says it is
                    a = e["addresses"]
                    link.learn_addresses(pid, e.get("chosenAddress") or "", [a["last"], *a["lan"], a["mdns"]], a["tailscale"])
            for pid, p in peers.items():                # a pairing the list never heard of (a crash between the two)
                if p.get("role") in ("helper", "help-target"):
                    continue
                if pid not in live and pid not in removed and pid not in dropped and pid != me:
                    if p.get("adopted"):
                        # trusted here only because the list had it: with no entry left (its dropped record aged
                        # out), it never comes back as if this computer had checked it
                        link.forget_device(pid, revoked=True)
                        done["forgot"].append(pid)
                    else:
                        upsert_paired(p, p.get("address") or "", "pairing")
        doc = load()
        say_on_screen(link, doc)
    # a computer whose person let the fleet manage it lets in every fleet computer's personal key; this account needs
    # one to be let in too, or Mission Control here can't manage it (paired with only one of them, it was "not
    # managed" on every other one). Made once, then sent with the list
    # (a machine that isn't a paired one counts too: the fleet passes this account's key on to it)
    if not doc["local"].get("left") and not personal_pub() and any((e.get("link") and e.get("manageable")) or e["id"].startswith("m-")
                                                                    for e in doc["machines"]):
        if ensure_personal_key()[0]:
            changed()
    done["keys"] = reconcile_manage_keys()
    if load()["local"].get("sessionRevokePending"):
        end_fleet_sessions()
    done["hosts"] = reconcile_known_hosts()
    with editing() as d:                                # this account's Mission Control state, from what they report
        for e in d["machines"]:
            if not e.get("link"):
                continue
            st = e["manage"]["state"]
            if e.get("manageable") and me in e.get("managers", []):
                new = "ready"
            elif st in ("ready",):
                new = "none"
            else:
                new = st
            if new != st:
                e["manage"] = {"state": new, "since": now()}
    with contextlib.suppress(OSError, ValueError):
        recovery_client().sync_keys()
    maybe_relay()
    return done


# ---------------------------------------------------------------------------------------------- keys on other computers
# A computer that isn't a paired Starchaser one (an m- entry: Fedora, Ubuntu, ...) has no link of its own, so it can't
# hear the fleet list. The person signed in to it once with its password (Mission Control's Add a machine), and then
# answered, on a question that names the computers, whether the rest of the fleet may manage it too (fleetAccess, decision
# 2026-10-19 #16). Until that OK only the adding computer's key goes there. With it, any fleet computer that can already
# sign in there passes the fleet's personal keys on: each live fleet computer's key goes in, tagged starchaser-manage:<device id>, and a removed
# computer's key comes out (also the untagged line the first sign-in added, when the remover was the one that added
# it). Done with this account's own key, the host key checked strictly against the one the person confirmed, and the
# fixed text below run there by sh. It never uses sudo and touches nothing but ~/.ssh/authorized_keys there. What was
# done is recorded on the entry (managers), so the other computers stop trying; a machine nobody can reach keeps its old
# keys until one of them does (tried again on each reconcile, at most every 10 minutes per machine). A computer that
# relayed before does it again whenever its own request changes (a removal or a new key it heard of later), even when
# the list says done: two computers relaying at once with different lists can't leave a removed key there for good.
# A copy of a fleet computer's key without the tag (the first sign-in put it there) is replaced by the tagged line, so
# removing the machine later takes every fleet key off it. Signed in with no login name chosen, the account it reached
# is kept in the list, so every computer in the fleet signs in to that account (where the keys are).
RELAY_SCRIPT = r"""umask 077
f="$HOME/.ssh/authorized_keys"
mkdir -p "$HOME/.ssh" && touch "$f" || exit 3
r=$(mktemp "$HOME/.ssh/.starchaser-relay.XXXXXX") || exit 4
t=$(mktemp "$HOME/.ssh/.starchaser-keys.XXXXXX") || { rm -f "$r"; exit 4; }
trap 'rm -f "$r" "$t"' EXIT
cat > "$r"
awk 'FNR == NR { if ($1 == "drop-tag") dt[$2] = 1; else if ($1 == "drop-key") dk[$2 " " $3] = 1; else if ($1 == "add") { n++; ad[n] = $2 " " $3 " " $4; at[$4] = 1 }; next }
{ d = 0; if (NF && (($NF in dt) || ($NF in at))) d = 1; for (i = 1; i < NF; i++) if (($i " " $(i + 1)) in dk) d = 1; if (!d) print }
END { for (i = 1; i <= n; i++) print ad[i] }' "$r" "$f" > "$t" || exit 5
cat "$t" > "$f" || exit 6
echo "relayed $(id -un 2>/dev/null)"
"""
RELAY_RETRY = 600


def relay_plan(doc: dict, my_pub: str | None = None, state: dict | None = None) -> list:
    """The machines that aren't paired Starchaser ones whose fleet keys are out of date: for each, the request the
    fixed text above reads (one line each: "v 1", "drop-tag <tag>", "drop-key <type> <key>", "add <type> <key> <tag>").
    Keys come only from the list: live fleet computers' personal keys (never a link key), this account's own."""
    if doc.get("unreadable") or doc["local"].get("left") or moved():
        return []                                       # rule 36.4: after the move, keys follow rule 35.5 instead
    me = device_id()
    pub = personal_pub() if my_pub is None else my_pub
    links = {e["link"]["key"] for e in doc["machines"] if e.get("link") and e["link"].get("key")}
    want = {}
    for e in doc["machines"]:
        if e.get("link") and e.get("managePub") and e["managePub"] not in links:
            want[e["link"]["device"]] = e["managePub"]
    if pub and pub not in links:
        want[me] = pub
    live = {e["link"]["device"] for e in doc["machines"] if e.get("link")} | {me}
    gone = [t for t in doc["removed"] if t["id"].startswith("dev-") and t["id"][4:] not in live]
    # (and the ones dropped because only a removed computer vouched for them: their keys go the same way)
    gone += [{"id": k, "managePub": v.get("managePub") or ""} for k, v in (doc["local"].get("dropped") or {}).items()
             if k.startswith("dev-") and k[4:] not in live and isinstance(v, dict)]
    drop_tags = sorted({t["id"][4:] for t in gone})
    drop_keys = sorted({t["managePub"] for t in gone if t.get("managePub")} - set(want.values()))
    # (a live computer's key is dropped too, wherever it is: an untagged copy goes, the tagged line below replaces it)
    drop_keys += sorted(set(want.values()))
    st = _relay_state() if state is None else state
    plan = []
    for e in doc["machines"]:
        if not e["id"].startswith("m-") or not want:
            continue
        owner = e.get("addedBy") or ""
        # (a machine whose person said "only this computer", or hasn't answered yet, gets only the adder's key)
        # (no known adder: "only the adder's key" would be no key at all, every fleet key stripped, this computer's too;
        # such a machine keeps the old default until someone answers, which makes that computer its adder)
        restricted = bool(owner) and (e.get("fleetAccess") in ("mine", "ask") or e.get("onlyMineManages") is True
                                      or (owner == me and doc["local"].get("onlyMineManages") is True))
        allowed = {d: k for d, k in want.items() if d == owner} if restricted else want
        # All members honor the adding computer's choice, even if another member does the relay. Remove the tags
        # we put there for other members, including ones whose personal key is no longer in this copy of the list.
        tags = sorted(set(drop_tags) | (live - {owner} - set(allowed) if restricted else set()))
        tag = "starchaser-help:" + e["helpOwner"] + ":" if e.get("helpOwner") else MANAGE_TAG
        request = "\n".join(["v 1"] + [f"drop-tag {tag}{d}" for d in tags] + [f"drop-key {k}" for k in drop_keys]
                            + [f"add {k} {tag}{d}" for d, k in sorted(allowed.items())]) + "\n"
        digest = hashlib.sha256(request.encode()).hexdigest()[:16]
        mine = st.get(e["id"]) if isinstance(st.get(e["id"]), dict) else {}
        if sorted(allowed) == sorted(e.get("managers") or []) and mine.get("ok") in (None, digest):
            continue                                    # (done already, by this computer or another one)
        a = e["addresses"]
        addrs = list(dict.fromkeys(x for x in [e.get("chosenAddress"), a["last"], *a["lan"], a["mdns"], a["tailscale"], e["hostname"]]
                                   if x and valid_host(x)))
        if addrs:
            plan.append({"id": e["id"], "name": display_name(e), "user": e.get("user") or "", "port": e.get("port") or 22,
                         "addresses": addrs, "managers": sorted(allowed), "request": request, "digest": digest})
    return plan


def relay_ssh(user: str, address: str, port: int, request: str) -> subprocess.CompletedProcess:
    """The fixed text, run there by sh with this account's own key, the host key checked strictly (never a question,
    never a first-use pin), and the request on its input."""
    import shlex
    target = f"{user}@{address}" if user else address
    return sh("ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UpdateHostKeys=no",
              "-o", "ConnectTimeout=8", "-p", str(port), "--", target, "sh -c " + shlex.quote(RELAY_SCRIPT),
              timeout=40, input=request)


def _relay_state() -> dict:
    try:
        d = json.loads(RELAY_STATE.read_text())
        return d if isinstance(d, dict) else {}
    except (OSError, ValueError, RecursionError):
        return {}


def _note_relay(ids_digests: dict, ok: bool = False) -> None:
    """Tried (digest, at: for the 10-minute wait), or done (ok: the request this computer last put there)."""
    st = _relay_state()
    for i, dg in ids_digests.items():
        cur = st.get(i) if isinstance(st.get(i), dict) else {}
        st[i] = dict(cur, ok=dg) if ok else dict(cur, digest=dg, at=now())
    with contextlib.suppress(OSError):
        write_atomic(RELAY_STATE, json.dumps(st) + "\n", 0o600)


def relay_keys() -> dict:
    """Pass the fleet's keys on to every machine in relay_plan this account can sign in to now. One run at a time."""
    out = {"ok": True, "relayed": [], "failed": []}
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    fd = os.open(STATE_DIR / "relay.lock", os.O_RDWR | os.O_CREAT, 0o600)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return dict(out, busy=True)
        plan = relay_plan(load())
        _note_relay({p["id"]: p["digest"] for p in plan})
        for p in plan:
            done, account = False, ""
            for addr in p["addresses"][:4]:
                r = relay_ssh(p["user"], addr, p["port"], p["request"])
                said = [ln.split() for ln in (r.stdout or "").splitlines() if ln.startswith("relayed")]
                if r.returncode == 0 and said:
                    done = True
                    account = said[-1][1] if len(said[-1]) > 1 else ""
                    break
                err = r.stderr or ""
                if "Permission denied" in err or "Host key verification failed" in err or "IDENTIFICATION HAS CHANGED" in err:
                    break                               # it answered: another address of it won't let this one in either
            if done:
                observe(p["id"], {"managers": p["managers"]})
                _note_relay({p["id"]: p["digest"]}, ok=True)
                if not p["user"] and USER_RE.fullmatch(account):
                    keep_account(p["id"], account)
                out["relayed"].append(p["name"])
            else:
                out["failed"].append(p["name"])
        return out
    finally:
        os.close(fd)


def keep_account(ident: str, user: str) -> None:
    """A machine added with no login name: the account the relay reached there (where the fleet's keys are now), so
    every computer in the fleet signs in to it, whatever its own account is called."""
    with editing() as doc:
        e = find(doc, ident)
        if e is None or e.get("user"):
            return
        e["user"] = user
        _bump(e, self_id())
        with_compat(e)
    changed()


def maybe_relay() -> None:
    """From reconcile: start relay-keys in the background when a machine's keys are out of date and it wasn't tried
    for the same keys in the last 10 minutes."""
    if NO_SPAWN:
        return
    try:
        plan = relay_plan(load())
    except OSError:
        return
    st = _relay_state()
    due = {p["id"]: p["digest"] for p in plan
           if not (isinstance(st.get(p["id"]), dict) and st[p["id"]].get("digest") == p["digest"]
                   and now() - counter(st[p["id"]].get("at")) < RELAY_RETRY)}
    if not due:
        return
    _note_relay(due)
    with contextlib.suppress(OSError):
        subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "relay-keys"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


# ---------------------------------------------------------------------------------------------- the network part
def link_path() -> str:
    """starchaser link next to this file, else the installed one."""
    for p in (Path(__file__).resolve().parent / "starchaser-link", Path(tool_path("starchaser-link"))):
        if p.exists():
            return str(p)
    return ""


_LINK = None


def load_link():
    global _LINK
    if _LINK is None:
        import importlib.machinery
        import importlib.util
        path = link_path()
        if not path:
            raise OSError("starchaser link isn't installed")
        loader = importlib.machinery.SourceFileLoader("starchaser_link", path)
        spec = importlib.util.spec_from_loader("starchaser_link", loader)
        mod = importlib.util.module_from_spec(spec)
        loader.exec_module(mod)
        _LINK = mod
    return _LINK


def remove_flow(ident: str, lost: bool = False, recovery=None, expected=None, drop_key: bool = False) -> dict:
    """Remove a computer from the fleet everywhere. Not lost: it is told first (so it leaves the fleet too). Lost:
    it is never contacted; every other computer drops its keys as soon as it hears (now, or when it is next on)."""
    doc = load()
    e = find(doc, ident)
    if e is None and not any(t["id"] == ident for t in doc["removed"]):
        raise KeyError(ident)
    name = display_name(e) if e else ident
    link = load_link()
    dev = e["link"]["device"] if e and e.get("link") else ""
    told = False
    if lost and e:
        paired = next((p for p in link.load_peers() if p.get("id") == dev), None) if dev else None
        with editing() as current:
            history = current["local"].get("lostComputers") or []
            if not any(row.get("id") == e["id"] for row in history):
                row = {"id": e["id"], "name": name, "peer": paired, "lastSeen": (paired or {}).get("lastSeen", 0),
                       "address": (paired or {}).get("address") or best_address(e), "enrollment": e.get("recovery") or {},
                       "request": None, "state": "removed", "requested": now()}
                current["local"]["lostComputers"] = [row] + history[:49]
    cleanup_hosts = None
    if drop_key and e and not dev and not lost:
        # Reconciliation may forget this identity as soon as the tombstone is saved.
        # Snapshot existing trust before that write; SSH still checks the same keys.
        with ssh_lock():
            try:
                cleanup_hosts = KNOWN_HOSTS.read_text()
            except FileNotFoundError:
                cleanup_hosts = ""
    t = tombstone(e["id"] if e else ident, revoked=lost, recovery=recovery, expected=expected)
    # Commit the generation-checked membership change before any optional remote key cleanup.
    # A stale delayed removal must leave both the current member and its keys intact.
    key_note = ""
    if cleanup_hosts is not None:
        try:
            with tempfile.NamedTemporaryFile(mode="w", prefix="starchaser-fleet-remove-hosts-") as pins:
                pins.write(cleanup_hosts)
                pins.flush()
                drop_managed_keys(e, known_hosts=Path(pins.name))
        except (OSError, ValueError):
            key_note = f"Your fleet's sign-in keys couldn't be taken off {name}; they are still there."
    if dev and not lost:
        told = link.tell_leaving(dev)
    res = link.fleet_sync(wait=True)
    reconcile(link)
    notes = []
    if dev and not lost and not told:
        notes.append("It was off, so it will find out when it's next on.")
    # every computer that didn't take the removal in: offline, an older build, turned this one away, or a bad answer
    ids = res.get("unreachedIds") or []
    pending = [p for p in res.get("unreached", [])]
    if len(ids) == len(pending):
        latest = load()
        for i in [*(res.get("needsUpdateIds") or []), *(res.get("refusedIds") or []), *(res.get("errorIds") or [])]:
            if i not in ids:
                other = find(latest, "dev-" + i)
                ids.append(i)
                pending.append(display_name(other) if other else i)
    if pending:
        with editing() as d:
            # cleared one by one as each of them hears of it (merge_in), so the screen stops saying so
            d["local"].setdefault("revokePending", {})[t["id"]] = [{"id": i, "name": n} for i, n in zip(ids, pending)] \
                if len(ids) == len(pending) else [{"id": "", "name": n} for n in pending]
        names = ", ".join(pending)
        notes.append(f"Still to hear about it: {names}. They drop it as soon as they're on.")
    warnings = []
    if load()["local"].get("sessionRevokePending"):
        warnings.append("Some existing remote sign-ins could not be ended. Turn off Remote login in Settings › Security to end them.")
    review = other_signin_keys() if lost else []
    if review:
        warnings.append(f"Review {len(review)} other sign-in key(s) in ~/.ssh/authorized_keys. A computer with full control "
                     "could have added them. Remove any you do not recognize, and change your password.")
    notes.extend(warnings)
    if key_note:
        notes.append(key_note)
    return {"ok": True, "warnings": warnings, "reviewKeys": review, "removed": t, "pending": pending, "unanswered": bool(dev and not lost and not told),
            "note": " ".join(notes)}



# Pending removals are local intent, never signed membership until the deadline.
REMOVAL_QUEUE = STATE_DIR / "fleet-removals.json"


def boot_id() -> str:
    return Path("/proc/sys/kernel/random/boot_id").read_text().strip()


def removal_queue() -> list:
    try:
        rows = json.loads(REMOVAL_QUEUE.read_text())
        return [r for r in rows if isinstance(r, dict) and r.get("boot") == boot_id()] if isinstance(rows, list) else []
    except (OSError, ValueError):
        return []


def pending_removals() -> list:
    with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
        rows = removal_queue()
        members = {m["id"]: m for m in load()["machines"]}
        current = [r for r in rows if not (r.get("state") == "done" and r.get("id") in members
                                          and members[r["id"]]["gen"] > r.get("gen", 0))]
        if current != rows:
            write_atomic(REMOVAL_QUEUE, json.dumps(current), 0o600)
        return [r for r in current if r.get("state") in ("pending", "committing", "error", "done")]


def schedule_remove(ident: str, drop_key: bool = False) -> dict:
    if ident == self_id():
        raise ValueError("This computer can't remove itself here.")
    with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
        entry = get(ident)
        if not entry:
            raise KeyError(ident)
        rows = removal_queue()
        old = next((r for r in rows if r.get("id") == entry["id"] and r.get("state") in ("pending", "committing")), None)
        if old:
            return old
        row = {"token": secrets.token_hex(16), "id": entry["id"], "name": display_name(entry),
               "gen": entry["gen"], "added": entry.get("added"), "boot": boot_id(),
               "deadline": time.time() + 30, "state": "pending", "dropKey": drop_key}
        rows = [r for r in rows if r.get("id") != entry["id"]][-49:] + [row]
        write_atomic(REMOVAL_QUEUE, json.dumps(rows), 0o600)
        if not NO_SPAWN:
            result = sh("systemd-run", "--user", "--collect", "--quiet",
                        "--unit=starchaser-fleet-remove-" + row["token"], "--property=RuntimeMaxSec=3min",
                        "--", sys.executable, str(Path(__file__).resolve()), "_remove-after", row["token"])
            if result.returncode:
                write_atomic(REMOVAL_QUEUE, json.dumps([r for r in rows if r is not row]), 0o600)
                raise ValueError("Couldn't schedule removal. Nothing was changed. Try again.")
        return row


def undo_remove(token: str) -> bool:
    with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
        rows = removal_queue()
        row = next((r for r in rows if r.get("token") == token and r.get("state") == "pending"), None)
        if not row:
            return False
        write_atomic(REMOVAL_QUEUE, json.dumps([r for r in rows if r is not row]), 0o600)
        return True


def commit_removal(token: str) -> bool:
    with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
        rows = removal_queue()
        row = next((r for r in rows if r.get("token") == token and r.get("state") == "pending"), None)
        if not row or time.time() < row["deadline"]:
            return False
        entry = get(row["id"])
        if not entry or entry["gen"] != row["gen"] or entry.get("added") != row.get("added"):
            write_atomic(REMOVAL_QUEUE, json.dumps([r for r in rows if r is not row]), 0o600)
            return False
        row["state"] = "committing"
        write_atomic(REMOVAL_QUEUE, json.dumps(rows), 0o600)
    # Undo can no longer succeed. No long network operation holds the queue lock.
    try:
        result = remove_flow(row["id"], expected=(row["gen"], row.get("added")), drop_key=bool(row.get("dropKey")))
    except Exception:
        with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
            rows = removal_queue()
            for r in rows:
                if r.get("token") == token:
                    r.update(state="error", error="Removal didn't finish. Check the computer and try again.")
            write_atomic(REMOVAL_QUEUE, json.dumps(rows), 0o600)
        raise
    with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
        rows = removal_queue()
        for r in rows:
            if r.get("token") == token:
                r.update(state="done", completed=time.time(), note=f"{row['name']} is out of your fleet."
                         + (" " + result.get("note", "") if isinstance(result, dict) and result.get("note") else ""))
        write_atomic(REMOVAL_QUEUE, json.dumps(rows), 0o600)
    return True


def dismiss_removal(token: str) -> bool:
    with _flock(STATE_DIR / "fleet-removals.lock", "removals"):
        rows = removal_queue()
        if not any(r.get("token") == token and r.get("state") in ("done", "error") for r in rows):
            return False
        write_atomic(REMOVAL_QUEUE, json.dumps([r for r in rows if r.get("token") != token]), 0o600)
        return True


def drop_managed_keys(entry: dict, known_hosts: Path | None = None) -> None:
    # A password-added computer has no fleet tool. Match public key material as well as
    # managed tags, using the same target lock as relay/reconcile. No key changes before Undo expires.
    pub = personal_pub()
    if not pub:
        raise ValueError("The sign-in key couldn't be read. Nothing was removed.")
    script = r'''set -f; set -- $1; type=$1; blob=$2
f="$HOME/.ssh/authorized_keys"; [ -f "$f" ] || exit 0
mkdir -p "$HOME/.local/state/starchaser" || exit 3
exec 9>"$HOME/.local/state/starchaser/ssh-files.lock"; flock -w 20 9 || exit 4
t="$f.remove.$$.tmp"
awk -v type="$type" -v blob="$blob" '$NF ~ /^starchaser-manage:[0-9a-f]+$/ { next } { found=0; for(i=1;i<NF;i++) if($i==type && $(i+1)==blob) found=1; if(!found) print }' "$f" > "$t" && chmod 600 "$t" && mv -f "$t" "$f"
'''
    trust = ["-o", "UserKnownHostsFile=" + str(known_hosts)] if known_hosts is not None else []
    argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "StrictHostKeyChecking=yes", *trust,
            "-p", str(entry.get("port") or 22), "--", (entry.get("user") + "@" if entry.get("user") else "") + best_address(entry),
            shlex.join(["sh", "-c", script, "remove", pub])]
    if sh(*argv, timeout=20).returncode:
        raise ValueError("The sign-in keys couldn't be removed. Try again when the computer is on.")


def remove_after(token: str) -> None:
    row = next((r for r in pending_removals() if r.get("token") == token), None)
    if row:
        time.sleep(max(0, row["deadline"] - time.time()))
        commit_removal(token)


def presence_path() -> Path:
    return Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-managed.json"


PRESENCE_PAGES = {"Overview", "Updates", "Services", "Accounts", "Terminal", "Files", "Network", "Power",
                  "Backups", "Firewall", "Vulnerabilities", "Practice targets", "Add-ons", "Fleet settings", "Mission Control", "Logs", "Storage", "Virtual machines"}


def presence_status() -> list:
    if not manage_consent_on():
        return []
    try:
        rows = json.loads(presence_path().read_text())
        return [r for r in rows if isinstance(r, dict) and r.get("boot") == boot_id()
                and 0 <= time.time() - r.get("at", 0) < 20] if isinstance(rows, list) else []
    except (OSError, ValueError, TypeError):
        return []


def presence(token: str, name: str, page: str) -> None:
    if not re.fullmatch(r"[A-Za-z0-9-]{1,80}", token) or page not in PRESENCE_PAGES | {"off"}:
        raise ValueError("That isn't a Mission Control session.")
    if page != "off" and not manage_consent_on():
        raise ValueError(NOT_ALLOWED)
    with _flock(presence_path().with_suffix(".lock"), "presence"):
        rows = [r for r in presence_status() if r.get("token") != token]
        if page != "off":
            rows.append({"token": token, "name": re.sub(r"[\x00-\x1f\x7f]", "", str(name))[:80] or "Another computer", "page": page,
                         "at": time.time(), "boot": boot_id()})
        write_atomic(presence_path(), json.dumps(rows[-20:]), 0o600)


def terminal_session(name: str, job=None) -> int:
    """Keep a visible lease for a real terminal, including after Mission Control closes."""
    if not manage_consent_on():
        print(NOT_ALLOWED, file=sys.stderr)
        return 4
    if job is None:
        job = [pwd.getpwuid(os.getuid()).pw_shell or "/bin/sh", "-l"]
    token = "terminal-" + secrets.token_hex(12)
    child = None
    handlers = {}
    try:
        presence(token, name, "Terminal")
        child = subprocess.Popen(job)
        # The foreground terminal handles its control keys; the supervising lease stays alive.
        for sig in (signal.SIGINT, signal.SIGQUIT):
            handlers[sig] = signal.signal(sig, signal.SIG_IGN)
        while True:
            try:
                return child.wait(timeout=5)
            except subprocess.TimeoutExpired:
                if not manage_consent_on():
                    child.terminate()
                    try:
                        child.wait(timeout=3)
                    except subprocess.TimeoutExpired:
                        child.kill()
                    return 4
                presence(token, name, "Terminal")
    finally:
        for sig, handler in handlers.items():
            signal.signal(sig, handler)
        presence(token, name, "off")
        if child and child.poll() is None:
            child.terminate()

def doctor() -> dict:
    """Why other computers might not see or reach this one, in plain words, each with what fixes it."""
    out = []
    link = None
    with contextlib.suppress(Exception):
        link = load_link()
    if link is not None and hasattr(link, "fleet_owner") and (owner := link.fleet_owner()):
        out.append({"id": "fleet-owner", "problem": f"This computer's fleet belongs to {owner['name']}.",
                    "fix": "Sign in to that account to add a computer or change the fleet."})
    if link is not None and not link.remote_login_on():
        out.append({"id": "remote-login", "problem": "Remote login is off, so your other computers can't talk to this one.",
                    "fix": "Turn on Remote login in Settings › Security."})
    if sh("systemctl", "--user", "is-active", "starchaser-link").stdout.strip() != "active":
        out.append({"id": "link", "problem": "The fleet service isn't running, so this computer doesn't answer pairing.",
                    "fix": "Sign out and back in, or run the Starchaser desktop setup again."})
    if sh("systemctl", "is-active", "avahi-daemon").stdout.strip() != "active":
        out.append({"id": "avahi", "problem": "Finding computers nearby is off.", "fix": "Run the Starchaser desktop setup again."})
    nets = fleet_networks()
    zone = network_zone()
    if nets is not None:
        # the system's own answer (starchaser-admin fleet-networks): which networks here count as the fleet's
        # (Tailscale and a VPN have their own switches; only a local network can be marked as your own)
        outside = [n for n in nets.get("networks") or [] if isinstance(n, dict) and n.get("zone") not in (nets.get("zones") or [])
                   and n.get("zone") not in ("tailscale", "vpn")]
        if nets.get("firewall") and outside and not nets.get("ready"):
            n = outside[0]
            out.append({"id": "public-network" if n.get("zone") == "public" else "not-fleet-network",
                        "problem": f"Your fleet can't reach this computer on {friendly_network_name(n.get('name'))}, because it "
                                   f"counts as {'Public' if n.get('zone') == 'public' else 'a network you have not marked Trusted'}.",
                        "fix": TRUST_HELP,
                        "action": "fleet-ready", "network": {"uuid": n.get("uuid", ""), "name": n.get("name", ""),
                                                             "zone": n.get("zone", "")}})
    elif zone == "public":
        out.append({"id": "public-network", "problem": "This network is Public, so your other computers can't find or reach "
                    "this one here.", "fix": TRUST_HELP,
                    "action": "firewall"})
    return {"ok": not out, "problems": out, "zone": zone}


ADMIN = Path("/usr/local/lib/starchaser/starchaser-admin")

TRUST_HELP = ("Trusted means only computers you have paired can reach you here; Public is for cafes and hotels. "
              "If it's a network you trust, mark it Trusted in Settings › Firewall.")


def friendly_network_name(name):
    """A default connection name like 'Wired connection 1' reads as jargon; say 'your wired connection'."""
    if re.fullmatch(r"Wired connection \d+", name or ""):
        return "your wired connection"
    return name or "this network"


def fleet_networks():
    """starchaser-admin fleet-networks (read-only, no password): the networks this computer is on with their kinds,
    and the kinds the fleet may reach it from (your own, plus Tailscale / VPN as their switches say). None when the
    helper is missing or older."""
    if not ADMIN.exists():
        return None
    r = sh(str(ADMIN), "fleet-networks", timeout=10)
    try:
        d = json.loads(r.stdout or "{}") if r.returncode == 0 else {}
    except ValueError:
        return None
    return d if isinstance(d, dict) and d.get("ok") and "zones" in d else None


def default_route_cards(route_file: Path = Path("/proc/net/route")) -> list:
    """The cards of the default routes in the main table, in order: what `ip -j route show default` lists, read from
    the kernel's route table file, so the link service's look every 10 s starts no process."""
    try:
        rows = [line.split() for line in route_file.read_text().splitlines()[1:]]
    except OSError:
        routes = json.loads(sh("ip", "-j", "route", "show", "default", timeout=4).stdout or "[]")
        return [r.get("dev") for r in routes if isinstance(r, dict) and r.get("dev")]
    devs = []
    for f in rows:
        # Iface Destination Gateway Flags ... Mask: a default route has destination and mask 0 and is up (flag 1)
        if len(f) >= 8 and f[1] == "00000000" and f[7] == "00000000" and int(f[3], 16) & 1 and f[0] != "*" \
                and f[0] not in devs:
            devs.append(f[0])
    return devs


def network_zone() -> str:
    """The firewall's kind for the network this computer reaches others on (the default route's card): "trusted",
    "public", "vpn", "tailscale", or "" when the firewall is off or it can't tell."""
    try:
        if not json.loads(Path("/etc/starchaser/policy.json").read_text()).get("enabled"):
            return ""
        zones = json.loads(Path("/run/starchaser/firewall-zones.json").read_text()).get("zones") or {}
        devs = default_route_cards()
    except (OSError, ValueError, AttributeError):
        return ""
    for dev in devs:
        for zone, cards in zones.items() if isinstance(zones, dict) else []:
            if isinstance(cards, list) and dev in cards:
                return zone
    return ""


# ---------------------------------------------------------------------------------------------- the command line
def fp(key: str) -> str:
    try:
        blob = base64.b64decode(key.split()[1])
    except (IndexError, ValueError):
        return ""
    return "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")


def out(obj) -> None:
    print(json.dumps(obj))


def error(message: str) -> None:
    # Apps read JSON from the pipe; a person at a terminal needs only the plain message.
    if sys.stdout.isatty():
        print(f"starchaser fleet: {message}", file=sys.stderr)
    else:
        out({"ok": False, "error": message})


_Fmt = argparse.RawDescriptionHelpFormatter


def main(argv: list) -> int:
    # Fleet v2's verbs (docs/fleet/commands.md) answer here only where /etc/starchaser/fleet-v2-preview exists, until
    # the fleet is finished (docs/fleet/build-plan.md section 1); everywhere else today's verbs are unchanged (rule 36.1)
    import starchaser_fleet_v2 as v2
    if v2.handles(argv):
        r = v2.main(argv)
        if r is not v2.LEGACY:
            return r
    ap = CommandParser(prog="starchaser fleet", usage="%(prog)s [-h] [COMMAND] ...",
                        description=__doc__.split("\n\nThe list (schema")[0],   # the commands too: --help is where people look for them
                        formatter_class=_Fmt,
                        epilog="Run with no command for the list. docs/fleet.md has the details.")
    sub = ap.add_subparsers(dest="cmd", metavar="COMMAND")
    one_id = "the computer's id from list"
    sub.add_parser("list", formatter_class=_Fmt,
                   description="Show the fleet as JSON (also used when no command is given).")
    a = sub.add_parser("add", formatter_class=_Fmt,
                       description="Record a computer's address in the fleet list for Mission Control, which signs in to it over SSH\n"
                                   "later. The computer isn't contacted now, so this works even when nobody answers at\n"
                                   "that address. To join a Starchaser computer to the fleet, use Settings › Fleet on it\n"
                                   "(starchaser link join). The same address, login and port is the same entry.")
    a.add_argument("--address", required=True, help="the address used to reach the computer")
    a.add_argument("--user", default="", help="the account to sign in as there")
    a.add_argument("--port", type=int, default=22, help="the sign-in port (default: 22)")
    a.add_argument("--label", default="", help="a name to show for it (default: the computer's own name)")
    a.add_argument("--via", default="mission-control", choices=VIAS, help="how it was added (default: mission-control)")
    a.add_argument("--os-label", default="", help="the name of the system it runs")
    a.add_argument("--os-id", default="", help="the id of the system it runs")
    r = sub.add_parser("rename", formatter_class=_Fmt,
                       description="Change a computer's name.")
    r.add_argument("id", help=one_id)
    r.add_argument("label", help='the new name ("" uses its own name again)')
    s = sub.add_parser("set-address", formatter_class=_Fmt,
                       description="Change the address used to reach a computer; the person typed it, so it wins over found addresses.")
    s.add_argument("id", help=one_id)
    s.add_argument("address", help="the address the person typed")
    s = sub.add_parser("update-address", formatter_class=_Fmt,
                       description="Save an automatically found address.")
    s.add_argument("id", help=one_id)
    s.add_argument("address", help="the address a search found")
    u = sub.add_parser("update", formatter_class=_Fmt,
                       description="Save details found about a computer.")
    u.add_argument("id", help=one_id)
    u.add_argument("--hostname", help="its name on the network")
    u.add_argument("--os-label", help="the name of the system it runs")
    u.add_argument("--os-id", help="the id of the system it runs")
    u.add_argument("--kind", help="what kind of computer it is")
    u.add_argument("--mac", action="append", help="a network card address it answered on (repeat for more)")
    u.add_argument("--host-key", action="append",
                   help="a sign-in key a person confirmed by its fingerprint (repeat for more; m- computers only)")
    m = sub.add_parser("merge", formatter_class=_Fmt,
                       description="Combine two entries for the same computer.")
    m.add_argument("keep", help="the id to keep")
    m.add_argument("drop", help="the id to fold into it")
    rm = sub.add_parser("remove", formatter_class=_Fmt,
                        description="Remove a computer from the whole fleet.")
    rm.add_argument("id", help=one_id)
    rm.add_argument("--lost", action="store_true", help="also remove its access without contacting it")
    fd = sub.add_parser("forget-device", formatter_class=_Fmt,
                        description="Remove a Starchaser computer and its access, using its device id.")
    fd.add_argument("device", help="the device id")
    ms = sub.add_parser("manage-state", formatter_class=_Fmt,
                        description="Save this account's Mission Control connection status.")
    ms.add_argument("id", help=one_id)
    ms.add_argument("state", choices=MANAGE_STATES, help="the new status")
    mr = sub.add_parser("manage-request", formatter_class=_Fmt,
                        description="Ask a computer to allow management from Mission Control.")
    mr.add_argument("id", help=one_id)
    mc = sub.add_parser("manage-consent", formatter_class=_Fmt,
                        description="Allow or stop fleet management of this computer.")
    mc.add_argument("value", choices=("on", "off"), help="on to allow it, off to stop it")
    clip = sub.add_parser("shared-clipboard", description="Allow clipboard transfer with the fleet.")
    clip.add_argument("value", choices=("on", "off"))
    rd = sub.add_parser("remote-own", description="Always allow remote desktop from live computers in your own fleet.")
    rd.add_argument("value", choices=("on", "off"))
    sub.add_parser("record-signin", description="Record the successful SSH key supplied by OpenSSH.")
    sn = sub.add_parser("_signin-notice", description="Show a saved-key sign-in notice with a button to remove the key.")
    sn.add_argument("fingerprint", help="the key's fingerprint")
    sn.add_argument("address", help="the address it signed in from, or -")
    sub.add_parser("activity", description="What my fleet did here.")
    ar = sub.add_parser("activity-record", description="Record an authenticated incoming fleet action.")
    ar.add_argument("source")
    ar.add_argument("name")
    ar.add_argument("action")
    sub.add_parser("signin-keys", description="Who can sign in here, with names and fingerprints.")
    sk = sub.add_parser("remove-signin-key", description="Remove every copy of a sign-in key and end remote sessions.")
    sk.add_argument("fingerprint")
    sub.add_parser("manage-key", formatter_class=_Fmt,
                   description="Create this account's sign-in key if needed.")
    sp = sub.add_parser("share-prompts", formatter_class=_Fmt,
                        description="Share AI prompt text with the fleet (off by default).")
    sp.add_argument("value", choices=("on", "off"), help="on to share it, off to stop")
    ft = sub.add_parser("fleet-trust", formatter_class=_Fmt,
                        description="Change who can manage computers and when to ask permission.")
    ft.add_argument("option", choices=TRUST_OPTIONS, help="which trust setting")
    ft.add_argument("value", choices=("on", "off"), help="on or off")
    ak = sub.add_parser("authkeys", formatter_class=_Fmt,
                        description="Manage saved remote sign-in keys.")
    ak.add_argument("op", choices=("add", "remove", "list"), help="add, remove or list")
    ak.add_argument("--tag", required=True, help="the key's tag")
    ak.add_argument("--key", default="", help="the key line to save (add)")
    sub.add_parser("sync", formatter_class=_Fmt,
                   description="Share the latest fleet list with the other computers now.")
    sub.add_parser("settings-sync", formatter_class=_Fmt,
                   description="Share settings you follow with the other computers now.")
    rmg = sub.add_parser("run-managed", formatter_class=_Fmt,
                         description="Run a command only while fleet management is allowed (exit 4 otherwise).")
    rmg.add_argument("job", nargs=argparse.REMAINDER, help="-- command [args...]")
    sub.add_parser("doctor", formatter_class=_Fmt,
                   description="Check why other computers cannot see this one.")
    sub.add_parser("migrate", formatter_class=_Fmt,
                   description="Convert an older fleet list (also done automatically).")
    sub.add_parser("start", formatter_class=_Fmt,
                   description="Start a new fleet on this computer.")
    sub.add_parser("stop", formatter_class=_Fmt,
                   description="Undo start: this computer is in no fleet again. Only while no other computer has joined.")
    sub.add_parser("relay-keys", formatter_class=_Fmt,
                   description="Update sign-in keys on computers added by address.")
    fa = sub.add_parser("fleet-access", formatter_class=_Fmt,
                        description="Say which computers manage a computer added by address: every fleet computer (all) "
                                    "or only this one (mine). With no choice, show the current answer.")
    fa.add_argument("id", help=one_id)
    fa.add_argument("value", nargs="?", choices=("all", "mine"), help="all or mine (with no choice, show the current answer)")
    sr = sub.add_parser("schedule-remove", description="Remove after 30 seconds, with Undo until then.")
    sr.add_argument("id", help=one_id)
    sr.add_argument("--drop-key", action="store_true", help="take fleet sign-in keys off a computer added by address")
    for command in ("undo-remove", "dismiss-removal", "_remove-after"):
        ur = sub.add_parser(command, description="Undo or finish a pending removal.")
        ur.add_argument("token", help="the pending removal token")
    sub.add_parser("pending-removals", description="Show removals waiting for Undo.")
    pr = sub.add_parser("presence", description="Renew a visible Mission Control session.")
    pr.add_argument("token", help="the session token")
    pr.add_argument("name", help="the source computer name")
    pr.add_argument("page", help="the page in use, or off")
    sub.add_parser("presence-status", description="Show active Mission Control sessions.")
    ts = sub.add_parser("terminal-session", description="Open a terminal with a visible connection mark.")
    ts.add_argument("name", help="the source computer name")
    ts.add_argument("session", nargs="?", help="an existing terminal session to attach to")
    args = ap.parse_args(argv)
    cmd = args.cmd or "list"
    if getattr(args, "id", None) == "":
        # an empty id is missing input ("" is a label's own reset word, never an id)
        ap.error(f"{cmd} needs a computer id. Use an id from 'starchaser fleet list'")
    if cmd == "run-managed":
        return run_managed(list(args.job))
    try:
        if cmd == "schedule-remove":
            out({"ok": True, **schedule_remove(args.id, args.drop_key)})
        elif cmd == "undo-remove":
            out({"ok": undo_remove(args.token)})
        elif cmd == "dismiss-removal":
            out({"ok": dismiss_removal(args.token)})
        elif cmd == "_remove-after":
            remove_after(args.token)
        elif cmd == "pending-removals":
            out({"ok": True, "pending": pending_removals()})
        elif cmd == "presence":
            presence(args.token, args.name, args.page)
            out({"ok": True})
        elif cmd == "terminal-session":
            if args.session and not re.fullmatch(r"[\w.-]{1,80}", args.session):
                raise ValueError("That isn't a terminal session name.")
            return terminal_session(args.name, ["tmux", "attach", "-t", args.session] if args.session else None)
        elif cmd == "presence-status":
            out({"ok": True, "sessions": presence_status()})
        elif cmd in ("list", "migrate"):
            out(load())
        elif cmd == "add":
            out({"ok": True, "machine": add_machine(args.address, args.user, args.port, args.label, args.via, args.os_label, args.os_id)})
        elif cmd == "rename":
            out({"ok": True, "machine": rename(args.id, args.label)})
        elif cmd == "set-address":
            out({"ok": True, "machine": set_address(args.id, args.address)})
        elif cmd == "update-address":
            if not valid_host(args.address):
                raise ValueError("That address has characters an address can't have.")
            if get(args.id) is None:
                raise KeyError(args.id)
            out({"ok": True, "changed": observe(args.id, {"addresses": {"last": args.address}})})
        elif cmd == "update":
            if get(args.id) is None:
                raise KeyError(args.id)
            facts = {}
            if args.hostname is not None:
                facts["hostname"] = args.hostname
            if args.os_label is not None or args.os_id is not None:
                e = get(args.id) or {}
                facts["os"] = {"id": args.os_id if args.os_id is not None else (e.get("os") or {}).get("id", ""),
                               "label": args.os_label if args.os_label is not None else (e.get("os") or {}).get("label", "")}
            if args.kind is not None:
                facts["kind"] = args.kind
            if args.mac:
                facts["macs"] = args.mac
            if args.host_key:
                e = get(args.id)
                if e is None:
                    raise KeyError(args.id)
                if not e["id"].startswith("m-"):
                    raise ValueError("A paired computer's host key comes from pairing, not from here.")
                keys = clean_keys(args.host_key)
                if len(keys) != len(args.host_key):
                    raise ValueError("That isn't a host key (it looks like: ssh-ed25519 AAAA…).")
                facts["checkedHostKeys"] = keys
            out({"ok": True, "changed": observe(args.id, facts)})
        elif cmd == "merge":
            out({"ok": True, "machine": merge_pair(args.keep, args.drop)})
        elif cmd == "remove":
            out(remove_flow(args.id, args.lost))
        elif cmd == "forget-device":
            dev = args.device.removeprefix("dev-")
            if not DEV_RE.fullmatch(dev):
                raise ValueError("not a device id")
            out(remove_flow("dev-" + dev, lost=True))
        elif cmd == "manage-state":
            out({"ok": True, "machine": manage_state(args.id, args.state)})
        elif cmd == "manage-request":
            e = get(args.id)
            if e is None or not e.get("link"):
                raise ValueError("Only a paired Starchaser computer can be asked. Add other computers with their password.")
            res = load_link().manage_request(e["link"]["device"])
            out(res)
            return 0 if res.get("ok") else 1
        elif cmd in ("manage-consent", "fleet-trust", "manage-key") and moved():
            error(MOVED_TEXT)                           # rule 36.4: retired here
            return 3
        elif cmd == "manage-consent":
            set_local(manageConsent=args.value == "on")
            reconcile()
            changed()
            pending = bool(load()["local"].get("sessionRevokePending"))
            out({"ok": True, "manageConsent": args.value == "on", "managers": authorized_managers(),
                 "note": "Keys were removed, but some remote sign-ins couldn't be ended. Turn off Remote login in Settings › Security to end them." if pending else ""})
        elif cmd == "shared-clipboard":
            set_local(sharedClipboard=args.value == "on")
            out({"ok": True, "sharedClipboard": args.value == "on"})
        elif cmd == "remote-own":
            set_local(remoteOwnFleet=args.value == "on")
            if args.value == "off":
                link = load_link()
                link.jwrite(link.REMOTE_OK, {})
                unit = link.sunshine_unit(link.session_env())
                if unit:
                    sh("systemctl", "--user", "stop", unit)
            out({"ok": True, "remoteOwnFleet": args.value == "on"})
        elif cmd == "record-signin":
            info = os.environ.get("SSH_USER_AUTH")
            out(record_signin(Path(info), signin_address()) if info else {"ok": True})
        elif cmd == "_signin-notice":
            sys.exit(signin_notice(args.fingerprint, args.address))
        elif cmd == "activity":
            out({"ok": True, "events": activity()})
        elif cmd == "activity-record":
            out(record_activity(args.source, args.name, args.action))
        elif cmd == "signin-keys":
            out({"ok": True, "keys": signin_keys()})
        elif cmd == "remove-signin-key":
            out(remove_signin_key(args.fingerprint))
        elif cmd == "manage-key":
            pub, made = ensure_personal_key()
            if not pub:
                raise OSError("Couldn't make a sign-in key for this account.")
            changed()
            out({"ok": True, "pub": pub, "fingerprint": fp(pub), "made": made})
        elif cmd == "share-prompts":
            set_local(sharePrompts=args.value == "on")
            out({"ok": True, "sharePrompts": args.value == "on"})
        elif cmd == "fleet-trust":
            out(set_trust(args.option, args.value == "on"))
        elif cmd == "authkeys":
            out({"ok": True, "lines": authkeys(args.op, args.tag, args.key)})
        elif cmd == "sync":
            out(load_link().fleet_sync(wait=True))
        elif cmd == "settings-sync":
            out(load_link().settings_sync())
        elif cmd == "doctor":
            r = doctor()
            out(r)
            return 0 if r.get("ok", True) else 1
        elif cmd == "start":
            if load()["local"].get("left"):
                recovery_client().retire()
            with editing() as d:
                if d["local"].get("left"):
                    d["local"]["selfGen"] = max(counter(d["local"].get("selfGen")),
                                                counter(d["local"]["left"].get("gen"))) + 1
                    d["security"] = {"sequence": 0, "anchors": {}, "records": []}
                    d["local"]["left"] = None           # (a computer removed from its old fleet starts a new one)
                    d["local"]["manageConsent"] = False     # (the old fleet's consent never carries over)
                ensure_tag(d)
                ensure_fleet_identity(d)
                load_link()  # use the installed module lookup shared by the fleet tools
                path = Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser/phone_trust.py"
                if not path.is_file():
                    path = Path("/usr/local/lib/starchaser/phone_trust.py")
                import importlib.util
                spec = importlib.util.spec_from_file_location("fleet_phone_trust", path)
                phone = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(phone)
                founder = d["security"]["identity"]["certificate"]["body"]
                if founder["founder"] == device_id():
                    phone.ensure_ca(DEVICES / "fleet-web-ca", root_binding=founder["rootKey"])
                tag = d["fleet"]["tag"]
            out({"ok": True, "tag": tag})
        elif cmd == "stop":
            # a fleet only this computer is in (started here, nobody joined): back to none, as before start. One that
            # others are in is left by removing this computer from another one
            with editing() as d:
                if d["machines"] or not (d.get("fleet") or {}).get("lone"):
                    out({"ok": False, "error": "Other computers are in this fleet. Remove this computer from one of them instead."})
                    return 1
                d["fleet"] = {"tag": ""}
                # No other member has joined: undo the founding identity and its
                # delegation records too, just as starting after leaving does.
                # The next start rotates the signing key using fleet-signing.tag.
                d["security"] = {"sequence": 0, "anchors": {}, "records": []}
                d["local"]["manageConsent"] = False     # off, as before start: the next fleet is asked again
            reconcile_manage_keys()
            out({"ok": True, "tag": ""})
        elif cmd == "relay-keys":
            out(relay_keys())
        elif cmd == "fleet-access":
            out(fleet_access(args.id, args.value))
    except KeyError as e:
        name = str(e).strip(chr(39))
        error(f"No computer {name} in the fleet." if name
              else "No computer id was given. Use an id from 'starchaser fleet list'.")
        return 1
    except ValueError as e:
        error(str(e))
        return 1
    except OSError as e:
        # a folder it may not read or write: plain words, never the raw "[Errno 13] ..." text (an OSError raised
        # here with its own plain message keeps that message)
        error(str(e) if e.filename is None else
              f"couldn't read or save the fleet list ({e.strerror}). Check that you can write to ~/.config and ~/.local/share.")
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
