Skip to content

Commit a7fd827

Browse files
committed
Merge current main and isolate LaunchAgent restart assertions
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
2 parents 853f32b + ff6ebe7 commit a7fd827

6 files changed

Lines changed: 171 additions & 11 deletions

File tree

‎loopx/cli_commands/update_source.py‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,112 @@
77

88
from __future__ import annotations
99

10+
from collections.abc import Callable
11+
import json
12+
import re
13+
import subprocess
1014
from typing import Any
15+
from urllib.parse import urlsplit
1116

1217
from .update_artifact import resolve_artifact, target_direction
1318
from ..activation_qualification import runtime_activation_qualification
19+
from ..python_install_owner import SPLIT_UPDATE_GUIDANCE
20+
21+
22+
def pin_pip_update_target(
23+
command: list[str], *, installed_version: object, timeout_seconds: int,
24+
) -> str:
25+
"""Resolve the real pip target and return an immutable install requirement."""
26+
result = subprocess.run(
27+
[*command[:-1], "--dry-run", "--quiet", "--disable-pip-version-check", "--report", "-", command[-1]],
28+
text=True, encoding="utf-8", errors="replace", capture_output=True, timeout=timeout_seconds,
29+
)
30+
if result.returncode:
31+
raise ValueError("pip could not resolve the in-place update target. Inspect the pip installation source.")
32+
33+
unverified = "pip could not verify the exact LoopX package for an in-place update."
34+
try:
35+
report = json.loads(result.stdout)
36+
if report["version"] not in {"0", "1"} or not isinstance(report["install"], list):
37+
raise ValueError
38+
packages = {
39+
re.sub(r"[-_.]+", "-", item["metadata"]["name"].lower()): item
40+
for item in report["install"]
41+
}
42+
if len(packages) != len(report["install"]):
43+
raise ValueError
44+
except (AttributeError, KeyError, TypeError, ValueError):
45+
raise ValueError(unverified) from None
46+
47+
target = packages.get("loopx")
48+
requirements = target["metadata"].get("requires_dist", []) if target is not None else []
49+
if not isinstance(requirements, list) or not all(isinstance(item, str) for item in requirements):
50+
raise ValueError(unverified)
51+
if "loopx-core" in packages or any(
52+
re.match(r"^\s*loopx[-_.]+core(?=$|[\s\[(;@<>=!~])", item, re.IGNORECASE)
53+
for item in requirements
54+
):
55+
raise ValueError(f"The selected LoopX package changes file ownership to the split layout. {SPLIT_UPDATE_GUIDANCE}")
56+
57+
if target is None:
58+
# Keep the existing distribution selected while preserving pip's normal
59+
# dependency handling and the runtime's post-install validation.
60+
if not isinstance(installed_version, str) or not re.fullmatch(r"[0-9A-Za-z.!+_-]+", installed_version):
61+
raise ValueError(unverified)
62+
return f"loopx=={installed_version}"
63+
try:
64+
download = target["download_info"]
65+
url = download["url"].partition("#")[0]
66+
archive = download["archive_info"]
67+
legacy = re.fullmatch(r"sha256=([0-9a-fA-F]{64})", archive.get("hash", ""))
68+
digest = archive.get("hashes", {}).get("sha256") or (legacy[1] if legacy else "")
69+
if urlsplit(url).scheme not in {"https", "http", "file"} or any(character.isspace() for character in url):
70+
raise ValueError
71+
if not re.fullmatch(r"[0-9a-fA-F]{64}", digest):
72+
raise ValueError
73+
except (AttributeError, KeyError, TypeError, ValueError):
74+
raise ValueError(unverified) from None
75+
return f"loopx @ {url}#sha256={digest}"
76+
77+
78+
def install_python_package(
79+
payload: dict[str, Any], command: list[str], *, installed_version: object,
80+
timeout_seconds: int, progress: Callable[[str], None],
81+
) -> subprocess.CompletedProcess[str] | dict[str, Any]:
82+
"""Apply the owning package manager command after validating a pip target."""
83+
install_command = command
84+
artifact_url = ""
85+
if payload["install_lifecycle"]["execution_driver"] == "python_pip":
86+
progress("Checking the Python package selected by pip")
87+
try:
88+
requirement = pin_pip_update_target(command, installed_version=installed_version, timeout_seconds=timeout_seconds)
89+
except ValueError as exc:
90+
reason = str(exc)
91+
return {
92+
**payload, "ok": False, "changes_applied": False, "execution": None,
93+
"error": reason, "recommended_action": reason,
94+
"plan": {**payload.get("plan", {}), "apply_supported": False,
95+
"blocked_reason": reason, "mutates_release_install": False},
96+
"next_action": {"kind": "review_update_target", "command": None,
97+
"mutating": False, "requires_explicit_approval": False, "reason": reason},
98+
}
99+
install_command = [*command[:-1], requirement]
100+
artifact_url = requirement.partition(" @ ")[2].partition("#")[0]
101+
progress("Updating CLI through its Python package manager")
102+
try:
103+
result = subprocess.run(
104+
install_command, text=True, encoding="utf-8", errors="replace",
105+
capture_output=True, timeout=timeout_seconds,
106+
)
107+
except subprocess.TimeoutExpired as exc:
108+
if artifact_url:
109+
raise subprocess.TimeoutExpired(command, exc.timeout) from None
110+
raise
111+
if artifact_url:
112+
# The retained worker output must not expose a signed artifact URL.
113+
result.stdout = result.stdout.replace(artifact_url, "<verified LoopX package>")
114+
result.stderr = result.stderr.replace(artifact_url, "<verified LoopX package>")
115+
return result
14116

15117

16118
def prepare_target(payload: dict[str, Any], *, freshness: dict, resolve_remote: bool,

‎loopx/control_plane/heartbeat/installed_prompt_update.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def update_with_prompts(payload: dict, *, registry: Path, runtime_root: str | No
158158
# Do not strand managed prompts after a successful install + core doctor,
159159
# but preserve the failed aggregate result and its original repair action.
160160
runtime_ready = bool(updated.get("ok"))
161-
execution = updated.get("execution", {})
161+
execution = updated.get("execution") or {}
162162
installed = runtime_ready or ((updated.get("changes_applied") is True
163163
or execution.get("package_identity_verified") is True)
164164
and execution.get("install_returncode") == 0

‎loopx/self_update.py‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,13 +1105,14 @@ def _execute_python_distribution_update(
11051105
previous_identity = release_runtime_identity(Path(__file__).resolve().parents[1])
11061106
installed_identity: dict[str, Any] = {}
11071107
results: dict[str, subprocess.CompletedProcess[str]] = {}
1108-
progress("Updating CLI through its Python package manager")
1109-
results["install"] = subprocess.run(
1110-
commands["install"],
1111-
text=True, encoding="utf-8", errors="replace",
1112-
capture_output=True,
1113-
timeout=timeout_seconds,
1108+
from .cli_commands.update_source import install_python_package
1109+
installation = install_python_package(
1110+
payload, commands["install"], installed_version=previous_identity.get("package_version")
1111+
or payload.get("current", {}).get("current_version"), timeout_seconds=timeout_seconds, progress=progress,
11141112
)
1113+
if isinstance(installation, dict):
1114+
return installation
1115+
results["install"] = installation
11151116
if results["install"].returncode == 0:
11161117
for step in ("installation_readback", *host_steps):
11171118
progress(f"Validating updated runtime: {step}")

‎tests/control_plane/test_automation_prompt_upgrade.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,8 @@ def forbidden(*args, **kwargs):
377377
raise AssertionError("failed installer must not invoke prompt writer")
378378
monkeypatch.setattr(lifecycle.subprocess, "run", forbidden)
379379
result = lifecycle.update_with_prompts({}, registry=registry, runtime_root=None,
380-
timeout_seconds=1, runtime_update=lambda payload, **_: {"ok": False})
380+
timeout_seconds=1,
381+
runtime_update=lambda payload, **_: {"ok": False, "changes_applied": False, "execution": None})
381382
assert result["automation_prompt_upgrade"]["status"] == "skipped_runtime_update_failed"
382383
assert path.read_bytes() == original
383384

‎tests/test_chat_runtime_activation.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -689,6 +689,7 @@ def test_update_keeps_install_readback_but_does_not_claim_deferred_service_is_se
689689
"scope": "installation_only", "service_runtime_identity": installed}), "")
690690
with (
691691
mock.patch("loopx.self_update.release_runtime_identity", return_value=previous),
692+
mock.patch("loopx.cli_commands.update_source.pin_pip_update_target", return_value="loopx==2.4.0"),
692693
mock.patch(
693694
"loopx.self_update.run_archive_installer", return_value=(passed, {})
694695
),

‎tests/test_self_update_runtime_activation.py‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ def identity(fingerprint):
3838
"package_version": __version__, "package_fingerprint": "sha256:" + fingerprint * 64}
3939

4040
monkeypatch.setattr("loopx.self_update.release_runtime_identity", lambda *_: identity("1"))
41+
# These lifecycle tests start after pip has checked a same-layout target.
42+
monkeypatch.setattr(
43+
"loopx.cli_commands.update_source.pin_pip_update_target",
44+
lambda _command, **_: f"loopx=={__version__}",
45+
)
4146

4247
def doctor(fingerprint="2"):
4348
body = {"ok": True, "scope": "installation_only", "service_runtime_identity": identity(fingerprint)}
@@ -505,7 +510,7 @@ def test_python_distribution_apply_uses_the_owning_interpreter_pip(python_packag
505510
"pip",
506511
"install",
507512
"--upgrade",
508-
"loopx",
513+
f"loopx=={__version__}",
509514
]
510515
assert run.call_args_list[1].args[0][-2:] == ["doctor", "--installation-only"]
511516
assert run.call_args_list[2].args[0][-4:] == ["authority-archive", "upgrade", "--all-known", "--execute"]
@@ -622,6 +627,54 @@ def test_real_windows_console_refuses_before_starting_installer(tmp_path: Path)
622627
assert "loopx.entrypoint" in refusal["next_action"]["command"]
623628

624629

630+
@pytest.mark.parametrize("core_already_present", [False, True])
631+
def test_pip_apply_refuses_split_target_before_starting_install(monkeypatch, core_already_present):
632+
rows = [{
633+
"metadata": {"name": "loopx", "requires_dist": ["LoopX_Core (==2.4.2rc1)"]},
634+
}]
635+
if not core_already_present:
636+
rows.append({"metadata": {"name": "loopx-core"}})
637+
report = subprocess.CompletedProcess([], 0, json.dumps({"version": "1", "install": rows}), "")
638+
run = mock.Mock(return_value=report)
639+
monkeypatch.setattr("loopx.self_update.subprocess.run", run)
640+
641+
result = execute_update_plan(apply_plan_for_driver("python_pip"))
642+
643+
run.assert_called_once()
644+
assert "--dry-run" in run.call_args.args[0]
645+
assert result["ok"] is False and result["changes_applied"] is False
646+
assert result["plan"]["mutates_release_install"] is False
647+
assert result["execution"] is None
648+
assert result["next_action"]["kind"] == "review_update_target"
649+
assert "separate environment" in result["error"]
650+
651+
652+
@pytest.mark.parametrize("legacy_report", [False, True])
653+
def test_pip_update_installs_the_verified_artifact_and_redacts_its_url(monkeypatch, legacy_report):
654+
version = __version__
655+
artifact = f"https://packages.example.invalid/loopx-{version}-py3-none-any.whl?access=fixture"
656+
digest = "a" * 64
657+
archive = {"hash": "sha256=" + digest} if legacy_report else {"hashes": {"sha256": digest}}
658+
target = {"metadata": {"name": "loopx", "version": version},
659+
"download_info": {"url": artifact, "archive_info": archive}}
660+
report_version = "0" if legacy_report else "1"
661+
report = subprocess.CompletedProcess([], 0, json.dumps({"version": report_version, "install": [target]}), "")
662+
# Failing at the package-manager boundary isolates the next command and its
663+
# error receipt from the unrelated post-install reconciliation steps.
664+
refused = subprocess.CompletedProcess([], 1, "", f"File changed at {artifact}#sha256={digest}")
665+
run = mock.Mock(side_effect=[report, refused])
666+
monkeypatch.setattr("loopx.self_update.subprocess.run", run)
667+
monkeypatch.setattr("loopx.self_update.restart_services_for_runtime_activation", lambda **_: {})
668+
669+
result = execute_update_plan(apply_plan_for_driver("python_pip"))
670+
671+
assert run.call_count == 2
672+
assert run.call_args.args[0][-1] == f"loopx @ {artifact}#sha256={digest}"
673+
assert result["ok"] is False and result["changes_applied"] is False
674+
assert artifact not in json.dumps(result)
675+
assert "<verified LoopX package>" in result["execution"]["install_stderr_tail"]
676+
677+
625678
def test_pipx_distribution_apply_preserves_the_pipx_environment(python_package_readback) -> None:
626679
doctor = doctor_payload()
627680
doctor["package"] = {"install_kind": "python_distribution"}
@@ -856,8 +909,10 @@ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[s
856909
"com.loopx.chat",
857910
"com.goal-harness.status",
858911
}
859-
assert len(calls) == 3
860-
assert all(call[0] == "launchctl" for call in calls)
912+
launchctl_calls = [call for call in calls if call[0] == "launchctl"]
913+
assert len(launchctl_calls) == 3
914+
assert all(call[1:3] == ["kickstart", "-k"] for call in launchctl_calls)
915+
assert {call[-1].rsplit("/", 1)[1] for call in launchctl_calls} == set(restarted)
861916

862917

863918
@pytest.mark.skipif(

0 commit comments

Comments
 (0)