Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 65 additions & 39 deletions loopx/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, distribution
import json
import os
import re
Expand All @@ -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
Expand Down Expand Up @@ -123,10 +125,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(*, 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
return None, False
path = Path(sys.argv[0]).expanduser()
if not path.is_absolute():
path = Path.cwd() / path
Expand All @@ -135,38 +137,65 @@ 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 != 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:
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 not inspect_distribution_launcher or 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 = verified_distribution_console(scripts.pop())
if script is not None and os.access(script, os.X_OK):
return script, True
Comment thread
huangruiteng marked this conversation as resolved.
Resolved
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 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 _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).resolve() == 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,
Expand Down Expand Up @@ -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 = doctor_invocation_path()
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
Expand Down Expand Up @@ -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",
Expand Down
21 changes: 20 additions & 1 deletion loopx/python_install_owner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
42 changes: 22 additions & 20 deletions loopx/release_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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 {
Expand All @@ -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",
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -311,10 +313,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)
Expand Down
Loading
Loading