#!/usr/bin/env python3
# summary: Check for updates and read update status.
"""starchaser updates: what Settings > Updates shows, read without root.

    starchaser updates state     JSON, fast and offline: the last check, plus this computer's facts (busy updating?,
                                 restore points, restart needed, settings files with a new version waiting, last
                                 update, update history)
    starchaser updates check     JSON: check now for updates to the system, Community recipes and Flathub apps, plus
                                 news since the last update; remembered for the state command
    starchaser updates restart-when-done  restart after the running install finishes (only when requested)
    starchaser updates startup-notice  announce the first-start result once
    starchaser updates release-notice  open this release's persistent updated screen
    starchaser updates installed-notes JSON: verified local release notes
    starchaser updates release-seen VERSION  acknowledge the version just shown
    starchaser updates history-detail TIME  JSON: the list from a known past update
    starchaser updates undo-preview JSON: Recovery's comparison with plain update names
    starchaser updates preflight JSON: battery and free space, before asking for a password
    starchaser updates power reboot|poweroff  install, then perform the requested power action
    starchaser updates notify    the daily timer: check, and send one notification per new set of updates
Installing updates asks for your password.
"""
# state: "settings files with a new version waiting" are .pacnew files; restore points are snapshots.
# check: official repos via checkupdates' private database, the AUR, Flatpak, and Arch news; cached to
# ~/.cache/starchaser/updates.json. Installing goes through
# `pkexec /usr/local/lib/starchaser/starchaser-admin-software update-run` (updater.py; starchaser-admin on older tools).
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime
from email.utils import parsedate_to_datetime
from html import escape
from html.parser import HTMLParser
from pathlib import Path

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

CACHE = Path.home() / ".cache/starchaser/updates.json"
NOTIFIED = Path.home() / ".cache/starchaser/updates-notified.json"
PACLOG = Path("/var/log/pacman.log")
# checkupdates' private copy of the package lists (the system's own are never synced by a check). Fixed here and handed
# to checkupdates, so the check and the targeted-install planner (starchaser software plan) read the same fresh copy.
DB = Path.home() / ".cache/starchaser/pacman-db"
NEWS = "https://archlinux.org/feeds/news/"
DEV = re.compile(r"-(git|svn|hg|bzr|darcs|nightly)$")
CORE = re.compile(r"^(linux(-[a-z0-9]+)*|linux-firmware.*|.*-ucode|nvidia.*|lib32-nvidia.*|mesa|lib32-mesa|vulkan-.*|"
                  r"systemd.*|glibc|lib32-glibc|gcc-libs|lib32-gcc-libs|pacman|pacman-contrib|archlinux-keyring|mkinitcpio|"
                  r"dracut|limine.*|grub|efibootmgr|cryptsetup|lvm2|btrfs-progs|filesystem|bash|coreutils|util-linux.*|"
                  r"openssl|sudo|polkit|dbus.*|networkmanager|wpa_supplicant|iwd|bluez.*|pipewire.*|wireplumber)$")
DESKTOP = re.compile(r"^(starchaser-.*|hypr.*|aquamarine|quickshell.*|qt6-.*|qt5-.*|gtk[34]?|gtk4|libadwaita|xdg-desktop-portal.*|"
                     r"wayland.*|xorg-xwayland|mako|kitty.*|squeekboard|.*-icon-theme|ttf-.*|noto-fonts.*|"
                     r"awww|swww|hypridle|hyprlock|wl-clipboard|grim|slurp|uwsm|greetd.*|libinput|libdrm|freetype2|"
                     r"fontconfig|harfbuzz|cairo|pango|glib2|gobject-introspection.*)$")
# The package-signing keys pacman checks (Starchaser uses Arch's repos and its own packages, so Arch's are the only
# ones): named, not "*-keyring", which also caught the saved-passwords service and filed it under the system core.
# Names people see in the list. A package name means little to someone new, and some carry another desktop's or
# distribution's name: those get a plain label (the table), and any other name with a brand in it gets its group's
# plain words. Package descriptions are a fallback only when they are brand-free. The raw names stay in the data (the
# update itself and Show details use them) and show beside the label only when they're brand-free.
LABELS = {
    "linux": "Kernel", "linux-lts": "Kernel (LTS)", "linux-zen": "Kernel (zen)", "linux-hardened": "Kernel (hardened)",
    # the boot menu's words for them (kernels.py): the restart card listed the package names (QA 20261104-2101 004)
    "linux-starchaser": "Starchaser kernel", "linux-starchaser-v3": "Starchaser kernel",
    "linux-starchaser-lts": "Starchaser LTS kernel",
    "linux-firmware": "Device firmware", "amd-ucode": "Processor fixes (AMD)", "intel-ucode": "Processor fixes (Intel)",
    "mesa": "Graphics drivers", "lib32-mesa": "Graphics drivers (32-bit apps)", "vulkan-radeon": "Graphics drivers (Vulkan)",
    "vulkan-intel": "Graphics drivers (Vulkan)", "nvidia": "Graphics drivers (NVIDIA)", "nvidia-open": "Graphics drivers (NVIDIA)",
    "nvidia-utils": "Graphics drivers (NVIDIA)", "systemd": "System startup and services", "systemd-libs": "System startup and services (shared parts)",
    "glibc": "Core system library", "pacman": "Package manager", "archlinux-keyring": "Package signing keys",
    "gnome-keyring": "Saved passwords", "libsecret": "Saved passwords (for apps)", "seahorse": "Passwords and keys",
    "adwaita-icon-theme": "Standard icons", "adwaita-cursors": "Mouse pointer shapes", "adwaita-fonts": "Standard fonts",
    "gsettings-desktop-schemas": "App settings", "gvfs": "File access for apps", "xdg-desktop-portal-gnome": "App permissions",
    "xdg-desktop-portal-gtk": "App permissions (file pickers)", "polkit-gnome": "Password prompts", "nautilus": "Files",
    "gnome-disk-utility": "Disks", "gnome-calculator": "Calculator", "gnome-text-editor": "Text Editor",
    "pipewire": "Sound and screen sharing", "wireplumber": "Sound and screen sharing", "networkmanager": "Networking",
    "bluez": "Bluetooth", "bluez-utils": "Bluetooth", "exfatprogs": "System tools", "cups": "Printing", "sunshine": "Remote desktop (Sunshine)",
    "at-spi2-core": "Accessibility support for apps", "atk": "Accessibility support for apps",
    "libatspi": "Accessibility support for apps", "orca": "Screen reader", "espeak-ng": "Speech for the screen reader",
    "imagemagick": "Picture tools", "ffmpeg": "Sound and video tools", "mpv": "Video player",
    "7zip": "Archive tools", "zip": "Create ZIP archives", "unzip": "Open ZIP archives",
    "curl": "Download tools", "wget": "Download tools", "rsync": "File copying tools",
    "perl-error": "Error handling for apps",
    "debugedit": "App debugging support", "sqlite": "Database support for apps",
    "xkeyboard-config": "Keyboard layouts", "hyprlock": "Screen lock",
    "onetbb": "Threading support for apps", "tbb": "Threading support for apps",
    "qt6-declarative": "App interface support", "harfbuzz": "Text display support",
    "fribidi": "Right-to-left text support", "poppler": "PDF display support", "poppler-glib": "PDF display support",
    "python": "Support for apps written in Python", "oniguruma": "Text matching support",
    "gnupg": "Encryption and signing tools", "luajit": "Scripting support for apps", "wayland-protocols": "Display system support",
    "gnome-maps": "Maps", "gnome-weather": "Weather", "gnome-clocks": "Clocks", "gnome-calendar": "Calendar",
    "gnome-contacts": "Contacts", "gnome-system-monitor": "System Monitor", "gnome-console": "Terminal",
    "gnome-font-viewer": "Fonts", "gnome-characters": "Characters", "gnome-logs": "Logs", "gnome-music": "Music",
    "gnome-photos": "Photos", "gnome-screenshot": "Screenshot", "gnome-control-center": "Settings",
    "gnome-shell": "Desktop shell", "gnome-session": "Desktop session", "gnome-settings-daemon": "Desktop settings service",
    "gnome-backgrounds": "Wallpapers", "gnome-online-accounts": "Online accounts", "gnome-autoar": "Archive support",
    "gnome-desktop": "Desktop library", "gnome-menus": "App menu data", "gnome-bluetooth-3.0": "Bluetooth settings",
    "plasma-workspace": "Desktop shell", "plasma-desktop": "Desktop", "kdeconnect": "Phone link",
    "gtk3": "App toolkit (version 3)", "gtk4": "App toolkit (version 4)", "libadwaita": "App toolkit (styles)",
    "glib2": "App toolkit (base library)",
    "loupe": "Image Viewer", "papers": "Document Viewer", "glycin": "Image loading",
    "tinysparql": "File search index", "localsearch": "File search index", "libnautilus-extension": "Files (add-on support)",
    "gsettings-system-schemas": "App settings", "libsysprof-capture": "Performance measuring (for apps)",
    "archlinux-appstream-data": "App listings", "pacman-mirrorlist": "Package server list",
    "appstream": "App store data", "appstream-glib": "App store data",
    "xdg-user-dirs": "Standard folders", "xdg-utils": "Open files and links", "shared-mime-info": "File types",
    "hicolor-icon-theme": "Standard icons", "desktop-file-utils": "App launcher entries",
    "libreoffice-fresh": "Office apps", "libreoffice-still": "Office apps", "flea": "Files", "thunar": "File manager", "kitty": "Terminal",
    "hyprland": "Desktop window manager", "hyprland-git": "Desktop window manager",
    "quickshell": "Desktop shell", "greetd": "Login screen", "sudo": "Administrator access",
    "linux-headers": "Kernel (for building drivers)", "linux-lts-headers": "Kernel (LTS, for building drivers)",
    "bpf": "Performance and network tools", "gpu-screen-recorder": "Screen recording",
    "tesseract": "Text recognition", "usbutils": "USB device tools",
    "strace": "Program debugging tools", "gperftools": "Memory and speed tools",
    "nmap": "Network discovery tools",
    "device-mapper": "Drive encryption and volume support",
    "cockpit": "Mission Control support", "mpv-mpris": "Media controls for the video player",
    "starchaser-keyring": "Package signing keys", "starchaser-desktop": "Starchaser Linux (desktop, Settings and tools)", "starchaser-starfield": "Starfield screensaver",
}
BRAND = re.compile(r"gnome|adwaita|kde|plasma|^kf[56]-|cachy|manjaro|endeavou?r|garuda|ubuntu|fedora|^xfce|^xfwm|"
                   r"^mate-|cinnamon|budgie|deepin|cosmic|archlinux|arch linux|^cockpit", re.I)
GROUP_WORDS = {"core": "System part", "desktop": "Desktop part", "apps": "App part", "aur": "Community recipes (AUR)",
               "flatpak": "Flatpak app", "held": "System part"}
# Flatpak runtimes and their add-ons: the shared support files apps run on (their own names carry brands)
RUNTIME = re.compile(r"\.(Platform|Sdk|BaseApp|GL|GL32|VAAPI|Codecs|ffmpeg-full|openh264)(\.|$)|^org\.freedesktop\.|"
                     r"\.Locale$|\.Debug$", re.I)


# what a package without a table entry is, from its name alone: every row gets plain words, and the package name
# shows beside them (muted) when it's brand-free, so whoever knows packages still sees exactly what updates
# linux-firmware comes in parts since 2025 (linux-firmware-amdgpu, -atheros...): the restart card listed each name
FIRMWARE = re.compile(r"-firmware$|^sof-firmware|^linux-firmware-")
KINDS = [(re.compile(r"^(gstreamer|gst-plugins?(-|$)|gst-libav$)"), "Media playback support"),
         # srt is a live-video streaming protocol library (r59 settings-software 004)
         (re.compile(r"^(srt|libsrt)$"), "Support for live video streaming"),
         # video formats ahead of "^lib": libvpx is a format, not a library anyone picks (r37 settings-software 005)
         (re.compile(r"^(aom|dav1d|x264|x265|libvpx|svt-av1|rav1e|libde265|openh264)$"), "Video format support"),
         (re.compile(r"^(ttf|otf|noto-fonts|adobe-source)-|-fonts?$"), "Fonts"),
         (re.compile(r"-icon-theme$|-icons$"), "Icons"),
         (FIRMWARE, "Device firmware"),
         (re.compile(r"^(python|python2|perl|ruby|lua\d*|nodejs|php|java|ocaml|haskell|rust|go)-"), "Programming language add-on"),
         (re.compile(r"-(i18n|l10n|langpacks?)(-|$)|-locales?$"), "Translations"),
         (re.compile(r"^lib(?!re)|-libs?$|-runtime$"), "Shared library"),
         (re.compile(r"-(data|schemas|common|docs?|headers)$"), "Support files"),
         (re.compile(r"-(utils|tools|progs)$"), "System tools")]


GENERIC = {w for _, w in KINDS} | set(GROUP_WORDS.values())
# Background parts: pieces apps use rather than anything a person picks or would recognize (libraries, translations,
# support files, the system core's unnamed "System part"s). Settings > Updates folds them into one "N background
# parts" row per group (decided 2026-10-07). Fonts, icons, firmware, tools, anything that needs a restart, and an
# unnamed desktop or app package ("App part": it may well be an app, such as VLC) stay listed.
BACKGROUND = {"Shared library", "Translations", "Support files", "Programming language add-on",
              "Media playback support", "Video format support", "Support for live video streaming", "Text matching support",
              "Threading support for apps",
              "Accessibility support for apps", "Shared support files for Flatpak apps", "Translations for Flatpak apps",
              "App interface support", "Text display support", "Right-to-left text support", "PDF display support", "Error handling for apps",
              "Scripting support for apps", "Display system support"}


def app_names(names) -> dict:
    """{package: its app's own name}, from the launcher entries the installed packages ship ("speedcrunch" ->
    "SpeedCrunch", the name Software and Recovery show). One pacman call for the lot; only entries people see (no
    NoDisplay), and only a package with exactly one such app (a suite's several apps don't name the package)."""
    names = [n for n in names if n not in LABELS]
    if not names:
        return {}
    found = {}
    for l in sh("pacman", "-Ql", "--", *names).stdout.splitlines():
        pkg, _, path = l.partition(" ")
        if not (path.startswith("/usr/share/applications/") and path.endswith(".desktop")):
            continue
        try:
            text = Path(path).read_text(errors="replace")
        except OSError:
            continue
        entry = text.split("[Desktop Entry]", 1)[-1].split("\n[", 1)[0]
        if re.search(r"^NoDisplay\s*=\s*true", entry, re.M | re.I) or re.search(r"^Hidden\s*=\s*true", entry, re.M | re.I):
            continue
        m = re.search(r"^Name\s*=\s*(.+)$", entry, re.M)
        if m:
            found.setdefault(pkg, []).append(m.group(1).strip())
    return {k: v[0] for k, v in found.items() if len(v) == 1 and not BRAND.search(v[0])}


APPS = {}           # app_names() for the list being labeled (filled by check and state)
DESCRIPTIONS = {}    # installed package descriptions, read offline in one batch


def load_labels(updates: list) -> None:
    names = list(dict.fromkeys(u.get("name", "") for u in updates
                              if u.get("category") in ("apps", "desktop", "aur", "held")))
    APPS.clear()
    APPS.update(app_names(names))
    DESCRIPTIONS.clear()
    names = [n for n in names if n and n not in LABELS and n not in APPS]
    if not names:
        return
    for block in sh("pacman", "-Qi", "--", *names).stdout.split("\n\n"):
        name = re.search(r"^Name\s*:\s*(\S+)", block, re.M)
        desc = re.search(r"^Description[ \t]*:[ \t]*(\S[^\n]*(?:\n[ \t]+\S[^\n]*)*)", block, re.M)
        if not name or not desc:
            continue
        words = " ".join(desc.group(1).split())
        # Descriptions are upstream text too: never expose other desktop brands or markup.
        if words and words != "None" and not BRAND.search(words) and not re.search(r"[<>]|\b(?:xfce|xfwm|mate|cockpit)\b", words, re.I):
            DESCRIPTIONS[name.group(1)] = words


def label(name: str, cat: str, ident: str = "") -> str:
    """The plain words a row shows: the table, then (for a Flatpak) the app's own name, then an installed app's own
    name (its launcher's), then what kind of thing the package name says it is, then a safe description
    or the group's words. A Flatpak
    update passes its app name as name, its id as ident."""
    if name in LABELS and not BRAND.search(LABELS[name]):         # a table entry that names a brand never shows
        return LABELS[name]
    if cat in ("apps", "desktop", "aur") and APPS.get(name):
        return APPS[name]
    if cat == "flatpak":
        if re.search(r"\.Locale$", ident or name):
            return "Translations for Flatpak apps"
        if RUNTIME.search(ident or name):
            return "Shared support files for Flatpak apps"
        return GROUP_WORDS["flatpak"] if BRAND.search(name) else name   # its app name: already plain words
    for rx, words in KINDS:
        if rx.search(name):
            return words
    return GROUP_WORDS.get(cat, "System part")



def reboot_label(name: str) -> str:
    """What the Restart to finish card calls a part waiting for a restart: the table's words, firmware as one kind."""
    return LABELS.get(name) or ("Device firmware" if FIRMWARE.search(name) else name)


def labeled(u: dict) -> dict:
    """Adds "label" (what the row says) and "showName" (the package name may show beside it: brand-free and different)."""

    def field(key):                             # a hand-edited cache row may hold another type: never a traceback
        value = u.get(key, "")
        return value if isinstance(value, str) else ""

    raw, cat, ident = field("name"), field("category"), field("id")
    lab = label(raw, cat, ident)
    show = lab != raw and not BRAND.search(raw) and not BRAND.search(ident)
    # "generic": the label only says what kind of thing it is ("Shared library"), so many rows share it; the page then
    # puts the package name first and the kind after it, muted, so narrow rows can still be told apart
    # "background": folded on the page (see BACKGROUND); an AUR package was chosen by hand, so it always shows
    bg = ((lab in BACKGROUND or lab == GROUP_WORDS.get(cat))
          and cat not in ("aur", "held") and not REBOOT.match(raw))
    # "restart": takes effect only after a restart (a kernel, drivers, systemd): the page says so before Update now
    return {**u, "description": DESCRIPTIONS.get(raw, ""), "label": lab, "showName": show, "generic": show and lab in GENERIC, "background": bg,
            "restart": cat != "flatpak" and bool(REBOOT.match(raw))}


def dev_labels(dev: list) -> dict:
    """Development packages aren't checked; the page names the brand-free ones (so the reader knows what to rebuild)
    and counts the rest. A cache from before this held labels in "dev": those group words are only counted."""
    named = sorted({n for n in dev if not BRAND.search(n) and n not in GROUP_WORDS.values()})
    return {"devLabels": named, "devOthers": len(dev) - len(named)}


REBOOT = re.compile(r"^(linux(-[a-z0-9]+)*|linux-firmware.*|nvidia.*|amd-ucode|intel-ucode|systemd|systemd-libs|glibc|mesa|"
                    r"lib32-mesa)$")


def sh(*cmd, timeout=120) -> subprocess.CompletedProcess:
    if (cmd and cmd[0] == 'pacman' and '--dbpath' in cmd and str(DB) in cmd and tested_releases.enabled()
            and (DB / 'tested-pacman.conf').is_file()):
        cmd = (cmd[0], '--config', str(DB / 'tested-pacman.conf'), *cmd[1:])
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, env={**os.environ, "LANG": "C.UTF-8"})
    except (OSError, subprocess.TimeoutExpired) as e:
        return subprocess.CompletedProcess(cmd, 1, "", str(e))


def jread(p: Path, default):
    try:
        data = json.loads(p.read_text())
    except (OSError, ValueError, RecursionError):
        return default
    return data if isinstance(data, dict) else default


def jwrite(p: Path, data) -> None:
    """Write JSON whole or not at all (never half a file): a per-process temp file next to p, fsynced, renamed over p."""
    p.parent.mkdir(parents=True, exist_ok=True)
    tmp = p.with_name(f".{p.name}.{os.getpid()}.tmp")
    with open(tmp, "w") as f:
        f.write(json.dumps(data))
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, p)


def locked_checkupdates(timeout=180):
    """checkupdates into DB (no -n: that skips the download), one run at a time with Software's planner, which uses
    the same copy (starchaser software plan): two at once made the second fail on that copy's lock, which read as
    "couldn't reach". None when the wait for the other run ran out. A good run touches DB/synced, the date Software's
    planner reads to skip a second refresh."""
    import fcntl
    DB.mkdir(parents=True, exist_ok=True)
    with open(DB.parent / "pacman-db.lock", "a") as lk:
        end = time.time() + timeout
        while True:
            try:
                fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except BlockingIOError:
                if time.time() > end:
                    return None
                time.sleep(0.5)
        try:
            r = subprocess.run(["checkupdates"], capture_output=True, text=True, timeout=timeout,
                               env={**os.environ, "LANG": "C.UTF-8", "CHECKUPDATES_DB": str(DB)})
        except (OSError, subprocess.TimeoutExpired) as e:
            return subprocess.CompletedProcess(["checkupdates"], 1, "", str(e))
        if r.returncode in (0, 2):                     # 2: up to date
            (DB / "synced").touch()
        elif r.returncode == 1 and shutil.which("fakeroot"):
            # checkupdates throws pacman's own words away ("Cannot fetch updates"): ask pacman again, the same way and
            # under the same lock, for which source failed and why
            try:
                p = subprocess.run(["fakeroot", "--", "pacman", "-Sy", "--dbpath", str(DB), "--logfile", "/dev/null"],
                                   capture_output=True, text=True, timeout=timeout, env={**os.environ, "LANG": "C.UTF-8"})
                if p.returncode != 0 and p.stderr.strip():
                    r.stderr = p.stderr
            except (OSError, subprocess.TimeoutExpired):
                pass
        return r


# The sources Starchaser sets up in pacman.conf: when one of them fails, it's Starchaser's main software source
OWN_SOURCES = {"core", "extra", "multilib", "core-testing", "extra-testing", "multilib-testing", "starchaser",
               "starchaser-testing"}


def failed_source(stderr: str) -> tuple:
    """(the Updates error, pacman's own error lines for Show details) for a check that couldn't fetch the lists. A
    source someone added themselves is named, not blamed on Starchaser's (QA 20261107-1549 004)."""
    lines = [l.strip() for l in stderr.splitlines() if l.strip().lower().startswith(("error:", "==> error:"))][:6]
    names = []
    for m in re.finditer(r"failed retrieving file '([^']+?)\.db'|failed to update (\S+)|database file for '([^']+)'", stderr):
        name = next(g for g in m.groups() if g)
        if name not in names:
            names.append(name)
    others = [n for n in names if n not in OWN_SOURCES]
    if others and len(others) == len(names):
        which = ", ".join(f"\u201c{n}\u201d" for n in others)
        return f"Couldn't reach the {which} software source{'s' if len(others) > 1 else ''} in pacman.conf", "\n".join(lines)
    return "Couldn't reach Starchaser's main software source", "\n".join(lines)


def category(name: str) -> str:
    return "core" if CORE.match(name) else "desktop" if DESKTOP.match(name) else "apps"


def installed() -> dict:
    return dict(l.split(" ", 1) for l in sh("pacman", "-Q").stdout.splitlines() if " " in l)


def current_pending(cache: dict, local: dict) -> dict:
    """Read a cached plan against today's installed versions, without another online check or a cache write."""
    def waiting(row):
        if not isinstance(row, dict) or row.get("category") == "flatpak":
            return True
        name, target = row.get("name"), row.get("new")
        if not isinstance(name, str) or not isinstance(target, str):
            return True
        have = local.get(name)
        if have == row.get("old") and have != target:
            return True
        return not (have and target and (have == target or sh("vercmp", have, target).stdout.strip() in ("0", "1")))

    current = dict(cache)
    for key in ("updates", "held", "deferred"):
        if isinstance(cache.get(key), list):
            current[key] = [row for row in cache[key] if waiting(row)]
    if current.get("updates") != cache.get("updates"):
        current["download"] = sum(row["size"] for row in current["updates"]
                                  if isinstance(row, dict) and type(row.get("size")) is int and row["size"] > 0)
    return current


def ignored() -> set:
    return set(sh("pacman-conf", "IgnorePkg").stdout.split())


def held_back(local: dict) -> list:
    """The updates pacman.conf holds back (IgnorePkg, IgnoreGroup). checkupdates drops its "[ignored]" lines (it filters
    out every line with brackets), so they are worked out here: what `pacman -Qu` against checkupdates' fresh lists
    marks [ignored], plus any upgradable package whose name matches IgnorePkg (globs allowed) or is in an IgnoreGroup."""
    import fnmatch
    pats = set(sh("pacman-conf", "IgnorePkg").stdout.split())
    groups = sh("pacman-conf", "IgnoreGroup").stdout.split()
    members = set(sh("pacman", "-Sgq", "--dbpath", str(DB), *groups).stdout.split()) if groups else set()
    members |= set(sh("pacman", "-Qgq", *groups).stdout.split()) if groups else set()
    held = []
    for l in sh("pacman", "-Qu", "--dbpath", str(DB)).stdout.splitlines():   # "kitty 0.46-1 -> 0.47-1 [ignored]"
        f = l.split()
        if len(f) < 4 or f[2] != "->":
            continue
        if "[ignored]" in l or f[0] in members or any(fnmatch.fnmatchcase(f[0], p) for p in pats):
            held.append({"name": f[0], "old": local.get(f[0], f[1]), "new": f[3], "repo": "", "size": 0,
                         "category": "held"})
    return held


# ---------------------------------------------------------------------------------------------- the check
def repo_updates(local: dict) -> tuple:
    """([update], [held], error, pacman's words for that error) from checkupdates' own copy of the databases (never
    the system's)."""
    if not shutil.which("checkupdates"):                              # pacman-contrib
        return [], [], "Couldn't check the main software source: part of the update checker is missing", ""
    r = locked_checkupdates()                                         # downloads fresh lists into DB
    if r is None:
        return [], [], "Another check for updates is running. Try again in a moment", ""
    if r.returncode == 1:
        return [], [], *failed_source(r.stderr or "")
    held = held_back(local)
    # what `pacman -Syu` would actually do (new dependencies included), with download sizes
    pr = sh("pacman", "-Sup", "--dbpath", str(DB), "--print-format", "%r|%n|%v|%s")
    if pr.returncode != 0:
        # pacman couldn't work out the update (a conflict, a broken list): never an empty, finished-looking answer
        return [], held, "Couldn't work out which system updates are waiting", pr.stderr.strip()
    ups = []
    for l in pr.stdout.splitlines():
        f = l.split("|")
        if len(f) != 4:
            continue
        ups.append({"name": f[1], "old": local.get(f[1], ""), "new": f[2], "repo": f[0], "size": int(f[3] or 0),
                    "category": category(f[1])})
    guard_error = desktop_update_error([(u["name"], u["old"], u["new"]) for u in ups])
    if guard_error:
        # A checked update waiting for our desktop build is different from an unreachable source.
        return [], held + [{**u, "category": "held", "deferred": True} for u in ups], guard_error, ""
    return ups, held, "", ""


def planned_kernels(local: dict, ups: list) -> list:
    """The Starchaser kernels Update now adds after the official updates (updater.add_kernels, decided 2026-11-02 #8),
    as rows with their restart, so the list and its restart line say so before Update now (QA 20261105-2101 005:
    "1 update available", then three packages installed and a restart). Same choice as add_kernels, from DB."""
    try:
        import kernels
        from updater import KERNELS_STATE
    except ImportError:
        return []
    if (KERNELS_STATE / "added.json").exists():
        return []
    available = set()
    for channel in ("starchaser-testing", "starchaser"):
        r = sh("pacman", "-Slq", "--dbpath", str(DB), channel)
        if r.returncode == 0:
            available |= set(r.stdout.split())
    targets = kernels.added_kernels(available, set(local), kernels.supports_v3()) if available else []
    try:
        if not targets or kernels.boot_free(targets) < kernels.BOOT_ROOM:
            return []                                    # add_kernels skips it then too (with a note)
    except OSError:
        return []
    pr = sh("pacman", "-Sp", "--needed", "--dbpath", str(DB), "--print-format", "%r|%n|%v|%s", "--", *targets)
    if pr.returncode != 0:
        return []
    listed = {u["name"] for u in ups}
    rows = []
    for l in pr.stdout.splitlines():
        f = l.split("|")
        # "added": nothing here is replaced, so the page counts these apart from the updates (QA 20261107-0414 002)
        if len(f) == 4 and f[1] not in listed:
            rows.append({"name": f[1], "old": local.get(f[1], ""), "new": f[2], "repo": f[0], "size": int(f[3] or 0),
                         "category": category(f[1]), "added": True})
    return rows




AUR_BATCH = 100


def foreign_names() -> list:
    """The packages in no package list (`pacman -Qm`), none while a source in pacman.conf has no list: then every
    package from that source looks foreign, and a fresh install once called all 970 Community recipes (P1-1)."""
    import package_lists
    out = package_lists.foreign(lambda *cmd: sh(*cmd).stdout)
    return [l.split()[0] for l in out.splitlines() if l.strip()]


def aur_updates(local: dict, skip: set) -> tuple:
    """([update], [dev packages not checked], error): foreign packages with a newer version in the AUR. The error is
    None when there was nothing to ask the AUR about (it isn't a source then), "" when it answered."""
    foreign = foreign_names()
    # Starchaser's own packages are foreign to pacman (built here, from the Starchaser repo) but never the AUR's: an AUR
    # package that happens to share the name would otherwise read as their update and be built and installed as root
    foreign = [n for n in foreign if not n.endswith("-debug") and n not in skip and not starchaser_own(n)]
    dev = [n for n in foreign if DEV.search(n)]
    names = [n for n in foreign if n not in dev]
    if not names:
        return [], dev, None
    res = []
    try:
        # 100 names a request, as the automatic updates ask (updater.aur_pending): one address with every name in it
        # is too long for the AUR, and a fresh install once sent 963 that way (P1-1)
        for start in range(0, len(names), AUR_BATCH):
            q = urllib.parse.urlencode([("arg[]", n) for n in names[start:start + AUR_BATCH]])  # a + or & stays in its name
            with urllib.request.urlopen(f"https://aur.archlinux.org/rpc/v5/info?{q}", timeout=20) as r:
                res += json.load(r).get("results", [])
    except Exception:
        return [], dev, "Couldn't reach Community recipes"
    ups = []
    for x in res:
        old = local.get(x["Name"], "")
        if old and sh("vercmp", x["Version"], old).stdout.strip() == "1":
            ups.append({"name": x["Name"], "old": old, "new": x["Version"], "repo": "aur", "size": 0, "category": "aur",
                        "outOfDate": bool(x.get("OutOfDate"))})
    return ups, dev, ""


def aur_installed(skip: set) -> list:
    """Plain names of the community-recipe (AUR) apps installed here, for the Updates note that they only update by
    hand unless the automatic level includes them. Same filter as aur_updates: Starchaser's own packages aren't the AUR's."""
    foreign = foreign_names()
    names = [n for n in foreign if not n.endswith("-debug") and n not in skip and not starchaser_own(n)]
    apps = app_names(names)
    return sorted({LABELS.get(n) or apps.get(n) or n for n in names}, key=str.lower)


def flatpak_updates() -> tuple:
    """([update], tried, error, answered): tried = some Flatpak install here has a remote to ask (else Flatpak isn't a
    source), or its remotes couldn't be listed; answered = at least one install (system or user) was checked."""
    if not shutil.which("flatpak"):
        return [], False, "", False
    ups, tried, failed, answered = [], False, False, False
    for scope in ("--system", "--user"):
        rem = sh("flatpak", "remotes", scope, "--columns=name")
        if rem.returncode != 0:                                        # couldn't even list remotes: a failure, not "none"
            tried = failed = True
            continue
        if not rem.stdout.strip():
            continue
        tried = True
        cur, names = {}, {}
        lst = sh("flatpak", "list", scope, "--columns=application,version,name")
        # nothing at all installed in this scope (apps or runtimes: no --app): nothing can update, and asking the
        # remote would download its whole listing first (about a minute the first time). A list that failed still asks.
        if lst.returncode == 0 and not lst.stdout.strip():
            answered = True
            continue
        for l in lst.stdout.splitlines():
            f = l.split("\t")
            cur[f[0]] = f[1] if len(f) > 1 else ""
            names[f[0]] = f[2] if len(f) > 2 else ""
        r = sh("flatpak", "remote-ls", scope, "--updates", "--columns=application,version,name")
        if r.returncode != 0:
            failed = True
            continue
        answered = True
        for l in r.stdout.splitlines():
            f = l.split("\t")
            if f and f[0]:
                # the installed app's own name first: Flathub's listing can fall back to the id's last part
                # ("ungoogled_chromium") when its app data isn't loaded
                remote = f[2] if len(f) > 2 else ""
                name = names.get(f[0]) or (remote if remote and remote != f[0].rsplit(".", 1)[-1] else "") \
                    or remote or f[0]
                ups.append({"name": name, "id": f[0], "old": cur.get(f[0], ""),
                            "new": f[1] if len(f) > 1 else "", "repo": "flatpak", "size": 0, "category": "flatpak"})
    return ups, tried, "Couldn't reach Flathub" if failed else "", answered


class NewsText(HTMLParser):
    """Keep plain text for old readers and a small, escaped subset for titled links in Settings."""
    tags = {"p": "p", "div": "p", "pre": "pre", "li": "li", "ul": "ul", "ol": "ol", "br": "br",
            "h1": "p", "h2": "p", "h3": "p", "code": "code", "strong": "b", "em": "i"}

    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.parts = []
        self.pre = False
        self.hidden = 0
        self.link = ""
        self.rich = []

    def handle_starttag(self, tag, attrs):
        if tag in ("script", "style"):
            self.hidden += 1
        if self.hidden:
            return
        if tag in self.tags:
            self.rich.append("<" + self.tags[tag] + ">")
        if tag in ("p", "div", "pre", "li", "br", "h1", "h2", "h3"):
            self.parts.append("\n")
        if tag == "pre":
            self.pre = True
        if tag == "li":
            self.parts.append("• ")
        if tag == "a":
            url = dict(attrs).get("href") or ""
            self.link = url if url.startswith(("https://", "http://")) else ""
            if self.link:
                self.rich.append('<a href="' + escape(self.link, quote=True) + '">')

    def handle_endtag(self, tag):
        if tag in ("script", "style"):
            self.hidden = max(0, self.hidden - 1)
        if self.hidden:
            return
        if tag in self.tags and tag != "br":
            self.rich.append("</" + self.tags[tag] + ">")
        if tag == "a" and self.link:
            self.parts.append(" (" + self.link + ")")
            self.rich.append("</a>")
            self.link = ""
        if tag in ("p", "div", "pre", "li", "h1", "h2", "h3"):
            self.parts.append("\n")
        if tag == "pre":
            self.pre = False

    def handle_data(self, text):
        if not self.hidden:
            self.parts.append(text if self.pre else re.sub(r"\s+", " ", text))
            self.rich.append(escape(text))

    def text(self):
        return re.sub(r"\n[ \t]*\n(?:[ \t]*\n)+", "\n\n", "".join(self.parts)).strip()


def news(since: float) -> tuple:
    """([item], error): Arch news posted since the last full update; the "manual intervention" ones are the reason to
    read first. The error says the feed couldn't load, so the page doesn't mistake that for "no news"."""
    try:
        req = urllib.request.Request(NEWS, headers={"User-Agent": "starchaser-updates/1"})
        with urllib.request.urlopen(req, timeout=15) as r:
            root = ET.fromstring(r.read())
    except Exception as e:
        # Keep the exact exception in the journal so "Details" can be checked later.
        failure = f"starchaser updates: news feed failed: {type(e).__name__}: {str(e)[:200]}"
        reason = news_error(e)
        print(f"Couldn't load the update news: {reason}. Package update results are still available.", file=sys.stderr)
        try:
            subprocess.run(["logger", "-t", "starchaser-updates", "--", failure],
                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2, check=False)
        except Exception:
            pass                                                       # journal logging is best effort
        return [], reason
    out = []
    for it in root.iter("item"):
        try:
            t = parsedate_to_datetime(it.findtext("pubDate")).timestamp()
        except (TypeError, ValueError):
            continue
        if t <= since:
            continue
        title = it.findtext("title") or ""
        reader = NewsText()
        reader.feed(it.findtext("description") or "")
        body = reader.text()
        out.append({"title": title, "link": it.findtext("link") or "", "time": int(t), "body": body,
                    "bodyHtml": "".join(reader.rich),
                    "manual": bool(re.search(r"manual intervention|requires? manual|action required", title + " " + body, re.I))})
    return out, ""


# Match reviewed notices by their exact source URL, never by package-like words in arbitrary prose.
# The fixed versions come from these notices and their linked security advisories.
NEWS_RULES = {
    "update-to-php-8512-andor-php-legacy-8336-to-prevent-remote-code-execution": (
        {"php": "8.5.12-1", "php-legacy": "8.3.36-1"}, "PHP (software used to run websites)"),
    "update-to-ca-certificates-mozilla-31311-1-to-prevent-man-in-the-middle-attacks": (
        {"ca-certificates-mozilla": "3.131.1-1"}, "the website security certificate list"),
    "mkinitcpio-42-requires-manual-intervention-for-tpm2-based-unlocking-of-luks-devices": (
        {"mkinitcpio": ""}, "the startup tool described in this notice"),
    "virtualbox-ext-vnc-7212-2-requires-manual-intervention": (
        {"virtualbox-ext-vnc": ""}, "the remote display add-on described in this notice"),
}


def news_relevance(item: dict, local: dict | None) -> dict:
    """Package presence/version can settle a reviewed notice; configuration-dependent ones stay uncertain.
    Recompute against today's installed packages, including for saved/offline notices."""
    unknown = "We can't tell whether this notice applies to this computer. Read the details before following its instructions."
    url = item.get("link", "")
    prefix = "https://archlinux.org/news/"
    slug = url[len(prefix):].strip("/") if url.startswith(prefix) else ""
    # Reviewed announcement: project leadership, with no software or setup changes.
    # Do not infer this from the absence of "manual intervention" in other news.
    if slug == "arch-linux-2026-leader-election-results":
        return {**item, "applicability": "informational",
                "summary": "For your information: this announces the project's leadership election result. No changes to this computer are needed."}
    rule = NEWS_RULES.get(slug)
    status, summary = "unknown", unknown
    if rule and local is not None:
        packages, label = rule
        present = {p: fixed for p, fixed in packages.items() if p in local}
        if not present:
            status, summary = "not-installed", f"This notice doesn't apply to this computer: {label} is not installed. No action is needed for this notice."
        elif all(present.values()):
            comparisons = [sh("vercmp", local[p], fixed).stdout.strip() for p, fixed in present.items()]
            if all(c in ("0", "1") for c in comparisons):
                status, summary = "fixed", "Already fixed on this computer. The installed software includes this security fix. No action is needed for this notice."
            elif "-1" in comparisons:
                status, summary = "affected", "This computer has software that needs this security fix. Choose Check now, then Update now. If it is held back, allow it to update first."
                if "php" in present or "php-legacy" in present:
                    summary += " If you use this computer to run a website, restart it after updating so the website uses the fix."
        elif "mkinitcpio" in present:
            summary = "This notice only applies if you set up encrypted drives to unlock automatically with this computer's security chip. We can't check that setup here. If you aren't sure, ask the person who set up drive encryption to check this notice with you before updating. If you use automatic unlocking, read the details first; installing updates alone doesn't complete the manual step. If you don't use it, no manual step is needed for this notice."
    return {**item, "applicability": status, "summary": summary}


def refresh_news(c: dict, local: dict | None) -> None:
    # Ignore old feed caches on upgrade, including while offline.
    c.update(news=[], newsArchive=[], newsError='', newsCached=False)


def news_error(e: Exception) -> str:
    """Why the news didn't load, in a few words the page shows (it doesn't claim the internet is down: other sites
    may well answer)."""
    import ssl
    import urllib.error
    if isinstance(e, urllib.error.HTTPError):
        return f"The news site answered with an error ({e.code})"
    if isinstance(e, ET.ParseError):
        return "The news site sent something Settings couldn't read"
    why = e.reason if isinstance(e, urllib.error.URLError) else e
    if isinstance(why, ssl.SSLCertVerificationError):
        return "The news site's security certificate wasn't accepted"
    if isinstance(why, ssl.SSLError):
        # seen in the VMs and on the host: archlinux.org drops the secure handshake (a network/site block, not our page)
        return "Couldn't connect to the news site"
    if isinstance(why, (TimeoutError, socket.timeout)):
        return "The news site took too long to answer"
    if isinstance(why, socket.gaierror):
        return "Couldn't find the news site's address"
    if isinstance(e, (urllib.error.URLError, ConnectionError, OSError)):
        return "Couldn't reach the news site"
    return "Couldn't load the update news"


def install_time() -> float:
    """When this computer was set up: the first line of pacman.log (0 when it can't be read)."""
    try:
        with PACLOG.open(errors="replace") as f:
            m = re.match(r"\[([^\]]+)\]", f.readline())
        return datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp() if m else 0
    except (OSError, ValueError):
        return 0


def news_since(last_upgrade: float) -> float:
    """With no full update yet (a fresh install), the last update would be "the beginning of time" and every post in the
    feed, years-old manual steps included, would show as new. Use the install time instead, and never more than 60 days."""
    if last_upgrade:
        return last_upgrade
    return max(install_time(), time.time() - 60 * 86400)


def sunshine_updates(local: dict) -> tuple:
    if "sunshine" not in local:
        return [], ""
    result = sh("starchaser", "sunshine", "status", timeout=30)
    try:
        state = json.loads(result.stdout)
        have, latest = state["installed"], state["latest"]
        if result.returncode or not have or not latest:
            raise ValueError("no release answer")
    except (ValueError, KeyError, TypeError):
        return [], "Couldn't check the remote desktop update. Check the internet connection and try again."
    if sh("vercmp", have, latest).stdout.strip() in ("0", "1"):
        return [], ""
    return [{"name": "sunshine", "old": have, "new": latest, "repo": "sunshine", "size": 0, "category": "apps"}], ""


def available_notice_body(result: dict, manual: list) -> str:
    if manual:
        return "There's a notice to read before updating."
    security = any(n.get("applicability") == "affected" and "security fix" in n.get("summary", "").lower()
                   for n in result.get("newsArchive", result.get("news", [])))
    return "Includes security fixes." if security else ""


def check() -> dict:
    local = installed()
    skip = ignored()
    tested = tested_releases.enabled()
    release_info = {}
    def system_updates():
        if not tested:
            return repo_updates(local)
        ups, held, err, detail, info = tested_releases.check_updates(Path('/etc/pacman.conf').read_text(), local, DB)
        release_info.update(info)
        for update in ups:
            update['category'] = category(update['name'])
        return ups, held, err, detail
    # the sources answer at the same time, not one after another: the slowest (often Flathub) sets the wait alone
    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(5) as ex:
        r_repo = ex.submit(system_updates)
        r_aur = ex.submit(aur_updates, local, set(skip) | {"sunshine"})
        r_sunshine = ex.submit(sunshine_updates, local)
        r_flat = ex.submit(flatpak_updates)
        since = news_since(last_upgrade(paclog_runs()))
        r_news = ex.submit(lambda: ([], ''))
        ups, held, err, err_detail = r_repo.result()
        if not err and not release_info.get('waiting'):
            ups = ups + planned_kernels(local, ups)
        aur, dev, aerr = r_aur.result()
        flat, _, ferr, fanswered = r_flat.result()
        items, nerr = r_news.result()
        sunshine, serr = r_sunshine.result()
        ups = [u for u in ups if u["name"] != "sunshine"] + sunshine
    deferred = [u for u in held if u.get("deferred")]
    held = [u for u in held if not u.get("deferred")]
    system_hold = err if deferred else ""
    if system_hold:
        err = ""
    # read after the sources answer, not before: an install that finished during the check is no longer "running"
    facts = system_facts()
    errors = [e for e in (err, aerr, ferr, serr) if e]
    now = int(time.time())
    # "Checked just now" is only said of a check that reached every source; the page says when that last happened
    prev = jread(CACHE, {})
    # Keep the full feed for the reader, including offline. Only posts after the cutoff become update warnings:
    # an older manual step must not come back as current just because someone opens the archive.
    news_cached = False
    if nerr and not items:
        items = [n for n in (prev.get("newsArchive") or prev.get("news") or []) if isinstance(n, dict)]
        news_cached = bool(items)
    good = now if not errors else prev.get("lastGood") or (prev.get("checked", 0) if prev and not prev.get("errors") else 0)
    items = [news_relevance(n, local or None) for n in items]
    load_labels(ups + aur + held + deferred)
    res = {"checked": now, "lastGood": good, "updates": [labeled(u) for u in ups + aur + flat],
           "flatpakUnchecked": bool(ferr),
           "deferred": [labeled(u) for u in deferred], "systemHold": system_hold,
           # the hold can only end by switching to Starchaser's packages: Updates offers that switch as a button
           "holdSwitch": bool(system_hold) and not starchaser_source(),
           "held": [labeled(u) for u in held], "dev": dev, **dev_labels(dev),
           "errors": errors,
           # the system check's own error: the welcome holds apps back only for this one, not for the AUR or Flathub
           "systemError": err,
           # pacman's own words for a failed check, under that error's Show details
           "errorDetails": {err: err_detail} if err and err_detail else {},
           "allFailed": bool(errors) and err != "" and aerr != "" and not fanswered, "news": [n for n in items if n.get("time", 0) > since], "newsError": nerr,
           "newsArchive": items,
           "newsCached": news_cached,
           "aurApps": aur_installed(skip),
           # the ones "System and app updates" leaves out: it updates Starchaser's recommended recipes (Brave Origin)
           "aurAppsOther": aur_installed({*skip, *RECOMMENDED_RECIPES}),
           "download": sum(u["size"] for u in ups)}
    res.update(testedReleases=tested, release=release_info)
    jwrite(CACHE, res)
    return {**res, **facts}


# ---------------------------------------------------------------------------------------------- facts
def paclog_runs(limit=8) -> list:
    """Recent full updates from pacman.log: when, how many packages, whether they finished."""
    runs, cur, sub = [], None, None
    try:
        lines = PACLOG.read_text(errors="replace").splitlines()[-30000:]
    except OSError:
        return []
    for l in lines:
        m = re.match(r"\[([^\]]+)\] \[(\w+)\] (.*)", l)
        if not m:
            continue
        ts, src, msg = m.groups()
        if src == "PACMAN" and msg.startswith("starting full system upgrade"):
            if cur:
                runs.append(cur)
            try:
                t = datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
            except ValueError:
                t = 0
            cur = {"time": int(t), "count": 0, "ok": False, "packages": []}
            sub = None
        elif cur and src == "PACMAN" and msg.startswith("Running "):
            # after the upgrade itself, a later install (Software's, minutes or days on) is not part of it. Only an
            # update's own AUR step follows it: those transactions count when they only upgrade, within 3 hours
            if "-S" not in msg and "-U" not in msg or not cur["ok"]:
                runs.append(cur)
                cur = None
            else:
                sub = []
        elif cur and src == "ALPM" and (mm := re.match(r"(upgraded|installed) (\S+)", msg)):
            if sub is None:
                cur["count"] += 1
                cur["packages"].append(mm.group(2))
            else:
                sub.append(mm.groups())
        elif cur and src == "ALPM" and msg.startswith("transaction completed"):
            if sub is None:
                cur["ok"] = True
                try:
                    cur["end"] = datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
                except ValueError:
                    pass
            else:
                try:
                    t_sub = datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
                except ValueError:
                    t_sub = 0
                if sub and all(a == "upgraded" for a, _ in sub) and t_sub - cur["time"] < 3 * 3600:
                    cur["count"] += len(sub)
                    cur["packages"] += [n for _, n in sub]
                    cur["end"] = t_sub
                sub = None
    if cur:
        runs.append(cur)
    runs = [r for r in runs if r["count"] or r["ok"]]
    return runs[-limit:][::-1]


UPDATER_LOGS = Path("/var/log/starchaser-updates")


def update_running() -> bool:
    """Settings' updater is running now (`starchaser-admin update-run`, as root: its command line is readable by all)."""
    try:
        procs = [d for d in Path("/proc").iterdir() if d.name.isdigit()]
    except OSError:
        return False
    for d in procs:
        try:
            cl = (d / "cmdline").read_bytes()
            if b"starchaser-admin\0update-run\0" in cl or b"starchaser-admin-software\0update-run\0" in cl or b"updater.py\0--unattended\0" in cl:
                return True
        except OSError:
            continue
    return False


def running_software_update_log() -> str:
    """Identify the live combined run by its own record, without hiding an older interrupted update."""
    from updater import RUN_DIR
    try:
        record = json.loads((RUN_DIR / f'last-run-{os.getuid()}-software.json').read_text())
        if (record.get('state') == 'running' and record.get('request', {}).get('updateFirst') is True
                and type(record.get('pid')) is int and record['pid'] > 0
                and b'\0software-run\0' in Path(f"/proc/{record['pid']}/cmdline").read_bytes()):
            return record.get('log', '')
    except (OSError, ValueError, AttributeError):
        pass
    return ''


def updater_runs(limit=8) -> list:
    """Recent runs of Settings' own updater, from its logs (updater.py marks an update run's log on its first line).
    These include what pacman.log never sees: a run that only updated Flatpak apps, or one that stopped before
    installing anything. [{"time", "end", "count", "ok", "canceled", "flatpak", "result"}], newest first. The run
    still going (no result yet while an update runs: the newest update log) is left out, however long it stays quiet
    (an AUR build can print nothing for many minutes). "result" False: it never said how it ended (cut off)."""
    from update_history import is_update_log
    out = []
    going = update_running()
    software_log = running_software_update_log()
    try:
        logs = sorted(UPDATER_LOGS.glob("*.log"), reverse=True)[:60]
    except OSError:
        return out
    for f in logs:
        try:
            with f.open("rb") as fh:
                first = fh.readline(4096)
                if not first.startswith(b'@@'):
                    continue
                header = json.loads(first[2:])
                if header.get('event') != 'start' or not is_update_log(header):
                    continue
                size = f.stat().st_size
                fh.seek(max(0, size - 16384))
                tail = fh.read().decode(errors="replace").splitlines()
            end = f.stat().st_mtime
            start = time.mktime(time.strptime(f.stem.split("-")[0] + "-" + f.stem.split("-")[1], "%Y%m%d-%H%M%S"))
        except (OSError, ValueError, IndexError, AttributeError):
            continue
        snapshot = None
        try:
            with f.open(errors="replace") as source:
                for line in source:
                    if line.startswith('@@{"event": "retained-snapshot"'):
                        snapshot = json.loads(line[2:]).get("number")
                        break
        except (OSError, ValueError):
            pass
        done = None
        for line in reversed(tail):
            if line.startswith('@@{"event": "done"'):
                try:
                    done = json.loads(line[2:])
                except ValueError:
                    pass
                break
        if done is None and (str(f) == software_log or going):
            going = False                               # only the newest update log can be the one still running
            continue
        going = False
        result = done is not None
        done = done or {}
        out.append({"time": int(start), "end": int(end), "count": int(done.get("upgraded") or 0), "result": result,
                    "ok": bool(done.get("ok")), "canceled": bool(done.get("canceled")),
                    "flatpak": bool(done.get("flatpakUpdated")), "skipped": bool(done.get("skipped")), "snapshot": snapshot})
        if len(out) >= limit:
            break
    return out


INSTALL_LOG = Path("/var/log/starchaser-install.log")


def history(runs: list, limit=8) -> list:
    """Recent updates for the page: Settings' own runs (their own verdict, Flatpak included) and the full updates
    pacman.log shows that no Settings run covers (a terminal update). Each says what it installed and how it went."""
    mine = updater_runs(limit)
    rows = [{"time": r["time"], "count": r["count"], "ok": r["ok"]} for r in runs
            if not any(m["time"] - 5 <= r["time"] <= m["end"] + 5 for m in mine)]
    for m in mine:
        n = m["count"]
        if not m["result"]:
            # cut off before it said how it ended (a power cut, a crash): pacman's log still says what it installed
            n = sum(r["count"] for r in runs if m["time"] - 5 <= r["time"] <= m["end"] + 5)
        pk = f"{n} update{'s' if n != 1 else ''}" if n else ""
        what = " and ".join(x for x in (pk, "Flatpak apps" if m["flatpak"] else "") if x) or "Nothing installed"
        # an automatic run that stopped at a hold installed nothing and isn't done with: "finished" read as all fine
        # (QA 2026-11-03: every night "Nothing installed · finished" while all system updates were on hold)
        held = m.get("skipped") and not n and not m["flatpak"]
        rows.append({"time": m["time"], "end": m["end"], "snapshot": m.get("snapshot"), "flatpak": m["flatpak"], "count": n, "ok": m["ok"], "what": "Nothing installed: updates on hold" if held else what,
                     "status": "skipped" if held else "Finished" if m["ok"] else "Canceled" if m["canceled"] else "Didn't finish"})
    # Undo last update: its own row, and the update it took away says "undone", not "finished" (QA 20261107-0300 004)
    for u in read_undo_log():
        rows.append({"time": u["time"], "count": 0, "ok": True, "kind": "undo",
                     "what": f"Went back to before the {u.get('date') or 'earlier'} update", "status": "Finished"})
        for r in rows:
            # the update's own snapshot was taken during its run (a terminal update: just before pacman's log entry)
            took = r["time"] - 5 <= u["snapshot"] <= r["end"] + 5 if "end" in r else u["snapshot"] - 5 <= r["time"] <= u["snapshot"] + 120
            took = took or u["snapshot"] - 5 <= r["time"] <= u["time"]
            # System snapshots leave per-user apps alone, including the app part of a mixed run.
            if r["count"] > 0 and took:
                r["status"] = "system updates undone" if r.get("flatpak") else "undone"
    targets = history_targets()
    used = set()
    for r in sorted(rows, key=lambda value: value["time"]):
        if r["count"] > 0 and r.get("status") not in ("undone", "system updates undone"):
            matches = [t for n, t in targets.items() if n not in used and (r.get("snapshot") == n or (not r.get("snapshot") and r["time"] - 120 <= t["time"] <= r.get("end", r["time"] + 120)))]
            if matches:
                target = min(matches, key=lambda value: abs(value['time'] - r['time']))
                r['undo'] = {**target, 'available': True}
                used.add(target['number'])
    try:
        installed = INSTALL_LOG.stat().st_mtime
    except OSError:
        installed = 0
    # The install is several pacman runs (the base system, then the desktop's own steps), all before the install log
    # was last written: one row for all of them, not "Installed Starchaser" once per run (QA 11-16, P3).
    setup = sorted((r for r in rows if installed and r.get("kind") != "undo" and r["time"] <= installed),
                   key=lambda value: value["time"])
    if setup:
        first = setup[0]
        first.update(what="Installed Starchaser", kind="install", count=sum(r["count"] for r in setup),
                     ok=all(r["ok"] for r in setup), end=int(installed))
        first.pop("undo", None)
        if "status" in first:
            first["status"] = "Finished" if first["ok"] else "Didn't finish"
        rows = [r for r in rows if r is first or not any(r is s for s in setup)]
    for r in rows:
        r.pop("end", None)
        r.pop("snapshot", None)
        r.pop("flatpak", None)
    return sorted(rows, key=lambda r: -r["time"])[:limit]


def undo_preview():
    """Recovery owns the comparison; Updates owns the plain update names."""
    result = sh("starchaser", "recovery", "list", timeout=60)
    data = json.loads(result.stdout)
    items = [item for snap in data.get("snapshots", []) for rows in (snap.get("undoes") or {}).values() for item in rows]
    load_labels([{"name": item.get("package", ""), "category": category(item.get("package", ""))} for item in items])
    for item in items:
        item["name"] = label(item.get("package", ""), category(item.get("package", "")))
    return data


def history_detail(stamp):
    """Only open a known update. Never accept a filename from a caller."""
    known = next((row for row in history(paclog_runs(60), limit=60) if row["time"] == stamp), None)
    if not known:
        return {"ok": False, "error": "That update is no longer in Recent updates."}
    if known.get("kind") == "undo":
        return {"ok": True, "items": [], "note": "This restored an earlier system snapshot. Open Recovery to see the available snapshots."}
    terminal = next((row for row in paclog_runs(60) if row["time"] == stamp), None)
    own = next((row for row in updater_runs(60) if row["time"] == stamp), None)
    end = own["end"] if own else terminal.get("end", stamp + 3 * 3600) if terminal else stamp + 3 * 3600
    setup = known.get("kind") == "install"
    if setup:
        try:
            end = max(end, INSTALL_LOG.stat().st_mtime)     # every pacman run of the install is in its one row
        except OSError:
            pass
    items, release = {}, None
    try:
        lines = PACLOG.read_text(errors="replace").splitlines()
    except OSError:
        lines = []
    active = False
    for line in lines:
        m = re.match(r"\[([^]]+)\] \[(\w+)\] (.*)", line)
        if not m:
            continue
        try:
            at = datetime.fromisoformat(m[1].replace("Z", "+00:00")).timestamp()
        except ValueError:
            continue
        if not stamp - 5 <= at <= end + 5:
            continue
        if m[2] == "PACMAN" and "starting full system upgrade" in m[3]:
            if active and not own and not setup:
                break
            active = True
        if m[2] == "ALPM" and (change := re.match(r"(?:upgraded|installed|downgraded) (\S+) \(([^)]*)\)", m[3])):
            name, versions = change.groups()
            old, sep, new = versions.partition(" -> ")
            items[(category(name), name)] = {"name": name, "category": category(name), "old": old if sep else "", "new": new if sep else old}
    if own:
        stem = time.strftime("%Y%m%d-%H%M%S", time.localtime(stamp))
        for path in UPDATER_LOGS.glob(stem + "*.log"):
            try:
                for line in path.read_text(errors="replace").splitlines():
                    if line.startswith("@@"):
                        event = json.loads(line[2:])
                        if event.get("event") == "update-item":
                            row = event.get("item") or {}
                            name = row.get("name", "")
                            if name:
                                cat = row.get("category", category(name))
                                # Display names can repeat across apps and parallel runtime branches.
                                # Older logs have only an app ID; retain those records too.
                                key = (cat, row.get("ref") or row.get("id") or name, row.get("scope", "")) if cat == "flatpak" else (cat, name)
                                items[key] = {**row, "category": cat}
                        if event.get("event") == "release-notes":
                            release = {"version": event.get("version", ""), "notes": event.get("notes", "")}
            except (OSError, ValueError):
                continue
    load_labels(list(items.values()))
    return {"ok": True, "items": [labeled(item) for item in items.values()], "release": release,
            "note": "" if items else "The list of updates from this run is no longer available."}


def history_targets():
    try:
        import update_history
        return update_history.undo_targets(update_history.snapshots())
    except (OSError, ValueError, subprocess.SubprocessError):
        return {}


# pacman's lock left by a crash or power cut ("stale") vs one in use: the rule lives in updater.py, which the root
# helper uses right before it clears a stale lock (one copy). Without it (an older install), never "stale".
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "updater.py").is_file():
        sys.path.insert(0, str(_lib))
        break
import tested_releases
try:
    from keep import starchaser_own
    from updater import pacman_lock_state
except ImportError:
    def pacman_lock_state() -> str:
        return "busy" if Path("/var/lib/pacman/db.lck").exists() else ""
try:
    from updater import RECOMMENDED_RECIPES
except ImportError:
    RECOMMENDED_RECIPES = ()
try:
    from updater import run_busy
except ImportError:
    def run_busy() -> bool:
        return False
try:
    from updater import desktop_update_error
except ImportError:
    def desktop_update_error(pending):
        return "Couldn't check the desktop window manager update. Restart Settings after Starchaser finishes updating." \
            if any(name == "hyprland" for name, _, _ in pending) else ""

try:
    from updater import read_undo_log
except ImportError:
    def read_undo_log() -> list:
        return []

try:
    from updater import starchaser_source
except ImportError:
    def starchaser_source() -> bool:
        return True

try:
    from updater import ours_overwrite
except ImportError:
    def ours_overwrite() -> list:
        return []


def changed_since(t: float) -> list:
    """Every package installed or updated since t, by any transaction (a Software install of a kernel or a graphics
    driver needs a restart as much as an update does)."""
    out = []
    try:
        lines = PACLOG.read_text(errors="replace").splitlines()[-30000:]
    except OSError:
        return out
    for l in reversed(lines):
        m = re.match(r"\[([^\]]+)\] \[ALPM\] (upgraded|installed|reinstalled|downgraded) (\S+)", l)
        if not m:
            continue
        try:
            ts = datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp()
        except ValueError:
            continue
        if ts <= t:
            break
        out.append(m.group(3))
    return out


def last_upgrade(runs: list) -> float:
    return runs[0]["time"] if runs and runs[0]["ok"] else next((r["time"] for r in runs if r["ok"]), 0)


def desktop_package_gone() -> bool:
    """Starchaser's desktop package was installed here (pacman.log says so, and never that it was removed) but isn't
    now, while Starchaser's package source is still listed: going back to a snapshot from between Get Starchaser's
    packages' steps took it away (/var/log isn't in snapshots). The copied desktop stays and works, but no update
    brings the package back by itself, so its updates stop (QA 20261104-2101 004)."""
    if not starchaser_source() or sh("pacman", "-Q", "starchaser-desktop").returncode == 0:
        return False
    try:
        lines = PACLOG.read_text(errors="replace").splitlines()[-30000:]
    except OSError:
        return False
    for l in reversed(lines):
        m = re.search(r"\[ALPM\] (installed|upgraded|reinstalled|downgraded|removed) starchaser-desktop ", l)
        if m:
            return m.group(1) != "removed"
    return False


def system_facts() -> dict:
    runs = paclog_runs()
    boot = time.time() - float(Path("/proc/uptime").read_text().split()[0])
    since_boot = [p for r in runs if r["time"] > boot for p in r["packages"]] + changed_since(boot)
    kernel_gone = not Path(f"/usr/lib/modules/{os.uname().release}").exists()
    reboot = sorted({p for p in since_boot if REBOOT.match(p)}) + (["the kernel"] if kernel_gone and not any(p.startswith("linux") for p in since_boot) else [])
    pacnew = []
    for d, _, files in os.walk("/etc", onerror=lambda e: None):
        pacnew += [os.path.join(d, f) for f in files if f.endswith(".pacnew")]
    snap = Path("/etc/snapper/configs/root").exists() and sh("pacman", "-Q", "snap-pac").returncode == 0
    bootable = any(sh("pacman", "-Q", p).returncode == 0 for p in ("limine-snapper-sync", "grub-btrfs"))
    helper = "paru" if shutil.which("paru") else "yay" if shutil.which("yay") else ""
    lock = pacman_lock_state()
    # Starchaser's own run lock: while an update builds an AUR package pacman's lock is free, but Update now would
    # ask for the password only to be told another run is going
    busy = run_busy()
    import update_health
    from update_experience import checkin, preflight

    health = update_health.read()
    from release_notes import installed as installed_notes
    return {"installedRelease": installed_notes(), "preflight": preflight(), "health": {key: health[key] for key in ("status", "number", "healthyAt", "updated") if key in health}, "checkin": checkin(health), "locked": bool(lock) or busy, "lockStale": lock == "stale" and not busy, "snapshots": snap, "bootableSnapshots": snap and bootable,
            # rebootLabels: the same in plain words ("Processor fixes (AMD)", not "amd-ucode"), one each
            "reboot": reboot, "rebootLabels": list(dict.fromkeys(reboot_label(p) for p in reboot)), "pacnew": sorted(pacnew)[:50], "history": history(runs),
            "lastUpgrade": last_upgrade(runs),
            "helperReady": Path("/usr/local/lib/starchaser/updater.py").exists(), "aurHelper": helper,
            # the door that asks for the password once per sitting (polkit org.starchaser.software); without it the
            # page runs starchaser-admin itself, which asks every time
            "batchHelper": os.access("/usr/local/lib/starchaser/starchaser-admin-software", os.X_OK),
            "flatpak": bool(shutil.which("flatpak")), "distro": distro(), "desktopPackageGone": desktop_package_gone(),
            # Finish in a terminal lets Starchaser's package replace its own copied files, as Update now does
            "overwrite": ours_overwrite()}


def distro() -> str:
    try:
        return dict(l.split("=", 1) for l in Path("/etc/os-release").read_text().splitlines() if "=" in l).get("ID", "")
    except OSError:
        return ""


# ---------------------------------------------------------------------------------------------- notify
def open_updates() -> None:
    """Open Settings > Updates from a notice's button. The daily check runs as a oneshot user service, and systemd
    kills everything left in its cgroup when it returns (a new session doesn't leave it), so Settings started as a
    plain child closed again at once (QA 2026-11-05). A scope of its own keeps it open."""
    try:
        if shutil.which("systemd-run") and subprocess.run(
                ["systemd-run", "--user", "--scope", "--collect", "--quiet", "starchaser", "settings", "updates"],
                capture_output=True, timeout=30).returncode == 0:
            return
    except (OSError, subprocess.TimeoutExpired):
        return                                        # it may still be opening: don't start a second one
    subprocess.Popen(["starchaser", "settings", "updates"], start_new_session=True)


def restart_when_done(run_dir=None, runner=subprocess.run):
    import fcntl
    if run_dir is None:
        from updater import RUN_DIR
        run_dir = RUN_DIR
    # Hold a shared lock through the request, so a second install cannot start between the wait and restart.
    with (Path(run_dir) / "run.lock").open("r") as lock:
        fcntl.flock(lock, fcntl.LOCK_SH)
        return runner(["systemctl", "reboot"], check=False).returncode


def cached_preflight():
    from update_experience import MIN_FREE, preflight
    cache = jread(CACHE, {})
    size = cache.get('download', 0) if isinstance(cache, dict) else 0
    size = size if isinstance(size, (int, float)) and 0 <= size < 10 ** 15 else 0
    return preflight(required=MIN_FREE + size)


def power_update(action, run=subprocess.run):
    """Only a successful, explicitly requested run may finish with a restart or shutdown."""
    flight = cached_preflight()
    if not flight['ok']:
        print('@@' + json.dumps({'event': 'done', 'ok': False, 'error': '. '.join(flight['problems'])}), flush=True)
        return 1
    import tempfile
    cache = jread(CACHE, {})
    cache = cache if isinstance(cache, dict) else {}
    runtime = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}'))
    fd, name = tempfile.mkstemp(prefix='starchaser-power-update-', suffix='.json', dir=runtime)
    try:
        with os.fdopen(fd, 'w') as source:
            json.dump({'flatpak': True, 'aur': [u['name'] for u in cache.get('updates', []) if isinstance(u, dict) and u.get('category') == 'aur' and isinstance(u.get('name'), str)]}, source)
        result = run(['pkexec', '/usr/local/lib/starchaser/starchaser-admin-software', 'update-run', name], check=False)
        if result.returncode:
            return result.returncode
        result = run(['systemctl', action], check=False)
        if result.returncode:
            verb = 'restart' if action == 'reboot' else 'shut down'
            print('@@' + json.dumps({'event': 'done', 'ok': False,
                  'error': f"The updates are installed, but your computer couldn't {verb}. Use Power to try again."}), flush=True)
        return result.returncode
    finally:
        Path(name).unlink(missing_ok=True)


RECOVERY_LAST = Path.home() / ".local/state/starchaser/recovery-last.json"   # starchaser recovery's last result


def going_back_needs_restart() -> bool:
    """Going back (or Undo last update) finished since this computer started and waits for its restart."""
    try:
        last = json.loads(RECOVERY_LAST.read_text())
        boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
    except (OSError, ValueError):
        return False
    return isinstance(last, dict) and bool(boot) and last.get("boot_id") == boot and last.get("outcome") in ("ok", "partial")


def notify() -> None:
    notify_release_notes()
    # People who were signed out hear once about an automatic failure or a needed restart at their next check.
    try:
        import updater
        undone = updater.read_undone()
        pause = updater.undo_pause(undone)
        pause_seen = Path.home() / ".cache/starchaser/undo-pause-seen"
        if pause and str(undone.get("time")) != (pause_seen.read_text() if pause_seen.exists() else ""):
            sent = sh("sh", "-c", 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"', "starchaser", "notify", "-a", "Starchaser", "-i", "system-software-update", "Starchaser updates", pause["text"], timeout=5)
            if sent.returncode == 0:
                pause_seen.parent.mkdir(parents=True, exist_ok=True)
                pause_seen.write_text(str(undone["time"]))
        auto = updater.read_auto_last()
        if auto and auto.get("skipped"):
            auto = auto.get("lastCompleted")          # a later skip doesn't hide the run that finished
        auto = auto if isinstance(auto, dict) else None
        seen_file = Path.home() / ".cache/starchaser/autoupdate-seen"
        try:
            seen = int(seen_file.read_text())
        except (OSError, ValueError):
            seen = 0
        if auto and not auto.get("skipped") and (auto.get("ok") is False or auto.get("reboot") or auto.get("upgraded", 0) or auto.get("flatpakUpdated")) and auto.get("finished", 0) > seen:
            message = updater.away_notification_text(auto, auto.get("level", "off"))
            if message:
                sent = sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "system-software-update", *message, timeout=5)
                if sent.returncode == 0:
                    seen_file.parent.mkdir(parents=True, exist_ok=True)
                    seen_file.write_text(str(auto["finished"]))
    except (ImportError, OSError, ValueError, TypeError):
        pass
    if going_back_needs_restart():
        # "N updates available" beside "Restart to finish going back" only tempts someone to put the updates back
        # before the restart (QA 20261106-0031 004); after it, the next check tells them
        return
    if run_busy() or pacman_lock_state() == "busy":
        # a check in the middle of an update sees a half-updated database and announces a wrong count (QA 20261107-2238 004)
        return
    res = check()
    # A desktop hold can leave every update in deferred. Still tell the person: otherwise the daily check is
    # silent on exactly the computers that need help setting up Starchaser's package source.
    deferred = res.get("deferred", [])
    # Versions the person just undid stay out of the count: the automatic updater skips them too, and the Updates
    # page explains the undo (QA 20261108-0326 004)
    try:
        import updater
        undone = updater.read_undone()
        again = set(updater.undone_again([(u["name"], u.get("old", ""), u["new"]) for u in res["updates"] + deferred], undone)) if undone else set()
    except (ImportError, OSError, ValueError, TypeError, KeyError):
        again = set()
    names = sorted(u["name"] + " " + u["new"] for u in res["updates"] + deferred if u["name"] not in again)
    hold = bool(deferred)
    last = jread(NOTIFIED, {})
    if not names or (names == last.get("set", []) and last.get("hold", False) == hold):
        return
    # the welcome or the tour on screen: the card would sit over it (QA 20261109-2303 002). Nothing is recorded, so
    # the next check tells them once both are gone
    if first_steps_open():
        return
    n = len(names)
    manual = [x for x in res["news"] if x["manual"] and x.get("applicability") not in ("not-installed", "fixed")]
    body = ("System updates are on hold. " if hold else "")
    if hold and res.get("holdSwitch"):
        # the lasting hold: one plain action, Review (QA 20261106-0950 001, 20261108-0502 002)
        body = "Updates are ready, but this computer needs a one-time setup step first. Choose Review to start it."
    else:
        body += available_notice_body(res, manual)
    title = f"{n} update{'s' if n != 1 else ''} " + ("waiting" if hold else "available")
    release_notice = tested_releases.release_notice(res.get('release'), res.get('download', 0))
    if release_notice:
        title, body = release_notice
    if run_busy() or pacman_lock_state() == "busy":
        return
    # x-starchaser-settings: the taskbar opens Settings > Updates itself for Review, so the button still works from the
    # bell's list after this sender has stopped waiting (QA 2026-11-05: the card went and nothing opened). So the card
    # needn't stay up long: 10 s, not a minute over whatever is open (it hid the focused controls in Settings, QA 2026-11-06)
    r = sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "system-software-update", "-t", "10000", "-A", "open=Review",
           "-h", "string:x-starchaser-settings:updates", title, body, timeout=75)
    if r.returncode == 0:
        jwrite(NOTIFIED, {"set": names, "hold": hold, "time": int(time.time())})
    if r.stdout.strip() == "open":
        open_updates()


def startup_notice():
    import update_health
    update_health.notice()
    notify_release_notes()


# The package's upgrade step writes RELEASE_NOTICE/updated ({"from": old version}) when the version changes; a first
# install (a new computer, the live stick) never does. The folder is root:wheel 2775, so the first administrator who
# closes the screen marks it seen for the whole computer.
RELEASE_NOTICE = Path('/var/lib/starchaser/release-notice')
LIVE_IMAGE = Path('/etc/starchaser-live-image')
LIVE_BOOT = Path('/run/archiso')


def release_notice_due(notes) -> bool:
    """The "is installed" screen is news only after an update on a computer that had an earlier version: never in the
    live session or on a fresh install, once per computer, and only to an administrator (QA fable-final P2-2)."""
    if not notes or LIVE_IMAGE.exists() or LIVE_BOOT.is_dir():
        return False
    import grp
    try:
        if grp.getgrnam('wheel').gr_gid not in os.getgroups():
            return False
    except KeyError:
        return False
    updated = jread(RELEASE_NOTICE / 'updated', {})
    if not updated.get('from') or updated['from'] == notes['version']:
        return False
    return jread(RELEASE_NOTICE / 'seen', {}).get('version') != notes['version']


def notify_release_notes():
    from release_notes import installed
    notes = installed()
    if not release_notice_due(notes) or first_steps_open():
        return
    # Only a later sign-in shows the persistent updated screen, never over a run in this boot.
    try:
        booted = time.time() - float(Path("/proc/uptime").read_text().split()[0])
        release_at = (tested_releases.STATE / 'installed.record').stat().st_mtime
        if release_at > booted:
            return
    except OSError:
        pass
    sh("starchaser", "settings", "release-updated", timeout=10)



REMINDED = Path.home() / ".cache/starchaser/restart-reminded"


TOUR_STATE = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "starchaser/tour.json"


def first_steps_open() -> bool:
    """Day one is the welcome, then the tour, then quiet: Starchaser's own background notices never come up over
    either (QA fable-final, section 8 item 13). The welcome ends when it is closed, so one running is the person
    mid-setup; a tour state left active for over two hours is one walked away from, as the tour itself treats it."""
    w = sh("pgrep", "-f", r"quickshell/welcome$", timeout=5)
    if w.returncode == 0 and w.stdout.strip():
        return True
    try:
        since = time.time() - TOUR_STATE.stat().st_mtime
        tour = json.loads(TOUR_STATE.read_text())
    except (OSError, ValueError):
        return False
    return isinstance(tour, dict) and tour.get("active") is True and since < 2 * 3600


def restart_reminder() -> None:
    """Once a boot, the daily check says when updates installed since this computer started still need a restart: after
    Update now's Later (or an update from Get Starchaser's packages…) nothing else said so once Settings was closed,
    while the running kernel's modules were already gone (QA 2026-11-04). An automatic run says it itself."""
    try:
        boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
        if not boot or REMINDED.read_text().strip() == boot:
            return
    except FileNotFoundError:
        pass
    except OSError:
        return
    if going_back_needs_restart():
        return                                        # the page says "Restart to finish going back"; this toast would say "updating"
    if first_steps_open():
        return                                        # nothing recorded: the next check reminds once they are done
    labels = system_facts()["rebootLabels"]
    if not labels:
        return
    try:
        import updater
        auto = updater.read_auto_last()
        started = time.time() - float(Path("/proc/uptime").read_text().split()[0])
        if isinstance(auto, dict) and auto.get("reboot") and auto.get("finished", 0) > started:
            return
    except (ImportError, OSError, ValueError):
        pass
    shown = ", ".join(labels[:3]) + (" and more" if len(labels) > 3 else "")
    r = sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "system-reboot", "-t", "60000", "-A", "open=Open Updates",
           "-h", "string:x-starchaser-settings:updates", "Restart to finish updating", f"Updated since this computer started: {shown}. They take effect after a "
           "restart. Save your work, then restart. If something isn't right afterward, Settings > Updates has Undo last update.", timeout=75)
    if r.returncode == 0:
        REMINDED.parent.mkdir(parents=True, exist_ok=True)
        REMINDED.write_text(boot + "\n")
    if r.stdout.strip() == "open":
        open_updates()


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "state"
    extra = sys.argv[2:]
    if cmd in ("check", "notify", "state", "restart-when-done", "startup-notice", "release-notice", "preflight", "installed-notes", "undo-preview") and extra:
        if any(a in ("-h", "--help") for a in extra):   # a help request must never run the command
            print(__doc__.strip())
            sys.exit(0)
        print(f"starchaser updates: {cmd} takes no more arguments. Run 'starchaser updates --help' for more help.", file=sys.stderr)
        sys.exit(2)
    if cmd == "installed-notes" and not extra:
        from release_notes import installed as installed_notes
        print(json.dumps(installed_notes()))
    elif cmd == "release-seen" and len(extra) == 1:
        from release_notes import installed as installed_notes
        notes = installed_notes()
        if notes and notes["version"] == extra[0]:
            try:
                jwrite(RELEASE_NOTICE / 'seen', {'version': notes['version']})
            except OSError:
                pass  # best-effort: a person outside wheel never sees the screen, so has nothing to mark
    elif cmd == "undo-preview" and not extra:
        print(json.dumps(undo_preview()))
    elif cmd == "history-detail" and len(extra) == 1 and extra[0].isdigit():
        print(json.dumps(history_detail(int(extra[0]))))
    elif cmd == "release-notice" and not extra:
        notify_release_notes()
    elif cmd == "startup-notice":
        startup_notice()
    elif cmd == "preflight" and not extra:
        print(json.dumps(cached_preflight()))
    elif cmd == "power" and extra in (["reboot"], ["poweroff"]):
        sys.exit(power_update(extra[0]))
    elif cmd == "restart-when-done":
        sys.exit(restart_when_done())
    elif cmd == "check":
        print(json.dumps(check()))
    elif cmd == "notify":
        notify()
        restart_reminder()
    elif cmd == "state":
        c = jread(CACHE, {})
        local = installed()
        c = current_pending(c, local)
        refresh_news(c, local or None)

        def rows(key):                       # a damaged cache's wrong shape reads as no rows, never a traceback
            value = c.get(key)
            return [u for u in value if isinstance(u, dict)] if isinstance(value, list) else []

        load_labels(rows("updates") + rows("held") + rows("deferred"))
        for k in ("updates", "held", "deferred"):                       # labels from this code, never from an older cache
            if k in c:                                      # no cache: no list at all (an empty one says "up to date")
                c[k] = [labeled(u) for u in rows(k)]
        if isinstance(c.get("dev"), list):
            c.update(dev_labels([n for n in c["dev"] if isinstance(n, str)]))
        print(json.dumps({**c, **system_facts()}))
    elif cmd in ("-h", "--help", "help"):
        print(__doc__.strip())
    else:
        print(f"starchaser updates: unknown command {cmd!r}. Run 'starchaser updates --help' for more help.", file=sys.stderr)
        sys.exit(2)
