#!/usr/bin/env python3
# summary: Find, install, and manage add-ons.
"""Satellites: local add-ons for Starchaser, using Python's standard library.

list/info/search/page-json --json serve Settings. menu-json, cards-json, and theme-dirs return
JSON arrays for the menu, Today, and theme engine. run-card ID FILE is internal:
it checks enabled state, runs ONLY the declared command through sh -c in the
satellite folder, stops its process group after 10 seconds, and caps output at
4 KB. hook EVENT runs the hooks of enabled satellites, 5 seconds each, logged.
Discovery reads the selected local or online list. The desktop checks Starchaser's
signed removals independently of that choice.
"""

import argparse
import contextlib
import fcntl
import hashlib
import http.client
import json
import math
import os
import re
import selectors
import shlex
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
import textwrap
import time
import tomllib
import unicodedata
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_satellite_host as satellite_host
import starchaser_satellite_list as satellite_list
import starchaser_satellite_network as satellite_network
import starchaser_satellite_runtime as satellite_runtime
from starchaser_cli import CommandParser

API = 2
# Test transports and trust overrides are available only in a source checkout; packages omit tests and Git metadata.
TEST_OVERRIDES = ((Path(__file__).resolve().parents[1] / ".git").exists()
                  and (Path(__file__).resolve().parents[1] / "tests/satellites_engine_test.py").is_file())
LIMIT = 20 * 1024 * 1024
WARNING = (
    "This add-on comes from outside Starchaser and has not been reviewed. "
    "Add-ons you add from outside can do anything you can do on this computer. "
    "Only install it if you trust who made it."
)
CHANGED = "This add-on's files changed after it was added. Remove it and add it again."
CODE_WARNING = (
    "This add-on includes code. It can do anything you can do on this computer. "
    "Only install it if you trust who made it. "
    "It runs apart from the rest of the desktop, so if it breaks, your desktop keeps working, "
    "but that is not a safety fence."
)
PIN_NOTE = "Starchaser keeps the exact version shown here (its commit). Reviewed restricted add-ons update automatically only if you turn that on."
KINDS = {"theme": "a theme", "menu-page": "a menu page", "today-card": "a Today card",
         "settings-page": "a Settings page", "cli-hook": "actions that run at set moments",
         "bar-widget": "a taskbar item", "service": "a background service", "panel": "a panel",
         "overlay": "a full-screen overlay"}
LATER = set()
# Where a satellite just turned on shows up, said after "<name> is on." (the first of its kinds listed here; a theme's
# place is said by Settings, which adds it to Appearance without applying it)
WHERE_ON = [("bar-widget", "Look for its icon in the taskbar."), ("today-card", "Its card is in Today."),
            ("menu-page", "Its rows are under Add-ons in the menu."),
            ("panel", "Open its panel from its taskbar item or a keyboard shortcut."),
            ("overlay", "Open it from its taskbar item or a keyboard shortcut; Escape closes it."),
            ("service", "It runs in the background; its log is under Details.")]
# Kinds whose files are programs Starchaser runs as you; the code warning names them (a Page.qml settings page too).
CODE_KINDS = {"cli-hook", "bar-widget", "service", "panel", "overlay"}
# These are the same defaults the runtime opens. Every explicit entry is checked too,
# even when its kind is inactive; unknown entries must never disappear during parsing.
ENTRY_DEFAULTS = {"theme": "theme", "menu-page": "menu.json", "today-card": "cards",
                  "settings-page": "page.toml", "cli-hook": "hooks", "bar-widget": "Widget.qml",
                  "service": "bin/service", "panel": "Panel.qml", "overlay": "Overlay.qml"}
ENTRY_DEFAULTS.update({kind: kind + ".json" for kind in ("quick-tile", "search-result", "desktop-widget", "lock-widget", "file-action")})
KINDS.update({"quick-tile": "a quick-settings tile", "search-result": "menu search results", "desktop-widget": "a desktop widget",
              "lock-widget": "a lock-screen widget", "file-action": "a Files action"})
VCS_DIRS = {"cvs", "rcs", "sccs", "_darcs", "_fossil_", "_mtn", "bitkeeper", "{arch}"}
# Hook events, in the words Settings uses after "Runs its own actions when".
EVENTS = {
    "theme-changed": "the theme or dark and light mode changes",
    "session-start": "you sign in",
    "session-end": "you sign out",
    "lock": "the screen locks",
    "unlock": "the screen unlocks",
    "network-changed": "a network connects or disconnects",
    "battery-low": "the battery first falls to 20% or less",
    "before-update": "an update starts",
    "after-update": "an update finishes",
}
PERSONAL_HOOKS = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "starchaser/hooks"
HOOK_SECONDS = 5
COMMAND_SECONDS = 10
CONTROL_TYPES = ("switch", "dropdown", "slider", "button", "note")
KEY_RE = re.compile(r"[a-z][a-z0-9_]{0,39}\Z")
VAR_RE = re.compile(r"STARCHASER_[A-Z0-9_]{1,40}\Z")
ID_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*\Z")
VERSION_RE = re.compile(
    r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
    r"(?:-(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?"
    r"(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?\Z"
)
# These identifiers are checked without putting foreign names in visible text.
FOREIGN = tuple("".join(parts).lower() for parts in (("GNO", "ME"), ("K", "DE"), ("Cachy", "OS"), ("Cael", "estia")))
HOME = Path.home()
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", HOME / ".config")) / "starchaser"
DATA = Path(os.environ.get("XDG_DATA_HOME", HOME / ".local/share")) / "starchaser"
LOGS = Path(os.environ.get("XDG_STATE_HOME", HOME / ".local/state")) / "starchaser/satellites"
STATE = CONFIG / "satellites.json"
THEME_STATE = Path(os.environ.get("XDG_STATE_HOME", HOME / ".local/state")) / "starchaser/theme.json"
MARKER = CONFIG / "satellites-safe"
DEVELOPER_FILE = CONFIG / "developer-mode"
# Examples for people who write satellites. Everyone else never sees them, unless one is already turned on.
SAMPLES = {"hello-orbit", "night-theme-hook", "sample-service", "sample-panel", "sample-overlay"}


def developer_mode():
    return os.environ.get("STARCHASER_DEVELOPER") == "1" or DEVELOPER_FILE.exists()
INSTALLED = DATA / "satellites"
INCLUDED = [Path("/usr/share/starchaser/satellites"), Path(__file__).resolve().parent.parent / "satellites"]
# Code satellites: the host shell and the SDK (Starchaser.Satellite) beside this tool, in the repo or /usr/share/starchaser.
SHELL_DIR = Path(__file__).resolve().parent.parent / "config/quickshell"
HOST_SHELL = SHELL_DIR / "satellite-host/shell.qml"
SDK_DIR = SHELL_DIR / "satellite-sdk"
RUN = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-satellites"
# A taskbar item that writes nothing for this long has stopped answering; the host stops it and counts a stop.
HANG_SECONDS = float(os.environ.get("STARCHASER_SATELLITE_HANG", "15"))
RESTART_SECONDS = float(os.environ.get("STARCHASER_SATELLITE_RESTART", "2"))
# One hang takes the quiet time plus start-up plus the restart wait (about 31 s), so at most two fit in a minute:
# hangs are counted over five minutes instead, or a satellite that keeps hanging would be restarted forever.
HANG_WINDOW = max(300.0, 6 * (HANG_SECONDS + RESTART_SECONDS))


class Problem(Exception):
    """A single plain sentence that can also be shown by Settings."""

    # a guide that says what to do next (a docs file and its section), sent to Settings as "help" beside "errors"
    help = ""


class OmarchyPlugin(Problem):
    """A repository made as a plugin for Omarchy's shell (manifest.json, QML that talks to that shell's services):
    it can't run here as it is, and nothing in it is run to find that out."""

    help = "satellites-for-omarchy-users.md#porting-an-omarchy-plugin"

    def __init__(self):
        super().__init__("This add-on was made for a different desktop. Port it to Starchaser before using it.")


def read_json(path, default):
    try:
        return json.loads(path.read_text())
    except FileNotFoundError:
        return default
    except (OSError, ValueError):
        raise Problem("The add-on settings couldn't be read.") from None


def state(locked=False):
    try:
        result = read_json(STATE, {"satellites": {}, "safe": False})
        if (not isinstance(result, dict) or not isinstance(result.get("satellites"), dict)
                or any(not isinstance(record, dict) for record in result["satellites"].values())):
            raise Problem("The add-on settings couldn't be read.")
        return result
    except (Problem, UnicodeError, RecursionError):
        if not locked:
            CONFIG.mkdir(parents=True, exist_ok=True)
            with (CONFIG / "satellites.lock").open("a") as lock:
                fcntl.flock(lock, fcntl.LOCK_EX)
                return state(locked=True)
        backup = STATE.with_name(f"{STATE.name}.broken-{time.time_ns()}")
        STATE.rename(backup)
        result = {"satellites": {}, "safe": True}
        # Preserve access to Disable and Remove, but an unknown installation must be added again before enabling.
        if INSTALLED.is_dir():
            result["satellites"] = {p.name: {"enabled": False, "source_url": "", "recovered": True}
                                    for p in INSTALLED.iterdir() if p.is_dir() and not p.is_symlink() and ID_RE.fullmatch(p.name)}
        MARKER.touch()
        atomic_json(STATE, result)
        print(f"The add-on settings were damaged. Every add-on is off. The damaged file is saved in {backup}.", file=sys.stderr)
        return result


def atomic_text(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(prefix=f".{path.name}.{os.getpid()}.", dir=path.parent)
    try:
        with os.fdopen(fd, "w") as stream:
            stream.write(value)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(name, path)
    finally:
        Path(name).unlink(missing_ok=True)


def atomic_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(prefix=f".{path.name}.{os.getpid()}.", dir=path.parent)
    try:
        with os.fdopen(fd, "w") as stream:
            json.dump(value, stream, indent=2)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(name, path)
    finally:
        Path(name).unlink(missing_ok=True)


@contextlib.contextmanager
def locked_state(rollback=None):
    CONFIG.mkdir(parents=True, exist_ok=True)
    with (CONFIG / "satellites.lock").open("a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        saved = state(locked=True)
        try:
            yield saved
            atomic_json(STATE, saved)
        except BaseException:
            if rollback is not None:
                rollback()
            raise


def forget_logs(sid):
    # a purge leaves nothing of the add-on behind, its logs included
    for path in [LOGS / f"{sid}.log", LOGS / f"{sid}-activity.json", *LOGS.glob(f"{sid}.*.log")]:
        path.unlink(missing_ok=True)


def log(sid, sentence):
    LOGS.mkdir(parents=True, exist_ok=True)
    with (LOGS / f"{sid}.log").open("a") as stream:
        stream.write(time.strftime("%Y-%m-%d %H:%M:%S ") + sentence + "\n")


def safe_on(saved):
    return os.environ.get("STARCHASER_SATELLITES_SAFE") == "1" or saved.get("safe", False) or MARKER.exists()


# A taskbar item's place: the start of the taskbar (after the menu button), the middle (after the desktops, before the
# running apps), or the end (before the privacy lights, where every one went before); on which screens it shows.
BAR_SECTIONS = ("start", "middle", "end")
SCREEN_RE = re.compile(r"[A-Za-z0-9_.:-]{1,64}\Z")


def bar_place(item, record):
    """{"section", "screens"} for a taskbar item: what you chose in Settings (kept in its record), else its manifest's
    default_section on the main screen. screens is "main", "all", or a list of screen names; more than one screen (or
    "all") only for an item that allows it."""
    place = record.get("bar") if isinstance(record.get("bar"), dict) else {}
    section = place.get("section") if place.get("section") in BAR_SECTIONS else item["bar"]["default_section"]
    screens = place.get("screens", "main")
    if isinstance(screens, list):
        screens = [n for n in screens if isinstance(n, str) and SCREEN_RE.fullmatch(n)][:16] or "main"
    elif screens not in ("main", "all"):
        screens = "main"
    if not item["bar"]["allow_multiple"] and (screens == "all" or (isinstance(screens, list) and len(screens) > 1)):
        screens = "main"
    return {"section": section, "screens": screens}


def place_bar_item(sid, section=None, screens=None):
    """bar-place: move an installed taskbar item to another part of the taskbar or other screens. It only says where
    the item is drawn: nothing is turned on, granted, or run."""
    if section is None and screens is None:
        raise Problem("Say where: --section start, middle or end, or --screens main, all, or screen names.")
    if section is not None and section not in BAR_SECTIONS:
        raise Problem('Use --section "start", "middle", or "end".')
    with locked_state() as saved:
        item = next((i for i in catalog(saved)["satellites"] if i["id"] == sid), None)
        if item is None or "bar-widget" not in item["kinds"]:
            raise Problem("That add-on has no taskbar item to place.")
        record = saved["satellites"].setdefault(sid, {})
        place = dict(record.get("bar")) if isinstance(record.get("bar"), dict) else {}
        if section is not None:
            place["section"] = section
        if screens is not None:
            names = screens if screens in ("main", "all") else [n.strip() for n in screens.split(",") if n.strip()]
            if isinstance(names, list) and (not names or not all(SCREEN_RE.fullmatch(n) for n in names)):
                raise Problem("Use --screens main, all, or screen names like DP-1,HDMI-A-1.")
            if (names == "all" or (isinstance(names, list) and len(names) > 1)) and not item["bar"]["allow_multiple"]:
                raise Problem(f"{item['name']} can show on one screen at a time.")
            place["screens"] = names
        record["bar"] = place
        now = bar_place(item, record)
    where = {"start": "at the start of the taskbar", "middle": "in the middle of the taskbar", "end": "at the end of the taskbar"}
    shown = {"main": "the main screen", "all": "every screen"}.get(now["screens"]) if isinstance(now["screens"], str) \
        else ", ".join(now["screens"])
    print(f"{item['name']} is {where[now['section']]}, on {shown}.")


def manifest(folder):
    try:
        path = folder / "satellite.toml"
        if path.stat().st_size > 65536:
            raise Problem("The add-on manifest is too large.")
        m = tomllib.loads(path.read_text())
    except FileNotFoundError:
        raise Problem("That isn't a Starchaser add-on: it has no add-on description file (satellite.toml). "
                      "If you pasted a link, check that it's the right one.") from None
    except (OSError, UnicodeError, tomllib.TOMLDecodeError, RecursionError):
        raise Problem("The add-on description file (satellite.toml) is damaged and couldn't be read.") from None
    if not isinstance(m.get("id"), str) or not ID_RE.fullmatch(m["id"]) or len(m["id"]) > 80:
        raise Problem("The add-on needs an id with lowercase letters, digits, and dashes.")
    if not isinstance(m.get("version"), str) or not VERSION_RE.fullmatch(m["version"]):
        raise Problem("The add-on needs a version like 1.0.0.")
    sc = m.get("starchaser", {})
    api = sc.get("api") if isinstance(sc, dict) else None
    if type(api) is not int or api < 1:
        raise Problem("The add-on needs a whole number for its Starchaser API.")
    if api > API:
        raise Problem("Needs a newer Starchaser.")
    minimum = sc.get("min")
    if minimum is not None:
        if not isinstance(minimum, str) or not VERSION_RE.fullmatch(minimum):
            raise Problem("The minimum Starchaser version must look like 1.0.0.")
        current = starchaser_version()
        if not current or version_key(current) < version_key(minimum):
            raise Problem(f"Needs Starchaser {minimum} or newer. Open Settings > Updates to update this computer.")
    for key in ("name", "summary", "author", "license", "homepage"):
        value = m.get(key)
        if not isinstance(value, str) or (not value.strip() and key != "homepage") or len(value) > 500 or any(ord(c) < 32 for c in value):
            if key == "homepage":
                raise Problem('Add a one-line homepage to satellite.toml, before any [table]: homepage = "https://...".')
            raise Problem(f"The add-on needs a one-line {key}.")
    if any(word in (m["name"] + " " + m["summary"]).lower() for word in FOREIGN):
        raise Problem("The add-on name and summary must use Starchaser branding.")
    included = any(folder.resolve().parent == base.resolve() for base in INCLUDED)
    if not included:
        names = set()
        for base in INCLUDED:
            for description in base.glob("*/satellite.toml"):
                with contextlib.suppress(OSError, ValueError):
                    names.add(tomllib.loads(description.read_text()).get("name", "").casefold())
        if (re.search(r"starchaser|\b(system|updates|security|settings)\b", m["name"], re.I)
                or m["name"].casefold() in names):
            raise Problem("Choose an add-on name that can't be mistaken for Starchaser or one of its included add-ons.")
    kinds = sc.get("kinds", m.get("kinds", []))
    if not isinstance(kinds, list) or any(not isinstance(k, str) for k in kinds):
        raise Problem("The add-on kinds must be a list of names.")
    m["kinds"] = list(dict.fromkeys(kinds))
    permissions = m.get("permissions", {})
    if not isinstance(permissions, dict):
        raise Problem("The add-on permissions must be a table.")
    new_capabilities = (set(sc) & {"sandbox", "providers", "secrets", "shortcut"}
                        or any(k in {"quick-tile", "search-result", "desktop-widget", "lock-widget", "file-action"} for k in kinds)
                        or any(permissions_key in permissions for permissions_key in {"media", "selected_file", "search"}))
    if api < 2 and new_capabilities:
        raise Problem("Restricted access and the new add-on features require Starchaser API 2. Set api = 2 so older computers refuse to run them.")
    if "entry" in sc and "entry" in m:
        raise Problem("Use one add-on entry table, inside [starchaser].")
    entry = sc.get("entry", m.get("entry", {}))
    if not isinstance(entry, dict):
        raise Problem("The add-on entries must be a table of paths.")
    m["entry"] = entry
    # This is also the install/enable gate (both load the manifest), and the decision
    # details(), update summaries and the warning UI use. No filename-based exemption.
    ships_code(m, folder)
    permissions = m.get("permissions", {})
    if not isinstance(permissions, dict):
        raise Problem("The add-on permissions must be a table.")
    m["permissions"] = {k: v for k, v in permissions.items() if k in {"network", "run", "read", "write", "notify", "location", "media", "selected_file", "search"}}
    for k, v in m["permissions"].items():
        if k in {"notify", "location", "media", "selected_file", "search"}:
            valid = type(v) is bool
        else:
            valid = isinstance(v, list) and all(isinstance(x, str) and len(x) <= 500 for x in v)
        if not valid:
            raise Problem("The add-on permissions need lists of names or true and false flags.")
    depends = m.get("depends", {})
    packages = depends.get("packages", []) if isinstance(depends, dict) else None
    if not isinstance(packages, list) or any(not isinstance(p, str) or not re.fullmatch(r"[a-z0-9@_+.-]+", p) for p in packages):
        raise Problem("Add-ons can only list packages from the system's own software list.")
    m["packages"] = packages
    m["starchaser"] = {"api": api}
    if isinstance(sc.get("min"), str):
        m["starchaser"]["min"] = sc["min"]
    # [starchaser.bar]: where a taskbar item starts (default_section) and whether it may show more than once
    # (allow_multiple: on several screens at a time), like Omarchy's barWidget defaultSection and allowMultiple
    bar = sc.get("bar", {})
    if not isinstance(bar, dict):
        raise Problem("[starchaser.bar] must be a table.")
    section = bar.get("default_section", "end")
    if section not in BAR_SECTIONS:
        raise Problem('[starchaser.bar] default_section must be "start", "middle", or "end".')
    multiple = bar.get("allow_multiple", False)
    if type(multiple) is not bool:
        raise Problem("[starchaser.bar] allow_multiple must be true or false.")
    m["bar"] = {"default_section": section, "allow_multiple": multiple}
    sandbox = sc.get("sandbox", "full-access")
    if sandbox not in {"restricted", "full-access"}:
        raise Problem('The sandbox must be "restricted" or "full-access".')
    if sandbox == "restricted" and (m["permissions"].get("location") or any(v != "its own data folder" for k in ("read", "write") for v in m["permissions"].get(k, []))):
        raise Problem("Restricted add-ons can only use their own data. External access needs explicit full-access mode.")
    if sandbox == "restricted" and any(not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?", h) for h in m["permissions"].get("network", [])):
        raise Problem("List exact HTTPS host names for restricted network access, without paths, ports, or wildcards.")
    m["sandbox"] = sandbox
    providers = sc.get("providers", [])
    if not isinstance(providers, list) or any(p not in {"battery", "network", "media", "workspaces", "weather", "calendar"} for p in providers):
        raise Problem("Choose supported typed data providers.")
    m["providers"] = providers
    secret_names = sc.get("secrets", [])
    if not isinstance(secret_names, list) or any(not isinstance(k, str) or not KEY_RE.fullmatch(k) for k in secret_names):
        raise Problem("Saved sign-in names must use lowercase letters, digits, and underscores.")
    m["secrets"] = secret_names
    suggested = sc.get("shortcut", "")
    if not isinstance(suggested, str) or len(suggested) > 80 or (suggested and not re.fullmatch(r"[A-Za-z0-9+ _-]+", suggested)):
        raise Problem("The suggested shortcut must be a short key combination.")
    m["shortcut"] = suggested
    m["icon"] = str(m.get("icon", ""))[:4]
    # Ignore unknown TOML values too: dates and extra tables must not break JSON readers.
    return {k: m[k] for k in ("id", "name", "version", "summary", "author", "license", "homepage", "icon",
                             "starchaser", "kinds", "entry", "permissions", "packages", "bar", "sandbox", "providers", "secrets", "shortcut")}


def version_key(version):
    release, _, pre = version.split("+", 1)[0].partition("-")
    suffix = tuple((0, int(p)) if p.isdigit() else (1, p) for p in pre.split(".")) if pre else ((2, ""),)
    return tuple(map(int, release.split("."))), suffix


@lru_cache(maxsize=1)
def starchaser_version():
    root = Path(__file__).resolve().parents[1]
    for path in (root / "VERSION", Path("/usr/share/starchaser/VERSION")):
        with contextlib.suppress(OSError):
            value = path.read_text().strip()
            # Development packages use 0.<commit count>.g<hash>[-<package release>]. Treat the count as
            # the minor version and the hash as build metadata, so release floors remain comparable.
            build = re.fullmatch(r"0\.(0|[1-9][0-9]*)\.g([0-9a-f]+)(?:-[0-9]+)?", value)
            if build:
                return f"0.{build[1]}.0+g{build[2]}"
            matched = re.fullmatch(r"(\d+\.\d+\.\d+)-\d+", value)
            value = matched[1] if matched else value
            if VERSION_RE.fullmatch(value):
                return value
    if (root / ".git").exists():
        with contextlib.suppress(OSError, subprocess.SubprocessError):
            value = subprocess.run(["git", "-C", str(root), "describe", "--tags", "--abbrev=0", "--match", "v[0-9]*"],
                                   capture_output=True, text=True, check=True, timeout=5).stdout.strip().removeprefix("v")
            if VERSION_RE.fullmatch(value):
                return value
    return ""


def check_tree(folder):
    """Dereference only internal file links; directory links are refused to avoid cycles."""
    root = folder.resolve()
    total = 0
    # a theme converted from a colors.toml folder (or about to be) carries its wallpapers, so it may be larger
    big = (root / THEME_IMPORT).is_file() or bool(is_plain_theme(root))
    limit = THEME_IMPORT_LIMIT if big else LIMIT
    for base, dirs, files in os.walk(root, followlinks=False):
        for name in dirs + files:
            path = Path(base) / name
            if path.is_symlink() and (not path.resolve().is_relative_to(root) or path.resolve().is_dir()):
                raise Problem("Satellite links must point to files inside its folder.")
            mode = path.stat().st_mode
            if not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)):
                raise Problem("Satellites can contain only folders and regular files.")
            if stat.S_ISREG(mode):
                total += path.stat().st_size
                if total > limit:
                    raise Problem("The add-on folder is larger than 200 MB." if big else "The add-on folder is larger than 20 MB.")


def catalog(saved=None):
    saved = state() if saved is None else saved
    policy = managed_policy()
    items, errors, hidden, seen = [], [], [], set()
    for base in [INSTALLED, *INCLUDED]:
        if not base.is_dir():
            continue
        for folder in sorted(base.iterdir()):
            if not folder.is_dir() or folder.name.startswith("."):
                continue
            try:
                if folder.is_symlink():
                    raise Problem("Satellite folders can't be links.")
                check_tree(folder)
                m = manifest(folder)
                if m["id"] != folder.name:
                    raise Problem("The add-on id must match its folder name.")
                if base == INSTALLED:
                    added(folder, saved["satellites"].get(m["id"], {}))
            except (Problem, OSError, ValueError, RecursionError) as ex:
                errors.append({"id": folder.name, "reason": str(ex) if isinstance(ex, Problem) else "The add-on folder couldn't be read.",
                               "path": str(folder), "removable": base == INSTALLED and not folder.is_symlink()})
                continue
            sid = m["id"]
            if sid in seen:
                continue
            seen.add(sid)
            record = saved["satellites"].get(sid, {})
            if sid in SAMPLES and base != INSTALLED and not record.get("enabled") and not developer_mode():
                continue
            if record.get("removed"):
                if base != INSTALLED:
                    hidden.append({"id": sid, "name": m["name"], "has_data": (DATA / "satellite-data" / sid).is_dir()})
                continue
            items.append({**m, "path": str(folder), "enabled": bool(record.get("enabled", False)) and not safe_on(saved),
                          "source": "Included" if base != INSTALLED else "From the online list" if record.get("source") == "From the add-on list" else record.get("source", "From a link"),
                          "review": "Included" if base != INSTALLED else record.get("review", "Unreviewed"),
                          "source_url": record.get("source_url", ""), "commit": record.get("commit", ""), "index_removed": record.get("index_removed", ""),
                          "reason": record.get("reason", ""), "granted_permissions": record.get("granted_permissions", {}), "granted_providers": record.get("granted_providers", []), "granted_secrets": record.get("granted_secrets", []), "granted_sandbox": record.get("granted_sandbox", "full-access"),
                          "log": str(LOGS / f"{sid}.log"), "data": str(DATA / "satellite-data" / sid)})
            if sid in policy.get("blocked", []) or (policy.get("reviewed_only") and not policy_reviewed(items[-1])):
                items[-1].update(enabled=False, reason="This add-on is off because of this computer's managed policy.")
            items[-1]["theme_choices"] = sorted(theme_ids([items[-1]]))
            items[-1]["reload"] = record.get("reload", "")
            items[-1]["place"] = bar_place(items[-1], record)
            try:
                items[-1]["page_kind"] = "toml" if page_entry(items[-1]) else "qml" if code_page(items[-1]) else ""
            except (OSError, Problem):
                items[-1]["page_kind"] = ""
            items[-1]["has_page"] = items[-1]["page_kind"] != ""
    for sid, record in saved["satellites"].items():
        if record.get("remove_leftovers") and not any(e["id"] == sid for e in errors):
            errors.append({"id": sid, "reason": "This add-on is off. Some files couldn't be deleted; try Remove again.",
                           "path": str(INSTALLED / sid), "removable": True})
    removed = [{"id": sid, "name": r.get("trash_name", sid), "until": r["trash_until"]}
               for sid, r in saved["satellites"].items() if r.get("trash_until", 0) > time.time() and r.get("removed")]
    return {"satellites": sorted(items, key=lambda i: i["name"].casefold()), "errors": errors, "hidden": hidden, "removed": removed,
            "bar_order": saved.get("bar_order", []), "managed_policy": policy, "automatic_updates": bool(saved.get("automatic_updates")), "update_count": len(saved.get("waiting_updates", [])), "safe": bool(safe_on(saved)), "state_path": str(STATE)}


def added(folder, record):
    """An added folder needs the record install writes after its warning, and a pinned one must still be at its commit."""
    if "source_url" not in record:
        raise Problem("This folder wasn't added with Starchaser, so it stays off. Add it again from its folder or link.")
    if any((base / folder.name).exists() for base in INCLUDED):
        raise Problem("An add-on with this id is already included with Starchaser.")
    if record.get("commit"):
        try:
            head = (folder / ".git/HEAD").read_text().strip()
        except (OSError, UnicodeError):
            head = ""
        if head != record["commit"]:
            raise Problem(CHANGED)


def pinned_files(folder, commit):
    """Read and hash the commit and its trees; local refs and object contents are account-owned too."""
    def read_object(kind, oid):
        raw = git(["--no-replace-objects", "cat-file", kind, oid], folder, binary=True)
        if hashlib.sha1(kind.encode() + b" " + str(len(raw)).encode() + b"\0" + raw).hexdigest() != oid:
            raise Problem(CHANGED)
        return raw

    raw = read_object("commit", commit)
    tree = raw.partition(b"\n")[0]
    if not re.fullmatch(rb"tree [0-9a-f]{40}", tree):
        raise Problem(CHANGED)
    expected = {}

    def visit(oid, parent=""):
        raw = read_object("tree", oid)
        offset, names = 0, set()
        while offset < len(raw):
            end = raw.index(b"\0", offset)
            mode, name = raw[offset:end].split(b" ", 1)
            if not name or name in {b".", b"..", b".git"} or b"/" in name or name in names or end + 21 > len(raw):
                raise Problem(CHANGED)
            names.add(name)
            child = raw[end + 1:end + 21].hex()
            relative = parent + os.fsdecode(name)
            offset = end + 21
            if mode == b"40000":
                visit(child, relative + "/")
            elif mode in {b"100644", b"100755", b"120000"}:
                expected[relative] = (mode.decode(), child)
            else:
                raise Problem(CHANGED)

    visit(tree[5:].decode())
    return expected


def unchanged(item):
    """Compare actual files with the pinned tree, independently of Git's editable index and ignores."""
    if not item["commit"]:
        return
    folder = Path(item["path"])

    def unreadable(error):
        raise Problem(CHANGED) from error

    try:
        # Replacement refs must not substitute an unreviewed tree for the signed commit.
        if (git(["--no-replace-objects", "rev-parse", "HEAD"], folder) != item["commit"]
                or git(["rev-parse", "--show-prefix"], folder)):
            raise Problem(CHANGED)
        expected = pinned_files(folder, item["commit"])
        if "satellite.toml" not in expected:
            # Plain-theme imports add Starchaser files outside the author's Git tree. Recreate only
            # those files from authenticated blobs; never trust their editable ignore rules or marker.
            with committed_snapshot(folder, item["commit"], expected) as snapshot:
                if not omarchy_to_satellite(snapshot, item["source_url"], item["commit"], sid=item["id"]):
                    raise Problem(CHANGED)
                for base, dirs, files in os.walk(snapshot, followlinks=False):
                    for name in files:
                        path = Path(base) / name
                        relative = path.relative_to(snapshot).as_posix()
                        if relative in expected:
                            continue
                        data = os.fsencode(os.readlink(path)) if path.is_symlink() else path.read_bytes()
                        mode = "120000" if path.is_symlink() else "100644"
                        oid = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest()
                        expected[relative] = (mode, oid)
        seen, total = set(), 0
        for base, dirs, files in os.walk(folder, followlinks=False, onerror=unreadable):
            if Path(base) == folder:
                dirs[:] = [name for name in dirs if name != ".git"]
                files = [name for name in files if name != ".git"]
            # A directory link cannot stand in for reviewed files beneath that directory.
            if any((Path(base) / name).is_symlink() for name in dirs):
                raise Problem(CHANGED)
            for name in files:
                path = Path(base) / name
                relative = path.relative_to(folder).as_posix()
                if relative not in expected:
                    raise Problem(CHANGED)  # Includes ignored files: they can contain executable content too.
                mode, oid = expected[relative]
                info = path.lstat()
                size = info.st_size
                total += size
                if total > THEME_IMPORT_LIMIT:
                    raise Problem(CHANGED)
                digest = hashlib.sha1(b"blob " + str(size).encode() + b"\0")
                if mode == "120000" and stat.S_ISLNK(info.st_mode):
                    data = os.fsencode(os.readlink(path))
                    if len(data) != size:
                        raise Problem(CHANGED)
                    digest.update(data)
                elif mode in {"100644", "100755"} and stat.S_ISREG(info.st_mode):
                    if bool(info.st_mode & 0o111) != (mode == "100755"):
                        raise Problem(CHANGED)
                    count = 0
                    with path.open("rb") as stream:
                        for data in iter(lambda: stream.read(65536), b""):
                            count += len(data)
                            if count > size:
                                raise Problem(CHANGED)
                            digest.update(data)
                    if count != size:
                        raise Problem(CHANGED)
                else:
                    raise Problem(CHANGED)
                if digest.hexdigest() != oid:
                    raise Problem(CHANGED)
                seen.add(relative)
        if seen != set(expected):
            raise Problem(CHANGED)
    except (OSError, ValueError, RecursionError) as error:
        raise Problem(CHANGED) from error


def find(sid, saved=None):
    data = catalog(saved)
    for item in data["satellites"]:
        if item["id"] == sid:
            return item
    for error in data["errors"]:
        if error["id"] == sid:
            raise Problem(error["reason"])
    for gone in data["hidden"]:
        if gone["id"] == sid:
            raise Problem(f"{gone['name']} was removed. Bring it back with: starchaser satellite restore {sid}")
    raise Problem(f'No add-on is called “{sid}”. Find one with: starchaser satellite search <words>')


def enabled(kind):
    return [item for item in catalog()["satellites"] if item["enabled"] and kind in item["kinds"]]


def entry_path(item, kind, default):
    return reference_path(Path(item["path"]), item["entry"].get(kind, default))


def theme_dirs():
    return [str(entry_path(item, "theme", "theme")) for item in enabled("theme")]


def theme_ids(items):
    """The theme ids these add-ons offer (the files in their theme folders)."""
    ids = set()
    for item in items:
        if "theme" in item.get("kinds", []):
            with contextlib.suppress(Problem, OSError):
                ids |= {f.stem for f in entry_path(item, "theme", "theme").glob("*.toml")}
    return ids


def theme_gone(ids):
    """A satellite's theme in use goes with it (turned off, removed, or safe mode): the theme engine puts the default
    back, as it does for a missing theme. Its colors used to stay, unreadable ones too, with no way out but a terminal."""
    try:
        active = json.loads(THEME_STATE.read_text()).get("id")
    except (OSError, ValueError, AttributeError):
        return
    if active not in ids:
        return
    with contextlib.suppress(OSError, subprocess.SubprocessError):
        subprocess.Popen([str(Path(__file__).resolve().with_name("starchaser-theme")), "reapply"],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)


def sanitize_rows(rows, run_limit=4096, ours=False):
    """Rows as the menu may show them. ours: the engine's own last pass, which keeps the ids and hidden flags it gave
    each satellite's own page (menu_page_id); a satellite's own rows never keep either."""
    count = 0

    def clean(nodes, depth):
        nonlocal count
        result = []
        if depth > 4 or not isinstance(nodes, list):
            return result
        for node in nodes:
            if count >= 200:
                break
            if not isinstance(node, dict) or not isinstance(node.get("label"), str) or not node["label"].strip():
                continue
            count += 1
            row = {"label": node["label"][:120].replace("\n", " ")}
            for key in ("icon", "run", "keys", "needs_file", "desc"):
                if isinstance(node.get(key), str):
                    row[key] = node[key][:run_limit if key == "run" else 500]
            for key in ("term", "stay", "info"):
                if type(node.get(key)) is bool:
                    row[key] = node[key]
            if ours and isinstance(node.get("id"), str) and re.fullmatch(r"satellite-[a-z0-9]+(?:-[a-z0-9]+)*", node["id"]):
                row["id"] = node["id"]
                if node.get("hidden") is True:
                    row["hidden"] = True
            needs = node.get("needs")
            if isinstance(needs, str):
                row["needs"] = needs[:120]
            elif isinstance(needs, list) and all(isinstance(n, str) for n in needs):
                row["needs"] = [n[:120] for n in needs[:20]]
            if "children" in node:
                row["children"] = clean(node["children"], depth + 1)
                if not row["children"]:
                    continue
            result.append(row)
        return result

    return clean(rows, 1)


def terminal_popup(run):
    """Apply placement to this launch only, with a plain terminal fallback."""
    command = "starchaser terminal --class menu-app -e sh -c " + shlex.quote(run)
    # Lua long strings preserve shell quoting and Unicode, including a row's newlines.
    equals = ""
    while f"]{equals}]" in command:
        equals += "="
    literal = f"[{equals}[{command}]{equals}]"
    script = f'hl.exec_cmd({literal}, {{ float = true, center = true, size = "min(800,monitor_w*0.9) min(480,monitor_h*0.8)" }})'
    return "hyprctl eval " + shlex.quote(script) + " >/dev/null 2>&1 || setsid -f " + command


def commands(rows, folder, sid=None):
    """Run a row in its add-on folder, like a Today card; a term row opens a terminal that waits for Enter."""
    for row in rows:
        if "run" in row:
            if sid:
                import hashlib
                token = hashlib.sha256(row["run"].encode()).hexdigest()
                run = shlex.quote(str(Path(__file__).resolve())) + " run-menu " + shlex.quote(sid) + " " + token
            else:
                run = f"cd {shlex.quote(folder)} && {{ {row['run']}\n}}"
            if row.pop("term", False):
                run += "; printf '\\nPress Enter to close.'; read -r _"
                run = terminal_popup(run)
            row["run"] = run
        row.pop("term", None)
        commands(row.get("children", []), folder, sid)
    return rows


def menu_page_id(sid):
    """The id the Super menu opens a satellite's own menu by (open-menu, toggle.sh): never one a satellite writes,
    since the rows it supplies have their ids taken out."""
    return "satellite-" + sid


def menu_rows(own_pages=False):
    """Enabled satellites' rows for the menu's Add-ons page. own_pages (menu-json): also each satellite's own menu,
    opened straight from a shortcut or its taskbar item (open-menu) by its engine-given id: the page itself when
    menu.json is one page; for a list of rows, a page of its own after the rows, hidden while browsing and in search
    (the menu puts it beside its other pages), so the rows under Add-ons stay where they were and nothing shows twice."""
    rows, pages = [], []
    for item in enabled("bar-widget"):
        published = jread_dict(RUN / item["id"] / "slot.json")
        label = str(published.get("label", "")).replace("\n", " ")[:40]
        tip = str(published.get("tip", "")).replace("\n", " ")[:300]
        rows.append({"label": "Add-on: " + item["name"] + (": " + label if label else ""),
                     "desc": tip, "run": "starchaser satellite click " + item["id"]})
    for kind in ("quick-tile", "desktop-widget"):
        rows.extend({"label": r["label"], "desc": r["text"], "run": r["run"]} for r in surface_rows(kind) if r["run"])
    for item in enabled("menu-page"):
        try:
            path = entry_path(item, "menu-page", "menu.json")
            if path.stat().st_size > 256 * 1024:
                continue
            value = json.loads(path.read_text())
            own = commands(sanitize_rows(value if isinstance(value, list) else [value]), item["path"], item["id"])
            if own_pages and not isinstance(value, list) and len(own) == 1 and own[0].get("children"):
                own[0]["id"] = menu_page_id(item["id"])
            elif own_pages and own:
                pages.append({"id": menu_page_id(item["id"]), "label": item["name"][:120], "hidden": True,
                              "children": json.loads(json.dumps(own))})
            rows.extend(own)
        except (OSError, ValueError, RecursionError, Problem):
            continue
    # The wrapped commands are longer than the 4 KB a satellite may write; this pass only caps the count (the rows
    # under Add-ons first, so the hidden copies are what a full menu leaves out).
    return sanitize_rows(rows + pages, 16384, ours=True)


def cards():
    result = []
    for item in enabled("today-card"):
        for path in sorted(entry_path(item, "today-card", "cards").glob("*.toml"))[:50]:
            try:
                if path.stat().st_size > 65536 or not path.resolve().is_relative_to(Path(item["path"]).resolve()):
                    continue
                card = tomllib.loads(path.read_text())
                title, run, every, show = (card.get(k) for k in ("title", "run", "every", "show"))
                if not isinstance(title, str) or not title or len(title) > 120 or "\n" in title:
                    continue
                if not isinstance(run, str) or not run or len(run) > 4096:
                    continue
                if type(every) is not int or every < 30 or every > 86400 or show not in {"number", "text", "list", "gauge", "progress"}:
                    continue
                result.append({"satellite_id": item["id"], "file_id": path.stem, "name": item["name"], "title": title,
                               "run": run, "cwd": item["path"], "command": ["sh", "-c", run], "every": every, "show": show})
            except (OSError, UnicodeError, tomllib.TOMLDecodeError, TypeError):
                continue
    return result


def data_dir(sid):
    return DATA / "satellite-data" / sid


def settings_path(sid):
    return data_dir(sid) / "settings.json"


def saved_settings(sid):
    """A page's saved values; a missing or unreadable file means every control shows its default."""
    try:
        value = json.loads(satellite_runtime.read_regular(settings_path(sid), 65536))
    except (OSError, ValueError):
        return {}
    return value if isinstance(value, dict) else {}


def satellite_env(sid, extra=None):
    """What every command an add-on runs is told: its id, its own folder for data, and its saved settings."""
    data_dir(sid).mkdir(parents=True, exist_ok=True)
    (RUN / sid).mkdir(parents=True, exist_ok=True, mode=0o700)
    env = {k: v for k, v in os.environ.items() if not k.startswith("STARCHASER_SETTING_")}
    # add-ons written before the one command run Starchaser's tools by their own names (starchaser satellite request):
    # their commands, and only theirs, also find the tools in Starchaser's own folder
    env["PATH"] = os.pathsep.join(p for p in (env.get("PATH", ""), str(Path(__file__).resolve().parent)) if p)
    env.update(STARCHASER_SATELLITE_ID=sid, STARCHASER_SATELLITE_DATA=str(data_dir(sid)),
               STARCHASER_SATELLITE_SETTINGS=str(settings_path(sid)), STARCHASER_SATELLITE_RUN=str(RUN / sid))
    for key, value in saved_settings(sid).items():
        if isinstance(key, str) and KEY_RE.fullmatch(key) and isinstance(value, (bool, int, float, str)):
            env["STARCHASER_SETTING_" + key.upper()] = text_value(value)[:1000].replace("\0", "")
    env.update(extra or {})
    return env


def text_value(value):
    if type(value) is bool:
        return "true" if value else "false"
    if isinstance(value, float) and value.is_integer():
        return str(int(value))
    return str(value)


def run_bounded(jobs, seconds, cap=4096):
    prepared, identities = [], {}
    for key, argv, cwd, env in jobs:
        sid = env.get("STARCHASER_SATELLITE_ID")
        if sid:
            item = enabled_item(sid)
            argv, env = execution(item, argv, env)
            activity_note(item, "command")
            identities[key] = sid
        prepared.append((key, argv, cwd, env))
    checked, permitted = 0.0, set()
    def gate(key):
        nonlocal checked, permitted
        if key not in identities:
            return True
        if time.monotonic() - checked >= 0.2:
            checked = time.monotonic()
            saved, policy = state(), managed_policy()
            permitted = {item["id"] for item in catalog(saved)["satellites"] if item["enabled"]}
        return identities[key] in permitted
    return satellite_runtime.run_bounded(prepared, seconds, cap, gate=gate)


def one_line(value, limit):
    return isinstance(value, str) and value.strip() and len(value) <= limit and "\n" not in value and "\0" not in value


def page_entry(item):
    """The declarative page file, or None when the add-on has none (or ships a code page for a later update)."""
    if "settings-page" not in item["kinds"]:
        return None
    path = entry_path(item, "settings-page", "page.toml")
    return path if path.suffix == ".toml" and path.is_file() else None


def code_page(item):
    """A settings page written in QML (Page.qml), shown in a window of its own process; None otherwise."""
    if "settings-page" not in item["kinds"]:
        return None
    path = entry_path(item, "settings-page", "page.toml")
    return path if path.suffix == ".qml" and path.is_file() else None


def widget_entry(item):
    """The taskbar item's QML file (Widget.qml unless the manifest names another), or None."""
    if "bar-widget" not in item["kinds"]:
        return None
    path = entry_path(item, "bar-widget", "Widget.qml")
    return path if path.suffix == ".qml" and path.is_file() else None


def read_page(item):
    """page.toml as checked controls. Any mistake is one plain sentence naming the control."""
    path = page_entry(item)
    if path is None:
        # one story with info: a QML page exists (its own window); it has no settings table to read and can't be
        # printed as JSON
        if code_page(item) is not None:
            raise Problem(f"This add-on's Settings page opens in its own window and can't be printed as JSON: "
                          f"it's written in QML, so it has no settings table to read. "
                          f"Open it with 'starchaser satellite open-page {item['id']}'.")
        raise Problem("This add-on has no Settings page.")
    try:
        if path.stat().st_size > 65536 or not path.resolve().is_relative_to(Path(item["path"]).resolve()):
            raise Problem("The Settings page file is too large.")
        page = tomllib.loads(path.read_text())
    except (OSError, UnicodeError, tomllib.TOMLDecodeError, RecursionError):
        raise Problem("The Settings page file couldn't be read.") from None
    title = page.get("title", item["name"])
    if not one_line(title, 120):
        raise Problem("The Settings page needs a one-line title.")
    intro = page.get("intro", "")
    if not isinstance(intro, str) or len(intro) > 1000:
        raise Problem("The Settings page intro must be text of 1,000 characters or fewer.")
    raw = page.get("controls")
    if not isinstance(raw, list) or not raw or len(raw) > 30 or not all(isinstance(c, dict) for c in raw):
        raise Problem("The Settings page needs between 1 and 30 [[controls]].")
    controls, keys = [], set()
    for index, c in enumerate(raw, 1):
        kind = c.get("type")
        where = f"Control {index}"
        if kind not in CONTROL_TYPES:
            raise Problem(f"{where} needs a type: switch, dropdown, slider, button, or note.")
        out = {"index": index - 1, "type": kind}
        if kind == "note":
            if not isinstance(c.get("text"), str) or not c["text"].strip() or len(c["text"]) > 2000:
                raise Problem(f"{where} is a note and needs its text.")
            out["text"] = c["text"].strip()
            controls.append(out)
            continue
        if not one_line(c.get("label"), 120):
            raise Problem(f"{where} needs a one-line label.")
        out["label"] = c["label"].strip()
        if "help" in c:
            if not isinstance(c["help"], str) or len(c["help"]) > 500:
                raise Problem(f"{where} help must be text of 500 characters or fewer.")
            out["help"] = c["help"].strip()
        if kind == "button":
            if not isinstance(c.get("run"), str) or not c["run"].strip() or len(c["run"]) > 4096:
                raise Problem(f"{where} is a button and needs a run command.")
            out["run"] = c["run"]
            if "done" in c and not one_line(c["done"], 200):
                raise Problem(f"{where} done must be one line.")
            out["done"] = c.get("done", "Done.")
            controls.append(out)
            continue
        if kind == "dropdown":
            options = c.get("options")
            if not isinstance(options, list) or not options or len(options) > 50:
                raise Problem(f"{where} is a dropdown and needs a list of options.")
            out["options"] = []
            for option in options:
                if isinstance(option, str):
                    option = {"label": option, "value": option}
                if not isinstance(option, dict) or not one_line(option.get("label"), 120) \
                        or not isinstance(option.get("value"), str) or len(option["value"]) > 200:
                    raise Problem(f"{where} options need a label and a value.")
                out["options"].append({"label": option["label"], "value": option["value"]})
            if len({o["value"] for o in out["options"]}) != len(out["options"]):
                raise Problem(f"{where} has two options with the same value.")
        if kind == "slider":
            low, high, step = c.get("min"), c.get("max", None), c.get("step", 1)
            if not all(isinstance(v, (int, float)) and type(v) is not bool and math.isfinite(v) for v in (low, high, step)) \
                    or not low < high or step <= 0 or step > high - low:
                raise Problem(f"{where} is a slider and needs a min below its max and a step that fits.")
            out.update(min=low, max=high, step=step)
            if "unit" in c and not one_line(c["unit"], 20):
                raise Problem(f"{where} unit must be a short word.")
            out["unit"] = c.get("unit", "")
        key, getter, setter = c.get("key"), c.get("get"), c.get("set")
        if key is not None:
            if getter is not None or setter is not None:
                raise Problem(f"{where} uses either a key or get and set commands, not both.")
            if not isinstance(key, str) or not KEY_RE.fullmatch(key):
                raise Problem(f"{where} key must use lowercase letters, digits, and underscores.")
            if key in keys:
                raise Problem(f"{where} uses the key {key} again.")
            keys.add(key)
            out["key"] = key
        else:
            if not all(isinstance(v, str) and v.strip() and len(v) <= 4096 for v in (getter, setter)):
                raise Problem(f"{where} needs a key, or both get and set commands.")
            out.update(get=getter, set=setter)
        try:
            out["default"] = coerce(out, c["default"]) if "default" in c else (
                False if kind == "switch" else out["options"][0]["value"] if kind == "dropdown" else out["min"])
        except Problem:
            raise Problem(f"{where} default isn't one of its choices.") from None
        controls.append(out)
    return {"title": title.strip(), "intro": intro.strip(), "controls": controls}


def coerce(control, raw):
    """A value for a control, from the page, a saved file, a command's output, or the command line."""
    kind = control["type"]
    if kind == "switch":
        if type(raw) is bool:
            return raw
        word = str(raw).strip().lower()
        if word in {"true", "on", "yes", "1"}:
            return True
        if word in {"false", "off", "no", "0"}:
            return False
    elif kind == "dropdown":
        word = raw if isinstance(raw, str) else text_value(raw)
        if word.strip() in [o["value"] for o in control["options"]]:
            return word.strip()
    elif kind == "slider" and type(raw) is not bool:
        try:
            number = float(raw)
        except (TypeError, ValueError):
            raise Problem("That value isn't a number.") from None
        if control["min"] <= number <= control["max"]:
            steps = round((number - control["min"]) / control["step"])
            number = round(min(control["max"], control["min"] + steps * control["step"]), 6)
            return int(number) if number.is_integer() else number
    raise Problem("That value isn't one of the choices.")


def enabled_item(sid):
    item = find(sid)
    if not item["enabled"]:
        raise Problem(f"Turn on {item['name']} first.")
    return item


def page_json(sid):
    """The page with each control's value now: saved settings for keys, the get command's answer otherwise."""
    item = enabled_item(sid)
    page = read_page(item)
    saved = saved_settings(sid)
    getters = [(c["index"], ["sh", "-c", c["get"]], item["path"], satellite_env(sid))
               for c in page["controls"] if "get" in c]
    answers = run_bounded(getters, COMMAND_SECONDS) if getters else {}
    for c in page["controls"]:
        if "key" in c:
            try:
                c["value"] = coerce(c, saved[c["key"]]) if c["key"] in saved else c["default"]
            except Problem:
                c["value"] = c["default"]
        elif "get" in c:
            status, output = answers.get(c["index"], (127, ""))
            lines = output.strip().splitlines()
            try:
                if status != 0 or not lines:
                    raise Problem("")
                c["value"] = coerce(c, lines[-1])
            except Problem:
                c["value"] = c["default"]
                c["problem"] = "Its current value couldn't be read."
            del c["get"], c["set"]
        c.pop("run", None)
    return {"id": sid, "name": item["name"], **page}


def page_control(sid, index):
    item = enabled_item(sid)
    page = read_page(item)
    if not 0 <= index < len(page["controls"]):
        raise Problem("That control isn't on this Settings page.")
    return item, page["controls"][index]


def page_set(sid, index, raw):
    item, control = page_control(sid, index)
    if control["type"] not in {"switch", "dropdown", "slider"}:
        raise Problem("That control doesn't hold a value.")
    value = coerce(control, raw)
    if "key" in control:
        data_dir(sid).mkdir(parents=True, exist_ok=True)
        with os.fdopen(os.open(data_dir(sid) / ".settings.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600), "a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            saved = saved_settings(sid)
            saved[control["key"]] = value
            atomic_json(settings_path(sid), saved)
    else:
        env = satellite_env(sid, {"STARCHASER_VALUE": text_value(value)})
        status, output = run_bounded([(0, ["sh", "-c", control["set"]], item["path"], env)], COMMAND_SECONDS)[0]
        if status != 0:
            log(sid, f"Changing {control['label']} failed ({'took too long' if status == 'timeout' else f'exit code {status}'}). " + output.strip()[:500])
            raise Problem(f"{control['label']} couldn't be changed. Show log has the details.")
    log(sid, f"{control['label']} is now {text_value(value)}.")
    print("Saved.")


def page_run(sid, index):
    item, control = page_control(sid, index)
    if control["type"] != "button":
        raise Problem("That control isn't a button.")
    status, output = run_bounded([(0, ["sh", "-c", control["run"]], item["path"], satellite_env(sid))], COMMAND_SECONDS)[0]
    if status != 0:
        log(sid, f"{control['label']} failed ({'took too long' if status == 'timeout' else f'exit code {status}'}). " + output.strip()[:500])
        raise Problem(f"{control['label']} didn't finish. Show log has the details.")
    log(sid, f"{control['label']} finished.")
    print(control["done"])


def hook_files(item):
    """{event: path} for this add-on's hooks: executable files inside its folder named after an event."""
    if "cli-hook" not in item["kinds"]:
        return {}
    root = Path(item["path"]).resolve()
    folder = entry_path(item, "cli-hook", "hooks")
    found = {}
    for event in EVENTS:
        path = folder / event
        if path.is_file() and path.resolve().is_relative_to(root) and os.access(path, os.X_OK):
            found[event] = path
    return found


def hook_vars(pairs):
    extra = {}
    for pair in pairs:
        name, sep, value = pair.partition("=")
        if not sep or not VAR_RE.fullmatch(name) or len(value) > 1000 or "\0" in value:
            raise Problem("Event details look like STARCHASER_NAME=value.")
        extra[name] = value
    return extra


def event_hooks(event):
    """[(item, path)] for the enabled satellites with a hook for this event. One satellite whose folder can't be
    read is skipped; it never stops the others' hooks."""
    found = []
    for item in enabled("cli-hook"):
        try:
            path = hook_files(item).get(event)
        except (OSError, Problem):
            continue
        if path:
            found.append((item, path))
    return found


def personal_hooks(event):
    """Plain executable files, sorted by name. Unreadable folders are an empty set."""
    try:
        return sorted((p for p in (PERSONAL_HOOKS / (event + ".d")).iterdir()
                       if p.is_file() and not p.is_symlink() and os.access(p, os.X_OK)), key=lambda p: p.name)
    except OSError:
        return []


def run_hooks(event, extra):
    """Every enabled add-on's hook for this event, side by side, each stopped after HOOK_SECONDS."""
    jobs = []
    for item, path in event_hooks(event):
        try:
            env = satellite_env(item["id"], {**extra, "STARCHASER_EVENT": event})
        except OSError as ex:
            with contextlib.suppress(OSError):
                log(item["id"], f"The {event} action could not start: {ex.strerror or ex}.")
            continue
        jobs.append((item["id"], [str(path)], item["path"], env))
    # read again just before starting: one switched off (or safe mode turned on) meanwhile runs nothing
    now = catalog()
    names = {item["id"]: item["name"] for item in now["satellites"]}
    still_on = {item["id"] for item in now["satellites"] if item["enabled"]}
    jobs = [job for job in jobs if job[0] in still_on]
    env = {k: v for k, v in os.environ.items() if not k.startswith("STARCHASER_SATELLITE_")}
    env.update(extra, STARCHASER_EVENT=event)
    jobs.extend(("personal:" + path.name, [str(path)], str(path.parent), env) for path in personal_hooks(event))
    if not jobs:
        return []
    results = run_bounded(jobs, HOOK_SECONDS, cap=2048)
    for sid, (status, output) in sorted(results.items()):
        if status == 0:
            sentence = f"The {event} action finished."
        elif status == "timeout":
            sentence = f"The {event} action took longer than {HOOK_SECONDS} seconds, so it was stopped."
        else:
            sentence = f"The {event} action stopped with exit code {status}."
        text = output.strip()
        with contextlib.suppress(OSError):
            log("personal-hooks" if sid.startswith("personal:") else sid,
                (sid + ": " if sid.startswith("personal:") else "") + sentence
                + ("\n  " + text.replace("\n", "\n  ") if text else ""))
        if status != 0 and not sid.startswith("personal:"):
            with contextlib.suppress(Problem, OSError):
                failure(sid, names.get(sid, sid))
    return sorted(results)


def hook(event, pairs, wait):
    if event not in EVENTS:
        raise Problem("Use one of these events: " + ", ".join(EVENTS) + ".")
    extra = hook_vars(pairs)
    if event == "lock":
        close_overlays()            # an overlay never stays up behind (or over) the lock screen
    if not event_hooks(event) and not personal_hooks(event):
        return
    # A caller that ignores the stop signals (the automatic updater, the lock script inside a service) would hand
    # that on to every hook, and a hook out of time would then only stop at the hard kill: the defaults, here.
    for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
        signal.signal(sig, signal.SIG_DFL)
    if not wait:
        # Whatever reported the event never waits for the hooks: they finish in a process of their own.
        if os.fork():
            return
        os.setsid()
        if os.fork():
            os._exit(0)
        devnull = os.open(os.devnull, os.O_RDWR)
        for fd in (0, 1, 2):
            os.dup2(devnull, fd)
        try:
            run_hooks(event, extra)
        finally:
            os._exit(0)
    run_hooks(event, extra)


def note_failure(saved, sid, name, window=60):
    """Record that an add-on's command stopped; three times in a minute (or in `window` seconds) turns it off."""
    record = saved["satellites"].setdefault(sid, {})
    now = time.time()
    failures = [t for t in record.get("failures", []) if isinstance(t, (int, float)) and now - window <= t <= now]
    failures.append(now)
    record["failures"] = failures[-3:]
    if len(failures) < 3:
        return f"{name} stopped."
    sentence = f"{name} kept stopping, so it's off."
    record.update(enabled=False, reason=sentence)
    return sentence


def failure(sid, name, window=60):
    with locked_state() as saved:
        sentence = note_failure(saved, sid, name, window)
        log(sid, sentence)
    return sentence


SAMPLE_LICENSE = """MIT License

Copyright (c) {year} {author}

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""


WIDGET_SAMPLE = """// A taskbar item. It runs in a process of its own; only Starchaser.Satellite (the SDK) is supported.
// The full reference is the Included Clock Seconds satellite (satellites/clock-seconds/Widget.qml).
import QtQuick
import Starchaser.Satellite 1.0

SatelliteWidget {
    id: widget
    label: "\\u{f0674}"                                  // a glyph or a few characters; the taskbar draws it
    tip: Satellite.name + "  \u00b7  click to open"      // the hover label
    onClicked: popup.toggle()

    Config { id: config }

    Popup {
        id: popup
        Label { width: parent.width; text: "Hello from your add-on." }
        Switch {
            width: parent.width
            text: "Say it twice"
            on: config.get("twice", false)
            onToggled: config.set("twice", !on)
        }
        Label { width: parent.width; visible: config.get("twice", false); text: "Hello again." }
        Button { text: "Send a notification"; onClicked: Notify.send(Satellite.name, "Hello from your add-on.") }
    }
}
"""


def new(sid, parent, with_hook, with_widget=False):
    """A working sample: a menu page, a Today card, and a Settings page whose choice the card reads."""
    if not ID_RE.fullmatch(sid) or len(sid) > 80:
        raise Problem("Use an add-on id with lowercase letters, digits, and dashes.")
    target = Path(parent) / sid
    if target.exists():
        raise Problem(f"{target} already exists.")
    name = sid.replace("-", " ").capitalize()
    kinds = ["menu-page", "today-card", "settings-page"] + (["cli-hook"] if with_hook else []) + (["bar-widget"] if with_widget else [])
    entry = 'menu-page = "menu.json", today-card = "cards/", settings-page = "page.toml"' + (
        ', cli-hook = "hooks/"' if with_hook else "") + (', bar-widget = "Widget.qml"' if with_widget else "")
    files = {
        "satellite.toml": f'''id = "{sid}"
name = "{name}"
version = "0.1.0"
summary = "A menu page, a Today card, and a Settings page."
author = "Your name"
license = "MIT"
homepage = "https://github.com/your-name/{sid}"

[starchaser]
api = {API}
sandbox = "restricted"
kinds = {json.dumps(kinds)}
entry = {{ {entry} }}

[permissions]
run = ["date", "notify-send"]
network = []
read = []
write = []
notify = true
location = false

[depends]
packages = ["coreutils", "libnotify"]
''',
        "README.md": f"""# {name}

A starting point made by `starchaser satellite new`. It adds a row under Add-ons in the menu, a Today card with
the date, and a Settings page (Settings > Satellites > {name}) whose choice changes how the card shows the date.

Try it:

    starchaser satellite check .
    starchaser satellite install . --yes
    starchaser satellite enable {sid}

Edit the files, then remove and install it again to see the changes.
""",
        "LICENSE": SAMPLE_LICENSE.format(year=time.strftime("%Y"), author="Your name"),
        "menu.json": json.dumps({"label": name, "children": [
            {"label": "Say hello", "run": f"starchaser satellite request notify {shlex.quote(name)} 'Hello from your add-on.'"}]}, indent=2) + "\n",
        "cards/date.toml": '''title = "Today's date"
run = "./bin/date-card"
every = 60
show = "text"
''',
        "bin/date-card": '''#!/bin/sh
# Prints one line of JSON for the Today card. The Settings page's choice arrives as STARCHASER_SETTING_DATE_STYLE.
if [ "${STARCHASER_SETTING_DATE_STYLE:-long}" = short ]; then
    day=$(date '+%-m/%-d/%Y')
else
    day=$(date '+%A, %B %-d')
fi
printf '{"text":"%s"}\\n' "$day"
''',
        "page.toml": '''title = "Date card"
intro = "Choose how the Today card shows the date."

[[controls]]
type = "dropdown"
label = "Date style"
key = "date_style"
default = "long"
options = [
    { label = "Weekday and month (Tuesday, October 13)", value = "long" },
    { label = "Numbers (10/13/2026)", value = "short" },
]

[[controls]]
type = "note"
text = "The card picks up a new choice the next time it updates, within a minute."
''',
    }
    if with_hook:
        files["hooks/theme-changed"] = '''#!/bin/sh
# Runs when the theme or dark and light mode changes. It has 5 seconds; its output goes to the satellite's log.
printf '%s %s (%s)\\n' "$(date '+%Y-%m-%d %H:%M')" "$STARCHASER_THEME" "$STARCHASER_THEME_MODE" \\
    >> "$STARCHASER_SATELLITE_DATA/theme-changes.txt"
'''
    if with_widget:
        files["Widget.qml"] = WIDGET_SAMPLE
    target.mkdir(parents=True)
    for rel, text in files.items():
        path = target / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(text)
        if rel.startswith(("bin/", "hooks/")):
            path.chmod(0o755)
    print(f"Made {name} in {target}. Check it with: starchaser satellite check {shlex.quote(str(target))}")


# ---------- new --kind / --theme: one small working add-on, made to share (Settings: Make your own, Share this look)

AUTHOR_DIR = Path(os.environ.get("STARCHASER_SATELLITE_HOME") or Path.home() / "Satellites")
NEW_KINDS = ("theme", "today-card", "bar-widget", "menu-page", "panel", "overlay", "service", "cli-hook", "settings-page", "quick-tile", "search-result", "desktop-widget", "lock-widget", "file-action")


def sample_text(sample, rel, replace):
    """A file of one of the developer samples that come with Starchaser (sample-panel, sample-service), with its
    names changed for a new add-on: the starters for new --kind panel and service are the samples themselves."""
    for base in INCLUDED:
        path = base / sample / rel
        if path.is_file() and not path.is_symlink():
            text = path.read_text()
            for old, new in replace.items():
                text = text.replace(old, new)
            return text
    raise Problem(f"The {sample} example that this starts from is missing, so nothing was made.")


def name_to_id(text):
    """("my-look", "My Look") for "My Look"; an id as given keeps itself ("night-cards" -> "Night cards")."""
    import unicodedata
    text = (text or "").strip()
    if any(ord(c) < 32 or 0x7f <= ord(c) < 0xa0 or c in "  " for c in text):
        raise Problem("Keep the name to one line of plain text.")
    if len(text) > 80:
        raise Problem("Keep the name to 80 characters or fewer.")
    if ID_RE.fullmatch(text):
        return text, text.replace("-", " ").capitalize()
    folded = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
    sid = re.sub(r"[^a-z0-9]+", "-", folded.lower()).strip("-")[:80].strip("-")
    if not sid:
        raise Problem("Give it a name with at least one letter or number.")
    return sid, text


def author_parent(parent):
    """The folder the new add-on goes in: ~/Satellites (what Settings passes) is AUTHOR_DIR, made when missing."""
    raw = str(parent)
    path = AUTHOR_DIR if raw.rstrip("/") in ("~/Satellites", str(Path.home() / "Satellites")) else Path(raw).expanduser()
    if path == AUTHOR_DIR:
        path.mkdir(parents=True, exist_ok=True)
    return path


SHARE_README = """## Try it live

    starchaser satellite dev .

Changes you save show at once while it runs. `starchaser satellite check .` finds mistakes before you share it.

## Share it

Put this folder on any public git site (GitHub, GitLab, Codeberg, or another) and send people its link. They
paste the link into Settings > Satellites > Add from a link. Before anything is turned on they see
what it adds and what it may do, and they get exactly the version you shared; a newer one reaches them only
when they agree to it after seeing what changed.

Before sharing, change `author` and `homepage` in satellite.toml to your own.
"""


def new_files(sid, name, kinds, entry, summary, permissions, packages):
    perms = "\n".join(f"{k} = {json.dumps(v)}" for k, v in permissions.items())
    return {
        "satellite.toml": f'''id = "{sid}"
name = {json.dumps(name)}
version = "0.1.0"
summary = {json.dumps(summary)}
author = "Your name"
license = "MIT"
homepage = "https://github.com/your-name/{sid}"

[starchaser]
api = {API}
sandbox = "restricted"
kinds = {json.dumps(kinds)}
entry = {{ {entry} }}

[permissions]
{perms}

[depends]
packages = {json.dumps(packages)}
''',
        "LICENSE": SAMPLE_LICENSE.format(year=time.strftime("%Y"), author="Your name"),
    }


def write_new(target, files, sid, name, kinds, as_json):
    """Write the folder, check it the way installing would, and say where it is (or take it away again)."""
    target.mkdir(parents=True)
    try:
        for rel, text in files.items():
            path = target / rel
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(text)
            if rel.startswith(("bin/", "hooks/")):
                path.chmod(0o755)
    except OSError:
        shutil.rmtree(target, ignore_errors=True)
        raise
    finish_new(target, sid, name, kinds, as_json)


def finish_new(target, sid, name, kinds, as_json):
    try:
        _, problems = check_folder(target)
    except Problem as ex:
        problems = [str(ex)]
    if problems:
        shutil.rmtree(target, ignore_errors=True)
        raise Problem(problems[0])
    nxt = f"starchaser satellite dev {shlex.quote(str(target))}"
    if as_json:
        print(json.dumps({"ok": True, "id": sid, "name": name, "path": str(target), "kinds": kinds, "next": nxt}))
    else:
        print(f"Made {name} in {target}. Try it live with: {nxt}")


def new_kind(sid, name, parent, kind, as_json=False):
    """A small working add-on of one kind: a Today card, a taskbar item, or a menu page."""
    if kind == "theme":
        return new_theme(sid, name, parent, False, as_json)
    if kind not in NEW_KINDS:
        raise Problem("Choose a kind: " + ", ".join(NEW_KINDS[:-1]) + ", or " + NEW_KINDS[-1] + ".")
    target = author_parent(parent) / sid
    if target.exists():
        raise Problem(f"{target} already exists. Choose another name.")
    if sid in taken_ids(state()):           # dev refuses it, so Try it now could never work
        raise Problem("An add-on with that id is already here. Choose another name.")
    none = {"run": [], "network": [], "read": [], "write": [], "notify": False, "location": False}
    if kind in SURFACE_KINDS:
        access = {**none, "selected_file": kind == "file-action"}
        files = new_files(sid, name, [kind], kind + ' = "' + kind + '.json"', "A declarative add-on surface.", access, [])
        row = {"label": name, "text": "Change this public text in " + kind + ".json."}
        if kind == "file-action":
            row["run"] = 'sha256sum -- "$STARCHASER_FILE"'
        files[kind + ".json"] = json.dumps([row], indent=2) + "\n"
        what = "It adds a declarative " + kind + ". Only lock widgets are shown while locked, and they cannot run commands."
    elif kind == "today-card":
        files = new_files(sid, name, [kind], 'today-card = "cards/"', "A Today card with the date.",
                          {**none, "run": ["date"]}, ["coreutils"])
        files["cards/date.toml"] = 'title = "Today\'s date"\nrun = "./bin/date-card"\nevery = 60\nshow = "text"\n'
        files["bin/date-card"] = '''#!/bin/sh
# Prints one line of JSON for the Today card: {"text": "..."}. Change it to show anything you like.
printf '{"text":"%s"}\\n' "$(date '+%A, %B %-d')"
'''
        what = "It adds a card to Today that shows the date. The card runs `bin/date-card` every minute; edit `cards/date.toml` and that script."
    elif kind == "bar-widget":
        files = new_files(sid, name, [kind], 'bar-widget = "Widget.qml"', "A taskbar item with a small popup.",
                          {**none, "notify": True}, [])
        files["Widget.qml"] = WIDGET_SAMPLE
        what = "It adds an item to the taskbar that opens a small popup. Edit `Widget.qml`; it runs in a process of its own."
    elif kind == "panel":
        names = {"Sample Panel": name, "sample-panel": sid}
        files = new_files(sid, name, ["bar-widget", "panel"], 'bar-widget = "Widget.qml", panel = "Panel.qml"',
                          "A taskbar item that opens its own panel.", none, [])
        files["Widget.qml"] = sample_text("sample-panel", "Widget.qml", names)
        files["Panel.qml"] = sample_text("sample-panel", "Panel.qml", names)
        what = ("It adds a taskbar item that opens its own panel. Edit `Panel.qml` (the panel) and `Widget.qml` (the "
                f"item); a keyboard shortcut can open it too: starchaser satellite open-panel {sid}")
    elif kind == "overlay":
        names = {"Sample Overlay": name, "sample-overlay": sid}
        files = new_files(sid, name, ["bar-widget", "overlay"], 'bar-widget = "Widget.qml", overlay = "Overlay.qml"',
                          "A taskbar item that opens a full-screen overlay.", none, [])
        files["Widget.qml"] = sample_text("sample-overlay", "Widget.qml", names)
        files["Overlay.qml"] = sample_text("sample-overlay", "Overlay.qml", names)
        what = ("It adds a taskbar item that opens a full-screen overlay with a clock. Edit `Overlay.qml`; Escape and "
                f"the close x always close it. A keyboard shortcut can open it too: starchaser satellite open-overlay {sid}")
    elif kind == "service":
        files = new_files(sid, name, ["service"], 'service = "bin/service"',
                          "A background service that writes the time to a file once a minute.",
                          {**none, "run": ["sh", "date", "sleep", "mv"], "write": ["its own data folder"]}, ["coreutils"])
        files["bin/service"] = sample_text("sample-service", "bin/service", {"Sample Background Service": name})
        what = ("It runs `bin/service` in the background while it is on, and its output goes to its log (Settings > "
                "Add-ons > Details > Show log). Edit that script; list every program it runs under [permissions] run.")
    elif kind == "cli-hook":
        files = new_files(sid, name, ["cli-hook"], 'cli-hook = "hooks/"', "Actions that run when the theme changes.",
                          {**none, "run": ["date"]}, ["coreutils"])
        files["hooks/theme-changed"] = '''#!/bin/sh
# Runs when the theme or dark and light mode changes. It has 5 seconds; its output goes to the add-on's log.
# Other moments: name a file in hooks/ after one of session-start, session-end, lock, unlock, network-changed,
# before-update or after-update.
printf '%s %s (%s)\\n' "$(date '+%Y-%m-%d %I:%M %p')" "$STARCHASER_THEME" "$STARCHASER_THEME_MODE" \\
    >> "$STARCHASER_SATELLITE_DATA/theme-changes.txt"
'''
        what = "It runs `hooks/theme-changed` each time the theme or dark and light mode changes. Add more files to `hooks/`, named after their moment."
    elif kind == "settings-page":
        files = new_files(sid, name, ["settings-page"], 'settings-page = "page.toml"', "A page of choices in Settings.", none, [])
        files["page.toml"] = f'''title = {json.dumps(name)}
intro = "Choices for this add-on. Its other parts read them as STARCHASER_SETTING_<KEY>."

[[controls]]
type = "switch"
label = "Say hello"
key = "say_hello"
default = true

[[controls]]
type = "note"
text = "Add switches, dropdowns, sliders and buttons here; each one is a [[controls]] table."
'''
        what = "It adds a page in Settings > Add-ons with one switch. Edit `page.toml` to add choices."
    else:
        files = new_files(sid, name, [kind], 'menu-page = "menu.json"', "A menu page with one row.",
                          {**none, "run": ["starchaser satellite request"], "notify": True}, [])
        files["menu.json"] = json.dumps({"label": name, "children": [
            {"label": "Say hello", "run": f"starchaser satellite request notify {shlex.quote(name)} 'Hello from your add-on.'"}]}, indent=2) + "\n"
        what = "It adds a page under Add-ons in the Super menu with one row. Edit `menu.json` to add rows."
    files["README.md"] = f"# {name}\n\n## What it does\n\n{plain_description(kind)}\n\n## For the author\n\n{what}\n\n" + SHARE_README
    write_new(target, files, sid, name, [kind], as_json)


def plain_description(kind):
    return {"panel": "A small window with useful information.", "bar-widget": "A button on your taskbar.",
            "quick-tile": "A button in quick settings.", "search-result": "An answer in the menu when someone types.",
            "desktop-widget": "A small box on the desktop.", "lock-widget": "A line everyone can read on the lock screen.",
            "file-action": "A right-click action in Files.", "today-card": "A small box in Today.",
            "settings-page": "Choices for this add-on in Settings.", "menu-page": "A page in the menu.",
            "service": "A helper that runs in the background.", "cli-hook": "An action at a set moment."}.get(kind, "A personal add-on.")


def new_theme(sid, name, parent, from_current, as_json=False):
    """A theme add-on: the Starchaser Cockpit palette as a start, or with from_current what you see now."""
    target = author_parent(parent) / sid
    if target.exists():
        raise Problem(f"{target} already exists. Choose another name.")
    if sid in taken_ids(state()):           # dev refuses it, so Try it now could never work
        raise Problem("An add-on with that id is already here. Choose another name.")
    none = {"run": [], "network": [], "read": [], "write": [], "notify": False, "location": False}
    files = new_files(sid, name, ["theme"], 'theme = "theme/"',
                      "Your look: colors, window style and wallpaper." if from_current else "A color theme.", none, [])
    made = ("It holds your look as it was when you made it: the theme colors with your color changes, the window "
            "and glass style, and the wallpaper, in `theme/" + sid + ".toml`" if from_current else
            "It starts as a copy of the Starchaser Cockpit colors in `theme/" + sid + ".toml`; change the colors there")
    files["README.md"] = (f"# {name}\n\nA theme add-on (add-on) made by `starchaser satellite new`. {made}. Fonts "
                          "are not part of a theme, so they are not included.\n\nWallpapers you add go in "
                          f"`theme/wallpapers/`, named `{sid}-dark-<width>x<height>.png` and "
                          f"`{sid}-light-<width>x<height>.png`. Only share pictures you're allowed to share.\n\n"
                          + SHARE_README)
    target.mkdir(parents=True)
    try:
        for rel, text in files.items():
            (target / rel).write_text(text)
        cmd = [sys.executable, str(Path(__file__).resolve().with_name("starchaser-theme")), "export",
               "--dir", str(target / "theme"), "--id", sid, "--name", name, "--json"] + (["--from-current"] if from_current else [])
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL)
        except (OSError, subprocess.SubprocessError):
            raise Problem("The theme couldn't be made.") from None
        if result.returncode != 0:
            try:
                reason = json.loads(result.stdout.strip().splitlines()[-1])["errors"]
            except (ValueError, IndexError, KeyError, TypeError):
                reason = result.stderr.strip().removeprefix("starchaser theme: ") or "The theme couldn't be made."
            raise Problem(reason)
    except BaseException:
        shutil.rmtree(target, ignore_errors=True)
        raise
    finish_new(target, sid, name, ["theme"], as_json)


def check_folder(folder):
    """Every problem an author can fix, one sentence each; the manifest comes first since the rest needs it."""
    folder = Path(folder)
    if not (folder / "satellite.toml").is_file():
        raise Problem("This isn't an add-on folder: satellite.toml is missing.")
    check_tree(folder)
    m = manifest(folder)
    item = {**m, "path": str(folder.resolve()), "source": "Local folder"}
    problems = []
    if not (folder / "LICENSE").is_file():
        problems.append("Add a LICENSE file.")
    if not (folder / "README.md").is_file():
        problems.append("Add a README.md that says what the add-on does.")
    if "menu-page" in m["kinds"]:
        try:
            value = json.loads(entry_path(item, "menu-page", "menu.json").read_text())
            if not sanitize_rows(value if isinstance(value, list) else [value]):
                problems.append("menu.json has no rows with a label.")
        except (OSError, ValueError, RecursionError):
            problems.append("menu.json could not be read as JSON.")
    if "today-card" in m["kinds"]:
        folder_cards = sorted(entry_path(item, "today-card", "cards").glob("*.toml"))
        if not folder_cards:
            problems.append("Add a card file to cards/.")
        for path in folder_cards:
            try:
                card = tomllib.loads(path.read_text())
            except (OSError, UnicodeError, tomllib.TOMLDecodeError):
                problems.append(f"{path.name} could not be read.")
                continue
            if not one_line(card.get("title"), 120) or not isinstance(card.get("run"), str) or not card["run"] \
                    or type(card.get("every")) is not int or not 30 <= card["every"] <= 86400 \
                    or card.get("show") not in {"number", "text", "list", "gauge", "progress"}:
                problems.append(f"{path.name} needs a title, a run command, every (30 to 86400 seconds), and show.")
    if "settings-page" in m["kinds"]:
        if page_entry(item) is not None:
            try:
                read_page(item)
            except Problem as ex:
                problems.append(str(ex))
        elif code_page(item) is not None:
            problems.extend(qml_problems(code_page(item), folder))
        else:
            problems.append("Add the settings page: page.toml, or Page.qml for one written in QML.")
    if "bar-widget" in m["kinds"]:
        widget = widget_entry(item)
        if widget is None:
            problems.append("Add the taskbar item: Widget.qml, with SatelliteWidget from Starchaser.Satellite at its root.")
        else:
            problems.extend(qml_problems(widget, folder))
            if not re.search(r"^\s*SatelliteWidget\s*\{", widget.read_text(errors="replace"), re.M):
                problems.append(f"{widget.name} needs SatelliteWidget at its root: the taskbar shows only what it publishes.")
    if "cli-hook" in m["kinds"]:
        hooks = entry_path(item, "cli-hook", "hooks")
        names = sorted(p.name for p in hooks.iterdir()) if hooks.is_dir() else []
        for name in names:
            if name not in EVENTS:
                problems.append(f"hooks/{name} is not an event; use one of: " + ", ".join(EVENTS) + ".")
            elif not os.access(hooks / name, os.X_OK):
                problems.append(f"hooks/{name} must be executable (chmod +x).")
            else:
                problems.extend(hook_problems(hooks / name))
        if not names:
            problems.append("Add a hook file to hooks/, named after its event.")
    if "service" in m["kinds"]:
        problems.extend(service_problems(item))
    if "panel" in m["kinds"]:
        panel = entry_path(item, "panel", "Panel.qml")
        name = item["entry"].get("panel", "Panel.qml")
        if panel.suffix != ".qml" or not panel.is_file():
            problems.append(f"Add the panel: {name}, with SatellitePanel from Starchaser.Satellite at its root.")
        else:
            problems.extend(qml_problems(panel, folder))
            if not re.search(r"^\s*SatellitePanel\s*\{", panel.read_text(errors="replace"), re.M):
                problems.append(f"{panel.name} needs SatellitePanel at its root: that is what gives a panel its frame and its close x.")
    if "overlay" in m["kinds"]:
        overlay = entry_path(item, "overlay", "Overlay.qml")
        name = item["entry"].get("overlay", "Overlay.qml")
        if overlay.suffix != ".qml" or not overlay.is_file():
            problems.append(f"Add the overlay: {name}, with SatelliteOverlay from Starchaser.Satellite at its root.")
        else:
            problems.extend(qml_problems(overlay, folder))
            text = overlay.read_text(errors="replace")
            if not re.search(r"^\s*SatelliteOverlay\s*\{", text, re.M):
                problems.append(f"{overlay.name} needs SatelliteOverlay at its root: that is what lets Escape and the close x always close it.")
            if re.search(r"\b(onShortcutOverride|WlrLayershell|PanelWindow|FloatingWindow|PopupWindow)\b", text):
                problems.append(f"{overlay.name} may not open windows of its own or take over keys; Starchaser draws the overlay and its close x.")
    for kind in m["kinds"]:
        if kind not in KINDS and kind not in LATER:
            problems.append(f"{kind} is not an add-on kind.")
    moves = pointer_problem(folder)
    if moves:
        problems.append(moves)
    return m, problems


def hook_problems(path):
    """A shell hook that can't be read as a script (parse only, nothing runs), found with the shell's own -n check.
    Hooks in other languages are left to their author."""
    try:
        first = path.read_text(errors="replace").split("\n", 1)[0]
    except OSError:
        return []
    shell = next((w for w in re.split(r"\s+", first[2:].strip()) if first.startswith("#!") and Path(w).name in {"sh", "bash", "dash"}), None)
    if not shell or not shutil.which(Path(shell).name):
        return []
    try:
        result = subprocess.run([Path(shell).name, "-n", str(path)], capture_output=True, text=True, timeout=10)
    except (OSError, subprocess.SubprocessError):
        return []
    if result.returncode:
        text = (result.stderr.strip().splitlines() or ["syntax error"])[0].replace(str(path) + ": ", "")
        return [f"hooks/{path.name} has a mistake that stops it from running: {text[:300]}"]
    return []


def qml_problems(path, folder):
    """The QML mistakes that stop a file from loading, found by qmllint with the SDK on its import path. Style warnings
    are left to the author; a computer without qmllint skips this part."""
    linter = shutil.which("qmllint") or next((str(p) for p in (Path("/usr/lib/qt6/bin/qmllint"),) if p.is_file()), None)
    if not linter:
        return []
    try:
        result = subprocess.run([linter, "-I", str(SDK_DIR), str(path)], capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.SubprocessError):
        return []
    for line in (result.stdout + result.stderr).splitlines():
        if "[syntax]" in line or "Syntax error" in line or "Expected token" in line:
            text = re.sub(r"^(Error|Warning):\s*", "", line).removesuffix("[syntax]").strip()
            text = text.replace(str(Path(folder).resolve()) + "/", "").replace(str(folder) + "/", "")
            return [f"{path.name} has a mistake that stops it from loading: {text[:300]}"]
    return []


def pointer_problem(folder):
    """One sentence when anything in the folder would move the pointer (Starchaser's own check), else ""."""
    checker = Path(__file__).resolve().parent / "starchaser-check-pointer"
    if not checker.is_file():
        return ""
    try:
        result = subprocess.run([str(checker), str(folder)], capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.SubprocessError):
        return ""
    if result.returncode == 1:
        return "Satellites never move the pointer: " + (result.stdout + result.stderr).strip()[:500]
    return ""


# The list of satellites (Find more). By default it is the file that comes with Starchaser (index.toml beside the
# included satellites; no network). A url in ~/.config/starchaser/satellite-index.toml points it at the shared list,
# which is fetched at most once a day (or on Check again) and kept for offline use. A .sig beside the list is
# checked with the same keys as the Starchaser package repository; a list with no .sig is shown with a plain warning.
# Starchaser's online list is list.json (format 1, built and signed with the release key by tools/satellites-list);
# an address or file ending in .json is read as that JSON, anything else as the index.toml format.
SHARED_INDEX = "https://downloads.starchaserlinux.org/satellites/list.json"
# Theme preview pictures the online list may point at directly (no other host is ever loaded by Find more)
PREVIEW_HOST = "https://downloads.starchaserlinux.org/satellites/previews/"
# Where the online list was planned before list.json; a setting that still names it (index --use shared, before)
# reads the online list instead of a "no list at its address" problem.
OLD_SHARED_INDEX = "https://raw.githubusercontent.com/starchaserlinux/satellites/main/index.toml"
INDEX_CONFIG = CONFIG / "satellite-index.toml"
CACHE = Path(os.environ.get("XDG_CACHE_HOME", HOME / ".cache")) / "starchaser/satellite-index"
INDEX_MAX_AGE = 86400
INDEX_BYTES = 1024 * 1024
KEYRING = Path(os.environ.get("STARCHASER_SATELLITES_KEYRING", "/usr/share/pacman/keyrings/starchaser.gpg")
               if TEST_OVERRIDES else "/usr/share/pacman/keyrings/starchaser.gpg")
REVIEWS = ("included", "reviewed", "unreviewed", "removed")
SHA_RE = re.compile(r"[0-9a-f]{40}\Z")
REVIEWED_NOTE = "A person at Starchaser read every file of this version before it was listed. It installs exactly that version."
REMOVED_DEFAULT = "Starchaser took it off the list."
NOT_SIGNED = satellite_list.NOT_SIGNED


class Unreachable(Exception):
    """The shared list couldn't be fetched (offline, a server problem, or a timeout)."""


class NotThere(Problem):
    """The server answered that there is no list at the address."""


# Starchaser's own online list, while it isn't published yet (its address answers 404 or 410): said as news, not as
# a problem with an address. Find more shows it as plain text (state "soon").
SHARED_NOT_YET = ("Coming soon: an online list of add-ons checked by Starchaser. Until then, use the ones that come "
                  "with Starchaser, or add one from a link.")


def index_path():
    override = os.environ.get("STARCHASER_SATELLITES_INDEX") if TEST_OVERRIDES else None
    if override:
        return Path(override)
    for base in INCLUDED:
        if (base / "index.toml").is_file():
            return base / "index.toml"
    return None


def index_url_ok(url):
    if re.fullmatch(r"https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?/\S*", url):
        return True
    # Offline tests opt in explicitly, the same switch as local Git links.
    return test_git() and url.startswith("file:///")


def index_url():
    """The address Find more reads, or "" for the list that comes with Starchaser."""
    if TEST_OVERRIDES and os.environ.get("STARCHASER_SATELLITES_INDEX"):
        return ""
    try:
        data = tomllib.loads(INDEX_CONFIG.read_text())
    except FileNotFoundError:
        return SHARED_INDEX
    except (OSError, UnicodeError, tomllib.TOMLDecodeError):
        raise Problem(f"The add-on list setting couldn't be read. Check {INDEX_CONFIG}.") from None
    url = data.get("url", "")
    if not isinstance(url, str):
        raise Problem(f"The add-on list address in {INDEX_CONFIG} must be text.")
    url = url.strip()
    if url and not index_url_ok(url):
        raise Problem("The add-on list address must start with https://.")
    return SHARED_INDEX if url == OLD_SHARED_INDEX else url


def use_index(where):
    """Point Find more at a list: local (the one that comes with Starchaser), shared, or an https address."""
    url = "" if where == "local" else SHARED_INDEX if where == "shared" else where.strip()
    if url and not index_url_ok(url):
        raise Problem("Use local, shared, or an address that starts with https://.")
    text = ("# Where Settings > Satellites > Find more reads the list of add-ons.\n"
            "# Empty: the list that comes with Starchaser (no network). The shared list is:\n"
            f"# {SHARED_INDEX}\n"
            f"url = {json.dumps(url)}\n")
    CONFIG.mkdir(parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(prefix=f".{INDEX_CONFIG.name}.", dir=CONFIG)
    try:
        with os.fdopen(fd, "w") as stream:
            stream.write(text)
        os.replace(name, INDEX_CONFIG)
    finally:
        Path(name).unlink(missing_ok=True)
    print(f"Find more now reads {url}." if url else "Find more now reads the list that comes with Starchaser.")


def revoked_keys():
    return satellite_list.revoked_keys(KEYRING)


def check_signature(data, sig):
    """(status, sentence) for the list: signed, unsigned, unchecked or bad, against the keyring in KEYRING."""
    return satellite_list.check_signature(data, sig, KEYRING)


def theme_previews(value, repo, commit, local_root=None):
    """Only palette colors and raster paths inside the listed version can reach the preview UI."""
    result = {}
    if not isinstance(value, dict):
        return result
    for mode in ("dark", "light"):
        preview = value.get(mode)
        if not isinstance(preview, dict):
            continue
        palette = preview.get("palette")
        roles = ("bg", "surface", "text", "accent")
        if not isinstance(palette, dict) or not all(
                isinstance(palette.get(k), str) and re.fullmatch(r"#[0-9a-fA-F]{6}", palette[k]) for k in roles):
            continue
        thumb = preview.get("thumbnail", "")
        source = ""
        # No URLs, absolute paths, traversal, escapes, or executable image formats from the catalog. The one exception
        # is a raster picture on Starchaser's own download host, where the online list keeps its previews.
        if (isinstance(thumb, str) and len(thumb) <= 240 and thumb.startswith(PREVIEW_HOST)
                and re.fullmatch(re.escape(PREVIEW_HOST) + r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*\.(?:png|jpg|jpeg|webp)", thumb)):
            source = thumb
        elif (isinstance(thumb, str) and len(thumb) <= 240
                and re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*\.(?:png|jpg|jpeg|webp)", thumb)):
            if re.fullmatch(r"https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/?", repo) and SHA_RE.fullmatch(commit):
                project = repo.removeprefix("https://github.com/").rstrip("/").removesuffix(".git")
                if all(part not in {"", ".", ".."} for part in project.split("/")):
                    source = f"https://raw.githubusercontent.com/{project}/{commit}/{thumb}"
            elif not repo and local_root is not None:
                with contextlib.suppress(OSError, RuntimeError):
                    path = (local_root / thumb).resolve()
                    if path.is_relative_to(local_root.resolve()) and path.is_file():
                        source = path.as_uri()
        result[mode] = {"thumbnail": source, "palette": {k: palette[k] for k in roles}}
    return result


def gallery_screenshot(entry, local_root):
    if entry.get("review") == "included" and local_root is not None:
        folder = local_root / entry["id"]
        path = folder / ("preview.png" if (folder / "preview.png").is_file() else "preview.svg")
        if path.is_file() and path.resolve().is_relative_to(local_root.resolve()):
            return path.resolve().as_uri()
    source = entry.get("screenshot", "")
    if isinstance(source, str) and re.fullmatch(re.escape(PREVIEW_HOST) + r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*\.(?:png|jpg|jpeg|webp)", source):
        return source
    return ""


def parse_entries(listed, local_root=None):
    """The entries Find more can show, from a list of entry tables (either list format). An entry that breaks a rule
    is skipped, never guessed at: an outside one must name an exact 40-character commit of a link install accepts."""
    entries, seen = [], set()
    for entry in listed if isinstance(listed, list) else []:
        if not isinstance(entry, dict) or not isinstance(entry.get("id"), str) or not ID_RE.fullmatch(entry["id"]):
            continue
        if entry["id"] in seen or not one_line(entry.get("name"), 120) or not one_line(entry.get("summary"), 500):
            continue
        kinds = [k for k in entry.get("kinds", []) if isinstance(k, str)] if isinstance(entry.get("kinds"), list) else []
        review = entry.get("review") if entry.get("review") in REVIEWS else "unreviewed"
        repo, commit = entry.get("repo", ""), entry.get("commit", "")
        repo = repo.strip() if isinstance(repo, str) else ""
        commit = commit.strip().lower() if isinstance(commit, str) else ""
        # an outside entry must name the exact reviewed commit of a repository install accepts; anything else is skipped
        if review in {"reviewed", "unreviewed"} and (not git_link(repo) or not SHA_RE.fullmatch(commit)):
            continue
        api = entry.get("api", API)
        version = entry.get("version", "")
        seen.add(entry["id"])
        entries.append({"id": entry["id"], "name": entry["name"].strip(), "summary": entry["summary"].strip(), "kinds": kinds,
                        "screenshot": gallery_screenshot(entry, local_root),
                        "review": review.capitalize(), "repo": repo, "commit": commit, "icon": str(entry.get("icon", ""))[:4],
                        "previews": theme_previews(entry.get("previews"), repo, commit, local_root) if "theme" in kinds else {},
                        "api": api if type(api) is int else API + 1,
                        "version": version if isinstance(version, str) and VERSION_RE.fullmatch(version) else "",
                        "author": entry["author"].strip() if one_line(entry.get("author"), 120) else "",
                        "reason": entry["reason"].strip() if one_line(entry.get("reason"), 300) else ""})
    return entries


def readable(read, raw):
    try:
        return read(raw)
    except satellite_list.Unreadable as ex:
        raise Problem(str(ex)) from None


def toml_entries(raw):
    return readable(satellite_list.toml_entries, raw)


def json_entries(raw):
    return readable(satellite_list.json_entries, raw)


def parse_index(raw, local_root=None, where=""):
    """The entries of a list. where is its address or file name; one ending in .json is read as list.json."""
    return parse_entries(readable(lambda data: satellite_list.entry_tables(data, where), raw), local_root)


def fetch_index(url):
    return satellite_list.fetch_index(url, INDEX_BYTES, Problem, Unreachable, NotThere)


CACHE_NAMES = satellite_list.CACHE_NAMES


def read_cache(url):
    return satellite_list.read_cache(CACHE, url, url == SHARED_INDEX)


def write_cache(url, raw, sig):
    satellite_list.write_cache(CACHE, url, raw, sig, url == SHARED_INDEX, atomic_json, time.time())


# The "generated" time of the newest signed list seen from each address. It is kept apart from the cache, so clearing
# the cache can't let an older signed list back in.
LIST_SEEN = CONFIG / "satellite-index-seen.json"


list_generated = satellite_list.list_generated


def newest_seen(url, cached):
    """The generated time of the newest signed list seen from url: the one noted, or the signed copy kept."""
    noted = satellite_list.noted_stamp(jread_dict(LIST_SEEN), url)
    kept = list_generated(cached[0], url) if cached and check_signature(cached[0], cached[1])[0] == "signed" else None
    return satellite_list.newest(noted, kept)


def note_seen(url, stamp):
    changed = satellite_list.with_seen(jread_dict(LIST_SEEN), url, stamp)
    if changed is not None:
        atomic_json(LIST_SEEN, changed)


def jread_dict(path):
    try:
        data = json.loads(satellite_runtime.read_regular(path))
    except (OSError, ValueError, RecursionError):
        return {}
    return data if isinstance(data, dict) else {}


def when(stamp):
    return time.strftime("%B %-d, %Y at %-I:%M %p", time.localtime(stamp)) if stamp else ""


def list_signature(url, raw, sig, cached=None):
    status, sentence = check_signature(raw, sig)
    signed_before = bool(url) and status not in ("bad", "signed") and (
        url in jread_dict(LIST_SEEN) or bool(cached and check_signature(cached[0], cached[1])[0] == "signed"))
    return satellite_list.signature_verdict(url, status, sentence, signed_before, url == SHARED_INDEX)


def load_index(refresh=False, offline=False, *, url=None):
    result = read_index(refresh, offline, url=url)
    # Keep discovery fallback separate from signed entries: it must never lift a security-feed block.
    if url is None and index_url() == SHARED_INDEX:
        path = index_path()
        if path:
            with contextlib.suppress(Problem, OSError, ValueError):
                installed = {item["id"]: item for item in catalog()["satellites"]}
                result["included_entries"] = [listing(e, installed.get(e["id"])) for e in visible_entries(parse_index(path.read_bytes(), path.parent, str(path))) if e["review"] == "Included"]
    return result


def read_index(refresh=False, offline=False, *, url=None):
    """The list Find more shows: its entries, where it came from, how it is signed, and one plain notice for an
    empty, offline, or badly signed list. Applies the kill switch to what is installed. offline reads only what is
    on this computer (the list command uses it, so the kill switch holds without the network)."""
    url = index_url() if url is None else url
    result = {"source": "shared" if url else "local", "where": url, "state": "ok", "notice": "", "updated": 0,
              "signature": "unsigned", "signature_text": "" if not url else NOT_SIGNED, "entries": [], "switched_off": []}
    raw = sig = None
    if not url:
        path = index_path()
        result["label"] = "Made by Starchaser"
        if path is None or not path.is_file():
            result.update(state="empty", notice="No list of add-ons is on this computer yet.")
            return result
        result["where"] = str(path)
        try:
            if path.stat().st_size > INDEX_BYTES:
                raise Problem("The list of add-ons is larger than 1 MB, so it wasn't used.")
            raw = path.read_bytes()
            sig_path = path.with_name(path.name + ".sig")
            sig = sig_path.read_bytes() if sig_path.is_file() else None
        except OSError:
            raise Problem("The list of add-ons couldn't be read.") from None
    else:
        result["label"] = "Online list" if url == SHARED_INDEX else "Another list"
        cached = read_cache(url)
        if not offline and (refresh or cached is None or time.time() - cached[2]["fetched"] > INDEX_MAX_AGE):
            try:
                fresh, fresh_sig = fetch_index(url)
                status, sentence = list_signature(url, fresh, fresh_sig, cached)
                newest = newest_seen(url, cached) if status == "signed" else None
                made = list_generated(fresh, url) if status == "signed" else None
                if satellite_list.rolled_back(newest, made):
                    status, sentence = "bad", satellite_list.OLDER_LIST
                if status == "bad":
                    result.update(state="bad", notice=sentence + (" Starchaser kept the last good copy." if cached else
                                                                 " The list isn't shown."))
                else:
                    parse_index(fresh, None, url)         # an unreadable list never replaces a good copy
                    write_cache(url, fresh, fresh_sig)
                    if status == "signed":
                        note_seen(url, made)
                    cached = read_cache(url)
            except Unreachable:
                result.update(state="offline", notice=(
                    f"Can't reach the list of add-ons right now. This is the copy from {when(cached[2]['fetched'])}."
                    if cached else "Can't reach the list of add-ons. Check your internet connection, then try again."))
            except NotThere as ex:
                # Starchaser's own list isn't published yet: news ("soon"), not a problem with an address
                if url == SHARED_INDEX:
                    # no list yet, so no "this list hasn't been checked" caution above the news either
                    result.update(state="soon", notice=SHARED_NOT_YET, signature="unsigned", signature_text="")
                else:
                    result.update(state="bad", notice=str(ex))
            except Problem as ex:
                result.update(state="bad", notice=str(ex))
        if cached is None:
            return result
        raw, sig, meta = cached
        result["updated"] = meta["fetched"]
    status, sentence = list_signature(url, raw, sig)
    # The list that comes with Starchaser has no signature and nobody needs to hear about it.
    result.update(signature=status, signature_text="" if (not url and status == "unsigned") else sentence)
    if status == "bad":
        result.update(state="bad", notice=sentence + " The list isn't shown.")
        return result
    # An included entry of the online list has no repository: its preview pictures, if any, are the ones on this
    # computer beside the included satellites.
    included = index_path()
    local_root = path.parent if not url else included.parent if included is not None else None
    result["entries"] = parse_index(raw, local_root, str(path) if not url else url)
    if url and status != "signed":
        result["entries"] = unvouched(result["entries"])
    result["switched_off"] = apply_removals(result["entries"], result["where"], status == "signed")
    if result["state"] == "ok" and not any(e["review"] != "Removed" for e in result["entries"]):
        result.update(state="empty", notice="No add-ons are listed yet.")
    return result


def unvouched(entries):
    """An online list Starchaser's keys didn't check can't say Starchaser reviewed anything: its Reviewed entries are
    Unreviewed, so installing one asks with the full warning, and Included stays only for what comes with Starchaser
    on this computer. Removed stays: switching an add-on off is always safe."""
    kept = []
    for entry in entries:
        if entry["review"] == "Reviewed":
            entry = {**entry, "review": "Unreviewed"}
        elif entry["review"] == "Included" and not any((base / entry["id"]).is_dir() for base in INCLUDED):
            continue
        kept.append(entry)
    return kept


def index_entries():
    data = load_index()
    return visible_entries(data["entries"] or data.get("included_entries", []))


def visible_entries(entries):
    """The developer samples are left out unless developer mode is on or one is already turned on."""
    if developer_mode():
        return entries
    try:
        on = {sid for sid, r in state()["satellites"].items() if r.get("enabled")}
    except Problem:
        on = set()
    return [e for e in entries if e["id"] not in SAMPLES or e["id"] in on]


def apply_managed_included():
    policy = managed_policy()
    desired = set(policy.get("included", [])) - set(policy.get("blocked", []))
    if not desired:
        return
    with locked_state() as saved:
        if safe_on(saved):
            return
        for item in catalog(saved)["satellites"]:
            if item["source"] == "Included" and item["id"] in desired:
                record = saved["satellites"].setdefault(item["id"], {})
                if not record.get("removed") and not record.get("index_removed"):
                    record.update(enabled=True, granted_permissions=item["permissions"])


def index_check():
    apply_managed_included()
    """The kill switch without Settings open: the taskbar runs this when the desktop starts and every hour. It reads
    the list (the shared one is fetched only when the kept copy is more than a day old) and switches off what the list
    took off, with a notification. Nothing is read or fetched when no satellite was added from outside Starchaser."""
    try:
        saved = state()
    except Problem:
        return
    if not any((INSTALLED / sid).is_dir() for sid in saved["satellites"]):
        return
    try:
        data = load_index(url=SHARED_INDEX)
    except (Problem, OSError, ValueError, RecursionError):
        return
    sender = shutil.which("notify-send")
    for sid in data["switched_off"]:
        entry = next((e for e in data["entries"] if e["id"] == sid), None)
        if entry is None or not sender:
            continue
        with contextlib.suppress(OSError, subprocess.SubprocessError):
            subprocess.run([sender, "-a", "Starchaser", "-i", "dialog-warning", f"{entry['name']} was turned off",
                            removal_sentence(entry) + " You can remove it in Settings > Satellites."],
                           stdin=subprocess.DEVNULL, capture_output=True, timeout=10)


def same_repo(a, b):
    """One repository written two ways (GitHub.com/a/b.git and github.com/a/b/) is the same repository, so the kill
    switch matches it either way."""
    def norm(link):
        if not isinstance(link, str):
            return ""
        link = link.strip().lower()
        # https's own port, written out (github.com:443 or :0443), is the same site; another port is another site
        link = re.sub(r"^(https://[^/:]+):0*443(?=/|$)", r"\1", link)
        while link.endswith(("/", ".git")):
            link = link.removesuffix("/").removesuffix(".git")
        return link
    return bool(norm(a)) and norm(a) == norm(b)


def removal_sentence(entry):
    return "Taken off the add-on list, so it's off. " + (entry["reason"] or REMOVED_DEFAULT)


def apply_removals(entries, source="", signed=False):
    """The kill switch. A satellite added from the list (or from the same link) that the list now marks removed is
    switched off with a plain notice and can't be turned on again; if the list lists it again, the block lifts. Only
    for entries the list names: included satellites and folders are never touched. Returns the names switched off."""
    removed = {e["id"]: e for e in entries if e["review"] == "Removed"}
    # the block lifts only when the list lists it again; a list that doesn't name it (another list, or one that
    # couldn't be read) never lifts it
    relisted = {e["id"] for e in entries if e["review"] != "Removed"} if signed else set()

    def blocks(record):
        # An older block has no proven source. Keep it until the official signed list clears it.
        return record.get("removed_by", {SHARED_INDEX: {"signed": True}}) if record.get("index_removed") else {}

    def can_lift(sid, record):
        return sid in relisted and source in blocks(record)

    def hit(sid, record):
        entry = removed.get(sid)
        return entry is not None and (INSTALLED / sid).is_dir() and (
            (record.get("index") and record.get("index_url", source) == source)
            or same_repo(record.get("source_url", ""), entry["repo"]))

    def needs(sid, record):
        if hit(sid, record):
            return record.get("enabled") or source not in blocks(record) or record.get("index_removed") != removal_sentence(removed[sid])
        return can_lift(sid, record)

    try:
        current = state()
    except Problem:
        return []
    if not any(needs(sid, r) for sid, r in current["satellites"].items()):
        return []
    switched, notes = [], []
    offered = theme_ids([i for i in catalog(current)["satellites"] if hit(i["id"], current["satellites"].get(i["id"], {}))])
    with locked_state() as saved:
        for sid, record in saved["satellites"].items():
            if hit(sid, record):
                sentence = removal_sentence(removed[sid])
                if record.get("enabled") or record.get("index_removed") != sentence:
                    notes.append((sid, sentence))
                    if record.get("enabled"):
                        switched.append(sid)
                imposed = dict(blocks(record))
                imposed[source] = {"signed": signed, "reason": sentence}
                record.update(enabled=False, index_removed=sentence, reason=sentence, removed_by=imposed)
            elif can_lift(sid, record):
                imposed = dict(blocks(record))
                imposed.pop(source)
                record["removed_by"] = imposed
                if not imposed:
                    record.pop("index_removed")
                    record["reason"] = ""
                    notes.append((sid, "The signed add-on list lists it again, so it can be turned on."))
                else:
                    record["index_removed"] = record["reason"] = next(iter(imposed.values())).get("reason", REMOVED_DEFAULT)
    for sid in switched:
        stop_satellite(sid)
    theme_gone(offered)
    for sid, sentence in notes:
        with contextlib.suppress(OSError):
            log(sid, sentence)
    return switched


list_format = satellite_list.list_format


def search(words, kind=None):
    words = [w.lower() for w in words if w.strip()]
    installed = {item["id"]: item for item in catalog()["satellites"]}
    found = []
    for entry in index_entries():
        if entry["review"] == "Removed" or (kind and kind not in entry["kinds"]):
            continue
        text = " ".join([entry["id"], entry["name"], entry["summary"], *entry["kinds"],
                         *(KINDS.get(k, "") for k in entry["kinds"])]).lower()
        if all(w in text for w in words):
            found.append(listing(entry, installed.get(entry["id"])))
    return found


def listing(entry, item):
    """An index entry as Find more shows it: whether it is here already, and whether it can be installed."""
    blocked = ""
    if entry["api"] > API:
        blocked = "Needs a newer Starchaser."
    elif entry["api"] < API - 1:
        blocked = "Needs an update from its author."
    elif item and item.get("index_removed"):
        blocked = "Taken off the list"
    return {**entry, "installed": item is not None, "enabled": bool(item and item["enabled"]),
            "adds": adds_text(entry["kinds"]), "blocked": blocked,
            "code": entry["review"] != "Included" and ships_code(entry, None)}


def adds_text(kinds):
    adds = [KINDS[k] for k in kinds if k in KINDS]
    text = ", ".join(adds[:-1]) + " and " + adds[-1] if len(adds) > 1 else (adds[0] if adds else "No additions yet")
    # Only the first letter: str.capitalize() would lowercase "Today" and "Settings".
    return text[0].upper() + text[1:] + "."


def reflow(text):
    """A README's paragraphs as one line each, so Settings wraps them to its own width instead of breaking each line
    the author wrapped at 80 or 120 columns ("They" alone on a line). Headings, lists, quotes, tables, indented and
    fenced code keep their lines."""
    out, fenced = [], False
    keep = re.compile(r"\s|#|[-*+>|]|\d+[.)]\s|```|~~~")
    for line in text.split("\n"):
        if line.lstrip().startswith(("```", "~~~")):
            fenced = not fenced
        if (not fenced and line and not keep.match(line) and out and out[-1] and not keep.match(out[-1])
                and not out[-1].endswith("  ")):
            out[-1] += " " + line
        else:
            out.append(line)
    return "\n".join(out)


def package_missing(name):
    try:
        return subprocess.run(["pacman", "-Q", name], capture_output=True, timeout=5).returncode != 0
    except (OSError, subprocess.SubprocessError):
        return True


def outside_warning(item):
    if item.get("path") and not ships_code(item, Path(item["path"])):
        return "This add-on comes from outside Starchaser and has not been reviewed. No programs from its folder run."
    if item.get("sandbox") == "restricted":
        return ("This add-on comes from outside Starchaser and has not been reviewed. "
                "Starchaser limits it to the access listed above. Only install it if you trust who made it.")
    return WARNING


def details(item):
    result = dict(item)
    result["theme_choices"] = sorted(theme_ids([item]))
    root = Path(item["path"])
    readme = root / "README.md"
    # Imported themes keep the author's files for attribution and updates. Their installation commands target
    # another desktop; both the preview and installed details should explain the Starchaser action instead.
    if (root / THEME_IMPORT).is_file():
        result["readme"] = ("Starchaser imports this theme's colors and wallpaper. After installing it, choose "
                            "Use this theme to apply it. Nothing in the theme's folder is run. "
                            "The author's original files are kept in its folder.")
    else:
        result["readme"] = reflow(readme.read_text(errors="replace")[:32768]) if readme.is_file() and readme.resolve().is_relative_to(root.resolve()) else "No README was supplied."
    page_kind = "toml" if page_entry(item) else "qml" if code_page(item) else ""
    has_page = page_kind != ""
    kinds = [k for k in item["kinds"] if (k != "settings-page" or has_page) and (k != "bar-widget" or widget_entry(item))]
    result["adds"] = adds_text(kinds)
    result["has_page"] = has_page and item.get("enabled", False)
    result["page_kind"] = page_kind
    result["later"] = [k for k in item["kinds"] if k not in kinds or k not in KINDS]
    result["hooks"] = sorted(hook_files(item), key=list(EVENTS).index)
    result["hook_text"] = ("Runs its own actions when " + "; when ".join(EVENTS[e] for e in result["hooks"]) + ".") if result["hooks"] else ""
    # Included satellites are ours and reviewed; anything else that ships programs gets the plain warning.
    result["code"] = ships_code(item, root)
    result["code_warning"] = (CODE_WARNING if item.get("sandbox") != "restricted" else "") if item.get("source") != "Included" and result["code"] else ""
    record = state()["satellites"].get(item["id"], {})
    result["can_undo_update"] = bool(record.get("previous") and (INSTALLED / (".previous-" + item["id"])).is_dir() and not record.get("index_removed"))
    result["access"] = access_note(item)
    result["activity"] = activity(item["id"])
    from urllib.parse import urlsplit
    repository = urlsplit(item.get("source_url", ""))
    owner = repository.path.strip("/").split("/")[0] if repository.hostname else ""
    result["repository_account"] = (owner + " at " + repository.hostname) if owner else ""
    result["support_url"] = support_url(item)
    result["unsafe_url"] = "https://github.com/starchaserlinux/starchaser/security/advisories/new"
    result["pin_note"] = PIN_NOTE if item.get("commit") else ""
    review = item.get("review", "Included" if item.get("source") == "Included" else "Unreviewed")
    result["review"] = review
    result["review_note"] = ("Made by Starchaser" if review == "Included" else
                             "A person at Starchaser reviewed this version." if review == "Reviewed" else
                             "Not reviewed by Starchaser.")
    asks = []
    labels = {"network": "Connects to", "run": "Runs", "read": "Reads", "write": "Writes"}
    for key, label in labels.items():
        if item["permissions"].get(key):
            asks.append(label + " " + ", ".join(item["permissions"][key]) + ".")
    for key, label in (("notify", "Shows notifications."), ("location", "Uses your location."), ("media", "Controls music and video playback."), ("selected_file", "Reads the one file you select in Files."), ("search", "Reads text you type in menu searches.")):
        if item["permissions"].get(key):
            asks.append(label)
    asks.extend("Reads " + name + " from Starchaser." for name in item.get("providers", []))
    asks.extend("Uses its saved sign-in named " + key + "." for key in item.get("secrets", []))
    result["asks"] = (" ".join(asks) or "No extra permissions are declared.") + " " + access_note(item)
    log_path = LOGS / f"{item['id']}.log"
    result["log_text"] = log_path.read_text(errors="replace")[-32768:] if log_path.is_file() else "No log entries yet."
    result["package_note"] = "Uses only the system's own packages; this update does not install packages."
    result["package_actions"] = [{"name": name, "command": ["starchaser", "software", "run", "install", "repo", name]} for name in item["packages"] if package_missing(name)]
    return result


# The links "Add from a link" takes: a public https:// git repository on any site (GitHub, GitLab with subgroups,
# Codeberg, sourcehut's ~user, a self-hosted Gitea or Forgejo with a port). No user@, ?query, #fragment, "::"
# transport, "." or ".." folder, or host without a dot (localhost); at least two folders after the host.
LINK_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
LINK_RE = re.compile(r"https://(" + LINK_LABEL + r"(?:\." + LINK_LABEL + r")+)(?::([0-9]{1,5}))?((?:/[A-Za-z0-9_.~-]+){2,})/?\Z")
LINK_WORDS = "an https:// git link (GitHub, GitLab, Codeberg, or any public git site)"


def test_git():
    """Offline tests opt in explicitly to file:/// links; never another network protocol."""
    return TEST_OVERRIDES and os.environ.get("STARCHASER_SATELLITES_TEST_LOCAL_GIT") == "1"


def git_link(source):
    if not isinstance(source, str) or len(source) > 500:
        return False
    if test_git() and source.startswith("file:///"):
        return True
    found = LINK_RE.fullmatch(source)
    if not found or "::" in source:
        return False
    import urllib.parse
    try:
        parts = urllib.parse.urlsplit(source)
        port = parts.port
    except ValueError:
        return False
    if (parts.scheme != "https" or parts.username is not None or parts.password is not None or parts.query
            or parts.fragment or (parts.hostname or "") != found[1].lower() or (port is not None and not 0 < port < 65536)):
        return False
    segments = found[3].strip("/").split("/")
    segments[-1] = segments[-1].removesuffix(".git")
    return all(seg and seg not in {".", ".."} for seg in segments)


def link_host(source):
    """The site a git link points at ("gitlab.com"), or "" for a folder, a file:/// test link, or anything else."""
    found = LINK_RE.fullmatch(source) if isinstance(source, str) and git_link(source) else None
    return found[1].lower() if found else ""


class TooSlow(Problem):
    """A git command ran out of time: a slow connection or a very large repository, not a wrong address."""


def git(args, cwd=None, timeout=120, binary=False):
    # GIT_NO_LAZY_FETCH: a blob a filtered clone left out is never fetched behind clone()'s size check
    env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull,
           "GIT_NO_LAZY_FETCH": "1"}
    # https only, so a redirect or a submodule can't switch to another protocol (file:// only for offline tests)
    allow = ["-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "submodule.recurse=false"]
    if test_git():
        allow += ["-c", "protocol.file.allow=always"]
    try:
        output = subprocess.run(["git", *allow, *args], cwd=cwd, env=env, capture_output=True, text=not binary, check=True,
                                timeout=timeout).stdout
        return output if binary else output.strip()
    except subprocess.TimeoutExpired:
        raise TooSlow("The add-on took too long to download. Check your connection and try again.") from None
    except (OSError, subprocess.SubprocessError):
        raise Problem("The add-on Git folder couldn't be read at that commit.") from None


def clone(source, target, commit):
    """Clone and check out one version, so that no more than a satellite may hold reaches the disk: only the newest commit
    when no version is named, no single file over the limit (on sites that filter), and the version's files are
    counted before any is checked out. check_tree applies the smaller limit for kinds other than themes."""
    shallow = [] if commit else ["--depth", "1"]
    try:
        git(["clone", "--no-checkout", "--no-recurse-submodules", *shallow, f"--filter=blob:limit={THEME_IMPORT_LIMIT}",
             "--", source, str(target)])
    except TooSlow:
        raise
    except Problem:
        # a link copied from the browser while looking inside a project (…/OWNER/REPO/tree/main/folder): say so
        inside = re.fullmatch(r"(https://[^/]+/[^/]+/[^/]+)/(?:tree|blob)/.+", source)
        if inside:
            raise Problem(f"This link points to a folder inside a project. Use the project's main address: {inside[1]}.") from None
        # a mistyped address, a private repository or no connection: all the person can check is the link
        raise Problem("No add-on was found at that link. Check the address, and that the repository is public "
                      "and you are online.") from None
    if commit and not re.fullmatch(r"[0-9a-fA-F]{7,40}", commit):
        raise Problem("Use a commit hash for the add-on version.")
    sha = git(["rev-parse", "--verify", (commit or "HEAD") + "^{commit}"], target)
    total = 0
    for line in git(["ls-tree", "-r", "-l", "-z", "--full-tree", sha], target).split("\0"):
        size = line.split("\t", 1)[0].split()[-1] if line else "0"
        if size == "BAD":                  # left out by the filter: one file over the limit
            total = THEME_IMPORT_LIMIT + 1
        elif size.isdigit():
            total += int(size)
        if total > THEME_IMPORT_LIMIT:
            raise Problem("The add-on folder is larger than 200 MB.")
    git(["checkout", "--detach", sha], target)
    return sha


def confirm(sentence, yes):
    print(sentence, file=sys.stderr)
    if yes:
        return
    if not sys.stdin.isatty() or input("Type yes to continue: ").strip() != "yes":
        raise Problem("The add-on change was canceled.")


FROM_LIST = "From the online list"


def removed_from_list(sid, repo):
    """The list's reason when it took off this id from this repository (read from this computer only), else ""."""
    # A damaged discovery list must never discard a valid official removal (or the other way around).
    for url in (SHARED_INDEX, None):
        try:
            entries = load_index(offline=True, url=url)["entries"]
        except (Problem, OSError, ValueError, RecursionError):
            continue
        entry = next((e for e in entries if e["id"] == sid and e["review"] == "Removed"
                      and same_repo(repo, e["repo"])), None)
        if entry:
            return entry["reason"] or REMOVED_DEFAULT
    return ""


def doc_path(page):
    """A guide in Starchaser's docs, "file.md#section": the installed copy, else the one in this checkout."""
    name, _, section = page.partition("#")
    for base in (Path("/usr/share/doc/starchaser"), Path(__file__).resolve().parent.parent / "docs"):
        if (base / name).is_file():
            return str(base / name) + (f"#{section}" if section else "")
    return page


def omarchy_plugin(folder):
    """True for a folder made as an Omarchy plugin: a manifest.json and no satellite.toml (only the names are looked
    at here; nothing in the folder is read or run)."""
    folder = Path(folder)
    return not os.path.lexists(folder / "satellite.toml") and (folder / "manifest.json").is_file() \
        and not (folder / "manifest.json").is_symlink()


# Omarchy plugin kinds (manifest.json "kinds" and "entryPoints" keys) and the Starchaser kind each one becomes when
# it is ported; anything else is listed in a comment in the drafted satellite.toml
OMARCHY_KINDS = {"barwidget": "bar-widget", "bar-widget": "bar-widget", "widget": "bar-widget", "panel": "panel",
                 "overlay": "overlay", "service": "service", "backgroundservice": "service", "background-service": "service",
                 "menu": "menu-page", "menupage": "menu-page", "settings": "settings-page", "settingspage": "settings-page"}


def port_text(value, limit=500):
    """One line of manifest.json text, or "" (anything else, too long, or with control characters)."""
    if isinstance(value, dict):
        value = value.get("name", "")
    if not isinstance(value, str):
        return ""
    value = " ".join(value.split())
    return value if value and len(value) <= limit else ""


def port_manifest(folder):
    """What a drafted satellite.toml says, read from an Omarchy plugin's manifest.json (data only)."""
    raw = read_small(Path(folder) / "manifest.json")
    try:
        data = json.loads(raw) if raw is not None else None
    except (ValueError, RecursionError):
        data = None
    if not isinstance(data, dict):
        raise Problem("This plugin's manifest.json couldn't be read, so nothing was ported.")
    sid = clone_id(str(data.get("id") or data.get("name") or "").replace(".", "-"))
    if not sid or not ID_RE.fullmatch(sid):
        raise Problem("This plugin's manifest.json has no id or name to port it under.")
    raw_kinds = data.get("kinds", data.get("kind", []))
    raw_kinds = [raw_kinds] if isinstance(raw_kinds, str) else raw_kinds if isinstance(raw_kinds, list) else []
    points = data.get("entryPoints", data.get("entry", {}))
    if isinstance(points, str):
        points = {raw_kinds[0] if raw_kinds and isinstance(raw_kinds[0], str) else "barWidget": points}
    points = points if isinstance(points, dict) else {}
    kinds, entry, unknown = [], {}, []
    for name in [k for k in raw_kinds if isinstance(k, str)] + [k for k in points if isinstance(k, str)]:
        kind = OMARCHY_KINDS.get(name.replace("_", "").lower()) or OMARCHY_KINDS.get(name.lower())
        if kind is None or kind not in KINDS:
            if name not in unknown:
                unknown.append(name)
            continue
        if kind not in kinds:
            kinds.append(kind)
        path = points.get(name)
        if isinstance(path, str) and path and not Path(path).is_absolute() and ".." not in Path(path).parts \
                and kind not in entry:
            entry[kind] = path
    version = data.get("version") if isinstance(data.get("version"), str) and VERSION_RE.fullmatch(data["version"]) else "0.1.0"
    return {"id": sid, "name": port_text(data.get("name")) or sid.replace("-", " ").title(), "version": version,
            "summary": port_text(data.get("description")) or "A ported plugin.",
            "author": port_text(data.get("author")) or "Unknown", "license": port_text(data.get("license")) or "See its own files",
            "homepage": port_text(data.get("homepage") or data.get("repository") or data.get("url")),
            "kinds": kinds, "entry": entry, "unknown": unknown}


def port_plugin(source, parent=None, as_json=False):
    """starchaser satellite port: draft a satellite from an Omarchy plugin, in ~/Satellites/<id>. Its files are
    copied (from a link: a clone of it), satellite.toml is drafted from manifest.json with an empty permission list,
    and nothing in it is run: the QML still has to be ported by hand before it can be turned on."""
    link = git_link(source)
    if not link and not Path(source).is_dir():
        raise Problem(f"Use a folder or {LINK_WORDS} to a plugin for another desktop.")
    parent = Path(parent).expanduser() if parent else satellite_home()
    parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".port-", dir=parent) as work:
        copy = Path(work) / "plugin"
        if link:
            clone(source, copy, None)
            shutil.rmtree(copy / ".git", ignore_errors=True)
        else:
            check_tree(Path(source))
            shutil.copytree(source, copy, ignore=shutil.ignore_patterns(".git"))
        if os.path.lexists(copy / "satellite.toml"):
            raise Problem("This is already an add-on, so there is nothing to port. Install it or try it with dev.")
        if not omarchy_plugin(copy):
            raise Problem("No manifest.json was found. Choose a plugin folder to port.")
        check_tree(copy)
        d = port_manifest(copy)
        homepage = d["homepage"] or (source if link else "Local folder")
        if d["id"] in taken_ids(state()):
            raise Problem(f"An add-on called “{d['id']}” is already here, so the port wasn't made.")
        lines = ["# Drafted by starchaser satellite port from this plugin's manifest.json. Nothing in this folder has run.",
                 "# Its QML still talks to another desktop's shell: port it to the Starchaser SDK, then check it with",
                 "# starchaser satellite validate, and try it with starchaser satellite dev.",
                 f"id = {toml_string(d['id'])}", f"name = {toml_string(d['name'])}", f"version = {toml_string(d['version'])}",
                 f"summary = {toml_string(d['summary'])}", f"author = {toml_string(d['author'])}",
                 f"license = {toml_string(d['license'])}", f"homepage = {toml_string(homepage)}", "",
                 "[starchaser]", f"api = {API}", "kinds = [" + ", ".join(toml_string(k) for k in d["kinds"]) + "]",
                 "entry = { " + ", ".join(f"{k} = {toml_string(v)}" for k, v in d["entry"].items()) + " }"]
        if d["unknown"]:
            lines.append("# Not ported (no Starchaser kind yet): " + ", ".join(d["unknown"]))
        lines += ["", "[permissions]",
                  "# Empty on purpose: people see this list before they turn the add-on on.",
                  "# It does not limit what the add-on can do. List what it really needs, for example:",
                  '# run = ["curl"]                  programs it runs (the SDK\'s Data)',
                  '# network = ["api.example.com"]   places it reaches online',
                  '# read = []  write = []           files outside its own data folder',
                  "# notify = false                  notifications", "# location = false", ""]
        write_generated(copy / "satellite.toml", "\n".join(lines))
        manifest(copy)                                         # the draft itself must read as a satellite
        target = parent / d["id"]
        if os.path.lexists(target):
            raise Problem(f"{target} already exists. Move it, or choose another folder with --dir.")
        os.rename(copy, target)
    check = f"starchaser satellite validate {shlex.quote(str(target))}"
    if as_json:
        print(json.dumps({"ok": True, "id": d["id"], "name": d["name"], "path": str(target), "kinds": d["kinds"],
                          "not_ported": d["unknown"], "next": check}))
    else:
        print(f"Drafted {d['name']} in {target}. Nothing in it has run. Port its QML to the Starchaser SDK "
              f"(docs/satellites-for-omarchy-users.md, Porting a plugin), then check it with: {check}")
    return target


def install(source, commit, yes):
    link = git_link(source)
    if not link and "://" not in source and not Path(source).is_dir() and ID_RE.fullmatch(source):
        return install_listed(source, commit, yes)
    if not link and ("://" in source or not Path(source).is_dir()):
        raise Problem(f"Use a local folder, {LINK_WORDS}, or the id of an add-on on the list.")
    origin = {"source": "From a link" if link else "Local folder", "source_url": source if link else "Local folder"}
    stage_install(source, commit, link, origin, yes=yes)


def listed_entry(sid):
    """The list's entry for an id that can be installed from it, or one plain sentence saying why not."""
    data = load_index()
    entry = next((e for e in data["entries"] if e["id"] == sid), None)
    if entry is None:
        if data["notice"] and data["state"] != "empty":
            raise Problem(data["notice"])
        raise Problem("That add-on isn't on the list of add-ons.")
    if entry["review"] == "Removed":
        raise Problem(f"{entry['name']} was taken off the add-on list, so it can't be installed.")
    if entry["review"] == "Included":
        # a developer sample isn't listed in Settings: its copy is what's meant to be tried and changed
        if sid in SAMPLES and not developer_mode():
            raise Problem(f"{entry['name']} is an example that comes with Starchaser. Make a copy to try and change "
                          f"with: starchaser satellite clone {sid}")
        raise Problem(f"{entry['name']} comes with Starchaser. Turn it on in Settings > Satellites.")
    blocked = listing(entry, None)["blocked"]
    if blocked:
        raise Problem(blocked)
    return entry


def install_listed(sid, commit, yes):
    entry = listed_entry(sid)
    if commit and commit.lower() != entry["commit"]:
        raise Problem("The list names a different version of this add-on now. Look at it again before installing.")
    origin = {"source": FROM_LIST, "source_url": entry["repo"], "review": entry["review"], "index": True,
              "index_url": index_url() or str(index_path())}
    stage_install(entry["repo"], entry["commit"], True, origin, expect=sid, yes=yes)


def stage_install(source, commit, link, origin, expect=None, yes=False):
    INSTALLED.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".install-", dir=INSTALLED) as work:
        stage = Path(work) / "satellite"
        sha = ""
        if link:
            sha = clone(source, stage, commit)
        else:
            if commit:
                raise Problem("A commit hash can be used only with a Git link.")
            check_tree(Path(source))
            if (Path(source) / "satellite.toml").is_file():
                manifest(Path(source))  # Check link targets before copytree dereferences them.
            shutil.copytree(source, stage)
        if omarchy_plugin(stage):
            raise OmarchyPlugin()
        omarchy_to_satellite(stage, source, sha)       # a plain colors.toml theme becomes a theme satellite
        check_tree(stage)
        m = manifest(stage)
        print(adds_text(m["kinds"]))
        print(access_note({**m, "path": str(stage)}))
        print("Requested access: " + json.dumps(m["permissions"], sort_keys=True))
        warning = REVIEWED_NOTE if origin.get("review") == "Reviewed" else outside_warning({**m, "path": str(stage)})
        confirm(warning + (" " + CODE_WARNING if ships_code(m, stage) and m.get("sandbox") != "restricted" else "") + " Install with this access?", yes)
        policy_check({**m, **origin, "commit": sha, "path": str(stage)})
        sid = m["id"]
        if expect and sid != expect:
            raise Problem("The add-on at that version has a different id than the list says, so it wasn't installed.")
        if link:
            taken = removed_from_list(sid, source)
            if taken:
                raise Problem(f"{m['name']} was taken off the add-on list, so it can't be installed. {taken}")
        # the pointer rule holds for everything installed, not only for authors who ran check
        moves = pointer_problem(stage)
        if moves:
            raise Problem(moves + " It wasn't installed.")
        renamed = False

        def rollback():
            # Keep the folder and its pin together if saving state fails.
            if renamed:
                shutil.rmtree(INSTALLED / sid)

        with locked_state(rollback) as saved:
            if (INSTALLED / sid).exists() or any((base / sid).exists() for base in INCLUDED):
                raise Problem("An add-on with that id is already installed.")
            saved["satellites"][sid] = {"enabled": False, **origin, "commit": sha, "granted_permissions": m["permissions"], "granted_providers": m.get("providers", []), "granted_secrets": m.get("secrets", []), "granted_sandbox": m.get("sandbox"),
                                        "failures": []}
            os.rename(stage, INSTALLED / sid)
            renamed = True
        log(sid, f"Installed {m['name']}." + (f" Pinned to {sha}." if sha else ""))
        print(f"{m['name']} is installed and off.")


# Themes made as a plain colors.toml folder (the way themes for other Hyprland desktops are shared: colors.toml,
# backgrounds/, sometimes only alacritty.toml). Such a folder has no satellite.toml, so it is converted into a theme
# satellite in the install stage: a generated satellite.toml, theme/<id>.toml and a wallpaper link. Nothing in the
# folder is run, and every safety rule of a link install still holds: the warning, the pinned commit, the kill
# switch, updates with a shown diff. The generated files are listed in .git/info/exclude for Git's display;
# unchanged() independently regenerates them from the pinned source and compares their actual content.
THEME_IMPORT = ".starchaser-theme-import"
THEME_IMPORT_LIMIT = 200 * 1024 * 1024
HEX6_RE = re.compile(r"#[0-9a-f]{6}\Z")
IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp")
ANSI_NAMES = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white")


def image_size(path):
    """(width, height) read from a PNG, JPEG or WebP header with the standard library, or None."""
    try:
        with open(path, "rb") as stream:
            head = stream.read(32)
            if head[:8] == b"\x89PNG\r\n\x1a\n" and head[12:16] == b"IHDR":
                width, height = int.from_bytes(head[16:20], "big"), int.from_bytes(head[20:24], "big")
            elif head[:4] == b"RIFF" and head[8:12] == b"WEBP":
                chunk = head[12:16]
                if chunk == b"VP8 " and head[23:26] == b"\x9d\x01\x2a":
                    width = int.from_bytes(head[26:28], "little") & 0x3FFF
                    height = int.from_bytes(head[28:30], "little") & 0x3FFF
                elif chunk == b"VP8L" and head[20:21] == b"\x2f":
                    bits = int.from_bytes(head[21:25], "little")
                    width, height = (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
                elif chunk == b"VP8X":
                    width = int.from_bytes(head[24:27], "little") + 1
                    height = int.from_bytes(head[27:30], "little") + 1
                else:
                    return None
            elif head[:2] == b"\xff\xd8":
                stream.seek(2)
                width = height = 0
                for _ in range(10000):
                    byte = stream.read(1)
                    while byte and byte != b"\xff":
                        byte = stream.read(1)
                    while byte == b"\xff":
                        byte = stream.read(1)
                    if not byte:
                        return None
                    marker = byte[0]
                    if marker in (0x01, *range(0xD0, 0xDA)):     # no length: TEM, RSTn, SOI, EOI (0xD9 ends it)
                        if marker == 0xD9:
                            return None
                        continue
                    size = int.from_bytes(stream.read(2), "big")
                    if size < 2:
                        return None
                    if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC):
                        frame = stream.read(5)
                        if len(frame) < 5:
                            return None
                        height, width = int.from_bytes(frame[1:3], "big"), int.from_bytes(frame[3:5], "big")
                        break
                    stream.seek(size - 2, os.SEEK_CUR)
            else:
                return None
    except (OSError, ValueError):
        return None
    return (width, height) if 0 < width <= 65535 and 0 < height <= 65535 else None


def theme_hex(value):
    """'#rrggbb' (lowercase) from '#rrggbb', '#rgb' or '0xRRGGBB'; anything else is None."""
    if not isinstance(value, str):
        return None
    text = value.strip().lower()
    if re.fullmatch(r"0x[0-9a-f]{6}", text):
        text = "#" + text[2:]
    elif re.fullmatch(r"#[0-9a-f]{3}", text):
        text = "#" + "".join(ch * 2 for ch in text[1:])
    return text if HEX6_RE.fullmatch(text) else None


def theme_mix(a, b, amount):
    """a mixed toward b by amount (0 to 1), rounded the way the colors.toml resolver rounds."""
    ra, rb = (tuple(int(c[i:i + 2], 16) for i in (1, 3, 5)) for c in (a, b))
    return "#" + "".join(f"{int(x * (1 - amount) + y * amount + 0.5):02x}" for x, y in zip(ra, rb))


def theme_contrast(a, b):
    def lum(c):
        def ch(x):
            x /= 255
            return x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4
        r, g, b_ = (ch(int(c[i:i + 2], 16)) for i in (1, 3, 5))
        return 0.2126 * r + 0.7152 * g + 0.0722 * b_
    la, lb = lum(a), lum(b)
    return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)


def theme_readable(fg, bg, ratio=4.5):
    """fg moved toward white (on a dark bg) or black (on a light one) in small steps until it reads at ratio."""
    toward = "#ffffff" if theme_contrast("#ffffff", bg) >= theme_contrast("#000000", bg) else "#000000"
    for i in range(21):
        c = theme_mix(fg, toward, i / 20)
        if theme_contrast(c, bg) >= ratio:
            return c
    return toward


def colors_lines(text):
    """The colors.toml line rules of the original resolver, for a file TOML can't read (odd quoting)."""
    found = {}
    for line in text.splitlines():
        key, _, value = line.partition("=")
        key = re.sub(r"[\"' ]", "", key)
        if not key or key.startswith("#") or not _:
            continue
        quoted = re.search(r"[\"']([^\"']*)", value)
        value = quoted.group(1) if quoted else value.strip()
        if re.fullmatch(r"[A-Za-z0-9_-]+", key):
            found[key] = value
    return found


def read_small(path, limit=65536):
    try:
        if not path.is_file() or path.stat().st_size > limit:
            return None
        return path.read_text(errors="replace")
    except OSError:
        return None


def omarchy_colors(folder):
    """Omarchy key -> '#rrggbb' (plus "mode"), resolved with the same alias and fallback cascade as Omarchy's own
    omarchy-theme-color, from colors.toml or, for the oldest themes, alacritty.toml. Empty when neither has colors."""
    folder = Path(folder)
    raw = {}
    text = read_small(folder / "colors.toml")
    if text is not None:
        try:
            parsed = tomllib.loads(text)
            raw = {k: v for k, v in parsed.items() if isinstance(v, str)}
        except (tomllib.TOMLDecodeError, RecursionError):
            raw = colors_lines(text)
    else:
        text = read_small(folder / "alacritty.toml")
        try:
            table = tomllib.loads(text).get("colors") if text is not None else None
        except (tomllib.TOMLDecodeError, RecursionError):
            table = None
        if isinstance(table, dict):
            def part(name):
                value = table.get(name)
                return value if isinstance(value, dict) else {}
            raw.update({k: part("primary").get(k) for k in ("background", "foreground")})
            for offset, name in ((0, "normal"), (8, "bright")):
                raw.update({f"color{offset + i}": part(name).get(n) for i, n in enumerate(ANSI_NAMES)})
            raw["selection_background"] = part("selection").get("background")
            raw["selection_foreground"] = part("selection").get("text")
    c = {}
    for key, value in raw.items():
        if key in {"mode", "theme_type"}:
            if isinstance(value, str) and value.strip().lower() in {"dark", "light"}:
                c[key] = value.strip().lower()
        elif theme_hex(value):
            c[key] = theme_hex(value)
    if not any(k not in {"mode", "theme_type"} for k in c):
        return {}

    def alias(key, fallback):
        if not c.get(key) and c.get(fallback):
            c[key] = c[fallback]

    def mixed(key, start, end, amount):
        if not c.get(key) and c.get(start):
            c[key] = theme_mix(c[start], end, amount)

    def first(key, *names):
        if not c.get(key):
            value = next((c[n] for n in names if c.get(n)), None)
            if value:
                c[key] = value

    short = {"background": "bg", "dark_background": "dark_bg", "darker_background": "darker_bg",
             "lighter_background": "lighter_bg", "foreground": "fg", "dark_foreground": "dark_fg",
             "light_foreground": "light_fg", "bright_foreground": "bright_fg"}
    for key, name in short.items():
        alias(key, name)
    alias("background", "color0")
    alias("foreground", "color7")
    if c.get("background"):
        c["color0"] = c["background"]
    if c.get("foreground"):
        c["color7"] = c["foreground"]
    for key, n in (("red", 1), ("green", 2), ("yellow", 3), ("blue", 4), ("magenta", 5), ("cyan", 6),
                   ("bright_red", 9), ("bright_green", 10), ("bright_yellow", 11), ("bright_blue", 12),
                   ("bright_magenta", 13), ("bright_cyan", 14)):
        alias(key, f"color{n}")
    alias("magenta", "purple")
    alias("bright_magenta", "bright_purple")
    first("light_foreground", "color7", "foreground")
    first("bright_foreground", "color15", "foreground")
    first("lighter_background", "color0", "background")
    first("dark_foreground", "color8", "foreground")
    first("muted", "color8", "dark_foreground")
    first("selection", "selection_background", "color8", "color0", "background")
    alias("selection_background", "selection")
    alias("selection_foreground", "bright_foreground")
    alias("orange", "yellow")
    mixed("brown", "orange", "#000000", 0.5)
    mixed("dark_background", "background", "#000000", 0.25)
    mixed("darker_background", "background", "#000000", 0.5)
    for name in ("red", "yellow", "green", "cyan", "blue", "magenta"):
        mixed("bright_" + name, name, "#ffffff", 0.2)
    alias("purple", "magenta")
    alias("bright_purple", "bright_magenta")
    for n, key in enumerate(("background", "red", "green", "yellow", "blue", "magenta", "cyan", "foreground", "muted",
                             "bright_red", "bright_green", "bright_yellow", "bright_blue", "bright_magenta",
                             "bright_cyan", "bright_foreground")):
        alias(f"color{n}", key)
    # the theme's mode: the mode key, the older theme_type key, a light.mode file, then how bright the background is
    mode = c.get("mode") or c.get("theme_type")
    if not mode:
        if (folder / "light.mode").exists():
            mode = "light"
        elif c.get("background"):
            mode = "light" if sum(int(c["background"][i:i + 2], 16) for i in (1, 3, 5)) > 382 else "dark"
        else:
            mode = "dark"
    c["mode"] = mode
    return c


def cockpit_palette():
    """The Starchaser Cockpit theme file: the palette of a theme folder that has only pictures, and the fallback for
    a role a colors.toml can't give."""
    for base in (Path(__file__).resolve().parent.parent / "themes", Path("/usr/share/starchaser/themes")):
        try:
            data = tomllib.loads((base / "starchaser-cockpit.toml").read_text())
        except (OSError, UnicodeError, tomllib.TOMLDecodeError):
            continue
        if all(isinstance(data.get(v), dict) for v in ("dark", "light")):
            return data
    raise Problem("The Starchaser Cockpit theme couldn't be read, so this theme can't be converted.")


THEME_ROLES = ("bg", "bg_alt", "surface", "surface_hi", "selection", "border", "text", "subtext", "muted",
               "accent", "accent2", "accent3", "success", "warning", "error", "info")


def omarchy_palette(colors):
    """(variant, roles, term) for Starchaser from resolved colors (omarchy_colors). The one mapping, also in
    docs/satellites.md:

        bg         = background
        bg_alt     = dark_background
        surface    = lighter_background (mix(background, foreground, 0.08) when it is missing or equals background)
        surface_hi = mix(surface, foreground, 0.10)
        selection  = selection
        border     = mix(surface, muted, 0.5)
        text       = foreground (pushed toward white or black until it reads at 4.5:1 on bg)
        subtext    = mix(foreground, background, 0.20) (pushed the same way)
        muted      = muted
        accent     = accent (blue when missing)
        accent2    = blue, or cyan when blue is the accent
        accent3    = magenta
        success    = green
        warning    = yellow
        error      = red
        info       = cyan
        term       = color0 to color15, the resolved ANSI colors

    Only '#rrggbb' values are used ('#rgb' and '0xRRGGBB' are converted); a role whose colors are missing takes
    the Starchaser Cockpit color for that role. variant is the theme's mode, "dark" or "light"."""
    variant = "light" if colors.get("mode") == "light" else "dark"
    base = cockpit_palette()[variant]
    c = {k: v for k, v in colors.items() if k != "mode" and HEX6_RE.fullmatch(str(v))}
    roles = {}
    bg = c.get("background")
    fg = c.get("foreground")
    roles["bg"] = bg or base["bg"]
    roles["bg_alt"] = c.get("dark_background") or base["bg_alt"]
    surface = c.get("lighter_background")
    if not surface or surface == bg:
        surface = theme_mix(bg, fg, 0.08) if bg and fg else base["surface"]
    roles["surface"] = surface
    roles["surface_hi"] = theme_mix(surface, fg, 0.10) if fg else base["surface_hi"]
    roles["selection"] = c.get("selection") or base["selection"]
    roles["border"] = theme_mix(surface, c["muted"], 0.5) if c.get("muted") else base["border"]
    roles["text"] = fg or base["text"]
    roles["subtext"] = theme_mix(fg, bg, 0.20) if fg and bg else base["subtext"]
    roles["muted"] = c.get("muted") or base["muted"]
    accent = c.get("accent") or c.get("blue")
    roles["accent"] = accent or base["accent"]
    roles["accent2"] = (c.get("cyan") if c.get("blue") == accent else c.get("blue")) or base["accent2"]
    roles["accent3"] = c.get("magenta") or base["accent3"]
    for role, key in (("success", "green"), ("warning", "yellow"), ("error", "red"), ("info", "cyan")):
        roles[role] = c.get(key) or base[role]
    for role in ("text", "subtext"):
        if theme_contrast(roles[role], roles["bg"]) < 4.5:
            roles[role] = theme_readable(roles[role], roles["bg"])
    roles = {r: theme_hex(roles[r]) or theme_hex(base[r]) for r in THEME_ROLES}
    if not all(roles[r] and HEX6_RE.fullmatch(roles[r]) for r in THEME_ROLES):
        raise Problem("This theme's colors couldn't be read.")
    term = {f"color{n}": c[f"color{n}"] for n in range(16) if c.get(f"color{n}")}
    return variant, roles, term


def is_plain_theme(folder):
    """What a folder without satellite.toml is a theme made of: "colors.toml", "alacritty.toml" (with a [colors]
    table) or "backgrounds" (pictures only). "" for anything else, and always for a satellite folder."""
    folder = Path(folder)
    if os.path.lexists(folder / "satellite.toml"):
        return ""
    if (folder / "colors.toml").is_file():
        return "colors.toml"
    text = read_small(folder / "alacritty.toml")
    if text is not None:
        with contextlib.suppress(tomllib.TOMLDecodeError, RecursionError):
            if isinstance(tomllib.loads(text).get("colors"), dict):
                return "alacritty.toml"
    if background_files(folder):
        return "backgrounds"
    return ""


# at most this many of a theme's pictures become its wallpaper set (Omarchy themes ship a handful)
WALLPAPER_PICTURES = 99


def background_files(folder):
    """The pictures in backgrounds/, in natural order (2 before 10)."""
    pictures = Path(folder) / "backgrounds"
    if not pictures.is_dir() or pictures.is_symlink():
        return []
    try:
        files = [p for p in pictures.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES and p.is_file()]
    except OSError:
        return []
    return sorted(files, key=lambda p: [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", p.name)])


def theme_link_id(source):
    """The theme's id from its link or folder name: the last part without .git, a leading omarchy- and a trailing
    -theme (the rule Omarchy's own theme install uses), then a leading theme- left by names like
    omarchy-theme-still-water (so its name isn't "Theme Still Water"), lowercase, then made into a satellite id."""
    text = str(source).strip()
    name = text.rstrip("/").rsplit("/", 1)[-1] if "://" in text else Path(text).resolve().name
    name = name.removesuffix(".git").lower()
    name = name.removeprefix("omarchy-").removesuffix("-theme")
    name = name.removeprefix("theme-") or name
    return re.sub(r"[^a-z0-9]+", "-", name).strip("-")[:80].strip("-")


def taken_theme_ids(sid):
    """Theme and add-on ids already here, other than the add-on sid itself."""
    ids = set()
    for base in (CONFIG / "themes", Path("/usr/share/starchaser/themes"), Path(__file__).resolve().parent.parent / "themes"):
        with contextlib.suppress(OSError):
            ids |= {f.stem for f in base.glob("*.toml")} if base.is_dir() else set()
    for base in INCLUDED:
        with contextlib.suppress(OSError):
            ids |= {p.name for p in base.iterdir() if p.is_dir()} if base.is_dir() else set()
    with contextlib.suppress(Problem, OSError, ValueError, RecursionError):
        ids |= theme_ids([i for i in catalog()["satellites"] if i["id"] != sid])
    return ids


def write_generated(path, text):
    """Create a file that must not exist yet (never through a link the folder ships)."""
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o644)
    with os.fdopen(fd, "w") as stream:
        stream.write(text)


def omarchy_to_satellite(stage, source, sha, sid=None):
    """Turn a plain theme folder (is_plain_theme) into a theme satellite, in place, and return what it was made of.
    stage is a clone or a copy, never the person's own folder. sid keeps the id an update must have. The folder's
    own files are kept but never read beyond colors.toml, alacritty.toml, light.mode and the picture headers, and
    nothing in it is run. sha is the pinned commit; the caller's record keeps it, so it is not written here."""
    stage = Path(stage)
    made_of = is_plain_theme(stage)
    if not made_of:
        return ""
    check_tree(stage)                         # links inside it are checked before anything in it is read
    if sid is None:
        sid = theme_link_id(source)
        if not sid or not ID_RE.fullmatch(sid):
            raise Problem("That link doesn't give a usable theme name.")
        taken = taken_theme_ids(sid)
        if sid in taken:
            sid = (sid[:74].rstrip("-") + "-theme")
            if sid in taken:
                raise Problem("A theme with this name is already here.")
    words = [w for w in sid.split("-") if w and w != "omarchy"] or [sid]
    name = " ".join(w.capitalize() for w in words)
    colors = omarchy_colors(stage) if made_of != "backgrounds" else {}
    cockpit = cockpit_palette()
    if colors:
        variant, roles, term = omarchy_palette(colors)
        palettes = {variant: (roles, term)}
    else:
        if made_of != "backgrounds" and not background_files(stage):
            raise Problem("This theme's colors couldn't be read.")
        # pictures only: a wallpaper pack with the Starchaser Cockpit colors, both modes
        variant = "light" if (stage / "light.mode").exists() else "dark"
        palettes = {v: ({r: cockpit[v][r] for r in THEME_ROLES}, {}) for v in ("dark", "light")}
    entry = next((d for d in ("theme", "starchaser-theme") if not os.path.lexists(stage / d)), None)
    if entry is None:
        raise Problem("This theme's folder already uses the names Starchaser needs, so it can't be converted.")
    owner = "Unknown"
    match = re.match(r"https://[^/]+/([A-Za-z0-9_.~-]+)/", str(source))
    if match:
        owner = match.group(1)
    homepage = str(source) if "://" in str(source) else "Local folder"
    generated = []
    # every picture whose size can be read, in natural order: the first is the theme's wallpaper, the rest are the
    # set's other pictures ("-p2", "-p3", ...), which starchaser wallpaper next and previous move through
    readable = [(path, size) for path in background_files(stage) for size in [image_size(path)] if size]
    picture = readable[0] if readable else None
    (stage / entry / "wallpapers").mkdir(parents=True)
    generated.append(f"/{entry}/")
    for number, (path, (width, height)) in enumerate(readable[:WALLPAPER_PICTURES], 1):
        tail = f"-p{number}" if number > 1 else ""
        link = stage / entry / "wallpapers" / f"{sid}-{variant}-{width}x{height}{tail}{path.suffix.lower()}"
        os.symlink(os.path.relpath(path, link.parent), link)
    lines = [f"# Made by Starchaser from this theme's {made_of}.", f"name = {json.dumps(name)}",
             f"description = {json.dumps('Colors and wallpaper from a theme folder.')}",
             f"wallpaper = {json.dumps(sid if picture else 'starchaser-cockpit')}"]
    # one picture for both modes, said only for the theme's own set: on the Cockpit set it would change how
    # Starchaser's own Cockpit theme looks in the other mode
    if picture:
        lines.append(f"wallpaper_variant = {json.dumps(variant)}")
    lines.append('screensaver = "journey"')
    for v, (roles, term) in palettes.items():
        lines += ["", f"[{v}]"] + [f"{r:<10} = {json.dumps(roles[r])}" for r in THEME_ROLES]
        if term:
            lines += ["", f"[{v}.term]"] + [f"{k} = {json.dumps(x)}" for k, x in term.items()]
    write_generated(stage / entry / f"{sid}.toml", "\n".join(lines) + "\n")
    manifest_text = "\n".join([
        f"# Made by Starchaser from this theme's {made_of}. Nothing in this folder is run.",
        f"id = {json.dumps(sid)}", f"name = {json.dumps(name)}", 'version = "1.0.0"',
        'summary = "A theme: colors and wallpaper."', f"author = {json.dumps(owner)}",
        "license = \"See the theme's own files\"", f"homepage = {json.dumps(homepage)}", "",
        "[starchaser]", f"api = {API}", 'kinds = ["theme"]', f'entry = {{ theme = "{entry}/" }}', "",
        "[permissions]", ""])
    write_generated(stage / "satellite.toml", manifest_text)
    generated.append("/satellite.toml")
    if not os.path.lexists(stage / "README.md"):
        write_generated(stage / "README.md", f"Converted by Starchaser from this theme's {made_of}. Nothing in this folder is run.\n")
        generated.append("/README.md")
    write_generated(stage / THEME_IMPORT, made_of + "\n")
    generated.append("/" + THEME_IMPORT)
    git_dir = stage / ".git"
    if git_dir.is_dir() and not git_dir.is_symlink():
        (git_dir / "info").mkdir(exist_ok=True)
        with (git_dir / "info/exclude").open("a") as stream:
            stream.write("\n# Made by Starchaser when this theme was added\n" + "\n".join(generated) + "\n")
    return made_of


def plain_theme_info(folder):
    """info for a plain theme folder on this computer: converted in a copy, never in the person's folder."""
    with tempfile.TemporaryDirectory(prefix="starchaser-satellite-info-") as work:
        root = Path(work) / "satellite"
        shutil.copytree(folder, root)
        converted = omarchy_to_satellite(root, str(folder), "")
        check_tree(root)
        result = details({**manifest(root), "path": str(root), "source": "Local folder", "commit": ""})
        result["converted"] = converted
        return result


def reference_path(folder, value):
    """Resolve a runtime reference, checking both its spelling and every symlink target.

    Dot components normalize normally; parent components are always refused. Inspect
    each prefix so a link through a hidden directory cannot escape detection by ending
    at a visible file. Missing targets remain unclassified and therefore warn.
    """
    message = "Satellite entries must stay inside its folder, outside hidden and version-control folders, without parent (..) paths."
    if (not isinstance(value, str) or not value.strip() or "\0" in value or "\\" in value
            or Path(value).is_absolute() or re.match(r"^[A-Za-z]:", value)):
        raise Problem(message)
    root = Path(folder).resolve()

    def check(parts):
        for part in parts:
            name = unicodedata.normalize("NFKC", part).casefold()
            if name.startswith(".") or name in VCS_DIRS or any(ord(c) < 32 for c in part):
                raise Problem(message)

    parts = Path(value).parts
    check(parts)
    path = root
    try:
        seen = set()
        def resolve_link(candidate):
            if candidate.is_symlink():
                if candidate in seen:
                    raise Problem(message)
                seen.add(candidate)
                target = Path(os.readlink(candidate))
                target = target if target.is_absolute() else candidate.parent / target
                if not target.is_relative_to(root):
                    raise Problem(message)
                # A relative file link may go up to a sibling inside the add-on
                # (imported wallpaper links do). Check its spelled components,
                # then the fully resolved target below; no parent path is returned.
                check(part for part in target.relative_to(root).parts if part != "..")
                return resolve_link(target)
            return candidate

        for part in parts:
            path = path / part
            resolved = resolve_link(path).resolve()
            if not resolved.is_relative_to(root):
                raise Problem(message)
            check(resolved.relative_to(root).parts)
        return path.resolve()
    except (OSError, ValueError, RuntimeError):
        raise Problem(message) from None


def ships_code(m, folder):
    """One fail-closed decision for validation, install, enable and every warning.

    Only successfully parsed data in a known data-only runtime route is exempt.
    Commands, QML, scripts, unknown kinds, missing/unreadable content and ambiguous
    formats are code. List metadata alone cannot prove that a download is plain data.
    Validate ALL references before returning, including indirect files in containers.
    """
    if folder is None:
        return True
    folder = Path(folder).resolve()
    entries = m.get("entry", {})
    if any(kind not in ENTRY_DEFAULTS for kind in entries):
        raise Problem("The add-on has an unknown entry; use a supported add-on kind.")
    references = {kind: reference_path(folder, value) for kind, value in entries.items()}
    for kind in m["kinds"]:
        if kind in ENTRY_DEFAULTS and kind not in references:
            references[kind] = reference_path(folder, ENTRY_DEFAULTS[kind])
    loaded = []
    for kind, path in references.items():
        if path.is_dir():
            # Directory entries can load child files (cards, hooks, themes, assets).
            # Validate their targets too, independently of any classification result.
            for base, dirs, files in os.walk(path, followlinks=False):
                for name in dirs + files:
                    reference_path(folder, str((Path(base) / name).relative_to(folder)))
            if kind not in {"theme", "today-card", "cli-hook"}:
                loaded.append((kind, path))  # A file entry naming a directory is unclassified.
                continue
            children = sorted(path.glob("*.toml")) if kind in {"theme", "today-card"} else list(path.iterdir())
            loaded.extend((kind, child) for child in children)
            if not children:
                loaded.append((kind, path))
        else:
            loaded.append(("unclassified" if kind in {"theme", "today-card", "cli-hook"} else kind, path))

    def no_duplicate_keys(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise ValueError("duplicate field")
            result[key] = value
        return result

    def has_commands(value):
        if isinstance(value, dict):
            # Even empty or mistyped commands are not a proof of plain data.
            return any(k in {"run", "get", "set", "query_command", "open"} or has_commands(v) for k, v in value.items())
        return isinstance(value, list) and any(has_commands(v) for v in value)

    def plain_data(kind, path):
        if kind not in {"theme", "menu-page", "settings-page", *SURFACE_KINDS} or not path.is_file():
            return False
        # Settings' runtime selects TOML or QML. Never parse a code page as data,
        # even if someone puts valid TOML in a file loaded by the QML engine.
        if kind == "settings-page" and path.suffix != ".toml":
            return False
        try:
            if path.stat().st_size > 256 * 1024 or path.stat().st_mode & 0o111:
                return False
            content = path.read_text()
            value = json.loads(content, object_pairs_hook=no_duplicate_keys) if kind == "menu-page" or kind in SURFACE_KINDS else tomllib.loads(content)
            return isinstance(value, (dict, list)) and not has_commands(value)
        except (OSError, ValueError, RecursionError):
            return False

    code = any(kind not in ENTRY_DEFAULTS for kind in m["kinds"])
    for kind, path in loaded:
        if not plain_data(kind, path):
            code = True
    # Keep warning about additional shipped executables too. Unreferenced Git
    # metadata is not loaded; referenced metadata was already refused above.
    for base, dirs, files in os.walk(folder, followlinks=False):
        dirs[:] = [d for d in dirs if d != ".git"]
        for name in files:
            try:
                if (Path(base) / name).stat().st_mode & 0o111:
                    code = True
            except OSError:
                code = True
    return code


def files_in(folder):
    root = Path(folder)
    return {str(p.relative_to(root)) for p in root.rglob("*")
            if (p.is_symlink() or p.is_file()) and ".git" not in p.relative_to(root).parts}


def same_file(a, b):
    """Same contents, same link target, and same executable bit: a hook that points somewhere else is a change."""
    if a.is_symlink() or b.is_symlink():
        return a.is_symlink() and b.is_symlink() and os.readlink(a) == os.readlink(b)
    return (a.stat().st_mode & 0o111) == (b.stat().st_mode & 0o111) and a.read_bytes() == b.read_bytes()


def plural(count, word):
    return f"{count} {word}{'' if count == 1 else 's'}"


def change_summary(old, new, before, after, review):
    """What an update changes, in plain sentences: version, files, what it adds, what it asks for, and its review."""
    lines = [f"Version {before['version']} to {after['version']}." if before["version"] != after["version"]
             else f"Same version number ({after['version']}), with changed files."]
    old_files, new_files = files_in(old), files_in(new)
    added = sorted(new_files - old_files)
    gone = sorted(old_files - new_files)
    edited = sorted(f for f in old_files & new_files if not same_file(Path(old) / f, Path(new) / f))
    touched = added + edited + gone
    if touched:
        lines.append(f"{plural(len(touched), 'file')} changed: {len(added)} new, {len(edited)} edited, {len(gone)} removed.")
        names = touched[:12]
        lines.append("Files: " + ", ".join(names) + (f", and {len(touched) - 12} more." if len(touched) > 12 else "."))
    else:
        lines.append("No files changed.")
    for kind in after["kinds"]:
        if kind in KINDS and kind not in before["kinds"]:
            lines.append(f"Now also adds {KINDS[kind]}.")
    for kind in before["kinds"]:
        if kind in KINDS and kind not in after["kinds"]:
            lines.append(f"No longer adds {KINDS[kind]}.")
    labels = {"network": "Now connects to", "run": "Now runs", "read": "Now reads", "write": "Now writes"}
    for key, label in labels.items():
        more = [v for v in after["permissions"].get(key, []) if v not in before["permissions"].get(key, [])]
        if more:
            lines.append(label + " " + ", ".join(more) + ".")
    for key, sentence in (("notify", "Now shows notifications."), ("location", "Now uses your location."),
                          ("media", "Now controls music and video playback."),
                          ("search", "Now reads text you type in menu searches."),
                          ("selected_file", "Now reads the one file you select in Files.")):
        if after["permissions"].get(key) and not before["permissions"].get(key):
            lines.append(sentence)
    for source in after.get("providers", []):
        if source not in before.get("providers", []):
            lines.append("Now reads " + source + " from Starchaser.")
    for key in after.get("secrets", []):
        if key not in before.get("secrets", []):
            lines.append("Now uses its saved sign-in named " + key + ".")
    if after.get("sandbox", "full-access") == "full-access" and before.get("sandbox", "full-access") != "full-access":
        lines.append("Now has full access to your files and network.")
    packages = [p for p in after["packages"] if p not in before["packages"]]
    if packages:
        lines.append("Now needs packages: " + ", ".join(packages) + ".")
    if ships_code(after, new) and not ships_code(before, old):
        lines.append("Now includes code. " + CODE_WARNING)
    lines.append("A person at Starchaser reviewed this version." if review == "Reviewed"
                 else "This version has not been reviewed.")
    return lines


def update_targets(sid=None, refresh=False):
    """(waiting, problems): the installed satellites with a newer version waiting. One added from the list follows the
    list's reviewed commit; one added from a link follows its repository's newest commit (unreviewed). Included ones
    update with Starchaser, and a local folder is added again by hand."""
    data, waiting, problems = None, [], []
    if any((INSTALLED / i).is_dir() for i in state()["satellites"]):
        # read the list first, so what it took off is switched off before anything is offered
        with contextlib.suppress(Problem, OSError, ValueError, RecursionError):
            load_index(offline=True, url=SHARED_INDEX)
        with contextlib.suppress(Problem, OSError, ValueError, RecursionError):
            data = load_index(refresh)
    saved = state()
    items = [i for i in catalog(saved)["satellites"] if sid is None or i["id"] == sid]
    if sid is not None and not items:
        find(sid, saved)                         # the plain reason it isn't here
    told = False
    # Independent link sites have a bounded wait and run together, so one slow site cannot hold up every add-on.
    with ThreadPoolExecutor(max_workers=8) as checks:
        remote = {item["id"]: checks.submit(git, ["ls-remote", "--", record.get("source_url", ""), "HEAD"], timeout=15)
                  for item in items
                  if (record := saved["satellites"].get(item["id"], {})).get("commit")
                  and not record.get("index") and not record.get("index_removed") and Path(item["path"]).parent == INSTALLED}
        return collect_updates(items, saved, data, waiting, problems, told, remote, sid, refresh)


def collect_updates(items, saved, data, waiting, problems, told, remote, sid, refresh):
    for item in items:
        record = saved["satellites"].get(item["id"], {})
        if Path(item["path"]).parent != INSTALLED or not record.get("commit") or record.get("index_removed"):
            if sid is not None:
                raise Problem(f"{item['name']} was taken off the add-on list, so it isn't updated." if record.get("index_removed")
                              else f"{item['name']} comes with Starchaser and updates with it." if item["source"] == "Included"
                              else f"{item['name']} was added from a folder. Remove it and add it again to change it.")
            continue
        target = {"id": item["id"], "name": item["name"], "version": item["version"], "from": record["commit"],
                  "repo": record.get("source_url", ""), "enabled": item["enabled"]}
        if record.get("index"):
            data = data or load_index(refresh)
            if data["state"] in {"offline", "bad"} and data["notice"] and not told:
                problems.append(data["notice"])
                told = True
            entry = next((e for e in data["entries"] if e["id"] == item["id"]), None)
            if entry is None or entry["review"] not in {"Reviewed", "Unreviewed"} or listing(entry, None)["blocked"]:
                continue
            if entry["commit"] != record["commit"]:
                changed_source = not same_repo(target["repo"], entry["repo"])
                if changed_source and data.get("signature") != "signed":
                    problems.append(f"{item['name']} now points to a different address in an unsigned list, so it wasn't updated.")
                    continue
                target.update(signature=data.get("signature"), previous_repo=target["repo"], to=entry["commit"], review=entry["review"], repo=entry["repo"],
                              version_to=entry["version"], source_warning=
                              f"Now comes from a different address: {entry['repo']}" if changed_source else "")
        else:
            try:
                heads = remote[item["id"]].result().split()
            except Problem:
                problems.append(f"Couldn't reach where {item['name']} comes from.")
                continue
            if heads and SHA_RE.fullmatch(heads[0]) and heads[0] != record["commit"]:
                target.update(to=heads[0], review="Unreviewed", version_to="")
        if "to" in target:
            try:
                check_update_removal(target)
            except Problem as ex:
                problems.append(str(ex))
                continue
            target["to_version"] = target.get("version_to", "")
            waiting.append(target)
    return waiting, problems


def check_update_removal(target):
    taken = removed_from_list(target["id"], target["repo"])
    if taken:
        raise Problem(f"{target['name']} was taken off the add-on list, so it can't be updated from that address. {taken}")


@contextlib.contextmanager
def staged_update(target):
    """The waiting version, cloned beside the installed one and checked like an install, with its change summary."""
    check_update_removal(target)
    if not git_link(target["repo"]):
        raise Problem("That add-on's address can't be used for updates.")
    old = INSTALLED / target["id"]
    with tempfile.TemporaryDirectory(prefix=".update-", dir=INSTALLED) as work:
        stage = Path(work) / "satellite"
        sha = clone(target["repo"], stage, target["to"])
        if sha != target["to"]:
            raise Problem("The waiting version couldn't be found.")
        omarchy_to_satellite(stage, target["repo"], sha, sid=target["id"])
        check_tree(stage)
        after = manifest(stage)
        if after["id"] != target["id"]:
            raise Problem("The new version has a different id, so it can't update this add-on.")
        moves = pointer_problem(stage)
        if moves:
            raise Problem(moves + " It wasn't updated.")
        before = manifest(old)
        summary = change_summary(old, stage, before, after, target["review"])
        if target.get("source_warning"):
            summary.insert(0, target["source_warning"])
        yield stage, after, summary


def update_info(sid, refresh=False):
    waiting, problems = update_targets(sid, refresh)
    if not waiting:
        if problems:
            raise Problem(problems[0])
        raise Problem(f"{find(sid)['name']} is up to date.")
    target = waiting[0]
    with staged_update(target) as (_stage, after, summary):
        return {**target, "version_to": after["version"], "summary": summary,
                "warning": "" if target["review"] == "Reviewed" else WARNING,
                "code_warning": (("This add-on includes code. " + access_note(after)) if after.get("sandbox") == "restricted" else CODE_WARNING) if ships_code(after, _stage) else ""}


def update(sid, commit, yes, refresh=False):
    """Update add-ons interactively, showing what changed and asking first."""
    waiting, problems = update_targets(sid, refresh)
    for sentence in problems:
        print(sentence, file=sys.stderr)
    if not waiting:
        if sid is not None and not problems:
            print(f"{find(sid)['name']} is up to date.")
        elif sid is None:
            print("Every add-on is up to date." if not problems else "No updates were found.")
        return
    if commit and (len(waiting) != 1 or waiting[0]["to"] != commit.lower()):
        raise Problem("The version waiting has changed. Check for updates again.")
    for target in waiting:
        with staged_update(target) as (stage, after, summary):
            print(f"{target['name']}:")
            for line in summary:
                print("  " + line)
            if target["review"] != "Reviewed":
                print(WARNING)
            try:
                confirm(f"Update {target['name']}?", yes)
            except Problem:
                if len(waiting) > 1:
                    print(f"{target['name']} was not updated.")
                    continue
                raise
            apply_update(target, stage, after)


def apply_update(target, stage, after):
    # The official feed may have changed while the files downloaded or the person reviewed the update.
    check_update_removal(target)
    sid = target["id"]
    old = INSTALLED / sid
    keep = old.parent / f".old-{sid}-{os.getpid()}"
    swapped = False

    def rollback():
        if swapped:
            os.rename(old, stage)
            os.rename(keep, old)

    with locked_state(rollback) as saved:
        record = saved["satellites"].get(sid)
        if not record or record.get("commit") != target["from"]:
            raise Problem(f"{target['name']} changed while it was being updated. Check for updates again.")
        if record.get("index_removed"):
            raise Problem(f"{target['name']} was taken off the add-on list, so it can't be updated. {record['index_removed']}")
        os.rename(old, keep)
        os.rename(stage, old)
        swapped = True
        record.update(commit=target["to"], source_url=target["repo"], granted_permissions=after["permissions"], granted_providers=after.get("providers", []), granted_secrets=after.get("secrets", []), granted_sandbox=after.get("sandbox"), failures=[], reason="")
        if record.get("index"):
            record["review"] = target["review"]
    previous = INSTALLED / (".previous-" + sid)
    if previous.exists():
        delete_satellite_tree(previous)
    os.rename(keep, previous)
    with locked_state() as saved:
        saved["satellites"][sid]["previous"] = {"commit": target["from"], "repo": target.get("previous_repo", target["repo"])}
    sentence = f"Updated {target['name']} from {target['version']} to {after['version']}."
    log(sid, sentence)
    print(sentence)


def use_added_theme(item, theme_id=None):
    """Run the theme engine only after saving add-on state and releasing its lock."""
    ids = theme_ids([item])
    if theme_id is None and len(ids) == 1:
        theme_id = next(iter(ids))
    if theme_id not in ids:
        print("The add-on is on. Choose one of its themes in Appearance to use it.")
        return
    try:
        result = subprocess.run([str(Path(__file__).resolve().with_name("starchaser-theme")), "apply", theme_id],
                                stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60)
        if result.returncode:
            raise OSError("theme apply failed")
    except (OSError, subprocess.SubprocessError):
        print("The add-on is on, but its theme could not be applied. Try it in Appearance.")
        return
    print(f"Using theme {theme_id}. Undo the change in Appearance.")


def stop_satellite(sid, keepers=None):
    """Stop only verified children belonging to this add-on, after its off state is durable."""
    if keepers is None:
        keepers = {mode: panel_keeper(sid, mode) for mode in ("page", "panel", "overlay")}
    for mode, pid in keepers.items():
        if pid is not None and keeper_ours(pid, sid, mode):
            with contextlib.suppress(ProcessLookupError):
                os.kill(pid, signal.SIGTERM)
    children = {}
    for mode in ("widget", "service", "page", "panel", "overlay"):
        pidfile = RUN / sid / f"{mode}.pid"
        try:
            pid = int(pidfile.read_text().strip())
            if ours(pid, sid, mode):
                children[mode] = pid
                stop_group(pid)
        except (OSError, ValueError):
            continue
    # Give keepers time to reap their children, remove PID files and restore overlay keys before deleting files.
    deadline = time.monotonic() + 3
    while time.monotonic() < deadline:
        if all(process_stopped(pid) for pid in keepers.values() if pid is not None):
            break
        time.sleep(0.02)
    for mode, pid in keepers.items():
        if pid is not None and keeper_ours(pid, sid, mode):
            stop_group(pid)
            if mode == "overlay":
                overlay_submap(False)
    deadline = time.monotonic() + 2
    while time.monotonic() < deadline:
        if all(process_stopped(pid) for pid in [*children.values(), *keepers.values()] if pid is not None):
            return
        time.sleep(0.02)
    raise Problem("The add-on is off, but one of its processes couldn't be stopped. Try Remove again.")


def process_stopped(pid):
    """A process has exited only once it is gone or a zombie, even if its command line is already empty."""
    try:
        return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] in ("Z", "X")
    except (OSError, IndexError):
        return True


def delete_satellite_tree(path):
    """An add-on may make its own folders read-only. Restore owner access without following links."""
    root = Path(path)
    if root.is_symlink():
        raise Problem("Satellite folders can't be links.")
    root.chmod(root.stat().st_mode | 0o700)
    # Make each folder traversable before os.walk enters it, including folders with no owner permissions.
    for base, folders, _files in os.walk(root, followlinks=False):
        for name in folders:
            folder = Path(base) / name
            if not folder.is_symlink():
                folder.chmod(folder.stat().st_mode | 0o700)

    def retry(function, name, _error):
        target = Path(name)
        for folder in (target.parent, target):
            if not folder.is_symlink() and folder.is_dir():
                folder.chmod(folder.stat().st_mode | 0o700)
        if function is os.open:
            # rmtree's open needs flags; a recursive retry also completes the folder it couldn't enter.
            shutil.rmtree(name, onerror=retry)
        else:
            function(name)

    shutil.rmtree(path, onerror=retry)


def remove_satellite(sid, yes, purge):
    with locked_state() as saved:
        installed, trash = INSTALLED / sid, INSTALLED / f".trash-{sid}"
        data = catalog(saved)
        item = next((i for i in data["satellites"] + data["hidden"] if i["id"] == sid), None)
        if (item is None and not installed.is_dir() and not trash.is_dir()
                and not saved["satellites"].get(sid, {}).get("remove_leftovers")):
            find(sid, saved)
        item = item or {"id": sid, "name": sid, "path": str(installed)}
        if installed.is_symlink():
            raise Problem("Satellite folders can't be links.")
        confirm(f"Remove {item['name']}? " + ("Its saved settings will be deleted." if purge else "Its saved settings will be kept."), yes)
        offered = theme_ids([item])
        record = saved["satellites"].setdefault(sid, {})
        # Remember keepers before publishing off: they may remove their PID files as soon as they see it.
        keepers = {mode: panel_keeper(sid, mode) for mode in ("page", "panel", "overlay")}
        record.update(restore_enabled=bool(item.get("enabled")), enabled=False, removed=True)
        if not purge:
            record.update(trash_until=time.time() + 7 * 86400, trash_name=item["name"])
        try:
            # Save before any process, file, log or theme operation can fail; never roll this state back.
            atomic_json(STATE, saved)
        except OSError:
            MARKER.touch()
            stop_satellite(sid, keepers)
            raise
        stop_satellite(sid, keepers)
        theme_gone(offered)
        leftovers = []
        if installed.is_dir() or trash.is_dir():
            try:
                if installed.is_dir():
                    if trash.exists():
                        delete_satellite_tree(trash)
                    os.rename(installed, trash)
                if purge:
                    delete_satellite_tree(trash)
                else:
                    record["trash_until"] = time.time() + 7 * 86400
                    record["trash_name"] = item["name"]
            except OSError:
                leftovers.append(str(trash if trash.exists() else installed))
            else:
                if purge:
                    saved["satellites"].pop(sid, None)
        if purge:
            try:
                if data_dir(sid).exists():
                    delete_satellite_tree(data_dir(sid))
                forget_logs(sid)
            except OSError:
                leftovers.append(str(data_dir(sid)))
        sentence = (f"Deleted the saved settings of {item['name']}." if purge and item in data["hidden"]
                    else f"Removed {item['name']}.")
        if leftovers:
            saved["satellites"].setdefault(sid, record)["remove_leftovers"] = leftovers
            sentence += " It is off; some files are left in " + ", ".join(leftovers) + ". Try Remove again to delete them."
        else:
            record.pop("remove_leftovers", None)
            if purge and not any((base / sid).is_dir() for base in INCLUDED):
                saved["satellites"].pop(sid, None)
        if installed != Path(item.get("path", installed)) and trash.exists() and any((base / sid).is_dir() for base in INCLUDED):
            delete_satellite_tree(trash)
            saved["satellites"].pop(sid, None)
        if not purge:
            log(sid, sentence)
    print(sentence)


def change(sid, action, yes=False, purge=False, use_theme=False, theme_id=None):
    if action == "remove":
        return remove_satellite(sid, yes, purge)
    if action == "enable":
        load_index(offline=True, url=SHARED_INDEX)
    with locked_state() as saved:
        if action == "restore":
            record = saved["satellites"].get(sid, {})
            if not record.get("removed"):
                raise Problem("That add-on isn't removed.")
            record["removed"] = False
            item = find(sid, saved)
            sentence = f"{item['name']} is back; it is off."
            log(sid, sentence)
            print(sentence)
            return
        item = find(sid, saved)
        record = saved["satellites"].setdefault(sid, {})
        where = ""
        offered = theme_ids([item]) if action == "disable" else set()
        if action == "enable":
            if record.get("recovered"):
                raise Problem("Its saved settings were damaged. Remove this add-on and add it again before turning it on.")
            if record.get("index_removed"):
                raise Problem(f"{item['name']} was taken off the add-on list, so it can't be turned on. You can remove it.")
            unchanged(item)
            policy_check(item)
            if item.get("sandbox") == "restricted" and ships_code(item, Path(item["path"])) and not shutil.which("bwrap"):
                raise Problem("The add-on sandbox is missing. Install bubblewrap in Software before turning this add-on on.")
        if action in {"enable", "disable"}:
            record["enabled"] = action == "enable"
            if action == "enable":
                if item.get("source") != "Included" and ships_code(item, item["path"]):
                    print(access_note(item) if item.get("sandbox") == "restricted" else CODE_WARNING, file=sys.stderr)
                record.update(reason="", failures=[], removed=False, granted_permissions=item["permissions"], granted_providers=item.get("providers", []), granted_secrets=item.get("secrets", []), granted_sandbox=item.get("sandbox"))
                saved["safe"] = False
                MARKER.unlink(missing_ok=True)
                (DATA / "satellite-data" / sid).mkdir(parents=True, exist_ok=True)
            sentence = f"{item['name']} is {'on' if action == 'enable' else 'off'}."
            if action == "enable":
                where = next((words for kind, words in WHERE_ON if kind in item.get("kinds", [])), "")
                if "search-result" in item.get("kinds", []):
                    with contextlib.suppress(OSError, ValueError, TypeError):
                        rows = json.loads(entry_path(item, "search-result", "search-result.json").read_text())
                        hint = next((r.get("text", "") for r in rows if isinstance(r, dict) and r.get("query_prefix")), "")
                        if hint:
                            where = "In the menu, " + hint[0].lower() + hint[1:]
        else:
            sentence = note_failure(saved, sid, item["name"])
        log(sid, sentence)
    sync_file_actions()
    theme_gone(offered)
    print(sentence + (f" {where}" if where and not use_theme else ""))
    if action == "enable" and use_theme:
        use_added_theme(item, theme_id)


def safe():
    with locked_state() as saved:
        offered = theme_ids([i for i in catalog(saved)["satellites"] if i["enabled"]])
        if not safe_on(saved):
            # remembered so Leave safe mode can turn the same ones back on, with the theme one of them gave (safe
            # mode puts the default theme in its place)
            saved["before_safe"] = [i["id"] for i in catalog(saved)["satellites"] if i["enabled"]]
            saved.pop("before_safe_theme", None)
            with contextlib.suppress(OSError, ValueError, AttributeError, TypeError):
                state = json.loads(THEME_STATE.read_text())
                if state.get("id") in offered:
                    saved["before_safe_theme"] = {"id": state["id"], "variant": state.get("variant") or "dark"}
        # Even a missing or broken folder must stay off after safe mode is cleared.
        for record in saved["satellites"].values():
            record["enabled"] = False
        for item in catalog(saved)["satellites"]:
            saved["satellites"].setdefault(item["id"], {})["enabled"] = False
            log(item["id"], "Safe mode turned this add-on off.")
        saved["safe"] = True
        MARKER.touch()
    theme_gone(offered)
    print("Safe mode is on; every add-on is off until you turn one on again.")


def leave_safe():
    """Turn back on the add-ons that were on when safe mode started, each checked as enable checks it."""
    load_index(offline=True, url=SHARED_INDEX)
    with locked_state() as saved:
        saved["safe"] = False
        MARKER.unlink(missing_ok=True)
        back, kept = [], []
        # None: this safe mode never saved the list (an older version started it, or only the marker file or
        # STARCHASER_SATELLITES_SAFE did), which is not the same as nothing having been on
        before = saved.pop("before_safe", None)
        theme = saved.pop("before_safe_theme", None)
        back_items = []
        for sid in before or []:
            name = sid
            try:
                item = find(sid, saved)
                name = item["name"]
                if item["index_removed"]:
                    raise Problem("taken off the list")
                unchanged(item)
                policy_check(item)
            except Problem:
                kept.append(name)
                continue
            saved["satellites"].setdefault(sid, {}).update(enabled=True, reason="", failures=[])
            log(sid, "Turned back on when safe mode was left.")
            back.append(item["name"])
            back_items.append(item)
    sentence = ("Safe mode is off. It didn't save which add-ons were on before it, so turn on the ones you want again."
                if before is None else
                "Safe mode is off; " + (f"turned back on {', '.join(back)}." if back else "no add-on was on before it."))
    if kept:
        sentence += f" Still off because its files changed or it was removed: {', '.join(kept)}."
    # the theme in use then comes back with its satellite (after the state is saved: the theme engine reads it),
    # unless the person chose another one than the default safe mode put in its place (starchaser theme's DEFAULT_THEME)
    owner = next((i for i in back_items if isinstance(theme, dict) and theme.get("id") in theme_ids([i])), None)
    try:
        now = json.loads(THEME_STATE.read_text()).get("id")
    except (OSError, ValueError, AttributeError):
        now = None
    if owner and now in (None, "starchaser-cockpit", theme["id"]):
        try:
            r = subprocess.run([str(Path(__file__).resolve().with_name("starchaser-theme")), "apply", str(theme["id"]),
                                "light" if theme.get("variant") == "light" else "dark"],
                               stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=120)
            ok = r.returncode == 0
        except (OSError, subprocess.SubprocessError):
            ok = False
        if not ok:
            sentence += f" {owner['name']}'s theme wasn't put back; choose it again in Appearance."
    print(sentence)


# Copy one to change it (clone), and run a folder live (dev). Like a copy of a built-in plugin in other Hyprland
# desktops, but every safety step still applies: dev shows what the folder adds and asks for and waits for a yes the
# first time (and again whenever it asks for more), each save is checked like an install (files, manifest, the
# pointer rule) before it replaces the running copy, and safe mode or three stops in a minute still turn it off.
DEV_SOURCE = "Your folder (live)"
DEV_POLL = 0.5
DEV_SETTLE = 0.3
TAKEN = "An add-on with that id is already here. Change the id in satellite.toml, or use starchaser satellite clone."
WALL_SET_RE = re.compile(r"-(?:(?:dark|light)-)?\d+x\d+(?:-p\d{1,4})?\.(?:png|jpe?g|webp)\Z", re.I)


class DevStop(Problem):
    """Stops watching a folder (a save that asks for more, a no, a new id): every other problem waits for a fix."""


def satellite_home():
    """Where add-ons people make or copy go: ~/Satellites (STARCHASER_SATELLITE_HOME for tests)."""
    return Path(os.environ.get("STARCHASER_SATELLITE_HOME") or Path.home() / "Satellites")


def clone_id(words):
    """An add-on id from a name as typed ("My Look" -> "my-look"), or ""."""
    return re.sub(r"[^a-z0-9]+", "-", words.lower()).strip("-")[:80].strip("-")


def clone_source(sid, saved):
    """(folder, manifest) of the satellite to copy: one in the list, or an included one the list hides (the developer
    samples while developer mode is off, or one that was removed)."""
    data = catalog(saved)
    item = next((i for i in data["satellites"] if i["id"] == sid), None)
    # the kill switch: what the list took off is never copied under a new id, where the list couldn't reach it
    if (item or {}).get("index_removed") or saved["satellites"].get(sid, {}).get("index_removed"):
        raise Problem(f"{(item or {}).get('name') or sid} was taken off the add-on list, so it can't be copied.")
    if item:
        return Path(item["path"]), item
    error = next((e for e in data["errors"] if e["id"] == sid), None)
    if error:
        raise Problem(error["reason"])
    for base in INCLUDED:
        folder = base / sid
        if folder.is_dir() and not folder.is_symlink():
            check_tree(folder)
            m = manifest(folder)
            if m["id"] == sid:
                return folder, m
    raise Problem(f'No add-on is called “{sid}”. Find one with: starchaser satellite search <words>')


def taken_ids(saved):
    """Every id an included or installed add-on uses here, listed or not."""
    data = catalog(saved)
    ids = {i["id"] for i in data["satellites"]} | {e["id"] for e in data["errors"]} | {h["id"] for h in data["hidden"]}
    ids |= {sid for sid, record in saved["satellites"].items() if record.get("source_url")}
    for base in [INSTALLED, *INCLUDED]:
        with contextlib.suppress(OSError):
            ids |= {p.name for p in base.iterdir()} if base.is_dir() else set()
    return ids


def toml_string(value):
    return json.dumps(value, ensure_ascii=False)


def set_top_keys(path, values):
    """Change top-level `key = value` lines (before the first [table]) and keep every other line, comments included."""
    lines = path.read_text().split("\n")
    done = set()
    for n, line in enumerate(lines):
        if re.match(r"\s*\[", line):
            break
        for key, value in values.items():
            found = re.match(rf'(\s*{re.escape(key)}\s*=\s*)("(?:[^"\\\n]|\\.)*"|\'[^\'\n]*\'|[^#\s]+)(.*)\Z', line)
            if found and key not in done:
                lines[n] = found.group(1) + toml_string(value) + found.group(3)
                done.add(key)
    path.write_text("\n".join(lines))
    return done


def rename_themes(copy, m, old, new, name):
    """A copied theme gets its own theme ids and wallpaper sets, so it never hides the original in Appearance."""
    if "theme" not in m["kinds"]:
        return
    folder = copy / m["entry"].get("theme", "theme")
    if not folder.resolve().is_relative_to(copy.resolve()) or not folder.is_dir():
        return
    sets = {}
    for path in sorted(folder.glob("*.toml")):
        stem = path.stem
        fresh = new if stem == old else new + stem[len(old):] if stem.startswith(old + "-") else f"{new}-{stem}"
        try:
            theme = tomllib.loads(path.read_text())
        except (OSError, UnicodeError, tomllib.TOMLDecodeError):
            raise Problem(f"{path.name} couldn't be read, so no copy was made.") from None
        values = {"name": name if stem == old else f"{theme.get('name', stem)} ({name})".strip()}
        wallpaper = theme.get("wallpaper")
        if isinstance(wallpaper, str) and wallpaper in {old, stem}:
            sets[wallpaper] = new if wallpaper == old else fresh
            values["wallpaper"] = sets[wallpaper]
        set_top_keys(path, values)
        path.rename(folder / f"{fresh}.toml")
    for walls in dict.fromkeys((folder / "wallpapers", copy / "wallpapers")):
        if not walls.is_dir() or walls.is_symlink():
            continue
        for path in sorted(walls.iterdir()):
            for before, after in sets.items():
                    rest = path.name[len(before):]
                    if path.name.startswith(before) and WALL_SET_RE.fullmatch(rest):
                        path.rename(walls / (after + rest))
                        break


# The taskbar's own parts that can be copied as a taskbar item (clone builtin:<part>). Each folder in
# data/satellite-builtins/ is that part rewritten on the SDK alone: a satellite publishes a label and a hover label
# into a slot of its own, so the copy shows beside the part, never in its place (a satellite can't replace the
# taskbar or a part of it: safe mode, the kill switch and the way out stay the taskbar's own).
BUILTIN_PREFIX = "builtin:"
BUILTIN_DIR = Path(__file__).resolve().parent.parent / "data/satellite-builtins"
BUILTIN_PARTS = {
    "clock": "The clock: the time in your 12- or 24-hour clock, the date beside it when you want it.",
    "battery": "The battery: the charge, and whether it is charging (computers with a battery).",
    "network": "The network icon: wired, Wi-Fi and its signal, or offline.",
    "sound": "The speaker: the volume, with buttons to change it or mute.",
}
# the parts that stay the taskbar's own, and why (docs/satellites.md lists the same)
BUILTIN_KEPT = {
    "menu": "The menu button is the way into the Super menu and its search, which stay the desktop's own.",
    "desktops": "The desktops and their windows come from the compositor, which an add-on can't read through the SDK.",
    "apps": "The running and kept apps come from the compositor and the app list, which an add-on can't read through the SDK.",
    "tray": "Tray icons belong to one tray per sign-in, which is the taskbar's.",
    "notifications": "Notifications have one keeper per sign-in, which is the taskbar's; an add-on can send them, not hold them.",
    "quick-settings": "Quick settings changes the computer's settings, which stay the desktop's own.",
    "privacy": "The privacy lights say when the microphone, camera or screen is in use; an add-on must never stand in for them.",
    "public-pause": "The firewall's Public pause light is a safety sign that stays the taskbar's own.",
    "power": "The power button opens the power confirmation, which an add-on must never imitate.",
}


def builtin_source(sid):
    """(folder, manifest) of a taskbar part to copy, for clone builtin:<part>."""
    part = sid[len(BUILTIN_PREFIX):]
    if part in BUILTIN_KEPT:
        raise Problem(f"That part stays the taskbar's own, so it can't be copied: {BUILTIN_KEPT[part]}")
    folder = BUILTIN_DIR / part
    if part not in BUILTIN_PARTS or not (folder / "satellite.toml").is_file():
        raise Problem("That taskbar part can't be copied. Choose one of: "
                      + ", ".join(BUILTIN_PREFIX + p for p in BUILTIN_PARTS) + ".")
    check_tree(folder)
    return folder, manifest(folder)


def builtins_list(as_json=False):
    """builtins: the taskbar parts clone builtin:<part> copies, and the ones that stay the taskbar's own."""
    parts = [{"part": p, "id": BUILTIN_PREFIX + p, "about": about} for p, about in BUILTIN_PARTS.items()
             if (BUILTIN_DIR / p / "satellite.toml").is_file()]
    if as_json:
        print(json.dumps({"parts": parts, "kept": [{"part": p, "why": why} for p, why in BUILTIN_KEPT.items()]}))
        return
    print("Taskbar parts you can copy (each copy shows beside the part, never in its place):")
    for x in parts:
        print(f"  {x['id']:<18} {x['about']}")
    print('Copy one with: starchaser satellite clone builtin:clock "My Clock"')
    print("\nParts that stay the taskbar's own:")
    for p, why in BUILTIN_KEPT.items():
        print(f"  {p:<18} {why}")


def clone_satellite(sid, new_name=None, parent=None, as_json=False):
    builtin = sid.startswith(BUILTIN_PREFIX)
    if not ID_RE.fullmatch(sid[len(BUILTIN_PREFIX):] if builtin else sid) or len(sid) > 80:
        raise Problem("Use an add-on id with lowercase letters, digits, and dashes."
                      + (" A part of the taskbar is builtin:<part> (see: starchaser satellite builtins)." if builtin else ""))
    saved = state()
    source, m = builtin_source(sid) if builtin else clone_source(sid, saved)
    check_tree(source)
    old = m["id"]
    parent = Path(parent).expanduser() if parent else satellite_home()
    taken = taken_ids(saved)
    if new_name is not None:
        name = new_name.strip()
        if not name or len(name) > 500 or any(ord(c) < 32 for c in name):
            raise Problem("Give the copy a one-line name.")
        nid = clone_id(name)
        if not nid or not ID_RE.fullmatch(nid):
            raise Problem("Give the copy a name with letters or digits in it.")
        if nid == old or nid in taken:
            raise Problem("An add-on with that id is already here. Choose another name.")
        if (parent / nid).exists():
            raise Problem(f"{parent / nid} already exists. Choose another name, or another folder with --dir.")
    else:
        name = "My " + m["name"]
        stem = clone_id("my-" + old)
        nid, count = stem, 1
        while nid == old or nid in taken or (parent / nid).exists():
            count += 1
            suffix = f"-{count}"
            nid = stem[:80 - len(suffix)].rstrip("-") + suffix
    target = parent / nid
    parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=f".{nid}-", dir=parent) as work:
        copy = Path(work) / nid
        # internal file links become plain files (as install copies a folder); .git stays with the original
        shutil.copytree(source, copy, ignore=shutil.ignore_patterns(".git"))
        for path in [copy, *copy.rglob("*")]:
            path.chmod(path.stat().st_mode | stat.S_IWUSR)      # what comes with Starchaser can be read-only
        done = set_top_keys(copy / "satellite.toml", {"id": nid, "name": name, "version": "0.1.0"})
        try:
            after = manifest(copy)
        except Problem as ex:
            raise Problem(f"{ex} No copy was made.") from None
        if done != {"id", "name", "version"} or after["id"] != nid or after["name"] != name:
            raise Problem("The id and name in its satellite.toml couldn't be changed, so no copy was made.")
        rename_themes(copy, after, old, nid, name)
        check_tree(copy)
        moves = pointer_problem(copy)
        if moves:
            raise Problem(moves + " No copy was made.")
        if target.exists():
            raise Problem(f"{target} already exists. Choose another name, or another folder with --dir.")
        os.rename(copy, target)
    command = f"starchaser satellite dev {shlex.quote(str(target))}"
    if as_json:
        print(json.dumps({"ok": True, "id": nid, "name": name, "path": str(target), "from": sid, "next": command}))
    else:
        print(f"Made a copy of {m['name']} called {name} in {target}. Try it with: {command}")
    return target


def open_in_editor(folder):
    """clone --edit and new --edit: the new folder in $VISUAL or $EDITOR (in this terminal when there is one, else in
    a terminal window of its own), else in a code editor that opens folders, else satellite.toml in the default text
    editor. Returns one sentence, which never names the program (it could carry another desktop's name)."""
    folder = Path(folder)
    editor = (os.environ.get("VISUAL") or os.environ.get("EDITOR") or "").strip()
    quiet = {"stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL, "start_new_session": True}
    try:
        if editor:
            argv = shlex.split(editor) + [str(folder)]
            desktop = os.environ.get("WAYLAND_DISPLAY") or os.environ.get("DISPLAY")
            if (sys.stdin.isatty() and sys.stdout.isatty()) or not desktop:
                subprocess.call(argv, cwd=folder)              # this terminal (or a script): wait for it to close
            else:                                              # Settings or a menu row: a terminal window of its own
                subprocess.Popen(["starchaser", "terminal", "--class", "menu-run", "--directory", str(folder), "-e", *argv],
                                 cwd=folder, **quiet)
            return "Opened it in your editor."
        for program in ("zeditor", "lite-xl"):
            if shutil.which(program):
                subprocess.Popen([program, str(folder)], cwd=folder, **quiet)
                return "Opened it in the code editor."
        subprocess.Popen(["xdg-open", str(folder / "satellite.toml")], cwd=folder, **quiet)
        return "Opened its satellite.toml in the default text editor."
    except (OSError, ValueError):
        return f"It couldn't be opened in an editor. Open {folder} yourself."


def edit_next(folder, as_json):
    """--edit: open the folder, then say what to run next (to stderr with --json, whose last stdout line is the answer)."""
    sentence = open_in_editor(folder)
    print(f"{sentence} Next, try it live with: starchaser satellite dev {shlex.quote(str(folder))}",
          file=sys.stderr if as_json else sys.stdout)


def folder_stamp(folder):
    """What every file in the folder looks like now (path, size, change time, mode), .git left out: a save changes it."""
    root = Path(folder)
    seen = []
    for base, dirs, files in os.walk(root, followlinks=False):
        dirs[:] = sorted(d for d in dirs if d != ".git")
        for name in sorted(files) + dirs:
            path = Path(base) / name
            with contextlib.suppress(OSError):
                info = path.lstat()
                seen.append((str(path.relative_to(root)), info.st_size, info.st_mtime_ns, info.st_mode))
    return tuple(sorted(seen))


def asks_more(m, record):
    """The permissions and kinds this folder asks for that were not agreed to yet."""
    granted = record.get("granted_permissions") or {}
    more = {}
    for key, value in m["permissions"].items():
        old = granted.get(key)
        if isinstance(value, list):
            fresh = [v for v in value if v not in (old if isinstance(old, list) else [])]
            if fresh:
                more[key] = fresh
        elif value is True and old is not True:
            more[key] = True
    for capability in ("providers", "secrets"):
        fresh = [v for v in m.get(capability, []) if v not in record.get("granted_" + capability, [])]
        if fresh:
            more[capability] = fresh
    if m.get("sandbox") == "full-access" and record.get("granted_sandbox") == "restricted":
        more["full_access"] = True
    kinds = [k for k in m["kinds"] if k not in record.get("granted_kinds", [])]
    return more, kinds


def dev_prompt(folder, m, first, more=None, kinds=None):
    item = details({**m, "path": str(folder), "source": DEV_SOURCE, "commit": ""})
    lines = [f"{m['name']} {m['version']}: {m['summary']}", item["adds"], item["asks"]]
    if not first:
        labels = {"network": "Connects to", "run": "Runs", "read": "Reads", "write": "Writes"}
        new = [labels[k] + " " + ", ".join(v) + "." for k, v in (more or {}).items() if k in labels]
        new += [{"notify": "Shows notifications.", "location": "Uses your location.", "media": "Controls playback.", "search": "Reads menu searches.", "selected_file": "Reads the selected file.", "providers": "Reads additional typed data.", "secrets": "Uses additional saved sign-ins.", "full_access": "Now requests full access."}.get(k, "Requests additional access.") for k in (more or {}) if k not in labels]
        if kinds:
            new.append("Adds " + adds_text(kinds)[0].lower() + adds_text(kinds)[1:])
        lines.append("New since you said yes: " + " ".join(new))
    if item["hook_text"]:
        lines.append(item["hook_text"])
    own_folder = folder.resolve().is_relative_to(AUTHOR_DIR.resolve())
    lines.append("It runs from your folder, so Starchaser has not reviewed it.")
    if not own_folder and ships_code(m, folder):
        lines.append(outside_warning(m) if m.get("sandbox") == "restricted" else CODE_WARNING)
    lines.append(f"Turn it on from {folder}? Starchaser copies it again each time you save." if first
                 else "It asks for more than before. Keep it on with these?")
    width = max(30, shutil.get_terminal_size((80, 24)).columns - 1)
    return "\n".join(textwrap.fill(line, width=width, break_long_words=False, break_on_hyphens=False) for line in lines)


def dev_record(sid, folder):
    """This folder's record, or None when it is new here; refuses an id that something else uses."""
    if any((base / sid).exists() for base in INCLUDED):
        raise Problem(TAKEN)
    record = state()["satellites"].get(sid)
    if record and record.get("dev_path") == str(folder):
        return record
    if (INSTALLED / sid).exists() or (record and record.get("source_url")):
        raise Problem(TAKEN)
    return None


def dev_sync(folder, m, sid, grant=None):
    """Copy the folder in, checked like an install, and swap it with the running copy in one step. sid: the id dev
    started with (a save that changes it is refused, never added as a second satellite). grant: what the person
    just agreed to ({"granted_permissions", "granted_kinds"}), for the first copy or one that asks for more."""
    INSTALLED.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".dev-", dir=INSTALLED) as work:
        stage = Path(work) / "satellite"
        check_tree(folder)
        shutil.copytree(folder, stage, ignore=shutil.ignore_patterns(".git"))
        check_tree(stage)
        after = manifest(stage)
        if after["id"] != sid:
            raise DevStop("Its id in satellite.toml changed. Run starchaser satellite dev again to add it under the new id.")
        moves = pointer_problem(stage)
        if moves:
            raise Problem(moves + " It wasn't reloaded.")
        live = INSTALLED / sid
        keep = INSTALLED / f".old-{sid}-{os.getpid()}"
        moved = {"old": False, "new": False}

        def rollback():
            if moved["new"]:
                os.rename(live, stage)
            if moved["old"]:
                os.rename(keep, live)

        with locked_state(rollback) as saved:
            record = saved["satellites"].get(sid)
            if any((base / sid).exists() for base in INCLUDED) or (
                    (live.exists() or (record or {}).get("source_url")) and (record or {}).get("dev_path") != str(folder)):
                raise Problem(TAKEN)
            if not grant and (record is None or not record.get("enabled")):
                raise DevStop((record or {}).get("reason") or f"{after['name']} is off now.")
            # a save between the check and the copy may not add to what was agreed to
            more, kinds = asks_more(after, grant if grant else record)
            if more or kinds:
                raise Problem("It asks for more than you agreed to.")
            if live.exists():
                os.rename(live, keep)
                moved["old"] = True
            os.rename(stage, live)
            moved["new"] = True
            record = saved["satellites"].setdefault(sid, {})
            if grant:
                record.update(enabled=record.get("enabled", False), source=DEV_SOURCE, source_url="Local folder",
                              dev_path=str(folder), commit="", granted_permissions=after["permissions"],
                              granted_kinds=after["kinds"], failures=record.get("failures", []))
            else:
                # what it asks for now never grows here (that needs a yes first); what it dropped is dropped
                record["granted_permissions"] = after["permissions"]
                record["granted_kinds"] = after["kinds"]
            record["reload"] = str(time.time_ns())
        shutil.rmtree(keep, ignore_errors=True)
    theme_gone(theme_ids([{"kinds": after["kinds"], "entry": after["entry"], "path": str(INSTALLED / sid)}]))
    return after


def dev_state(sid):
    """"" while it stays on, else the one sentence that says why it is off now."""
    saved = state()
    record = saved["satellites"].get(sid)
    if record is None:
        return "It was removed, so Starchaser stopped watching your folder."
    if safe_on(saved):
        return "Safe mode is on, so it is off. Starchaser stopped watching your folder."
    if not record.get("enabled"):
        return (record.get("reason") or "It was turned off.") + " Starchaser stopped watching your folder."
    return ""


def dev_preview(item):
    """Show a successful reload without toggling an existing panel closed."""
    sid, kinds = item["id"], item["kinds"]
    if "panel" in kinds or "overlay" in kinds:
        mode = "panel" if "panel" in kinds else "overlay"
        # The old keeper notices the reload stamp and closes its old QML first.
        deadline = time.monotonic() + 3
        while panel_keeper(sid, mode):
            if time.monotonic() >= deadline:
                return
            time.sleep(0.05)
        open_panel(sid, mode, ensure=True)
    elif "bar-widget" in kinds:
        # The fresh widget must have published before it can receive a click.
        subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "dev-click", sid],
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)


def dev_click(sid):
    deadline = time.monotonic() + 8
    while time.monotonic() < deadline:
        try:
            item = enabled_item(sid)
            if jread_dict(RUN / sid / "slot.json").get("reload") == item.get("reload", ""):
                click(sid)
                return
        except Problem:
            pass
        time.sleep(0.1)


def dev_run(path, yes=False, once=False, seconds=None):
    folder = Path(path).expanduser().resolve()
    deadline = None if seconds is None else time.monotonic() + seconds
    stamp = folder_stamp(folder)

    def next_save():
        """Wait for a save (and a moment for it to settle); False when the time given with --for is up."""
        nonlocal stamp
        while deadline is None or time.monotonic() < deadline:
            time.sleep(DEV_POLL)
            if folder_stamp(folder) != stamp:
                time.sleep(DEV_SETTLE)
                stamp = folder_stamp(folder)
                return True
        return False

    m, problems = check_folder(folder)       # a folder that isn't a satellite, or a manifest it can't read, stops here
    sid = m["id"]
    record = dev_record(sid, folder)
    try:
        while problems:
            print("\n".join(problems), file=sys.stderr)
            if once:
                raise Problem("Fix these first, then run starchaser satellite dev again.")
            print("Waiting for a save that fixes this.", file=sys.stderr)
            if not next_save():
                return 1
            m, problems = check_folder(folder)
            if m["id"] != sid:
                raise DevStop("Its id in satellite.toml changed. Run starchaser satellite dev again.")
        more, kinds = asks_more(m, record or {})
        if record is None or more or kinds:
            confirm(dev_prompt(folder, m, record is None, more, kinds), yes)
        if record is None or more or kinds or not record.get("enabled"):
            dev_sync(folder, m, sid, grant={"granted_permissions": m["permissions"], "granted_kinds": m["kinds"], "granted_providers": m.get("providers", []), "granted_secrets": m.get("secrets", []), "granted_sandbox": m.get("sandbox")})
            change(sid, "enable", yes=True)
        else:
            dev_sync(folder, m, sid)
            print(f"Reloaded {m['name']} at {clock()}.", flush=True)
    except KeyboardInterrupt:
        raise Problem("The add-on change was canceled.") from None
    dev_preview(m)
    if once:
        return 0
    name = m["name"]
    print("Save a file to reload it; press Ctrl+C to stop.", flush=True)
    stamp = folder_stamp(folder)
    try:
        while deadline is None or time.monotonic() < deadline:
            time.sleep(DEV_POLL)
            why = dev_state(sid)
            if why:
                print(f"{name}: {why}", file=sys.stderr)
                return 0
            if folder_stamp(folder) == stamp:
                continue
            time.sleep(DEV_SETTLE)
            stamp = folder_stamp(folder)
            try:
                m, problems = check_folder(folder)
                if m["id"] != sid:
                    raise DevStop("Its id in satellite.toml changed. Run starchaser satellite dev again to add it under the new id.")
                if problems:
                    raise Problem("\n".join(problems))
                more, kinds = asks_more(m, state()["satellites"].get(sid, {}))
                if more or kinds:
                    if not yes and not sys.stdin.isatty():
                        raise DevStop("It asks for more now; run starchaser satellite dev again to review it.")
                    try:
                        confirm(dev_prompt(folder, m, False, more, kinds), yes)
                    except Problem as ex:
                        raise DevStop(str(ex)) from None
                    m = dev_sync(folder, m, sid, grant={"granted_permissions": m["permissions"], "granted_kinds": m["kinds"], "granted_providers": m.get("providers", []), "granted_secrets": m.get("secrets", []), "granted_sandbox": m.get("sandbox")})
                else:
                    m = dev_sync(folder, m, sid)
            except DevStop:
                raise
            except Problem as ex:
                print(f"{ex}\nWaiting for a save that fixes it.", file=sys.stderr)
                continue
            dev_preview(m)
            name = m["name"]
            print(f"Reloaded {name} at {clock()}.", flush=True)
    except KeyboardInterrupt:
        print(flush=True)
    if not dev_state(sid):
        print(f"{name} stays on. Turn it off with: starchaser satellite disable {sid}", flush=True)
    return 0


def clock():
    return time.strftime("%I:%M %p").lstrip("0")


def run_card(sid, file_id):
    card = next((c for c in cards() if c["satellite_id"] == sid and c["file_id"] == file_id), None)
    if not card:
        raise Problem("That Today card is off or couldn't be read.")
    item = enabled_item(sid)
    command, env = execution(item, card["command"], satellite_env(sid))
    activity_note(item, "Today card")
    proc = subprocess.Popen(command, cwd=card["cwd"], env=env, stdout=subprocess.PIPE,
                            stderr=subprocess.DEVNULL, start_new_session=True)

    def stop(*_args):
        with contextlib.suppress(ProcessLookupError):
            os.killpg(proc.pid, signal.SIGKILL)

    old_handler = signal.signal(signal.SIGTERM, lambda *_args: (stop(), sys.exit(1)))
    output = bytearray()
    try:
        with selectors.DefaultSelector() as selector:
            selector.register(proc.stdout, selectors.EVENT_READ)
            deadline = time.monotonic() + 10
            while selector.get_map() or proc.poll() is None:
                saved = state()
                if safe_on(saved) or not saved["satellites"].get(sid, {}).get("enabled", False):
                    raise Problem("That Today card is off.")
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    raise Problem("The Today card took too long.")
                for key, _event in selector.select(min(remaining, 0.25)):
                    chunk = os.read(key.fileobj.fileno(), 4097)
                    if not chunk:
                        selector.unregister(key.fileobj)
                    output.extend(chunk)
                    if len(output) > 4096:
                        raise Problem("The Today card returned too much text.")
            if proc.wait(timeout=max(0.01, deadline - time.monotonic())) != 0:
                raise Problem("The Today card command stopped.")
        lines = output.decode().strip().splitlines()
        if len(lines) != 1 or not isinstance(json.loads(lines[0]), dict):
            raise Problem("The Today card needs one line of JSON.")
        print(lines[0])
    except (ValueError, UnicodeError, subprocess.TimeoutExpired):
        raise Problem("The Today card needs one line of JSON.") from None
    finally:
        stop()
        proc.wait()
        proc.stdout.close()
        signal.signal(signal.SIGTERM, old_handler)


def bar_items():
    """The taskbar items to run now: enabled bar-widget add-ons with their Widget.qml (none in safe mode)."""
    found = []
    for item in enabled("bar-widget"):
        try:
            entry = widget_entry(item)
        except (OSError, Problem):
            continue
        if entry is not None:
            found.append({**item, "entry": str(entry),
                          "commit": item.get("commit", ""), "reload": item.get("reload", ""), **item["place"]})
    order = state().get("bar_order", [])
    rank = {sid: i for i, sid in enumerate(order)}
    return sorted(found, key=lambda item: (rank.get(item["id"], len(rank)), item["name"].casefold()))


def order_bar_items(ids):
    available = {i["id"] for i in enabled("bar-widget")}
    if len(ids) != len(set(ids)) or any(sid not in available for sid in ids):
        raise Problem("Only taskbar add-ons that are on can be reordered.")
    with locked_state() as saved:
        saved["bar_order"] = ids + [sid for sid in saved.get("bar_order", []) if sid not in ids and sid in available]
    print("Taskbar add-ons reordered.")


def click(sid):
    """A keyboard activation uses its own file, so pointer events cannot overwrite or replay it."""
    item = find(sid)
    if not item["enabled"] or "bar-widget" not in item["kinds"]:
        raise Problem("That taskbar add-on is off.")
    published = jread_dict(RUN / sid / "slot.json")
    alive = published.get("alive")
    if not isinstance(alive, (int, float)) or not 0 <= time.time() * 1000 - alive < 8000:
        raise Problem("That taskbar add-on isn't answering. Try turning it off and on in Settings > Satellites.")
    path = RUN / sid / "keyboard.json"
    with locked_state() as saved:
        if safe_on(saved) or not saved["satellites"].get(sid, {}).get("enabled"):
            raise Problem("That taskbar add-on is off.")
        stamp = max(time.time_ns() // 1_000_000, int(jread_dict(path).get("t", 0)) + 1)
        atomic_json(path, {"t": stamp, "clickAt": stamp, "kind": "click"})


def service_entry(item):
    """A background service's program (bin/service unless the manifest names another), or None."""
    if "service" not in item["kinds"]:
        return None
    path = entry_path(item, "service", "bin/service")
    return path if path.is_file() else None


def overlay_entry(item):
    """An overlay's QML file (Overlay.qml unless the manifest names another), or None."""
    if "overlay" not in item["kinds"]:
        return None
    path = entry_path(item, "overlay", "Overlay.qml")
    return path if path.suffix == ".qml" and path.is_file() else None


def panel_entry(item):
    """A panel's QML file (Panel.qml unless the manifest names another), or None."""
    if "panel" not in item["kinds"]:
        return None
    path = entry_path(item, "panel", "Panel.qml")
    return path if path.suffix == ".qml" and path.is_file() else None


def service_problems(item):
    """What stops a background service's program from starting: missing, not a plain file, not executable, or a
    shell script that can't be read (parsed with the shell's own -n check; nothing runs)."""
    name = item["entry"].get("service", "bin/service")
    path = entry_path(item, "service", "bin/service")
    if not path.exists():
        return [f"Add the background service: {name}, a program that keeps running."]
    if not path.is_file():
        return [f"{name} must be a program file, not a folder."]
    if not os.access(path, os.X_OK):
        return [f"{name} must be executable (chmod +x)."]
    return [sentence.replace(f"hooks/{path.name} ", f"{name} ", 1) for sentence in hook_problems(path)]


def service_items():
    """The background services to run now: enabled service add-ons with their program (none in safe mode)."""
    found = []
    for item in enabled("service"):
        try:
            entry = service_entry(item)
        except (OSError, Problem):
            continue
        if entry is not None:
            found.append({**item, "entry": str(entry),
                          "commit": item.get("commit", ""), "reload": item.get("reload", "")})
    return found
def ServiceChild(item):
    return satellite_host.ServiceChild(EngineContext(), item)




def qs_program():
    return os.environ.get("STARCHASER_SATELLITE_QS") or shutil.which("qs") or shutil.which("quickshell")


def code_env(item, entry, mode):
    """What a satellite's own Quickshell process is given: the usual satellite variables, the SDK on the import path,
    and which file to load."""
    sid = item["id"]
    run = RUN / sid
    run.mkdir(parents=True, exist_ok=True, mode=0o700)
    imports = [str(SDK_DIR)] + [p for p in os.environ.get("QML_IMPORT_PATH", "").split(":") if p]
    return satellite_env(sid, {"STARCHASER_SATELLITE_NAME": item["name"], "STARCHASER_SATELLITE_DIR": item["path"],
                               "STARCHASER_SATELLITE_ENTRY": str(entry), "STARCHASER_SATELLITE_RUN": str(run),
                               "STARCHASER_SATELLITE_MODE": mode, "QML_IMPORT_PATH": ":".join(imports),
                               # how its QML runs this tool (Satellite.openPanel())
                               "STARCHASER_SATELLITE_TOOL": str(Path(__file__).resolve())})


def start_satellite_process(item, mode, command, env):
    """Serialize starting and publishing a child with Remove's durable off state."""
    sid, proc = item["id"], None
    pidfile = RUN / sid / f"{mode}.pid"
    try:
        with locked_state() as saved:
            current = find(sid, saved)
            if (not current["enabled"] or current["commit"] != item.get("commit", "")
                    or current.get("reload", "") != item.get("reload", "")):
                raise Problem("The add-on is off or its files changed, so it wasn't started.")
            policy_check(current)
            command, env = execution(current, command, env)
            activity_note(current, mode)
            proc = subprocess.Popen(command, cwd=item["path"], env=env, stdin=subprocess.DEVNULL,
                                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True,
                                    preexec_fn=die_with_parent())
            if mode == "service":
                # exec preserves this identity even when the worker changes its program or clears its environment.
                started = process_start(proc.pid)
                if not started:
                    raise Problem("The background service couldn't be tracked, so it wasn't started.")
                atomic_json(RUN / sid / "service-process.json",
                            {"pid": proc.pid, "start": started, "id": sid, "mode": mode})
            atomic_text(pidfile, f"{proc.pid}\n")
            if mode in ("page", "panel", "overlay"):
                atomic_text(RUN / sid / f"{mode}-host.pid", f"{os.getpid()}\n")
    except BaseException:
        if proc is not None:
            stop_group(proc.pid, proc)
            proc.stdout.close()
            pidfile.unlink(missing_ok=True)
            if mode == "service":
                (RUN / sid / "service-process.json").unlink(missing_ok=True)
        raise
    return proc


ANSI = re.compile(r"\x1b\[[0-9;]*m")
# the graphics driver's own warnings (in a VM, on many NVIDIA computers), not the satellite's: kept out of its log, where
# they made a working one look broken (QA 2026-11-05: "MESA-EGL: warning: egl: failed to create dri2 screen")
DRIVER_NOISE = ("MESA", "libEGL warning", "libGL error", "libGL warning")
# Qt's own words when the desktop closes under a satellite ("The Wayland connection broke. Did the Wayland compositor
# die?"): a log out read as a crash. The log says it plainly instead (LOGGED_OUT). QA u842.
SESSION_NOISE = ("The Wayland connection broke",)
LOGGED_OUT = "The taskbar item stopped because you logged out."
# What a satellite may publish for its taskbar slot: anything bigger is a mistake, and the taskbar never reads it.
PUBLISH_BYTES = 4096


def die_with_parent():
    """What a satellite's process runs just before it starts: it then ends when the host that started it ends, even a
    host that was killed outright (so a new host never finds a second copy running). Prepared here, in the host."""
    try:
        import ctypes
        prctl = ctypes.CDLL(None, use_errno=True).prctl
    except (ImportError, OSError, AttributeError):
        return None
    return lambda: prctl(1, signal.SIGTERM)       # PR_SET_PDEATHSIG


def process_start(pid):
    """Kernel start time, unchanged by exec; together with the pid it distinguishes a child from a reused pid."""
    try:
        return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[19]
    except (OSError, IndexError):
        return ""


def ours(pid, sid, mode):
    """Only a verified child leading its own process group may be stopped through a saved pid file."""
    try:
        identity = RUN / sid / "service-process.json"
        if mode == "service" and identity.exists():
            record = jread_dict(identity)
            return (record.get("pid") == pid and record.get("id") == sid and record.get("mode") == mode
                    and bool(record.get("start")) and record["start"] == process_start(pid) and os.getpgid(pid) == pid)
        cmdline = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
        environ = Path(f"/proc/{pid}/environ").read_bytes().split(b"\0")
        program = str(HOST_SHELL).encode()
        if mode == "service":
            # Older hosts did not save a start time. Keep their original launcher verification for compatibility.
            entry = next((v[len(b"STARCHASER_SATELLITE_ENTRY="):] for v in environ if v.startswith(b"STARCHASER_SATELLITE_ENTRY=")), b"")
            program = entry if entry and entry in cmdline[:2] else b"\0"
        return (program in cmdline and f"STARCHASER_SATELLITE_ID={sid}".encode() in environ
                and f"STARCHASER_SATELLITE_MODE={mode}".encode() in environ and os.getpgid(pid) == pid)
    except (OSError, ValueError):
        return False


def stop_group(pid, wait=None):
    """End an add-on's process group: ask, then make sure. `wait` is its Popen, when we started it."""
    with contextlib.suppress(ProcessLookupError, PermissionError):
        os.killpg(pid, signal.SIGTERM)
    if wait is not None:
        try:
            wait.wait(timeout=2)
        except subprocess.TimeoutExpired:
            pass
    with contextlib.suppress(ProcessLookupError, PermissionError):
        os.killpg(pid, signal.SIGKILL)
    if wait is not None:
        wait.wait()


def leftovers(mode):
    """Taskbar items (or settings windows) left by a host that ended without cleaning up: stopped before anything new
    starts, but only after checking each really is one of ours."""
    for pidfile in RUN.glob(f"*/{mode}.pid"):
        with contextlib.suppress(OSError, ValueError):
            pid = int(pidfile.read_text().strip())
            if ours(pid, pidfile.parent.name, mode):
                stop_group(pid)
        with contextlib.suppress(OSError):
            pidfile.unlink(missing_ok=True)
            if mode == "service":
                (pidfile.parent / "service-process.json").unlink(missing_ok=True)


def switch_off(sid, sentence):
    with locked_state() as saved:
        saved["satellites"].setdefault(sid, {}).update(enabled=False, reason=sentence)
    log(sid, sentence)


def display_gone():
    """The desktop this host serves has closed (its Wayland socket is gone): time to stop everything."""
    name = os.environ.get("WAYLAND_DISPLAY")
    if not name:
        return False
    path = Path(name) if name.startswith("/") else Path(os.environ.get("XDG_RUNTIME_DIR", "/nonexistent")) / name
    return not path.exists()
class EngineContext:
    """The supervisor calls the current engine gates, including after state and policy change."""

    def __getattr__(self, name):
        return globals()[name]


def Output(sid, stream, logfile=None):
    return satellite_host.Output(EngineContext(), sid, stream, logfile)


def Child(item, program):
    return satellite_host.Child(EngineContext(), item, program)




# What the host's log lines call each kind of process it keeps.
RUNNING_WORDS = {"widget": "The taskbar item", "service": "The background service"}
def host(seconds=None):
    return satellite_host.host(EngineContext(), seconds)




def open_page(sid):
    """A satellite's settings page written in QML, in a window of its own Quickshell process (one at a time). A small
    keeper (page-host) starts it and closes it when the satellite is turned off or safe mode is turned on."""
    item = enabled_item(sid)
    if page_entry(item) is not None:
        raise Problem(f"{item['name']} has its settings in Settings > Satellites > {item['name']}.")
    if code_page(item) is None:
        raise Problem("This add-on has no Settings page.")
    if not qs_program():
        raise Problem("This settings page can't open: a part of the desktop is missing (the quickshell package).")
    unchanged(item)
    (RUN / sid).mkdir(parents=True, exist_ok=True, mode=0o700)
    lock = os.open(RUN / sid / "page.lock", os.O_RDWR | os.O_CREAT, 0o600)
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(lock)
        print(f"The {item['name']} settings window is already open.")
        return
    # the keeper holds the lock for as long as the window is open; it outlives Settings
    with open(os.devnull, "rb") as nothing, open(os.devnull, "wb") as quiet:
        subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "page-host", sid, "--lock-fd", str(lock)],
                         stdin=nothing, stdout=quiet, stderr=quiet, start_new_session=True, pass_fds=(lock,))
    os.close(lock)
    log(sid, "Its settings window was opened.")
    print(f"Opened the {item['name']} settings.")


def page_host(sid, lock_fd=None):
    """Keep one satellite's QML settings window, and close it as soon as the satellite is off, safe mode is on, or
    the desktop ends."""
    if lock_fd is None:
        lock = os.open(RUN / sid / "page.lock", os.O_RDWR | os.O_CREAT, 0o600)
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return 0
    item = enabled_item(sid)
    entry = code_page(item)
    program = qs_program()
    if entry is None or not program:
        return 1
    unchanged(item)
    stopping = []
    for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
        signal.signal(sig, lambda *_args: stopping.append(True))
    env = code_env(item, entry, "page")
    LOGS.mkdir(parents=True, exist_ok=True)
    (LOGS / f"{sid}.page.log").write_text("")
    proc = start_satellite_process(item, "page", [program, "-p", str(HOST_SHELL)], env)
    output = Output(sid, proc.stdout, LOGS / f"{sid}.page.log")
    stamp, looked, reason = None, 0.0, ""
    provider_at = 0.0
    try:
        while proc.poll() is None and not stopping and not display_gone():
            output.drain()
            take_request(item)
            now = time.monotonic()
            if now - provider_at > 15:
                provider_at = now
                deliver_providers([item], provider_snapshot(item.get("providers", [])))
            try:
                mark = (STATE.stat().st_mtime_ns if STATE.exists() else 0, MARKER.exists())
            except OSError:
                mark = None
            if mark != stamp or now - looked > 5:
                stamp, looked = mark, now
                try:
                    current = find(sid)
                    if not current["enabled"]:
                        reason = "Its settings window was closed because the add-on is off."
                except Problem:
                    reason = "Its settings window was closed because the add-on was removed."
                except (OSError, ValueError, RecursionError):
                    pass
                if reason:
                    break
            time.sleep(0.25)
    finally:
        stop_group(proc.pid, proc)
        output.drain()
        proc.stdout.close()
        for name in ("page.pid", "page-host.pid"):
            (RUN / sid / name).unlink(missing_ok=True)
    if not reason and display_gone():
        reason = "Its settings window was closed because you logged out."
    if reason:
        log(sid, reason)
    return 0


def panel_keeper(sid, mode="panel"):
    """The verified keeper of one settings page, panel or overlay, or None."""
    try:
        pid = int((RUN / sid / f"{mode}-host.pid").read_text().strip())
    except (OSError, ValueError):
        return None
    return pid if keeper_ours(pid, sid, mode) else None


def keeper_ours(pid, sid, mode):
    """Verify the process itself, including after it removes its PID file during shutdown."""
    try:
        cmdline = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
        verb = b"page-host" if mode == "page" else b"panel-host"
        if cmdline[1:4] != [str(Path(__file__).resolve()).encode(), verb, sid.encode()] or os.getpgid(pid) != pid:
            return False
        if mode != "page":
            actual = cmdline[cmdline.index(b"--mode") + 1] if b"--mode" in cmdline else b"panel"
            if actual != mode.encode():
                return False
    except (OSError, ValueError, IndexError):
        return False
    return True


def open_menu(sid):
    """open-menu: the Super menu straight at this satellite's own menu (its menu.json rows, drawn by the menu with its
    letters, search and spoken names), or closed when it is open there. Only for an enabled menu-page satellite; in
    safe mode nothing opens. Nothing of the satellite's runs here."""
    item = enabled_item(sid)
    if "menu-page" not in item["kinds"]:
        raise Problem(f"{item['name']} has no menu to open.")
    toggle = os.environ.get("STARCHASER_MENU_TOGGLE") or str(HOME / ".config/keybinds/toggle.sh")
    if not Path(toggle).is_file():
        toggle = str(Path(__file__).resolve().parent.parent / "config/keybinds/toggle.sh")
    subprocess.Popen([toggle, menu_page_id(sid)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, start_new_session=True)


# What open-panel opens: a panel (Panel.qml, a box under the taskbar) or an overlay (Overlay.qml, the focused screen
# beside the taskbar). Each has its own lock, keeper pid file and log, so one satellite can have both.
# While an overlay is open, Hyprland runs this submap: its Escape closes every overlay, whatever the overlay's own QML
# does with keys (a submap's binds come before any window or layer), and puts the normal keys back. Keys it doesn't
# bind reach the overlay as usual. Super+L still locks (and the lock hook closes the overlay too), the volume, mute,
# mic mute and brightness keys get their binds again (starchaser_hardware_keys); the power button and the lid work
# in every submap already (hyprland.lua, submap_universal).
OVERLAY_SUBMAP = "starchaser-overlay"


def surface_mode(item, want=None):
    """"panel" or "overlay" for open-panel: the one asked for, else the add-on's panel, else its overlay."""
    if want:
        return want
    return "panel" if "panel" in item["kinds"] or "overlay" not in item["kinds"] else "overlay"


def hypr(*args):
    """One hyprctl call for the overlay's submap; nothing happens without Hyprland (tests, another session)."""
    if not os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") or not shutil.which("hyprctl"):
        return ""
    with contextlib.suppress(OSError, subprocess.SubprocessError):
        return subprocess.run(["hyprctl", *args], capture_output=True, text=True, timeout=5,
                              stdin=subprocess.DEVNULL).stdout
    return ""


def focused_screen():
    """The name of the monitor that has focus now ("" without Hyprland): the overlay opens there and stays there."""
    try:
        monitors = json.loads(hypr("-j", "monitors") or "[]")
    except (ValueError, RecursionError):
        return ""
    return next((m["name"] for m in monitors if isinstance(m, dict) and m.get("focused") is True
                 and isinstance(m.get("name"), str)), "") if isinstance(monitors, list) else ""


def overlay_submap_defined():
    try:
        binds = json.loads(hypr("-j", "binds") or "[]")
    except (ValueError, RecursionError):
        return False
    return isinstance(binds, list) and any(isinstance(b, dict) and b.get("submap") == OVERLAY_SUBMAP for b in binds)


def overlay_submap(on):
    """Enter (on) or leave the overlay's submap. Leaving only when it is the one on, and no other overlay is open."""
    if on:
        close = json.dumps(shlex.quote(str(Path(__file__).resolve())) + " close-overlay")     # a Lua string
        from starchaser_hardware_keys import hardware_binds
        # the volume, mute, mic mute and brightness keys too: only the submap's own binds run while it is on
        binds = (f'hl.bind("Escape", hl.dsp.exec_cmd({close})) '
                 'hl.bind("SUPER + L", hl.dsp.exec_cmd("starchaser lock"), { locked = true }) ' + hardware_binds())
        # defined once per Hyprland start: defining it again adds a second copy of every bind, and two Mute binds
        # undo each other on one press
        if not overlay_submap_defined():
            hypr("eval", f'hl.define_submap("{OVERLAY_SUBMAP}", function() {binds} end)')
        hypr("eval", f'hl.dispatch(hl.dsp.submap("{OVERLAY_SUBMAP}"))')
    elif hypr("submap").strip() == OVERLAY_SUBMAP and not open_overlays():
        hypr("eval", 'hl.dispatch(hl.dsp.submap("reset"))')


def open_overlays():
    """{sid: keeper pid} for the overlays open now."""
    found = {}
    with contextlib.suppress(OSError):
        for pidfile in RUN.glob("*/overlay-host.pid"):
            pid = panel_keeper(pidfile.parent.name, "overlay")
            if pid is not None and pid != os.getpid():
                found[pidfile.parent.name] = pid
    return found


def close_overlays(reason=""):
    """close-overlay (the overlay's Escape) and the lock: every open overlay closes, and the normal keys come back."""
    for pid in open_overlays().values():
        with contextlib.suppress(ProcessLookupError, PermissionError):
            os.kill(pid, signal.SIGTERM)
    if hypr("submap").strip() == OVERLAY_SUBMAP:
        hypr("eval", 'hl.dispatch(hl.dsp.submap("reset"))')


def password_prompt_up():
    """A password prompt (the system's own, namespace starchaser-password) is on screen: an overlay never sits
    under or over one, so it closes and the prompt has the screen and the keys to itself."""
    out = hypr("layers", "-j")
    return '"starchaser-password"' in out


def open_panel(sid, want=None, ensure=False):
    """Open a satellite's panel (Panel.qml) or overlay (Overlay.qml) in a window of its own Quickshell process, or
    close it when it is open: a taskbar item's click and a keyboard shortcut both run this. A small keeper
    (panel-host) holds it and closes it when the satellite is turned off or removed, safe mode is turned on, or the
    desktop ends; an overlay also when the screen locks or a password prompt opens."""
    if not isinstance(sid, str) or not ID_RE.fullmatch(sid):
        raise Problem("Use an add-on id with lowercase letters, digits, and dashes.")
    (RUN / sid).mkdir(parents=True, exist_ok=True, mode=0o700)
    if want is None:
        with contextlib.suppress(Problem, OSError, ValueError, RecursionError):
            want = surface_mode(find(sid))
    mode = want or "panel"
    lock = os.open(RUN / sid / f"{mode}.lock", os.O_RDWR | os.O_CREAT, 0o600)
    deadline = time.monotonic() + 3
    while True:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            break
        except BlockingIOError:
            if ensure and time.monotonic() < deadline:
                time.sleep(0.05)
                continue
            os.close(lock)
            try:
                name = find(sid)["name"]
            except Problem:
                name = sid
            keeper = panel_keeper(sid, mode)
            if ensure:
                print(f"The {name} {mode} is open.")
                return
            if keeper is None:
                print(f"The {name} {mode} is opening.")
                return
            with contextlib.suppress(ProcessLookupError, PermissionError):
                os.kill(keeper, signal.SIGTERM)
            print(f"Closed the {name} {mode}.")
            return
    try:
        item = enabled_item(sid)
        if mode not in item["kinds"]:
            raise Problem(f"{item['name']} has no {mode}.")
        if (panel_entry(item) if mode == "panel" else overlay_entry(item)) is None:
            raise Problem(f"{item['name']} is missing its {mode} file, so it can't open.")
        if not qs_program():
            raise Problem(f"This {mode} can't open: a part of the desktop is missing (the quickshell package).")
        if mode == "overlay" and password_prompt_up():
            raise Problem("A password prompt is open. Answer it first, then open the overlay again.")
        unchanged(item)
        # the keeper holds the lock for as long as the panel is open
        with open(os.devnull, "rb") as nothing, open(os.devnull, "wb") as quiet:
            subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "panel-host", sid, "--lock-fd", str(lock),
                              "--mode", mode],
                             stdin=nothing, stdout=quiet, stderr=quiet, start_new_session=True, pass_fds=(lock,))
    finally:
        os.close(lock)
    log(sid, f"Its {mode} was opened.")
    print(f"Opened the {item['name']} {mode}.")


def panel_host(sid, lock_fd=None, mode="panel"):
    """Keep one satellite's panel (or overlay), and close it as soon as it is asked to (open-panel again), the
    satellite is off or removed, safe mode is on, or the desktop ends; an overlay also when its Escape is pressed
    (close-overlay), the screen locks, or a password prompt opens. One that ends with an error counts as a stop, like
    a taskbar item (three in a minute switch the satellite off); closing it (Escape, its close x) does not."""
    if not ID_RE.fullmatch(sid) or mode not in ("panel", "overlay"):
        return 1
    if lock_fd is None:
        (RUN / sid).mkdir(parents=True, exist_ok=True, mode=0o700)
        lock = os.open(RUN / sid / f"{mode}.lock", os.O_RDWR | os.O_CREAT, 0o600)
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return 0
    item = enabled_item(sid)
    entry = panel_entry(item) if mode == "panel" else overlay_entry(item)
    program = qs_program()
    if entry is None or not program:
        return 1
    unchanged(item)
    stopping = []
    for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
        signal.signal(sig, lambda *_args: stopping.append(True))
    env = code_env(item, entry, mode)
    if mode == "panel" and os.environ.get("STARCHASER_SATELLITE_FROM_TASKBAR") == "1":
        with contextlib.suppress(OSError, ValueError, TypeError):
            event = json.loads(satellite_runtime.read_regular(RUN / sid / "events.json", 8192))
            if time.time() * 1000 - 5000 <= event.get("clickAt", 0) <= time.time() * 1000 + 1000:
                env["STARCHASER_SATELLITE_ANCHOR"] = json.dumps({k: event[k] for k in ("screen", "x", "y", "w", "h", "edge")})
    LOGS.mkdir(parents=True, exist_ok=True)
    (LOGS / f"{sid}.{mode}.log").write_text("")
    proc = output = None
    stamp, looked, reason, prompt_looked = None, 0.0, "", 0.0
    provider_at = 0.0
    word = "panel" if mode == "panel" else "overlay"
    try:
        if mode == "overlay":
            env["STARCHASER_SATELLITE_SCREEN"] = focused_screen()
            overlay_submap(True)
        proc = start_satellite_process(item, mode, [program, "-p", str(HOST_SHELL)], env)
        output = Output(sid, proc.stdout, LOGS / f"{sid}.{mode}.log")
        while proc.poll() is None and not stopping and not display_gone():
            output.drain()
            take_request(item)
            now = time.monotonic()
            if now - provider_at > 15:
                provider_at = now
                deliver_providers([item], provider_snapshot(item.get("providers", [])))
            if mode == "overlay" and now - prompt_looked >= 1:
                prompt_looked = now
                if password_prompt_up():
                    reason = "Its overlay was closed because a password prompt opened."
                    break
            try:
                mark = (STATE.stat().st_mtime_ns if STATE.exists() else 0, MARKER.exists())
            except OSError:
                mark = None
            if mark != stamp or now - looked > 5:
                stamp, looked = mark, now
                try:
                    current = find(sid)
                    if not current["enabled"]:
                        reason = f"Its {word} was closed because the add-on is off."
                    elif current["commit"] != item["commit"] or current.get("reload", "") != item.get("reload", ""):
                        reason = f"Its {word} was closed because its files changed. Open it again to see them."
                except Problem:
                    reason = f"Its {word} was closed because the add-on was removed."
                except (OSError, ValueError, RecursionError):
                    pass
                if reason:
                    break
            time.sleep(0.25)
    finally:
        try:
            if proc is not None:
                code = proc.poll()
                stop_group(proc.pid, proc)
                if output is not None:
                    output.drain()
                proc.stdout.close()
        finally:
            with contextlib.suppress(OSError):
                (RUN / sid / f"{mode}-host.pid").unlink(missing_ok=True)
                (RUN / sid / f"{mode}.pid").unlink(missing_ok=True)
            if mode == "overlay":
                overlay_submap(False)              # the normal keys again (unless another overlay is still open)
    if not reason and display_gone():
        reason = f"Its {word} was closed because you logged out."
    elif not reason and stopping:
        reason = f"Its {word} was closed."
    if reason:
        log(sid, reason)
    elif code:
        log(sid, f"Its {word} stopped (exit code {code}).")
        with contextlib.suppress(Problem, OSError):
            failure(sid, item["name"])
    return 0


def info(source, fetch=False):
    if not source or not source.strip():
        # an empty word is missing input; Path("") would read as this folder and look like a broken satellite
        raise Problem("An id, folder, or link is needed. Find one with: starchaser satellite search <words>")
    if git_link(source):
        with tempfile.TemporaryDirectory(prefix="starchaser-satellite-info-") as work:
            root = Path(work) / "satellite"
            sha = clone(source, root, None)
            if omarchy_plugin(root):
                raise OmarchyPlugin()
            converted = omarchy_to_satellite(root, source, sha)
            check_tree(root)
            result = details({**manifest(root), "path": str(root), "source": "From a link", "source_url": source, "commit": sha})
            return {**result, "converted": converted} if converted else result
    if Path(source).is_dir():
        root = Path(source).resolve()
        if omarchy_plugin(root):
            raise OmarchyPlugin()
        check_tree(root)
        if is_plain_theme(root):
            return plain_theme_info(root)
        return details({**manifest(root), "path": str(root), "source": "Local folder", "commit": ""})
    try:
        return details(find(source))
    except Problem:
        entry = next((e for e in index_entries() if e["id"] == source and e["review"] != "Removed"), None)
        if entry is None:
            raise
        if fetch and entry["review"] in {"Reviewed", "Unreviewed"}:
            # what it adds and asks for, read from the exact version the list names, before anything is installed
            with tempfile.TemporaryDirectory(prefix="starchaser-satellite-info-") as work:
                root = Path(work) / "satellite"
                sha = clone(entry["repo"], root, entry["commit"])
                check_tree(root)
                m = manifest(root)
                if m["id"] != entry["id"]:
                    raise Problem("The add-on at that version has a different id than the list says.") from None
                result = details({**m, "path": str(root), "source": FROM_LIST, "review": entry["review"], "commit": sha})
                result.update(path="", installed=False, listed=listing(entry, None),
                              install_note=REVIEWED_NOTE if entry["review"] == "Reviewed" else outside_warning(m))
                return result
        # Listed but not on this computer: what the list knows, in the same shape Settings reads.
        return {**entry, "version": "", "source": entry["review"], "path": "", "packages": [], "permissions": {},
                "readme": "", "asks": "Install it to see what it asks for.", "adds": adds_text(entry["kinds"]),
                "later": [], "hooks": [], "hook_text": "", "has_page": False, "page_kind": "", "pin_note": "", "installed": False,
                "code_warning": CODE_WARNING if listing(entry, None)["code"] else "",
                "package_note": "Uses only the system's own packages; this update does not install packages.",
                "review_note": "Made by Starchaser" if entry["review"] == "Included" else
                "A person at Starchaser reviewed this version." if entry["review"] == "Reviewed" else "Not reviewed by Starchaser.",
                "install_note": REVIEWED_NOTE if entry["review"] == "Reviewed" else WARNING, "listed": listing(entry, None)}


SURFACE_KINDS = {"quick-tile", "search-result", "desktop-widget", "lock-widget", "file-action"}


def query_value(row, query):
    prefix = row.get("query_prefix")
    if one_line(prefix, 40) and query.lower().startswith(prefix.lower()):
        return query[len(prefix):].strip()
    value = query.strip()
    if len(value) > 200:
        return None
    pattern = row.get("query_pattern")
    if pattern == "calculation" and re.fullmatch(r"[0-9().+*/%\s-]+", value) and re.search(r"[0-9]", value):
        return value
    if pattern == "quantity" and re.fullmatch(r"-?\d+(?:\.\d+)?\s*(?:mi|miles?|km|kilometers?|ft|feet|foot|m|meters?|lb|pounds?|kg|kilograms?|f|fahrenheit|c|celsius)", value, re.I):
        return value
    return None


def surface_query(query):
    if not isinstance(query, str) or len(query) > 500 or any(ord(c) < 32 for c in query):
        raise Problem("Use a short menu search.")
    jobs, owners = [], {}
    for item in enabled("search-result"):
        if not item["permissions"].get("search"):
            continue
        path = entry_path(item, "search-result", "search-result.json")
        try:
            if path.stat().st_size > 65536:
                continue
            rows = json.loads(path.read_text())
            if not isinstance(rows, list):
                continue
            for index, row in enumerate(rows[:20]):
                if not isinstance(row, dict):
                    continue
                command, value = row.get("query_command"), query_value(row, query)
                if not one_line(command, 4096) or value is None:
                    continue
                key = item["id"] + ":" + str(index)
                owners[key] = (item, index)
                jobs.append((key, ["sh", "-c", command], item["path"], satellite_env(item["id"], {"STARCHASER_QUERY": value})))
                if len(jobs) >= 5:
                    break
        except (OSError, ValueError):
            continue
        if len(jobs) >= 5:
            break
    answers = run_bounded(jobs, 2, cap=2048) if jobs else {}
    results = []
    for key, (status, output) in answers.items():
        if status == 0 and output.strip():
            item, index = owners[key]
            results.append({"label": output.strip().replace("\n", " ")[:300], "text": "Add-on: " + item["name"],
                            "icon": item.get("icon", ""), "run": "starchaser satellite run-surface " + item["id"] + " search-result " + str(index)})
    return results


def surface_rows(kind):
    if kind not in SURFACE_KINDS:
        raise Problem("Choose a supported add-on surface.")
    rows = []
    for item in enabled(kind):
        path = entry_path(item, kind, kind + ".json")
        try:
            if path.stat().st_size > 65536:
                continue
            data = json.loads(path.read_text())
            if not isinstance(data, list):
                continue
            for index, row in enumerate(data[:20]):
                if not isinstance(row, dict) or not one_line(row.get("label"), 120):
                    continue
                # The lock surface is static public text; no command or provider is ever evaluated there.
                if kind == "lock-widget" and (set(row) - {"label", "text"}):
                    continue
                text = row.get("text", "")
                if not isinstance(text, str) or len(text) > 1000:
                    continue
                command = row.get("run", "")
                if not isinstance(command, str) or len(command) > 4096:
                    continue
                native = row.get("open")
                can_open = native in {"panel", "overlay", "menu"} and ({"panel": "panel", "overlay": "overlay", "menu": "menu-page"}[native] in item["kinds"])
                rows.append({"id": item["id"], "index": index, "label": "Add-on: " + row["label"], "text": text,
                             "run": "starchaser satellite run-surface " + item["id"] + " " + kind + " " + str(index) if command or can_open else ""})
        except (OSError, ValueError, Problem):
            continue
    return rows


def run_surface(sid, kind, index, file=None):
    if kind == "lock-widget":
        raise Problem("Lock widgets can't run actions.")
    item = enabled_item(sid)
    if kind not in SURFACE_KINDS or kind not in item["kinds"]:
        raise Problem("That add-on doesn't provide this surface.")
    row = next((r for r in surface_rows(kind) if r["id"] == sid and r["index"] == index and r["run"]), None)
    if not row:
        raise Problem("That add-on action changed. Open it again.")
    path = entry_path(item, kind, kind + ".json")
    value = json.loads(path.read_text())[index]
    native = value.get("open")
    if native in {"panel", "overlay"} and native in item["kinds"]:
        return open_panel(sid, native)
    if native == "menu" and "menu-page" in item["kinds"]:
        return open_menu(sid)
    extra = {"STARCHASER_FILE": str(Path(file).resolve())} if file and kind == "file-action" else {}
    status, output = run_bounded([(0, ["sh", "-c", value["run"]], item["path"], satellite_env(sid, extra))], COMMAND_SECONDS)[0]
    if status != 0:
        raise Problem("The add-on action couldn't finish.")
    print(output, end="")


def provider_snapshot(requested=None):
    """Trusted snapshots shared by all SDK consumers; no author command runs here."""
    requested = set(requested) if requested is not None else {"battery", "network", "media", "workspaces", "weather", "calendar"}
    snapshot = {"updated": time.time(), "battery": {}, "network": {}, "media": {}, "workspaces": [], "weather": {}, "calendar": []}
    for path in (Path("/sys/class/power_supply").glob("*") if "battery" in requested else []):
        with contextlib.suppress(OSError, ValueError):
            if (path / "type").read_text().strip() == "Battery":
                snapshot["battery"] = {"percent": int((path / "capacity").read_text()), "status": (path / "status").read_text().strip()}
                for unit in ("energy", "charge"):
                    full, design = path / (unit + "_full"), path / (unit + "_full_design")
                    if full.exists() and design.exists():
                        snapshot["battery"]["health"] = round(100 * int(full.read_text()) / max(1, int(design.read_text())))
                        break
    jobs = {"network": ["ip", "-j", "address", "show", "up"], "workspaces": ["hyprctl", "-j", "workspaces"],
            "media": ["playerctl", "metadata", "--format", "{{artist}} — {{title}}"]}
    for key, command in jobs.items():
        if key not in requested:
            continue
        try:
            result = subprocess.run(command, capture_output=True, text=True, timeout=2)
            if result.returncode == 0 and len(result.stdout) < 65536:
                snapshot[key] = {"title": result.stdout.strip()} if key == "media" else json.loads(result.stdout)
        except (OSError, ValueError, subprocess.SubprocessError):
            pass
    agenda = data_dir("date-agenda") / "date-agenda.json"
    with contextlib.suppress(OSError, ValueError):
        snapshot["calendar"] = json.loads(satellite_runtime.read_regular(agenda, 128000)).get("entries", [])[:200] if "calendar" in requested else []
    # The weather service's public cache is optional; absent data stays explicitly unavailable.
    for weather in ((CONFIG / "weather.json", DATA / "weather.json") if "weather" in requested else []):
        with contextlib.suppress(OSError, ValueError):
            value = json.loads(weather.read_text())
            if isinstance(value, dict):
                snapshot["weather"] = {k: v for k, v in value.items() if k in {"temperature", "conditions", "forecast", "updated"}}
    return snapshot


def deliver_providers(items, snapshot):
    for item in items:
        requested = item.get("providers", [])
        filtered = {k: v for k, v in snapshot.items() if k == "updated" or k in requested}
        atomic_json(RUN / item["id"] / "providers.json", filtered)


HTTP_POOL = None
HTTP_JOBS = {}


def queue_http(item, request):
    global HTTP_POOL
    poll_http()
    sid = item["id"]
    if not isinstance(request, dict):
        return
    request_id = request.get("requestId", "") if isinstance(request, dict) else ""
    if not isinstance(request_id, str) or len(request_id) > 80:
        return
    if sid in HTTP_JOBS or len(HTTP_JOBS) >= 32:
        atomic_json(RUN / sid / "http-result.json", {"requestId": request_id, "at": time.time()*1000, "status": 0, "text": "", "error": "An add-on request is already running. Try again shortly."})
        return
    hosts = tuple(item["permissions"].get("network", []))
    # Validate before creating a worker; invalid requests never occupy the queue.
    satellite_network.authorized_url(request.get("url", ""), hosts)
    def work():
        current = enabled_item(sid)
        if tuple(current["permissions"].get("network", [])) != hosts:
            raise Problem("The add-on's access changed.")
        return satellite_network.exchange(request, hosts)
    if HTTP_POOL is None:
        HTTP_POOL = ThreadPoolExecutor(max_workers=4, thread_name_prefix="addon-https")
    HTTP_JOBS[sid] = (HTTP_POOL.submit(work), hosts, request_id, request.get("url", ""))


def poll_http():
    for sid, (future, hosts, request_id, address) in list(HTTP_JOBS.items()):
        try:
            item = enabled_item(sid)
            allowed = tuple(item["permissions"].get("network", [])) == hosts
        except (Problem, OSError, ValueError):
            allowed = False
        if not allowed:
            future.cancel()
            HTTP_JOBS.pop(sid, None)
            continue
        if not future.done():
            continue
        HTTP_JOBS.pop(sid, None)
        try:
            answer = future.result()
        except (OSError, ValueError, Problem, http.client.HTTPException):
            answer = {"status": 0, "text": "", "error": "The add-on request couldn't finish or exceeded its declared access."}
        if answer["status"]:
            from urllib.parse import urlsplit
            activity_path = LOGS / (sid + "-activity.json")
            atomic_json(activity_path, {**jread_dict(activity_path), "last_host": urlsplit(address).hostname,
                        "last_contact": time.time(), "network": "Declared HTTPS broker"})
        atomic_json(RUN / sid / "http-result.json", {**answer, "at": time.time()*1000, "requestId": request_id})


def take_request(item):
    satellite_runtime.publish_appearance(os.environ, RUN / ".appearance")
    poll_http()
    sid = item["id"]
    path = RUN / sid / "request.json"
    try:
        if path.stat().st_size > 8192:
            return
        request = json.loads(satellite_runtime.read_regular(path, 8192))
        path.unlink()
        if not isinstance(request, dict):
            return
        stamp, now = request.get("at"), time.time() * 1000
        # Compare before doing arithmetic with untrusted numbers: subtracting a
        # huge JSON integer from a float raises OverflowError. This also refuses
        # booleans, NaN, infinities and stale requests without coercion.
        if type(stamp) not in (int, float) or not now - 5000 <= stamp <= now + 5000:
            return
        item = enabled_item(sid)
        if request.get("action") in {"panel", "overlay", "menu"}:
            action = {"panel": "open-panel", "overlay": "open-overlay", "menu": "open-menu"}[request["action"]]
            subprocess.Popen([str(Path(__file__).resolve()), action, sid], env={**os.environ, "STARCHASER_SATELLITE_FROM_TASKBAR": "1"}, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        elif request.get("action") == "http":
            queue_http(item, json.loads(request.get("body", "")))
        elif request.get("action") == "secret" and request.get("title") in item.get("secrets", []):
            key = request["title"]
            result = subprocess.run(["secret-tool", "lookup", "starchaser-addon", sid, "key", key], capture_output=True, text=True, timeout=5)
            value = result.stdout.strip()[:8192] if result.returncode == 0 else ""
            atomic_json(RUN / sid / "secret-result.json", {"key": key, "value": value, "at": time.time() * 1000})
        elif request.get("action") == "media" and item["permissions"].get("media"):
            if request.get("title") in {"play-pause", "next", "previous"}:
                subprocess.run(["playerctl", request["title"]], capture_output=True, timeout=5)
        elif request.get("action") == "notify" and item["permissions"].get("notify"):
            title, body = request.get("title"), request.get("body")
            if one_line(title, 120) and isinstance(body, str) and len(body) <= 1000:
                subprocess.Popen(["starchaser", "notify", "-a", "Add-on: " + item["name"], "--", title, body],
                                 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except (OSError, ValueError, TypeError, OverflowError, RecursionError, subprocess.SubprocessError, Problem):
        return


def access_note(item):
    if item.get("path") and not ships_code(item, Path(item["path"])):
        return "No executable content."
    if item.get("sandbox", "full-access") == "restricted":
        return ("Restricted access: its own files and data, no account files. Can open windows and run installed system programs. "
                + ("HTTPS only through Starchaser to: " + ", ".join(item["permissions"]["network"]) + "." if item.get("permissions", {}).get("network") else "No network."))
    return "Full access to your files and network. Its declared access list is not enforced."


def managed_policy():
    path = Path("/etc/starchaser/satellite-policies") / (str(os.getuid()) + ".json")
    if not path.exists():
        path = Path("/etc/starchaser/satellites-policy.json")
    try:
        info = path.stat()
        if info.st_uid != 0 or info.st_mode & 0o022:
            raise Problem("The managed add-on policy isn't protected. Ask your administrator to repair it.")
        value = json.loads(path.read_text())
        if not isinstance(value, dict) or set(value) - {"reviewed_only", "blocked", "included"}:
            raise ValueError()
        for key in ("blocked", "included"):
            if not isinstance(value.get(key, []), list) or any(not isinstance(x, str) or not ID_RE.fullmatch(x) for x in value.get(key, [])):
                raise ValueError()
        if type(value.get("reviewed_only", False)) is not bool:
            raise ValueError()
        return value
    except FileNotFoundError:
        return {}
    except (ValueError, OSError):
        raise Problem("The managed add-on policy couldn't be read. Ask your administrator to repair it.") from None


def policy_reviewed(item):
    """Authenticate review against the official signed list, never an account's editable labels."""
    path = Path(item.get("path", "/nonexistent"))
    if any(path == base / item["id"] and path.is_dir() and not path.is_symlink() for base in INCLUDED):
        return True
    commit, repo = item.get("commit", ""), item.get("source_url", "")
    if not isinstance(commit, str) or not SHA_RE.fullmatch(commit) or not isinstance(repo, str) or not git_link(repo):
        return False
    try:
        cached = read_cache(SHARED_INDEX)
        if not cached or check_signature(cached[0], cached[1])[0] != "signed":
            return False
        made = list_generated(cached[0], SHARED_INDEX)
        floor = jread_dict(LIST_SEEN).get(SHARED_INDEX)
        if isinstance(floor, (float, int)) and (made is None or made < floor):
            return False
        # The account can edit both labels and the enabled flag. Check the actual pinned files at
        # every policy gate too, including requests and commands that do not go through enable.
        unchanged(item)
        return any(entry["id"] == item["id"] and entry["review"] == "Reviewed"
                   and entry["repo"] == repo and entry["commit"] == commit
                   for entry in parse_index(cached[0], where=SHARED_INDEX))
    except (Problem, OSError, ValueError):
        return False


def policy_check(item):
    policy = managed_policy()
    if item["id"] in policy.get("blocked", []):
        raise Problem("This add-on is blocked on this managed computer.")
    if policy.get("reviewed_only") and not policy_reviewed(item):
        raise Problem("Only reviewed add-ons are allowed on this managed computer.")


def execution(item, command, env):
    policy_check(item)
    return satellite_runtime.sandbox_command(item, command, env, data_dir(item["id"]), RUN / item["id"],
                                             Path(__file__).resolve().parent.parent, Problem)


def activity_note(item, mode):
    atomic_json(LOGS / (item["id"] + "-activity.json"), {"last_run": time.time(), "mode": mode,
                "access": item.get("sandbox", "full-access"), "network": "Blocked" if item.get("sandbox") == "restricted" else "Not monitored"})


def activity(sid):
    result = jread_dict(LOGS / (sid + "-activity.json"))
    result.update(running=False, memory_bytes=0)
    for mode in ("widget", "service", "page", "panel", "overlay"):
        try:
            pid = int((RUN / sid / (mode + ".pid")).read_text())
            if not ours(pid, sid, mode):
                continue
            result["running"] = True
            for line in Path(f"/proc/{pid}/status").read_text().splitlines():
                if line.startswith("VmRSS:"):
                    result["memory_bytes"] += int(line.split()[1]) * 1024
        except (OSError, ValueError):
            continue
    return result


def support_url(item):
    from urllib.parse import urlsplit
    address = item.get("homepage", "")
    parsed = urlsplit(address)
    if parsed.scheme != "https" or parsed.username or parsed.password or not parsed.hostname:
        return ""
    return address.rstrip("/") + "/issues" if parsed.hostname in {"github.com", "codeberg.org", "gitlab.com"} else address


def protocol_source(address):
    from urllib.parse import parse_qs, urlsplit
    try:
        parsed = urlsplit(address)
        query = parse_qs(parsed.query, strict_parsing=True)
        if (parsed.scheme != "starchaser" or parsed.netloc != "satellites" or parsed.path != "/install"
                or parsed.fragment or set(query) != {"source"} or len(query["source"]) != 1):
            raise ValueError()
        source = query["source"][0]
        if not ID_RE.fullmatch(source) and not git_link(source):
            raise ValueError()
        return source
    except (ValueError, KeyError):
        raise Problem("This add-on link isn't valid. Use an add-on id or a public Git address.") from None


def undo_update(sid):
    load_index(offline=True, url=SHARED_INDEX)
    with locked_state() as saved:
        record = saved["satellites"].get(sid, {})
        previous = record.get("previous")
        kept, current = INSTALLED / (".previous-" + sid), INSTALLED / sid
        if not previous or not kept.is_dir() or record.get("index_removed"):
            raise Problem("There is no safe previous version to restore.")
        check_tree(kept)
        item = manifest(kept)
        policy_check({**item, **record, "path": str(kept), "commit": previous["commit"], "source_url": previous["repo"]})
        old = INSTALLED / (".undone-" + sid)
        if old.exists():
            delete_satellite_tree(old)
        # Publish off before changing files; the previous version is never silently enabled.
        record["enabled"] = False
        atomic_json(STATE, saved)
        stop_satellite(sid)
        os.rename(current, old)
        try:
            os.rename(kept, current)
        except OSError:
            os.rename(old, current)
            raise
        record.update(commit=previous["commit"], source_url=previous["repo"], granted_permissions=item["permissions"], review="Unreviewed")
        record.pop("previous", None)
    delete_satellite_tree(old)
    print("Restored the previous version; it is off. Review it before turning it on.")


def undo_remove(sid):
    leases = [(p, jread_dict(p)) for p in (CONFIG / "satellite-result-leases").glob("*.json")]
    pending = [(p, lease) for p, lease in leases if lease.get("action") == "remove" and lease.get("id") == sid
               and lease.get("purge") and lease.get("until", 0) > time.time()]
    for _, lease in pending:
        if (DATA / "satellite-result-backup" / lease["token"]).exists() and data_dir(sid).exists() and any(data_dir(sid).iterdir()):
            raise Problem("Its saved settings changed after removal, so this Undo can't replace them.")
    load_index(offline=True, url=SHARED_INDEX)
    with locked_state() as saved:
        record = saved["satellites"].get(sid, {})
        if not record.get("removed") or record.get("trash_until", 0) <= time.time():
            raise Problem("That removal can no longer be undone.")
        if record.get("index_removed"):
            raise Problem("This add-on was removed for safety, so it can't be restored.")
        trash, target = INSTALLED / (".trash-" + sid), INSTALLED / sid
        if trash.exists():
            if target.exists():
                raise Problem("Another add-on is using that folder.")
            check_tree(trash)
            item = manifest(trash)
            policy_check({**item, **record, "path": str(trash)})
            os.rename(trash, target)
        item = manifest(target) if target.is_dir() else find(sid, {**saved, "satellites": {**saved["satellites"], sid: {**record, "removed": False}}})
        policy_check({**item, **record, "path": str(target) if target.is_dir() else item.get("path", "")})
        restored = {**item, **record, "path": str(target) if target.is_dir() else item.get("path", "")}
        unchanged(restored)
        record.update(enabled=bool(record.pop("restore_enabled", False)), removed=False)
        record.pop("trash_until", None)
        name = record.get("trash_name", item["name"])
    for path, lease in pending:
        backup = DATA / "satellite-result-backup" / lease["token"]
        if backup.exists():
            if data_dir(sid).exists():
                data_dir(sid).rmdir()
            os.rename(backup, data_dir(sid))
        path.unlink(missing_ok=True)
    sync_file_actions()
    print(f"{name} is back.")


def result_fingerprint():
    return hashlib.sha256(json.dumps(state(), sort_keys=True).encode()).hexdigest()


@contextlib.contextmanager
def result_lock():
    CONFIG.mkdir(parents=True, exist_ok=True)
    with (CONFIG / "satellite-result.lock").open("a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        yield


def result_command(args):
    return subprocess.run([sys.executable, str(Path(__file__).resolve()), *args], capture_output=True, text=True)


def result_action(args):
    if not args or args[0] not in {"install", "update", "remove", "safe"}:
        raise Problem("This change has no result Undo.")
    action = args[0]
    turn_on = "--turn-on" in args
    use_theme = "--use-theme" in args
    purge = action == "remove" and "--purge" in args
    command = [arg for arg in args if arg not in {"--turn-on", "--use-theme", "--purge"}]
    with result_lock():
        before = state()
        was_safe = safe_on(before)
        before_ids = {sid for sid, record in before["satellites"].items() if not record.get("removed")}
        proc = result_command(command)
        if proc.returncode:
            raise Problem(proc.stderr.strip() or proc.stdout.strip() or "The change couldn't be saved.")
        after = state()
        sid = args[1] if action in {"remove", "update"} else ""
        theme_applied = False
        if action == "install":
            # Removal keeps a state record, so a reinstallation can reuse an existing id.
            added = {sid for sid, record in after["satellites"].items() if not record.get("removed")} - before_ids
            sid = next(iter(added), "") if len(added) == 1 else ""
            if turn_on and sid:
                # A single theme needs no second choice after Install and turn
                # on. Collections still let the person pick which theme to use.
                themes = theme_ids([find(sid)])
                enabled = result_command(["enable", sid] + (["--use-theme"] if use_theme and len(themes) == 1 else []))
                if enabled.returncode:
                    result_command(["remove", sid, "--yes"])
                    raise Problem(enabled.stderr.strip() or "The add-on couldn't be turned on; its installation was undone.")
                proc.stdout = enabled.stdout
                theme_applied = use_theme and len(themes) == 1 and jread_dict(THEME_STATE).get("id") in themes
        token = os.urandom(16).hex()
        undo = {"token": token, "action": action, "id": sid, "until": time.time() + 10, "purge": purge}
        backup = DATA / "satellite-result-backup" / token
        if purge and data_dir(sid).exists():
            backup.parent.mkdir(parents=True, exist_ok=True)
            os.rename(data_dir(sid), backup)
        undo["fingerprint"] = result_fingerprint()
        undo["record"] = state()["satellites"].get(sid, {})
        message = proc.stdout.strip().split("\n")[-1]
        reversible = ((action == "install" and bool(sid)) or (action == "remove" and after["satellites"].get(sid, {}).get("trash_until", 0) > time.time())
                      or (action == "update" and message.startswith("Updated ")) or (action == "safe" and not was_safe))
        if reversible:
            atomic_json(CONFIG / "satellite-result-undo.json", undo)
            atomic_json(CONFIG / "satellite-result-leases" / (token + ".json"), undo)
            subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "result-expire", token],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
        print(json.dumps({"message": message, "undo": token if reversible else "", "themeApplied": theme_applied}))


def result_undo(token):
    if not re.fullmatch(r"[a-f0-9]{32}", token):
        raise Problem("That Undo has expired.")
    with result_lock():
        path = CONFIG / "satellite-result-undo.json"
        lease = jread_dict(path)
        if lease.get("token") != token or lease.get("until", 0) <= time.time():
            raise Problem("That Undo has expired.")
        if lease.get("fingerprint") != result_fingerprint():
            raise Problem("Add-ons changed since that result. Open Details to review them.")
        backup = DATA / "satellite-result-backup" / token
        target = data_dir(lease["id"]) if lease["id"] else None
        if backup.exists() and target.exists() and any(target.iterdir()):
            raise Problem("Its saved settings changed after removal, so this Undo can't replace them.")
        action, sid = lease["action"], lease["id"]
        if action == "install":
            change(sid, "remove", yes=True)
        elif action == "update":
            undo_update(sid)
        elif action == "remove":
            undo_remove(sid)
            backup = DATA / "satellite-result-backup" / token
            if backup.exists():
                target = data_dir(sid)
                if target.exists():
                    target.rmdir()
                os.rename(backup, target)
        elif action == "safe":
            leave_safe()
        # The result lock serializes activations. Keep recovery and expiration available
        # if dispatch fails; consume this exact result only after a successful Undo.
        path.unlink(missing_ok=True)
        (CONFIG / "satellite-result-leases" / (token + ".json")).unlink(missing_ok=True)


def result_expire(token):
    if not re.fullmatch(r"[a-f0-9]{32}", token):
        return
    path = CONFIG / "satellite-result-leases" / (token + ".json")
    lease = jread_dict(path)
    if lease.get("token") != token:
        return
    time.sleep(max(0, min(10, lease.get("until", 0) - time.time())))
    if not path.exists():
        return
    with result_lock():
        lease = jread_dict(path)
        if lease.get("token") != token or lease.get("until", 0) > time.time():
            return
        path.unlink(missing_ok=True)
        if lease.get("purge") and state()["satellites"].get(lease["id"], {}) == lease.get("record"):
            change(lease["id"], "remove", yes=True, purge=True)
        backup = DATA / "satellite-result-backup" / token
        if backup.exists():
            delete_satellite_tree(backup)


def clean_result_leases():
    # Catch up after sign-out or a stopped expiration worker.
    for path in (CONFIG / "satellite-result-leases").glob("*.json"):
        lease = jread_dict(path)
        if lease.get("until", 0) <= time.time():
            result_expire(path.stem)


def clean_trash():
    clean_result_leases()
    with locked_state() as saved:
        for sid, record in saved["satellites"].items():
            if record.get("trash_until") and record["trash_until"] <= time.time():
                path = INSTALLED / (".trash-" + sid)
                if path.exists():
                    delete_satellite_tree(path)
                record.pop("trash_until", None)


def run_menu(sid, token):
    import hashlib
    item = enabled_item(sid)
    path = entry_path(item, "menu-page", "menu.json")
    if path.stat().st_size > 256 * 1024:
        raise Problem("That menu is too large.")
    value = json.loads(path.read_text())
    rows = sanitize_rows(value if isinstance(value, list) else [value])
    def walk(entries):
        for row in entries:
            if "run" in row and hashlib.sha256(row["run"].encode()).hexdigest() == token:
                return row["run"]
            found = walk(row.get("children", []))
            if found:
                return found
        return None
    command = walk(rows)
    if command is None:
        raise Problem("That add-on action changed or was removed. Open the menu again.")
    status, output = run_bounded([(0, ["sh", "-c", command], item["path"], satellite_env(sid))], COMMAND_SECONDS)[0]
    if status != 0:
        raise Problem("The add-on action couldn't finish. Its log has the details.")
    print(output, end="")


def automatic_update_allowed(target, before, after, stage):
    grants = {"granted_permissions": before["permissions"], "granted_kinds": before["kinds"],
              "granted_providers": before.get("providers", []), "granted_secrets": before.get("secrets", []),
              "granted_sandbox": before.get("sandbox")}
    return (target.get("signature") == "signed" and target.get("review") == "Reviewed" and not target.get("source_warning")
            and before.get("sandbox") == after.get("sandbox") == "restricted"
            and not any(asks_more(after, grants))
            and not (ships_code(after, stage) and not ships_code(before, Path(before["path"]))))


def background_updates(force=False):
    # One weekly check for the account, even when several screens request it together.
    CONFIG.mkdir(parents=True, exist_ok=True)
    with (CONFIG / "satellite-updates.lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return
        saved = state()
        if not force and time.time() - saved.get("updates_checked", 0) < 7 * 86400:
            return
        index_check()
        sync_file_actions()
        waiting, problems = update_targets(refresh=True)
        if saved.get("automatic_updates") and not safe_on(saved):
            for target in list(waiting):
                if target["review"] != "Reviewed" or target.get("source_warning"):
                    continue
                try:
                    item = find(target["id"])
                    with staged_update(target) as (stage, after, _summary):
                        if not automatic_update_allowed(target, item, after, stage):
                            continue
                        apply_update(target, stage, after)
                    waiting.remove(target)
                except (Problem, OSError) as ex:
                    problems.append(str(ex))
        ids = sorted(t["id"] + ":" + t["to"] for t in waiting)
        with locked_state() as current:
            notify = ids and ids != current.get("notified_updates", [])
            current.update(waiting_updates=waiting, update_problems=problems, updates_checked=time.time(), notified_updates=ids)
        if notify:
            subprocess.run(["starchaser", "notify", "-a", "Starchaser", "Add-on updates", f"{len(ids)} add-ons have updates. Open Settings > Satellites to review them."],
                           check=False, timeout=10)
        clean_trash()


def export_addons(output):
    entries = []
    saved = state()
    for item in catalog(saved)["satellites"]:
        record = saved["satellites"].get(item["id"], {})
        entries.append({"id": item["id"], "included": item["source"] == "Included", "repo": record.get("source_url", ""),
                        "commit": record.get("commit", ""), "was_on": item["enabled"]})
    path = Path(output)
    if path.exists():
        raise Problem("That file already exists. Choose another export file.")
    atomic_json(path, {"format": 1, "addons": entries})
    print("Saved the add-on list. Backups also carry their folders and private data. Imported add-ons start off.")


def import_addons(source, yes):
    path = Path(source)
    if path.stat().st_size > 1024 * 1024:
        raise Problem("That add-on migration file is too large.")
    value = json.loads(path.read_text())
    if not isinstance(value, dict) or value.get("format") != 1 or not isinstance(value.get("addons"), list) or len(value["addons"]) > 100:
        raise Problem("That add-on migration file couldn't be read.")
    for row in value["addons"]:
        if not isinstance(row, dict) or not isinstance(row.get("id"), str) or not ID_RE.fullmatch(row["id"]):
            raise Problem("That migration file has an invalid add-on id.")
        sid = row["id"]
        if row.get("included") is True:
            if not any((base / sid / "satellite.toml").is_file() for base in INCLUDED):
                raise Problem("Update Starchaser to bring over " + sid + ".")
            with locked_state() as saved:
                saved["satellites"].setdefault(sid, {}).update(enabled=False, removed=False)
        else:
            if not git_link(row.get("repo", "")) or not SHA_RE.fullmatch(row.get("commit", "")):
                raise Problem("Only pinned public Git sources can be brought to another computer.")
            stage_install(row["repo"], row["commit"], True, {"source": "From migration", "source_url": row["repo"], "review": "Unreviewed"}, expect=sid, yes=yes)
    print("Your add-ons are here and off. Check their access before turning them on.")


def sync_file_actions():
    folder = CONFIG.parent / "flea/actions"
    folder.mkdir(parents=True, exist_ok=True)
    rows = surface_rows("file-action")
    wanted = set()
    for row in rows:
        if not row["run"]:
            continue
        name = "starchaser-addon-" + row["id"] + "-" + str(row["index"]) + ".toml"
        wanted.add(name)
        path = folder / name
        values = {"name": row["label"], "mime": ["*/*"], "selection": "one", "mode": "preview",
                  "run": ["starchaser", "satellite", "run-surface", row["id"], "file-action", str(row["index"]), "--file", "{path}"]}
        text = "\n".join(k + " = " + json.dumps(v) for k, v in values.items()) + "\n"
        fd, temp = tempfile.mkstemp(prefix="." + name, dir=folder)
        try:
            with os.fdopen(fd, "w") as stream:
                stream.write(text)
                stream.flush()
                os.fsync(stream.fileno())
            os.replace(temp, path)
        finally:
            Path(temp).unlink(missing_ok=True)
    for path in folder.glob("starchaser-addon-*.toml"):
        if path.name not in wanted:
            path.unlink(missing_ok=True)


def secret_set(sid, key):
    item = find(sid)
    if key not in item.get("secrets", []):
        raise Problem("That saved sign-in wasn't declared by this add-on.")
    value = sys.stdin.readline(8193).rstrip("\n")
    if not value or len(value) > 8192:
        raise Problem("Enter a saved sign-in of at most 8,192 characters on standard input.")
    result = subprocess.run(["secret-tool", "store", "--label", "Add-on: " + item["name"] + " · " + key,
                             "starchaser-addon", sid, "key", key], input=value, text=True, capture_output=True, timeout=30)
    if result.returncode:
        raise Problem("The sign-in couldn't be saved. Unlock Saved passwords and try again.")
    print("Saved in this add-on's own encrypted sign-in space.")


def shortcut_draft(sid):
    item = find(sid)
    action = "open-panel" if "panel" in item["kinds"] else "open-overlay" if "overlay" in item["kinds"] else "click" if "bar-widget" in item["kinds"] else "open-menu"
    atomic_json(CONFIG / "satellite-shortcut.json", {"name": "Open " + item["name"], "run": "starchaser satellite " + action + " " + sid, "keys": item.get("shortcut", "")})
    subprocess.run(["starchaser", "settings", "custom-shortcuts"], check=True)


def shell_exit():
    with locked_state() as saved:
        now = time.time()
        exits = [t for t in saved.get("desktop_exits", []) if now - t < 300] + [now]
        saved["desktop_exits"] = exits
    if len(exits) >= 3:
        safe()
        print("Add-ons were turned off because the desktop kept restarting. Review them in Settings > Satellites.")


@contextlib.contextmanager
def committed_snapshot(folder, commit, expected=None):
    expected = pinned_files(folder, commit) if expected is None else expected
    # Read objects, not the index or working tree. This also works for Git worktrees and avoids
    # export-ignore/export-subst changing what a reviewer would actually clone at the pinned commit.
    with tempfile.TemporaryDirectory(prefix="starchaser-submit-") as work:
        snapshot = Path(work)
        total = 0
        for row in git(["--no-replace-objects", "ls-tree", "-r", "-l", "-z", "--full-tree", commit], cwd=folder).split("\0"):
            if not row:
                continue
            info, name = row.split("\t", 1)
            mode, kind, oid, size = info.split()
            if expected.get(name) != (mode, oid):
                raise Problem(CHANGED)
            total += int(size) if size.isdigit() else THEME_IMPORT_LIMIT + 1
            if total > THEME_IMPORT_LIMIT or kind != "blob":
                raise Problem("The committed add-on is too large or contains a nested Git repository.")
            path = snapshot / name
            if Path(name).is_absolute() or ".." in Path(name).parts:
                raise Problem("The committed add-on contains an unsafe path.")
            path.parent.mkdir(parents=True, exist_ok=True)
            with path.open("wb") as stream:
                subprocess.run(["git", "--no-replace-objects", "-C", str(folder), "cat-file", "blob", oid], stdout=stream,
                               stderr=subprocess.DEVNULL, check=True, timeout=30)
            digest = hashlib.sha1(b"blob " + str(path.stat().st_size).encode() + b"\0")
            with path.open("rb") as stream:
                for data in iter(lambda: stream.read(65536), b""):
                    digest.update(data)
            if digest.hexdigest() != oid:
                raise Problem("The committed add-on's Git objects are damaged. Repair its repository before submitting it.")
            if mode == "120000":
                link = path.read_text()
                path.unlink()
                path.symlink_to(link)
            else:
                path.chmod(0o755 if mode == "100755" else 0o644)
        yield snapshot


def publish_draft(folder, output, open_browser=True):
    folder = Path(folder).resolve()
    if git(["rev-parse", "--show-prefix"], cwd=folder):
        raise Problem("Submit the add-on from its Git repository root, with satellite.toml at that root.")
    commit = git(["--no-replace-objects", "rev-parse", "--verify", "HEAD^{commit}"], cwd=folder)
    with committed_snapshot(folder, commit) as snapshot:
        item, problems = check_folder(snapshot)
        if problems:
            raise Problem("Fix the committed add-on's check results before submitting it: " + " ".join(problems))
        visible = set(item["kinds"]) - {"cli-hook", "service"}
        for kind in sorted(visible):
            shot = snapshot / "screenshots" / (kind + ".png")
            if not shot.is_file() or not image_size(shot):
                raise Problem("Commit a PNG screenshot of the " + kind + " surface at screenshots/" + kind + ".png before submitting it.")
    entry = {k: item[k] for k in ("id", "name", "summary", "version", "author", "kinds")}
    entry.update(api=item["starchaser"]["api"], review="unreviewed", repo=item["homepage"], commit=commit)
    if not SHA_RE.fullmatch(entry["commit"]) or not git_link(entry["repo"]):
        raise Problem("Commit the add-on and set its homepage to its public Git repository before submitting it.")
    target = Path(output)
    if target.exists():
        raise Problem("That entry file already exists. Choose another output file.")
    target.write_text("\n".join(k + " = " + json.dumps(v) for k, v in entry.items()) + "\n")
    from urllib.parse import urlencode
    print(str(target.resolve()))
    address = "https://github.com/starchaserlinux/satellites/compare?" + urlencode({"expand": "1", "title": "Add " + item["name"], "body": target.read_text()})
    print(address)
    if open_browser:
        subprocess.run(["xdg-open", address], check=True)


def main():
    parser = CommandParser(prog="starchaser satellite", description=(
        "Satellites are optional desktop add-ons, such as themes, menu pages, and Today cards.\n"
        "Installing an add-on leaves it off until you enable it.\n\n"
        "Start here (these commands change nothing):\n"
        "  starchaser satellite list          Show installed add-ons\n"
        "  starchaser satellite search theme  Find themes in the list\n"
        "  starchaser satellite info ID       Read about an add-on before installing it"),
                           formatter_class=argparse.RawDescriptionHelpFormatter,
                           usage="%(prog)s [-h] COMMAND ...")
    subs = parser.add_subparsers(dest="action", required=True, metavar="COMMAND")
    descriptions = {
        "list": "List installed add-ons and problems.",
        "info": f"Show details for an id, folder, or {LINK_WORDS}.",
        "install": f"Add an add-on from the list (by id), a local folder, or {LINK_WORDS}, pinned to its exact commit and off by default.",
        "enable": "Turn on an add-on and its additions.",
        "disable": "Turn off an add-on without deleting its folder or settings.",
        "remove": "Remove an add-on, keeping saved settings unless --purge is used.",
        "restore": "Bring back a removed included add-on, off by default.",
        "report-failure": "Record a failed card run and turn off an add-on that keeps stopping.",
        "safe": "Turn off every add-on and save safe mode.",
        "leave-safe": "Leave safe mode, turning back on the add-ons that were on before it.",
        "check": "Check an add-on folder for mistakes before sharing or installing it.",
        "new": "Make a working sample add-on folder to start from.",
        "clone": "Copy any add-on (one that comes with Starchaser or one you added), or a part of the taskbar "
                 "(builtin:clock), into your own folder to change it.",
        "builtins": "List the taskbar parts clone builtin:<part> can copy, and the ones that stay the taskbar's own.",
        "dev": "Turn on an add-on straight from its folder and reload it each time you save (asks first).",
        "search": "Search the list of add-ons (Find more in Settings).",
        "index": "Show where the list of add-ons comes from, how it is signed, and what it holds; --use changes where.",
        "updates": "Show which installed add-ons have a newer version waiting (nothing is changed).",
        "update-info": "Show what an update to one add-on changes, before anything is changed.",
        "update": "Update add-ons after showing what changed and asking first.",
        "index-check": "Switch off add-ons the list took off (the desktop runs this; it prints nothing).",
        "hook": "Run enabled add-ons' actions for an event (Starchaser does this itself).",
        "page-json": "Print an add-on's Settings page and its values as JSON (settings tables only; a QML page has none to print).",
        "page-set": "Change one value on an add-on's Settings page (settings tables only).",
        "page-run": "Press one button on an add-on's Settings page.",
        "menu-json": "Print enabled add-on menu rows as JSON.",
        "cards-json": "Print enabled add-on Today cards as JSON.",
        "theme-dirs": "Print enabled add-on theme folders as JSON.",
        "run-card": "Run one enabled add-on card with time and output limits.",
        "bar-json": "Print the enabled taskbar items as JSON (the taskbar reads this).",
        "click": "Activate an enabled taskbar add-on from the keyboard.",
        "host": "Keep enabled taskbar items and background services running, each in its own process (the taskbar starts this).",
        "open-page": "Open an add-on's settings page written in QML, in its own window.",
        "developer": "Show or hide the example add-ons for people who write their own (on, off, or nothing to see which).",
        "page-host": "Keep one QML settings window and close it when its add-on is off (open-page starts this).",
        "validate": "Check an add-on folder for mistakes (the same as check).",
        "open-panel": "Open an add-on's panel (or its overlay, when it has no panel), or close it when it is open (bind this to a key in Settings > Custom shortcuts).",
        "panel-host": "Keep one add-on's panel and close it when its add-on is off (open-panel starts this).",
        "open-overlay": "Open an add-on's full-screen overlay, or close it when it is open (Escape closes it too).",
        "close-overlay": "Close every open overlay (an overlay's Escape runs this).",
        "open-menu": "Open the Super menu at an add-on's own menu page, or close it (bind this to a key in Settings > Custom shortcuts).",
        "bar-place": "Move a taskbar item to the start, middle or end of the taskbar, or to other screens (Settings does this).",
        "port": "Draft an add-on from a plugin for another desktop (a folder or link with manifest.json) in ~/Satellites; nothing in it runs.",
    }

    def subcommand(action):
        return subs.add_parser(action, help=descriptions[action], description=descriptions[action])

    for action in ("list", "info", "search", "page-json", "index", "updates", "update-info"):
        p = subcommand(action)
        if action == "info":
            p.add_argument("source", help=f"An id, folder, or {LINK_WORDS}.")
            p.add_argument("--fetch", action="store_true", help="For an add-on on the list: read its files at the listed version.")
        elif action == "search":
            p.add_argument("words", nargs="*", help="Words to look for; none lists everything.")
            p.add_argument("--kind", choices=sorted(KINDS), help="Only add-ons that add this kind of thing.")
        elif action == "index":
            p.add_argument("--use", metavar="WHERE", help="local (the list that comes with Starchaser), shared, or an https:// address.")
        elif action == "update-info":
            p.add_argument("id")
        if action in {"index", "updates", "update-info"}:
            p.add_argument("--refresh", action="store_true", help="Fetch the shared list again now, even if it was read today.")
        elif action == "page-json":
            p.add_argument("id")
        p.add_argument("--json", action="store_true")
    p = subcommand("install")
    p.add_argument("source", help=f"An id from the list, a folder, or {LINK_WORDS}.")
    p.add_argument("--commit")
    p.add_argument("--yes", action="store_true")
    for action in ("enable", "disable", "remove", "restore", "report-failure"):
        p = subcommand(action)
        p.add_argument("id")
        if action == "enable":
            p.add_argument("--use-theme", action="store_true", help="Turn on and apply its theme; with several themes, choose one with --theme or in Appearance.")
            p.add_argument("--theme", help="The theme id to apply with --use-theme.")
        if action == "remove":
            p.add_argument("--yes", action="store_true")
            p.add_argument("--purge", action="store_true")
    subcommand("safe")
    subcommand("leave-safe")
    subcommand("index-check")
    p = subcommand("update")
    p.add_argument("id", nargs="?", help="One add-on; none checks every one.")
    p.add_argument("--commit", help="Only this exact waiting version (Settings passes the one it showed).")
    p.add_argument("--yes", action="store_true", help="Update without asking after showing what changed.")
    p.add_argument("--refresh", action="store_true", help="Fetch the shared list again first.")
    p = subcommand("clone")
    p.add_argument("id", help="The add-on to copy, or builtin:<part> for a part of the taskbar (see builtins).")
    p.add_argument("new_name", nargs="?", metavar="NEW-NAME", help='A name for the copy (default: "My <name>").')
    p.add_argument("--dir", help="The folder to put it in (default: ~/Satellites).")
    p.add_argument("--edit", action="store_true", help="Open the copy in your editor ($VISUAL or $EDITOR) once it is made.")
    p.add_argument("--json", action="store_true")
    p = subcommand("builtins")
    p.add_argument("--json", action="store_true")
    p = subcommand("dev")
    p.add_argument("dir", nargs="?", default=".", help="The add-on folder (default: here).")
    p.add_argument("--yes", action="store_true", help="Turn it on without asking after showing what it adds and asks for.")
    p.add_argument("--once", action="store_true", help="Copy it in once and stop, without watching.")
    p.add_argument("--for", dest="seconds", type=float, help="Stop watching after this many seconds.")
    p = subcommand("check")
    p.add_argument("dir", nargs="?", default=".", help="The folder to check (default: here).")
    p = subcommand("new")
    p.add_argument("id")
    p.add_argument("--dir", default=".", help="The folder to make it in (default: here).")
    p.add_argument("--hook", action="store_true", help="Also add a theme-changed action (a script).")
    p.add_argument("--widget", action="store_true", help="Also add a taskbar item written in QML (code).")
    p.add_argument("--theme", action="store_true", help="Make a theme add-on instead (the same as --kind theme).")
    p.add_argument("--from-current", action="store_true", help="With --theme: your current look (colors, wallpaper, window style).")
    p.add_argument("--kind", choices=NEW_KINDS, help="Make a small add-on of just this kind; the id may be a name like \"My Look\".")
    p.add_argument("--edit", action="store_true", help="Open the new folder in your editor ($VISUAL or $EDITOR) once it is made.")
    p.add_argument("--json", action="store_true")
    p = subcommand("hook")
    p.add_argument("event", help="One of: " + ", ".join(EVENTS) + ".")
    p.add_argument("details", nargs="*", help="Event details as STARCHASER_NAME=value.")
    p.add_argument("--wait", action="store_true", help="Wait for the actions instead of returning at once.")
    p = subcommand("page-set")
    p.add_argument("id")
    p.add_argument("control", type=int)
    p.add_argument("value")
    p = subcommand("page-run")
    p.add_argument("id")
    p.add_argument("control", type=int)
    for action in ("menu-json", "cards-json", "theme-dirs", "bar-json"):
        subcommand(action)
    p = subcommand("host")
    p.add_argument("--for", dest="seconds", type=float, help="Stop after this many seconds (for tests).")
    p = subcommand("open-page")
    p.add_argument("id")
    p = subcommand("developer")
    p.add_argument("mode", nargs="?", choices=("on", "off"), help="on shows the example add-ons; off hides them.")
    p = subcommand("page-host")
    p.add_argument("id")
    p.add_argument("--lock-fd", type=int, help=argparse.SUPPRESS)
    p = subcommand("validate")
    p.add_argument("dir", nargs="?", default=".", help="The folder to check (default: here).")
    p = subcommand("open-panel")
    p.add_argument("id")
    p = subcommand("panel-host")
    p.add_argument("id")
    p.add_argument("--lock-fd", type=int, help=argparse.SUPPRESS)
    p.add_argument("--mode", choices=("panel", "overlay"), default="panel", help=argparse.SUPPRESS)
    p = subcommand("open-overlay")
    p.add_argument("id")
    subcommand("close-overlay")
    p = subcommand("open-menu")
    p.add_argument("id")
    p = subs.add_parser("bar-order", help="Save the order of taskbar add-ons that are on.")
    p.add_argument("ids", nargs="+")
    p = subs.add_parser("result-action", help="Apply a Settings change with a ten-second Undo.")
    p.add_argument("args", nargs=argparse.REMAINDER)
    for name in ("result-undo", "result-expire", "dev-click"):
        p = subs.add_parser(name, help=argparse.SUPPRESS)
        p.add_argument("token")
    p = subcommand("bar-place")
    p.add_argument("id")
    p.add_argument("--section", choices=BAR_SECTIONS, help="Where along the taskbar: start, middle, or end.")
    p.add_argument("--screens", help="main, all (when the item allows more than one), or screen names like DP-1,HDMI-A-1.")
    p = subcommand("port")
    p.add_argument("source", help=f"A folder or {LINK_WORDS} to a plugin for another desktop.")
    p.add_argument("--dir", help="The folder to put it in (default: ~/Satellites).")
    p.add_argument("--json", action="store_true")
    p = subcommand("run-card")
    p.add_argument("id")
    p.add_argument("file_id")
    p = subcommand("click")
    p.add_argument("id")
    for action in ("undo-remove", "undo-update", "activity", "shortcut", "run-menu"):
        p = subs.add_parser(action, help="Restore an add-on, show activity, or run a declared action.")
        p.add_argument("id")
        if action == "run-menu":
            p.add_argument("token")
    p = subs.add_parser("protocol", help="Open an add-on web link at its review sheet.")
    p.add_argument("address")
    p = subs.add_parser("automatic-updates", help="Choose whether reviewed restricted add-ons update automatically.")
    p.add_argument("mode", choices=("on", "off"))
    subs.add_parser("background-updates", help="Check weekly for updates and apply eligible reviewed updates when chosen.")
    subs.add_parser("shell-exit", help="Record an unexpected desktop exit for automatic safe mode.")
    p = subs.add_parser("publish", help="Validate and write a local submission draft; never upload or sign.")
    p.add_argument("folder", nargs="?", default=".")
    p.add_argument("--out", required=True)
    p.add_argument("--no-open", action="store_true", help="Only write the local draft and print the submission URL.")
    p = subs.add_parser("search-query", help="Ask enabled add-ons for bounded answers to a menu search.")
    p.add_argument("query")
    p = subs.add_parser("surface-json", help="Read declarative add-on tiles, widgets, search results, or Files actions.")
    p.add_argument("kind", choices=sorted(SURFACE_KINDS))
    p = subs.add_parser("run-surface", help="Run one declared surface action after checking its enabled state.")
    p.add_argument("id")
    p.add_argument("kind", choices=sorted(SURFACE_KINDS))
    p.add_argument("index", type=int)
    p.add_argument("--file")
    p = subs.add_parser("secret-set", help="Save one declared add-on sign-in, read from standard input, in the encrypted keyring.")
    p.add_argument("id")
    p.add_argument("key")
    p = subs.add_parser("export", help="Save your pinned add-on list for another computer; backups carry saved data too.")
    p.add_argument("file")
    p = subs.add_parser("import", help="Bring add-ons from an exported list, reviewing outside code and leaving everything off.")
    p.add_argument("file")
    p.add_argument("--yes", action="store_true")
    args = parser.parse_args()
    try:
        if args.action in {"list", "host"}:
            clean_result_leases()
        if args.action == "result-action":
            result_action(args.args)
        elif args.action == "result-undo":
            result_undo(args.token)
        elif args.action == "result-expire":
            result_expire(args.token)
        elif args.action == "dev-click":
            dev_click(args.token)
        elif args.action == "bar-order":
            order_bar_items(args.ids)
        elif args.action == "export":
            export_addons(args.file)
        elif args.action == "import":
            import_addons(args.file, args.yes)
        elif args.action == "secret-set":
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use a valid add-on id.")
            secret_set(args.id, args.key)
        elif args.action == "search-query":
            print(json.dumps(surface_query(args.query)))
        elif args.action == "surface-json":
            print(json.dumps(surface_rows(args.kind)))
        elif args.action == "run-surface":
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use a valid add-on id.")
            run_surface(args.id, args.kind, args.index, args.file)
        elif args.action in {"undo-remove", "undo-update", "activity", "shortcut", "run-menu"}:
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use a valid add-on id.")
            if args.action == "undo-remove":
                undo_remove(args.id)
            elif args.action == "undo-update":
                undo_update(args.id)
            elif args.action == "shortcut":
                shortcut_draft(args.id)
            elif args.action == "activity":
                print(json.dumps(activity(args.id)))
            else:
                run_menu(args.id, args.token)
        elif args.action == "protocol":
            source = protocol_source(args.address)
            CONFIG.mkdir(parents=True, exist_ok=True)
            atomic_json(CONFIG / "satellite-review-link.json", {"source": source})
            subprocess.run(["starchaser", "settings", "satellite-link"], check=True)
        elif args.action == "automatic-updates":
            with locked_state() as saved:
                saved["automatic_updates"] = args.mode == "on"
            print("Saved.")
        elif args.action == "background-updates":
            background_updates()
        elif args.action == "shell-exit":
            shell_exit()
        elif args.action == "publish":
            publish_draft(args.folder, args.out, not args.no_open)
        elif args.action == "list":
            with contextlib.suppress(Problem, OSError, ValueError):
                load_index(offline=True)
            data = catalog()
            if args.json:
                print(json.dumps(data))
            else:
                if data["safe"]:
                    print("Safe mode is on; every add-on is off until you turn one on again.")
                for item in data["satellites"]:
                    # "Included" alone reads as a state, not a place it came from
                    where = "comes with Starchaser" if item["source"] == "Included" else item["source"].lower()
                    print(f"{item['name']} ({item['id']}) {item['version']} "
                          f"is {'on' if item['enabled'] else 'off'} ({where}).")
                for error in data["errors"]:
                    print(error["reason"])
                if not data["satellites"] and not data["errors"]:
                    print("No add-ons are installed yet.")
        elif args.action == "info":
            if not args.source.strip():
                # a missing word, not a satellite that can't be found (Problem answers those with exit 1)
                message = "An id, folder, or link is needed. Find one with: starchaser satellite search <words>"
                if args.json:
                    print(json.dumps({"ok": False, "errors": message}))
                print(message, file=sys.stderr)
                return 2
            data = info(args.source, args.fetch)
            # the site it comes from ("gitlab.com"), so Settings can say "From gitlab.com"; "" for a folder
            if "host" not in data:
                record = state()["satellites"].get(data.get("id"), {}) if data.get("installed", True) else {}
                data["host"] = (link_host(args.source) or link_host(data.get("repo") or "")
                                or link_host(record.get("source_url", "")))
            if args.json:
                print(json.dumps(data))
            else:
                print(f"{data['name']} {data['version']}".strip() + f": {data['summary']}")
                print(data["adds"], data["asks"])
                if data.get("hook_text"):
                    print(data["hook_text"])
                if data.get("installed") is False:
                    print(f"{data.get('review', data['source'])}; not installed.")
                print(data["package_note"])
                if data["packages"]:
                    print("Needs packages: " + ", ".join(data["packages"]) + ".")
                if data["commit"]:
                    print("Pinned to " + data["commit"] + ".")
                if data["later"]:
                    print("Other additions are coming in a later Starchaser update.")
                if data["code_warning"]:
                    print(data["code_warning"])
        elif args.action == "install":
            install(args.source, args.commit, args.yes)
        elif args.action in {"enable", "disable", "remove", "restore", "report-failure"}:
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use an add-on id with lowercase letters, digits, and dashes.")
            change(args.id, args.action, getattr(args, "yes", False), getattr(args, "purge", False),
                   getattr(args, "use_theme", False), getattr(args, "theme", None))
        elif args.action == "index-check":
            index_check()
        elif args.action == "safe":
            safe()
        elif args.action == "leave-safe":
            leave_safe()
        elif args.action in {"check", "validate"}:
            where = Path(args.dir).resolve()
            m, problems = check_folder(Path(args.dir))
            if problems:
                print("\n".join(problems), file=sys.stderr)
                return 1
            print(f"{m['name']} is ready in {where}: no problems found.")
            if ships_code(m, where):
                print(CODE_WARNING)
        elif args.action == "new":
            if args.theme or args.kind == "theme":
                new_theme(*name_to_id(args.id), args.dir, args.from_current, args.json)
                made = author_parent(args.dir) / name_to_id(args.id)[0]
            elif args.kind:
                if args.from_current:
                    raise Problem("--from-current goes with --theme.")
                new_kind(*name_to_id(args.id), args.dir, args.kind, args.json)
                made = author_parent(args.dir) / name_to_id(args.id)[0]
            elif args.from_current:
                raise Problem("--from-current goes with --theme.")
            else:
                new(args.id, args.dir, args.hook, args.widget)
                made = Path(args.dir) / args.id
            if args.edit:
                edit_next(made, args.json)
        elif args.action == "developer":
            if args.mode == "on":
                DEVELOPER_FILE.parent.mkdir(parents=True, exist_ok=True)
                DEVELOPER_FILE.touch()
            elif args.mode == "off":
                DEVELOPER_FILE.unlink(missing_ok=True)
            print("Example add-ons are shown." if developer_mode() else "Example add-ons are hidden.")
        elif args.action == "clone":
            made = clone_satellite(args.id, args.new_name, args.dir, args.json)
            if args.edit:
                edit_next(made, args.json)
        elif args.action == "builtins":
            builtins_list(args.json)
        elif args.action == "bar-place":
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use an add-on id with lowercase letters, digits, and dashes.")
            place_bar_item(args.id, args.section, args.screens)
        elif args.action == "port":
            port_plugin(args.source, args.dir, args.json)
        elif args.action == "dev":
            return dev_run(args.dir, args.yes, args.once, args.seconds)
        elif args.action == "host":
            return host(args.seconds)
        elif args.action == "open-page":
            open_page(args.id)
        elif args.action == "open-panel":
            open_panel(args.id)
        elif args.action == "open-menu":
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use an add-on id with lowercase letters, digits, and dashes.")
            open_menu(args.id)
        elif args.action == "panel-host":
            return panel_host(args.id, args.lock_fd, args.mode)
        elif args.action == "open-overlay":
            open_panel(args.id, "overlay")
        elif args.action == "close-overlay":
            close_overlays()
        elif args.action == "page-host":
            return page_host(args.id, args.lock_fd)
        elif args.action == "search":
            found = search(args.words, args.kind)
            if args.json:
                print(json.dumps({"satellites": found}))
            else:
                for entry in found:
                    # "Included" alone reads as a state, not a place it came from (the same words as list)
                    where = "Made by Starchaser" if entry["review"] == "Included" else entry["review"]
                    state_words = ("is on" if entry["enabled"] else "is off") if entry["installed"] else "not installed"
                    print(f"{entry['name']} ({entry['id']}): {entry['summary']} {where}; {state_words}.")
                if not found:
                    print("No add-ons match those words.")
        elif args.action == "index":
            if args.use:
                use_index(args.use)
                return 0
            data = load_index(args.refresh)
            installed = {item["id"]: item for item in catalog()["satellites"]}
            data["entries"] = [listing(e, installed.get(e["id"])) for e in visible_entries(data["entries"])]
            data["updated_text"] = when(data["updated"])
            if args.json:
                print(json.dumps(data))
            else:
                print(f"{data['label']}: {data['where']}")
                if data["updated"]:
                    print(("Fetched " if data["source"] == "shared" else "Updated ") + when(data["updated"]) + ".")
                if data["signature_text"]:
                    print(data["signature_text"])
                for sid in data["switched_off"]:
                    print(f"{sid}: " + removal_sentence(next(e for e in data["entries"] if e["id"] == sid)))
                if data["notice"]:
                    print(data["notice"])
                shown = [e for e in data["entries"] if e["review"] != "Removed"]
                print(f"{plural(len(shown), 'add-on')} listed.")
        elif args.action == "updates":
            waiting, problems = update_targets(None, args.refresh)
            if args.json:
                for target in waiting:
                    if not target.get("to_version"):
                        try:
                            with staged_update(target) as (_stage, after, _summary):
                                target["to_version"] = after["version"]
                        except (Problem, OSError, ValueError) as ex:
                            problems.append(str(ex))
                print(json.dumps({"updates": waiting, "problems": problems}))
            else:
                for target in waiting:
                    print(f"{target['name']}: a newer version is waiting ({target['review']}).")
                for sentence in problems:
                    print(sentence)
                if not waiting and not problems:
                    print("Every add-on is up to date.")
        elif args.action == "update-info":
            data = update_info(args.id, args.refresh)
            if args.json:
                print(json.dumps(data))
            else:
                print(f"{data['name']}:")
                for line in data["summary"]:
                    print("  " + line)
        elif args.action == "update":
            update(args.id, args.commit, args.yes, args.refresh)
        elif args.action == "hook":
            hook(args.event, args.details, args.wait)
        elif args.action == "page-json":
            print(json.dumps(page_json(args.id)))
        elif args.action == "page-set":
            page_set(args.id, args.control, args.value)
        elif args.action == "page-run":
            page_run(args.id, args.control)
        elif args.action == "run-card":
            run_card(args.id, args.file_id)
        elif args.action == "click":
            if not ID_RE.fullmatch(args.id):
                raise Problem("Use an add-on id with lowercase letters, digits, and dashes.")
            click(args.id)
        else:
            if args.action == "bar-json":
                print(json.dumps([{"id": item["id"], "name": item["name"], "section": item["section"],
                                   "screens": item["screens"]} for item in bar_items()]))
            else:
                print(json.dumps({"menu-json": lambda: menu_rows(own_pages=True), "cards-json": cards, "theme-dirs": theme_dirs}[args.action]()))
    except (Problem, OSError, ValueError, RecursionError) as ex:
        message = str(ex) if isinstance(ex, Problem) else "The add-on files couldn't be changed."
        if getattr(args, "json", False) or args.action == "page-json":
            print(json.dumps({"ok": False, "errors": message, **({"help": ex.help} if getattr(ex, "help", "") else {})}))
        print(message, file=sys.stderr)
        if getattr(ex, "help", "") and not getattr(args, "json", False):    # Settings shows its own Read how
            print("Read how: " + doc_path(ex.help), file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
