Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

62.5 KB
Raw Blame
"""Build the managed-install macOS app identity (BUG-060).

The bundle's main executable must remain a Mach-O process. A shell launcher
that ``exec``s an external virtual-environment Python loses its ``NSBundle``
identity and causes TCC grants to attach to Python or a terminal instead of
the app. The managed installer therefore compiles the in-repo stub
launcher (``macos_stub_launcher.c``): it embeds the active Python runtime in
the app process and runs the managed entry script, so it works with framework
AND non-framework interpreters (for example uv-managed standalone builds)
while the source and dependencies remain in the managed checkout.

The locally generated app is signed with the per-user code-signing identity
from ``macos_signing_identity`` whenever one exists. macOS then pins the TCC
grants to ``identifier + certificate`` instead of to the code-directory hash,
so the bundle can be rebuilt as often as needed without losing a single
permission. Without that identity (no GUI session at install time, the user
declined the one trust dialog) the app falls back to an ad-hoc signature and
is preserved byte-for-byte on ordinary source updates so its identity does
not churn. When the TCC identity does change (ad-hoc rebuild, or the one-time
migration from ad-hoc to the certificate), macOS orphans every previously
recorded grant — the old rows then read as silently DENIED for the "new" app
and macOS never prompts again (BUG-083). After such a change this module
resets the stale TCC rows for our bundle id via ``tccutil`` so the app can
prompt fresh. Public binary distribution still requires the separate
Developer-ID signing and notarization pipeline; this module never claims a
locally signed app is a notarized artifact.
"""

from __future__ import annotations

import importlib.util
import json
import logging
import os
import platform
import plistlib
import re
import shutil
import stat
import subprocess
import sys
import tempfile
from pathlib import Path
from types import ModuleType

from dodaios.core.branding import (
    LEGACY_MACOS_APP_DIR_NAMES,
    MACOS_APP_DIR_NAMES,
    MACOS_DMG_BUNDLE_ID,
    MACOS_EXECUTABLE_NAME,
)
from dodaios.core.branding import (
    MACOS_APP_DIR_NAME as APP_DIR_NAME,
)
from dodaios.core.branding import (
    MACOS_APP_NAME as APP_NAME,
)
from dodaios.core.branding import (
    MACOS_BUNDLE_ID as BUNDLE_ID,
)
from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS
from dodaios.setup.macos_signing_identity import ensure_local_signing_identity

log = logging.getLogger(__name__)

# 2: stub launcher sets only LC_CTYPE (BUG-079 — LC_ALL leaked a de_DE
# LC_NUMERIC into native libs; libvosk then emitted malformed JSON). Bumping
# forces existing bundles through a rebuild on the next ensure pass.
# 3: one forced rebuild so the new signature-change TCC reset (BUG-083) heals
# bundles whose grants were orphaned by the version-2 rebuild.
# The shared usage-string table (dodaios/core/macos_privacy_strings.py) added
# Desktop, Documents, Downloads, volume and local-network strings that this
# bundle never carried. They are cosmetic prompt text, so the format version is
# deliberately NOT bumped: a bump would rebuild every installed bundle, and an
# ad-hoc rebuild is a new identity that re-asks every permission. The next
# rebuild that happens for another reason carries the new strings.
_BUNDLE_FORMAT_VERSION = 3

# TCC service names this app ever requests; reset scope is always limited to
# our own bundle id, never the whole service (BUG-083).
_TCC_SERVICES: tuple[str, ...] = (
    "Microphone",
    "ScreenCapture",
    "Accessibility",
    "ListenEvent",
    "PostEvent",
    # Automation consent for the Music/Spotify ducking scripts. It is keyed to
    # our code requirement exactly like the rows above, so a stale row here
    # made the Music prompt "come back" after every rebuild while never
    # showing up in any permission view.
    "AppleEvents",
)
_MACHO_MAGICS = frozenset(
    {
        b"\xfe\xed\xfa\xce",
        b"\xce\xfa\xed\xfe",
        b"\xfe\xed\xfa\xcf",
        b"\xcf\xfa\xed\xfe",
        b"\xca\xfe\xba\xbe",
        b"\xbe\xba\xfe\xca",
        b"\xca\xfe\xba\xbf",
        b"\xbf\xba\xfe\xca",
    }
)

# The reason the most recent ensure_macos_app_bundle call returned None, so
# callers can surface the real failure instead of a generic warning.
_LAST_ERROR: str | None = None


def last_error() -> str | None:
    """Return why the last ensure_macos_app_bundle call failed, if it did."""
    return _LAST_ERROR


_PRIVACY_STRINGS_PATH = Path(__file__).resolve().parents[1] / "core" / "macos_privacy_strings.py"


def _privacy_strings() -> ModuleType:
    """Load the shared usage-string table BY PATH, exactly as ``dodaios.spec`` does.

    The managed app is built from a source checkout, so the file is on disk. The
    path load (rather than an ordinary import) is what lets the parity test
    prove that both bundles read the same file. Nothing runs when this module
    is imported; the file is read when a plist is built (a few hundred bytes).
    A frozen app carries no source file, and it never builds a plist (desktop
    registration is a no-op there), so a missing file is a loud error here,
    never an empty plist.
    """
    loader_spec = importlib.util.spec_from_file_location(
        "_jarvis_macos_privacy_strings", _PRIVACY_STRINGS_PATH
    )
    if loader_spec is None or loader_spec.loader is None:
        raise RuntimeError(f"cannot load the macOS usage strings from {_PRIVACY_STRINGS_PATH}")
    module = importlib.util.module_from_spec(loader_spec)
    loader_spec.loader.exec_module(module)
    return module


def _version() -> str:
    try:
        from dodaios import __version__

        return __version__
    except Exception:  # noqa: BLE001 - version metadata is cosmetic here
        return "0.0.0"


def _default_install_dir() -> Path:
    """Return the parent of the installed ``jarvis`` package directory."""
    import dodaios

    return Path(dodaios.__file__).resolve().parents[1]


def _venv_python(install_dir: Path) -> Path:
    candidate = install_dir / ".venv" / "bin" / "python"
    if candidate.is_file() and os.access(candidate, os.X_OK):
        return candidate
    return Path(sys.executable)


SYSTEM_APPLICATIONS_DIR = Path("/Applications")


def user_applications_dir() -> Path:
    return Path.home() / "Applications"


def macos_applications_dir(
    *, system_dir: Path | None = None, user_dir: Path | None = None
) -> Path:
    """The folder the app lives in — or, when it lives nowhere yet, belongs in.

    ``/Applications`` is the folder Finder's "Applications" sidebar item and
    Launchpad show; a bundle kept only in ``~/Applications`` is installed but
    invisible to a user who looks where Mac apps are (BUG-216). It is writable
    without a password for every admin account, so it is the default whenever
    this user can write there; a standard account keeps ``~/Applications``.
    """
    system = system_dir or SYSTEM_APPLICATIONS_DIR
    user = user_dir or user_applications_dir()
    for root in (system, user):
        candidate = root / APP_DIR_NAME
        if (candidate.exists() or candidate.is_symlink()) and not _is_foreign_bundle(candidate):
            return root
    system_slot = system / APP_DIR_NAME
    if os.access(system, os.W_OK) and not (system_slot.exists() or system_slot.is_symlink()):
        return system
    return user


def _bundle_identifier(candidate: Path) -> str | None:
    """``CFBundleIdentifier`` of ``candidate``; ``None`` when it cannot be read."""
    try:
        with (candidate / "Contents" / "Info.plist").open("rb") as stream:
            bundle_id = plistlib.load(stream).get("CFBundleIdentifier")
    except (OSError, ValueError, plistlib.InvalidFileException):
        # Missing or unreadable metadata proves nothing about ownership.
        return None
    return bundle_id if isinstance(bundle_id, str) and bundle_id else None


def _is_foreign_bundle(candidate: Path) -> bool:
    """Whether ``candidate`` is an app of the same NAME that is not ours.

    The notarized DMG build carries the same name and is
    dragged to ``/Applications`` by hand, under its own bundle id. It is the
    user's app, not this installer's: it must never be taken for the managed
    bundle, replaced by a rebuild, or deleted by an uninstall. Only a readable
    ``Info.plist`` naming a different bundle id proves that — a damaged bundle
    of ours (no or unreadable ``Info.plist``) stays ours, so it can be repaired.
    """
    bundle_id = _bundle_identifier(candidate)
    return bundle_id is not None and bundle_id != BUNDLE_ID


def installed_macos_app_bundle_path() -> Path:
    """The app the user actually launches: the managed bundle, else the .dmg app.

    ``macos_app_bundle_path`` answers for the managed install only and, on a
    Mac that has just the downloaded .dmg app, points at a bundle that does not
    exist — so anything that has to bring the running app to the front (the
    ``jarvis permissions`` commands) reported "app not found" for a perfectly
    healthy install. The .dmg app is accepted only under its own bundle id.
    """
    managed = macos_app_bundle_path()
    if managed.is_dir():
        return managed
    # A .dmg app the in-app updater has not reached yet keeps its earlier name.
    for root in (SYSTEM_APPLICATIONS_DIR, user_applications_dir()):
        for name in MACOS_APP_DIR_NAMES:
            candidate = root / name
            if candidate.is_dir() and _bundle_identifier(candidate) == MACOS_DMG_BUNDLE_ID:
                return candidate
    return managed


def macos_app_bundle_path(*, applications_dir: Path | None = None) -> Path:
    """Return the application-bundle path (see ``macos_applications_dir``)."""
    root = applications_dir or macos_applications_dir()
    return root / APP_DIR_NAME


def rename_legacy_macos_app_bundles(roots: tuple[Path, ...] | None = None) -> list[Path]:
    """Give our bundle under an earlier name the current name, once.

    One ``os.rename`` in the folder it lives in: every byte stays, and with
    them the code signature, so the privacy grants survive it (TCC pins them to
    the bundle id and the signing requirement, never to a path, BUG-161). No
    link is left under the earlier name: Launchpad and Spotlight would list the
    app twice. A process that runs from the bundle keeps running; it still
    reports the path it started from, which the repair below allows for.

    Only a bundle whose ``Info.plist`` names the managed bundle id is renamed.
    An unreadable one proves nothing, and the .dmg app (its own id) is renamed
    by its own updater (``dodaios.core.installer_update``), which swaps the
    bundle it runs from and must find it where it started. A folder that
    already holds an app under the current name keeps both untouched. Returns
    the bundles now under the current name; never raises.
    """
    renamed: list[Path] = []
    for root in roots or (SYSTEM_APPLICATIONS_DIR, user_applications_dir()):
        target = root / APP_DIR_NAME
        for legacy_name in LEGACY_MACOS_APP_DIR_NAMES:
            source = root / legacy_name
            try:
                if source.is_symlink() or not source.is_dir():
                    continue
                if _bundle_identifier(source) != BUNDLE_ID:
                    log.info("Keeping %s under its name: it is not this install's app.", source)
                    continue
                if target.exists() or target.is_symlink():
                    log.warning(
                        "Keeping %s under its earlier name: %s already exists.", source, target
                    )
                    continue
                os.rename(source, target)
            except OSError as exc:
                log.warning("Could not rename %s to %s; keeping it: %s", source, target, exc)
                continue
            log.info("Renamed the macOS app %s to %s.", source, target)
            unregister_from_launch_services(source)
            renamed.append(target)
    return renamed


def _promote_to_system_applications(
    *, system_dir: Path | None = None, user_dir: Path | None = None
) -> Path | None:
    """Move a ``~/Applications`` install into ``/Applications`` once.

    A rename keeps every byte and therefore the code signature: TCC pins grants
    to the bundle id and signature, never to a path (BUG-161), so the user's
    permissions survive the move. Only runs when ``/Applications`` has no copy
    of its own and is writable without elevation; a failure leaves the app where
    it was, which still works.
    """
    system = system_dir or SYSTEM_APPLICATIONS_DIR
    user = user_dir or user_applications_dir()
    source = user / APP_DIR_NAME
    target = system / APP_DIR_NAME
    if (
        not source.is_dir()
        or source.is_symlink()
        or target.exists()
        or target.is_symlink()
        or not os.access(system, os.W_OK)
    ):
        return None
    try:
        source.rename(target)
    except OSError as exc:
        log.warning("Could not move %s to %s; keeping it in place: %s", source, system, exc)
        return None
    log.info("Moved the macOS app into %s so Finder and Launchpad show it.", system)
    unregister_from_launch_services(source)
    return target


def _is_macho_executable(path: Path) -> bool:
    try:
        mode = path.stat().st_mode
        with path.open("rb") as stream:
            magic = stream.read(4)
    except OSError:  # An unreadable binary cannot pass the bundle probe.
        return False
    # Windows cannot represent POSIX execute bits. The only Windows caller is
    # the explicit cross-platform fixture seam; production validation runs on
    # macOS and therefore still requires an executable mode.
    executable_mode = os.name == "nt" or bool(mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
    return executable_mode and magic in _MACHO_MAGICS


def _codesign_issue(bundle: Path) -> str | None:
    """Return the codesign verification failure detail, or ``None`` if valid.

    Deliberately verifies WITHOUT ``--strict`` and ``--deep``: the first
    local app was a py2app *alias* bundle (since replaced by the native stub
    launcher) whose entire design was symlinking the managed checkout and
    Python runtime, and strict validation rejects every symlink that leaves the
    bundle ("invalid destination for symbolic link") — it failed on 100% of
    freshly built bundles on real macOS (Intel and Apple Silicon alike). The
    native stub bundle has not been checked against ``--strict`` on a real Mac
    (unverified), so the relaxed check stays. The ad-hoc signature only has to
    give the app a stable local TCC identity; distribution-grade validation
    belongs to the separate Developer-ID signing and notarization pipeline.
    """
    if sys.platform != "darwin":
        return None
    try:
        result = subprocess.run(
            ["/usr/bin/codesign", "--verify", str(bundle)],
            capture_output=True,
            text=True,
            timeout=30,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        # The caller receives the verification failure as a diagnostic.
        return f"codesign verification did not run: {exc}"
    if result.returncode == 0:
        return None
    return (result.stderr or result.stdout or "unknown codesign error").strip()


def _bundle_cdhash(bundle: Path) -> str | None:
    """Return the bundle's code-directory hash — its TCC identity — or ``None``.

    An ad-hoc signature has no certificate chain, so macOS pins TCC grants to
    the CDHash of the main executable. Two bundles with different CDHashes are
    different apps to TCC even under the same bundle id.
    """
    if sys.platform != "darwin":
        return None
    try:
        result = subprocess.run(
            ["/usr/bin/codesign", "--display", "--verbose=4", str(bundle)],
            capture_output=True,
            text=True,
            timeout=30,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
    except (OSError, subprocess.TimeoutExpired):  # A failed code-hash probe has no usable hash.
        return None
    # codesign prints the display block on stderr.
    match = re.search(r"^CDHash=([0-9a-f]+)", result.stderr or "", re.MULTILINE)
    return match.group(1) if match else None


def _bundle_tcc_identity(bundle: Path) -> str | None:
    """Return the bundle's designated requirement — what TCC pins grants to.

    ``cdhash H"..."`` for an ad-hoc signature (a new one per rebuild) and
    ``identifier "..." and certificate leaf = H"..."`` for a certificate
    signature (the same one for every rebuild). ``None`` when unreadable.
    """
    if sys.platform != "darwin":
        return None
    try:
        result = subprocess.run(
            ["/usr/bin/codesign", "--display", "-r-", str(bundle)],
            capture_output=True,
            text=True,
            timeout=30,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        log.debug("codesign could not read the designated requirement of %s: %s", bundle, exc)
        return None
    return _parse_designated_requirement(f"{result.stdout or ''}\n{result.stderr or ''}")


def _parse_designated_requirement(text: str) -> str | None:
    """Pull the ``designated => ...`` requirement out of ``codesign -r-`` output."""
    match = re.search(r"^(?:#\s*)?designated\s*=>\s*(.+?)\s*$", text, re.MULTILINE)
    return match.group(1) if match else None


def _signed_with_certificate(bundle: Path) -> bool:
    """Whether the bundle's TCC identity is certificate-bound (rebuild-proof)."""
    identity = _bundle_tcc_identity(bundle)
    return identity is not None and "certificate leaf" in identity


def _tcc_reset_needed(previous_identity: str | None, current_identity: str | None) -> bool:
    """An identity change (or an unknowable previous one) orphans TCC rows."""
    return current_identity is not None and previous_identity != current_identity


def _reset_stale_tcc_grants(runner=subprocess.run) -> None:
    """Drop this app's orphaned TCC rows so macOS can prompt fresh (BUG-083).

    After an identity change the recorded grants belong to the OLD code
    requirement: the app reads them as DENIED and macOS suppresses every prompt,
    so permissions appear "auto-rejected" without the user ever being asked.
    Resetting is scoped to our bundle id, is best-effort per service, and never
    raises — a failed reset leaves behavior no worse than before. The caller
    (`_install_native_bundle`) only runs on macOS; the injectable runner keeps
    this unit-testable on every OS.
    """
    for service in _TCC_SERVICES:
        try:
            result = runner(
                ["/usr/bin/tccutil", "reset", service, BUNDLE_ID],
                capture_output=True,
                text=True,
                timeout=30,
                check=False,
                creationflags=NO_WINDOW_CREATIONFLAGS,
            )
        except (OSError, subprocess.TimeoutExpired) as exc:
            log.warning("TCC reset for %s did not run: %s", service, exc)
            continue
        if result.returncode == 0:
            log.info("Reset stale TCC rows for %s (%s).", service, BUNDLE_ID)
        else:
            detail = (result.stderr or result.stdout or "unknown error").strip()
            log.warning("TCC reset for %s failed: %s", service, detail[-300:])


# Fingerprint of the last rebuild this install performed. A rebuild that does
# not satisfy the very probe that triggered it is not a repair — it is a loop
# that costs the user every macOS permission on every start (BUG-161).
_REBUILD_MARKER_FILENAME = "macos-bundle-rebuild.json"


def _rebuild_marker_path() -> Path:
    from dodaios.core.paths import user_data_dir

    return user_data_dir() / _REBUILD_MARKER_FILENAME


def _rebuild_fingerprint(
    bundle: Path, *, install_root: Path, identity: str | None = None
) -> dict[str, str | None]:
    """Everything that decides whether a fresh build could come out different."""
    return {
        "cdhash": _bundle_cdhash(bundle),
        "install_root": str(install_root),
        "python": f"{sys.version_info.major}.{sys.version_info.minor}",
        "machine": platform.machine(),
        # A signing identity that appeared since the last build is a reason to
        # build again: the result carries a rebuild-proof TCC identity.
        "identity": identity,
    }


def _record_rebuild(bundle: Path, *, install_root: Path, identity: str | None = None) -> None:
    """Note what this rebuild produced, so a repeat of it can be recognized."""
    marker = _rebuild_marker_path()
    try:
        marker.parent.mkdir(parents=True, exist_ok=True)
        marker.write_text(
            json.dumps(
                _rebuild_fingerprint(bundle, install_root=install_root, identity=identity),
                sort_keys=True,
            ),
            encoding="utf-8",
        )
    except OSError:
        # Best-effort: without the note the next start rebuilds once more,
        # which is the behaviour that existed before this guard.
        log.debug("Could not record the macOS bundle rebuild fingerprint.", exc_info=True)


def _rebuild_would_repeat(bundle: Path, *, install_root: Path, identity: str | None = None) -> bool:
    """Whether rebuilding now would reproduce the build that just failed a probe.

    Same sources, same interpreter, same machine, same signing identity, and
    the bundle on disk is still byte-identical to what the last rebuild
    signed: a fresh build can only produce the same app and fail the same
    probe again. Doing it anyway changes an ad-hoc signature, and macOS
    answers a changed signature by orphaning every recorded TCC grant — the
    "I allow everything, restart, and it asks again" loop (BUG-161). A
    launchable bundle is worth more than a probe verdict that no rebuild can
    satisfy.
    """
    try:
        recorded = json.loads(_rebuild_marker_path().read_text(encoding="utf-8"))
    except (OSError, ValueError):
        # Nothing recorded, unreadable, or not JSON: to this caller they all
        # mean the same thing — no previous rebuild to compare against.
        return False
    if not isinstance(recorded, dict):
        return False
    current = _rebuild_fingerprint(bundle, install_root=install_root, identity=identity)
    if current["cdhash"] is None:
        # Without a readable signature we cannot prove the bundle is the one
        # the last rebuild produced, so the guard must not suppress a repair.
        return False
    return recorded == current


def _launchable_issue(candidate: Path) -> str | None:
    """Name the first reason ``candidate`` is not a usable app bundle.

    Every rebuild changes the ad-hoc signature and therefore voids every
    recorded TCC grant (BUG-083). A rebuild that cannot say WHY it happened is
    undiagnosable from a user's log — which is exactly the position the
    "permissions keep resetting" reports left us in (BUG-159).
    """
    info_path = candidate / "Contents" / "Info.plist"
    if candidate.name != APP_DIR_NAME:
        return f"unexpected bundle directory name: {candidate.name}"
    if candidate.is_symlink():
        return "bundle path is a symlink"
    if not candidate.is_dir():
        return "bundle directory is missing"
    if not info_path.is_file():
        return "Info.plist is missing"
    try:
        with info_path.open("rb") as stream:
            info = plistlib.load(stream)
    except (OSError, plistlib.InvalidFileException) as exc:
        # The caller receives the plist failure text.
        return f"Info.plist is unreadable: {exc}"
    executable_name = info.get("CFBundleExecutable")
    if not isinstance(executable_name, str) or Path(executable_name).name != executable_name:
        return f"invalid CFBundleExecutable: {executable_name!r}"
    if info.get("CFBundleIdentifier") != BUNDLE_ID:
        return f"bundle id is {info.get('CFBundleIdentifier')!r}, expected {BUNDLE_ID!r}"
    if info.get("CFBundlePackageType") != "APPL":
        return f"package type is {info.get('CFBundlePackageType')!r}, expected 'APPL'"
    if info.get("JarvisBundleFormatVersion") != _BUNDLE_FORMAT_VERSION:
        return (
            f"bundle format version is {info.get('JarvisBundleFormatVersion')!r}, "
            f"expected {_BUNDLE_FORMAT_VERSION}"
        )
    executable = candidate / "Contents" / "MacOS" / executable_name
    if not executable.is_file():
        return f"executable is missing: {executable.name}"
    if executable.is_symlink():
        return "executable is a symlink"
    if not _is_macho_executable(executable):
        return "executable is not a Mach-O binary"
    signature = _codesign_issue(candidate)
    if signature is not None:
        return f"code signature is invalid: {signature[-300:]}"
    return None


def macos_app_bundle_is_launchable(bundle: Path | None = None) -> bool:
    """Validate native executable, canonical metadata, and code signature."""
    return _launchable_issue(bundle or macos_app_bundle_path()) is None


def macos_launch_services_command(
    bundle: Path | None = None,
    *,
    background: bool = False,
    wait_for_exit: bool = False,
    new_instance: bool = False,
    arguments: tuple[str, ...] = (),
) -> list[str]:
    """Build the ``open`` argv that enters through LaunchServices."""
    candidate = bundle or macos_app_bundle_path()
    command = ["/usr/bin/open"]
    if background:
        command.append("-g")
    if wait_for_exit:
        command.append("-W")
    if new_instance:
        command.append("-n")
    command.extend(["-a", str(candidate)])
    if arguments:
        command.append("--args")
        command.extend(arguments)
    return command


_LSREGISTER = (
    "/System/Library/Frameworks/CoreServices.framework/Frameworks"
    "/LaunchServices.framework/Support/lsregister"
)


def register_with_launch_services(bundle: Path) -> bool:
    """Announce the bundle to LaunchServices AND Spotlight.

    Writing the ``.app`` is only half the job. Launchpad and the ``open -a``
    name lookup resolve through the LaunchServices database, which is rebuilt
    from directory scans that are not immediate. ``lsregister`` registers one
    bundle right away — the macOS counterpart of the Windows Start-Menu shell
    notification and the Linux ``update-desktop-database`` call.

    Spotlight is NOT that database: its search field answers from the per-volume
    metadata store, so a bundle LaunchServices knows can still be missing from
    Spotlight (the 2026-09-16 report). The bundle is therefore also imported
    into Spotlight, which warns with the admin repair command when the volume's
    index itself is broken (``macos_search_index``).

    Best-effort and idempotent. Returns ``True`` only when ``lsregister`` ran
    cleanly; a failure degrades to "appears after the next login", never to an
    error.
    """
    if sys.platform != "darwin":
        return False
    from dodaios.setup.macos_search_index import announce_to_spotlight

    try:
        announce_to_spotlight(bundle)
    except Exception as exc:  # noqa: BLE001 - search registration is best-effort
        log.debug("Spotlight import skipped: %s", exc)
    tool = Path(_LSREGISTER)
    if not tool.is_file():
        log.debug("lsregister not present; relying on the periodic rescan")
        return False
    try:
        result = subprocess.run(  # noqa: S603 - fixed system path, no shell
            [str(tool), "-f", str(bundle)],
            timeout=60,
            stdin=subprocess.DEVNULL,
            capture_output=True,
            text=True,
            check=False,
        )
        if result.returncode != 0:
            log.debug(
                "lsregister failed (rc=%s): %s",
                result.returncode,
                (result.stderr or "").strip()[:300],
            )
            return False
        log.debug("Registered with LaunchServices: %s", bundle)
        return True
    except Exception as exc:  # noqa: BLE001 - search registration is best-effort
        log.debug("LaunchServices registration skipped: %s", exc)
        return False


def unregister_from_launch_services(bundle: Path) -> bool:
    """Drop ``bundle`` from the LaunchServices database.

    A deleted or moved app otherwise lingers as a second copy of the app in
    "Open With" and as a dead target for ``open -b`` until the next database
    rebuild. Works on a path that no longer exists. Best-effort, never raises.
    """
    if sys.platform != "darwin" or not Path(_LSREGISTER).is_file():
        return False
    try:
        result = subprocess.run(  # noqa: S603 - fixed system path, no shell
            [_LSREGISTER, "-u", str(bundle)],
            timeout=60,
            stdin=subprocess.DEVNULL,
            capture_output=True,
            text=True,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
    except (OSError, subprocess.SubprocessError) as exc:
        log.debug("LaunchServices unregistration skipped: %s", exc)
        return False
    return result.returncode == 0


def _try_build_icns(resources_dir: Path) -> str | None:
    """Best-effort ``dodaios.icns`` creation; never block bundle creation."""
    if sys.platform != "darwin":
        return None
    try:
        from PIL import Image  # noqa: PLC0415 - optional at this boundary

        source = Path(__file__).resolve().parents[1] / "assets" / "icons" / "dodaios.png"
        if not source.is_file():
            return None
        with tempfile.TemporaryDirectory() as raw_tmp:
            iconset = Path(raw_tmp) / "dodaios.iconset"
            iconset.mkdir()
            image = Image.open(source).convert("RGBA")
            # Apple's iconset grammar allows exactly 16/32/128/256/512 (+@2x);
            # a 64x64 member is outside it and iconutil rejects the whole
            # iconset over one bad name, so the app shipped without any icon.
            # The 64 px slot is already covered by [email protected].
            for size in (16, 32, 128, 256, 512):
                image.resize((size, size)).save(iconset / f"icon_{size}x{size}.png")
                image.resize((size * 2, size * 2)).save(iconset / f"icon_{size}x{size}@2x.png")
            output = resources_dir / "dodaios.icns"
            result = subprocess.run(
                ["iconutil", "-c", "icns", str(iconset), "-o", str(output)],
                capture_output=True,
                text=True,
                timeout=60,
                check=False,
                creationflags=NO_WINDOW_CREATIONFLAGS,
            )
            if result.returncode == 0 and output.is_file():
                return "dodaios"
    except Exception as exc:  # noqa: BLE001 - the icon is optional
        log.debug("icns build skipped: %s", exc)
    return None


def _bundle_plist() -> dict[str, object]:
    """Return metadata shared by local and future signed bundle builders."""
    return {
        "CFBundleName": APP_NAME,
        "CFBundleDisplayName": APP_NAME,
        "CFBundleIdentifier": BUNDLE_ID,
        "CFBundlePackageType": "APPL",
        "CFBundleShortVersionString": _version(),
        "CFBundleVersion": _version(),
        "JarvisBundleFormatVersion": _BUNDLE_FORMAT_VERSION,
        "LSMinimumSystemVersion": "11.0",
        "NSHighResolutionCapable": True,
        # Every NS...UsageDescription string comes from the one table shared
        # with dodaios.spec (the .dmg app), never from a copy kept here. The
        # German and Spanish text is declared here and written as
        # <lang>.lproj/InfoPlist.strings by _write_localizations.
        **_privacy_strings().usage_descriptions(),
        **_privacy_strings().localization_plist_keys(),
    }


def _write_localizations(resources: Path) -> None:
    """Write the German and Spanish ``InfoPlist.strings`` into ``resources``.

    Part of laying out a bundle, before it is signed (the files are in the seal).
    Existing installed bundles are NOT rewritten: the format version stays, because
    a bump would rebuild every bundle and an ad-hoc rebuild is a new identity that
    re-asks every permission. The next rebuild for another reason carries them.
    """
    _privacy_strings().write_localizations(resources)


def _remove_path(path: Path) -> None:
    if path.is_symlink() or path.is_file():
        path.unlink(missing_ok=True)
    elif path.exists():
        shutil.rmtree(path)


def _write_cross_platform_fixture_bundle(bundle: Path) -> Path:
    """Create a structural fixture when a test injects a path off macOS."""
    _remove_path(bundle)
    contents = bundle / "Contents"
    macos_dir = contents / "MacOS"
    resources = contents / "Resources"
    macos_dir.mkdir(parents=True)
    resources.mkdir(parents=True)
    executable_name = MACOS_EXECUTABLE_NAME
    executable = macos_dir / executable_name
    executable.write_bytes(b"\xcf\xfa\xed\xfeJARVIS_TEST_FIXTURE\n")
    executable.chmod(executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
    info = _bundle_plist()
    info["CFBundleExecutable"] = executable_name
    with (contents / "Info.plist").open("wb") as stream:
        plistlib.dump(info, stream)
    _write_localizations(resources)
    return bundle


_LINK_INFO_SCRIPT = (
    "import json, platform, sys, sysconfig\n"
    "data = {name: sysconfig.get_config_var(name) or '' for name in "
    "('PYTHONFRAMEWORK', 'LDLIBRARY', 'LIBDIR', 'PYTHONFRAMEWORKPREFIX')}\n"
    "data['base_prefix'] = sys.base_prefix\n"
    "data['include'] = sysconfig.get_paths()['include']\n"
    "data['machine'] = platform.machine()\n"
    "print(json.dumps(data))\n"
)


def _runtime_link_info(venv_python: Path) -> dict:
    """Ask the managed venv interpreter how its runtime library is laid out."""
    try:
        result = subprocess.run(
            [str(venv_python), "-B", "-c", _LINK_INFO_SCRIPT],
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            timeout=60,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise RuntimeError(f"could not query the venv interpreter {venv_python}: {exc}") from exc
    if result.returncode != 0:
        detail = (result.stderr or result.stdout or "unknown interpreter error").strip()
        raise RuntimeError(f"venv runtime introspection failed: {detail[-1200:]}")
    try:
        return json.loads(result.stdout.strip().splitlines()[-1])
    except (ValueError, IndexError) as exc:
        raise RuntimeError(f"venv runtime introspection returned invalid JSON: {exc}") from exc


# A fully versioned uv/python-build-standalone prefix directory name, for
# example ``cpython-3.12.13-macos-aarch64-none``. Group "head" keeps the
# implementation and major.minor; "tail" keeps the platform suffix.
_VERSIONED_PREFIX_RE = re.compile(r"^(?P<head>[^-]+-\d+\.\d+)\.\d+(?P<tail>-.*)?$")


def _prefer_unversioned_runtime(dylib: Path, base_prefix: Path | None) -> Path:
    """Prefer an unversioned sibling runtime dir when one holds the dylib.

    uv keeps a ``cpython-3.12-...`` alias beside the fully versioned
    ``cpython-3.12.13-...`` install. Linking (and rpath-ing) against the
    alias keeps the bundle working across uv patch upgrades that replace the
    versioned directory.
    """
    if base_prefix is None:
        return dylib
    match = _VERSIONED_PREFIX_RE.match(base_prefix.name)
    if match is None:
        return dylib
    try:
        relative = dylib.relative_to(base_prefix)
    except ValueError:  # A library outside the base prefix keeps its original path.
        return dylib
    candidate = base_prefix.with_name(match.group("head") + (match.group("tail") or ""))
    sibling = candidate / relative
    try:
        if sibling.is_file():
            return sibling
    except OSError:  # A missing sibling library keeps the original path.
        return dylib
    return dylib


def _resolve_runtime_dylib(info: dict) -> Path:
    """Locate the runtime libpython/framework dylib to link the stub against."""
    ldlibrary = str(info.get("LDLIBRARY") or "")
    if not ldlibrary:
        raise RuntimeError("the venv interpreter reported no LDLIBRARY config variable")
    roots = [
        Path(str(root)) for root in (info.get("LIBDIR"), info.get("PYTHONFRAMEWORKPREFIX")) if root
    ]
    base_prefix = str(info.get("base_prefix") or "")
    if base_prefix:
        roots.append(Path(base_prefix) / "lib")
    candidates = [root / ldlibrary for root in roots]
    for candidate in candidates:
        if candidate.is_file():
            return _prefer_unversioned_runtime(
                candidate, Path(base_prefix) if base_prefix else None
            )
    listing = ", ".join(str(candidate) for candidate in candidates) or "(none)"
    raise RuntimeError(f"no linkable Python runtime library found; tried: {listing}")


def _compile_stub(
    stub_c: Path,
    dylib: Path,
    include_dir: Path,
    machine: str,
    defines: list[str],
    out_path: Path,
) -> None:
    """Compile the in-repo stub launcher into the bundle's Mach-O executable."""
    command = [
        "/usr/bin/xcrun",
        "clang",
        "-O2",
        "-Wall",
        "-arch",
        machine,
        "-I",
        str(include_dir),
        str(stub_c),
        str(dylib),
        f"-Wl,-rpath,{dylib.parent}",
        *defines,
        "-o",
        str(out_path),
    ]
    hint = "install the Xcode Command Line Tools (xcode-select --install)"
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            timeout=300,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
    except FileNotFoundError as exc:
        raise RuntimeError(f"clang is not available ({exc}); {hint}") from exc
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise RuntimeError(f"stub launcher compilation failed: {exc}; {hint}") from exc
    if result.returncode != 0:
        detail = (result.stderr or result.stdout or "unknown clang error").strip()
        raise RuntimeError(f"stub launcher compilation failed: {detail[-1200:]}; {hint}")


def _build_native_bundle(install_root: Path, work_dir: Path) -> Path:
    """Compile the stub launcher and lay out the app bundle in ``work_dir``."""
    entry = install_root / "dodaios" / "setup" / "macos_launcher_entry.py"
    if not entry.is_file():
        raise FileNotFoundError(f"macOS launcher entry is missing: {entry}")
    stub_c = Path(__file__).resolve().parent / "macos_stub_launcher.c"
    if not stub_c.is_file():
        raise FileNotFoundError(f"macOS stub launcher source is missing: {stub_c}")

    # Deliberately NOT resolve()d: the venv interpreter is a symlink chain to
    # the base runtime, and CPython's venv detection looks for pyvenv.cfg next
    # to the UNRESOLVED executable path. Resolving it would point the embedded
    # interpreter at the base install and lose the venv's site-packages.
    venv_python = _venv_python(install_root)
    info = _runtime_link_info(venv_python)
    dylib = _resolve_runtime_dylib(info)
    machine = str(info.get("machine") or "") or platform.machine()

    bundle = work_dir / APP_DIR_NAME
    macos_dir = bundle / "Contents" / "MacOS"
    resources = bundle / "Contents" / "Resources"
    macos_dir.mkdir(parents=True)
    resources.mkdir(parents=True)

    executable_name = MACOS_EXECUTABLE_NAME
    plist = _bundle_plist()
    plist["CFBundleExecutable"] = executable_name
    icon_stem = _try_build_icns(resources)
    if icon_stem is not None:
        plist["CFBundleIconFile"] = icon_stem

    executable = macos_dir / executable_name
    # The paths become C string literals via -D macros; subprocess passes each
    # define as one argv element, so spaces in paths survive verbatim.
    defines = [
        f'-DJARVIS_VENV_PYTHON="{venv_python}"',
        f'-DJARVIS_ENTRY_SCRIPT="{entry}"',
    ]
    _compile_stub(
        stub_c,
        dylib,
        Path(str(info.get("include") or "")),
        machine,
        defines,
        executable,
    )
    executable.chmod(executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
    with (bundle / "Contents" / "Info.plist").open("wb") as stream:
        plistlib.dump(plist, stream)
    _write_localizations(resources)
    return bundle


def _sign_bundle(bundle: Path, identity: str | None = None) -> None:
    """Sign with the local identity (rebuild-proof TCC) or ad-hoc (``None``)."""
    signer = identity or "-"
    result = subprocess.run(
        ["/usr/bin/codesign", "--force", "--deep", "--sign", signer, str(bundle)],
        capture_output=True,
        text=True,
        timeout=60,
        check=False,
        creationflags=NO_WINDOW_CREATIONFLAGS,
    )
    if result.returncode != 0:
        detail = (result.stderr or result.stdout or "unknown codesign error").strip()
        kind = "ad-hoc" if identity is None else f"identity {identity}"
        raise RuntimeError(f"code signing ({kind}) failed: {detail[-1200:]}")
    issue = _codesign_issue(bundle)
    if issue is not None:
        raise RuntimeError(
            f"the generated macOS bundle failed code-signature verification: {issue[-1200:]}"
        )


def _runtime_identity_valid(
    bundle: Path,
    *,
    install_root: Path,
    diagnostics: list[str] | None = None,
) -> bool:
    """Verify native identity and imports against the managed checkout.

    When ``diagnostics`` is given, human-readable probe evidence is appended
    to it so failed checks can surface the real cause to the installer.
    """
    if sys.platform != "darwin":
        return True
    descriptor, raw_probe = tempfile.mkstemp(prefix="jarvis-bundle-probe-", suffix=".json")
    os.close(descriptor)
    probe = Path(raw_probe)
    probe.unlink(missing_ok=True)
    try:
        result = subprocess.run(
            macos_launch_services_command(
                bundle,
                wait_for_exit=True,
                new_instance=True,
                arguments=("--jarvis-identity-probe", str(probe)),
            ),
            capture_output=True,
            text=True,
            timeout=60,
            check=False,
            creationflags=NO_WINDOW_CREATIONFLAGS,
        )
        if diagnostics is not None:
            stderr_tail = (result.stderr or "").strip()[-500:]
            diagnostics.append(
                f"open returncode {result.returncode}, stderr tail: {stderr_tail or '(empty)'}"
            )
        # ``open -W`` can lose its wait hook after the probe process exits;
        # a written payload is still checked for the full runtime identity below.
        if not probe.is_file():
            if diagnostics is not None:
                diagnostics.append("probe file was not written")
            return False
        payload = json.loads(probe.read_text(encoding="utf-8"))
        if diagnostics is not None:
            diagnostics.append(f"probe payload: {payload!r}")
        expected_bundle = bundle.resolve()
        reported_bundle = Path(str(payload.get("bundle_path", ""))).resolve()
        executable = Path(str(payload.get("executable", ""))).resolve()
        launcher_file = Path(str(payload.get("launcher_file", ""))).resolve()
        reported_install_root = Path(str(payload.get("install_root", ""))).resolve()
        executable_root = expected_bundle / "Contents" / "MacOS"
        expected_install_root = install_root.resolve()
        expected_launcher_root = expected_install_root / "dodaios" / "ui" / "web"
        return (
            payload.get("bundle_id") == BUNDLE_ID
            and reported_bundle == expected_bundle
            and executable.is_relative_to(executable_root)
            and launcher_file.is_file()
            and launcher_file.is_relative_to(expected_launcher_root)
            and reported_install_root == expected_install_root
            and payload.get("python_version")
            == f"{sys.version_info.major}.{sys.version_info.minor}"
            and payload.get("machine") == platform.machine()
        )
    except (OSError, ValueError, json.JSONDecodeError, subprocess.TimeoutExpired) as exc:
        # Diagnostics record the unavailable identity before this probe fails.
        if diagnostics is not None:
            diagnostics.append(f"identity probe failed: {type(exc).__name__}: {exc}")
        return False
    finally:
        probe.unlink(missing_ok=True)


def _running_managed_bundle(
    *,
    install_root: Path,
    diagnostics: list[str] | None = None,
) -> Path | None:
    """Return the bundle THIS process runs from, when it is our managed app.

    A running process is proof no probe can beat: if we are executing as a
    bundle that carries our id and imports the managed checkout, the install
    is valid and must be left alone — wherever the user keeps the app.

    The location is deliberately NOT part of the verdict (BUG-161). Dragging
    an app to ``/Applications`` is the most ordinary thing a Mac user does,
    and the old path equality turned it into a permanent loop: the canonical
    ``~/Applications`` slot looked empty, every start rebuilt a bundle there,
    the rebuild changed the ad-hoc signature shared by both copies, and
    ``tccutil reset`` then wiped the grants of the app that was running at
    that moment. The user re-granted everything and the next start did it
    again. TCC pins grants to the bundle id and signature, never to a path,
    so the path can never be the reason to rebuild.
    """
    if sys.platform != "darwin":
        return None
    try:
        from Foundation import NSBundle  # type: ignore[import-not-found]

        import dodaios.ui.web.launcher as launcher

        current = NSBundle.mainBundle()
        current_bundle = Path(str(current.bundlePath() or "")).resolve()
        launcher_file = Path(str(launcher.__file__ or "")).resolve()
        expected_root = install_root.resolve()
        current_id = str(current.bundleIdentifier() or "")
        reasons: list[str] = []
        if current_id != BUNDLE_ID:
            reasons.append(f"running bundle id is {current_id!r}, expected {BUNDLE_ID!r}")
        if current_bundle.suffix != ".app":
            reasons.append(f"not running from an app bundle: {current_bundle}")
        if not launcher_file.is_file():
            reasons.append(f"launcher module has no file on disk: {launcher_file}")
        elif not launcher_file.is_relative_to(expected_root / "dodaios" / "ui" / "web"):
            reasons.append(f"launcher {launcher_file} is outside the checkout {expected_root}")
        if diagnostics is not None:
            diagnostics.extend(f"current process: {reason}" for reason in reasons)
        return None if reasons else current_bundle
    except (ImportError, OSError, TypeError, ValueError) as exc:
        # Diagnostics record the failed process probe when requested.
        if diagnostics is not None:
            diagnostics.append(f"current process: probe failed: {type(exc).__name__}: {exc}")
        return None


def _install_native_bundle(
    install_root: Path, bundle: Path, *, identity: str | None = None
) -> Path:
    """Build beside the destination and replace it atomically with rollback."""
    parent = bundle.parent
    parent.mkdir(parents=True, exist_ok=True)
    previous_identity = _bundle_tcc_identity(bundle) if bundle.exists() else None
    with tempfile.TemporaryDirectory(prefix=".jarvis-native-", dir=parent) as raw_work:
        work = Path(raw_work)
        built = _build_native_bundle(install_root, work)
        _sign_bundle(built, identity)
        previous = work / "previous.app"
        if bundle.exists() or bundle.is_symlink():
            bundle.rename(previous)
        try:
            built.rename(bundle)
            if not macos_app_bundle_is_launchable(bundle):
                raise RuntimeError(
                    "the installed macOS application bundle failed the launchable "
                    f"check (native executable, metadata, or signature): {bundle}"
                )
            diagnostics: list[str] = []
            if not _runtime_identity_valid(
                bundle, install_root=install_root, diagnostics=diagnostics
            ):
                detail = "; ".join(diagnostics) or "no probe diagnostics captured"
                raise RuntimeError(
                    f"the installed app reported an unexpected runtime identity ({detail})"
                )
        except Exception:
            _remove_path(bundle)
            if previous.exists() or previous.is_symlink():
                previous.rename(bundle)
            raise
    # An ad-hoc rebuild changed the app's TCC identity: every recorded grant
    # is now orphaned and would read as silently DENIED (BUG-083). With the
    # certificate identity the requirement is unchanged and nothing is reset.
    _reset_after_identity_change(bundle, previous_identity)
    return bundle


def _bundle_metadata_is_current(bundle: Path) -> bool:
    """Whether the bundle's ``Info.plist`` names this version and this app name."""
    try:
        with (bundle / "Contents" / "Info.plist").open("rb") as stream:
            info = plistlib.load(stream)
    except (OSError, ValueError, plistlib.InvalidFileException):
        # An unreadable plist has no usable metadata.
        return False
    return (
        info.get("CFBundleShortVersionString") == _version()
        and info.get("CFBundleName") == APP_NAME
        and info.get("CFBundleDisplayName") == APP_NAME
    )


def _stamp_current_metadata(staged: Path) -> None:
    info_path = staged / "Contents" / "Info.plist"
    with info_path.open("rb") as stream:
        info = plistlib.load(stream)
    info["CFBundleShortVersionString"] = _version()
    info["CFBundleVersion"] = _version()
    # The name the menu bar shows; a bundle built under an earlier name still
    # carries that one after the folder was renamed.
    info["CFBundleName"] = APP_NAME
    info["CFBundleDisplayName"] = APP_NAME
    with info_path.open("wb") as stream:
        plistlib.dump(info, stream)


def _refresh_bundle_metadata(bundle: Path, identity: str) -> Path:
    """Make Finder's "Get Info" and the menu bar show what is actually installed.

    The bundle is kept across source updates, so its ``Info.plist`` froze at
    the version and the name that first built it. Under the certificate
    identity the code requirement does not depend on the bundle's bytes, so the
    metadata can be brought up to date without costing a single permission. An
    ad-hoc bundle is never touched here — for it, any new signature is a new
    TCC identity; it keeps the earlier name inside until a rebuild that happens
    for another reason.
    """
    refreshed = _resign_bundle_in_place(bundle, identity, prepare=_stamp_current_metadata)
    log.info(
        "macOS app bundle metadata updated to %s %s: %s", APP_NAME, _version(), bundle
    )
    return refreshed


def _resign_bundle_in_place(bundle: Path, identity: str, *, prepare=None) -> Path:
    """Move a healthy ad-hoc bundle onto the certificate identity.

    Same files, new signature: a copy is signed beside the original and
    swapped in atomically, so a running instance keeps its own (old) inode
    and nothing is ever half-signed on disk. This is the ONE remaining
    identity change the user pays for with a final round of re-granting —
    after it, no rebuild can orphan a grant again. ``prepare`` may edit the
    staged copy before it is signed.
    """
    parent = bundle.parent
    previous_identity = _bundle_tcc_identity(bundle)
    with tempfile.TemporaryDirectory(prefix=".jarvis-resign-", dir=parent) as raw_work:
        work = Path(raw_work)
        staged = work / bundle.name
        shutil.copytree(bundle, staged, symlinks=True)
        if prepare is not None:
            prepare(staged)
        _sign_bundle(staged, identity)
        if not _signed_with_certificate(staged):
            raise RuntimeError("re-signing produced a bundle without a certificate identity")
        previous = work / "previous.app"
        bundle.rename(previous)
        try:
            staged.rename(bundle)
            if not macos_app_bundle_is_launchable(bundle):
                raise RuntimeError(
                    "the re-signed macOS application bundle failed the launchable check"
                )
        except Exception:
            _remove_path(bundle)
            if previous.exists() or previous.is_symlink():
                previous.rename(bundle)
            raise
    _reset_after_identity_change(bundle, previous_identity)
    return bundle


def _reset_after_identity_change(bundle: Path, previous_identity: str | None) -> None:
    """Drop the orphaned TCC rows once, when the bundle's identity changed (BUG-083).

    A rebuild loop (a failing identity probe, a churning interpreter) must not
    wipe the user's permissions on every start (BUG-159, BUG-161): that loop is
    stopped one layer up, by the rebuild fingerprint that refuses to build the
    identical app again, so this only ever runs for a rebuild that really
    happened. The app then asks again just in time, at the moment a feature
    needs a permission; there is nothing to explain up front.
    """
    if _tcc_reset_needed(previous_identity, _bundle_tcc_identity(bundle)):
        _reset_stale_tcc_grants()


def ensure_macos_app_bundle(
    *,
    install_dir: Path | None = None,
    applications_dir: Path | None = None,
    create_signing_identity: bool = False,
) -> Path | None:
    """Ensure the app bundle (see ``_ensure_macos_app_bundle``) and keep the
    login item aimed at it, so a moved app still starts at login."""
    bundle = _ensure_macos_app_bundle(
        install_dir=install_dir,
        applications_dir=applications_dir,
        create_signing_identity=create_signing_identity,
    )
    if applications_dir is None and sys.platform == "darwin":
        from dodaios.autostart.macos import retarget_launch_agent
        from dodaios.platform.permissions import remove_leftover_state_files

        # An upgrade drops the two state files the permission wall of an earlier
        # build kept; nothing reads them any more.
        remove_leftover_state_files()
        # A repair that failed still leaves the app wherever it was moved to,
        # and login must find it there.
        target = bundle or macos_app_bundle_path()
        if target.is_dir():
            retarget_launch_agent(target)
    return bundle


def _ensure_macos_app_bundle(
    *,
    install_dir: Path | None = None,
    applications_dir: Path | None = None,
    create_signing_identity: bool = False,
) -> Path | None:
    """Ensure ``/Applications/<APP_DIR_NAME>`` has a stable identity.

    ``~/Applications`` is used instead when this account cannot write
    ``/Applications``; an existing install there is moved over once, and a
    bundle under an earlier name is renamed once
    (``rename_legacy_macos_app_bundles``).

    A valid existing bundle is preserved byte-for-byte so normal source
    updates cannot churn its local TCC identity. ``create_signing_identity``
    allows the one password dialog that trusts a fresh per-user signing
    certificate — only the installer passes it; the running app merely looks
    the identity up. Off macOS, this is a no-op unless a caller explicitly
    injects an applications directory for tests.
    """
    global _LAST_ERROR
    _LAST_ERROR = None
    if applications_dir is None:
        if sys.platform != "darwin":
            log.info("App bundle skipped: only macOS uses .app bundles.")
            return None
        rename_legacy_macos_app_bundles()
        _promote_to_system_applications()
        applications_dir = macos_applications_dir()
    else:
        rename_legacy_macos_app_bundles((applications_dir,))
    try:
        install_root = (install_dir or _default_install_dir()).resolve()
        bundle = macos_app_bundle_path(applications_dir=applications_dir)
        if _is_foreign_bundle(bundle):
            # Rebuilding "repairs" by replacing; that would destroy an app the
            # user installed themselves (the DMG build shares our name).
            raise RuntimeError(
                f"{bundle} is a separately installed app with its own bundle id; "
                "it is left untouched and no second copy is written next to it"
            )
        diagnostics: list[str] = []
        identity = (
            ensure_local_signing_identity(create=create_signing_identity)
            if sys.platform == "darwin"
            else None
        )
        # The app running right now IS the installed app — including when the
        # user keeps it in /Applications. Nothing to repair, and a rebuild
        # under our bundle id here would strip the grants of the very process
        # asking the question (BUG-161). The same goes for moving it onto the
        # certificate identity: the reset that follows would hit this very
        # process, so that migration waits for the installer.
        running = _running_managed_bundle(install_root=install_root, diagnostics=diagnostics)
        if running is not None and not running.exists() and bundle.exists():
            # This process still carries the path it launched from, but the
            # bundle was just moved or renamed (``_promote_to_system_applications``,
            # ``rename_legacy_macos_app_bundles``).
            running = bundle
        if running is not None:
            register_with_launch_services(running)
            if identity is not None and not _signed_with_certificate(running):
                log.info(
                    "The running app is still ad-hoc signed; the next installer run "
                    "moves it onto the local signing identity."
                )
            return running
        launchable_issue = _launchable_issue(bundle) if bundle.exists() else "bundle not installed"
        if launchable_issue is None:
            if _runtime_identity_valid(bundle, install_root=install_root, diagnostics=diagnostics):
                if identity is not None and not _signed_with_certificate(bundle):
                    # Healthy but ad-hoc: same files, rebuild-proof signature.
                    # One last round of re-granting, then never again.
                    log.warning(
                        "Re-signing the macOS app bundle with the local signing identity "
                        "(this resets its macOS permissions one final time) [%s]",
                        bundle,
                    )
                    resigned = _resign_bundle_in_place(bundle, identity)
                    log.info("Moved the macOS app bundle onto the local signing identity.")
                    register_with_launch_services(resigned)
                    _record_rebuild(resigned, install_root=install_root, identity=identity)
                    return resigned
                if identity is not None and not _bundle_metadata_is_current(bundle):
                    bundle = _refresh_bundle_metadata(bundle, identity)
                # A healthy bundle is kept byte-for-byte, but LaunchServices may
                # still not know it — an interrupted earlier run, or a database
                # rebuilt since. Re-registering is a no-op when it is known, and
                # repairs "installed but unsearchable" when it is not.
                register_with_launch_services(bundle)
                return bundle
            launchable_issue = "; ".join(diagnostics) or "identity probe failed without detail"
            if _rebuild_would_repeat(bundle, install_root=install_root, identity=identity):
                # The last rebuild already produced exactly this bundle and the
                # probe still refuses it. Building it again would only change
                # the signature and cost the user every permission, so keep the
                # launchable app and say what is really wrong.
                log.warning(
                    "The macOS app bundle failed its identity probe again after a rebuild "
                    "that produced the identical app — keeping it so its macOS permissions "
                    "survive. Reason: %s [%s]",
                    launchable_issue,
                    bundle,
                )
                register_with_launch_services(bundle)
                return bundle
        # A rebuild is never routine: without the signing identity it changes
        # the ad-hoc signature and macOS then discards every permission the
        # user granted. Say why, at WARNING, so a recurring rebuild is visible
        # in the log instead of showing up as "the app keeps forgetting my
        # permissions".
        log.warning(
            "Rebuilding the macOS app bundle (%s) — reason: %s [%s]",
            "permissions are kept: local signing identity"
            if identity is not None
            else "this resets its macOS permissions",
            launchable_issue,
            bundle,
        )
        if sys.platform != "darwin":
            return _write_cross_platform_fixture_bundle(bundle)
        installed = _install_native_bundle(install_root, bundle, identity=identity)
        register_with_launch_services(installed)
        _record_rebuild(installed, install_root=install_root, identity=identity)
        log.info("Native macOS app bundle installed: %s", installed)
        return installed
    except Exception as exc:  # noqa: BLE001 - installer consumes the None result
        _LAST_ERROR = f"{type(exc).__name__}: {exc}"
        log.warning("macOS app bundle could not be written: %s", exc)
        return None


def remove_macos_app_bundle(*, applications_dir: Path | None = None) -> bool:
    """Delete the bundle on uninstall and report whether it is gone.

    Without an explicit directory both install locations are cleared, so an
    app the installer moved or the user dragged elsewhere is not left behind,
    under its current name and every earlier one.
    """
    if applications_dir is None:
        if sys.platform != "darwin":
            return True
        roots = [SYSTEM_APPLICATIONS_DIR, user_applications_dir()]
    else:
        roots = [applications_dir]
    removed = True
    for root in roots:
        for name in MACOS_APP_DIR_NAMES:
            bundle = root / name
            if not bundle.exists() and not bundle.is_symlink():
                continue
            if _is_foreign_bundle(bundle):
                log.info(
                    "Keeping %s: it is a separately installed app, not this install's.", bundle
                )
                continue
            try:
                _remove_path(bundle)
                unregister_from_launch_services(bundle)
                log.info("macOS app bundle removed: %s", bundle)
            except OSError as exc:
                log.warning("Could not remove %s: %s", bundle, exc)
                removed = False
    return removed


__all__ = [
    "APP_DIR_NAME",
    "APP_NAME",
    "BUNDLE_ID",
    "ensure_macos_app_bundle",
    "last_error",
    "macos_app_bundle_is_launchable",
    "SYSTEM_APPLICATIONS_DIR",
    "installed_macos_app_bundle_path",
    "macos_app_bundle_path",
    "macos_applications_dir",
    "user_applications_dir",
    "macos_launch_services_command",
    "register_with_launch_services",
    "remove_macos_app_bundle",
    "rename_legacy_macos_app_bundles",
    "unregister_from_launch_services",
]