diff --git a/loopx/hosts/agy/__init__.py b/loopx/hosts/agy/__init__.py index 0312354b60..dc1eb79556 100644 --- a/loopx/hosts/agy/__init__.py +++ b/loopx/hosts/agy/__init__.py @@ -7,9 +7,11 @@ from __future__ import annotations +from collections.abc import Sequence import os import shlex import shutil +import subprocess import sys from pathlib import Path from typing import Any @@ -233,27 +235,409 @@ def build_antigravity_sidecar_template( } -def _antigravity_provider_args( +_HOST_RUNTIME_MODULE = "loopx.hosts.agy.host_runtime" +_LEGACY_HOST_RUNTIME_MODULE = "loopx.agy_goal_mode.host_runtime" +_RELEASE_ROOT_BOOTSTRAP = ( + "import os,runpy,shutil,sys;from pathlib import Path;" + "a=sys.argv[1:];" + 'c=next((a[i+1] for i,v in enumerate(a) if v=="--cli-bin" and i+11 and p.parent.name in (\"scripts\",\"bin\") and (p.parents[1]/\"loopx\"/\"__init__.py\").is_file() else None;" + f'm=(("{_HOST_RUNTIME_MODULE}" if (r/"loopx"/"hosts"/"agy"/"__init__.py").is_file() and (r/"loopx"/"hosts"/"agy"/"host_runtime.py").is_file() else "") if (r/"loopx"/"hosts"/"agy").is_dir() else ("{_LEGACY_HOST_RUNTIME_MODULE}" if (r/"loopx"/"agy_goal_mode"/"__init__.py").is_file() and (r/"loopx"/"agy_goal_mode"/"host_runtime.py").is_file() else "")) if r is not None else "";' + 'not m and sys.exit("loopx release root not found from --cli-bin");' + 'sys.path[:]=[str(r),*(x for x in sys.path if x not in ("",".",str(r)))];' + 'os.environ["LOOPX_RELEASE_ROOT"]=str(r);' + 'sys.argv=[m,*a];' + 'runpy.run_module(m,run_name="__main__",alter_sys=True)' +) +_POSIX_RELEASE_SHELL_BOOTSTRAP = ( + "set -eu\n" + 'fallback_py="$1"\n' + 'boot="$2"\n' + "shift 2\n" + 'cli=""\n' + 'prev=""\n' + 'for arg in "$@"; do\n' + ' if [ "$prev" = "--cli-bin" ]; then\n' + ' cli="$arg"\n' + " break\n" + " fi\n" + ' case "$arg" in\n' + ' --cli-bin=*) cli="${arg#--cli-bin=}"; break ;;\n' + " esac\n" + ' prev="$arg"\n' + "done\n" + 'case "$cli" in\n' + ' "") p="" ;;\n' + ' */*) p="$cli" ;;\n' + ' *) p="$(command -v "$cli" 2>/dev/null || printf \'%s\' "$cli")" ;;\n' + "esac\n" + 'while [ -n "$p" ] && [ -L "$p" ]; do\n' + ' case "$p" in\n' + ' */*) p_dir="${p%/*}"; [ -n "$p_dir" ] || p_dir="/" ;;\n' + ' *) p_dir="." ;;\n' + " esac\n" + ' d="$(cd -P "$p_dir" && pwd)"\n' + ' t="$(readlink "$p")"\n' + ' case "$t" in\n' + ' /*) p="$t" ;;\n' + ' *) p="$d/$t" ;;\n' + " esac\n" + "done\n" + 'if [ -z "$p" ] || [ ! -f "$p" ] || [ ! -x "$p" ]; then\n' + ' printf \'loopx release root not found from --cli-bin\\n\' >&2\n' + " exit 1\n" + "fi\n" + 'case "$p" in\n' + ' */*) p_dir="${p%/*}"; [ -n "$p_dir" ] || p_dir="/" ;;\n' + ' *) p_dir="." ;;\n' + "esac\n" + 'p_dir="$(cd -P "$p_dir" && pwd)"\n' + 'parent_name="${p_dir##*/}"\n' + 'r="$(cd -P "$p_dir/.." && pwd)"\n' + 'if { [ "$parent_name" != "scripts" ] && [ "$parent_name" != "bin" ]; } \\\n' + ' || [ ! -f "$r/loopx/__init__.py" ]; then\n' + ' printf \'loopx release root not found from --cli-bin\\n\' >&2\n' + " exit 1\n" + "fi\n" + 'if [ -d "$r/loopx/hosts/agy" ]; then\n' + ' if [ ! -f "$r/loopx/hosts/agy/__init__.py" ] \\\n' + ' || [ ! -f "$r/loopx/hosts/agy/host_runtime.py" ]; then\n' + ' printf \'loopx release root not found from --cli-bin\\n\' >&2\n' + " exit 1\n" + " fi\n" + 'elif [ ! -f "$r/loopx/agy_goal_mode/__init__.py" ] \\\n' + ' || [ ! -f "$r/loopx/agy_goal_mode/host_runtime.py" ]; then\n' + ' printf \'loopx release root not found from --cli-bin\\n\' >&2\n' + " exit 1\n" + "fi\n" + 'py=""\n' + 'if [ -n "${LOOPX_PYTHON:-}" ]; then\n' + ' case "$LOOPX_PYTHON" in\n' + ' */*) py="$LOOPX_PYTHON" ;;\n' + ' *) py="$(command -v "$LOOPX_PYTHON" 2>/dev/null || true)" ;;\n' + " esac\n" + ' if [ -z "$py" ] || [ ! -f "$py" ] || [ ! -x "$py" ]; then\n' + ' printf \'loopx configured LOOPX_PYTHON not found: %s\\n\' "$LOOPX_PYTHON" >&2\n' + " exit 1\n" + " fi\n" + 'elif [ -f "$r/.loopx-python" ]; then\n' + ' if [ -f "$r/scripts/loopx-python.sh" ]; then\n' + ' py="$(bash "$r/scripts/loopx-python.sh" 2>/dev/null || true)"\n' + " else\n" + ' IFS= read -r py <"$r/.loopx-python" || true\n' + " cr=\"$(printf '\\r')\"\n" + ' case "$py" in\n' + ' *"$cr") py="${py%"$cr"}" ;;\n' + " esac\n" + " fi\n" + "fi\n" + 'if [ -z "$py" ] || [ ! -f "$py" ] || [ ! -x "$py" ]; then\n' + ' if [ -n "$fallback_py" ] && [ -f "$fallback_py" ] && [ -x "$fallback_py" ]; then\n' + ' py="$fallback_py"\n' + ' elif [ -f "$r/scripts/loopx-python.sh" ]; then\n' + ' py="$(bash "$r/scripts/loopx-python.sh" 2>/dev/null || true)"\n' + " else\n" + ' py=""\n' + " fi\n" + "fi\n" + 'if [ -z "$py" ] || [ ! -f "$py" ] || [ ! -x "$py" ]; then\n' + ' py="$(command -v python3 2>/dev/null || true)"\n' + "fi\n" + 'if [ -z "$py" ] || [ ! -f "$py" ] || [ ! -x "$py" ]; then\n' + ' printf \'loopx python interpreter not found for release root: %s\\n\' "$r" >&2\n' + " exit 1\n" + "fi\n" + 'exec "$py" -E -P -c "$boot" "$@"\n' +) + + +def _resolved_executable_path(binary: str) -> str: + # Keep symlinked CLI paths (e.g. ~/.local/bin/loopx) un-dereferenced so + # hooks and plists track future `loopx upgrade` targets instead of pinning one release. + return os.path.abspath(os.path.expanduser(binary)) + + +def _is_explicit_cli_path(cli_bin: str) -> bool: + return ( + os.sep in cli_bin + or (os.altsep is not None and os.altsep in cli_bin) + or cli_bin.startswith((".", "~")) + ) + + +def _find_dangling_path_symlink(cli_bin: str) -> str | None: + for entry in os.environ.get("PATH", "").split(os.pathsep): + if not entry: + continue + candidate = Path(entry) / cli_bin + if os.path.islink(candidate) and not candidate.exists(): + return str(candidate) + if candidate.is_file() and os.access(candidate, os.X_OK): + return None + return None + + +def _has_host_runtime_files(release_root: Path) -> bool: + if not (release_root / "loopx" / "__init__.py").is_file(): + return False + hosts_agy_dir = release_root / "loopx" / "hosts" / "agy" + if hosts_agy_dir.is_dir(): + return ( + (hosts_agy_dir / "__init__.py").is_file() + and (hosts_agy_dir / "host_runtime.py").is_file() + ) + legacy_dir = release_root / "loopx" / "agy_goal_mode" + return ( + (legacy_dir / "__init__.py").is_file() + and (legacy_dir / "host_runtime.py").is_file() + ) + + +def _is_release_tree_launcher(path: Path) -> bool: + return ( + path.is_file() + and (os.name == "nt" or os.access(path, os.X_OK)) + and len(path.parents) > 1 + and path.parent.name in ("scripts", "bin") + and ( + (path.parents[1] / "loopx").is_dir() + or (path.parents[1] / "release.json").is_file() + ) + ) + + +def _is_valid_release_launcher(path: Path) -> bool: + return _is_release_tree_launcher(path) and _has_host_runtime_files(path.parents[1]) + + +def _validate_cli_launcher( + resolved_cli_bin: str, *, require_release_layout: bool +) -> Path | None: + if _is_explicit_cli_path(resolved_cli_bin): + target = Path(resolved_cli_bin).expanduser().resolve() + if not (target.is_file() and (os.name == "nt" or os.access(target, os.X_OK))): + raise FileNotFoundError( + f"LoopX CLI launcher not found or not executable: {resolved_cli_bin}" + ) + if require_release_layout and not _is_valid_release_launcher(target): + detail = ( + "host_runtime missing" + if _is_release_tree_launcher(target) + else "layout invalid" + ) + raise FileNotFoundError( + f"LoopX release snapshot launcher {detail}: {resolved_cli_bin}" + ) + return target + if require_release_layout: + raise FileNotFoundError( + f"LoopX release snapshot launcher not found for --cli-bin: {resolved_cli_bin}" + ) + return None + + +def _validated_release_shim_candidate( + raw_path: str, *, expected_root: Path | None +) -> tuple[str, bool] | None: + """Validate a candidate release CLI path, preserving symlinks lexically.""" + stripped = raw_path.strip() + if not stripped: + return None + normalized = _resolved_executable_path(stripped) + shim_path = Path(normalized) + try: + target = shim_path.resolve() + except (OSError, RuntimeError): + return None + if not _is_release_tree_launcher(target): + return None + if expected_root is not None: + try: + if not target.is_relative_to(expected_root): + return None + except (OSError, RuntimeError): + return None + return normalized, shim_path.is_symlink() + + +def _find_path_release_shim_candidate( + cli_bin: str, *, expected_root: Path +) -> tuple[str, bool] | None: + """Scan all PATH entries for a launcher resolving inside ``expected_root``.""" + first_regular: tuple[str, bool] | None = None + for entry in os.environ.get("PATH", "").split(os.pathsep): + if not entry: + continue + which_raw = shutil.which(cli_bin, path=entry) + if which_raw is None: + continue + candidate = _validated_release_shim_candidate( + which_raw, expected_root=expected_root + ) + if candidate is None: + continue + if candidate[1]: + return candidate + if first_regular is None: + first_regular = candidate + return first_regular + + +def _resolve_release_cli_shim(cli_bin: str) -> str | None: + release_root_raw = os.environ.get("LOOPX_RELEASE_ROOT", "").strip() + shim_raw = os.environ.get("LOOPX_CLI_SHIM", "").strip() + if cli_bin != "loopx" or (not release_root_raw and not shim_raw): + return None + expected_root: Path | None = None + if release_root_raw: + try: + expected_root = Path(release_root_raw).expanduser().resolve() + except (OSError, RuntimeError): + expected_root = None + + shim_candidate = ( + _validated_release_shim_candidate(shim_raw, expected_root=expected_root) + if shim_raw + else None + ) + if shim_candidate is not None and shim_candidate[1]: + return shim_candidate[0] + + launcher_name = "loopx.ps1" if os.name == "nt" else "loopx" + if expected_root is not None: + which_candidate = _find_path_release_shim_candidate( + cli_bin, expected_root=expected_root + ) + if which_candidate is not None and which_candidate[1]: + return which_candidate[0] + + default_shim = Path.home() / ".local" / "bin" / launcher_name + if default_shim.is_symlink(): + default_candidate = _validated_release_shim_candidate( + str(default_shim), expected_root=expected_root + ) + if default_candidate is not None: + return default_candidate[0] + + if which_candidate is not None: + return which_candidate[0] + if shim_candidate is not None: + return shim_candidate[0] + + root_launcher = expected_root / "scripts" / launcher_name + if _is_release_tree_launcher(root_launcher): + return str(root_launcher) + return None + + if shim_candidate is not None: + return shim_candidate[0] + return None + + +def resolve_antigravity_runtime_bins( + cli_bin: str, *, resolve_local_executable: bool = True +) -> tuple[str, str]: + """Resolve ``(python_bin, cli_bin)`` while preserving symlinked CLI shims.""" + if not resolve_local_executable: + return "python3", cli_bin + python_bin = _resolved_executable_path(sys.executable) + if _is_explicit_cli_path(cli_bin): + return python_bin, _resolved_executable_path(cli_bin) + found_cli = _resolve_release_cli_shim(cli_bin) + if found_cli is None: + dangling = _find_dangling_path_symlink(cli_bin) + found_cli = dangling if dangling is not None else shutil.which(cli_bin) + resolved_cli_bin = ( + _resolved_executable_path(found_cli) if found_cli is not None else cli_bin + ) + return python_bin, resolved_cli_bin + + +def _python_supports_isolated_module( + python_bin: str, *, expected_root: Path | None = None +) -> bool: + """Check whether ``python_bin -E -P`` imports ``host_runtime`` (and matches ``expected_root`` if given).""" + probe_code = ( + "import importlib.util, sys; from pathlib import Path; " + 'top = importlib.util.find_spec("loopx"); ' + f'mod = importlib.util.find_spec("{_HOST_RUNTIME_MODULE}") if top else None; ' + "ok = mod is not None; " + "origin = getattr(mod, 'origin', None) if ok else None; " + "ok = ok and (" + "len(sys.argv) <= 1 or (" + "isinstance(origin, str) and origin not in ('frozen', 'built-in') " + "and Path(origin).is_file() " + "and Path(origin).resolve().is_relative_to(Path(sys.argv[1]).resolve())" + ")); " + "raise SystemExit(0 if ok else 1)" + ) + cmd = [python_bin, "-E", "-P", "-c", probe_code] + if expected_root is not None: + cmd.append(str(expected_root.resolve())) + try: + probe = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=10, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return expected_root is None + return probe.returncode == 0 + + +def _use_isolated_host_module(python_bin: str, resolved_cli_bin: str) -> bool: + """Decide between ``-m`` and ``-c _RELEASE_ROOT_BOOTSTRAP`` without editable shadowing.""" + target = _validate_cli_launcher(resolved_cli_bin, require_release_layout=False) + if target is not None and _is_release_tree_launcher(target): + if not _has_host_runtime_files(target.parents[1]): + raise FileNotFoundError( + f"LoopX release snapshot host_runtime missing: {resolved_cli_bin}" + ) + cli_path = Path(resolved_cli_bin).expanduser() + if cli_path.is_symlink() or (target.parents[1] / "release.json").is_file(): + # Symlinked release shims or packaged snapshots always bootstrap from the + # CLI launcher so older .pth installs cannot shadow upgrades. + return False + return _python_supports_isolated_module( + python_bin, expected_root=target.parents[1] + ) + if _python_supports_isolated_module(python_bin): + return True + _validate_cli_launcher(resolved_cli_bin, require_release_layout=True) + return False + + +def build_antigravity_host_runtime_args( operation: str, *, cli_bin: str, goal_id: str | None, agent_id: str | None, conversation_id: str | None, - runtime_root: str | None, + runtime_root: str | None = None, registry: str | None = None, resolve_local_executable: bool = True, + extra_args: Sequence[str] = (), + resolved_bins: tuple[str, str] | None = None, ) -> list[str]: - python_bin = sys.executable if resolve_local_executable else "python3" - resolved_cli_bin = ( - (shutil.which(cli_bin) or cli_bin) if resolve_local_executable else cli_bin + """Build argv to launch ``loopx.hosts.agy.host_runtime`` across venv and release snapshots.""" + python_bin, resolved_cli_bin = ( + resolved_bins + if resolved_bins is not None + else resolve_antigravity_runtime_bins( + cli_bin, resolve_local_executable=resolve_local_executable + ) ) - args = [ - python_bin, - "-E", - "-P", - "-m", - "loopx.hosts.agy.host_runtime", + uses_isolated_module = ( + not resolve_local_executable + or _use_isolated_host_module(python_bin, resolved_cli_bin) + ) + operation_tail = [ operation, "--cli-bin", resolved_cli_bin, @@ -263,12 +647,34 @@ def _antigravity_provider_args( agent_id or "", "--conversation-id", conversation_id or "", + *extra_args, ] if runtime_root: - args.extend(["--runtime-root", runtime_root]) + operation_tail.extend(["--runtime-root", runtime_root]) if registry: - args.extend(["--registry", registry]) - return args + operation_tail.extend(["--registry", registry]) + if not uses_isolated_module and os.name != "nt": + return [ + "/bin/sh", + "-c", + _POSIX_RELEASE_SHELL_BOOTSTRAP, + "loopx-agy-host-runtime", + python_bin, + _RELEASE_ROOT_BOOTSTRAP, + *operation_tail, + ] + launcher_prefix = ( + ["-m", _HOST_RUNTIME_MODULE] + if uses_isolated_module + else ["-c", _RELEASE_ROOT_BOOTSTRAP] + ) + return [ + python_bin, + "-E", + "-P", + *launcher_prefix, + *operation_tail, + ] def cron_for_interval_minutes(interval_minutes: int) -> str: @@ -291,7 +697,7 @@ def build_antigravity_hooks_template( ) -> dict[str, Any]: """Native Stop hook; installation alone never binds an arbitrary chat.""" conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) - args = _antigravity_provider_args( + args = build_antigravity_host_runtime_args( "stop-hook", cli_bin=cli_bin, goal_id=goal_id, @@ -323,7 +729,7 @@ def build_antigravity_launchd_command( ) -> list[str]: """Return argv to preview or install the reboot-surviving LaunchAgent watchdog.""" conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) - return _antigravity_provider_args( + return build_antigravity_host_runtime_args( "install-launchd", cli_bin=cli_bin, goal_id=goal_id, @@ -418,7 +824,7 @@ def antigravity_app_activation_extras( agent_id=agent_id, runtime_root=runtime_root, registry=registry, - resolve_local_executable=False, + resolve_local_executable=True, ) launchd_command = build_antigravity_launchd_command( cli_bin=cli_bin, @@ -426,7 +832,7 @@ def antigravity_app_activation_extras( agent_id=agent_id, runtime_root=runtime_root, registry=registry, - resolve_local_executable=False, + resolve_local_executable=True, ) wake_prompt = sidecar_template["sidecar"]["loopx-heartbeat"]["bootstrap_prompt"] return { diff --git a/loopx/hosts/agy/launchd_watchdog.py b/loopx/hosts/agy/launchd_watchdog.py index be82386ac3..18244652fb 100644 --- a/loopx/hosts/agy/launchd_watchdog.py +++ b/loopx/hosts/agy/launchd_watchdog.py @@ -12,6 +12,11 @@ import subprocess import sys +from . import ( + build_antigravity_host_runtime_args, + resolve_antigravity_runtime_bins, +) + DEFAULT_LAUNCHD_INTERVAL_SECONDS = 300 MIN_LAUNCHD_INTERVAL_SECONDS = 60 DEFAULT_LONG_IDLE_SECONDS = 2400 @@ -34,11 +39,6 @@ def _resolved_optional_path( return str(Path(stripped).expanduser().resolve()) -def _resolved_executable_path(binary: str) -> str: - expanded = os.path.expanduser(binary) - return os.path.abspath(expanded) - - def _resolved_launchd_path( env_path: str | None = None, *, @@ -59,6 +59,7 @@ def _resolved_launchd_path( for candidate in (python_bin, cli_bin): if candidate and Path(candidate).is_absolute(): extras.append(str(Path(candidate).parent)) + extras.extend(["/usr/bin", "/bin"]) for entry in extras: if entry not in parts: parts.append(entry) @@ -112,17 +113,8 @@ def build_antigravity_launchd_plist( resolved_label = validated_launchd_label( label, goal_id=goal_id, agent_id=agent_id, conversation_id=conversation_id ) - python_bin = ( - _resolved_executable_path(sys.executable) - if resolve_local_executable - else "python3" - ) - found_cli = shutil.which(cli_bin) if resolve_local_executable else None - resolved_cli_bin = ( - _resolved_executable_path(found_cli or cli_bin) - if resolve_local_executable - and (found_cli is not None or os.sep in cli_bin or cli_bin.startswith(".")) - else cli_bin + python_bin, resolved_cli_bin = resolve_antigravity_runtime_bins( + cli_bin, resolve_local_executable=resolve_local_executable ) resolved_state = _resolved_optional_path(state_dir) or str( (Path.home() / ".loopx/host-state/antigravity").resolve() @@ -134,32 +126,25 @@ def build_antigravity_launchd_plist( registry, preserve_tokens=frozenset({_HOST_GLOBAL_REGISTRY_SELECTOR}) ) resolved_runtime_root = _resolved_optional_path(runtime_root) - program_args = [ - python_bin, - "-E", - "-P", - "-m", - "loopx.hosts.agy.host_runtime", + program_args = build_antigravity_host_runtime_args( "heartbeat-tick", - "--cli-bin", - resolved_cli_bin, - "--goal-id", - goal_id, - "--agent-id", - agent_id, - "--conversation-id", - conversation_id, - "--state-dir", - resolved_state, - "--long-idle-seconds", - str(max(60, int(long_idle_seconds))), - "--cooldown-seconds", - str(max(MIN_STALL_COOLDOWN_SECONDS, int(cooldown_seconds))), - ] - if resolved_registry: - program_args.extend(["--registry", resolved_registry]) - if resolved_runtime_root: - program_args.extend(["--runtime-root", resolved_runtime_root]) + cli_bin=resolved_cli_bin, + goal_id=goal_id, + agent_id=agent_id, + conversation_id=conversation_id, + runtime_root=resolved_runtime_root, + registry=resolved_registry, + resolve_local_executable=resolve_local_executable, + extra_args=[ + "--state-dir", + resolved_state, + "--long-idle-seconds", + str(max(60, int(long_idle_seconds))), + "--cooldown-seconds", + str(max(MIN_STALL_COOLDOWN_SECONDS, int(cooldown_seconds))), + ], + resolved_bins=(python_bin, resolved_cli_bin), + ) return { "Label": resolved_label, "ProgramArguments": program_args, diff --git a/scripts/loopx b/scripts/loopx index caf7d9b03a..8ccaba0650 100755 --- a/scripts/loopx +++ b/scripts/loopx @@ -2,6 +2,12 @@ set -euo pipefail script_path="${BASH_SOURCE[0]}" +if [[ "$script_path" == /* ]]; then + invoked_cli_path="$script_path" +else + invoked_cli_path="$PWD/$script_path" +fi +export LOOPX_CLI_SHIM="$invoked_cli_path" while [[ -L "$script_path" ]]; do script_dir="$(cd -P "$(dirname "$script_path")" && pwd)" script_path="$(readlink "$script_path")" diff --git a/tests/test_agy_goal_mode_host_runtime.py b/tests/test_agy_goal_mode_host_runtime.py index a417bac493..1ce019789d 100644 --- a/tests/test_agy_goal_mode_host_runtime.py +++ b/tests/test_agy_goal_mode_host_runtime.py @@ -9,16 +9,19 @@ from pathlib import Path import platform import plistlib +import shlex import shutil import subprocess import sys import tempfile import time +import venv import pytest from loopx.hosts.agy import ( antigravity_app_activation_extras, + build_antigravity_hooks_template, build_antigravity_launchd_command, host_runtime, launchd_watchdog, @@ -433,13 +436,24 @@ def intercept_run( assert sent_payloads[0]["cascadeId"] == "conv-real-1" +def _make_venv_cli_stub(root: Path) -> Path: + bin_dir = root / ("Scripts" if os.name == "nt" else "bin") + bin_dir.mkdir(parents=True, exist_ok=True) + stub = bin_dir / ("loopx.exe" if os.name == "nt" else "loopx") + stub.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + stub.chmod(0o755) + return stub + + def test_install_launchd_preview_execute_no_load_reload_and_uninstall( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: agents_dir = tmp_path / "LaunchAgents" log_dir = tmp_path / "logs" + venv_cli = _make_venv_cli_stub(tmp_path / "stub-venv") args = _args( tmp_path, + cli_bin=str(venv_cli), launch_agents_dir=str(agents_dir), log_dir=str(log_dir), interval_seconds=20, # clamped to >= 60s @@ -458,7 +472,7 @@ def test_install_launchd_preview_execute_no_load_reload_and_uninstall( assert not agents_dir.exists() # Dry-run safety rejects path-traversal labels. - bad_args = _args(tmp_path, label="../../escape") + bad_args = _args(tmp_path, cli_bin=str(venv_cli), label="../../escape") with pytest.raises(ValueError, match="unsafe path"): host_runtime.install_launchd(bad_args) @@ -534,9 +548,12 @@ def test_install_launchd_uninstall_verifies_launchd_readback_across_all_paths( monkeypatch.setattr(sys, "platform", "darwin") agents_dir = tmp_path / "LaunchAgents" state_dir = tmp_path / "state" + venv_cli = _make_venv_cli_stub(tmp_path / "stub-venv") base_argv = [ "host_runtime", "install-launchd", + "--cli-bin", + str(venv_cli), "--goal-id", "g-uninst", "--agent-id", @@ -629,6 +646,8 @@ def ambiguous_readback( "-m", "loopx.hosts.agy.host_runtime", "install-launchd", + "--cli-bin", + str(venv_cli), "--goal-id", "g-uninst", "--agent-id", @@ -819,7 +838,10 @@ def test_activation_extras_and_main_cli_json_contracts( "loopx.hosts.agy.host_runtime", "install-launchd", ] - extras = antigravity_app_activation_extras(goal_id="g1", agent_id="a1") + venv_cli = _make_venv_cli_stub(tmp_path / "stub-venv") + extras = antigravity_app_activation_extras( + goal_id="g1", agent_id="a1", cli_bin=str(venv_cli) + ) assert "install-launchd" in extras["extra_host_mutation"]["reboot_watchdog_command"] monkeypatch.setattr( @@ -828,6 +850,8 @@ def test_activation_extras_and_main_cli_json_contracts( [ "host_runtime", "install-launchd", + "--cli-bin", + str(venv_cli), "--goal-id", "g1", "--agent-id", @@ -843,3 +867,2130 @@ def test_activation_extras_and_main_cli_json_contracts( assert host_runtime.main() == 0 payload = json.loads(capsys.readouterr().out) assert payload["ok"] is True and payload["dry_run"] is True + + +def _make_release_snapshot(release_dir: Path, repo_root: Path) -> None: + """Create a release-snapshot tree matching ``scripts/install-local.sh`` layout.""" + scripts_dir = release_dir / "scripts" + pkg_dir = release_dir / "loopx" + scripts_dir.mkdir(parents=True, exist_ok=True) + pkg_dir.mkdir(parents=True, exist_ok=True) + launcher = scripts_dir / "loopx" + launcher.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + launcher.chmod(0o755) + source_pkg = repo_root / "loopx" + for entry in source_pkg.iterdir(): + if entry.name in {"__pycache__", "hosts"}: + continue + target = pkg_dir / entry.name + if entry.is_dir(): + target.symlink_to(entry, target_is_directory=True) + else: + target.symlink_to(entry) + shutil.copytree( + source_pkg / "hosts", + pkg_dir / "hosts", + ignore=shutil.ignore_patterns("__pycache__"), + ) + + +def test_release_snapshot_hooks_and_launchd_survive_upgrades_without_site_packages_loopx( + tmp_path: Path, +) -> None: + repo_root = Path(__file__).resolve().parents[1] + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / ( + "Scripts/python.exe" if os.name == "nt" else "bin/python" + ) + + # Confirm the provider Python has no `loopx` in site-packages under `-E -P`. + missing_mod = subprocess.run( + [ + str(provider_python), + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + "--help", + ], + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert missing_mod.returncode != 0 + assert "No module named 'loopx'" in missing_mod.stderr + + r1 = tmp_path / "releases" / "r1" + r2 = tmp_path / "releases" / "r2" + _make_release_snapshot(r1, repo_root) + _make_release_snapshot(r2, repo_root) + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + cli_symlink = bin_dir / "loopx" + cli_symlink.symlink_to(r1 / "scripts" / "loopx") + + # Simulate generating hooks.json, LaunchAgent plist, and launchd install command + # from inside the live r1 release-snapshot process (where PYTHONPATH=r1 makes + # loopx importable in-process, even though provider_python -E -P lacks it). + state_dir = tmp_path / "state" + log_dir = tmp_path / "logs" + build_script = ( + "import json; from loopx.hosts.agy import " + "build_antigravity_hooks_template, build_antigravity_launchd_command, launchd_watchdog; " + "hooks = build_antigravity_hooks_template(" + "cli_bin='loopx', goal_id='g-rel', agent_id='a-rel', conversation_id='c-rel'); " + "plist = launchd_watchdog.build_antigravity_launchd_plist(" + "goal_id='g-rel', agent_id='a-rel', conversation_id='c-rel', " + f"cli_bin='loopx', state_dir={str(state_dir)!r}, log_dir={str(log_dir)!r}); " + "install_cmd = build_antigravity_launchd_command(" + "cli_bin='loopx', goal_id='g-rel', agent_id='a-rel', conversation_id='c-rel'); " + "print(json.dumps({'hooks': hooks, 'plist': plist, 'install_cmd': install_cmd}))" + ) + build_env = { + **os.environ, + "LOOPX_RELEASE_ROOT": str(r1), + "PYTHONPATH": str(r1), + "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '/usr/bin:/bin')}", + } + generated = json.loads( + subprocess.check_output( + [str(provider_python), "-c", build_script], + env=build_env, + text=True, + encoding="utf-8", + timeout=30, + ) + ) + hook_cmd = shlex.split(generated["hooks"]["loopx"]["Stop"][0]["command"]) + program_args = [str(arg) for arg in generated["plist"]["ProgramArguments"]] + install_cmd = [str(arg) for arg in generated["install_cmd"]] + + for cmd in (hook_cmd, program_args, install_cmd): + assert "--cli-bin" in cmd + assert cmd[cmd.index("--cli-bin") + 1] == str(cli_symlink) + assert str(r1) not in " ".join(cmd) + + # Works against r1 first. + stop_event = json.dumps({"terminationReason": "USER_CANCELED"}) + r1_hook = subprocess.run( + hook_cmd, + input=stop_event, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=True, + ) + assert json.loads(r1_hook.stdout) == {} + + # Upgrade symlink to r2 and remove r1 completely; poison ambient PYTHONPATH and cwd. + cli_symlink.unlink() + cli_symlink.symlink_to(r2 / "scripts" / "loopx") + shutil.rmtree(r1) + + foreign_pkg = tmp_path / "foreign" / "loopx" + foreign_pkg.mkdir(parents=True) + (foreign_pkg / "__init__.py").write_text( + 'raise RuntimeError("poisoned PYTHONPATH")\n', encoding="utf-8" + ) + poison_cwd = tmp_path / "work" + cwd_pkg = poison_cwd / "loopx" + cwd_pkg.mkdir(parents=True) + (cwd_pkg / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + isolated_env = { + "HOME": str(tmp_path), + "PATH": "/usr/bin:/bin", + "PYTHONPATH": str(foreign_pkg.parent), + "TMPDIR": str(tmp_path), + } + + r2_hook = subprocess.run( + hook_cmd, + input=stop_event, + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=True, + ) + assert json.loads(r2_hook.stdout) == {} + + plist_env = { + **{str(k): str(v) for k, v in generated["plist"]["EnvironmentVariables"].items()}, + "HOME": str(tmp_path), + "PYTHONPATH": str(foreign_pkg.parent), + "TMPDIR": str(tmp_path), + } + r2_tick = subprocess.run( + program_args, + cwd="/", + env=plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=True, + ) + assert json.loads(r2_tick.stdout)["ok"] is True + + # Even inside an editable/pip venv, a symlinked release launcher still uses the + # launcher bootstrap so editable installs do not shadow `cli_symlink` or `loopx upgrade`. + symlink_hook_cmd = shlex.split( + build_antigravity_hooks_template( + cli_bin=str(cli_symlink), + goal_id="g-rel", + agent_id="a-rel", + conversation_id="c-rel", + )["loopx"]["Stop"][0]["command"] + ) + if os.name == "nt": + assert symlink_hook_cmd[:4] == [sys.executable, "-E", "-P", "-c"] + else: + assert symlink_hook_cmd[:2] == ["/bin/sh", "-c"] + assert symlink_hook_cmd[4] == sys.executable + + # Ordinary pip/venv console scripts (and matching checkout scripts) keep standard `-m`. + venv_cli = Path(sys.executable).with_name( + "loopx.exe" if os.name == "nt" else "loopx" + ) + if venv_cli.is_file() and (os.name == "nt" or os.access(venv_cli, os.X_OK)): + venv_hook_cmd = shlex.split( + build_antigravity_hooks_template( + cli_bin=str(venv_cli), + goal_id="g-rel", + agent_id="a-rel", + conversation_id="c-rel", + )["loopx"]["Stop"][0]["command"] + ) + assert venv_hook_cmd[:5] == [ + sys.executable, + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + ] + checkout_cli = repo_root / "scripts" / "loopx" + if ( + checkout_cli.is_file() + and Path(host_runtime.__file__).resolve().is_relative_to(repo_root.resolve()) + and not (repo_root / "release.json").is_file() + ): + checkout_hook_cmd = shlex.split( + build_antigravity_hooks_template( + cli_bin=str(checkout_cli), + goal_id="g-rel", + agent_id="a-rel", + conversation_id="c-rel", + )["loopx"]["Stop"][0]["command"] + ) + assert checkout_hook_cmd[:5] == [ + sys.executable, + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + ] + + r2_install = subprocess.run( + [ + *install_cmd, + "--dry-run", + "--state-dir", + str(state_dir), + "--launch-agents-dir", + str(tmp_path / "LaunchAgents"), + ], + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=True, + ) + r2_install_payload = json.loads(r2_install.stdout) + assert r2_install_payload["ok"] is True + assert str(cli_symlink) in r2_install_payload["plist"]["ProgramArguments"] + + # Fail closed when only the target launcher file (`scripts/loopx`) disappears while + # the release package directory (`r2/loopx`) and symlink remain intact. + (r2 / "scripts" / "loopx").unlink() + missing_launcher_install = subprocess.run( + [ + *install_cmd, + "--dry-run", + "--state-dir", + str(state_dir), + "--launch-agents-dir", + str(tmp_path / "LaunchAgents"), + ], + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert missing_launcher_install.returncode != 0 + assert "release root not found" in missing_launcher_install.stderr + assert missing_launcher_install.stdout.strip() == "" + + missing_launcher_hook = subprocess.run( + hook_cmd, + input=stop_event, + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert missing_launcher_hook.returncode != 0 + assert "release root not found" in missing_launcher_hook.stderr + assert "poisoned" not in missing_launcher_hook.stderr + + # Direct in-process builders inside the retained r2 package tree and editable venv + # also fail closed rather than emitting a dangling launcher into hooks or plists. + dangling_build_probe = subprocess.run( + [str(provider_python), "-c", build_script], + env={ + **os.environ, + "LOOPX_RELEASE_ROOT": str(r2), + "PYTHONPATH": str(r2), + "PATH": f"{bin_dir}{os.pathsep}/usr/bin:/bin", + }, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert dangling_build_probe.returncode != 0 + assert "FileNotFoundError" in dangling_build_probe.stderr + with pytest.raises(FileNotFoundError): + build_antigravity_hooks_template( + cli_bin=str(cli_symlink), + goal_id="g-rel", + agent_id="a-rel", + conversation_id="c-rel", + ) + with pytest.raises(FileNotFoundError): + launchd_watchdog.build_antigravity_launchd_plist( + goal_id="g-rel", + agent_id="a-rel", + conversation_id="c-rel", + cli_bin=str(cli_symlink), + state_dir=str(state_dir), + log_dir=str(log_dir), + ) + + # Reject non-release layout even when the pointed file exists inside the release tree + # (parents[1] is `r2`, with `r2/loopx` present, but parent dir is not `scripts`/`bin`). + bad_layout_dir = r2 / "other" + bad_layout_dir.mkdir() + bad_exec = bad_layout_dir / "loopx" + bad_exec.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + bad_exec.chmod(0o755) + bad_layout_link = tmp_path / "bad-loopx" + bad_layout_link.symlink_to(bad_exec) + bad_layout_probe = subprocess.run( + [ + str(provider_python), + "-c", + "from loopx.hosts.agy import build_antigravity_launchd_command; " + f"build_antigravity_launchd_command(cli_bin={str(bad_layout_link)!r}, " + "goal_id='g', agent_id='a', conversation_id='c')", + ], + env={**os.environ, "PYTHONPATH": str(r2)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert bad_layout_probe.returncode != 0 + assert "FileNotFoundError" in bad_layout_probe.stderr + bad_layout_hook_cmd = list(hook_cmd) + bad_layout_hook_cmd[bad_layout_hook_cmd.index("--cli-bin") + 1] = str(bad_layout_link) + bad_layout_runtime = subprocess.run( + bad_layout_hook_cmd, + input=stop_event, + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert bad_layout_runtime.returncode != 0 + assert "release root not found" in bad_layout_runtime.stderr + assert "poisoned" not in bad_layout_runtime.stderr + + # Fail closed if the entire release symlink target directory disappears. + shutil.rmtree(r2) + broken_hook = subprocess.run( + hook_cmd, + input=stop_event, + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert broken_hook.returncode != 0 + assert "release root not found" in broken_hook.stderr + assert "poisoned" not in broken_hook.stderr + + +def test_release_snapshot_not_shadowed_by_older_editable_pth_install( + tmp_path: Path, +) -> None: + repo_root = Path(__file__).resolve().parents[1] + + # 1. Build an older importable editable LoopX tree supporting only `stop-hook` + # (rejecting `heartbeat-tick` with exit 2) and attach it via `.pth` to provider_venv. + old_editable = tmp_path / "old-editable" + old_pkg = old_editable / "loopx" / "hosts" / "agy" + old_pkg.mkdir(parents=True) + (old_editable / "loopx" / "__init__.py").write_text("", encoding="utf-8") + (old_editable / "loopx" / "hosts" / "__init__.py").write_text("", encoding="utf-8") + (old_pkg / "__init__.py").write_text("", encoding="utf-8") + (old_pkg / "host_runtime.py").write_text( + "import argparse, sys\n" + "def main() -> int:\n" + " parser = argparse.ArgumentParser(prog='loopx.hosts.agy.host_runtime')\n" + " sub = parser.add_subparsers(dest='operation', required=True)\n" + " sub.add_parser('stop-hook')\n" + " parser.parse_args()\n" + " return 0\n" + "if __name__ == '__main__':\n" + " raise SystemExit(main())\n", + encoding="utf-8", + ) + + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / ( + "Scripts/python.exe" if os.name == "nt" else "bin/python" + ) + provider_purelib = Path( + subprocess.check_output( + [str(provider_python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], + text=True, + encoding="utf-8", + timeout=15, + ).strip() + ) + (provider_purelib / "old_loopx.pth").write_text( + f"{old_editable}\n", encoding="utf-8" + ) + + shadow_check = subprocess.run( + [ + str(provider_python), + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + "heartbeat-tick", + "--help", + ], + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert shadow_check.returncode == 2 + assert "stop-hook" in shadow_check.stderr + + # 2. Create healthy newer release snapshot + symlinked CLI shim, non-symlink packaged + # snapshot (with release.json), and non-symlink checkout (without release.json). + r_sym = tmp_path / "releases" / "r-sym" + _make_release_snapshot(r_sym, repo_root) + cli_symlink = tmp_path / "bin" / "loopx" + cli_symlink.parent.mkdir() + cli_symlink.symlink_to(r_sym / "scripts" / "loopx") + + r_pkg = tmp_path / "releases" / "r-pkg" + _make_release_snapshot(r_pkg, repo_root) + (r_pkg / "release.json").write_text('{"schema_version":"v1"}\n', encoding="utf-8") + + r_direct = tmp_path / "checkouts" / "r-direct" + _make_release_snapshot(r_direct, repo_root) + + state_dir = tmp_path / "state" + log_dir = tmp_path / "logs" + inspect_script = ( + "import json; from loopx.hosts.agy import " + "build_antigravity_host_runtime_args, launchd_watchdog; " + f"args_sym = build_antigravity_host_runtime_args('heartbeat-tick', cli_bin={str(cli_symlink)!r}, " + "goal_id='g-e2e', agent_id='a-e2e', conversation_id='c-e2e'); " + "plist_sym = launchd_watchdog.build_antigravity_launchd_plist(" + f"goal_id='g-e2e', agent_id='a-e2e', conversation_id='c-e2e', cli_bin={str(cli_symlink)!r}, " + f"state_dir={str(state_dir)!r}, log_dir={str(log_dir)!r}); " + f"args_pkg = build_antigravity_host_runtime_args('heartbeat-tick', cli_bin={str(r_pkg / 'scripts' / 'loopx')!r}, " + "goal_id='g-e2e', agent_id='a-e2e', conversation_id='c-e2e'); " + f"args_direct = build_antigravity_host_runtime_args('heartbeat-tick', cli_bin={str(r_direct / 'scripts' / 'loopx')!r}, " + "goal_id='g-e2e', agent_id='a-e2e', conversation_id='c-e2e'); " + "print(json.dumps({'args_sym': args_sym, 'plist_args': plist_sym['ProgramArguments'], " + "'args_pkg': args_pkg, 'args_direct': args_direct}))" + ) + generated = json.loads( + subprocess.check_output( + [str(provider_python), "-c", inspect_script], + env={**os.environ, "PYTHONPATH": str(r_sym)}, + text=True, + encoding="utf-8", + timeout=30, + ) + ) + for key in ("args_sym", "plist_args", "args_pkg", "args_direct"): + argv = [str(item) for item in generated[key]] + if os.name == "nt": + assert argv[:4] == [str(provider_python), "-E", "-P", "-c"], (key, argv[:6]) + else: + assert argv[:2] == ["/bin/sh", "-c"], (key, argv[:6]) + assert argv[4] == str(provider_python), (key, argv[:6]) + help_run = subprocess.run( + [*argv, "--help"], + cwd=tmp_path, + env={"HOME": str(tmp_path), "PATH": "/usr/bin:/bin", "TMPDIR": str(tmp_path)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert help_run.returncode == 0, (key, help_run.stderr) + assert "--cli-bin" in help_run.stdout + + # 3. Preserve `-m` fast-path for BOTH matching editable checkouts (Case B without + # release.json) AND ordinary pip/venv console scripts (Case C). + matching_venv = tmp_path / "matching-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(matching_venv) + matching_python = matching_venv / ( + "Scripts/python.exe" if os.name == "nt" else "bin/python" + ) + matching_purelib = Path( + subprocess.check_output( + [str(matching_python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], + text=True, + encoding="utf-8", + timeout=15, + ).strip() + ) + (matching_purelib / "matching_loopx.pth").write_text( + f"{r_direct}\n", encoding="utf-8" + ) + venv_console_cli = matching_venv / ( + "Scripts/loopx.exe" if os.name == "nt" else "bin/loopx" + ) + venv_console_cli.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + venv_console_cli.chmod(0o755) + + matching_script = ( + "import json; from loopx.hosts.agy import build_antigravity_host_runtime_args; " + f"direct_args = build_antigravity_host_runtime_args('heartbeat-tick', cli_bin={str(r_direct / 'scripts' / 'loopx')!r}, " + "goal_id='g-m', agent_id='a-m', conversation_id='c-m'); " + f"venv_args = build_antigravity_host_runtime_args('heartbeat-tick', cli_bin={str(venv_console_cli)!r}, " + "goal_id='g-m', agent_id='a-m', conversation_id='c-m'); " + "print(json.dumps({'direct_args': direct_args, 'venv_args': venv_args}))" + ) + matching_out = json.loads( + subprocess.check_output( + [str(matching_python), "-c", matching_script], + text=True, + encoding="utf-8", + timeout=30, + ) + ) + for key in ("direct_args", "venv_args"): + argv = [str(item) for item in matching_out[key]] + assert argv[:5] == [ + str(matching_python), + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + ], (key, argv[:6]) + help_run = subprocess.run( + [*argv, "--help"], + cwd=tmp_path, + env={"HOME": str(tmp_path), "PATH": "/usr/bin:/bin", "TMPDIR": str(tmp_path)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert help_run.returncode == 0, (key, help_run.stderr) + + +def test_activation_pack_and_onboard_commands_execute_under_clean_provider_python( + tmp_path: Path, +) -> None: + repo_root = Path(__file__).resolve().parents[1] + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / ( + "Scripts/python.exe" if os.name == "nt" else "bin/python" + ) + missing_mod = subprocess.run( + [str(provider_python), "-E", "-P", "-m", "loopx.hosts.agy.host_runtime", "--help"], + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert missing_mod.returncode != 0 + assert "No module named 'loopx'" in missing_mod.stderr + + r_act = tmp_path / "releases" / "r-act" + _make_release_snapshot(r_act, repo_root) + (r_act / "release.json").write_text('{"schema_version":"v1"}\n', encoding="utf-8") + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + cli_symlink = bin_dir / "loopx" + cli_symlink.symlink_to(r_act / "scripts" / "loopx") + + project = tmp_path / "project" + registry_path = project / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True) + runtime_root = tmp_path / "runtime" + runtime_root.mkdir() + (project / "ACTIVE_GOAL_STATE.md").write_text("# Goal\n\nActivate.\n", encoding="utf-8") + registry_path.write_text( + json.dumps( + { + "common_runtime_root": str(runtime_root), + "goals": [ + { + "id": "g-act", + "domain": "test", + "status": "active", + "repo": str(project), + "state_file": "ACTIVE_GOAL_STATE.md", + "coordination": { + "registered_agents": ["worker-act"], + "agent_model": "peer_v1", + }, + "adapter": { + "kind": "generic_project_goal_v0", + "status": "connected", + }, + } + ], + } + ), + encoding="utf-8", + ) + + poison_cwd = tmp_path / "poison" + poison_pkg = poison_cwd / "loopx" + poison_pkg.mkdir(parents=True) + (poison_pkg / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + isolated_provider_env = { + "HOME": str(tmp_path), + "LOOPX_USAGE_PING": "0", + "PATH": "/usr/bin:/bin", + "TMPDIR": str(tmp_path), + } + + node_bin = shutil.which("node") + assert node_bin is not None, "node is required to execute agent-onboard CLI probe" + node_only_dir = tmp_path / "node-only-bin" + node_only_dir.mkdir() + (node_only_dir / ("node.exe" if os.name == "nt" else "node")).symlink_to(node_bin) + + cli_runner = "import sys; from loopx.cli import main; raise SystemExit(main(sys.argv[1:]))" + invocations = [ + ( + "bootstrap-command-pack-with-path", + f"{bin_dir}{os.pathsep}{node_only_dir}{os.pathsep}/usr/bin:/bin", + str(cli_symlink), + [ + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "bootstrap-command-pack", + "--project", + str(project), + "--host-surface", + "antigravity-app", + "--goal-id", + "g-act", + "--agent-id", + "worker-act", + ], + ), + ( + "agent-onboard-with-path", + f"{bin_dir}{os.pathsep}{node_only_dir}{os.pathsep}/usr/bin:/bin", + str(cli_symlink), + [ + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "agent-onboard", + "--project", + str(project), + "--agent-type", + "antigravity-app", + "--goal-id", + "g-act", + "--agent-id", + "worker-act", + ], + ), + ( + "bootstrap-command-pack-release-root-fallback", + f"{node_only_dir}{os.pathsep}/usr/bin:/bin", + str(r_act / "scripts" / "loopx"), + [ + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "bootstrap-command-pack", + "--project", + str(project), + "--host-surface", + "antigravity-app", + "--goal-id", + "g-act", + "--agent-id", + "worker-act", + ], + ), + ] + + stop_event = json.dumps({"terminationReason": "USER_CANCELED"}) + agents_dir = tmp_path / "LaunchAgents" + wd_state_dir = tmp_path / "wd-state" + + for label, cli_path_env, expected_cli, cli_args in invocations: + cli_proc = subprocess.run( + [str(provider_python), "-c", cli_runner, *cli_args], + cwd=project, + env={ + "HOME": str(tmp_path), + "LOOPX_USAGE_PING": "0", + "LOOPX_RELEASE_ROOT": str(r_act), + "PYTHONPATH": str(r_act), + "PATH": cli_path_env, + "TMPDIR": str(tmp_path), + }, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + assert cli_proc.returncode == 0, (label, cli_proc.stderr, cli_proc.stdout) + packet = json.loads(cli_proc.stdout) + mutation = packet["host_loop_activation"]["host_mutation"] + stop_cmd = shlex.split(mutation["hooks_template"]["loopx"]["Stop"][0]["command"]) + watchdog_cmd = shlex.split(mutation["reboot_watchdog_command"]) + + for generated_cmd in (stop_cmd, watchdog_cmd): + if os.name == "nt": + assert generated_cmd[:4] == [str(provider_python), "-E", "-P", "-c"], ( + label, + generated_cmd[:6], + ) + else: + assert generated_cmd[:2] == ["/bin/sh", "-c"], ( + label, + generated_cmd[:6], + ) + assert generated_cmd[4] == str(provider_python), ( + label, + generated_cmd[:6], + ) + assert generated_cmd[generated_cmd.index("--cli-bin") + 1] == expected_cli + + stop_exec = subprocess.run( + stop_cmd, + input=stop_event, + cwd=poison_cwd, + env=isolated_provider_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert stop_exec.returncode == 0, (label, stop_exec.stderr) + assert json.loads(stop_exec.stdout) == {} + + dry_watchdog_cmd = [ + *(arg for arg in watchdog_cmd if arg != "--execute"), + "--dry-run", + "--state-dir", + str(wd_state_dir), + "--launch-agents-dir", + str(agents_dir), + ] + watchdog_exec = subprocess.run( + dry_watchdog_cmd, + cwd=poison_cwd, + env=isolated_provider_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert watchdog_exec.returncode == 0, (label, watchdog_exec.stderr) + wd_payload = json.loads(watchdog_exec.stdout) + assert wd_payload["ok"] is True + assert wd_payload["dry_run"] is True + plist_args = [str(item) for item in wd_payload["plist"]["ProgramArguments"]] + if os.name == "nt": + assert plist_args[:4] == [str(provider_python), "-E", "-P", "-c"], ( + label, + plist_args[:6], + ) + else: + assert plist_args[:2] == ["/bin/sh", "-c"], (label, plist_args[:6]) + assert plist_args[4] == str(provider_python), (label, plist_args[:6]) + tick_help = subprocess.run( + [*plist_args, "--help"], + cwd=poison_cwd, + env=isolated_provider_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert tick_help.returncode == 0, (label, tick_help.stderr) + + +def test_incomplete_release_snapshot_missing_host_runtime_fails_closed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + repo_root = Path(__file__).resolve().parents[1] + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / ( + "Scripts/python.exe" if os.name == "nt" else "bin/python" + ) + + r_bad = tmp_path / "releases" / "r-bad" + _make_release_snapshot(r_bad, repo_root) + cli_symlink = tmp_path / "bin" / "loopx" + cli_symlink.parent.mkdir() + cli_symlink.symlink_to(r_bad / "scripts" / "loopx") + + # Capture pre-corruption Stop hook and LaunchAgent argv while snapshot is intact. + state_dir = tmp_path / "state" + log_dir = tmp_path / "logs" + capture_script = ( + "import json; from loopx.hosts.agy import " + "build_antigravity_hooks_template, launchd_watchdog; " + f"hooks = build_antigravity_hooks_template(cli_bin={str(cli_symlink)!r}, " + "goal_id='g-inc', agent_id='a-inc', conversation_id='c-inc'); " + f"plist = launchd_watchdog.build_antigravity_launchd_plist(" + "goal_id='g-inc', agent_id='a-inc', conversation_id='c-inc', " + f"cli_bin={str(cli_symlink)!r}, state_dir={str(state_dir)!r}, log_dir={str(log_dir)!r}); " + "print(json.dumps({'hooks': hooks, 'plist': plist}))" + ) + captured = json.loads( + subprocess.check_output( + [str(provider_python), "-c", capture_script], + env={**os.environ, "PYTHONPATH": str(r_bad)}, + text=True, + encoding="utf-8", + timeout=30, + ) + ) + hook_cmd = shlex.split(captured["hooks"]["loopx"]["Stop"][0]["command"]) + program_args = [str(arg) for arg in captured["plist"]["ProgramArguments"]] + + # Remove host_runtime.py while retaining executable scripts/loopx, loopx/__init__.py, + # and loopx/hosts/agy/__init__.py. + (r_bad / "loopx" / "hosts" / "agy" / "host_runtime.py").unlink() + assert (r_bad / "scripts" / "loopx").is_file() + assert (r_bad / "loopx" / "__init__.py").is_file() + assert (r_bad / "loopx" / "hosts" / "agy" / "__init__.py").is_file() + + agents_dir = tmp_path / "LaunchAgents" + for cli_candidate in (str(cli_symlink), str(r_bad / "scripts" / "loopx")): + with pytest.raises(FileNotFoundError, match="host_runtime missing"): + build_antigravity_hooks_template( + cli_bin=cli_candidate, + goal_id="g-inc", + agent_id="a-inc", + conversation_id="c-inc", + ) + with pytest.raises(FileNotFoundError, match="host_runtime missing"): + build_antigravity_launchd_command( + cli_bin=cli_candidate, + goal_id="g-inc", + agent_id="a-inc", + conversation_id="c-inc", + ) + with pytest.raises(FileNotFoundError, match="host_runtime missing"): + launchd_watchdog.build_antigravity_launchd_plist( + goal_id="g-inc", + agent_id="a-inc", + conversation_id="c-inc", + cli_bin=cli_candidate, + state_dir=str(state_dir), + log_dir=str(log_dir), + ) + for execute_flag in (False, True): + install_args = _args( + tmp_path, + cli_bin=cli_candidate, + launch_agents_dir=str(agents_dir), + log_dir=str(log_dir), + execute=execute_flag, + no_load=True, + ) + with pytest.raises(FileNotFoundError, match="host_runtime missing"): + launchd_watchdog.install_launchd(install_args) + assert not agents_dir.exists() + + # Main CLI `install-launchd` preview AND `--execute --no-load` fail closed with no plist written. + for extra in ([], ["--execute", "--no-load"]): + monkeypatch.setattr( + sys, + "argv", + [ + "host_runtime", + "install-launchd", + "--cli-bin", + str(cli_symlink), + "--goal-id", + "g-inc", + "--agent-id", + "a-inc", + "--conversation-id", + "c-inc", + "--launch-agents-dir", + str(agents_dir), + "--state-dir", + str(state_dir), + "--log-dir", + str(log_dir), + *extra, + ], + ) + assert host_runtime.main() == 1 + err_payload = json.loads(capsys.readouterr().out) + assert err_payload == {"ok": False, "error": "FileNotFoundError"} + assert not agents_dir.exists() + + # Pre-existing runtime commands also fail closed without falling back to poisoned imports. + poison_cwd = tmp_path / "poison" + poison_pkg = poison_cwd / "loopx" + poison_pkg.mkdir(parents=True) + (poison_pkg / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + isolated_env = { + "HOME": str(tmp_path), + "PATH": "/usr/bin:/bin", + "TMPDIR": str(tmp_path), + } + broken_hook = subprocess.run( + hook_cmd, + input=json.dumps({"terminationReason": "USER_CANCELED"}), + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert broken_hook.returncode != 0 + assert "release root not found" in broken_hook.stderr + assert "poisoned" not in broken_hook.stderr + + broken_tick = subprocess.run( + program_args, + cwd=poison_cwd, + env=isolated_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert broken_tick.returncode != 0 + assert "release root not found" in broken_tick.stderr + + +def _make_runnable_release_snapshot( + release_dir: Path, + repo_root: Path, + *, + python_bin: Path, + include_python_selector: bool = True, +) -> None: + _make_release_snapshot(release_dir, repo_root) + real_launcher = release_dir / "scripts" / "loopx" + shutil.copy2(repo_root / "scripts" / "loopx", real_launcher) + real_launcher.chmod(0o755) + if include_python_selector: + selector = release_dir / "scripts" / "loopx-python.sh" + shutil.copy2(repo_root / "scripts" / "loopx-python.sh", selector) + selector.chmod(0o755) + (release_dir / ".loopx-python").write_text(f"{python_bin}\n", encoding="utf-8") + (release_dir / "release.json").write_text('{"schema_version":"v1"}\n', encoding="utf-8") + + +def _connected_agy_project(tmp_path: Path, name: str = "project") -> tuple[Path, Path, Path]: + project = tmp_path / name + registry_path = project / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True) + runtime_root = tmp_path / f"{name}-runtime" + runtime_root.mkdir() + (project / "ACTIVE_GOAL_STATE.md").write_text("# Goal\n\nUpgrade test.\n", encoding="utf-8") + registry_path.write_text( + json.dumps( + { + "common_runtime_root": str(runtime_root), + "goals": [ + { + "id": "g-upg", + "domain": "test", + "status": "active", + "repo": str(project), + "state_file": "ACTIVE_GOAL_STATE.md", + "coordination": { + "registered_agents": ["worker-upg"], + "agent_model": "peer_v1", + }, + "adapter": { + "kind": "generic_project_goal_v0", + "status": "connected", + }, + } + ], + } + ), + encoding="utf-8", + ) + return project, registry_path, runtime_root + + +def test_real_cli_shim_activation_survives_old_snapshot_deletion_with_or_without_path( + tmp_path: Path, +) -> None: + if os.name == "nt": + pytest.skip("requires POSIX scripts/loopx launcher") + repo_root = Path(__file__).resolve().parents[1] + node_bin = shutil.which("node") + assert node_bin is not None, "node is required for agent-onboard CLI probe" + node_dir = tmp_path / "node-only-bin" + node_dir.mkdir() + (node_dir / "node").symlink_to(node_bin) + + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / "bin" / "python" + + v1 = tmp_path / "releases" / "v1" + v2 = tmp_path / "releases" / "v2" + _make_runnable_release_snapshot(v1, repo_root, python_bin=provider_python) + _make_runnable_release_snapshot(v2, repo_root, python_bin=provider_python) + + custom_bin = tmp_path / "custom-bin" + custom_bin.mkdir() + cli_symlink = custom_bin / "loopx" + cli_symlink.symlink_to(v1 / "scripts" / "loopx") + + home_dir = tmp_path / "fake-home" + local_bin = home_dir / ".local" / "bin" + local_bin.mkdir(parents=True) + local_shim = local_bin / "loopx" + local_shim.symlink_to(v1 / "scripts" / "loopx") + + project, registry_path, runtime_root = _connected_agy_project(tmp_path) + poison_cwd = tmp_path / "poison" + (poison_cwd / "loopx").mkdir(parents=True) + (poison_cwd / "loopx" / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + + saved_artifacts: list[tuple[str, list[str], list[str], Path]] = [] + agents_dir = tmp_path / "LaunchAgents" + state_dir = tmp_path / "wd-state" + log_dir = tmp_path / "wd-logs" + + cases = [ + ("bootstrap-with-path", f"{custom_bin}:{node_dir}:/usr/bin:/bin", str(cli_symlink), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "bootstrap-command-pack", "--project", str(project), + "--host-surface", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(cli_symlink)), + ("bootstrap-without-path", f"{node_dir}:/usr/bin:/bin", str(cli_symlink), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "bootstrap-command-pack", "--project", str(project), + "--host-surface", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(cli_symlink)), + ("onboard-without-path", f"{node_dir}:/usr/bin:/bin", str(cli_symlink), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "agent-onboard", "--project", str(project), + "--agent-type", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(cli_symlink)), + ("direct-script-prefers-home-local-shim", f"{node_dir}:/usr/bin:/bin", str(v1 / "scripts" / "loopx"), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "bootstrap-command-pack", "--project", str(project), + "--host-surface", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(local_shim)), + ] + + for idx, (label, path_env, invoked_bin, cli_args, expected_cli) in enumerate(cases): + cli_proc = subprocess.run( + [invoked_bin, *cli_args], + cwd=project, + env={ + "HOME": str(home_dir), + "LOOPX_USAGE_PING": "0", + "PATH": path_env, + "TMPDIR": str(tmp_path), + }, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + assert cli_proc.returncode == 0, (label, cli_proc.stderr, cli_proc.stdout) + packet = json.loads(cli_proc.stdout) + mutation = packet["host_loop_activation"]["host_mutation"] + stop_cmd = shlex.split(mutation["hooks_template"]["loopx"]["Stop"][0]["command"]) + watchdog_cmd = shlex.split(mutation["reboot_watchdog_command"]) + assert stop_cmd[stop_cmd.index("--cli-bin") + 1] == expected_cli + assert watchdog_cmd[watchdog_cmd.index("--cli-bin") + 1] == expected_cli + + case_label = f"com.loopx.test.shim.{idx}" + install_cmd = [ + *watchdog_cmd, + "--no-load", + "--label", + case_label, + "--launch-agents-dir", + str(agents_dir), + "--state-dir", + str(state_dir), + "--log-dir", + str(log_dir), + ] + installed = subprocess.run( + install_cmd, + cwd=poison_cwd, + env={"HOME": str(home_dir), "LOOPX_USAGE_PING": "0", "PATH": "/usr/bin:/bin", "TMPDIR": str(tmp_path)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert installed.returncode == 0, (label, installed.stderr, installed.stdout) + plist_path = Path(str(json.loads(installed.stdout)["plist_path"])) + assert plist_path.is_file() + dry_cmd = [ + *(arg for arg in watchdog_cmd if arg != "--execute"), + "--dry-run", + "--state-dir", + str(state_dir), + "--launch-agents-dir", + str(agents_dir), + ] + saved_artifacts.append((label, stop_cmd, dry_cmd, plist_path)) + + # Upgrade both shims to v2 and delete v1 completely. + for shim in (cli_symlink, local_shim): + shim.unlink() + shim.symlink_to(v2 / "scripts" / "loopx") + shutil.rmtree(v1) + assert not v1.exists() + + stop_event = json.dumps({"terminationReason": "USER_CANCELED"}) + clean_runtime_env = { + "HOME": str(home_dir), + "LOOPX_USAGE_PING": "0", + "PATH": "/usr/bin:/bin", + "TMPDIR": str(tmp_path), + } + for label, stop_cmd, dry_cmd, plist_path in saved_artifacts: + stop_exec = subprocess.run( + stop_cmd, + input=stop_event, + cwd=poison_cwd, + env=clean_runtime_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert stop_exec.returncode == 0, (label, stop_exec.stderr) + assert json.loads(stop_exec.stdout) == {} + + dry_exec = subprocess.run( + dry_cmd, + cwd=poison_cwd, + env=clean_runtime_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert dry_exec.returncode == 0, (label, dry_exec.stderr) + assert json.loads(dry_exec.stdout)["ok"] is True + + parsed_plist = plistlib.loads(plist_path.read_bytes()) + plist_env = {str(k): str(v) for k, v in parsed_plist["EnvironmentVariables"].items()} + plist_env["HOME"] = str(home_dir) + plist_env["TMPDIR"] = str(tmp_path) + tick_help = subprocess.run( + [*[str(x) for x in parsed_plist["ProgramArguments"]], "--help"], + cwd="/", + env=plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert tick_help.returncode == 0, (label, tick_help.stderr) + assert "--cli-bin" in tick_help.stdout + + +def test_saved_launchd_and_stop_hook_follow_active_interpreter_after_old_python_retired( + tmp_path: Path, +) -> None: + if os.name == "nt": + pytest.skip("requires POSIX shell trampoline") + repo_root = Path(__file__).resolve().parents[1] + + venv1 = tmp_path / "venv1" + venv2 = tmp_path / "venv2" + venv.EnvBuilder(symlinks=True, with_pip=False).create(venv1) + venv.EnvBuilder(symlinks=True, with_pip=False).create(venv2) + py1 = venv1 / "bin" / "python" + real_py2 = venv2 / "bin" / "python" + + py2_log = tmp_path / "py2-invocations.log" + py2_wrapper = tmp_path / "venv2-py-probe" + py2_wrapper.write_text( + f"#!/bin/sh\nprintf 'ran:%s\\n' \"$0\" >> {shlex.quote(str(py2_log))}\n" + f"exec {shlex.quote(str(real_py2))} \"$@\"\n", + encoding="utf-8", + ) + py2_wrapper.chmod(0o755) + + v1 = tmp_path / "releases" / "v1" + v2 = tmp_path / "releases" / "v2" + _make_runnable_release_snapshot(v1, repo_root, python_bin=py1) + _make_runnable_release_snapshot(v2, repo_root, python_bin=py2_wrapper) + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + cli_symlink = bin_dir / "loopx" + cli_symlink.symlink_to(v1 / "scripts" / "loopx") + + project, registry_path, runtime_root = _connected_agy_project(tmp_path) + agents_dir = tmp_path / "LaunchAgents" + state_dir = tmp_path / "wd-state" + log_dir = tmp_path / "wd-logs" + + # Generate Stop hook and write real LaunchAgent plist while running on v1 + venv1. + cli_pack = subprocess.run( + [ + str(cli_symlink), + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "bootstrap-command-pack", + "--project", + str(project), + "--host-surface", + "antigravity-app", + "--goal-id", + "g-upg", + "--agent-id", + "worker-upg", + ], + cwd=project, + env={"HOME": str(tmp_path), "LOOPX_USAGE_PING": "0", "PATH": "/usr/bin:/bin", "TMPDIR": str(tmp_path)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=True, + ) + mutation = json.loads(cli_pack.stdout)["host_loop_activation"]["host_mutation"] + stop_cmd = shlex.split(mutation["hooks_template"]["loopx"]["Stop"][0]["command"]) + watchdog_cmd = shlex.split(mutation["reboot_watchdog_command"]) + assert stop_cmd[4] == str(py1) + + installed = subprocess.run( + [ + *watchdog_cmd, + "--no-load", + "--label", + "com.loopx.test.retired-py", + "--launch-agents-dir", + str(agents_dir), + "--state-dir", + str(state_dir), + "--log-dir", + str(log_dir), + ], + cwd=tmp_path, + env={"HOME": str(tmp_path), "LOOPX_USAGE_PING": "0", "PATH": "/usr/bin:/bin", "TMPDIR": str(tmp_path)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=True, + ) + plist_path = Path(str(json.loads(installed.stdout)["plist_path"])) + parsed_plist = plistlib.loads(plist_path.read_bytes()) + assert parsed_plist["ProgramArguments"][4] == str(py1) + + # Upgrade symlink to v2 (which uses py2_wrapper), and retire BOTH v1 and venv1 completely. + cli_symlink.unlink() + cli_symlink.symlink_to(v2 / "scripts" / "loopx") + shutil.rmtree(v1) + shutil.rmtree(venv1) + assert not v1.exists() + assert not py1.exists() + + poison_cwd = tmp_path / "poison" + (poison_cwd / "loopx").mkdir(parents=True) + (poison_cwd / "loopx" / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + + plist_env = {str(k): str(v) for k, v in parsed_plist["EnvironmentVariables"].items()} + plist_env["HOME"] = str(tmp_path) + plist_env["TMPDIR"] = str(tmp_path) + tick_help = subprocess.run( + [*[str(x) for x in parsed_plist["ProgramArguments"]], "--help"], + cwd="/", + env=plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert tick_help.returncode == 0, tick_help.stderr + assert "--cli-bin" in tick_help.stdout + + stop_exec = subprocess.run( + stop_cmd, + input=json.dumps({"terminationReason": "USER_CANCELED"}), + cwd=poison_cwd, + env={"HOME": str(tmp_path), "LOOPX_USAGE_PING": "0", "PATH": "/usr/bin:/bin", "TMPDIR": str(tmp_path)}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert stop_exec.returncode == 0, stop_exec.stderr + assert json.loads(stop_exec.stdout) == {} + + invocations_logged = [ + line for line in py2_log.read_text(encoding="utf-8").splitlines() if line.strip() + ] + assert len(invocations_logged) >= 2, invocations_logged + assert all(str(py2_wrapper) in line for line in invocations_logged) + + +def test_invoked_release_shim_overrides_different_install_on_path( + tmp_path: Path, +) -> None: + if os.name == "nt": + pytest.skip("requires POSIX scripts/loopx launcher") + repo_root = Path(__file__).resolve().parents[1] + node_bin = shutil.which("node") + assert node_bin is not None, "node is required for agent-onboard CLI probe" + node_dir = tmp_path / "node-only-bin" + node_dir.mkdir() + (node_dir / "node").symlink_to(node_bin) + + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / "bin" / "python" + + install_a = tmp_path / "install-a" / "release" + install_b = tmp_path / "install-b" / "release" + _make_runnable_release_snapshot(install_a, repo_root, python_bin=provider_python) + _make_runnable_release_snapshot(install_b, repo_root, python_bin=provider_python) + + a_bin = tmp_path / "install-a" / "bin" + b_bin = tmp_path / "install-b" / "bin" + a_bin.mkdir(parents=True) + b_bin.mkdir(parents=True) + a_shim = a_bin / "loopx" + b_shim = b_bin / "loopx" + a_shim.symlink_to(install_a / "scripts" / "loopx") + b_shim.symlink_to(install_b / "scripts" / "loopx") + + project, registry_path, runtime_root = _connected_agy_project(tmp_path) + poison_cwd = tmp_path / "poison" + (poison_cwd / "loopx").mkdir(parents=True) + (poison_cwd / "loopx" / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + + # B_bin precedes everything on PATH while A is invoked directly. + competing_path = f"{b_bin}:{node_dir}:/usr/bin:/bin" + run_env = { + "HOME": str(tmp_path), + "LOOPX_USAGE_PING": "0", + "PATH": competing_path, + "TMPDIR": str(tmp_path), + } + + agents_dir = tmp_path / "LaunchAgents" + state_dir = tmp_path / "wd-state" + log_dir = tmp_path / "wd-logs" + + # Explicit --cli-bin must still take precedence over invoked A while B exists. + explicit_b = subprocess.run( + [ + str(a_shim), + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "bootstrap-command-pack", + "--project", + str(project), + "--host-surface", + "antigravity-app", + "--goal-id", + "g-upg", + "--agent-id", + "worker-upg", + "--cli-bin", + str(b_shim), + ], + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=True, + ) + b_mut = json.loads(explicit_b.stdout)["host_loop_activation"]["host_mutation"] + b_stop = shlex.split(b_mut["hooks_template"]["loopx"]["Stop"][0]["command"]) + b_wd = shlex.split(b_mut["reboot_watchdog_command"]) + assert b_stop[b_stop.index("--cli-bin") + 1] == str(b_shim) + assert b_wd[b_wd.index("--cli-bin") + 1] == str(b_shim) + + a_invocations = [ + ("a-shim-bootstrap", str(a_shim), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "bootstrap-command-pack", "--project", str(project), + "--host-surface", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(a_shim)), + ("a-shim-onboard", str(a_shim), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "agent-onboard", "--project", str(project), + "--agent-type", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(a_shim)), + ("a-direct-bootstrap", str(install_a / "scripts" / "loopx"), [ + "--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "bootstrap-command-pack", "--project", str(project), + "--host-surface", "antigravity-app", "--goal-id", "g-upg", "--agent-id", "worker-upg", + ], str(install_a / "scripts" / "loopx")), + ] + + saved_a: list[tuple[str, list[str], list[str], Path]] = [] + for idx, (label, invoked_a, cli_args, expected_cli) in enumerate(a_invocations): + proc = subprocess.run( + [invoked_a, *cli_args], + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + assert proc.returncode == 0, (label, proc.stderr, proc.stdout) + mut = json.loads(proc.stdout)["host_loop_activation"]["host_mutation"] + stop_cmd = shlex.split(mut["hooks_template"]["loopx"]["Stop"][0]["command"]) + wd_cmd = shlex.split(mut["reboot_watchdog_command"]) + assert stop_cmd[stop_cmd.index("--cli-bin") + 1] == expected_cli + assert wd_cmd[wd_cmd.index("--cli-bin") + 1] == expected_cli + assert str(install_b) not in " ".join(stop_cmd) + assert str(b_shim) not in " ".join(stop_cmd) + assert str(install_b) not in " ".join(wd_cmd) + assert str(b_shim) not in " ".join(wd_cmd) + + installed = subprocess.run( + [ + *wd_cmd, + "--no-load", + "--label", + f"com.loopx.test.installa.{idx}", + "--launch-agents-dir", + str(agents_dir), + "--state-dir", + str(state_dir), + "--log-dir", + str(log_dir), + ], + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert installed.returncode == 0, (label, installed.stderr, installed.stdout) + plist_path = Path(str(json.loads(installed.stdout)["plist_path"])) + assert plist_path.is_file() + dry_cmd = [ + *(arg for arg in wd_cmd if arg != "--execute"), + "--dry-run", + "--state-dir", + str(state_dir), + "--launch-agents-dir", + str(agents_dir), + ] + saved_a.append((label, stop_cmd, dry_cmd, plist_path)) + + # Delete install B completely (both release tree and B_bin shim). + shutil.rmtree(install_b.parent) + assert not b_shim.exists() + assert not install_b.exists() + + a_ver = subprocess.run( + [str(a_shim), "--version"], + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert a_ver.returncode == 0, a_ver.stderr + + stop_event = json.dumps({"terminationReason": "USER_CANCELED"}) + for label, stop_cmd, dry_cmd, plist_path in saved_a: + stop_exec = subprocess.run( + stop_cmd, + input=stop_event, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert stop_exec.returncode == 0, (label, stop_exec.stderr) + assert json.loads(stop_exec.stdout) == {} + + dry_exec = subprocess.run( + dry_cmd, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert dry_exec.returncode == 0, (label, dry_exec.stderr) + assert json.loads(dry_exec.stdout)["ok"] is True + + parsed_plist = plistlib.loads(plist_path.read_bytes()) + plist_env = {str(k): str(v) for k, v in parsed_plist["EnvironmentVariables"].items()} + plist_env["HOME"] = str(tmp_path) + plist_env["TMPDIR"] = str(tmp_path) + tick_help = subprocess.run( + [*[str(x) for x in parsed_plist["ProgramArguments"]], "--help"], + cwd="/", + env=plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert tick_help.returncode == 0, (label, tick_help.stderr) + + +def test_direct_release_invocation_picks_later_matching_shim_on_path( + tmp_path: Path, +) -> None: + if os.name == "nt": + pytest.skip("requires POSIX scripts/loopx launcher") + repo_root = Path(__file__).resolve().parents[1] + node_bin = shutil.which("node") + assert node_bin is not None, "node is required for agent-onboard CLI probe" + node_dir = tmp_path / "node-only-bin" + node_dir.mkdir() + (node_dir / "node").symlink_to(node_bin) + + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / "bin" / "python" + + install_a_v1 = tmp_path / "install-a" / "releases" / "v1" + install_a_v2 = tmp_path / "install-a" / "releases" / "v2" + install_b = tmp_path / "install-b" / "releases" / "v1" + _make_runnable_release_snapshot(install_a_v1, repo_root, python_bin=provider_python) + _make_runnable_release_snapshot(install_a_v2, repo_root, python_bin=provider_python) + _make_runnable_release_snapshot(install_b, repo_root, python_bin=provider_python) + + a_bin = tmp_path / "install-a" / "bin" + b_bin = tmp_path / "install-b" / "bin" + a_bin.mkdir(parents=True) + b_bin.mkdir(parents=True) + a_shim = a_bin / "loopx" + b_shim = b_bin / "loopx" + a_shim.symlink_to(install_a_v1 / "scripts" / "loopx") + b_shim.symlink_to(install_b / "scripts" / "loopx") + + project, registry_path, runtime_root = _connected_agy_project(tmp_path) + poison_cwd = tmp_path / "poison" + (poison_cwd / "loopx").mkdir(parents=True) + (poison_cwd / "loopx" / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + + # Install B's shim is FIRST on PATH; Install A's custom shim is SECOND on PATH + # (and ~/.local/bin/loopx does not exist under HOME=tmp_path). + # Invoking install_a_v1/scripts/loopx directly must find a_shim and survive v1 retirement. + layered_path = f"{b_bin}:{a_bin}:{node_dir}:/usr/bin:/bin" + run_env = { + "HOME": str(tmp_path), + "LOOPX_USAGE_PING": "0", + "PATH": layered_path, + "TMPDIR": str(tmp_path), + } + + agents_dir = tmp_path / "LaunchAgents" + state_dir = tmp_path / "wd-state" + log_dir = tmp_path / "wd-logs" + + direct_invocations = [ + ( + "direct-v1-bootstrap", + [ + str(install_a_v1 / "scripts" / "loopx"), + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "bootstrap-command-pack", + "--project", + str(project), + "--host-surface", + "antigravity-app", + "--goal-id", + "g-upg", + "--agent-id", + "worker-upg", + ], + ), + ( + "direct-v1-onboard", + [ + str(install_a_v1 / "scripts" / "loopx"), + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "agent-onboard", + "--project", + str(project), + "--agent-type", + "antigravity-app", + "--goal-id", + "g-upg", + "--agent-id", + "worker-upg", + ], + ), + ] + + saved: list[tuple[str, list[str], list[str], Path]] = [] + for idx, (label, cmd_argv) in enumerate(direct_invocations): + proc = subprocess.run( + cmd_argv, + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + assert proc.returncode == 0, (label, proc.stderr, proc.stdout) + mut = json.loads(proc.stdout)["host_loop_activation"]["host_mutation"] + stop_cmd = shlex.split(mut["hooks_template"]["loopx"]["Stop"][0]["command"]) + wd_cmd = shlex.split(mut["reboot_watchdog_command"]) + assert stop_cmd[stop_cmd.index("--cli-bin") + 1] == str(a_shim) + assert wd_cmd[wd_cmd.index("--cli-bin") + 1] == str(a_shim) + + installed = subprocess.run( + [ + *wd_cmd, + "--no-load", + "--label", + f"com.loopx.test.layered.{idx}", + "--launch-agents-dir", + str(agents_dir), + "--state-dir", + str(state_dir), + "--log-dir", + str(log_dir), + ], + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert installed.returncode == 0, (label, installed.stderr, installed.stdout) + plist_path = Path(str(json.loads(installed.stdout)["plist_path"])) + assert plist_path.is_file() + dry_cmd = [ + *(arg for arg in wd_cmd if arg != "--execute"), + "--dry-run", + "--state-dir", + str(state_dir), + "--launch-agents-dir", + str(agents_dir), + ] + saved.append((label, stop_cmd, dry_cmd, plist_path)) + + # Upgrade install-a's custom shim from v1 -> v2, delete v1, and delete install-b. + a_shim.unlink() + a_shim.symlink_to(install_a_v2 / "scripts" / "loopx") + shutil.rmtree(install_a_v1) + shutil.rmtree(tmp_path / "install-b") + assert not install_a_v1.exists() + + a_ver = subprocess.run( + [str(a_shim), "--version"], + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert a_ver.returncode == 0, a_ver.stderr + + stop_event = json.dumps({"terminationReason": "USER_CANCELED"}) + for label, stop_cmd, dry_cmd, plist_path in saved: + stop_exec = subprocess.run( + stop_cmd, + input=stop_event, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert stop_exec.returncode == 0, (label, stop_exec.stderr) + assert json.loads(stop_exec.stdout) == {} + + dry_exec = subprocess.run( + dry_cmd, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert dry_exec.returncode == 0, (label, dry_exec.stderr) + assert json.loads(dry_exec.stdout)["ok"] is True + + parsed_plist = plistlib.loads(plist_path.read_bytes()) + plist_env = {str(k): str(v) for k, v in parsed_plist["EnvironmentVariables"].items()} + plist_env["HOME"] = str(tmp_path) + plist_env["TMPDIR"] = str(tmp_path) + tick_help = subprocess.run( + [*[str(x) for x in parsed_plist["ProgramArguments"]], "--help"], + cwd="/", + env=plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert tick_help.returncode == 0, (label, tick_help.stderr) + assert "--cli-bin" in tick_help.stdout + + +def _make_pre_consolidation_release_snapshot( + release_dir: Path, + repo_root: Path, + *, + python_bin: Path, +) -> None: + """Build a runnable pre-#9510 snapshot using ``loopx/agy_goal_mode`` (no ``hosts/agy``).""" + _make_runnable_release_snapshot(release_dir, repo_root, python_bin=python_bin) + pkg_dir = release_dir / "loopx" + source_pkg = repo_root / "loopx" + + # Replace symlinked files that reference `hosts.agy` inside `prev_release` only. + for rel, old, new in ( + ("doctor.py", "from .hosts.agy import", "from .agy_goal_mode import"), + ("host_loop_activation.py", "from .hosts.agy import", "from .agy_goal_mode import"), + ("slash_command_install.py", "from .hosts.agy import", "from .agy_goal_mode import"), + ("workflow_skill_install.py", "from .hosts.agy import", "from .agy_goal_mode import"), + ): + target = pkg_dir / rel + if target.is_symlink(): + target.unlink() + target.write_text( + (source_pkg / rel).read_text(encoding="utf-8").replace(old, new), + encoding="utf-8", + ) + facade_copy = pkg_dir / "hosts" / "skill_facade.py" + facade_copy.write_text( + facade_copy.read_text(encoding="utf-8").replace( + "from .agy import", "from ..agy_goal_mode import" + ), + encoding="utf-8", + ) + caps_copy = pkg_dir / "hosts" / "capabilities.py" + caps_copy.write_text( + caps_copy.read_text(encoding="utf-8").replace( + '"agy": "loopx.hosts.agy"', '"agy": "loopx.agy_goal_mode"' + ), + encoding="utf-8", + ) + + # Convert canonical `hosts/agy/*.py` back to pre-#9510 `agy_goal_mode/*.py`, then delete `hosts/agy`. + legacy_dir = pkg_dir / "agy_goal_mode" + legacy_dir.unlink() + legacy_dir.mkdir(parents=True) + for name in ("__init__.py", "host_runtime.py", "launchd_watchdog.py"): + src = (source_pkg / "hosts" / "agy" / name).read_text(encoding="utf-8") + converted = ( + src.replace("from ...command_invocation", "from ..command_invocation") + .replace("from ...entrypoint", "from ..entrypoint") + .replace("from ...file_lock", "from ..file_lock") + .replace("from ...chat_agent", "from ..chat_agent") + .replace( + "from ...capabilities.native_chat.antigravity_adapter", + "from ..capabilities.native_chat.antigravity_adapter", + ) + .replace("from ..capabilities import (", "from ..hosts.capabilities import (") + .replace("loopx.hosts.agy.host_runtime", "loopx.agy_goal_mode.host_runtime") + .replace("loopx.hosts.agy", "loopx.agy_goal_mode") + .replace("loopx/hosts/agy", "loopx/agy_goal_mode") + .replace('"hosts" / "agy"', '"agy_goal_mode"') + .replace('"hosts"/"agy"', '"agy_goal_mode"') + ) + (legacy_dir / name).write_text(converted, encoding="utf-8") + shutil.rmtree(pkg_dir / "hosts" / "agy") + + +def test_archive_rollback_to_pre_consolidation_release_preserves_saved_commands( + tmp_path: Path, +) -> None: + if os.name == "nt": + pytest.skip("requires POSIX scripts/loopx launcher") + repo_root = Path(__file__).resolve().parents[1] + node_bin = shutil.which("node") + assert node_bin is not None, "node is required for agent-onboard CLI probe" + node_dir = tmp_path / "node-only-bin" + node_dir.mkdir() + (node_dir / "node").symlink_to(node_bin) + + provider_venv = tmp_path / "provider-venv" + venv.EnvBuilder(symlinks=True, with_pip=False).create(provider_venv) + provider_python = provider_venv / "bin" / "python" + + home_dir = tmp_path / "fake-home" + releases_dir = home_dir / ".local" / "share" / "loopx" / "releases" + prev_release = releases_dir / "20261127T044107Z" + curr_release = releases_dir / "20261127T054107Z" + _make_pre_consolidation_release_snapshot( + prev_release, repo_root, python_bin=provider_python + ) + _make_runnable_release_snapshot( + curr_release, repo_root, python_bin=provider_python + ) + assert not (prev_release / "loopx" / "hosts" / "agy").exists() + assert (prev_release / "loopx" / "agy_goal_mode" / "host_runtime.py").is_file() + + local_bin = home_dir / ".local" / "bin" + local_bin.mkdir(parents=True) + cli_shim = local_bin / "loopx" + cli_shim.symlink_to(curr_release / "scripts" / "loopx") + + project, registry_path, runtime_root = _connected_agy_project(tmp_path) + poison_cwd = tmp_path / "poison" + (poison_cwd / "loopx").mkdir(parents=True) + (poison_cwd / "loopx" / "__init__.py").write_text( + 'raise RuntimeError("poisoned cwd")\n', encoding="utf-8" + ) + + run_env = { + "HOME": str(home_dir), + "LOOPX_USAGE_PING": "0", + "PATH": f"{local_bin}:{node_dir}:/usr/bin:/bin", + "TMPDIR": str(tmp_path), + } + + agents_dir = tmp_path / "LaunchAgents" + state_dir = tmp_path / "wd-state" + log_dir = tmp_path / "wd-logs" + + activations = [ + ( + "curr-bootstrap", + [ + str(cli_shim), + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "bootstrap-command-pack", + "--project", + str(project), + "--host-surface", + "antigravity-app", + "--goal-id", + "g-upg", + "--agent-id", + "worker-upg", + ], + ), + ( + "curr-onboard", + [ + str(cli_shim), + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "agent-onboard", + "--project", + str(project), + "--agent-type", + "antigravity-app", + "--goal-id", + "g-upg", + "--agent-id", + "worker-upg", + ], + ), + ] + + saved: list[tuple[str, list[str], list[str], Path]] = [] + for idx, (label, argv) in enumerate(activations): + proc = subprocess.run( + argv, + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + assert proc.returncode == 0, (label, proc.stderr, proc.stdout) + mut = json.loads(proc.stdout)["host_loop_activation"]["host_mutation"] + stop_cmd = shlex.split(mut["hooks_template"]["loopx"]["Stop"][0]["command"]) + wd_cmd = shlex.split(mut["reboot_watchdog_command"]) + assert stop_cmd[stop_cmd.index("--cli-bin") + 1] == str(cli_shim) + assert wd_cmd[wd_cmd.index("--cli-bin") + 1] == str(cli_shim) + + installed = subprocess.run( + [ + *wd_cmd, + "--no-load", + "--label", + f"com.loopx.test.rollback.{idx}", + "--launch-agents-dir", + str(agents_dir), + "--state-dir", + str(state_dir), + "--log-dir", + str(log_dir), + ], + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert installed.returncode == 0, (label, installed.stderr, installed.stdout) + plist_path = Path(str(json.loads(installed.stdout)["plist_path"])) + assert plist_path.is_file() + dry_cmd = [ + *(arg for arg in wd_cmd if arg != "--execute"), + "--dry-run", + "--state-dir", + str(state_dir), + "--launch-agents-dir", + str(agents_dir), + ] + saved.append((label, stop_cmd, dry_cmd, plist_path)) + + # Perform native `loopx update --rollback previous` back to pre-#9510 archive layout. + rollback = subprocess.run( + [str(cli_shim), "--format", "json", "update", "--rollback", "previous"], + cwd=project, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + check=False, + ) + assert rollback.returncode == 0, (rollback.stderr, rollback.stdout) + rb_payload = json.loads(rollback.stdout) + assert rb_payload["ok"] is True, rb_payload + assert rb_payload["mode"] == "rollback", rb_payload + assert rb_payload["plan"]["selected_release_id"] == prev_release.name, rb_payload + assert cli_shim.resolve() == (prev_release / "scripts" / "loopx").resolve() + + # All three saved entrypoints generated by curr_release must work after rollback to prev_release. + stop_event = json.dumps({"terminationReason": "USER_CANCELED"}) + for label, stop_cmd, dry_cmd, plist_path in saved: + stop_exec = subprocess.run( + stop_cmd, + input=stop_event, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert stop_exec.returncode == 0, (label, stop_exec.stderr) + assert json.loads(stop_exec.stdout) == {} + + dry_exec = subprocess.run( + dry_cmd, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert dry_exec.returncode == 0, (label, dry_exec.stderr) + assert json.loads(dry_exec.stdout)["ok"] is True + + parsed_plist = plistlib.loads(plist_path.read_bytes()) + plist_env = {str(k): str(v) for k, v in parsed_plist["EnvironmentVariables"].items()} + plist_env["HOME"] = str(home_dir) + plist_env["TMPDIR"] = str(tmp_path) + tick_help = subprocess.run( + [*[str(x) for x in parsed_plist["ProgramArguments"]], "--help"], + cwd="/", + env=plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert tick_help.returncode == 0, (label, tick_help.stderr) + assert "loopx.agy_goal_mode.host_runtime" in tick_help.stdout + + # Incomplete pre-#9510 snapshot missing host_runtime.py must still fail closed. + (prev_release / "loopx" / "agy_goal_mode" / "host_runtime.py").unlink() + failed_stop = subprocess.run( + saved[0][1], + input=stop_event, + cwd=poison_cwd, + env=run_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert failed_stop.returncode != 0 + assert "release root not found" in failed_stop.stderr + + failed_plist_payload = plistlib.loads(saved[0][3].read_bytes()) + failed_plist_env = { + str(k): str(v) for k, v in failed_plist_payload["EnvironmentVariables"].items() + } + failed_plist_env["HOME"] = str(home_dir) + failed_plist_env["TMPDIR"] = str(tmp_path) + failed_tick = subprocess.run( + [*[str(x) for x in failed_plist_payload["ProgramArguments"]], "--help"], + cwd="/", + env=failed_plist_env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert failed_tick.returncode != 0 + assert "release root not found" in failed_tick.stderr