diff --git a/docs/product/release-readiness.md b/docs/product/release-readiness.md index 7e44c3842f..3afd9dd8b0 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -70,6 +70,18 @@ current data. Use `loopx update plan qualification. Re-running the curl installer remains a repair path when an archive wrapper is too broken to run its own updater. +For pip and pipx, `changes_applied` reports an observed change to the installed +package version or fingerprint. A successful apply can leave the package +unchanged and still refresh host material or reconcile a stale service. +`execution.restarted_services` records the services actually restarted. The +updater rechecks the package after extension validation and inside the managed +service handoff. If identity cannot be verified, the update retains the +package-manager result and directs you to `loopx doctor --installation-only` in +the owning Python environment before retrying. +An unbound service can restart through its verified launcher and needs matching +HTTP readiness before activation succeeds. A mismatched route or response +leaves activation pending. + For contributors, keep the clone-plus-canary path: ```bash diff --git a/loopx/control_plane/heartbeat/installed_prompt_update.py b/loopx/control_plane/heartbeat/installed_prompt_update.py index e659b939a8..9ebae35f24 100644 --- a/loopx/control_plane/heartbeat/installed_prompt_update.py +++ b/loopx/control_plane/heartbeat/installed_prompt_update.py @@ -159,7 +159,8 @@ def update_with_prompts(payload: dict, *, registry: Path, runtime_root: str | No # but preserve the failed aggregate result and its original repair action. runtime_ready = bool(updated.get("ok")) execution = updated.get("execution", {}) - installed = runtime_ready or (updated.get("changes_applied") is True + installed = runtime_ready or ((updated.get("changes_applied") is True + or execution.get("package_identity_verified") is True) and execution.get("install_returncode") == 0 and execution.get("doctor_returncode") == 0) updated["upgrade_complete"] = False diff --git a/loopx/hosts/managed_service_runtime.py b/loopx/hosts/managed_service_runtime.py index ce62e107bc..9b9fecf290 100644 --- a/loopx/hosts/managed_service_runtime.py +++ b/loopx/hosts/managed_service_runtime.py @@ -23,8 +23,10 @@ import time import urllib.error import urllib.request +from xml.parsers.expat import ExpatError from ..file_lock import exclusive_file_lock, write_bytes_atomic, write_json_atomic +from ..release_manifest import RUNTIME_IDENTITY_SCHEMA_VERSION from .. import runtime_activation as activation @@ -135,13 +137,13 @@ def has_runtime_binding() -> bool: return False -def _service_command(payload: dict) -> tuple[dict[str, str], list[str]]: +def _service_command(payload: dict, *, expected_command: str | None = None) -> tuple[dict[str, str], list[str]]: arguments, _ = _launcher(payload) # Parse the command # position, rather than finding a word that could be an option's value. # This adapter accepts the installer's global options; custom invocations # remain under their original owner without any signal or persistent edit. - expected = {"com.loopx.status": "serve-status", "com.loopx.chat": "chat"}.get(payload.get("Label")) + expected = expected_command or {"com.loopx.status": "serve-status", "com.loopx.chat": "chat"}.get(payload.get("Label")) if expected is None or Path(arguments[0]).name != "loopx": raise ValueError("service_runtime_route_unverified") index = 1 @@ -158,8 +160,8 @@ def _service_command(payload: dict) -> tuple[dict[str, str], list[str]]: return options, arguments[index + 1:] -def _endpoint(payload: dict) -> int: - _, arguments = _service_command(payload) +def _endpoint(payload: dict, *, expected_command: str | None = None) -> int: + _, arguments = _service_command(payload, expected_command=expected_command) def option(flag): values = [word.split("=", 1)[1] if word.startswith(flag + "=") else arguments[i + 1] if i + 1 < len(arguments) else "" @@ -178,6 +180,23 @@ def option(flag): return port +def legacy_restart_endpoint(plist: Path, launcher: Path) -> int: + """Verify the loaded legacy route without retargeting its installation.""" + if plist.is_symlink(): + raise ValueError("service_runtime_route_unverified") + payload = plistlib.loads(plist.read_bytes()) + if not isinstance(payload, dict) or payload.get("Label") != plist.stem: + raise ValueError("service_runtime_route_unverified") + arguments, _ = _launcher(payload) + if Path(arguments[0]).resolve(strict=True) != launcher: + raise ValueError("service_runtime_route_unverified") + loaded, _ = activation._managed_service_state(plist, payload=payload) + if not loaded: + raise ValueError("service_runtime_route_unverified") + command = "chat" if plist.stem.endswith(".chat") else "serve-status" + return _endpoint(payload, expected_command=command) + + def _observer_route(payload: dict) -> Path: if not isinstance(payload, dict): raise ValueError("native_observer_route_unverified") @@ -340,13 +359,64 @@ def _start_order(paths): return sorted(paths, key=lambda path: path.stem != _OBSERVER_LABEL) +def _serving_identity(opener: urllib.request.OpenerDirector, path: Path, port: int) -> dict | None: + status = path.stem.endswith(".status") + url = f"http://127.0.0.1:{port}" + ("/?readiness=1" if status else "/api/chat/readiness") + try: + try: + response = opener.open(url, timeout=0.5) + except urllib.error.HTTPError as exc: + if status or exc.code != 404: + raise + response = opener.open(f"http://127.0.0.1:{port}/api/chat/capabilities", timeout=0.5) + with response: + body = response.read(1024 * 1024 + 1) + if len(body) > 1024 * 1024: + return None + observed = json.loads(body) + if isinstance(observed, dict): + readiness = observed.get("readiness") + ready = (observed.get("source") == "serve-status" + and isinstance(readiness, dict) and readiness.get("state") == "ready") if status else ( + observed.get("schema_version") == "loopx_chat_capabilities_v1" or + (observed.get("schema_version") == "loopx_chat_readiness_v1" + and observed.get("ok") is True and observed.get("state") == "ready")) + identity = observed.get("runtime_identity") + if ready and isinstance(identity, dict): + return identity + except (OSError, ValueError): + pass + return None + + +def managed_services_match_runtime(plists: list[Path], identity: dict) -> bool: + """Prove an unbound standard service already serves the installed package.""" + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + try: + for path in plists: + if path.is_symlink(): + return False + payload = plistlib.loads(path.read_bytes()) + if not isinstance(payload, dict) or payload.get("Label") != path.stem: + return False + port = _endpoint(payload) + if not all(activation._managed_service_state(path, payload=payload)): + return False + if _serving_identity(opener, path, port) != identity: + return False + return bool(plists) + except (OSError, ValueError, plistlib.InvalidFileException, ExpatError, subprocess.SubprocessError): + return False + + def _verify_services( services: dict[Path, int], identity: dict, *, timeout_seconds: float = _SERVICE_READINESS_TIMEOUT_SECONDS, ) -> None: - # Read back the + # A working CLI does not prove its Chat assets can serve. Read back the + # exact HTTP runtime before committing the handoff; a failed start restores # the original manager configuration instead of leaving the App spinning. pending = dict(services) @@ -354,39 +424,17 @@ def _verify_services( deadline = time.monotonic() + timeout_seconds while pending and time.monotonic() < deadline: for path, port in list(pending.items()): - status = path.stem.endswith(".status") - url = f"http://127.0.0.1:{port}" + ("/?readiness=1" if status else "/api/chat/readiness") - try: - try: - response = opener.open(url, timeout=0.5) - except urllib.error.HTTPError as exc: - if status or exc.code != 404: - raise - response = opener.open(f"http://127.0.0.1:{port}/api/chat/capabilities", timeout=0.5) - with response: - body = response.read(1024 * 1024 + 1) - if len(body) > 1024 * 1024: - continue - observed = json.loads(body) - if not isinstance(observed, dict): - continue - readiness = observed.get("readiness") - ready = (observed.get("source") == "serve-status" - and isinstance(readiness, dict) and readiness.get("state") == "ready") if status else ( - observed.get("schema_version") == "loopx_chat_capabilities_v1" or - (observed.get("schema_version") == "loopx_chat_readiness_v1" - and observed.get("ok") is True and observed.get("state") == "ready")) - if ready and observed.get("runtime_identity") == identity: - pending.pop(path) - except (OSError, ValueError): - pass + if _serving_identity(opener, path, port) == identity: + pending.pop(path) if pending: time.sleep(0.1) if pending: raise RuntimeError("service_runtime_alignment_failed") -def align_managed_runtime(executable: str) -> dict: +def align_managed_runtime( + executable: str, *, expected_python_identity: dict | None = None, +) -> dict: """Align the standard desktop services once, with rollback and Chat fencing. This is an explicit activation operation, not an installer or a change to @@ -397,7 +445,9 @@ def align_managed_runtime(executable: str) -> dict: journal = directory / ".loopx-runtime-activation.json" with exclusive_file_lock(directory / ".loopx-runtime-activation.lock", timeout_seconds=2): _recover_alignment(journal) - return _align_managed_runtime(executable, journal) + return _align_managed_runtime( + executable, journal, expected_python_identity=expected_python_identity, + ) def _recover_alignment(journal: Path) -> None: @@ -482,7 +532,7 @@ def _recover_alignment(journal: Path) -> None: journal.unlink() -def _align_managed_runtime(executable: str, journal: Path) -> dict: +def _qualified_runtime(executable: str | Path) -> tuple[Path, dict, str]: target = Path(executable) if not target.is_absolute() or not target.is_file() or not os.access(target, os.X_OK): raise ValueError("service_runtime_unverified") @@ -502,13 +552,38 @@ def _align_managed_runtime(executable: str, journal: Path) -> dict: python = python_info.get("executable") if isinstance(python_info, dict) else None if (doctor.returncode or qualified.get("ok") is not True or qualified.get("scope") != "installation_only" - or not isinstance(identity, dict) or identity.get("schema_version") != "loopx_runtime_identity_v1" + or not isinstance(identity, dict) or identity.get("schema_version") != RUNTIME_IDENTITY_SCHEMA_VERSION or not isinstance(python, str) or not Path(python).is_absolute()): raise ValueError("service_runtime_unverified") + return target, identity, python + +def qualify_expected_python_runtime( + executable: str | Path | None, expected_identity: dict, +) -> tuple[Path, dict, str]: + """Check that the live install is the package the updater already checked.""" + if executable is None: + raise activation.RuntimeActivationIdentityUnverified() + try: + qualified = _qualified_runtime(executable) + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + raise activation.RuntimeActivationIdentityUnverified() from exc + if qualified[1] != expected_identity: + raise activation.RuntimeActivationIdentityUnverified() + return qualified + + +def _align_managed_runtime( + executable: str, journal: Path, *, expected_python_identity: dict | None = None, +) -> dict: + target, identity, python = ( + qualify_expected_python_runtime(executable, expected_python_identity) + if expected_python_identity is not None else _qualified_runtime(executable) + ) plists = [Path.home() / "Library/LaunchAgents" / f"com.loopx.{kind}.plist" for kind in ("status", "chat")] originals, updates, pids, endpoints = {}, {}, {}, {} + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) for plist in plists: if not plist.exists(): continue @@ -527,6 +602,14 @@ def _align_managed_runtime(executable: str, journal: Path) -> dict: originals[plist] = original updates[plist] = plistlib.dumps(updated) pids[plist] = pid + elif pid and identity.get("package_fingerprint"): + # Pip and pipx can replace bytes in place. A verified old runtime + # on the same managed route still requires a fenced handoff. + running = _serving_identity(opener, plist, endpoints[plist]) + if (running and running.get("schema_version") == identity["schema_version"] + and running != identity): + originals[plist] = updates[plist] = original + pids[plist] = pid chat = [p for p in plists if p.exists() and p.stem.endswith(".chat")] observer = journal.parent / f"{_OBSERVER_LABEL}.plist" observer_root = None @@ -579,6 +662,11 @@ def _align_managed_runtime(executable: str, journal: Path) -> dict: or _chat_account_root(plistlib.loads(chat[0].read_bytes())) != observer_root.resolve()): raise ValueError("native_observer_owner_unverified") observer_handed_off_from_chat = lock_pid != pid + # Route and service checks above can outlast an external package replacement. + if expected_python_identity is not None and qualify_expected_python_runtime( + executable, expected_python_identity, + ) != (target, identity, python): + raise activation.RuntimeActivationIdentityUnverified() write_json_atomic(journal, {"schema_version": "loopx_managed_runtime_handoff_v1", "services": {p.stem: {"original": base64.b64encode(originals[p]).decode(), "candidate": base64.b64encode(updates[p]).decode()} for p in updates}}, diff --git a/loopx/runtime_activation.py b/loopx/runtime_activation.py index 362c106af2..d91459d10a 100644 --- a/loopx/runtime_activation.py +++ b/loopx/runtime_activation.py @@ -29,6 +29,14 @@ def __init__(self, reason: str, labels: list[str]) -> None: self.labels = labels +class RuntimeActivationIdentityUnverified(Exception): + """Service activation could no longer verify the selected Python package.""" + + def __init__(self, pending: list[str] | None = None) -> None: + super().__init__() + self.pending = pending or [] + + class RuntimeActivationFailed(Exception): def __init__(self, restarted: list[str], pending: list[str]) -> None: super().__init__("service_restart_unverified") @@ -274,7 +282,11 @@ def activate_runtime_services(*, service: str = "all", port: int = 8767, return {**payload, "ok": False, "status": "failed", "reason": reason} -def restart_managed_loopx_services(*, plists: list[Path] | None = None) -> list[str]: +def restart_managed_loopx_services( + *, + plists: list[Path] | None = None, + expected_python_installation: tuple[Path | None, dict[str, Any]] | None = None, +) -> list[str]: """Switch managed macOS services only with no accepted Chat work outstanding. After ``loopx update`` replaces the installed release, running status/chat @@ -284,13 +296,9 @@ def restart_managed_loopx_services(*, plists: list[Path] | None = None) -> list[ """ if sys.platform != "darwin": return [] - labels: list[str] = [] - chat_plists: list[Path] = [] - for plist in _managed_service_plists() if plists is None else plists: - stem = plist.stem.lower() - labels.append(plist.stem) - if stem.endswith(".chat"): - chat_plists.append(plist) + service_plists = _managed_service_plists() if plists is None else plists + labels = [plist.stem for plist in service_plists] + chat_plists = [plist for plist in service_plists if plist.stem.lower().endswith(".chat")] restarted: list[str] = [] uid = os.getuid() if hasattr(os, "getuid") else 0 try: @@ -298,7 +306,24 @@ def restart_managed_loopx_services(*, plists: list[Path] | None = None) -> list[ # Keep admission fenced until launchctl has replaced the old process. # Existing workers need no new lock: any accepted queued/active work # was checked above, including completing and orphaned queued Turns. - for label in labels: + if labels and expected_python_installation is not None: + from .hosts.managed_service_runtime import ( + _verify_services, legacy_restart_endpoint, qualify_expected_python_runtime, + ) + + try: + launcher, identity, _ = qualify_expected_python_runtime(*expected_python_installation) + except RuntimeActivationIdentityUnverified as exc: + raise RuntimeActivationIdentityUnverified(labels) from exc + try: + endpoints = {plist: legacy_restart_endpoint(plist, launcher) for plist in service_plists} + except (OSError, ValueError, plistlib.InvalidFileException, ExpatError, + subprocess.SubprocessError) as exc: + raise RuntimeActivationDeferred("service_runtime_route_unverified", labels) from exc + else: + endpoints = {} + for plist in service_plists: + label = plist.stem try: result = subprocess.run( ["launchctl", "kickstart", "-k", f"gui/{uid}/{label}"], @@ -312,8 +337,10 @@ def restart_managed_loopx_services(*, plists: list[Path] | None = None) -> list[ raise RuntimeActivationFailed( restarted, [s for s in labels if s not in restarted] ) + if plist in endpoints: + _verify_services({plist: endpoints[plist]}, identity) restarted.append(label) - except (OSError, subprocess.SubprocessError) as exc: + except (OSError, RuntimeError, subprocess.SubprocessError) as exc: raise RuntimeActivationFailed( restarted, [s for s in labels if s not in restarted] ) from exc @@ -337,6 +364,7 @@ def restart_services_for_runtime_activation( changes_applied: bool, runtime_ready: bool, installed_bin: Path | None = None, + installed_python_identity: dict[str, Any] | None = None, ) -> dict[str, Any]: """Report and perform the restart that moves services onto the new release. @@ -349,48 +377,86 @@ def restart_services_for_runtime_activation( Archive installs can select a separate bin directory. Those installs do not own the user's default managed services. Compare directories, not launcher targets: a symlink still belongs to the directory the installer updates. - Package-manager callers retain their existing activation path. + Package-manager callers can reconcile stale services after a successful + no-op install, and keep a service that already serves the verified package. """ - if not (changes_applied and runtime_ready): + if not runtime_ready or not (changes_applied or installed_python_identity): return { "restarted_services": [], "restart_status": "skipped_runtime_not_activated", } if ( installed_bin is not None + and installed_python_identity is None and installed_bin.parent.resolve() != (Path.home() / ".local/bin").resolve() ): return { "restarted_services": [], "restart_status": "skipped_custom_installation", } + aligned_restarts: list[str] = [] try: - from .hosts.managed_service_runtime import align_managed_runtime, has_runtime_binding + from .hosts.managed_service_runtime import ( + align_managed_runtime, + has_runtime_binding, + managed_services_match_runtime, + ) + plists = _managed_service_plists() if sys.platform == "darwin" else [] if sys.platform == "darwin" and has_runtime_binding(): # Preserve the existing pending-work result even when the new # installation cannot yet be qualified. Alignment rechecks under # its own lock before any manager mutation. - with managed_chat_activation_guard([p for p in _managed_service_plists() if p.stem.endswith(".chat")]): - pass + if changes_applied: + with managed_chat_activation_guard([p for p in plists if p.stem.endswith(".chat")]): + pass if installed_bin is None: + if installed_python_identity is not None: + raise RuntimeActivationIdentityUnverified() from .doctor import current_script_invocation_path installed_bin = current_script_invocation_path() if installed_bin is None: raise RuntimeActivationDeferred("service_runtime_unverified", ["com.loopx.status", "com.loopx.chat"]) - aligned = align_managed_runtime(str(installed_bin)) - other = [p for p in _managed_service_plists() if p.stem not in {"com.loopx.status", "com.loopx.chat"}] - restarted = restart_managed_loopx_services(plists=other) if other else [] - return {"restarted_services": [*aligned["restarted_services"], *restarted], - "restart_status": "restarted", "activation_pending": False} + aligned = align_managed_runtime( + str(installed_bin), expected_python_identity=installed_python_identity, + ) + aligned_restarts = aligned["restarted_services"] + other = [p for p in plists if p.stem not in {"com.loopx.status", "com.loopx.chat"}] + expected = (installed_bin, installed_python_identity) if installed_python_identity is not None else None + restarted = list(aligned_restarts) + if other: + restarted.extend(restart_managed_loopx_services( + plists=other, expected_python_installation=expected, + )) + no_restart_status = "already_active" if aligned["readiness_verified"] else "not_running" + return {"restarted_services": restarted, "activation_pending": False, + "restart_status": "restarted" if restarted else no_restart_status} + if (installed_python_identity and not changes_applied + and managed_services_match_runtime(plists, installed_python_identity)): + return {"restarted_services": [], "restart_status": "already_active", "activation_pending": False} + if plists and installed_python_identity is not None: + restarted = restart_managed_loopx_services( + plists=plists, expected_python_installation=(installed_bin, installed_python_identity), + ) + else: + restarted = restart_managed_loopx_services() return { - "restarted_services": restart_managed_loopx_services(), - "restart_status": "restarted", + "restarted_services": restarted, + "restart_status": "restarted" if restarted else "not_running", "activation_pending": False, } + except RuntimeActivationIdentityUnverified as exc: + return { + "restarted_services": aligned_restarts, + "deferred_services": exc.pending, + "restart_status": "skipped_runtime_not_activated", + "restart_reason": "service_runtime_unverified", + "package_identity_verified": False, + "activation_pending": bool(exc.pending), + } except RuntimeActivationDeferred as exc: return { - "restarted_services": [], + "restarted_services": aligned_restarts, "deferred_services": exc.labels, "restart_status": "deferred", "restart_reason": str(exc), @@ -398,12 +464,12 @@ def restart_services_for_runtime_activation( } except RuntimeActivationFailed as exc: return { - "restarted_services": exc.restarted, + "restarted_services": [*aligned_restarts, *exc.restarted], "deferred_services": exc.pending, "restart_status": "failed", "restart_reason": str(exc), "activation_pending": True, } except (OSError, ValueError, RuntimeError, subprocess.SubprocessError): - return {"restarted_services": [], "restart_status": "failed", + return {"restarted_services": aligned_restarts, "restart_status": "failed", "restart_reason": "service_runtime_alignment_failed", "activation_pending": True} diff --git a/loopx/self_update.py b/loopx/self_update.py index 6d0db1f106..a929e3eade 100644 --- a/loopx/self_update.py +++ b/loopx/self_update.py @@ -22,8 +22,10 @@ runtime_activation_qualification, ) from .doctor import collect_doctor +from .control_plane.content_digest import ENVELOPED_SHA256_PATTERN from .install_contract import NO_CLONE_INSTALL_URL from .python_install_owner import interpreter_invocation +from .release_manifest import RUNTIME_IDENTITY_SCHEMA_VERSION, release_runtime_identity from .runtime_activation import restart_services_for_runtime_activation from .self_update_download import run_archive_installer @@ -42,10 +44,16 @@ _PACKAGE_VERSION_PATTERN = re.compile(r'^__version__\s*=\s*"([^"]+)"$', re.MULTILINE) -def _installed_readback(result: subprocess.CompletedProcess[str]) -> dict[str, Any]: +def _installed_readback( + result: subprocess.CompletedProcess[str], *, installation_only: bool = False, +) -> dict[str, Any]: try: doctor = json.loads(result.stdout) if isinstance(doctor, dict): + if installation_only and ( + doctor.get("scope") != "installation_only" or doctor.get("ok") is not True + ): + return {} identity = doctor.get("service_runtime_identity") if isinstance(identity, dict): return identity @@ -54,6 +62,19 @@ def _installed_readback(result: subprocess.CompletedProcess[str]) -> dict[str, A return {} +def _python_package_key(identity: dict[str, Any]) -> tuple[str, str] | None: + version = identity.get("package_version") + fingerprint = identity.get("package_fingerprint") + if ( + identity.get("schema_version") == RUNTIME_IDENTITY_SCHEMA_VERSION + and isinstance(version, str) and version + and isinstance(fingerprint, str) + and ENVELOPED_SHA256_PATTERN.fullmatch(fingerprint) + ): + return version, fingerprint + return None + + class UpdateAction(StrEnum): """Stable operator intent for the self-update boundary.""" @@ -1023,45 +1044,44 @@ def _execute_python_distribution_update( ) driver = lifecycle.get("execution_driver") package_manager_environment = lifecycle.get("package_manager_environment") + # Keep the owning interpreter and its user site, while ignoring a caller's + # checkout and PYTHONPATH. The worker itself is already pinned at startup. + python_module = [sys.executable, "-E", "-P", "-m"] + runtime_cli = [*python_module, "loopx.cli", *route_arguments] + runtime_env = os.environ.copy() + runtime_env.pop("LOOPX_RELEASE_ROOT", None) install_command = ( ["pipx", "upgrade", str(package_manager_environment or "loopx")] if driver == "python_pipx" - else [sys.executable, "-m", "pip", "install", "--upgrade", "loopx"] + else [*python_module, "pip", "install", "--upgrade", "loopx"] ) commands = { "install": install_command, - "authority_upgrade": [sys.executable, "-m", "loopx.cli", "--format", "json", + "installation_readback": [*runtime_cli, "--format", "json", "doctor", "--installation-only"], + "authority_upgrade": [*runtime_cli, "--format", "json", "authority-archive", "upgrade", "--all-known", "--execute"], "workflow_skills": [ - sys.executable, - "-m", - "loopx.cli", + *runtime_cli, "workflow-skills", "--install", "--format", "json", ], "slash_commands": [ - sys.executable, - "-m", - "loopx.cli", + *runtime_cli, "slash-commands", "--install", "--format", "json", ], "doctor": [ - sys.executable, - "-m", - "loopx.cli", + *runtime_cli, "doctor", "--format", "json", ], "extension_doctor": [ - sys.executable, - "-m", - "loopx.cli", + *runtime_cli, "extension", "doctor", "--all-enabled", @@ -1070,9 +1090,9 @@ def _execute_python_distribution_update( "json", ], } - for step, command in commands.items(): - if step != "install": - command[3:3] = route_arguments + host_steps = ("authority_upgrade", "workflow_skills", "slash_commands", "doctor") + previous_identity = release_runtime_identity(Path(__file__).resolve().parents[1]) + installed_identity: dict[str, Any] = {} results: dict[str, subprocess.CompletedProcess[str]] = {} progress("Updating CLI through its Python package manager") results["install"] = subprocess.run( @@ -1082,35 +1102,75 @@ def _execute_python_distribution_update( timeout=timeout_seconds, ) if results["install"].returncode == 0: - for step in ("authority_upgrade", "workflow_skills", "slash_commands", "doctor"): + for step in ("installation_readback", *host_steps): progress(f"Validating updated runtime: {step}") results[step] = subprocess.run( commands[step], text=True, encoding="utf-8", errors="replace", - capture_output=True, + capture_output=True, env=runtime_env, timeout=timeout_seconds, ) if results[step].returncode != 0: break + if step == "installation_readback": + installed_identity = _installed_readback(results[step], installation_only=True) + if _python_package_key(installed_identity) is None: + break if all( step in results and results[step].returncode == 0 - for step in ("authority_upgrade", "workflow_skills", "slash_commands", "doctor") + for step in host_steps ): results["extension_doctor"] = subprocess.run( commands["extension_doctor"], text=True, encoding="utf-8", errors="replace", - capture_output=True, + capture_output=True, env=runtime_env, + timeout=timeout_seconds, + ) + progress("Rechecking package identity after extension validation") + results["activation_readback"] = subprocess.run( + commands["installation_readback"], + text=True, encoding="utf-8", errors="replace", + capture_output=True, env=runtime_env, timeout=timeout_seconds, ) + previous_key = _python_package_key(previous_identity) + installed_key = _python_package_key(installed_identity) + # Host-material checks can overlap another installer. Never certify the + # earlier package, or align services to it, after Doctor observes new bytes. + final_doctor = results.get("doctor") + final_identity = _installed_readback(final_doctor) if final_doctor is not None else {} + final_key = _python_package_key(final_identity) + activation_doctor = results.get("activation_readback") + activation_identity = ( + _installed_readback(activation_doctor, installation_only=True) + if activation_doctor is not None and activation_doctor.returncode == 0 else {} + ) + identity_verified = ( + previous_key is not None and installed_key is not None + and (final_doctor is None or final_key == installed_key) + and (activation_doctor is None or _python_package_key(activation_identity) == installed_key) + ) + installed_launcher = None + launcher_readback = activation_doctor or final_doctor + if launcher_readback is not None and launcher_readback.returncode == 0: + try: + launcher = json.loads(launcher_readback.stdout).get("path", {}).get("loopx") + if isinstance(launcher, str) and Path(launcher).is_absolute(): + installed_launcher = Path(launcher) + except (ValueError, AttributeError): + pass execution: dict[str, Any] = { "driver": driver, "python_executable": sys.executable, "install_returncode": results["install"].returncode, "install_stdout_tail": results["install"].stdout[-2000:], "install_stderr_tail": results["install"].stderr[-2000:], + "previous_runtime_identity": previous_identity, + "installed_runtime_identity": installed_identity, + "package_identity_verified": identity_verified, } - for step in ("authority_upgrade", "workflow_skills", "slash_commands", "doctor", "extension_doctor"): + for step in ("installation_readback", *host_steps, "extension_doctor", "activation_readback"): result = results.get(step) if result is None: execution[f"{step}_status"] = "skipped_prior_step_failed" @@ -1118,40 +1178,37 @@ def _execute_python_distribution_update( execution[f"{step}_returncode"] = result.returncode execution[f"{step}_stdout_tail"] = result.stdout[-2000:] execution[f"{step}_stderr_tail"] = result.stderr[-2000:] - if step == "doctor" and result.returncode == 0: - execution["installed_runtime_identity"] = _installed_readback(result) - - runtime_steps = ( - "install", - "authority_upgrade", - "workflow_skills", - "slash_commands", - "doctor", - ) - runtime_ready = all( - step in results and results[step].returncode == 0 for step in runtime_steps + runtime_ready = identity_verified and all( + step in results and results[step].returncode == 0 for step in host_steps ) extension_ready = ( "extension_doctor" in results and results["extension_doctor"].returncode == 0 ) updated = dict(payload) updated["execution"] = execution - updated["ok"] = runtime_ready and extension_ready - updated["changes_applied"] = results["install"].returncode == 0 + changes_applied = identity_verified and previous_key != installed_key execution.update( restart_services_for_runtime_activation( - changes_applied=updated["changes_applied"], + changes_applied=changes_applied, runtime_ready=runtime_ready, + installed_python_identity=activation_identity if runtime_ready else None, + installed_bin=installed_launcher, ) ) - if _retain_pending_service_activation(updated): + identity_verified = execution["package_identity_verified"] + runtime_ready = runtime_ready and identity_verified + updated["changes_applied"] = changes_applied and identity_verified + updated["ok"] = runtime_ready and extension_ready + if identity_verified and _retain_pending_service_activation(updated): return updated if updated["ok"]: updated["recommended_action"] = ( - "PyPI update and host-material readback passed; use the new LoopX process" + "Python package update and host-material readback passed; use the new LoopX process" + if updated["changes_applied"] + else "The installed Python package is unchanged; host-material readback passed" ) updated["next_action"] = { - "kind": "use_updated_runtime", + "kind": "use_updated_runtime" if updated["changes_applied"] else "review_execution", "command": "loopx doctor", "mutating": False, "requires_explicit_approval": False, @@ -1159,7 +1216,7 @@ def _execute_python_distribution_update( } elif runtime_ready: updated["recommended_action"] = ( - "the updated runtime is installed and serving; repair the blocked " + "the installed runtime passed its core checks; repair the blocked " "enabled extension providers, then rerun " "`loopx extension doctor --all-enabled --execute`" ) @@ -1170,6 +1227,18 @@ def _execute_python_distribution_update( "requires_explicit_approval": False, "reason": updated["recommended_action"], } + elif results["install"].returncode == 0 and not identity_verified: + updated["recommended_action"] = ( + "the package manager succeeded, but the installed package change could not be " + "verified; inspect the installation with `loopx doctor --installation-only`" + ) + updated["next_action"] = { + "kind": "review_update_failure", + "command": "loopx doctor --installation-only", + "mutating": False, + "requires_explicit_approval": False, + "reason": updated["recommended_action"], + } else: updated["recommended_action"] = ( "inspect the failed update step and retry the verified authority upgrade; " diff --git a/tests/architecture/test_content_digest_single_owner.py b/tests/architecture/test_content_digest_single_owner.py index ee512f209d..175480f277 100644 --- a/tests/architecture/test_content_digest_single_owner.py +++ b/tests/architecture/test_content_digest_single_owner.py @@ -230,6 +230,7 @@ "loopx.presentation.chat_bundle", "loopx.presentation.content_media_api", "loopx.presentation.static_site", + "loopx.self_update", ) # A consumer that hands `re` a pattern this file cannot fold. Folding reads diff --git a/tests/test_chat_runtime_activation.py b/tests/test_chat_runtime_activation.py index 7d6170a9b5..65e6128636 100644 --- a/tests/test_chat_runtime_activation.py +++ b/tests/test_chat_runtime_activation.py @@ -667,8 +667,9 @@ def launchctl(args, **_kwargs): @pytest.mark.parametrize("driver", ["archive_snapshot", "python_pip", "python_pipx"]) +@pytest.mark.parametrize("package_changed", [True, False]) def test_update_keeps_install_readback_but_does_not_claim_deferred_service_is_serving( - services, driver + services, driver, package_changed ): runtime, _agents, _calls = services store = ChatSessionStore(runtime) @@ -679,15 +680,21 @@ def test_update_keeps_install_readback_but_does_not_claim_deferred_service_is_se "plan": {}, "install_lifecycle": {"execution_driver": driver}, } - passed = subprocess.CompletedProcess([], 0, json.dumps({"ok": True}), "") + previous = {"schema_version": "loopx_runtime_identity_v1", "package_version": "2.4.0", + "package_fingerprint": "sha256:" + "1" * 64} + installed = {**previous, "package_fingerprint": "sha256:" + ("2" if package_changed else "1") * 64} + passed = subprocess.CompletedProcess([], 0, json.dumps({"ok": True, + "scope": "installation_only", "service_runtime_identity": installed}), "") with ( + mock.patch("loopx.self_update.release_runtime_identity", return_value=previous), mock.patch( "loopx.self_update.run_archive_installer", return_value=(passed, {}) ), mock.patch("loopx.self_update.subprocess.run", return_value=passed), ): result = execute_update_plan(payload) - assert result["changes_applied"] and not result["ok"] + assert result["changes_applied"] is (driver == "archive_snapshot" or package_changed) + assert not result["ok"] assert result["execution"]["doctor_returncode"] == 0 assert result["execution"]["restart_status"] == "deferred" assert result["next_action"]["kind"] == "retry_runtime_activation" diff --git a/tests/test_managed_service_runtime.py b/tests/test_managed_service_runtime.py index 4640707a10..5e942cf0f2 100644 --- a/tests/test_managed_service_runtime.py +++ b/tests/test_managed_service_runtime.py @@ -2,6 +2,7 @@ from __future__ import annotations from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import os from pathlib import Path @@ -10,6 +11,7 @@ import subprocess import sys import socket +from threading import Thread import time from types import SimpleNamespace import urllib.request @@ -19,7 +21,7 @@ from loopx import runtime_activation as activation from loopx.hosts import managed_service_runtime as managed_runtime -from loopx.hosts.managed_service_runtime import _retarget, align_managed_runtime +from loopx.hosts.managed_service_runtime import _retarget, _verify_services, align_managed_runtime from loopx.chat_store import ChatSessionStore @@ -590,6 +592,223 @@ def test_cli_update_moves_bound_pair_and_still_restarts_other_services(managed, assert str(replacement.resolve()) in loaded[f"com.loopx.{kind}"]["ProgramArguments"][2] +def test_python_installation_is_rechecked_inside_handoff_before_mutating_services( + managed, monkeypatch, +): + _, agents, target, _, calls, _ = managed + align_managed_runtime(str(target)) + calls.clear() + before = {path: path.read_bytes() for path in agents.glob("*.plist")} + replacement = target.with_name("next-loopx") + installed = { + "schema_version": "loopx_runtime_identity_v1", + "package_version": "2.4.0", + "package_fingerprint": "sha256:" + "2" * 64, + } + doctor = { + "ok": True, "scope": "installation_only", "service_runtime_identity": installed, + "python": {"executable": sys.executable}, + } + launcher = f"#!{sys.executable}\nprint({json.dumps(json.dumps(doctor))})\n" + replacement.write_text(launcher) + replacement.chmod(0o700) + original_guard = managed_runtime._alignment_guard + entered = [] + + @contextmanager + def replace_inside_handoff(*args): + with original_guard(*args) as owner: + entered.append(True) + replacement.write_text(launcher.replace("2" * 64, "3" * 64)) + yield owner + + monkeypatch.setattr(activation.sys, "platform", "darwin") + monkeypatch.setattr(managed_runtime, "_alignment_guard", replace_inside_handoff) + result = activation.restart_services_for_runtime_activation( + changes_applied=True, runtime_ready=True, installed_bin=replacement, + installed_python_identity=installed, + ) + + assert entered + assert result["package_identity_verified"] is False + assert result["restart_status"] == "skipped_runtime_not_activated" + assert result["restart_reason"] == "service_runtime_unverified" + assert result["restarted_services"] == [] + assert not calls + assert not (agents / ".loopx-runtime-activation.json").exists() + assert {path: path.read_bytes() for path in before} == before + + +def test_python_update_checks_legacy_service_restart_inside_chat_fence(managed, monkeypatch): + _, _, target, _, calls, _ = managed + identity = json.loads(subprocess.check_output([str(target), "doctor"]))["service_runtime_identity"] + original_guard = activation.managed_chat_activation_guard + + @contextmanager + def replace_inside_guard(plists): + with original_guard(plists): + target.write_text(target.read_text().replace("new-revision", "different-revision")) + yield + + monkeypatch.setattr(activation.sys, "platform", "darwin") + monkeypatch.setattr(activation, "managed_chat_activation_guard", replace_inside_guard) + result = activation.restart_services_for_runtime_activation( + changes_applied=True, runtime_ready=True, installed_bin=target, + installed_python_identity=identity, + ) + + assert result["package_identity_verified"] is False + assert result["restart_status"] == "skipped_runtime_not_activated" + assert calls == [] + + +@pytest.mark.parametrize("mixed", [False, True]) +@pytest.mark.parametrize("condition", ["same_install", "foreign_launcher", "loaded_mismatch", "wrong_http", "package_drift"]) +def test_python_update_verifies_legacy_service_route_and_readback(managed, monkeypatch, mixed, condition): + _, agents, target, loaded, calls, _ = managed + legacy_path = agents / "com.loopx.project.status.plist" + legacy_label = legacy_path.stem + kickstart = ("kickstart", legacy_label) + if mixed: + align_managed_runtime(str(target)) + calls.clear() + else: + for path in agents.glob("com.loopx.*.plist"): + path.unlink() + loaded.clear() + + launcher = target.parent / "selected" / "loopx" + launcher.parent.mkdir() + launcher.write_bytes(target.read_bytes()) + launcher.chmod(0o700) + identity = json.loads(subprocess.check_output([str(launcher), "doctor"]))["service_runtime_identity"] + previous_identity = {**identity, "package_version": "2.1.0"} + + class Status(BaseHTTPRequestHandler): + def do_GET(self): + assert self.path == "/?readiness=1" + active = identity if condition == "same_install" and kickstart in calls else previous_identity + body = json.dumps({"source": "serve-status", + "readiness": {"state": "ready"}, "runtime_identity": active}).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Status) as server: + thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True) + thread.start() + try: + route = target if condition == "foreign_launcher" else launcher + arguments = [str(route), "serve-status", "--host", "127.0.0.1", "--port", str(server.server_port)] + payload = {"Label": legacy_label, "ProgramArguments": arguments} + original = plistlib.dumps(payload) + legacy_path.write_bytes(original) + loaded[legacy_label] = {**payload, "ProgramArguments": + [str(target), *arguments[1:]]} if condition == "loaded_mismatch" else payload + + def verify(endpoints, expected): + if legacy_path in endpoints: + _verify_services(endpoints, expected, timeout_seconds=0.25) + + original_guard = activation.managed_chat_activation_guard + + @contextmanager + def guard(plists, **kwargs): + with original_guard(plists, **kwargs): + if condition == "package_drift" and not plists: + launcher.write_text(launcher.read_text().replace("new-revision", "other-revision")) + yield + + monkeypatch.setattr(activation.sys, "platform", "darwin") + monkeypatch.setattr(activation, "managed_chat_activation_guard", guard) + monkeypatch.setattr(managed_runtime, "_verify_services", verify) + result = activation.restart_services_for_runtime_activation( + changes_applied=False, runtime_ready=True, installed_bin=launcher, + installed_python_identity=identity, + ) + finally: + server.shutdown() + thread.join(timeout=2) + + assert legacy_path.read_bytes() == original + assert (kickstart in calls) is (condition in {"same_install", "wrong_http"}) + assert result["activation_pending"] is (condition != "same_install") + expected_restarts = {"com.loopx.status", "com.loopx.chat"} if mixed else set() + if condition == "same_install": + expected_restarts.add(legacy_label) + assert result["restart_status"] == "restarted" + else: + assert result["deferred_services"] == [legacy_label] + if condition == "package_drift": + assert result["package_identity_verified"] is False + assert set(result["restarted_services"]) == expected_restarts + + +def test_unchanged_python_update_keeps_running_standard_services(managed, monkeypatch): + _, _, _, _, calls, _ = managed + monkeypatch.setattr(activation.sys, "platform", "darwin") + installed = {"schema_version": "loopx_runtime_identity_v1", "package_version": "2.4.0", + "package_fingerprint": "sha256:" + "1" * 64} + monkeypatch.setattr(managed_runtime, "_serving_identity", lambda *_: installed) + + result = activation.restart_services_for_runtime_activation( + changes_applied=False, runtime_ready=True, installed_python_identity=installed) + + assert result["restart_status"] == "already_active" + assert result["restarted_services"] == [] + assert calls == [] + + +@pytest.mark.parametrize("running_fingerprint, restart", [("1", True), ("2", False), ("legacy", True), (None, False)]) +def test_same_launcher_retries_only_proven_stale_package_service( + managed, monkeypatch, running_fingerprint, restart, +): + _, agents, target, _, calls, _ = managed + align_managed_runtime(str(target)) + calls.clear() + before = {path: path.read_bytes() for path in agents.glob("*.plist")} + installed = {"schema_version": "loopx_runtime_identity_v1", "package_version": "2.4.0", + "release_id": None, "source_revision": None, "package_fingerprint": "sha256:" + "2" * 64} + package_doctor = {"ok": True, "scope": "installation_only", + "service_runtime_identity": installed, "python": {"executable": sys.executable}} + target.write_text(f"#!{sys.executable}\nprint({json.dumps(json.dumps(package_doctor))})\n") + + def serving(_opener, path, _port): + if path.stem != "com.loopx.status" or ("bootstrap", path.stem) in calls: + return installed + if running_fingerprint is None: + return None + if running_fingerprint == "legacy": + return {key: value for key, value in installed.items() if key != "package_fingerprint"} + return {**installed, "package_fingerprint": "sha256:" + running_fingerprint * 64} + + def verify(endpoints, expected): + if not all(serving(None, path, port) == expected for path, port in endpoints.items()): + raise RuntimeError("service_runtime_alignment_failed") + + monkeypatch.setattr(activation.sys, "platform", "darwin") + monkeypatch.setattr(sys, "argv", ["-c"]) + monkeypatch.setattr(managed_runtime, "_serving_identity", serving) + monkeypatch.setattr(managed_runtime, "_verify_services", verify) + result = activation.restart_services_for_runtime_activation( + changes_applied=False, runtime_ready=True, installed_python_identity=installed, + installed_bin=target) + + assert {path: path.read_bytes() for path in before} == before + assert result["activation_pending"] is (running_fingerprint is None) + if restart: + assert result["restart_status"] == "restarted" + assert result["restarted_services"] == ["com.loopx.status"] + assert calls == [("bootout", "com.loopx.status"), ("bootstrap", "com.loopx.status")] + else: + assert result["restart_status"] == ("failed" if running_fingerprint is None else "already_active") + assert not calls + + @pytest.mark.parametrize("shell", ["exec /old/loopx $(touch /tmp/no)", "exec /old/loopx chat | cat", "exec /old/loopx chat > out", "echo exec /old/loopx chat", 'exec /old/loopx "$RUNTIME"', "exec /old/loopx `whoami`", "exec /old/loopx; echo done"]) diff --git a/tests/test_self_update_runtime_activation.py b/tests/test_self_update_runtime_activation.py index e8cda548f5..57027067b7 100644 --- a/tests/test_self_update_runtime_activation.py +++ b/tests/test_self_update_runtime_activation.py @@ -31,6 +31,21 @@ TARGET_COMMIT = "2" * 40 +@pytest.fixture +def python_package_readback(monkeypatch): + def identity(fingerprint): + return {"schema_version": "loopx_runtime_identity_v1", + "package_version": __version__, "package_fingerprint": "sha256:" + fingerprint * 64} + + monkeypatch.setattr("loopx.self_update.release_runtime_identity", lambda *_: identity("1")) + + def doctor(fingerprint="2"): + body = {"ok": True, "scope": "installation_only", "service_runtime_identity": identity(fingerprint)} + return subprocess.CompletedProcess([], 0, json.dumps(body), "") + + return doctor + + class FakeVersionResponse: def __init__(self, body: bytes | None = None) -> None: self.body = body if body is not None else f'__version__ = "{__version__}"\n'.encode() @@ -415,7 +430,7 @@ def test_update_actions_are_explicit_and_legacy_flags_remain_compatible() -> Non resolve_update_action("check", execute=True) -def test_python_distribution_apply_uses_the_owning_interpreter_pip() -> None: +def test_python_distribution_apply_uses_the_owning_interpreter_pip(python_package_readback) -> None: doctor = doctor_payload() doctor["package"] = { "install_kind": "python_distribution", @@ -464,7 +479,10 @@ def test_python_distribution_apply_uses_the_owning_interpreter_pip() -> None: with ( mock.patch( "loopx.self_update.subprocess.run", - side_effect=[passed, passed, passed, passed, passed, passed], + side_effect=[ + passed, python_package_readback(), *([passed] * 3), + python_package_readback(), passed, python_package_readback(), + ], ) as run, mock.patch( "loopx.runtime_activation.restart_managed_loopx_services", @@ -476,18 +494,23 @@ def test_python_distribution_apply_uses_the_owning_interpreter_pip() -> None: assert result["ok"] is True assert result["changes_applied"] is True assert result["execution"]["driver"] == "python_pip" + assert result["execution"]["previous_runtime_identity"]["package_version"] == __version__ + assert result["execution"]["installed_runtime_identity"]["package_version"] == __version__ assert result["execution"]["restarted_services"] == ["com.loopx.status"] assert run.call_args_list[0].args[0] == [ sys.executable, + "-E", + "-P", "-m", "pip", "install", "--upgrade", "loopx", ] - assert run.call_args_list[1].args[0][-4:] == ["authority-archive", "upgrade", "--all-known", "--execute"] - assert run.call_args_list[2].args[0][3:5] == ["workflow-skills", "--install"] - assert run.call_args_list[3].args[0][3:5] == ["slash-commands", "--install"] + assert run.call_args_list[1].args[0][-2:] == ["doctor", "--installation-only"] + assert run.call_args_list[2].args[0][-4:] == ["authority-archive", "upgrade", "--all-known", "--execute"] + assert run.call_args_list[3].args[0][5:7] == ["workflow-skills", "--install"] + assert run.call_args_list[4].args[0][5:7] == ["slash-commands", "--install"] @pytest.mark.parametrize("installer", ["pip", "pipx"]) @@ -599,7 +622,7 @@ def test_real_windows_console_refuses_before_starting_installer(tmp_path: Path) assert "loopx.entrypoint" in refusal["next_action"]["command"] -def test_pipx_distribution_apply_preserves_the_pipx_environment() -> None: +def test_pipx_distribution_apply_preserves_the_pipx_environment(python_package_readback) -> None: doctor = doctor_payload() doctor["package"] = {"install_kind": "python_distribution"} doctor["install_freshness"].update( @@ -622,7 +645,10 @@ def test_pipx_distribution_apply_preserves_the_pipx_environment() -> None: with ( mock.patch( "loopx.self_update.subprocess.run", - side_effect=[passed, passed, passed, passed, passed, passed], + side_effect=[ + passed, python_package_readback(), *([passed] * 3), + python_package_readback(), passed, python_package_readback(), + ], ) as run, mock.patch( "loopx.runtime_activation.restart_managed_loopx_services", @@ -911,13 +937,14 @@ def test_windows_execute_update_fails_closed_without_launching_bash( assert "install-windows.ps1" in updated["recommended_action"] -def test_failed_authority_upgrade_does_not_activate_services_or_continue_host_updates(): +def test_failed_authority_upgrade_does_not_activate_services_or_continue_host_updates(python_package_readback): doctor = doctor_payload() doctor["package"] = {"install_kind": "python_distribution", "release_root": None} doctor["install_freshness"].update(install_kind="python_distribution", python_distribution_installer="pip") payload = build_update_plan(action="apply", doctor_payload=doctor) with mock.patch("loopx.self_update.subprocess.run", side_effect=[ subprocess.CompletedProcess([], 0, "installed", ""), + python_package_readback(), subprocess.CompletedProcess([], 1, '{"status":"failed","reason":"backup failed"}', ""), ]) as run, mock.patch("loopx.runtime_activation.restart_managed_loopx_services") as restart: result = execute_update_plan(payload) @@ -925,7 +952,7 @@ def test_failed_authority_upgrade_does_not_activate_services_or_continue_host_up assert result["changes_applied"] # Package installed; data migration failure is not a rollback. assert result["execution"]["authority_upgrade_returncode"] == 1 assert result["execution"]["doctor_status"] == "skipped_prior_step_failed" - assert run.call_count == 2 + assert run.call_count == 3 restart.assert_not_called() @@ -954,7 +981,9 @@ def apply_plan_for_driver(driver): "python_pip", "python_pipx", ]) -def test_update_preserves_selected_route_through_install_and_readback(tmp_path, monkeypatch, driver): +def test_update_preserves_selected_route_through_install_and_readback( + tmp_path, monkeypatch, driver, python_package_readback, +): registry, runtime = tmp_path / "project/.loopx/registry.json", tmp_path / "selected runtime" payload = apply_plan_for_driver(driver) calls, installer_env = [], {} @@ -965,6 +994,8 @@ def install(_url, *, env, **kwargs): return passed, {"stage": "installer_execution"} def run(command, **kwargs): calls.append(command) + if "doctor" in command: + return python_package_readback() return passed monkeypatch.setattr("loopx.self_update.run_archive_installer", install) monkeypatch.setattr("loopx.self_update.subprocess.run", run) @@ -1469,15 +1500,140 @@ def test_archive_readback_and_activation_follow_installer_bin_owner( @pytest.mark.parametrize("driver", ["python_pip", "python_pipx"]) -def test_python_distribution_activation_ignores_archive_bin_override(tmp_path, monkeypatch, driver): +def test_python_distribution_activation_ignores_archive_bin_override( + tmp_path, monkeypatch, driver, python_package_readback, +): monkeypatch.setenv("LOOPX_BIN_DIR", str(tmp_path / "custom/bin")) payload = apply_plan_for_driver(driver) passed = subprocess.CompletedProcess([], 0, '{"ok":true}', '') with ( - mock.patch("loopx.self_update.subprocess.run", return_value=passed), + mock.patch("loopx.self_update.subprocess.run", + side_effect=[ + passed, python_package_readback(), *([passed] * 3), + python_package_readback(), passed, python_package_readback(), + ]), mock.patch("loopx.runtime_activation.restart_managed_loopx_services", return_value=[]) as restart, ): result = execute_update_plan(payload) assert result["ok"] restart.assert_called_once_with() - assert result["execution"]["restart_status"] == "restarted" + assert result["execution"]["restart_status"] == "not_running" + + +@pytest.mark.parametrize("driver", ["python_pip", "python_pipx"]) +def test_unchanged_python_package_still_refreshes_host_material(driver, python_package_readback): + payload = apply_plan_for_driver(driver) + passed = subprocess.CompletedProcess([], 0, '{"ok":true}', '') + with ( + mock.patch("loopx.self_update.subprocess.run", + side_effect=[ + passed, python_package_readback("1"), *([passed] * 3), + python_package_readback("1"), passed, python_package_readback("1"), + ], + ) as run, + mock.patch("loopx.runtime_activation.restart_managed_loopx_services", return_value=[]), + ): + result = execute_update_plan(payload) + assert run.call_count == 8 + assert result["ok"] and result["changes_applied"] is False + assert result["execution"]["package_identity_verified"] is True + assert result["execution"]["restart_status"] == "not_running" + assert result["execution"]["extension_doctor_returncode"] == 0 + assert "unchanged" in result["recommended_action"] + + +@pytest.mark.parametrize("readback", [ + subprocess.CompletedProcess([], 1, '', 'not installed'), + subprocess.CompletedProcess([], 0, '{"ok":true,"scope":"installation_only"}', ''), +]) +def test_python_update_preserves_unverified_result_without_activating(readback, python_package_readback): + payload = apply_plan_for_driver("python_pipx") + passed = subprocess.CompletedProcess([], 0, 'already at latest version', '') + with ( + mock.patch("loopx.self_update.subprocess.run", side_effect=[passed, readback]) as run, + mock.patch("loopx.runtime_activation.restart_managed_loopx_services") as restart, + ): + result = execute_update_plan(payload) + assert result["ok"] is False and result["changes_applied"] is False + assert result["execution"]["install_returncode"] == 0 + assert result["execution"]["package_identity_verified"] is False + assert result["next_action"]["command"] == "loopx doctor --installation-only" + assert run.call_count == 2 + restart.assert_not_called() + + +@pytest.mark.parametrize("driver", ["python_pip", "python_pipx"]) +@pytest.mark.parametrize("final_fingerprint", ["1", "2"]) +def test_python_update_rechecks_final_package_before_service_activation( + driver, final_fingerprint, python_package_readback, +): + passed = subprocess.CompletedProcess([], 0, '{"ok":true}', '') + with ( + mock.patch("loopx.self_update.subprocess.run", side_effect=[ + passed, python_package_readback("1"), passed, passed, passed, + python_package_readback(final_fingerprint), passed, python_package_readback("1"), + ]), + mock.patch("loopx.runtime_activation.restart_managed_loopx_services", return_value=[]) as restart, + ): + result = execute_update_plan(apply_plan_for_driver(driver)) + assert result["ok"] is (final_fingerprint == "1") + assert result["execution"]["package_identity_verified"] is (final_fingerprint == "1") + assert result["changes_applied"] is False + if final_fingerprint == "2": + restart.assert_not_called() + assert result["execution"]["restart_status"] == "skipped_runtime_not_activated" + else: + restart.assert_called_once() + + +@pytest.mark.parametrize("driver", ["python_pip", "python_pipx"]) +@pytest.mark.parametrize("extension_returncode", [0, 1]) +def test_python_update_rejects_package_replaced_during_extension_check( + driver, extension_returncode, python_package_readback, monkeypatch, +): + passed = subprocess.CompletedProcess([], 0, '{"ok":true}', '') + extension = subprocess.CompletedProcess([], extension_returncode, '', '') + checked = python_package_readback("2") + replacement = python_package_readback("3") + monkeypatch.setattr("loopx.hosts.managed_service_runtime.has_runtime_binding", lambda: False) + with ( + mock.patch("loopx.self_update.subprocess.run", side_effect=[ + passed, checked, passed, passed, passed, checked, extension, replacement, + ]) as run, + mock.patch("loopx.runtime_activation.restart_managed_loopx_services") as restart, + ): + result = execute_update_plan(apply_plan_for_driver(driver)) + + assert result["ok"] is False + assert result["changes_applied"] is False + assert result["execution"]["install_returncode"] == 0 + assert result["execution"]["installed_runtime_identity"]["package_fingerprint"].endswith("2" * 64) + assert result["execution"]["package_identity_verified"] is False + assert result["execution"]["extension_doctor_returncode"] == extension_returncode + assert result["execution"]["restart_status"] == "skipped_runtime_not_activated" + assert result["next_action"]["command"] == "loopx doctor --installation-only" + assert run.call_args_list[-1].args[0][-2:] == ["doctor", "--installation-only"] + restart.assert_not_called() + + +@pytest.mark.parametrize("driver", ["python_pip", "python_pipx"]) +def test_python_update_passes_doctor_owned_launcher_from_background_worker( + tmp_path, monkeypatch, driver, python_package_readback, +): + launcher = tmp_path / "own venv/bin/loopx" + passed = subprocess.CompletedProcess([], 0, '{"ok":true}', '') + final = python_package_readback() + body = json.loads(final.stdout) + body["path"] = {"loopx": str(launcher)} + final = subprocess.CompletedProcess([], 0, json.dumps(body), '') + monkeypatch.setattr(sys, "argv", ["-c"]) + with ( + mock.patch("loopx.self_update.subprocess.run", side_effect=[ + passed, python_package_readback(), passed, passed, passed, + python_package_readback(), passed, final, + ]), + mock.patch("loopx.self_update.restart_services_for_runtime_activation", return_value={}) as activate, + ): + result = execute_update_plan(apply_plan_for_driver(driver)) + assert result["ok"] + assert activate.call_args.kwargs["installed_bin"] == launcher diff --git a/tests/test_self_upgrade.py b/tests/test_self_upgrade.py index 32964bd92b..9c2fb706b1 100644 --- a/tests/test_self_upgrade.py +++ b/tests/test_self_upgrade.py @@ -525,6 +525,24 @@ def run(): assert text.startswith("LoopX upgrade completed.") +def test_unchanged_verified_package_keeps_prompt_recovery_available(tmp_path, monkeypatch): + from loopx.control_plane.heartbeat import installed_prompt_update + + monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex")) + monkeypatch.setattr(installed_prompt_update, "snapshot", + lambda **_kwargs: {"ok": True, "status": "current", "entries": []}) + runtime = {"ok": False, "changes_applied": False, "execution": { + "package_identity_verified": True, "install_returncode": 0, "doctor_returncode": 0, + "extension_doctor_returncode": 1, + }} + result = installed_prompt_update.update_with_prompts( + {}, registry=tmp_path / "registry.json", runtime_root=None, timeout_seconds=1, + runtime_update=lambda *_args, **_kwargs: dict(runtime), + ) + assert result["automation_prompt_upgrade"] == {"ok": True, "status": "current"} + assert result["upgrade_complete"] is False + + def test_failed_cli_does_not_restart_the_app(monkeypatch): with mock.patch("loopx.cli_commands.support_control_upgrade._upgrade_desktop") as restart: result = finish_upgrade(