From 44ce91d5025ec783d2d2a230f4f2c7c1ae66f8a0 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:10:21 +0800 Subject: [PATCH 1/3] fix(doctor): bind package update readback to its Python environment Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/doctor.py | 104 +++++++++++++++--------- tests/test_doctor_installation_scope.py | 53 ++++++++++++ 2 files changed, 118 insertions(+), 39 deletions(-) diff --git a/loopx/doctor.py b/loopx/doctor.py index 9cfe865986..d118ff9c68 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -4,7 +4,7 @@ from datetime import datetime, timezone from functools import partial -from importlib.metadata import PackageNotFoundError, distribution +from importlib.metadata import Distribution, PackageNotFoundError, PackagePath, distribution import json import os import re @@ -123,10 +123,10 @@ def command_release_root(command_realpath: Path | None) -> Path | None: return None -def current_script_invocation_path() -> Path | None: - """Return the active console script or installed standalone-core module.""" +def _current_invocation() -> tuple[Path | None, bool]: + """Return the invocation path and whether a verified module owns the route.""" if not sys.argv or not sys.argv[0]: - return None + return None, False path = Path(sys.argv[0]).expanduser() if not path.is_absolute(): path = Path.cwd() / path @@ -135,38 +135,67 @@ def current_script_invocation_path() -> Path | None: except OSError: path = path.absolute() if path.exists() and path.name.lower() in {"loopx", "loopx.exe"}: - return path - if path == Path(__file__).with_name("entrypoint.py").resolve(): - # Module invocation is the core's isolated continuation route. Verify - # the imported distribution before replacing ambient PATH discovery. - installed = python_distribution_install(Path(__file__).resolve()) - if installed.get("distribution_name") == "loopx-core": - return path - return None + return path, False + module_path = Path(__file__).resolve() + entrypoint = module_path.with_name("entrypoint.py") + if path not in {entrypoint, module_path.with_name("cli.py")}: + return None, False + installed = _python_distribution_owning_module(module_path) + if installed is None: + return None, False + if installed.name == "loopx-core": + return (path, True) if path == entrypoint else (None, False) + # Source metadata can list the module without recording an installed script. + if installed.read_text("RECORD") is None: + return None, False + + # The package updater invokes Doctor with its interpreter. Resolve that + # distribution's console script even if the shell names a different CLI. + script_name = "loopx.exe" if os.name == "nt" else "loopx" + scripts = { + _distribution_record_path(item) + for item in installed.files or () + if Path(item.as_posix()).name.lower() == script_name + } + if len(scripts) == 1: + script = scripts.pop() + if script.is_file() and os.access(script, os.X_OK): + return script, True + return None, True -def python_distribution_install(module_path: Path) -> dict[str, Any]: - """Identify a wheel/sdist install that owns the imported LoopX module.""" +def current_script_invocation_path() -> Path | None: + """Return an active console script or installed standalone-core module.""" + return _current_invocation()[0] + + +def _distribution_record_path(item: PackagePath) -> Path: + # PackagePath uses POSIX components and can lose a Windows drive root on + # Python 3.11. Interpret absolute RECORD entries under native path rules. + path = Path(item.as_posix()) + return (path if path.is_absolute() else Path(item.locate())).resolve() + +def _python_distribution_owning_module(module_path: Path) -> Distribution | None: try: installed = installed_loopx_distribution(distribution) except PackageNotFoundError: - return {"available": False} - installer = (installed.read_text("INSTALLER") or "").strip() or "unknown" + return None expected = module_path.resolve() module_suffix = os.path.join("loopx", "doctor.py") for item in installed.files or (): entry = item.as_posix() - if not os.path.normcase(entry).endswith(module_suffix): - continue - # A PackagePath uses POSIX components, so locating a drive-qualified - # RECORD entry can lose its Windows root on Python 3.11. - record_path = Path(entry) - located = record_path if record_path.is_absolute() else Path(item.locate()) - if located.resolve() == expected: - break - else: + if os.path.normcase(entry).endswith(module_suffix) and _distribution_record_path(item) == expected: + return installed + return None + + +def python_distribution_install(module_path: Path) -> dict[str, Any]: + """Identify a wheel/sdist install that owns the imported LoopX module.""" + installed = _python_distribution_owning_module(module_path) + if installed is None: return {"available": False} + installer = (installed.read_text("INSTALLER") or "").strip() or "unknown" owner = resolve_python_install_owner(default_installer=installer, prefix=Path(sys.prefix)) return { "available": True, @@ -735,15 +764,18 @@ def collect_doctor( else None ) loopx_path = resolve_command_path("loopx") - invocation_path = current_script_invocation_path() + invocation_path, module_owns_route = _current_invocation() loopx_canary_path = resolve_command_path("loopx-canary") - command_path_primary = ( - invocation_path - if invocation_path == Path(__file__).with_name("entrypoint.py").resolve() - else loopx_path or invocation_path - ) + command_path = invocation_path if module_owns_route else loopx_path or invocation_path + if module_owns_route: + command_detail = str(invocation_path) if invocation_path else "installed Python console script unavailable" + elif loopx_path: + command_detail = str(loopx_path) + elif invocation_path: + command_detail = f"loopx was not found on PATH; using current invocation {invocation_path}" + else: + command_detail = "loopx was not found on PATH" canary_path = loopx_canary_path - command_path = command_path_primary command_realpath = command_path.resolve() if command_path else None canary_realpath = canary_path.resolve() if canary_path else None loopx_canary_realpath = loopx_canary_path.resolve() if loopx_canary_path else None @@ -1018,13 +1050,7 @@ def collect_doctor( "id": "command_available", "required": True, "ok": command_path is not None, - "detail": str(loopx_path) - if loopx_path - else ( - f"loopx was not found on PATH; using current invocation {invocation_path}" - if invocation_path - else "loopx was not found on PATH" - ), + "detail": command_detail, }, { "id": "command_on_path", diff --git a/tests/test_doctor_installation_scope.py b/tests/test_doctor_installation_scope.py index d8aacd3193..fbf6299b13 100644 --- a/tests/test_doctor_installation_scope.py +++ b/tests/test_doctor_installation_scope.py @@ -1,6 +1,9 @@ from __future__ import annotations +import csv +from importlib.metadata import PathDistribution import json +import os from pathlib import Path import threading import time @@ -184,6 +187,56 @@ def deep_checks(**kwargs) -> dict: assert observed["deep_checks"]["distribution_root"] == str(distribution_root) +@pytest.mark.parametrize("module", ["cli.py", "entrypoint.py"]) +@pytest.mark.parametrize("launcher_record", ["owned", "missing", "other_distribution", "source_manifest"]) +def test_full_doctor_keeps_packaged_module_readback_on_its_python_environment( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, module: str, launcher_record: str, +) -> None: + module_path = Path(doctor.__file__).resolve() + owned_console = tmp_path / ("loopx.exe" if os.name == "nt" else "loopx") + owned_console.touch(mode=0o700) + foreign_console = tmp_path / "other" / owned_console.name + foreign_console.parent.mkdir() + foreign_console.touch(mode=0o700) + dist_info = tmp_path / "loopx.dist-info" + dist_info.mkdir() + (dist_info / "METADATA").write_text("Name: loopx\nVersion: 2.4.0\n", encoding="utf-8") + recorded_module = ( + tmp_path / "other/loopx/doctor.py" if launcher_record == "other_distribution" else module_path + ) + if launcher_record == "source_manifest": + (dist_info / "SOURCES.txt").write_text(f"{module_path.as_posix()}\n", encoding="utf-8") + else: + with (dist_info / "RECORD").open("w", encoding="utf-8", newline="") as record: + writer = csv.writer(record) + writer.writerow([recorded_module.as_posix(), "", ""]) + if launcher_record != "missing": + writer.writerow([owned_console.as_posix(), "", ""]) + monkeypatch.setattr(doctor, "distribution", lambda _name: PathDistribution(dist_info)) + monkeypatch.setattr(doctor.sys, "argv", [str(module_path.with_name(module)), "doctor"]) + monkeypatch.setattr( + doctor, "resolve_command_path", lambda name: foreign_console if name == "loopx" else None, + ) + monkeypatch.setattr( + "loopx.control_plane.effect_runtime.collect_effect_runtime_readiness", + lambda *, deep: {"ready": True, "status": "ready"}, + ) + + runtime = tmp_path / "runtime" + result = doctor.collect_doctor(runtime_root_override=str(runtime)) + assert result["path"]["loopx_on_path"] == str(foreign_console) + expected = { + "owned": str(owned_console), + "missing": None, + "other_distribution": str(foreign_console), + "source_manifest": str(foreign_console), + } + assert result["path"]["loopx"] == expected[launcher_record] + checks = {check["id"]: check for check in result["checks"]} + assert checks["command_available"]["ok"] is (launcher_record != "missing") + assert checks["command_resolves"]["ok"] is (launcher_record != "missing") + + def test_runtime_projection_diagnostics_bound_one_stalled_source_and_retry( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, From cb56cdb50e6c8ce8431f0c9785fec4ebcab81e05 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:07:41 +0800 Subject: [PATCH 2/3] Keep Doctor discovery separate from service activation Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/doctor.py | 17 ++++--- loopx/release_candidate.py | 6 +-- tests/test_doctor_installation_scope.py | 67 +++++++++++++++++++++---- 3 files changed, 71 insertions(+), 19 deletions(-) diff --git a/loopx/doctor.py b/loopx/doctor.py index d118ff9c68..e2968e8410 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -123,7 +123,7 @@ def command_release_root(command_realpath: Path | None) -> Path | None: return None -def _current_invocation() -> tuple[Path | None, bool]: +def _current_invocation(*, inspect_distribution_launcher: bool) -> tuple[Path | None, bool]: """Return the invocation path and whether a verified module owns the route.""" if not sys.argv or not sys.argv[0]: return None, False @@ -138,7 +138,7 @@ def _current_invocation() -> tuple[Path | None, bool]: return path, False module_path = Path(__file__).resolve() entrypoint = module_path.with_name("entrypoint.py") - if path not in {entrypoint, module_path.with_name("cli.py")}: + if path != entrypoint and (not inspect_distribution_launcher or path != module_path.with_name("cli.py")): return None, False installed = _python_distribution_owning_module(module_path) if installed is None: @@ -146,7 +146,7 @@ def _current_invocation() -> tuple[Path | None, bool]: if installed.name == "loopx-core": return (path, True) if path == entrypoint else (None, False) # Source metadata can list the module without recording an installed script. - if installed.read_text("RECORD") is None: + if not inspect_distribution_launcher or installed.read_text("RECORD") is None: return None, False # The package updater invokes Doctor with its interpreter. Resolve that @@ -165,8 +165,13 @@ def _current_invocation() -> tuple[Path | None, bool]: def current_script_invocation_path() -> Path | None: - """Return an active console script or installed standalone-core module.""" - return _current_invocation()[0] + """Return the launcher eligible under the existing service activation policy.""" + return _current_invocation(inspect_distribution_launcher=False)[0] + + +def doctor_invocation_path() -> tuple[Path | None, bool]: + """Resolve Doctor's invocation while retaining ownership if its launcher is unavailable.""" + return _current_invocation(inspect_distribution_launcher=True) def _distribution_record_path(item: PackagePath) -> Path: @@ -764,7 +769,7 @@ def collect_doctor( else None ) loopx_path = resolve_command_path("loopx") - invocation_path, module_owns_route = _current_invocation() + invocation_path, module_owns_route = doctor_invocation_path() loopx_canary_path = resolve_command_path("loopx-canary") command_path = invocation_path if module_owns_route else loopx_path or invocation_path if module_owns_route: diff --git a/loopx/release_candidate.py b/loopx/release_candidate.py index 34200592fe..31c5259f8c 100644 --- a/loopx/release_candidate.py +++ b/loopx/release_candidate.py @@ -311,10 +311,10 @@ def collect_installation_doctor(*, deep: bool) -> dict[str, Any]: """ from .control_plane.effect_runtime import collect_effect_runtime_readiness from .command_invocation import resolve_command_path - from .doctor import current_script_invocation_path, python_distribution_install + from .doctor import doctor_invocation_path, python_distribution_install - invocation = current_script_invocation_path() - command = invocation or resolve_command_path("loopx") + invocation, module_owns_route = doctor_invocation_path() + command = invocation if module_owns_route else invocation or resolve_command_path("loopx") package_root = Path(__file__).resolve().parents[1] selected = os.environ.get("LOOPX_RELEASE_ROOT") runtime = collect_effect_runtime_readiness(deep=deep) diff --git a/tests/test_doctor_installation_scope.py b/tests/test_doctor_installation_scope.py index fbf6299b13..b5cd7fb8a8 100644 --- a/tests/test_doctor_installation_scope.py +++ b/tests/test_doctor_installation_scope.py @@ -159,7 +159,7 @@ def test_installation_scope_uses_current_distribution_and_console_script( other_command = tmp_path / "old" / "bin" / "loopx" distribution_root = tmp_path / "current" / "site-packages" observed: dict = {} - monkeypatch.setattr(doctor, "current_script_invocation_path", lambda: invocation) + monkeypatch.setattr(doctor, "doctor_invocation_path", lambda: (invocation, True)) monkeypatch.setattr( "loopx.command_invocation.resolve_command_path", lambda _name: other_command ) @@ -188,13 +188,16 @@ def deep_checks(**kwargs) -> dict: @pytest.mark.parametrize("module", ["cli.py", "entrypoint.py"]) -@pytest.mark.parametrize("launcher_record", ["owned", "missing", "other_distribution", "source_manifest"]) -def test_full_doctor_keeps_packaged_module_readback_on_its_python_environment( +@pytest.mark.parametrize( + "launcher_record", ["owned", "missing", "missing_file", "ambiguous", "other_distribution", "source_manifest"], +) +def test_both_doctors_keep_packaged_module_readback_on_its_python_environment( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, module: str, launcher_record: str, ) -> None: module_path = Path(doctor.__file__).resolve() owned_console = tmp_path / ("loopx.exe" if os.name == "nt" else "loopx") - owned_console.touch(mode=0o700) + if launcher_record != "missing_file": + owned_console.touch(mode=0o700) foreign_console = tmp_path / "other" / owned_console.name foreign_console.parent.mkdir() foreign_console.touch(mode=0o700) @@ -212,11 +215,15 @@ def test_full_doctor_keeps_packaged_module_readback_on_its_python_environment( writer.writerow([recorded_module.as_posix(), "", ""]) if launcher_record != "missing": writer.writerow([owned_console.as_posix(), "", ""]) + if launcher_record == "ambiguous": + writer.writerow([foreign_console.as_posix(), "", ""]) monkeypatch.setattr(doctor, "distribution", lambda _name: PathDistribution(dist_info)) monkeypatch.setattr(doctor.sys, "argv", [str(module_path.with_name(module)), "doctor"]) - monkeypatch.setattr( - doctor, "resolve_command_path", lambda name: foreign_console if name == "loopx" else None, - ) + def find_command(name): + return foreign_console if name == "loopx" else None + + monkeypatch.setattr(doctor, "resolve_command_path", find_command) + monkeypatch.setattr("loopx.command_invocation.resolve_command_path", find_command) monkeypatch.setattr( "loopx.control_plane.effect_runtime.collect_effect_runtime_readiness", lambda *, deep: {"ready": True, "status": "ready"}, @@ -224,17 +231,57 @@ def test_full_doctor_keeps_packaged_module_readback_on_its_python_environment( runtime = tmp_path / "runtime" result = doctor.collect_doctor(runtime_root_override=str(runtime)) + installation = doctor.collect_doctor(installation_only=True) assert result["path"]["loopx_on_path"] == str(foreign_console) expected = { "owned": str(owned_console), "missing": None, + "missing_file": None, + "ambiguous": None, "other_distribution": str(foreign_console), "source_manifest": str(foreign_console), } - assert result["path"]["loopx"] == expected[launcher_record] + assert result["path"]["loopx"] == installation["path"]["loopx"] == expected[launcher_record] checks = {check["id"]: check for check in result["checks"]} - assert checks["command_available"]["ok"] is (launcher_record != "missing") - assert checks["command_resolves"]["ok"] is (launcher_record != "missing") + available = expected[launcher_record] is not None + assert checks["command_available"]["ok"] is available + assert checks["command_resolves"]["ok"] is available + assert installation["ok"] is available + + +def test_owned_python_module_does_not_retarget_bound_macos_services(monkeypatch, tmp_path): + from contextlib import nullcontext + from types import SimpleNamespace + + from loopx import runtime_activation + + script = tmp_path / "loopx" + script.touch(mode=0o700) + distribution = SimpleNamespace( + name="loopx", + read_text=lambda name: "" if name == "RECORD" else None, + files=[script], + ) + monkeypatch.setattr(doctor, "_python_distribution_owning_module", lambda _path: distribution) + monkeypatch.setattr(doctor.sys, "argv", [str(Path(doctor.__file__).with_name("cli.py")), "update"]) + monkeypatch.setattr(runtime_activation.sys, "platform", "darwin") + monkeypatch.setattr(runtime_activation, "_managed_service_plists", lambda: []) + monkeypatch.setattr(runtime_activation, "managed_chat_activation_guard", lambda _plists: nullcontext()) + monkeypatch.setattr("loopx.hosts.managed_service_runtime.has_runtime_binding", lambda: True) + aligned = [] + monkeypatch.setattr( + "loopx.hosts.managed_service_runtime.align_managed_runtime", + lambda path: aligned.append(path) or {"restarted_services": []}, + ) + + result = runtime_activation.restart_services_for_runtime_activation( + changes_applied=True, runtime_ready=True, + ) + + assert result["restart_status"] == "deferred" + assert result["restart_reason"] == "service_runtime_unverified" + assert result["activation_pending"] is True + assert not aligned def test_runtime_projection_diagnostics_bound_one_stalled_source_and_retry( From 788c5983d041b847996d0001f615e57e77df08c6 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:04:48 +0800 Subject: [PATCH 3/3] Verify the recorded Python launcher before Doctor probes it Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/doctor.py | 19 ++++------- loopx/python_install_owner.py | 21 +++++++++++- loopx/release_candidate.py | 36 ++++++++++---------- tests/test_doctor_installation_scope.py | 13 ++++++-- tests/test_release_candidate.py | 44 ++++++++++++++++++++----- 5 files changed, 93 insertions(+), 40 deletions(-) diff --git a/loopx/doctor.py b/loopx/doctor.py index e2968e8410..eba039e94b 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -4,7 +4,7 @@ from datetime import datetime, timezone from functools import partial -from importlib.metadata import Distribution, PackageNotFoundError, PackagePath, distribution +from importlib.metadata import Distribution, PackageNotFoundError, distribution import json import os import re @@ -28,9 +28,11 @@ from .paths import configured_runtime_route, default_runtime_route, global_registry_path from .python_install_owner import ( PythonInstallOwner, + distribution_record_path, installed_loopx_distribution, python_distribution_upgrade_command, resolve_python_install_owner, + verified_distribution_console, ) from .capabilities.project_skill_delivery import discover_project_scoped_skill_ids from .registry_writability import probe_registry_write_path @@ -153,13 +155,13 @@ def _current_invocation(*, inspect_distribution_launcher: bool) -> tuple[Path | # distribution's console script even if the shell names a different CLI. script_name = "loopx.exe" if os.name == "nt" else "loopx" scripts = { - _distribution_record_path(item) + distribution_record_path(item) for item in installed.files or () if Path(item.as_posix()).name.lower() == script_name } if len(scripts) == 1: - script = scripts.pop() - if script.is_file() and os.access(script, os.X_OK): + script = verified_distribution_console(scripts.pop()) + if script is not None and os.access(script, os.X_OK): return script, True return None, True @@ -174,13 +176,6 @@ def doctor_invocation_path() -> tuple[Path | None, bool]: return _current_invocation(inspect_distribution_launcher=True) -def _distribution_record_path(item: PackagePath) -> Path: - # PackagePath uses POSIX components and can lose a Windows drive root on - # Python 3.11. Interpret absolute RECORD entries under native path rules. - path = Path(item.as_posix()) - return (path if path.is_absolute() else Path(item.locate())).resolve() - - def _python_distribution_owning_module(module_path: Path) -> Distribution | None: try: installed = installed_loopx_distribution(distribution) @@ -190,7 +185,7 @@ def _python_distribution_owning_module(module_path: Path) -> Distribution | None module_suffix = os.path.join("loopx", "doctor.py") for item in installed.files or (): entry = item.as_posix() - if os.path.normcase(entry).endswith(module_suffix) and _distribution_record_path(item) == expected: + if os.path.normcase(entry).endswith(module_suffix) and distribution_record_path(item).resolve() == expected: return installed return None diff --git a/loopx/python_install_owner.py b/loopx/python_install_owner.py index 8270d105ce..9daa40beec 100644 --- a/loopx/python_install_owner.py +++ b/loopx/python_install_owner.py @@ -9,7 +9,7 @@ from dataclasses import dataclass from collections.abc import Callable -from importlib.metadata import Distribution, PackageNotFoundError +from importlib.metadata import Distribution, PackageNotFoundError, PackagePath import json import os from pathlib import Path @@ -29,6 +29,25 @@ def installed_loopx_distribution(lookup: Callable[[str], Distribution]) -> Distr return lookup("loopx-core") +def distribution_record_path(item: PackagePath) -> Path: + # PackagePath uses POSIX components and can lose a Windows drive root on + # Python 3.11. Interpret absolute RECORD entries under native path rules. + path = Path(str(item)) + return path if path.is_absolute() else Path(item.locate()) + + +def verified_distribution_console(recorded: Path) -> Path | None: + """Keep the recorded launcher identity when resolving its directory.""" + try: + expected = recorded.parent.resolve(strict=True) / recorded.name + resolved = recorded.resolve(strict=True) + if resolved == expected and resolved.is_file(): + return resolved + except (OSError, RuntimeError): + pass + return None + + @dataclass(frozen=True) class PythonInstallOwner: manager: str diff --git a/loopx/release_candidate.py b/loopx/release_candidate.py index 31c5259f8c..a0565dd4b1 100644 --- a/loopx/release_candidate.py +++ b/loopx/release_candidate.py @@ -10,7 +10,11 @@ from typing import Any, Sequence from .command_invocation import command_argv -from .python_install_owner import installed_loopx_distribution +from .python_install_owner import ( + distribution_record_path, + installed_loopx_distribution, + verified_distribution_console, +) from .release_manifest import release_runtime_identity @@ -131,14 +135,15 @@ def _distribution_command_summary(command_path: Path | None) -> dict[str, Any]: "error": "distribution_missing", } - recorded_commands: list[Path] = [] + recorded_commands: set[Path] = set() + verified_commands: set[Path] = set() recorded_module = False resolved_command = command_path.resolve() standalone_core = getattr(installed, "name", None) == "loopx-core" for item in installed.files or (): if standalone_core and str(item) == "loopx/entrypoint.py": recorded_module = ( - Path(item.locate()).resolve() == resolved_command + distribution_record_path(item).resolve() == resolved_command == Path(__file__).with_name("entrypoint.py").resolve() ) if Path(str(item)).name.lower() not in { @@ -147,20 +152,16 @@ def _distribution_command_summary(command_path: Path | None) -> dict[str, Any]: "loopx-script.py", }: continue - try: - resolved_path = Path(item.locate()).resolve() - except OSError: - continue - if resolved_path not in recorded_commands: - recorded_commands.append(resolved_path) - recorded_commands.sort(key=str) + recorded = distribution_record_path(item) + verified = verified_distribution_console(recorded) + recorded_commands.add(verified if verified is not None else recorded) + if verified is not None: + verified_commands.add(verified) return { - "ok": resolved_command in recorded_commands or ( - recorded_module and any(path.is_file() for path in recorded_commands) - ), + "ok": resolved_command in verified_commands or (recorded_module and bool(verified_commands)), **({"distribution_name": "loopx-core"} if getattr(installed, "name", None) == "loopx-core" else {}), "command": str(resolved_command), - "recorded_commands": [str(path) for path in recorded_commands], + "recorded_commands": sorted(str(path) for path in recorded_commands), "error": None if recorded_commands else "console_script_not_recorded", } @@ -236,14 +237,15 @@ def collect_python_distribution_checks( """Validate a wheel/sdist install without requiring source-only wrappers.""" distribution_command = _distribution_command_summary(command_path) + verified_command = Path(distribution_command["command"]) if distribution_command["ok"] else None standalone_core = distribution_command.get("distribution_name") == "loopx-core" imports = _import_summary(CORE_CLI_IMPORTS) if standalone_core else _import_summary() - if standalone_core and command_path == Path(__file__).with_name("entrypoint.py").resolve(): + if standalone_core and verified_command == Path(__file__).with_name("entrypoint.py").resolve(): commands = _command_summary( - command_path, invocation_argv=[sys.executable, "-I", "-m", "loopx.entrypoint"], + verified_command, invocation_argv=[sys.executable, "-I", "-m", "loopx.entrypoint"], ) else: - commands = _command_summary(command_path) + commands = _command_summary(verified_command) package_paths = _package_path_summary( package_root, CORE_DISTRIBUTION_PATHS if standalone_core else REPRESENTATIVE_DISTRIBUTION_PATHS, diff --git a/tests/test_doctor_installation_scope.py b/tests/test_doctor_installation_scope.py index b5cd7fb8a8..8164f2aaa7 100644 --- a/tests/test_doctor_installation_scope.py +++ b/tests/test_doctor_installation_scope.py @@ -189,18 +189,26 @@ def deep_checks(**kwargs) -> dict: @pytest.mark.parametrize("module", ["cli.py", "entrypoint.py"]) @pytest.mark.parametrize( - "launcher_record", ["owned", "missing", "missing_file", "ambiguous", "other_distribution", "source_manifest"], + "launcher_record", + ["owned", "missing", "missing_file", "redirected", "ambiguous", "other_distribution", "source_manifest"], ) def test_both_doctors_keep_packaged_module_readback_on_its_python_environment( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, module: str, launcher_record: str, ) -> None: module_path = Path(doctor.__file__).resolve() owned_console = tmp_path / ("loopx.exe" if os.name == "nt" else "loopx") - if launcher_record != "missing_file": + if launcher_record not in {"missing_file", "redirected"}: owned_console.touch(mode=0o700) foreign_console = tmp_path / "other" / owned_console.name foreign_console.parent.mkdir() foreign_console.touch(mode=0o700) + if launcher_record == "redirected": + try: + owned_console.symlink_to(foreign_console) + except OSError: + if os.name != "nt": + raise + pytest.skip("console script symlinks unavailable") dist_info = tmp_path / "loopx.dist-info" dist_info.mkdir() (dist_info / "METADATA").write_text("Name: loopx\nVersion: 2.4.0\n", encoding="utf-8") @@ -237,6 +245,7 @@ def find_command(name): "owned": str(owned_console), "missing": None, "missing_file": None, + "redirected": None, "ambiguous": None, "other_distribution": str(foreign_console), "source_manifest": str(foreign_console), diff --git a/tests/test_release_candidate.py b/tests/test_release_candidate.py index 1293ff44d7..3b18023157 100644 --- a/tests/test_release_candidate.py +++ b/tests/test_release_candidate.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os from pathlib import Path import pytest @@ -37,9 +38,11 @@ def _materialize_distribution_paths(package_root: Path) -> None: path.touch() +@pytest.mark.parametrize("use_alias", [False, True]) def test_python_distribution_checks_accept_recorded_console_script_without_source_wrapper( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + use_alias: bool, ) -> None: package_root = tmp_path / "site-packages" command_path = tmp_path / "bin" / "loopx" @@ -59,8 +62,18 @@ def test_python_distribution_checks_accept_recorded_console_script_without_sourc lambda _path: {"ok": True, "results": {}, "failed": []}, ) + invocation = command_path + if use_alias: + invocation = tmp_path / "loopx" + try: + invocation.symlink_to(command_path) + except OSError: + if os.name != "nt": + raise + pytest.skip("console script symlinks unavailable") + payload = collect_python_distribution_checks( - command_path=command_path, + command_path=invocation, package_root=package_root, ) @@ -116,16 +129,27 @@ def test_deep_distribution_checks_prefer_current_invocation_over_path_command( assert probed_commands == [invocation_path] +@pytest.mark.parametrize("redirected_record", [False, True]) def test_python_distribution_checks_reject_command_from_another_install( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + redirected_record: bool, ) -> None: package_root = tmp_path / "site-packages" recorded_command = tmp_path / "installed" / "bin" / "loopx" active_command = tmp_path / "other" / "bin" / "loopx" - for command_path in (recorded_command, active_command): - command_path.parent.mkdir(parents=True) - command_path.touch() + active_command.parent.mkdir(parents=True) + active_command.touch() + recorded_command.parent.mkdir(parents=True) + if redirected_record: + try: + recorded_command.symlink_to(active_command) + except OSError: + if os.name != "nt": + raise + pytest.skip("console script symlinks unavailable") + else: + recorded_command.touch() _materialize_distribution_paths(package_root) monkeypatch.setattr( "loopx.release_candidate.distribution", @@ -135,10 +159,13 @@ def test_python_distribution_checks_reject_command_from_another_install( "loopx.release_candidate._import_summary", lambda: {"ok": True, "results": {}, "failed": []}, ) - monkeypatch.setattr( - "loopx.release_candidate._command_summary", - lambda _path: {"ok": True, "results": {}, "failed": []}, - ) + probed_commands: list[Path | None] = [] + + def probe(command_path: Path | None) -> dict: + probed_commands.append(command_path) + return {"ok": command_path is not None, "results": {}, "failed": []} + + monkeypatch.setattr("loopx.release_candidate._command_summary", probe) payload = collect_python_distribution_checks( command_path=active_command, @@ -148,6 +175,7 @@ def test_python_distribution_checks_reject_command_from_another_install( checks = {check["id"]: check for check in payload["checks"]} assert payload["ok"] is False assert checks["command_package_same_distribution"]["ok"] is False + assert probed_commands == [None] def test_command_probes_overlap_but_keep_each_failure(monkeypatch):