Skip to content

The agent that grows with you

test(pm): consolidate lifecycle coverage and remove synthetic duplicates

ethernetb34963c67433
diff --git a/tests/hermes_cli/test_update_receipt_pm_embed.py b/tests/hermes_cli/test_update_receipt_pm_embed.py
index bcf1175e3e2..04dc60aac49 100644
--- a/tests/hermes_cli/test_update_receipt_pm_embed.py
+++ b/tests/hermes_cli/test_update_receipt_pm_embed.py
@@ -71,6 +71,7 @@ def test_update_receipt_embeds_pm_sections(homed):
path = ur.finalize_update_receipt("success")
data = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8"))
+ assert json.loads(path.read_text(encoding="utf-8")) == data
assert data["outcome"] == "success"
assert data["pm_venv_rebuild"] == {"ok": True, "reason": ""}
assert data["pm_feature_list"] == ["web", "acp"]
@@ -91,13 +92,6 @@ def test_legacy_worker_receipt_fields_still_embed(homed):
assert data["pm_plugin_bisect"] == legacy["plugin_bisect"]
-def test_update_receipt_without_sync_embeds_nothing(homed):
- ur.begin_update_receipt()
- ur.finalize_update_receipt("success")
- data = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8"))
- assert "pm_venv_rebuild" not in data
- assert data["outcome"] == "success"
-
def test_stale_sync_from_before_the_update_is_never_embedded(homed):
"""The audit defect: an old sync receipt on disk (latest.json's newest)
@@ -152,6 +146,7 @@ def test_nested_update_ids_do_not_cross_embed(homed):
outer_id = ur.current_correlation_id()
pm_receipt_mod.begin("sync")
pm_receipt_mod.record_venv_rebuild(True, "outer rebuild")
+ pm_receipt_mod.record_step("outer-sync", True)
pm_receipt_mod.finalize("ok")
ur.begin_update_receipt() # nested update — new id, outer preserved behind the token
@@ -159,11 +154,15 @@ def test_nested_update_ids_do_not_cross_embed(homed):
assert inner_id != outer_id
pm_receipt_mod.begin("sync")
pm_receipt_mod.record_venv_rebuild(True, "inner rebuild")
+ pm_receipt_mod.record_step("inner-sync", True)
pm_receipt_mod.finalize("ok")
inner_path = ur.finalize_update_receipt("success")
assert inner_path is not None
assert json.loads(inner_path.read_text(encoding="utf-8"))["pm_venv_rebuild"]["reason"] == "inner rebuild"
+ assert pm_receipt_mod.last_for_update(inner_id) is None
+ assert ur.current_correlation_id() == outer_id
+ assert pm_receipt_mod.last_for_update(outer_id)["steps"][0]["name"] == "outer-sync"
# outer finalize: the outer sync is STILL its own completion — the
# nested update's finalize restored the outer receipt and must not
@@ -174,42 +173,20 @@ def test_nested_update_ids_do_not_cross_embed(homed):
assert outer_data["update_id"] == outer_id
assert outer_data["pm_venv_rebuild"]["reason"] == "outer rebuild"
assert "inner rebuild" not in json.dumps(outer_data)
+ assert outer_data["pm_steps"][0]["name"] == "outer-sync"
+ assert pm_receipt_mod.last_for_update(outer_id) is None
+ assert inner_path != outer_path
+ inner_data = json.loads(inner_path.read_text(encoding="utf-8"))
+ assert inner_data["update_id"] == inner_id
+ assert inner_data["pm_steps"][0]["name"] == "inner-sync"
+ assert inner_data["pm_venv_rebuild"]["reason"] == "inner rebuild"
+ latest = json.loads((homed / "logs/update_receipts/latest.json").read_text(encoding="utf-8"))
+ assert latest == outer_data
# outermost finalize popped the last receipt: no correlation remains
assert ur.current_correlation_id() is None
-def test_both_nested_receipts_still_read_correctly_after_all_finalizations(homed):
- """Invariant: inner and outer receipts have UNIQUE file names (same
- process, possibly the same second) and each exact path still reads its
- own story AFTER every finalize — no overwrite, no cross-contamination,
- including the latest.json pointer (outer finished last)."""
- import pm.receipt as pm_receipt_mod
-
- ur.begin_update_receipt()
- pm_receipt_mod.begin("sync")
- pm_receipt_mod.record_venv_rebuild(True, "outer rebuild")
- pm_receipt_mod.finalize("ok")
-
- ur.begin_update_receipt()
- pm_receipt_mod.begin("sync")
- pm_receipt_mod.record_venv_rebuild(True, "inner rebuild")
- pm_receipt_mod.finalize("ok")
-
- inner_path = ur.finalize_update_receipt("success")
- outer_path = ur.finalize_update_receipt("success")
-
- assert inner_path != outer_path
- assert inner_path.is_file() and outer_path.is_file()
- inner_data = json.loads(inner_path.read_text(encoding="utf-8"))
- outer_data = json.loads(outer_path.read_text(encoding="utf-8"))
- assert inner_data["pm_venv_rebuild"]["reason"] == "inner rebuild"
- assert outer_data["pm_venv_rebuild"]["reason"] == "outer rebuild"
- # latest.json points at the LAST finalization (the outer run)
- latest = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8"))
- assert latest["update_id"] == outer_data["update_id"]
- assert latest["pm_venv_rebuild"]["reason"] == "outer rebuild"
-
def test_sync_after_nested_update_finalizes_embeds_into_outer(homed):
"""Continuing the outer update after the nested one closed: a sync
diff --git a/tests/pm/_fixtures.py b/tests/pm/_fixtures.py
index 47b8336878f..147784bb4d6 100644
--- a/tests/pm/_fixtures.py
+++ b/tests/pm/_fixtures.py
@@ -2,6 +2,7 @@
from __future__ import annotations
from functools import partial
+from contextlib import contextmanager
import hashlib
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
import importlib
@@ -40,6 +41,21 @@ def _run(command, *, cwd: Path, env: dict) -> str:
return result.stdout.strip()
+def _ar_member(name: str, data: bytes) -> bytes:
+ hdr = (
+ name.ljust(16).encode()
+ + b"0".ljust(12)
+ + b"0".ljust(6)
+ + b"0".ljust(6)
+ + b"100644".ljust(8)
+ + str(len(data)).encode().ljust(10)
+ + b"`\n"
+ )
+ pad = b"\n" if len(data) % 2 else b""
+ return hdr + data + pad
+
+
+
def make_tar(docroot: Path, name: str, files: dict[str, str]) -> tuple[str, str]:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tf:
@@ -54,21 +70,28 @@ def make_tar(docroot: Path, name: str, files: dict[str, str]) -> tuple[str, str]
return name, hashlib.sha256(payload).hexdigest()
-def served(tmp_path):
- docroot = tmp_path / "www"
- docroot.mkdir()
- handler = partial(SimpleHTTPRequestHandler, directory=str(docroot))
+@contextmanager
+def threaded_server(handler):
with ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
+ server.daemon_threads = True
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
- yield docroot, f"http://127.0.0.1:{server.server_port}"
+ yield server
finally:
server.shutdown()
thread.join(timeout=5)
+def served(tmp_path):
+ docroot = tmp_path / "www"
+ docroot.mkdir()
+ handler = partial(SimpleHTTPRequestHandler, directory=str(docroot))
+ with threaded_server(handler) as server:
+ yield docroot, f"http://127.0.0.1:{server.server_port}"
+
+
@pytest.fixture(scope="module")
def isolated_python(tmp_path_factory):
from pm.runtime_stage import stage_runtime
@@ -95,20 +118,25 @@ def client(tmp_path, monkeypatch, isolated_python):
return client
-def build_worker(client, isolated_python, monkeypatch):
- """Inject prepared real tools only inside the independent worker process."""
+def worker_toolchain(client, monkeypatch, isolated_python, injection=""):
uv = shutil.which("uv")
- assert uv, "the worker contract requires real uv"
+ assert uv
worker = Path(client.__file__).with_name("worker.py")
script = (
- "import runpy, sys; from pathlib import Path; "
+ "import runpy, sys, os; from pathlib import Path; "
f"sys.path.insert(0, {str(worker.parent.parent)!r}); "
"import pm._uv; "
- f"pm._uv._toolchain = lambda **kwargs: (Path({uv!r}), Path({sys.executable!r})); "
- f"runpy.run_path({str(worker)!r}, run_name='__main__')"
+ f"pm._uv._toolchain = lambda **kwargs: (Path({uv!r}), Path({sys.executable!r}));\n"
+ + injection + f"\nrunpy.run_path({str(worker)!r}, run_name='__main__')"
)
monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])
+
+
+
+def build_worker(client, isolated_python, monkeypatch):
+ """Inject prepared real tools only inside the independent worker process."""
+ worker_toolchain(client, monkeypatch, isolated_python)
monkeypatch.setattr(client, "is_runtime", lambda: False)
def caller_engine(*args, **kwargs):
diff --git a/tests/pm/test_activate_scripts.py b/tests/pm/test_activate_scripts.py
index a32ce658c08..88c45c282f9 100644
--- a/tests/pm/test_activate_scripts.py
+++ b/tests/pm/test_activate_scripts.py
@@ -189,6 +189,7 @@ def test_bash_scripts_pass_syntax_check():
assert result.returncode == 0, f"{script.name}: {result.stderr}"
def test_source_activate_exports_the_pm_env(tmp_path: Path):
root = _isolated_checkout(tmp_path)
store, _ = _fake_store(tmp_path)
@@ -208,6 +209,7 @@ def test_source_activate_exports_the_pm_env(tmp_path: Path):
assert result.stdout == "env-ok"
def test_deactivate_restores_the_prior_shell(tmp_path: Path):
root = _isolated_checkout(tmp_path)
store, _ = _fake_store(tmp_path)
diff --git a/tests/pm/test_activation_runtime.py b/tests/pm/test_activation_runtime.py
index a88a50d2dd0..c80d036fbde 100644
--- a/tests/pm/test_activation_runtime.py
+++ b/tests/pm/test_activation_runtime.py
@@ -84,15 +84,21 @@ def _assert_syncs(root: Path):
@pytest.mark.platforms("posix")
-def test_bash_cold_sync_changed_input_and_warm_noop(tmp_path):
[email protected]("canary", [None, "caller-canary"])
+def test_bash_cold_sync_changed_input_and_warm_noop(tmp_path, canary):
root, env = _sync_checkout(tmp_path)
assert not (root / ".venv").exists()
+ if canary is not None:
+ env["HERMES_PM_ACTIVATE_CANARY"] = canary
+ from tests.pm.test_activate_scripts import _fake_store
+ _fake_store(tmp_path)
script = f'''
set -e
export PYTHONPATH=caller-original VIRTUAL_ENV=caller-venv
original_path="$PATH"
source "{_posix(root / 'activate')}"
printf '%s\\n' "$PYTHONPATH"
+ test "$HERMES_PM_ACTIVATE_CANARY" = env-ok
printf second > "{_posix(root / 'input')}"
source "{_posix(root / 'activate')}"
printf '%s\\n' "$PYTHONPATH"
@@ -103,6 +109,9 @@ def test_bash_cold_sync_changed_input_and_warm_noop(tmp_path):
test "$PATH" = "$original_path"
test "$PYTHONPATH" = caller-original
test "$VIRTUAL_ENV" = caller-venv
+ {('test "$HERMES_PM_ACTIVATE_CANARY" = caller-canary' if canary else 'test -z "${HERMES_PM_ACTIVATE_CANARY+set}"')}
+ test -z "${{__HERMES_ACTIVATED+set}}"
+ ! declare -F deactivate >/dev/null
'''
run = subprocess.run([_bash(), "-c", script], cwd=tmp_path, env=env,
capture_output=True, text=True, timeout=40)
diff --git a/tests/pm/test_archive_safety.py b/tests/pm/test_archive_safety.py
index 449fa2dca1f..34fbc8c7bbb 100644
--- a/tests/pm/test_archive_safety.py
+++ b/tests/pm/test_archive_safety.py
@@ -64,13 +64,6 @@ def _add_file(
zf.writestr(info, data)
-def _write_zip(path: Path, build) -> Path:
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, "w") as zf:
- build(zf)
- path.write_bytes(buf.getvalue())
- return path
-
class TestPathTraversal:
def test_zip_entries_cannot_escape_the_destination(self, tmp_path):
diff --git a/tests/pm/test_custom_root_union.py b/tests/pm/test_custom_root_union.py
index de05778ae6e..2656023fa2c 100644
--- a/tests/pm/test_custom_root_union.py
+++ b/tests/pm/test_custom_root_union.py
@@ -1,18 +1,11 @@
-"""E2E: custom HERMES_HOME roots (Docker, non-default local) join the
-plugin-deps union the same as standard ~/.hermes ones.
-
-get_default_hermes_root() is the ONE authority: HERMES_HOME outside the
-default (e.g. /opt/data in Docker) → that root directly; profile-mode
-HERMES_HOME (<root>/profiles/<name>) → <root>. The union's profile scan
-must flow through it: hardcoded Path.home()/.hermes/profiles silently
-omitted custom-root profiles and their enabled dependency plugins.
-"""
+"""Real default, custom and active-profile roots all discover sibling members."""
from __future__ import annotations
from pathlib import Path
import hermes_yaml as yaml
+import pytest
import pm.plugins_state as pstate
import pm.workspace as ws
@@ -39,71 +32,22 @@ def _make_dep_plugin(plugins_dir: Path, name: str) -> Path:
return plug
-def test_custom_hermes_home_profile_joins_union(tmp_path, monkeypatch):
- """Docker shape: HERMES_HOME=/opt/data-like root, a profile under it
- with an enabled dep plugin. Discovery must find the member through
- the REAL get_default_hermes_root (no path mocks)."""
- custom_root = tmp_path / "opt-data" # the /opt/data shape
- profile_home = custom_root / "profiles" / "worker"
- _write_enabled(profile_home, ["dep-plug"])
- _make_dep_plugin(profile_home / "plugins", "dep-plug")
-
- monkeypatch.setenv("HERMES_HOME", str(custom_root))
- import hermes_constants
-
- # the real authority must resolve the custom root (the contract this
- # test exists to pin: env → get_default_hermes_root → union)
- assert hermes_constants.get_default_hermes_root() == custom_root
-
- # union discovery: the profile's enabled dep plugin IS a member
- members = ws.enabled_member_dirs()
- assert [p.name for p in members] == ["dep-plug"], (
- "custom-root profile's enabled dep plugin missing from the union — "
- "profile scan must derive from get_default_hermes_root"
- )
- # ordered enabled reads see it too
- ordered = pstate.enabled_plugins_ordered()
- assert ordered.get(profile_home / "plugins") == ["dep-plug"]
-
-
-def test_standard_layout_still_works(tmp_path, monkeypatch):
- """The default-home path: profile under the (monkeypatched) default
- root, standard layout. Guards the derivation change didn't break the
- common case."""
- default_root = tmp_path / "home" # stands in for ~/.hermes
- profile_home = default_root / "profiles" / "coder"
- _write_enabled(profile_home, ["dep-plug"])
- _make_dep_plugin(profile_home / "plugins", "dep-plug")
-
- import hermes_constants
-
- monkeypatch.setattr(
- hermes_constants, "get_default_hermes_root", lambda: default_root
- )
- # NOTE: pm.plugins_state imports the function lazily inside
- # _profiles_root, so the attribute patch reaches it.
-
- members = ws.enabled_member_dirs()
- assert [p.name for p in members] == ["dep-plug"]
-
-
-def test_profile_mode_hermes_home_resolves_parent(tmp_path, monkeypatch):
- """Profile-mode shape: HERMES_HOME=<root>/profiles/<name> — the
- authority returns <root> so sibling profiles join the union."""
- root = tmp_path / "data-root"
- active_home = root / "profiles" / "active"
- sibling_home = root / "profiles" / "sibling"
- _write_enabled(sibling_home, ["dep-plug"])
- _make_dep_plugin(sibling_home / "plugins", "dep-plug")
- active_home.mkdir(parents=True) # active profile has no dep plugins
-
- monkeypatch.setenv("HERMES_HOME", str(active_home))
[email protected]("layout", ["default", "custom", "profile"])
+def test_home_layout_joins_sibling_union(tmp_path, monkeypatch, layout):
import hermes_constants
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ root = tmp_path / (".hermes" if layout == "default" else "data-root")
+ active = root / "profiles/active" if layout == "profile" else root
+ if layout == "default":
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ else:
+ monkeypatch.setenv("HERMES_HOME", str(active))
+ active.mkdir(parents=True)
+ sibling = root / "profiles/sibling"
+ _write_enabled(sibling, ["dep-plug"])
+ member = _make_dep_plugin(sibling / "plugins", "dep-plug")
+ (root / "profiles/README.txt").write_text("not a profile")
assert hermes_constants.get_default_hermes_root() == root
-
- members = ws.enabled_member_dirs()
- assert [p.name for p in members] == ["dep-plug"], (
- "profile-mode HERMES_HOME must not hide sibling profiles' plugins "
- "from the union"
- )
+ assert ws.enabled_member_dirs() == [member]
+ assert pstate.enabled_plugins_ordered() == {sibling / "plugins": ["dep-plug"]}
diff --git a/tests/pm/test_deb_safety.py b/tests/pm/test_deb_safety.py
index a0e467a1b7f..769426778e0 100644
--- a/tests/pm/test_deb_safety.py
+++ b/tests/pm/test_deb_safety.py
@@ -18,25 +18,13 @@ from pathlib import Path
import pytest
from pm.package import DebPackage, InstallError
+from tests.pm._fixtures import _ar_member
class _P(DebPackage):
name = "evil-deb"
-def _ar_member(name: str, data: bytes) -> bytes:
- hdr = (
- name.ljust(16).encode()
- + b"0".ljust(12)
- + b"0".ljust(6)
- + b"0".ljust(6)
- + b"100644".ljust(8)
- + str(len(data)).encode().ljust(10)
- + b"`\n"
- )
- pad = b"\n" if len(data) % 2 else b""
- return hdr + data + pad
-
def _build_deb(path: Path, members: list[tarfile.TarInfo | tuple[str, bytes]]) -> None:
"""A real ar archive with one data.tar (uncompressed) holding `members`."""
@@ -84,6 +72,17 @@ def test_chained_aliases_survive_without_symlink_support(tmp_path, monkeypatch):
assert (staged / lib / name).read_bytes() == b"library payload"
+def test_relative_member_escape_preserves_outside(tmp_path):
+ deb, staged = tmp_path / "escape.deb", tmp_path / "staged"
+ sentinel = tmp_path / "sentinel"
+ sentinel.write_bytes(b"outside")
+ _build_deb(deb, [("../sentinel", b"escaped")])
+ staged.mkdir()
+ with pytest.raises(InstallError, match="escape|unsafe|outside"):
+ _P().unpack(deb, staged, "linux-arm64-bionic")
+ assert sentinel.read_bytes() == b"outside"
+
+
def test_absolute_symlink_target_rejected(tmp_path: Path):
"""A member whose symlink target is ABSOLUTE must be refused outright:
the link points outside the staged tree the moment it is created."""
@@ -104,38 +103,33 @@ def test_absolute_symlink_target_rejected(tmp_path: Path):
@pytest.mark.platforms("posix")
@pytest.mark.parametrize(
"shape",
- ["write-through", "chmod-follow"],
+ ["relative-link", "planted-ancestor"],
)
def test_symlink_escape_forbidden(tmp_path: Path, shape: str):
- """A symlink planted in the staged tree must never become a path OUT:
- not for a later data member written through it (write-through), and not
- for the final mode-normalization walk following it (chmod-follow)."""
+ """Relative link and pre-existing ancestor escapes leave outside bytes/mode intact.
+
+ These exercise containment, not an independent late chmod-walk guard.
+ """
outside = tmp_path / "outside"
outside.mkdir()
sentinel = outside / "sentinel.txt"
sentinel.write_text("do not touch")
os.chmod(sentinel, 0o600)
- linkname = str(sentinel if shape == "chmod-follow" else outside)
- members: list = [_symlink_member("link", linkname)]
- if shape == "write-through":
- members.append(("link/evil.txt", b"escaped"))
+ staged = tmp_path / "staged"
+ staged.mkdir()
+ if shape == "relative-link":
+ members = [_symlink_member("link", "../outside"), ("link/evil.txt", b"escaped")]
else:
- members.append(("regular.txt", b"payload"))
+ (staged / "link").symlink_to(outside, target_is_directory=True)
+ members = [("link/evil.txt", b"escaped")]
deb = tmp_path / f"escape-{shape}.deb"
_build_deb(deb, members)
-
- staged = tmp_path / "staged"
- staged.mkdir()
- with pytest.raises(InstallError):
+ with pytest.raises(InstallError, match="escape|unsafe|outside"):
_P().unpack(deb, staged, "linux-arm64-bionic")
assert sentinel.read_text() == "do not touch", (
f"{shape}: a staged symlink was followed outside the tree"
)
- if shape == "chmod-follow":
- assert os.stat(sentinel).st_mode & 0o777 == 0o600, (
- "the mode walk chmod'd a file outside the staged tree"
- )
- if shape == "write-through":
- assert not (outside / "evil.txt").exists()
+ assert os.stat(sentinel).st_mode & 0o777 == 0o600
+ assert not (outside / "evil.txt").exists()
diff --git a/tests/pm/test_download_cleanup.py b/tests/pm/test_download_cleanup.py
deleted file mode 100644
index f2c1f33e903..00000000000
--- a/tests/pm/test_download_cleanup.py
+++ /dev/null
@@ -1,123 +0,0 @@
-"""Archive lifetime follows package publication, not transfer completion."""
-from __future__ import annotations
-
-import hashlib
-import io
-from pathlib import Path
-import zipfile
-
-import pytest
-
-import pm
-from pm import paths, registry
-from pm.ensure import ensure, stage_only
-from pm.lock import Facts, Lockfile
-from pm.package import Package
-from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
-
-
-class Components(Package):
- name = "cleanup-components"
-
- def verify(self, entry, target):
- return "" if (entry / "engine").is_file() and (entry / "library").is_file() else "incomplete package"
-
-
-def install_case(tmp_path, monkeypatch, dl_server):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- store = tmp_path / "store"
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
- lock_path = tmp_path / "lock.json"
- monkeypatch.setattr(paths, "lockfile_path", lambda: lock_path)
- package = Components()
- monkeypatch.setitem(registry._packages, package.name, package)
- pins = []
- for name in ("engine", "library"):
- data = io.BytesIO()
- with zipfile.ZipFile(data, "w") as archive:
- archive.writestr(name, name.encode())
- path = f"/{name}.zip"
- RangeHandler.payloads[path] = data.getvalue()
- pins.append({"url": url(dl_server, path), "sha256": hashlib.sha256(data.getvalue()).hexdigest()})
- lock = Lockfile(lock_path)
- lock.set_pin(package.name, "1", {pm.current_target(): pins})
- lock.save()
- other = store / ("fetch-" + "f" * 64)
- other.mkdir(parents=True)
- (other / "other.zip").write_bytes(b"another install's download")
- partial = paths.partials_root() / "unrelated.part"
- partial.parent.mkdir(parents=True, exist_ok=True)
- partial.write_bytes(b"in-progress download")
- return package, store, pins, other, partial
-
-
-def install(package, mode):
- if mode == "stage":
- return stage_only(package.name, pm.current_target())
- ensure(package.name, explicit=True, base_env={})
- return pm.installed_package(package.name).path
-
-
[email protected]("mode", ["install", "stage"])
-def test_publication_removes_only_its_archives(install_case, mode):
- package, store, pins, other, partial = install_case
- entry = install(package, mode)
- for name in ("engine", "library"):
- assert (entry / name).read_bytes() == name.encode()
- assert not any((store / f"fetch-{pin['sha256']}").exists() for pin in pins)
- assert (other / "other.zip").read_bytes() == b"another install's download"
- assert partial.read_bytes() == b"in-progress download"
- RangeHandler.payloads.clear()
- assert install(package, mode) == entry # Already installed works offline without archives.
-
-
[email protected](("mode", "failure"), [
- (mode, failure)
- for mode in ("install", "stage")
- for failure in ("unpack", "verify", "publish", "published-verify", "facts")
- if mode == "install" or failure != "facts"
-])
-def test_failure_keeps_archives_for_offline_retry(install_case, monkeypatch, mode, failure):
- package, store, pins, _, _ = install_case
- original_verify = package.verify
- original_unpack = package.unpack
-
- def fail(*args, **kwargs):
- raise pm.InstallError(package.name, "injected failure")
-
- def unpack(archive, staged, target):
- original_unpack(archive, staged, target)
- if (staged / "library").exists():
- fail()
-
- def verify(entry, target):
- published = entry.parent == store
- if failure == "verify" or published:
- fail()
- return original_verify(entry, target)
-
- with monkeypatch.context() as fault:
- if failure == "unpack":
- fault.setattr(package, "unpack", unpack)
- elif failure in ("verify", "published-verify"):
- fault.setattr(package, "verify", verify)
- elif failure == "publish":
- original_publish = pm.Store.publish
-
- def publish(self, staged, name):
- if name.startswith(package.name):
- fail()
- return original_publish(self, staged, name)
-
- fault.setattr(pm.Store, "publish", publish)
- else:
- fault.setattr(Facts, "record", fail)
- with pytest.raises(pm.InstallError, match="injected failure"):
- install(package, mode)
- assert all((store / f"fetch-{pin['sha256']}").is_dir() for pin in pins)
- RangeHandler.payloads.clear()
- entry = install(package, mode)
- assert (entry / "engine").read_bytes() == b"engine"
- assert not any((store / f"fetch-{pin['sha256']}").exists() for pin in pins)
diff --git a/tests/pm/test_download_retry_limits.py b/tests/pm/test_download_retry_limits.py
index b7a39d3bf40..c99eb9acc9c 100644
--- a/tests/pm/test_download_retry_limits.py
+++ b/tests/pm/test_download_retry_limits.py
@@ -11,8 +11,9 @@ from pm.downloader import Download, DownloadPaused, DownloadTransportError, Hash
from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
[email protected]("failure", ["503", "404", "403", "hash", "disk"])
[email protected]("phase", ["probe", "ranged", "single"])
[email protected]("failure,phase", [
+ (failure, phase) for failure in ("503", "404", "403") for phase in ("probe", "ranged", "single")
+] + [("hash", "ranged"), ("hash", "single"), ("disk", "probe")])
def test_download_failure_never_publishes_partial_bytes(tmp_path, dl_server, monkeypatch, failure, phase):
payload = b"verified bytes"
RangeHandler.payloads["/tool"] = payload
diff --git a/tests/pm/test_downloader.py b/tests/pm/test_downloader.py
index 12160d28e45..4b270000a4a 100644
--- a/tests/pm/test_downloader.py
+++ b/tests/pm/test_downloader.py
@@ -11,15 +11,14 @@ from __future__ import annotations
import hashlib
import json
import threading
-import time
-from pathlib import Path
import pytest
from pm.downloader import (Download, DownloadError, DownloadPaused,
HashError, Source)
-from tests.pm._range_server import RangeHandler as _Handler, dl_server, url as _url
+from tests.pm._range_server import RangeHandler as _Handler, url as _url
+from tests.pm._range_server import dl_server as dl_server
def _payload(n: int, seed: bytes = b"x") -> bytes:
@@ -129,44 +128,6 @@ def test_no_hash_accepts_any_bytes_of_right_size(dl_server, tmp_path):
# ── resume ────────────────────────────────────────────────────
-def test_resume_refetches_only_missing_ranges(dl_server, tmp_path):
- payload = _payload(8 << 20)
- _Handler.payloads["/r"] = payload
- dest = tmp_path / "r.bin"
- partials = tmp_path / "partials"
- # first run: one connection, server drops after 2 MiB
- _Handler.abort_after = 2 << 20
- dl = Download([Source(_url(dl_server, "/r"), dest, _sha(payload))],
- partials_dir=partials, connections=1)
- with pytest.raises(Exception):
- dl.run()
- first = list(_Handler.ranges_seen)
- # second run resumes: only the missing tail is re-fetched
- _Handler.abort_after = None
- dl = Download([Source(_url(dl_server, "/r"), dest, _sha(payload))],
- partials_dir=partials, connections=1)
- dl.run()
- assert dest.read_bytes() == payload
- assert _Handler.ranges_seen == first + [("/r", 2 << 20, (8 << 20) - 1)]
-
-
-def test_resume_after_crash_reads_sidecar(dl_server, tmp_path):
- payload = _payload(4 << 20)
- _Handler.payloads["/c"] = payload
- dest = tmp_path / "c.bin"
- partials = tmp_path / "partials"
- partials.mkdir()
- key = hashlib.sha256(_url(dl_server, "/c").encode("utf-8")).hexdigest()
- (partials / f"{key}.part").write_bytes(payload[: 1 << 20])
- (partials / f"{key}.ranges").write_text(json.dumps({
- "total": len(payload), "etag": '"' + _sha(payload) + '"',
- "sha256": _sha(payload), "ranges": [[0, 1 << 20]],
- }), encoding="utf-8")
- dl = Download([Source(_url(dl_server, "/c"), dest, _sha(payload))],
- partials_dir=partials)
- dl.run()
- assert dest.read_bytes() == payload
- assert _Handler.ranges_seen == [("/c", 1 << 20, (4 << 20) - 1)]
def test_partials_never_in_scratch_or_dest(dl_server, tmp_path):
@@ -185,12 +146,13 @@ def test_partials_never_in_scratch_or_dest(dl_server, tmp_path):
if p.suffix in (".part", ".ranges")]
-def test_completed_dest_is_skipped(dl_server, tmp_path):
[email protected]("hashed", [False, True])
+def test_completed_dest_is_skipped(dl_server, tmp_path, hashed):
payload = _payload(1 << 20)
_Handler.payloads["/s"] = payload
dest = tmp_path / "s.bin"
dest.write_bytes(payload)
- dl = Download([Source(_url(dl_server, "/s"), dest, _sha(payload))],
+ dl = Download([Source(_url(dl_server, "/s"), dest, _sha(payload) if hashed else None)],
partials_dir=tmp_path / "partials")
dl.run()
assert _Handler.ranges_seen == [] # nothing fetched
@@ -208,18 +170,6 @@ def test_stale_dest_with_wrong_hash_is_refetched(dl_server, tmp_path):
assert _Handler.ranges_seen # a fetch actually happened
-def test_completed_dest_without_hash_is_skipped(dl_server, tmp_path):
- # Model-catalog policy: no pinned hash -> a present file is accepted
- # (size is the only tripwire), matching fresh-download semantics.
- payload = _payload(1 << 20)
- _Handler.payloads["/s"] = payload
- dest = tmp_path / "s.bin"
- dest.write_bytes(payload)
- dl = Download([Source(_url(dl_server, "/s"), dest)],
- partials_dir=tmp_path / "partials")
- dl.run()
- assert _Handler.ranges_seen == [] # nothing fetched
-
def test_redirect_to_non_https_refused():
import urllib.request
@@ -239,23 +189,6 @@ def test_redirect_to_non_https_refused():
# ── pause ─────────────────────────────────────────────────────
-def test_pause_leaves_partials_intact(dl_server, tmp_path):
- _Handler.payloads["/p"] = _payload(32 << 20)
- dest = tmp_path / "p.bin"
- partials = tmp_path / "partials"
- dl = Download([Source(_url(dl_server, "/p"), dest)],
- partials_dir=partials)
- def pause_after_bytes(done, total, ranges):
- if done > 0:
- dl.pause()
-
- with pytest.raises(DownloadPaused):
- dl.run(progress=pause_after_bytes)
- assert not dest.exists()
- names = {p.name for p in partials.iterdir()}
- assert any(n.endswith(".part") for n in names)
- assert any(n.endswith(".ranges") for n in names)
-
# ── safety ────────────────────────────────────────────────────
@@ -328,11 +261,19 @@ def test_resume_across_plan_skips_completed_source(dl_server, tmp_path):
with pytest.raises(Exception):
dl.run()
+ sidecars = list(partials.glob("*.ranges"))
+ assert len(sidecars) == 1
+ assert json.loads(sidecars[0].read_text())["ranges"] == [[0, 2 << 20]]
+ assert da.read_bytes() == p_a and not db.exists()
_Handler.abort_after = None
dl = Download([Source(_url(dl_server, "/a"), da, _sha(p_a)),
Source(_url(dl_server, "/b"), db, _sha(p_b))],
partials_dir=partials, connections=1)
- dl.run()
+ ticks = []
+ dl.run(progress=lambda d, t, r: ticks.append((d, t, dict(r))))
+ assert ticks[0] == (len(p_a) + (2 << 20), len(p_a) + len(p_b),
+ {str(da): [(0, len(p_a))], str(db): [(0, 2 << 20)]})
+ assert not list(partials.glob("*.ranges")) and not list(partials.glob("*.part"))
assert da.read_bytes() == p_a
assert db.read_bytes() == p_b
a_reqs = [r for r in _Handler.ranges_seen if r[0] == "/a"]
@@ -344,36 +285,6 @@ def test_resume_across_plan_skips_completed_source(dl_server, tmp_path):
assert b_reqs[1][1] != b_reqs[0][1]
-def test_resume_first_progress_shows_durable_prefix(dl_server, tmp_path):
- """On a resumed download, the SECOND run's first progress tick already
- reports the durable prefix as a covered range and overall_done starting
- above zero."""
- total = 8 << 20
- payload = _payload(total)
- _Handler.payloads["/rp"] = payload
- dest = tmp_path / "rp.bin"
- partials = tmp_path / "partials"
-
- _Handler.abort_after = 2 << 20
- dl = Download([Source(_url(dl_server, "/rp"), dest, _sha(payload))],
- partials_dir=partials, connections=1)
- with pytest.raises(Exception):
- dl.run()
-
- _Handler.abort_after = None
- dl = Download([Source(_url(dl_server, "/rp"), dest, _sha(payload))],
- partials_dir=partials, connections=1)
- seen = []
- dl.run(progress=lambda d, t, r: seen.append((d, t, dict(r))))
- assert dest.read_bytes() == payload
- d0, t0, r0 = seen[0]
- assert d0 > 0 # overall_done starts above zero (durable prefix + new)
- assert t0 == total
- ranges = r0[str(dest)]
- assert len(ranges) == 1 # coalesced
- assert ranges[0][0] == 0 # the durable prefix is a covered range
- assert ranges[0][1] > 0
-
def test_pause_mid_plan_resumes_to_completion(dl_server, tmp_path):
"""Pause after source 1 completes: DownloadPaused is raised, source 1's
diff --git a/tests/pm/test_downloader_integrity.py b/tests/pm/test_downloader_integrity.py
index 9b58460cef6..b9e304c796a 100644
--- a/tests/pm/test_downloader_integrity.py
+++ b/tests/pm/test_downloader_integrity.py
@@ -8,6 +8,7 @@ from threading import Thread
import pytest
from pm.downloader import Download, DownloadError, Source
+from tests.pm._fixtures import threaded_server
from tests.pm._range_server import dl_server # noqa: F401 — fixture
@@ -47,27 +48,17 @@ def test_invalid_worker_response_cannot_publish(reply, tmp_path):
def log_message(self, *args):
pass
- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
- server.daemon_threads = True
- thread = Thread(target=server.serve_forever, daemon=True)
- thread.start()
destination = tmp_path / "model.gguf"
- try:
+ with threaded_server(Handler) as server:
source = Source(f"http://127.0.0.1:{server.server_port}/model", destination)
with pytest.raises(DownloadError):
Download([source], partials_dir=tmp_path / "partials", connections=1).run()
assert not destination.exists()
- finally:
- server.shutdown()
- server.server_close()
- thread.join(timeout=5)
@pytest.mark.parametrize("previous", [None, b"previous complete model"])
-def test_failed_cross_volume_publication_keeps_destination_atomic(tmp_path, monkeypatch, previous):
+def test_failed_copy_publication_keeps_destination_atomic(tmp_path, monkeypatch, previous):
import errno
- import os
- from pathlib import Path
import shutil
part = tmp_path / "partials" / "model.part"
@@ -83,23 +74,12 @@ def test_failed_cross_volume_publication_keeps_destination_atomic(tmp_path, monk
source = Source("https://example.invalid/model", destination)
download = Download([source], partials_dir=part.parent)
- original_rename = os.rename
-
- def cross_device(src, dst, *args, **kwargs):
- if Path(src) == part:
- raise OSError(errno.EXDEV, "cross-volume fixture")
- return original_rename(src, dst, *args, **kwargs)
-
- def interrupted_copy(src, dst, *args, **kwargs):
- Path(dst).write_bytes(Path(src).read_bytes()[:4])
- raise OSError(errno.ENOSPC, "destination full")
def interrupted_stream(src, dst, *args, **kwargs):
dst.write(src.read(4))
raise OSError(errno.ENOSPC, "destination full")
- monkeypatch.setattr(os, "rename", cross_device)
- monkeypatch.setattr(shutil.move, "__defaults__", (interrupted_copy,))
+
monkeypatch.setattr(shutil, "copyfileobj", interrupted_stream)
with pytest.raises(OSError, match="destination full"):
download._finalize(source, part, side)
diff --git a/tests/pm/test_environment_build.py b/tests/pm/test_environment_build.py
index aa3cac30af7..231558ae0d1 100644
--- a/tests/pm/test_environment_build.py
+++ b/tests/pm/test_environment_build.py
@@ -130,6 +130,9 @@ def test_public_build_installs_all_extras_at_explicit_destination(installable_pr
source, uv, env = installable_project
monkeypatch.setattr(pm.paths, "repo_root", lambda: tmp_path / "unrelated-project")
monkeypatch.setattr(pm.workspace, "enabled_member_dirs", lambda: pytest.fail("user plugins"))
+ monkeypatch.setenv("UV_PYTHON", "/not-the-interpreter")
+ monkeypatch.setenv("UV_PROJECT_ENVIRONMENT", str(tmp_path / "wrong-environment"))
+ monkeypatch.setenv("VIRTUAL_ENV", str(tmp_path / "wrong-environment"))
before = dict(os.environ)
locked = (source / "uv.lock").read_bytes()
executable = build_environment(explicit=True,
@@ -141,6 +144,8 @@ def test_public_build_installs_all_extras_at_explicit_destination(installable_pr
"import root_app, member_dep, chosen_dep, other_dep; print(root_app.VALUE)"],
cwd=tmp_path, env=env) == "installed from the explicit source"
assert executable.parent.parent == tmp_path / "native environment"
+ assert not (tmp_path / "wrong-environment").exists()
+ assert "root_app" not in sys.modules
from hermes_cli.runtime_paths import site_packages
site = site_packages(executable.parent.parent)
@@ -631,6 +636,9 @@ def test_explicit_workspace_preserves_seed_and_replays_copied_members(locked_pro
_wheel(tmp_path / "wheels", "base_dep", "1.1")
original_member = source / "member"
before_member = (original_member / "pyproject.toml").read_bytes()
+ stamp = workspace.members_stamp([original_member])
+ assert stamp != workspace.members_stamp([])
+ assert workspace.members_stamp([original_member, original_member]) == stamp
monkeypatch.setattr(workspace.paths, "repo_root", lambda: pytest.fail("implicit source discovery"))
monkeypatch.setattr(workspace, "enabled_member_dirs", lambda: pytest.fail("profile discovery"))
@@ -648,6 +656,15 @@ def test_explicit_workspace_preserves_seed_and_replays_copied_members(locked_pro
assert (original_member / "pyproject.toml").read_bytes() == before_member
recorded = tmp_path / "first" / "workspace"
recorded_lock = (recorded / "uv.lock").read_bytes()
+ import tomllib
+ document = tomllib.loads((recorded / "pyproject.toml").read_text())
+ assert document["project"] == tomllib.loads(project.read_text())["project"]
+ [relative] = document["tool"]["uv"]["workspace"]["members"]
+ copied = recorded / relative / "pyproject.toml"
+ assert copied.read_bytes() == before_member
+ assert copied.resolve().is_relative_to(recorded.resolve())
+ (original_member / "pyproject.toml").unlink()
+ assert workspace.members_stamp([original_member]) != stamp
# Repair replays recorded inputs, not today's edited source/plugins.
(original_member / "pyproject.toml").write_text("broken plugin TOML")
@@ -666,6 +683,51 @@ def test_explicit_workspace_preserves_seed_and_replays_copied_members(locked_pro
assert (recorded / "uv.lock").read_bytes() == recorded_lock
[email protected]("failure", ["facts", "missing-cfg", "restart"])
+def test_real_sync_retains_selection_until_commit(locked_project, tmp_path, monkeypatch, failure):
+ import importlib
+ import pm.extras as extras
+ from pm import paths
+ from pm.lock import Facts
+ from hermes_cli.runtime_paths import selected_venv
+
+ source, uv, env = locked_project
+ monkeypatch.setattr(paths, "repo_root", lambda: source)
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kw: (uv, Path(sys.executable)))
+ engine = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)
+ engine.sync_venv(["chosen"], plugin_dirs=[], explicit=True)
+ old = selected_venv(source)
+ facts = paths.runtime_facts_path().read_bytes()
+ home = Path(os.environ["HERMES_HOME"])
+ config = home / "config.yaml"
+ config.write_text("plugins: {enabled: []}\nsecurity: {allow_lazy_installs: true}\n")
+ config_bytes = config.read_bytes()
+ if failure == "facts":
+ def refuse(*args, **kwargs):
+ raise OSError("facts disk full")
+ with monkeypatch.context() as fault:
+ fault.setattr(Facts, "record_state", refuse)
+ with pytest.raises(OSError, match="facts disk full"):
+ engine.sync_venv(["other"], plugin_dirs=[], explicit=True)
+ assert selected_venv(source) == old
+ assert paths.runtime_facts_path().read_bytes() == facts
+ elif failure == "missing-cfg":
+ (old / "pyvenv.cfg").unlink()
+ engine.sync_venv(["chosen"], plugin_dirs=[], explicit=True)
+ assert selected_venv(source) != old
+ assert (selected_venv(source) / "pyvenv.cfg").is_file()
+ else:
+ monkeypatch.setattr("pm.client.sync_venv", engine.sync_venv)
+ monkeypatch.setattr(extras, "available", lambda _: False)
+ with pytest.raises(engine.InstallError, match="restart"):
+ extras.ensure_import("other")
+ assert selected_venv(source) != old
+ assert "other_dep" not in sys.modules
+ assert old.is_dir()
+ assert config.read_bytes() == config_bytes
+
+
def test_live_apply_keeps_selection_on_failed_union(locked_project, tmp_path, monkeypatch):
from hermes_cli.runtime_paths import runtime_facts_path, selected_venv
from pm.lock import Facts
diff --git a/tests/pm/test_extras.py b/tests/pm/test_extras.py
index 0f5cec417c8..8bc5c3ce700 100644
--- a/tests/pm/test_extras.py
+++ b/tests/pm/test_extras.py
@@ -94,9 +94,6 @@ def synced(monkeypatch):
return calls
-def test_available_known_anchor_present():
- assert extras.available("web") is True # fastapi ships in this venv
-
def test_available_missing_module():
assert extras.available("no-such-extra-anywhere") is False
@@ -149,40 +146,22 @@ def test_ensure_import_propagates_install_error(monkeypatch):
extras.ensure_import("fal")
-def test_ensure_and_bind_binds_on_success(monkeypatch, synced):
- monkeypatch.setattr(extras, "available", lambda e: True)
- target: dict = {}
- ok = extras.ensure_and_bind("fal", lambda: {"NAME": 42}, target)
- assert ok is True and target["NAME"] == 42
-
-
-def test_ensure_and_bind_false_on_install_failure(monkeypatch):
- def boom(x=None):
- raise pm.InstallError("venv", "nope")
-
- monkeypatch.setattr(client, "sync_venv", boom)
- monkeypatch.setattr(extras, "available", lambda e: False)
- target: dict = {}
- assert extras.ensure_and_bind("fal", lambda: {"X": 1}, target) is False
- assert target == {}
-
-
-def test_ensure_and_bind_false_on_import_failure(monkeypatch, synced):
- monkeypatch.setattr(extras, "available", lambda e: True)
-
[email protected]("failure", [None, "install", "import"])
+def test_ensure_and_bind_preserves_target_on_failure(monkeypatch, failure):
+ monkeypatch.setattr(extras, "available", lambda _: failure != "install")
+ def sync(*args):
+ raise pm.InstallError("venv", "install refused")
+ monkeypatch.setattr(client, "sync_venv", sync)
def importer():
- raise ImportError("still broken")
+ if failure == "import":
+ raise ImportError("still broken")
+ return {"NAME": 42}
+ target = {"existing": "kept"}
+ assert extras.ensure_and_bind("fal", importer, target) is (failure is None)
+ assert target == ({"existing": "kept", "NAME": 42} if failure is None else {"existing": "kept"})
- assert extras.ensure_and_bind("fal", importer, {}) is False
-def test_package_exports_preserve_availability_and_noop_install(monkeypatch, synced):
- monkeypatch.setitem(sys.modules, "some_new_thing", SimpleNamespace())
- assert pm.available("some-new-thing") == extras.available("some-new-thing") is True
- assert pm.available("no-such-extra-anywhere") == extras.available("no-such-extra-anywhere") is False
- pm.ensure_import("some-new-thing")
- assert synced == []
-
def test_every_anchor_extra_exists_in_pyproject():
"""Contract: ANCHORS maps real pyproject extras (no orphaned names)."""
diff --git a/tests/pm/test_features.py b/tests/pm/test_features.py
index 00118f0d617..37acaa1c8bb 100644
--- a/tests/pm/test_features.py
+++ b/tests/pm/test_features.py
@@ -22,19 +22,15 @@ def rooted(tmp_path, monkeypatch):
def test_write_then_read_roundtrip(rooted):
+ assert feats.read_features() is None
path = feats.write_features(["web", "acp", "web"])
assert path.is_file()
got = feats.read_features()
assert got == ["acp", "web"] # sorted, deduped
-
-
-def test_read_features_none_when_absent(rooted):
+ path.write_text("{ not json", encoding="utf-8")
assert feats.read_features() is None
-def test_read_features_none_on_garbage(rooted):
- feats.features_path().write_text("{ not json", encoding="utf-8")
- assert feats.read_features() is None
def test_features_path_in_bundle_uses_payload_root(rooted):
@@ -55,6 +51,13 @@ def test_sync_venv_refuses_outside_frozen_extras(rooted, monkeypatch):
with pytest.raises(InstallError) as exc:
ensure_mod.sync_venv(["slack"], explicit=True)
assert "frozen" in str(exc.value) or "outside" in str(exc.value)
+ from pm import receipt
+ saved = receipt.latest()
+ assert saved["refusal"]["code"] == "lazy-install"
+ assert saved["outcome"] == "failed" and saved["exit_code"] != 0
+ assert saved["steps"][-1]["ok"] is False
+ assert "slack" in saved["steps"][-1]["detail"]
+ assert "hermes pm install" in saved["steps"][-1]["detail"]
def test_sync_venv_allows_frozen_extras_when_lazy_off(rooted, monkeypatch):
diff --git a/tests/pm/test_install_default_closure.py b/tests/pm/test_install_default_closure.py
index cc1de5807b6..c6f3a2a6e18 100644
--- a/tests/pm/test_install_default_closure.py
+++ b/tests/pm/test_install_default_closure.py
@@ -18,9 +18,6 @@ import importlib
import pytest
import pm.cli
-from pm.lock import Lockfile
-from pm.paths import repo_root
-from pm.registry import get_package
@pytest.fixture()
@@ -40,29 +37,13 @@ def install_spy(monkeypatch):
return calls
-def test_default_closure_includes_the_boot_interpreter(install_spy) -> None:
- assert pm.cli.cmd_install(argparse.Namespace(names=None)) == 0
-
- lockfile = Lockfile(repo_root() / "pm" / "lock.json")
- names = install_spy["names"]
- # The launchers' interpreter must be requested...
- assert "python" in names
- # ...through the existing authorities: it is pinned in pm/lock.json and
- # defined in the package registry — no parallel hand-written list here.
- assert "python" in lockfile.names()
- get_package("python")
- # ...and the rest of the root closure is unchanged (non-optional packages).
- expected = {
- n for n in lockfile.names() if not get_package(n).optional
- } | {"python"}
- assert set(names) == expected
-
-
-def test_default_closure_still_syncs_the_venv_with_all_extras(install_spy) -> None:
+def test_default_closure_includes_the_boot_interpreter(install_spy):
assert pm.cli.cmd_install(argparse.Namespace(names=None)) == 0
+ assert "python" in install_spy["names"]
assert install_spy["sync_extras"] == ["all"]
+
def test_explicit_names_pass_through_untouched(install_spy) -> None:
assert pm.cli.cmd_install(argparse.Namespace(names=["npm", "ripgrep"])) == 0
assert install_spy["names"] == ["npm", "ripgrep"]
diff --git a/tests/pm/test_install_download_control.py b/tests/pm/test_install_download_control.py
index d9622cf31dd..c8405c7b5e0 100644
--- a/tests/pm/test_install_download_control.py
+++ b/tests/pm/test_install_download_control.py
@@ -18,6 +18,7 @@ from pm.downloader import DownloadPaused
from pm.ensure import ensure, stage_only
from pm.lock import Facts, Lockfile
from pm.package import Package
+from pm.store import tree_digest
from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
@@ -46,7 +47,8 @@ def realize(request):
return partial(stage_only, target="linux-arm64-bionic")
-def test_install_pause_preserves_archives_and_resumes_the_same_pin(tmp_path, monkeypatch, dl_server, realize):
[email protected]("cached", [False, True])
+def test_install_pause_preserves_archives_and_resumes_the_same_pin(tmp_path, monkeypatch, dl_server, realize, cached):
root = tmp_path / "store"
lock_path = tmp_path / "lock.json"
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
@@ -63,14 +65,32 @@ def test_install_pause_preserves_archives_and_resumes_the_same_pin(tmp_path, mon
lock = Lockfile(lock_path)
lock.set_pin(ComponentPackage.name, "1", {"any": pins})
lock.save()
+ if cached:
+ with pm.Store(root).scratch() as scratch:
+ pm.Store(root).fetch(pins[0]["url"], pins[0]["sha256"], scratch)
+ other = root / ("fetch-" + "f" * 64) / "other.zip"
+ other.parent.mkdir(parents=True, exist_ok=True)
+ other.write_bytes(b"another install")
+ unrelated = paths.partials_root() / "unrelated.part"
+ unrelated.parent.mkdir(parents=True, exist_ok=True)
+ unrelated.write_bytes(b"in progress")
pause = threading.Event()
+ ticks, stages = [], []
def progress(stage, done, total, label):
+ stages.append((stage, done, total, label))
if stage == "download" and label == "2/2" and len(payloads[0]) < done < total:
pause.set()
with pytest.raises(DownloadPaused):
- realize(ComponentPackage.name, progress=progress, pause_event=pause)
+ realize(ComponentPackage.name, progress=progress, pause_event=pause,
+ download_progress=lambda done, total, ranges: ticks.append((done, total, ranges)))
+ expected = sum(map(len, payloads))
+ assert ticks and all(total == expected for _, total, _ in ticks)
+ assert ticks[0][0] == (len(payloads[0]) if cached else 0)
+ assert all(sum(end - start for rows in ranges.values() for start, end in rows) == done
+ for done, _, ranges in ticks)
+ assert [done for done, _, _ in ticks] == sorted(done for done, _, _ in ticks)
assert Facts(paths.facts_path()).get(ComponentPackage.name) is None
assert list(paths.partials_root().glob("*.ranges"))
first_requests = [request for request in RangeHandler.ranges_seen if request[0] == "/component-0.zip"]
@@ -78,50 +98,31 @@ def test_install_pause_preserves_archives_and_resumes_the_same_pin(tmp_path, mon
assert (root / f"fetch-{pins[0]['sha256']}").is_dir()
pause.clear()
- result = realize(ComponentPackage.name, pause_event=pause)
+ stages.clear()
+ result = realize(ComponentPackage.name, pause_event=pause,
+ progress=lambda *args: stages.append(args),
+ download_progress=lambda done, total, ranges: ticks.append((done, total, ranges)))
+ assert ticks[-1][:2] == (expected, expected)
fact = Facts(paths.facts_path()).get(ComponentPackage.name)
if fact is None:
entry = result
- assert json.loads((entry / ".pm-stage-pin.json").read_text())["sha256"] == [pin["sha256"] for pin in pins]
+ assert json.loads((entry / ".pm-stage-pin.json").read_text()) == {
+ "target": "linux-arm64-bionic", "sha256": [pin["sha256"] for pin in pins],
+ }
+ assert not paths.facts_path().exists()
else:
entry = root / fact["entry"]
assert fact["artifacts"] == [pin["sha256"] for pin in pins]
+ assert fact["digest"] == tree_digest(entry)
+ assert not (entry / ".pm-stage-pin.json").exists()
for name, body in contents.items():
assert (entry / name).read_bytes() == body
assert [request for request in RangeHandler.ranges_seen if request[0] == "/component-0.zip"] == first_requests
- assert not list(paths.partials_root().glob("*.part"))
- assert not list(root.glob("fetch-*"))
-
-
-def test_install_progress_covers_all_archives_including_cache(tmp_path, monkeypatch, dl_server, realize):
- root = tmp_path / "store"
- lock_path = tmp_path / "lock.json"
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- monkeypatch.setattr(paths, "store_root", lambda: root)
- monkeypatch.setattr(paths, "lockfile_path", lambda: lock_path)
- monkeypatch.setitem(registry._packages, ComponentPackage.name, ComponentPackage())
- payloads = [archive({"engine.dat": b"engine"}), archive({"runtime.dll": b"runtime"})]
- pins = []
- for index, payload in enumerate(payloads):
- path = f"/component-{index}.zip"
- RangeHandler.payloads[path] = payload
- pins.append({"url": url(dl_server, path), "sha256": hashlib.sha256(payload).hexdigest()})
- lock = Lockfile(lock_path)
- lock.set_pin(ComponentPackage.name, "1", {"any": pins})
- lock.save()
- store = pm.Store(root)
- with store.scratch() as scratch:
- store.fetch(pins[0]["url"], pins[0]["sha256"], scratch)
- ticks = []
- stages = []
- realize(ComponentPackage.name,
- progress=lambda *args: stages.append(args),
- download_progress=lambda done, total, ranges: ticks.append((done, total, ranges)))
- expected = sum(map(len, payloads))
- assert ticks and all(total == expected for _, total, _ in ticks)
- assert ticks[0][0] == len(payloads[0])
- assert ticks[-1][0] == expected
- assert all(sum(end - start for rows in ranges.values() for start, end in rows) == done
- for done, _, ranges in ticks)
- assert [done for done, _, _ in ticks] == sorted(done for done, _, _ in ticks)
+ assert [label for stage, _, _, label in stages if stage == "unpack"] == ["1/2", "2/2"]
assert {stage for stage, *_ in stages} >= {"download", "unpack", "verify"}
+ assert list(paths.partials_root().glob("*.part")) == [unrelated]
+ assert list(root.glob("fetch-*")) == [other.parent]
+ assert other.read_bytes() == b"another install"
+ assert unrelated.read_bytes() == b"in progress"
+ RangeHandler.payloads.clear()
+ realize(ComponentPackage.name) # Warm reuse needs neither server nor archives.
diff --git a/tests/pm/test_installed_package.py b/tests/pm/test_installed_package.py
index 30c252644a3..fb2e7ae5593 100644
--- a/tests/pm/test_installed_package.py
+++ b/tests/pm/test_installed_package.py
@@ -6,7 +6,7 @@ import pm
from pm import paths
from pm.ensure import ensure
from pm.lock import Lockfile
-from tests.pm.test_pm_authority import pm_env, served # noqa: F401
+from tests.pm.test_pm_authority import core_env, pm_env, served # noqa: F401
def test_installed_lookup_prefers_current_pin_then_recorded_fallback(pm_env, tmp_path, monkeypatch):
diff --git a/tests/pm/test_network_retries.py b/tests/pm/test_network_retries.py
index 2335bdb1589..ea9d6333777 100644
--- a/tests/pm/test_network_retries.py
+++ b/tests/pm/test_network_retries.py
@@ -16,11 +16,10 @@ from pm.store import Store, current_target
from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
[email protected]("failure_phase", [
- "probe", "probe-disconnect", "probe-empty-body", "ranged", "single",
- "interrupted", "single-interrupted",
-])
[email protected]("install_path", ["install", "stage"])
[email protected]("failure_phase,install_path", [
+ (phase, "install") for phase in ("probe", "probe-disconnect", "probe-empty-body", "ranged", "single",
+ "interrupted", "single-interrupted")
+] + [("ranged", "stage")])
def test_install_recovers_from_transient_http_failure(tmp_path, dl_server, monkeypatch, failure_phase, install_path):
payload = io.BytesIO()
with zipfile.ZipFile(payload, "w") as archive:
diff --git a/tests/pm/test_no_lazy_deps.py b/tests/pm/test_no_lazy_deps.py
index 4f9e2f67d2d..cc2fc0661ab 100644
--- a/tests/pm/test_no_lazy_deps.py
+++ b/tests/pm/test_no_lazy_deps.py
@@ -74,82 +74,36 @@ def _track(root: Path, relpath: str, body: str) -> None:
)
-def test_clean_repo_passes(fixture_repo):
- result = _run_checker(fixture_repo)
- assert result.returncode == 0, result.stdout + result.stderr
- assert result.stdout.strip() == ""
-
-
- ("body", "lineno"),
- [
- ("from tools.lazy_deps import install_specs\n", 1),
- ("from tools import lazy_deps\n\nlazy_deps.ensure('x')\n", 1),
- ("from tools.lazy_deps.sub import x\n", 1),
- ("import tools.lazy_deps\n", 1),
- ("import tools.lazy_deps.submodule as s\n", 1),
- ("if True:\n from tools.lazy_deps import ensure\n", 2),
- ],
- ids=[
- "from-module",
- "from-parent",
- "from-dotted-child",
- "plain-import",
- "dotted-import",
- "nested",
- ],
-)
-def test_each_import_form_is_caught_with_exact_site(fixture_repo, body, lineno):
- _track(fixture_repo, "app.py", body)
- result = _run_checker(fixture_repo)
- assert result.returncode == 1, result.stdout + result.stderr
- assert f"app.py:{lineno}" in result.stdout
- assert "lazy_deps" in result.stdout
-
-
- ("relpath", "body", "lineno"),
- [
- ("tools/helper.py", "from . import lazy_deps\n\nlazy_deps.ensure('x')\n", 1),
- ("tools/helper.py", "from .lazy_deps import ensure\n", 1),
- ("tools/sub/mod.py", "from .. import lazy_deps\n", 1),
- ("tools/__init__.py", "from . import lazy_deps\n", 1),
- ],
- ids=["from-dot", "from-dot-module", "from-dotdot-in-subpackage", "pkg-init"],
-)
-def test_relative_import_resolved_inside_tools_is_caught(
- fixture_repo, relpath, body, lineno
-):
- """``from . import lazy_deps`` inside the tracked tools/ package IS an
- import of the deleted tools.lazy_deps module."""
+
[email protected]("relpath, body, code, site", [
+ ("app.py", "from tools.lazy_deps import install_specs\n", 1, "app.py:1"),
+ ("app.py", "from tools import lazy_deps\n", 1, "app.py:1"),
+ ("app.py", "from tools.lazy_deps.sub import x\n", 1, "app.py:1"),
+ ("app.py", "import tools.lazy_deps\n", 1, "app.py:1"),
+ ("app.py", "import tools.lazy_deps.submodule as s\n", 1, "app.py:1"),
+ ("app.py", "if True:\n from tools.lazy_deps import ensure\n", 1, "app.py:2"),
+ ("tools/helper.py", "from . import lazy_deps\n", 1, "tools/helper.py:1"),
+ ("tools/helper.py", "from .lazy_deps import ensure\n", 1, "tools/helper.py:1"),
+ ("tools/sub/mod.py", "from .. import lazy_deps\n", 1, "tools/sub/mod.py:1"),
+ ("tools/__init__.py", "from . import lazy_deps\n", 1, "tools/__init__.py:1"),
+ ("pkg/other.py", "from . import lazy_deps\n", 0, ""),
+ ("app.py", '# tools.lazy_deps\n"""tools.lazy_deps.ensure"""\nx=1\n', 0, ""),
+ ("broken.py", "def f(:\n", 2, "broken.py"),
+ ("app.py", "x = 1\n", 0, ""),
+])
+def test_checker_outcomes(fixture_repo, relpath, body, code, site):
_track(fixture_repo, "tools/__init__.py", "")
+ _track(fixture_repo, "pkg/__init__.py", "")
_track(fixture_repo, relpath, body)
result = _run_checker(fixture_repo)
- assert result.returncode == 1, result.stdout + result.stderr
- assert f"{relpath}:{lineno}" in result.stdout
+ assert result.returncode == code, result.stdout + result.stderr
+ assert site in result.stdout + result.stderr
+ if code == 0:
+ assert result.stdout.strip() == ""
-def test_relative_import_outside_tools_is_not_flagged(fixture_repo):
- """A same-package ``lazy_deps`` elsewhere is not the deleted module."""
- _track(fixture_repo, "pkg/__init__.py", "")
- _track(fixture_repo, "pkg/other.py", "from . import lazy_deps\n")
- result = _run_checker(fixture_repo)
- assert result.returncode == 0, result.stdout + result.stderr
-def test_comments_and_prose_are_not_imports(fixture_repo):
- _track(
- fixture_repo,
- "app.py",
- (
- "# tools.lazy_deps was deleted; see pm.extras\n"
- '\"\"\"Best-effort tools.lazy_deps.ensure: failures are swallowed.\"\"\"\n'
- "x = 1\n"
- ),
- )
- result = _run_checker(fixture_repo)
- assert result.returncode == 0, result.stdout + result.stderr
-
def test_untracked_files_are_not_scanned(fixture_repo):
# Untracked debris (not in the tracked inventory) must not be scanned.
@@ -189,37 +143,9 @@ def test_repo_without_tracked_python_fails_the_check(tmp_path):
assert "inventory" in (result.stdout + result.stderr).lower()
-def test_unparseable_tracked_file_fails_the_check(fixture_repo):
- # A tracked file that cannot be parsed is an error, not a skip: the
- # check must fail rather than silently scan a partial inventory.
- _track(fixture_repo, "broken.py", "def f(:\n")
- result = _run_checker(fixture_repo)
- assert result.returncode == 2, result.stdout + result.stderr
- assert "broken.py" in (result.stdout + result.stderr)
-
def test_deleted_tracked_files_are_not_live_source(fixture_repo):
_track(fixture_repo, "removed.py", "from tools import lazy_deps\n")
(fixture_repo / "removed.py").unlink()
result = _run_checker(fixture_repo)
assert result.returncode == 0, result.stdout + result.stderr
-
-
-def test_real_repo_invocation_stays_deterministic():
- """Drive the checker against THIS repo.
-
- Exit 0 = migration complete (stdout empty). Exit 1 = live offenders
- remain — output must be the deterministic exact-site list the
- lazy-deps-guard CI job blocks on (migration owned elsewhere; the
- fixture tests above, not this visibility check, are the red/green
- proof of the guard itself).
- """
- result = _run_checker(REPO_ROOT)
- assert result.returncode in (0, 1), result.stdout + result.stderr
- if result.returncode == 0:
- assert result.stdout.strip() == ""
- return
- for line in result.stdout.splitlines():
- path, lineno, rest = line.split(":", 2)
- assert path.endswith(".py") and lineno.isdigit()
- assert "lazy_deps" in rest
diff --git a/tests/pm/test_node_sidecar.py b/tests/pm/test_node_sidecar.py
index 2e3d915784b..4e973358f5c 100644
--- a/tests/pm/test_node_sidecar.py
+++ b/tests/pm/test_node_sidecar.py
@@ -5,7 +5,6 @@ import os
from pathlib import Path
import shutil
import shlex
-import subprocess
import pytest
@@ -88,21 +87,11 @@ def test_real_npm_uses_paired_node_with_empty_ambient_path(tmp_path, monkeypatch
assert not (tmp_path / "node_modules").exists()
assert dict(os.environ) == ambient
assert calls == [("npm", {"explicit": True})] * 2
+ (plugin / "package.json").write_text("{malformed")
+ reason = install_node_sidecar(plugin, explicit=True)
+ assert "exited" in reason and "JSON" in reason
-def test_npm_process_failure_is_reported(tmp_path, monkeypatch):
- (tmp_path / "package.json").write_text('{}')
- binary = tmp_path / ("npm.cmd" if os.name == "nt" else "npm")
- binary.write_text("process boundary fixture")
- binary.chmod(0o755)
- class FailedRunner:
- env = {"PATH": str(tmp_path)}
- def run(self, command, **kwargs):
- return subprocess.CompletedProcess(command, 1, "", "ERESOLVE dependency conflict")
- monkeypatch.setattr(pm, "ensure", lambda *args, **kwargs: FailedRunner())
- reason = install_node_sidecar(tmp_path, explicit=True)
- assert "exited 1" in reason and "ERESOLVE" in reason
-
def test_on_demand_sidecar_install_respects_lazy_refusal(tmp_path, monkeypatch):
(tmp_path / "package.json").write_text('{}')
diff --git a/tests/pm/test_npm_dist_tags.py b/tests/pm/test_npm_dist_tags.py
index 1d33d0ff34e..272d8579c62 100644
--- a/tests/pm/test_npm_dist_tags.py
+++ b/tests/pm/test_npm_dist_tags.py
@@ -1,69 +1,32 @@
-"""npm update discovery reads the tag endpoint, not the package history."""
-from __future__ import annotations
-
+"""npm metadata keeps escaped names, caller headers and retry policy."""
import json
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-import threading
-
from pm.packages import AgentBrowser, Npm
from pm.update import npm_dist_tags, resolve_package
+from tests.pm.test_update_request_reuse import upstream # noqa: F401
+from tests.pm._range_server import RangeHandler, dl_server # noqa: F401
-def test_tag_endpoint_drives_package_updates_and_preserves_escaped_names(monkeypatch):
+def test_tag_endpoint_drives_package_updates_and_preserves_escaped_names(upstream, monkeypatch):
from hermes_cli import urllib_security
-
+ calls, failures = upstream
tags = {
"/-/package/npm/dist-tags": {"latest": "2.3.4", "next": "3.0.0-beta.1"},
"/-/package/agent-browser/dist-tags": {"latest": "4.5.6"},
"/-/package/@scope%2Ftool/dist-tags": {},
}
- requests = []
-
- class Registry(BaseHTTPRequestHandler):
- def do_GET(self):
- requests.append((self.path, self.headers.get("User-Agent"), self.headers.get("Authorization")))
- if len(requests) == 1:
- self.send_error(503)
- return
- if self.path not in tags:
- self.send_error(404)
- return
- body = json.dumps(tags[self.path]).encode()
- self.send_response(200)
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- self.wfile.write(body)
-
- def log_message(self, format, *args):
- pass
-
- real_open = urllib_security.open_credentialed_url
- with ThreadingHTTPServer(("127.0.0.1", 0), Registry) as server:
- def loopback(request, **kwargs):
- # Route transport only; retain the production JSON reader, headers,
- # retry policy, and credential-safe opener.
- origin = "https://registry.npmjs.org"
- assert request.full_url.startswith(origin + "/")
- request.full_url = request.full_url.replace(origin, f"http://127.0.0.1:{server.server_port}", 1)
- return real_open(request, **kwargs)
-
- monkeypatch.setattr(urllib_security, "open_credentialed_url", loopback)
- monkeypatch.setenv("GH_TOKEN", "not-for-npm")
- monkeypatch.setenv("HF_TOKEN", "not-for-npm-either")
- thread = threading.Thread(target=server.serve_forever, daemon=True)
- thread.start()
- try:
- for package, version in [(Npm(), "2.3.4"), (AgentBrowser(), "4.5.6")]:
- decision = resolve_package(package, ["linux-x64"], locked="1.0.0")
- assert decision.version == version
- assert decision.changed
- assert npm_dist_tags("@scope%2Ftool") == {}
- finally:
- server.shutdown()
- thread.join(timeout=5)
-
- assert [path for path, _, _ in requests] == [
- "/-/package/npm/dist-tags", "/-/package/npm/dist-tags",
- "/-/package/agent-browser/dist-tags", "/-/package/@scope%2Ftool/dist-tags",
- ]
- assert all(agent == "hermes-pm" and auth is None for _, agent, auth in requests)
+ RangeHandler.payloads.update({path: json.dumps(value).encode() for path, value in tags.items()})
+ failures["/-/package/npm/dist-tags"] = [503]
+ original = urllib_security.open_credentialed_url
+ def open_registry(request, **kwargs):
+ assert request.full_url.startswith("https://registry.npmjs.org/")
+ assert request.get_header("User-agent") == "hermes-pm"
+ return original(request, **kwargs)
+ monkeypatch.setattr(urllib_security, "open_credentialed_url", open_registry)
+ monkeypatch.setenv("GH_TOKEN", "not-for-npm")
+ monkeypatch.setenv("HF_TOKEN", "not-for-npm-either")
+ for package, version in [(Npm(), "2.3.4"), (AgentBrowser(), "4.5.6")]:
+ decision = resolve_package(package, ["linux-x64"], locked="1.0.0")
+ assert decision.version == version and decision.changed
+ assert npm_dist_tags("@scope%2Ftool") == {}
+ assert calls == [("/-/package/npm/dist-tags", None), ("/-/package/npm/dist-tags", None),
+ ("/-/package/agent-browser/dist-tags", None), ("/-/package/@scope%2Ftool/dist-tags", None)]
diff --git a/tests/pm/test_plugin_survival_contract.py b/tests/pm/test_plugin_survival_contract.py
index 696038a952a..e5fc70d062f 100644
--- a/tests/pm/test_plugin_survival_contract.py
+++ b/tests/pm/test_plugin_survival_contract.py
@@ -51,9 +51,7 @@ def _uv_available() -> bool:
return shutil.which("uv") is not None
-# ---------------------------------------------------------------------------
# 1. Sidecar with no root dependency surface never joins the union
-# ---------------------------------------------------------------------------
def test_sidecar_no_root_pyproject_excludes_nested_and_external(tmp_path, monkeypatch):
"""The mnemosyne-wrapper shape: plugin root has ONLY plugin.yaml +
@@ -98,9 +96,7 @@ def test_sidecar_no_root_pyproject_excludes_nested_and_external(tmp_path, monkey
assert all("runtime" not in str(p) for p in members)
-# ---------------------------------------------------------------------------
# 2. Conflict through the PUBLIC admission path: refused, preserved, retry
-# ---------------------------------------------------------------------------
def _local_conflict_members(home: Path) -> tuple[Path, Path, Path, Path]:
"""plug-a and plug-b both need a local project named sharedlib, but
@@ -197,6 +193,14 @@ def test_conflicting_candidate_refused_unenabled_and_unimported(admission_env):
working = selected_venv(tmp_path / "core")
config_before = (home / "config.yaml").read_bytes()
tree_before = {p: sorted(str(f) for f in p.rglob("*")) for p in (plug_a, plug_b)}
+ wrapper = home / "plugins/mnemosyne-wrapper"
+ wrapper.mkdir()
+ marker = wrapper / "mnemosyne-wrapper.json"
+ marker.write_bytes(b'{"wrapper":true}\n')
+ sidecar = tmp_path / "external-sidecar"
+ subprocess.run([shutil.which("uv"), "venv", "--python", sys.executable, str(sidecar)], check=True, capture_output=True, timeout=60)
+ sidecar_python = sidecar / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ before = marker.read_bytes()
with pytest.raises(admission.AdmissionRefused) as excinfo:
admission.admit_plugin_set_change(
@@ -232,31 +236,6 @@ def test_conflicting_candidate_refused_unenabled_and_unimported(admission_env):
assert "plug-b" in flattened or "sharedlib" in flattened, (
"receipt must carry the conflict identity/reason"
)
-
-
[email protected](not _uv_available(), reason="uv not on PATH")
-def test_retry_after_conflict_enables_resolvable_candidate(admission_env):
- """The retry path: re-admitting ONLY the resolvable candidate through
- the same public admission commits config + environment together; the
- conflicting plugin stays unenabled (never imported)."""
- from hermes_cli import plugins_admission as admission
-
- tmp_path, home = admission_env
- plug_a, plug_b, *_ = _local_conflict_members(home)
-
- wrapper = home / "plugins/mnemosyne-wrapper"
- wrapper.mkdir()
- marker = wrapper / "mnemosyne-wrapper.json"
- marker.write_bytes(b'{"wrapper":true}\n')
- sidecar = tmp_path / "external-sidecar"
- subprocess.run([shutil.which("uv"), "venv", "--python", sys.executable, str(sidecar)], check=True, capture_output=True, timeout=60)
- sidecar_python = sidecar / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
- before = marker.read_bytes()
- with pytest.raises(admission.AdmissionRefused):
- admission.admit_plugin_set_change(
- {"plug-a", "plug-b"}, set(), active_plugins_dir=home / "plugins"
- )
-
# retry: drop the conflicting candidate, keep the good one
admission.admit_plugin_set_change(
{"plug-a"}, set(), active_plugins_dir=home / "plugins"
@@ -283,10 +262,6 @@ def test_retry_after_conflict_enables_resolvable_candidate(admission_env):
subprocess.run([str(sidecar_python), "-c", "import sys; assert sys.prefix != sys.base_prefix"], check=True, timeout=30)
-# ---------------------------------------------------------------------------
-# 4. Active context home propagates to wrapper subprocess launches
-# ---------------------------------------------------------------------------
-
def test_active_context_home_exported_to_wrapper_subprocess(monkeypatch, tmp_path):
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
from tools.environments.local import build_subprocess_env
diff --git a/tests/pm/test_plugins_state.py b/tests/pm/test_plugins_state.py
index 4f0e8b226ee..023aabd0c3f 100644
--- a/tests/pm/test_plugins_state.py
+++ b/tests/pm/test_plugins_state.py
@@ -90,13 +90,6 @@ def test_missing_config_parser_is_not_an_empty_plugin_selection(homes, monkeypat
assert (default_home / "config.yaml").read_bytes() == before
-def test_enabled_list_preserves_config_order(homes):
- default_home, _ = homes
- # NOT alphabetical: recency order must survive the read
- _write_config(default_home, ["z-first-enabled", "a-second"])
- by_root = pstate.enabled_plugins_ordered()
- assert by_root[default_home / "plugins"] == ["z-first-enabled", "a-second"]
-
@pytest.mark.parametrize("content", ["{ not yaml", "[]", "plugins: wrong", "plugins:\n enabled: wrong", "memory: wrong"])
def test_enabled_read_refuses_invalid_existing_config(homes, content):
@@ -116,49 +109,42 @@ def test_empty_config_is_an_explicit_empty_selection(homes, content):
assert pstate.enabled_plugins_ordered() == {}
-def test_active_memory_provider_joins_union(homes, tmp_path):
- """The mnemosyne path: a provider installed via memory.provider (not
- plugins.enabled) must join the union — deps ride the lock either way."""
- default_home, _ = homes
- provider_dir = default_home / "plugins" / "mnemosyne-like"
- provider_dir.mkdir(parents=True)
- (provider_dir / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
[email protected]("enabled, provider, exists, expected", [
+ (["z-first", "a-second"], "provider", True, ["z-first", "a-second", "provider"]),
+ (["provider"], "provider", True, ["provider"]),
+ ([], "ghost", False, []),
+])
+def test_memory_provider_joins_ordered_selection(homes, enabled, provider, exists, expected):
import hermes_yaml as yaml
-
- with (default_home / "config.yaml").open("w", encoding="utf-8") as f:
- yaml.safe_dump(
- {"plugins": {"enabled": ["regular-plug"]},
- "memory": {"provider": "mnemosyne-like"}},
- f,
- )
-
+ home, sibling = homes
+ if exists:
+ (home / "plugins" / provider).mkdir(parents=True)
+ (home / "config.yaml").write_text(yaml.safe_dump({"plugins": {"enabled": enabled}, "memory": {"provider": provider}}))
+ _write_config(sibling, ["sibling"])
by_root = pstate.enabled_plugins_ordered()
- assert by_root[default_home / "plugins"] == ["regular-plug", "mnemosyne-like"]
-
+ assert by_root.get(home / "plugins", []) == expected
+ assert by_root[sibling / "plugins"] == ["sibling"]
-def test_memory_provider_without_dir_is_skipped(homes):
- """memory.provider set but no plugin dir on disk — not a member."""
- default_home, _ = homes
- import hermes_yaml as yaml
- with (default_home / "config.yaml").open("w", encoding="utf-8") as f:
- yaml.safe_dump({"memory": {"provider": "ghost-provider"}}, f)
-
- assert pstate.enabled_plugins_ordered() == {}
-
-
-def test_memory_provider_already_enabled_not_duplicated(homes):
- default_home, _ = homes
- (default_home / "plugins" / "dual").mkdir(parents=True)
- import hermes_yaml as yaml
+def test_member_discovery_uses_real_enabled_config(homes):
+ from pm.workspace import enabled_member_dirs
+ home, _ = homes
+ manifests = {
+ "modern/pyproject.toml": "[project]\n",
+ "legacy/plugin.yaml": 'name: legacy\npip_dependencies: ["requests>=2"]\n',
+ "plain/plugin.yaml": "name: plain\n",
+ "orphan/pyproject.toml": "[project]\n",
+ }
+ for relative, body in manifests.items():
+ path = home / "plugins" / relative
+ path.parent.mkdir(parents=True)
+ path.write_text(body)
+ _write_config(home, ["legacy", "modern", "plain"])
+ assert enabled_member_dirs() == [home / "plugins/legacy", home / "plugins/modern"]
+ _write_config(home, [])
+ assert enabled_member_dirs() == []
- with (default_home / "config.yaml").open("w", encoding="utf-8") as f:
- yaml.safe_dump(
- {"plugins": {"enabled": ["dual"]}, "memory": {"provider": "dual"}}, f
- )
- by_root = pstate.enabled_plugins_ordered()
- assert by_root[default_home / "plugins"] == ["dual"] # once, not twice
def test_read_parses_config_once_per_home(homes, monkeypatch):
diff --git a/tests/pm/test_pm_authority.py b/tests/pm/test_pm_authority.py
index 6aafe94b21f..07bf3f9f6d9 100644
--- a/tests/pm/test_pm_authority.py
+++ b/tests/pm/test_pm_authority.py
@@ -18,119 +18,38 @@ import pytest
import pm.paths as paths
import pm.registry as registry
from pm.lock import Facts, Lockfile
-from pm.package import Package
-from pm.packages import BinaryPackage
from pm.store import Store, current_target, tree_digest
from tests.pm._fixtures import make_tar, served as served
-
-
-class FakeTool(BinaryPackage):
- name = "faketool"
- probe_version = False
- binary_rel = {"win32": "bin/faketool", "posix": "bin/faketool"}
-
- def fetch_url(self, version, target):
- return f"{FakeTool.base_url}/{self.name}-{version}.tar.gz"
+from tests.pm.test_pm_core import FakeTool, pm_env as core_env # noqa: F401
@pytest.fixture
-def pm_env(tmp_path, served, monkeypatch):
- docroot, base_url = served
- runtime = tmp_path / "runtime"
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))
- monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)
- import importlib
-
- ensure_mod = importlib.import_module("pm.ensure")
- monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)
-
- saved = dict(registry._packages)
- registry._packages.clear()
- registry._packages[FakeTool.name] = FakeTool()
- FakeTool.base_url = base_url
-
- lock_dir = tmp_path / "repo-lock"
- lock_dir.mkdir()
- lockfile_path = lock_dir / "lock.json"
- monkeypatch.setattr(paths, "lockfile_path", lambda: lockfile_path)
-
- name, digest = make_tar(docroot, "faketool-1.0.tar.gz", {"bin/faketool": "#!x"})
- lockfile = Lockfile(lockfile_path)
- lockfile.set_pin(
- "faketool", "1.0",
- {"any": {"url": f"{base_url}/faketool-1.0.tar.gz", "sha256": digest}},
- )
- lockfile.save()
-
- yield {
- "lockfile_path": lockfile_path,
- "runtime": runtime,
- "docroot": docroot,
- "base_url": base_url,
- "digest": digest,
- "tmp_path": tmp_path,
- "monkeypatch": monkeypatch,
- }
-
- registry._packages.clear()
- registry._packages.update(saved)
-
-
-def _pin(env, name: str, version: str, digest: str) -> None:
- lockfile = Lockfile(env["lockfile_path"])
- url = f"{env['base_url']}/{name}-{version}.tar.gz"
- lockfile.set_pin(name, version, {"any": {"url": url, "sha256": digest}})
- lockfile.save()
-
-
-# ── item 1: digest-bound facts ────────────────────────────────────────
+def pm_env(core_env, tmp_path, monkeypatch):
+ lock, runtime, docroot, base_url = core_env
+ return {"lockfile_path": lock, "runtime": runtime, "docroot": docroot,
+ "base_url": base_url, "tmp_path": tmp_path, "monkeypatch": monkeypatch,
+ "digest": Lockfile(lock).artifacts("faketool", current_target())[0]["sha256"]}
@pytest.mark.parametrize("route", ["install", "stage"])
-def test_realization_reports_ordered_multi_archive_progress(pm_env, monkeypatch, route):
- from pm.ensure import ensure, stage_only
-
- env = pm_env
- monkeypatch.setattr(registry._packages["faketool"], "flatten", False)
- artifacts = []
- for name, files in [("tool.tar.gz", {"bin/faketool": "#!tool"}),
- ("data.tar.gz", {"share/data": "auxiliary"})]:
- _, digest = make_tar(env["docroot"], name, files)
- artifacts.append({"url": f"{env['base_url']}/{name}", "sha256": digest})
- lock = Lockfile(env["lockfile_path"])
- lock.set_pin("faketool", "1.0", {"any": artifacts})
- lock.save()
- events = []
- progress = lambda stage, done, total, label: events.append((stage, done, total, label))
- if route == "install":
- ensure("faketool", explicit=True, base_env={}, progress=progress)
- fact = Facts(paths.facts_path()).get("faketool")
- entry = paths.store_root() / fact["entry"]
- assert fact["artifacts"] == [artifact["sha256"] for artifact in artifacts]
- assert fact["digest"] == tree_digest(entry)
- assert not (entry / ".pm-stage-pin.json").exists()
- else:
- entry = stage_only("faketool", "linux-arm64-bionic", progress=progress)
- assert json.loads((entry / ".pm-stage-pin.json").read_text()) == {
- "target": "linux-arm64-bionic", "sha256": [artifact["sha256"] for artifact in artifacts],
- }
- assert not paths.facts_path().exists()
- assert (entry / "bin/faketool").read_text() == "#!tool"
- assert (entry / "share/data").read_text() == "auxiliary"
- assert [label for stage, _, _, label in events if stage == "unpack"] == ["1/2", "2/2"]
- assert any(stage == "verify" for stage, _, _, _ in events)
- assert not list(paths.store_root().glob("fetch-*"))
-
-
-def test_same_version_different_sha_is_not_installed_and_repaired(pm_env):
+def test_same_version_different_sha_is_not_installed_and_repaired(pm_env, caplog, route):
"""The witness: same version, different artifact sha. Version/path
matching cannot see this; identity matching must — check() reports
it and ensure() replaces the entry bytes."""
from pm.ensure import check, ensure, is_installed
env = pm_env
- ensure("faketool", base_env={})
- assert is_installed("faketool")
+ from pm.ensure import stage_only
+ realize = (lambda: ensure("faketool", explicit=True, base_env={})) if route == "install" else (
+ lambda: stage_only("faketool", "linux-arm64-bionic"))
+ realize()
+ if route == "install":
+ assert is_installed("faketool")
+ else:
+ entry = realize()
+ (entry / "sentinel").write_text("published")
+ assert realize() == entry
+ assert (entry / "sentinel").read_text() == "published"
_, digest_b = make_tar(env["docroot"], "faketool-1.0-b.tar.gz", {"bin/faketool": "#!B"})
# Same VERSION, different archive (different url + sha) — the
@@ -141,10 +60,19 @@ def test_same_version_different_sha_is_not_installed_and_repaired(pm_env):
{"any": {"url": f"{env['base_url']}/faketool-1.0-b.tar.gz", "sha256": digest_b}},
)
lockfile.save()
+ if route == "stage":
+ assert realize() == entry
+ assert (entry / "bin/faketool").read_bytes() == b"#!B"
+ assert not (entry / "sentinel").exists()
+ assert realize() == entry
+ assert not paths.facts_path().exists()
+ return
assert not is_installed("faketool")
assert check() == ["faketool: not installed or outdated"]
- runner = ensure("faketool", base_env={})
+ with caplog.at_level(logging.INFO, logger="pm.ensure"):
+ realize()
+ assert any("1.0" in r.message and env["digest"][:12] in r.message for r in caplog.records)
assert is_installed("faketool")
fact = Facts(paths.facts_path()).get("faketool")
entry_bin = paths.store_root() / fact["entry"] / "bin" / "faketool"
@@ -158,8 +86,8 @@ def test_same_version_different_sha_is_not_installed_and_repaired(pm_env):
@pytest.mark.parametrize("matching_fact", [False, True])
[email protected]("damage", ["missing-binary", "changed-bytes", "entry-is-file"])
-def test_install_repairs_corrupt_entry_from_verified_archive(pm_env, matching_fact, damage):
[email protected]("damage", ["missing-binary", "changed-bytes", "entry-is-file", "missing-entry"])
+def test_install_repairs_corrupt_entry_from_verified_archive(pm_env, matching_fact, damage, caplog):
from pm.cli import cmd_doctor
from pm.ensure import ensure
@@ -174,25 +102,28 @@ def test_install_repairs_corrupt_entry_from_verified_archive(pm_env, matching_fa
binary.write_bytes(b"corrupted")
else:
shutil.rmtree(entry)
- entry.write_bytes(b"not a directory")
+ if damage == "entry-is-file":
+ entry.write_bytes(b"not a directory")
if not matching_fact:
data = json.loads(facts_path.read_text())
data["packages"]["faketool"].pop("artifacts")
facts_path.write_text(json.dumps(data))
- ensure("faketool", explicit=True, base_env={})
-
+ with caplog.at_level(logging.INFO, logger="pm.ensure"):
+ ensure("faketool", explicit=True, base_env={})
+ assert any("repair: faketool re-realized" in r.message for r in caplog.records)
assert binary.read_bytes() == b"#!x"
assert cmd_doctor(None) == 0
assert Facts(facts_path).get("faketool")["digest"] == tree_digest(binary.parent.parent)
[email protected](("route", "replacement"), [
[email protected]("route,failure", [
(route, failure) for route in ("install", "stage")
- for failure in ("invalid", "publish-failure", "post-publish-invalid", "interrupted", "facts-failure")
- if route == "install" or failure != "facts-failure"
+ for failure in ("invalid", "fetch", "unpack", "verify", "publish", "published-verify", "interrupt", "facts")
+ if route == "install" or failure != "facts"
])
-def test_failed_replacement_preserves_entry_and_facts(pm_env, monkeypatch, route, replacement):
[email protected]("initial", [False, True], ids=["replacement", "first-install"])
+def test_failed_replacement_preserves_entry_and_facts(pm_env, monkeypatch, route, initial, failure):
from functools import partial
from pm.ensure import ensure, stage_only
from pm.package import InstallError
@@ -201,47 +132,78 @@ def test_failed_replacement_preserves_entry_and_facts(pm_env, monkeypatch, route
target = current_target() if route == "install" else "linux-arm64-bionic"
realize = partial(ensure, "faketool", explicit=True, base_env={}) if route == "install" else partial(
stage_only, "faketool", target)
- realize()
+ if not initial:
+ realize()
facts_path = paths.facts_path()
old_facts = facts_path.read_bytes() if facts_path.exists() else None
entry = paths.store_root() / FakeTool().store_entry("1.0", target)
marker = entry / ".pm-stage-pin.json"
old_marker = marker.read_bytes() if marker.exists() else None
- binary = entry / "bin/faketool"
- files = {"bin/unrelated": "bad layout"} if replacement == "invalid" else {"bin/faketool": "#!new"}
+ files = {"bin/unrelated": "bad layout"} if failure == "invalid" else {"bin/faketool": "#!new"}
_, digest = make_tar(env["docroot"], "replacement.tar.gz", files)
+ _, extra_digest = make_tar(env["docroot"], "data.tar.gz", {"share/data": "second archive"})
lockfile = Lockfile(env["lockfile_path"])
- lockfile.set_pin("faketool", "1.0", {"any": {
- "url": f"{env['base_url']}/replacement.tar.gz", "sha256": digest,
- }})
+ lockfile.set_pin("faketool", "1.0", {"any": [
+ {"url": f"{env['base_url']}/replacement.tar.gz", "sha256": digest},
+ {"url": f"{env['base_url']}/data.tar.gz", "sha256": extra_digest},
+ ]})
lockfile.save()
- if replacement in ("publish-failure", "post-publish-invalid", "interrupted"):
- original = Store.publish
-
- def fail_package_publish(self, staged, name):
- if name != entry.name:
- return original(self, staged, name)
- if replacement == "interrupted":
- raise KeyboardInterrupt()
- if replacement == "post-publish-invalid":
- published = original(self, staged, name)
- (published / "bin/faketool").unlink()
- return published
- raise OSError("replacement publication failed")
-
- monkeypatch.setattr(Store, "publish", fail_package_publish)
- elif replacement == "facts-failure":
- def fail_record(*args, **kwargs):
- raise OSError("facts write failed")
- monkeypatch.setattr(Facts, "record", fail_record)
-
- expected_error = KeyboardInterrupt if replacement == "interrupted" else InstallError
- with pytest.raises(expected_error):
- realize()
-
- assert binary.read_bytes() == b"#!x"
+ package = registry._packages["faketool"]
+
+ def fail(*args, **kwargs):
+ if failure == "interrupt":
+ raise KeyboardInterrupt()
+ if failure in ("publish", "facts"):
+ raise OSError("injected failure")
+ raise InstallError("faketool", "injected failure")
+
+ with monkeypatch.context() as fault:
+ if failure in ("publish", "published-verify", "interrupt"):
+ original = Store.publish
+ def publish(self, staged, name):
+ if name != entry.name:
+ return original(self, staged, name)
+ if failure == "published-verify":
+ published = original(self, staged, name)
+ (published / "bin/faketool").unlink()
+ return published
+ fail()
+ fault.setattr(Store, "publish", publish)
+ elif failure == "facts":
+ fault.setattr(Facts, "record", fail)
+ elif failure == "fetch":
+ fault.setattr(Store, "fetch_many", fail)
+ elif failure == "verify":
+ original_verify = package.verify
+ def verify(path, target):
+ if path != entry:
+ fail()
+ return original_verify(path, target)
+ fault.setattr(package, "verify", verify)
+ elif failure == "unpack":
+ original_unpack = package.unpack
+ def unpack(archive, staged, target):
+ original_unpack(archive, staged, target)
+ if (staged / "share/data").exists():
+ fail()
+ fault.setattr(package, "unpack", unpack)
+ with pytest.raises(KeyboardInterrupt if failure == "interrupt" else InstallError):
+ realize()
+ if not initial:
+ assert (entry / "bin/faketool").read_bytes() == b"#!x"
assert (facts_path.read_bytes() if facts_path.exists() else None) == old_facts
- assert (marker.read_bytes() if marker.exists() else None) == old_marker
+ if not initial:
+ assert (marker.read_bytes() if marker.exists() else None) == old_marker
+ archives = [paths.store_root() / f"fetch-{sha}" for sha in (digest, extra_digest)]
+ if failure != "fetch":
+ assert all(archive.is_dir() for archive in archives)
+ if failure not in ("invalid", "fetch"):
+ for filename in ("replacement.tar.gz", "data.tar.gz"):
+ (env["docroot"] / filename).unlink()
+ realize() # Publication failures must be retryable from verified cached bytes.
+ assert (entry / "bin/faketool").read_bytes() == b"#!new"
+ assert (entry / "share/data").read_bytes() == b"second archive"
+ assert not any(archive.exists() for archive in archives)
@pytest.mark.parametrize("route", ["install", "stage"])
@@ -339,7 +301,6 @@ def test_failed_restore_preserves_both_interrupted_versions(pm_env, monkeypatch)
def test_fetch_cache_verification_is_owned_by_downloader(pm_env, monkeypatch, poisoned):
"""Real cached bytes are checked in planning and under the partial lock;
corrupt bytes must be replaced, without an extra Store-layer hash."""
- import pm.downloader as downloader
import pm.store as store_mod
env = pm_env
@@ -349,33 +310,22 @@ def test_fetch_cache_verification_is_owned_by_downloader(pm_env, monkeypatch, po
with store.scratch() as scratch:
first = store.fetch(url, digest, scratch)
assert sha_of(first) == digest
- size = first.stat().st_size
+
if poisoned:
first.write_bytes(b"poisoned")
- hashes = []
- for module, symbol in [(store_mod, "sha256_file"), (downloader, "_sha256_file")]:
- original = getattr(module, symbol)
-
- def counted(path, original=original, owner=module.__name__):
- hashes.append((owner, path.stat().st_size))
- return original(path)
-
- monkeypatch.setattr(module, symbol, counted)
-
+ monkeypatch.setattr(store_mod, "sha256_file", lambda *args: pytest.fail("Store rehashed downloader-verified bytes"))
with store.scratch() as scratch:
second = store.fetch(url, digest, scratch)
assert second == first
assert sha_of(second) == digest
- expected_sizes = [len(b"poisoned"), len(b"poisoned"), size] if poisoned else [size, size]
- assert hashes == [("pm.downloader", size) for size in expected_sizes]
def sha_of(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
-def test_legacy_fact_without_identity_is_not_installed(pm_env):
+def test_legacy_fact_without_identity_is_not_installed(pm_env, capsys):
"""Facts written before identity existed read back fine but are NOT
vouchable: installed() with identity returns False and forces one
reinstall."""
@@ -394,6 +344,9 @@ def test_legacy_fact_without_identity_is_not_installed(pm_env):
facts_path.write_text(json.dumps(data), encoding="utf-8")
assert not is_installed("faketool")
+ from pm.cli import cmd_doctor
+ assert cmd_doctor(None) == 1
+ assert "legacy fact: no recorded identity" in capsys.readouterr().out
# ensure() repairs it: reinstalls and records the full identity.
ensure("faketool", base_env={})
assert is_installed("faketool")
@@ -401,30 +354,22 @@ def test_legacy_fact_without_identity_is_not_installed(pm_env):
assert fact["artifacts"] == [env["digest"]]
-def test_doctor_flags_legacy_fact(pm_env, capsys):
- from pm.cli import cmd_doctor
+def test_unproven_entry_without_facts_is_rebuilt(pm_env):
from pm.ensure import ensure
-
- env = pm_env
- ensure("faketool", base_env={})
- facts_path = paths.facts_path()
- data = json.loads(facts_path.read_text(encoding="utf-8"))
- for key in ("target", "artifacts", "digest"):
- data["packages"]["faketool"].pop(key, None)
- facts_path.write_text(json.dumps(data), encoding="utf-8")
-
- assert cmd_doctor(None) == 1
- assert "legacy fact: no recorded identity" in capsys.readouterr().out
-
-
-# ── item 2: realized digest + doctor re-hash ──────────────────────────
+ entry = paths.store_root() / FakeTool().store_entry("1.0", current_target())
+ (entry / "bin").mkdir(parents=True)
+ (entry / "bin/faketool").write_bytes(b"unproven")
+ (entry / "sentinel").touch()
+ ensure("faketool", explicit=True)
+ assert (entry / "bin/faketool").read_bytes() == b"#!x"
+ assert not (entry / "sentinel").exists()
+ assert Facts(paths.facts_path()).get("faketool")["digest"] == tree_digest(entry)
def test_tree_digest_is_content_bound(pm_env):
"""Same content in different creation order digests identically; one
changed byte digests differently; a symlink contributes its link
TARGET TEXT, not the target's bytes."""
- import os
a = pm_env["tmp_path"] / "tree-a"
b = pm_env["tmp_path"] / "tree-b"
@@ -458,7 +403,6 @@ def test_doctor_flags_tampered_entry_bytes(pm_env, capsys):
from pm.cli import cmd_doctor
from pm.ensure import ensure
- env = pm_env
ensure("faketool", base_env={})
assert cmd_doctor(None) == 0
@@ -473,9 +417,6 @@ def test_doctor_flags_tampered_entry_bytes(pm_env, capsys):
assert cmd_doctor(None) == 0
-# ── item 4: adopt() verification gate ─────────────────────────────────
-
-
def _bundle_payload(env) -> Path:
"""Build a shipped payload the way cmd_bundle lays it out: a repo
snapshot carrying pm/lock.json, and a store whose facts.json holds
@@ -492,18 +433,6 @@ def _bundle_payload(env) -> Path:
return shipped_repo
-def test_adopt_adopts_intact_payload(pm_env):
- from pm.ensure import adopt
-
- _bundle_payload(pm_env)
- marker = paths.runtime_facts_path().parent / ".adopted"
- assert not marker.is_file()
- assert adopt() is True
- assert marker.is_file()
- # Idempotent: already adopted → False, marker untouched.
- assert adopt() is False
-
-
def test_adopt_refuses_on_missing_staged_binary(pm_env):
from pm.ensure import adopt
@@ -547,78 +476,6 @@ def test_adopt_refuses_when_fact_lacks_identity(pm_env):
assert not (paths.store_root().parent / ".adopted").is_file()
-# ── item 6: repair logging ────────────────────────────────────────────
-
-
-def test_gc_protects_in_flight_partials(pm_env):
- """gc sweeps the store root and the partials area, but partials an
- in-flight download still owns (fresh mtimes) survive; stale partials
- are swept."""
- from pm.cli import cmd_gc
-
- env = pm_env
- runtime = env["runtime"]
- runtime.mkdir(parents=True, exist_ok=True)
- partials = paths.partials_root()
- partials.mkdir(parents=True, exist_ok=True)
- fresh = partials / "abc.part"
- fresh.write_bytes(b"x")
- stale = partials / "old.part"
- stale.write_bytes(b"y")
- import os
- import time
-
- old = time.time() - 7 * 3600 # beyond the 6h gc grace window
- os.utime(stale, (old, old))
-
- orphan = runtime / "orphan-9.9-nowhere"
- orphan.mkdir()
-
- cmd_gc(None)
- assert fresh.is_file()
- assert not stale.exists()
- assert not orphan.exists()
-
-
-def test_repair_log_line_on_reinstall(pm_env, caplog):
- """Established fact + missing entry + ensure() → one repair log line,
- and the install completes."""
- from pm.ensure import ensure, is_installed
-
- env = pm_env
- ensure("faketool", base_env={})
-
- fact = Facts(paths.facts_path()).get("faketool")
- shutil.rmtree(paths.store_root() / fact["entry"])
-
- with caplog.at_level(logging.INFO, logger="pm.ensure"):
- ensure("faketool", base_env={})
- assert is_installed("faketool")
- repairs = [r for r in caplog.records if "repair:" in r.getMessage()]
- assert any(
- "repair: faketool re-realized" in r.getMessage() for r in repairs
- )
-
-
-def test_repair_log_line_on_same_version_repin(pm_env, caplog):
- from pm.ensure import ensure
-
- env = pm_env
- ensure("faketool", base_env={})
- _, digest_b = make_tar(env["docroot"], "faketool-1.0-b.tar.gz", {"bin/faketool": "#!B"})
- lockfile = Lockfile(env["lockfile_path"])
- lockfile.set_pin(
- "faketool", "1.0",
- {"any": {"url": f"{env['base_url']}/faketool-1.0-b.tar.gz", "sha256": digest_b}},
- )
- lockfile.save()
-
- with caplog.at_level(logging.INFO, logger="pm.ensure"):
- ensure("faketool", base_env={})
- repairs = [r.getMessage() for r in caplog.records if "repair:" in r.getMessage()]
- assert any("1.0" in msg and env["digest"][:12] in msg for msg in repairs)
-
-
def test_tree_digest_ignores_pycache(pm_env, monkeypatch):
"""Bytecode caches are runtime state, not package bytes: the staged
python entry runs (uv venv/uv sync in a bundle build, first boot of a
diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.py
index ff830fad58f..b0400936809 100644
--- a/tests/pm/test_pm_core.py
+++ b/tests/pm/test_pm_core.py
@@ -15,7 +15,7 @@ import pm.registry as registry
from pm.lock import Facts, Lockfile
from pm.package import InstallError, compose_env
from pm.packages import BinaryPackage
-from pm.store import Store, current_target, flatten_single_dir
+from pm.store import Store, current_target
from tests.pm._fixtures import make_tar, served as served
@@ -103,22 +103,6 @@ def _pin(lockfile_path: Path, name: str, version: str, digest: str) -> None:
lockfile.save()
-def test_install_and_env(pm_env):
- from pm.ensure import ensure, is_installed
-
- runner = ensure("faketool", base_env={})
- assert is_installed("faketool")
- assert "faketool-1.0" in runner.env["PATH"]
-
-
-def test_idempotent_and_offline_after_install(pm_env):
- from pm.ensure import ensure
-
- _, _, docroot, _ = pm_env
- ensure("faketool", base_env={})
- (docroot / "faketool-1.0.tar.gz").unlink()
- runner = ensure("faketool", base_env={})
- assert "faketool-1.0" in runner.env["PATH"]
def test_bad_hash_rejected(pm_env):
@@ -130,17 +114,8 @@ def test_bad_hash_rejected(pm_env):
ensure("faketool", base_env={})
-def test_fetch_is_a_store_entry(pm_env):
- lock_path, runtime, _, _ = pm_env
- artifact = Lockfile(lock_path).artifacts("faketool", current_target())[0]
- store = Store(runtime)
- with store.scratch() as scratch:
- store.fetch(artifact["url"], artifact["sha256"], scratch)
- fetches = [p for p in runtime.iterdir() if p.name.startswith("fetch-")]
- assert len(fetches) == 1
-
-def test_multi_archive_merges_into_one_entry(pm_env):
+def test_multi_archive_merges_into_one_entry(pm_env, capsys):
"""A package split across two archives lands in ONE store entry: a
second entry would put the DLLs where a loading executable can never
find them. No per-archive entries, no leftover scratch."""
@@ -158,7 +133,11 @@ def test_multi_archive_merges_into_one_entry(pm_env):
]})
lockfile.save()
- ensure("multitool", base_env={})
+ from pm import cli
+ assert cli._install_names(["multitool"]) == 0
+ out = capsys.readouterr().out
+ assert "✓ multitool" in out and "multitool: 100.0%" in out
+ assert "multitool: unpacking 1/2" in out and "multitool: unpacking 2/2" in out
assert is_installed("multitool")
entry_dirs = [p for p in runtime.iterdir() if p.name.startswith("multitool-")]
@@ -168,94 +147,24 @@ def test_multi_archive_merges_into_one_entry(pm_env):
assert (entry / "lib" / "extra.so").is_file()
# Both archives verified before publish: a digest mismatch in either
# must fail loudly, not be silently dropped.
- _, bad = make_tar(docroot, "multitool-2.0-b.tar.gz", {"lib/extra.so": "z"})
+ old_facts = (runtime / "facts.json").read_bytes()
+ _, good = make_tar(docroot, "multitool-2.0-a.tar.gz", {"bin/multitool": "#!new"})
+ make_tar(docroot, "multitool-2.0-b.tar.gz", {"lib/extra.so": "z"})
lockfile = Lockfile(lockfile_path)
lockfile.set_pin("multitool", "2.0", {"any": [
- {"url": f"{FakeTool.base_url}/multitool-2.0-a.tar.gz", "sha256": "0" * 64},
- {"url": f"{FakeTool.base_url}/multitool-2.0-b.tar.gz", "sha256": bad},
+ {"url": f"{FakeTool.base_url}/multitool-2.0-a.tar.gz", "sha256": good},
+ {"url": f"{FakeTool.base_url}/multitool-2.0-b.tar.gz", "sha256": "0" * 64},
]})
lockfile.save()
- with pytest.raises(InstallError):
+ with pytest.raises(InstallError, match="sha256 mismatch.*multitool-2.0-b"):
ensure("multitool", base_env={})
+ assert (runtime / "facts.json").read_bytes() == old_facts
+ assert (entry / "bin/multitool").read_bytes() == b"#!a"
+ assert (entry / "lib/extra.so").read_bytes() == b"y"
+ assert not list(runtime.glob("multitool-2.0*"))
-def test_install_emits_staged_progress(pm_env):
- """ensure() streams download -> unpack per artifact, labelled when a
- package has several. A slow download must not look frozen."""
- from pm.ensure import ensure
-
- lockfile_path, _, docroot, _ = pm_env
- _, digest_a = make_tar(docroot, "multitool-1.0-a.tar.gz", {"bin/multitool": "#!a"})
- _, digest_b = make_tar(docroot, "multitool-1.0-b.tar.gz", {"lib/extra.so": "y"})
- lockfile = Lockfile(lockfile_path)
- lockfile.set_pin("multitool", "1.0", {"any": [
- {"url": f"{FakeTool.base_url}/multitool-1.0-a.tar.gz", "sha256": digest_a},
- {"url": f"{FakeTool.base_url}/multitool-1.0-b.tar.gz", "sha256": digest_b},
- ]})
- lockfile.save()
-
- events: list[tuple[str, str]] = []
- ensure("multitool", base_env={},
- progress=lambda stage, d, t, label: events.append((stage, label)))
-
- assert ("download", "1/2") in events
- assert ("download", "2/2") in events
- assert ("unpack", "1/2") in events
- assert ("unpack", "2/2") in events
- # download before unpack within each artifact.
- stages = [s for s, _ in events]
- assert stages.index("download") < stages.index("unpack")
-
-
-def test_install_names_streams_progress(pm_env, capsys):
- """The CLI install loop renders live download/unpack progress + a ✓
- line per package, so a slow bundle run is never silent in a piped
- log."""
- from pm import cli
-
- assert cli._install_names(["faketool"]) == 0
- out = capsys.readouterr().out
- assert "✓ faketool" in out
- assert "faketool: 100.0%" in out
- assert "faketool: unpacking" in out
-
-
-def test_install_names_labels_multi_archive(pm_env, capsys):
- """A package split across archives gets a label on its progress lines,
- so the log says which archive is moving."""
- from pm import cli
-
- lockfile_path, _, docroot, _ = pm_env
- _, digest_a = make_tar(docroot, "multitool-1.0-a.tar.gz", {"bin/multitool": "#!a"})
- _, digest_b = make_tar(docroot, "multitool-1.0-b.tar.gz", {"lib/extra.so": "y"})
- lockfile = Lockfile(lockfile_path)
- lockfile.set_pin("multitool", "1.0", {"any": [
- {"url": f"{FakeTool.base_url}/multitool-1.0-a.tar.gz", "sha256": digest_a},
- {"url": f"{FakeTool.base_url}/multitool-1.0-b.tar.gz", "sha256": digest_b},
- ]})
- lockfile.save()
-
- assert cli._install_names(["multitool"]) == 0
- out = capsys.readouterr().out
- assert "multitool: unpacking 1/2" in out
- assert "multitool: unpacking 2/2" in out
- assert "✓ multitool" in out
-
-
-def test_download_ticks_per_chunk(pm_env, monkeypatch):
- """The raw download stream reports byte progress on every chunk so a
- slow line proves liveness."""
- from pm.store import Store
- _, runtime, docroot, _ = pm_env
- ticks: list[tuple[int, int]] = []
- store = Store(runtime / "scratch")
- url = f"{FakeTool.base_url}/faketool-1.0.tar.gz"
- _, digest = make_tar(docroot, "faketool-1.0.tar.gz", {"bin/faketool": "#!x"})
- archive = store.fetch(url, digest, runtime / "scratch",
- progress=lambda d, t: ticks.append((d, t)))
- assert archive.is_file()
- assert ticks and ticks[-1][0] == ticks[-1][1] == archive.stat().st_size
def test_deps_compose_dependents_win(pm_env):
@@ -407,15 +316,6 @@ def test_corrupt_facts_degrades_to_empty(pm_env):
assert (runtime / "facts.corrupt").is_file()
-def test_sealed_install_explicit_addition_leaves_payload_unchanged(pm_env, monkeypatch):
- from pm.ensure import ensure, is_installed
-
- _, runtime, *_ = pm_env
- (runtime.parent / "manifest.json").write_text('{"schema": 1}', encoding="utf-8")
- ensure("faketool", base_env={}, explicit=True)
- assert is_installed("faketool")
- assert not (runtime / "facts.json").exists()
-
def test_concurrent_installs_do_not_clobber(pm_env):
from pm.ensure import ensure, is_installed
@@ -444,26 +344,52 @@ def test_concurrent_installs_do_not_clobber(pm_env):
assert is_installed("faketool") and is_installed("deptool")
-def test_single_flight_one_store_entry(pm_env):
+def test_single_flight_one_store_entry(pm_env, monkeypatch):
+ from concurrent.futures import ThreadPoolExecutor
+ from contextlib import contextmanager
+ from http.server import SimpleHTTPRequestHandler
from pm.ensure import ensure
_, runtime, *_ = pm_env
- errors = []
-
- def go():
+ contenders = threading.Barrier(6)
+ body_started, release_body = threading.Event(), threading.Event()
+ bodies, stages = [], []
+ install_lock, do_get, stage = Store.install_lock, SimpleHTTPRequestHandler.do_GET, FakeTool.stage
+
+ @contextmanager
+ def contending(self):
+ contenders.wait(timeout=15)
+ with install_lock(self):
+ yield
+
+ def body(self):
+ if self.headers.get("Range") == "bytes=0-0":
+ return do_get(self)
+ bodies.append(self.path)
+ body_started.set()
+ assert release_body.wait(15), "server was never released"
+ return do_get(self)
+
+ def staged(self, *args):
+ stages.append(self.name)
+ return stage(self, *args)
+
+ monkeypatch.setattr(Store, "install_lock", contending)
+ monkeypatch.setattr(SimpleHTTPRequestHandler, "do_GET", body)
+ monkeypatch.setattr(FakeTool, "stage", staged)
+ with ThreadPoolExecutor(max_workers=6) as pool:
+ futures = [pool.submit(ensure, "faketool", base_env={}) for _ in range(6)]
try:
- ensure("faketool", base_env={})
- except Exception as e:
- errors.append(e)
-
- threads = [threading.Thread(target=go) for _ in range(6)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
- assert not errors
- entries = [p for p in runtime.iterdir() if p.name.startswith("faketool-")]
- assert len(entries) == 1
+ assert body_started.wait(15)
+ finally:
+ release_body.set()
+ runners = [future.result(timeout=30) for future in futures]
+ assert bodies == ["/faketool-1.0.tar.gz"]
+ assert stages == ["faketool"]
+ assert all(runner.env == runners[0].env for runner in runners)
+ fact = Facts(runtime / "facts.json").get("faketool")
+ assert fact["entry"] in runners[0].env["PATH"]
+ assert (runtime / fact["entry"] / "bin/faketool").read_bytes() == b"#!x"
def test_gc_keeps_used_removes_orphans(pm_env):
@@ -513,34 +439,12 @@ def test_env_for_never_installs(pm_env):
assert not any(p.name.startswith("faketool-") for p in installed)
-def test_facts_adopt_by_path_substitution(tmp_path):
- store_a = tmp_path / "bundle-store"
- facts_a = Facts(store_a / "facts.json")
- store_a.mkdir()
- facts_a.record("tool", "1.0", "tool-1.0-any", {"PATH": [str(store_a / "tool-1.0-any" / "bin")]}, store_a)
-
- raw = (store_a / "facts.json").read_text(encoding="utf-8")
- assert "{{store}}" in raw and str(store_a) not in raw
-
- store_b = tmp_path / "user-store"
- store_b.mkdir()
- (store_a / "facts.json").rename(store_b / "facts.json")
- facts_b = Facts(store_b / "facts.json")
- env = facts_b.env_for("tool", store_b)
- assert env["PATH"] == [str(store_b / "tool-1.0-any" / "bin")]
-
def test_compose_env_dependents_win_non_path_too():
env = compose_env([{"X": "dep"}, {"X": "dependent"}], base={})
assert env["X"] == "dependent"
-def test_flatten_refuses_layout_dirs(tmp_path):
- (tmp_path / "bin").mkdir()
- (tmp_path / "bin" / "tool").write_text("x")
- flatten_single_dir(tmp_path)
- assert (tmp_path / "bin" / "tool").is_file()
-
# ── bundle payload pieces ─────────────────────────────────────────────
@@ -642,26 +546,6 @@ def test_adopt_noop_without_facts(pm_env, monkeypatch):
assert pm.adopt() is False
-def test_bundle_package_names_include_browsers(monkeypatch, tmp_path):
- from scripts.bundles.native import _bundle_package_names
- from pm.lock import Lockfile
-
- lock = Lockfile(tmp_path / "lock.json")
- for name in ("uv", "python", "ripgrep", "chromium", "node", "npm"):
- lock.set_pin(name, "1", {"any": {"url": "x", "sha256": "0" * 64}})
- lock.save()
- monkeypatch.setattr("scripts.bundles.native._lockfile", lambda: lock)
- names = _bundle_package_names()
- # Browsers now ship in every payload (win32-arm64 runs the x64 build
- # under emulation); nothing is excluded from the bundle.
- assert "chromium" in names
- assert "python" in names
- assert "ripgrep" in names
- # node/npm are shipped runtime tools (TUI, plugins), not install
- # machinery; only uv remains internal.
- assert "node" in names
- assert "npm" in names
-
def test_bundle_closure_uv_stays_internal_node_npm_ship(monkeypatch, tmp_path):
"""Locks the semantics split: uv is pm's install machinery and never
diff --git a/tests/pm/test_receipt.py b/tests/pm/test_receipt.py
index 6d94bb3847e..e4e9d3c4a25 100644
--- a/tests/pm/test_receipt.py
+++ b/tests/pm/test_receipt.py
@@ -15,26 +15,12 @@ import pm.receipt as receipt
@pytest.fixture(autouse=True)
def _isolated_receipt_context():
- """The ContextVars are module state — tests must not see each other's
- in-flight/completed receipts (a leaked begin or finalize would corrupt
- the next test)."""
- receipt._current.set(None)
- receipt._completed_by_update.set(None)
- try:
- import hermes_cli.update_receipt as _ur
-
- _ur._current.set(None)
- except Exception:
- pass
+ import hermes_cli.update_receipt as update_receipt
+ variables = (receipt._current, receipt._completed_by_update, update_receipt._current)
+ tokens = [variable.set(None) for variable in variables]
yield
- receipt._current.set(None)
- receipt._completed_by_update.set(None)
- try:
- import hermes_cli.update_receipt as _ur
-
- _ur._current.set(None)
- except Exception:
- pass
+ for variable, token in zip(variables, tokens):
+ variable.reset(token)
@pytest.fixture
@@ -46,20 +32,47 @@ def homed(tmp_path, monkeypatch):
return tmp_path
-def test_begin_record_finalize_roundtrip(homed):
[email protected]("outcome,exit_code", [("failed", 1), ("refused", 2)])
+def test_begin_record_finalize_roundtrip(homed, outcome, exit_code):
+ assert receipt.latest() is None
+ assert not (homed / "logs").exists()
+ assert receipt.finalize("ok") is None
+ receipt.record_warning("orphan")
+ receipt.record_refusal("x", "y")
+ assert receipt.latest() is None
receipt.begin("sync")
+ assert receipt.snapshot()["update_id"] is None
receipt.record_step("uv-lock", True)
receipt.record_venv_rebuild(True)
receipt.record_feature_list(["web", "acp"])
+ assert receipt.snapshot()["kind"] == "sync"
path = receipt.finalize("ok")
assert path is not None and path.is_file()
-
data = json.loads(path.read_text(encoding="utf-8-sig"))
- assert data["kind"] == "sync"
- assert data["outcome"] == "ok"
+ assert receipt.latest() == data
+ assert data["kind"] == "sync" and data["outcome"] == "ok"
assert data["venv_rebuild"] == {"ok": True, "reason": ""}
assert data["steps"][0]["name"] == "uv-lock"
assert data["feature_list"] == ["web", "acp"]
+ assert receipt.snapshot() is None
+ assert receipt.finalize("ok") is None
+ assert receipt.last_for_update("any-id") is None
+ assert receipt.last_for_update(None) is None
+ receipt.begin("sync")
+ receipt.record_venv_rebuild(False, "uv sync exited 1")
+ receipt.record_warning("first")
+ receipt.record_warning("second")
+ receipt.record_refusal("lazy-install", "extras outside frozen set")
+ failed = receipt.finalize(outcome, exit_code)
+ latest = receipt.latest()
+ assert latest == json.loads(failed.read_text(encoding="utf-8-sig"))
+ assert latest["outcome"] == outcome and latest["exit_code"] == exit_code
+ assert latest["venv_rebuild"]["reason"] == "uv sync exited 1"
+ assert latest["refusal"]["code"] == "lazy-install"
+ assert latest["refusal"]["detail"] == "extras outside frozen set"
+ assert [w["message"] for w in latest["warnings"]] == ["first", "second"]
+ assert all(w["at"] for w in latest["warnings"])
+ assert json.loads(path.read_text(encoding="utf-8-sig")) == data
def test_bare_python_can_report_a_failed_bootstrap(tmp_path, monkeypatch):
@@ -99,48 +112,6 @@ print(json.dumps(row))
assert row["steps"][0]["ok"] is False
-def test_latest_points_at_newest(homed):
- receipt.begin("sync")
- receipt.finalize("ok")
- latest = receipt.latest()
- assert latest is not None
- assert latest["outcome"] == "ok"
-
- receipt.begin("sync")
- receipt.record_venv_rebuild(False, "uv sync exited 1")
- receipt.finalize("failed", 1)
- latest = receipt.latest()
- assert latest["outcome"] == "failed"
- assert latest["venv_rebuild"]["reason"] == "uv sync exited 1"
-
-
-def test_finalize_without_begin_is_none(homed):
- assert receipt.finalize("ok") is None
-
-
-def test_snapshot_returns_inflight(homed):
- receipt.begin("sync")
- snap = receipt.snapshot()
- assert snap is not None and snap["kind"] == "sync"
- receipt.finalize("ok")
- assert receipt.snapshot() is None
-
-
-def test_latest_none_when_empty(homed):
- assert receipt.latest() is None
-
-
-def test_latest_does_not_create_dirs(homed):
- """Reading a receipt must be side-effect free — no logs/ mkdir."""
- import shutil
-
- logs = homed / "logs"
- if logs.exists():
- shutil.rmtree(logs)
- assert receipt.latest() is None
- assert not logs.exists()
-
-
def test_concurrent_finalize_writes_unique_names(homed):
"""Overlapping syncs (threaded cadence/ensure) must each get their own
receipt file — no stamp collision overwrites."""
@@ -189,13 +160,15 @@ def test_receipt_state_is_thread_scoped(homed):
another thread neither sees nor clobbers this one's in-flight receipt."""
import threading
- receipt.begin("sync")
+ with receipt.worker_context("mine"):
+ receipt.begin("sync")
receipt.record_step("mine", True)
seen: dict = {}
def other():
seen["snapshot_from_other"] = receipt.snapshot()
- receipt.begin("update")
+ with receipt.worker_context("theirs"):
+ receipt.begin("update")
receipt.record_step("theirs", False)
receipt.finalize("failed")
seen["after_other"] = receipt.snapshot()
@@ -211,6 +184,8 @@ def test_receipt_state_is_thread_scoped(homed):
assert [s["name"] for s in snap["steps"]] == ["mine"]
path = receipt.finalize("ok")
assert path is not None and path.is_file()
+ assert receipt.last_for_update("theirs") is None
+ assert receipt.last_for_update("mine")["steps"][0]["name"] == "mine"
def test_copied_context_does_not_corrupt_parent_receipt():
@@ -285,47 +260,6 @@ def test_nested_begin_with_token_restores_outer():
assert receipt.snapshot() is None
-def test_finalize_without_token_pops_receipt():
- """Ambient (no token) finalize still pops the receipt — the existing
- linear begin→finalize consumers keep working."""
- receipt.begin("sync")
- assert receipt.finalize("ok") is not None
- assert receipt.snapshot() is None
- assert receipt.finalize("ok") is None # nothing begun
-
-
-# --- correlation with the invoking update (update_id stamping) ----------
-
-
-def test_begin_stamps_ambient_update_correlation_id(homed):
- """A sync begun while an update receipt is open is stamped with THAT
- update's correlation id — the embed matches on it."""
- import hermes_cli.update_receipt as ur
-
- ur.begin_update_receipt()
- my_id = ur.current_correlation_id()
- assert my_id
- receipt.begin("sync")
- assert receipt.snapshot()["update_id"] == my_id
- receipt.finalize("ok")
- # the completion is filed under the update's id
- assert receipt.last_for_update(my_id)["update_id"] == my_id
-
-
-def test_standalone_sync_has_no_update_id(homed):
- receipt.begin("sync")
- assert receipt.snapshot()["update_id"] is None
-
-
-def test_standalone_sync_is_never_filed_for_an_update(homed):
- """A sync with no invoking update (update_id None) can never be
- embedded into any update — it is not filed in the map at all."""
- receipt.begin("sync")
- receipt.finalize("ok")
- assert receipt.last_for_update("any-id") is None
- assert receipt.last_for_update(None) is None
-
-
def test_sync_begin_after_update_finalized_has_no_update_id(homed, monkeypatch):
"""The correlation id comes from the OPEN update receipt: after its
finalize pops it, a sync begun is standalone."""
@@ -339,64 +273,6 @@ def test_sync_begin_after_update_finalized_has_no_update_id(homed, monkeypatch):
assert receipt.snapshot()["update_id"] is None
-def test_completion_map_is_per_context(homed):
- """Another thread's finalize must not enter THIS context's completion
- map — concurrency cannot misattribute its receipt to us."""
- import threading
- import hermes_cli.update_receipt as ur
-
- ur.begin_update_receipt()
- my_id = ur.current_correlation_id()
- receipt.begin("sync")
- receipt.finalize("ok")
- mine = receipt.last_for_update(my_id)
- assert mine is not None
-
- def other():
- ur.begin_update_receipt()
- receipt.begin("sync")
- receipt.record_step("theirs", True)
- receipt.finalize("ok")
-
- t = threading.Thread(target=other)
- t.start()
- t.join()
- assert receipt.last_for_update(my_id)["steps"] == mine["steps"]
-
-
-def test_nested_update_syncs_do_not_displace_each_other(homed, monkeypatch):
- """outer sync → nested update → nested sync → finalize inner →
- finalize outer: BOTH completions stay filed under their own update
- id; the nested one never overwrites the outer's entry."""
- import hermes_cli.update_receipt as ur
-
- monkeypatch.setattr(ur, "_receipt_dir", lambda: homed / "logs" / "update_receipts")
- ur.begin_update_receipt()
- outer_id = ur.current_correlation_id()
- receipt.begin("sync")
- receipt.record_step("outer-sync", True)
- receipt.finalize("ok")
-
- ur.begin_update_receipt() # nested
- inner_id = ur.current_correlation_id()
- receipt.begin("sync")
- receipt.record_step("inner-sync", True)
- receipt.finalize("ok")
-
- # both entries exist while the inner update is still open
- assert [s["name"] for s in receipt.last_for_update(outer_id)["steps"]] == ["outer-sync"]
- assert [s["name"] for s in receipt.last_for_update(inner_id)["steps"]] == ["inner-sync"]
-
- ur.finalize_update_receipt("success")
- # and after the nested finalize restored the outer receipt
- assert ur.current_correlation_id() == outer_id
- assert [s["name"] for s in receipt.last_for_update(outer_id)["steps"]] == ["outer-sync"]
- assert receipt.last_for_update(inner_id) is None
- path = ur.finalize_update_receipt("success")
- assert receipt.last_for_update(outer_id) is None
- assert json.loads(path.read_text(encoding="utf-8-sig"))["pm_steps"][0]["name"] == "outer-sync"
-
-
def test_last_for_update_returns_a_copy(homed):
import hermes_cli.update_receipt as ur
@@ -407,50 +283,3 @@ def test_last_for_update_returns_a_copy(homed):
snap = receipt.last_for_update(my_id)
snap["outcome"] = "tampered"
assert receipt.last_for_update(my_id)["outcome"] == "ok"
-
-
-# --- failures, refusals, surfaced warnings ------------------------------
-
-
-def test_record_warning_appends(homed):
- receipt.begin("sync")
- receipt.record_warning("shim quarantine skipped: file locked")
- receipt.record_warning("second")
- receipt.finalize("ok")
- warnings = receipt.latest()["warnings"]
- assert [w["message"] for w in warnings] == [
- "shim quarantine skipped: file locked", "second"
- ]
- assert all(w["at"] for w in warnings)
-
-
-def test_record_warning_without_begin_is_noop(homed):
- receipt.record_warning("orphan")
- receipt.record_refusal("x", "y")
- assert receipt.latest() is None
-
-
-def test_record_refusal_names_the_policy_conflict(homed):
- """A refusal record names WHY the sync refused (policy conflict) while
- the outcome stays a failure — network/build InstallErrors stay plain
- failures and must never be recorded as refusals."""
- receipt.begin("sync")
- receipt.record_refusal("lazy-install", "venv out of sync")
- path = receipt.finalize("failed", 1)
- data = json.loads(path.read_text(encoding="utf-8-sig"))
- assert data["outcome"] == "failed"
- assert data["refusal"]["code"] == "lazy-install"
- assert data["refusal"]["detail"] == "venv out of sync"
-
-
-def test_warnings_and_refusal_survive_finalize_rotation(homed):
- """Failure receipts must survive: recorded, written to latest.json,
- and present on the stamped file after rotation."""
- receipt.begin("sync")
- receipt.record_warning("uv exited 1")
- receipt.record_refusal("lazy-install", "extras outside frozen set")
- receipt.finalize("refused", 2)
- latest = receipt.latest()
- assert latest["outcome"] == "refused"
- assert latest["warnings"] and latest["refusal"]["code"] == "lazy-install"
- assert latest["update_id"] is None
diff --git a/tests/pm/test_recovery.py b/tests/pm/test_recovery.py
index ee24dd0616f..2c1a7f29558 100644
--- a/tests/pm/test_recovery.py
+++ b/tests/pm/test_recovery.py
@@ -59,15 +59,8 @@ def test_startup_validation_checks_real_ruamel_dependency(tmp_path, failure):
validate_environment(python, env=dict(os.environ), cwd=tmp_path)
[email protected]("failure", [None, "missing_lock", "corrupt_facts", "empty_environment", "missing_extras", "validation", "publication"])
-def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, monkeypatch, failure):
- import pm.paths as paths
- import pm.workspace as workspace
- from hermes_cli.runtime_paths import selected_venv, site_packages
-
- engine = importlib.import_module("pm.ensure")
- uv = shutil.which("uv")
- assert uv, "recovery integration requires real uv"
+def recovery_graph(tmp_path):
core = tmp_path / "core"
core.mkdir()
wheels = tmp_path / "wheels"
@@ -86,6 +79,19 @@ def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, m
'[project]\nname="repair-plugin"\nversion="1"\nrequires-python=">=3.11"\n'
'dependencies=["plugin-dep==1.0"]\n[tool.uv]\npackage=false\n', encoding="utf-8",
)
+ return core, plugin
+
+
[email protected]("failure", [None, "missing_lock", "corrupt_facts", "empty_environment", "missing_extras", "validation", "publication"])
+def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, monkeypatch, recovery_graph, failure):
+ import pm.paths as paths
+ import pm.workspace as workspace
+ from hermes_cli.runtime_paths import selected_venv, site_packages
+
+ engine = importlib.import_module("pm.ensure")
+ uv = shutil.which("uv")
+ assert uv, "recovery integration requires real uv"
+ core, plugin = recovery_graph
monkeypatch.setattr(paths, "repo_root", lambda: core)
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
@@ -157,7 +163,7 @@ def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, m
assert config.read_bytes() == config_before
-def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_path, monkeypatch):
+def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_path, monkeypatch, recovery_graph):
import pm.paths as paths
from hermes_cli.plugins_admission import AdmissionRefused, admit_plugin_set_change
from hermes_cli.runtime_paths import install_state_dir, selected_venv, site_packages
@@ -167,25 +173,12 @@ def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_pa
monkeypatch.setattr("pm.client.sync_venv", engine.sync_venv)
uv = shutil.which("uv")
assert uv
- core = tmp_path / "core"
- core.mkdir()
- wheels = tmp_path / "wheels"
- wheels.mkdir()
- _wheel(wheels, "core_dep", "1.0")
- _wheel(wheels, "plugin_dep", "1.0")
- (core / "pyproject.toml").write_text(
- '[project]\nname="uncertain-core"\nversion="1"\nrequires-python=">=3.11"\n'
- 'dependencies=["core-dep==1.0"]\n[tool.uv]\npackage=false\nno-index=true\n'
- f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8",
- )
+ core, original_plugin = recovery_graph
home = tmp_path / "home"
sibling = home / "profiles" / "worker"
plugin = sibling / "plugins" / "worker-deps"
- plugin.mkdir(parents=True)
- (plugin / "pyproject.toml").write_text(
- '[project]\nname="worker-deps"\nversion="1"\nrequires-python=">=3.11"\n'
- 'dependencies=["plugin-dep==1.0"]\n[tool.uv]\npackage=false\n', encoding="utf-8",
- )
+ plugin.parent.mkdir(parents=True)
+ original_plugin.rename(plugin)
active_config = home / "config.yaml"
active_config.write_text("plugins:\n enabled: []\n", encoding="utf-8")
sibling_config = sibling / "config.yaml"
diff --git a/tests/pm/test_recovery_validation.py b/tests/pm/test_recovery_validation.py
deleted file mode 100644
index cf754a0b7f8..00000000000
--- a/tests/pm/test_recovery_validation.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""PM validates real imports before it publishes a recovered dependency tree."""
-from __future__ import annotations
-
-import importlib.metadata
-import os
-from pathlib import Path
-import shutil
-import sys
-
-import pytest
-
-from pm.package import InstallError
-from pm.runtime import runtime_environment
-from pm.recovery import validate_environment
-
[email protected](autouse=True)
-def isolated_machine_home(tmp_path, monkeypatch):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
-
-
-
[email protected]("damage", ["module", "distribution"])
-def test_validation_rejects_a_missing_required_import(tmp_path, monkeypatch, damage):
- import pm.paths as paths
- from hermes_cli.runtime_paths import site_packages
-
- core = tmp_path / "core"
- core.mkdir()
- version = importlib.metadata.version("python-dotenv")
- (core / "pyproject.toml").write_text(
- '[project]\nname="validation-proof"\nversion="1"\nrequires-python=">=3.11"\n'
- f'dependencies=["python-dotenv=={version}"]\n[tool.uv]\npackage=false\n',
- encoding="utf-8",
- )
- monkeypatch.setattr(paths, "repo_root", lambda: core)
- uv = shutil.which("uv")
- assert uv, "validation integration requires real uv"
- env = {**runtime_environment(), "UV_PYTHON": sys.executable}
- env.pop("UV_NO_CONFIG", None)
- workspace = tmp_path / "workspace"
- candidate = tmp_path / "venv"
- monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
- from pm.workspace import lock_and_sync
- from pm.environment import managed_environment
-
- lock_and_sync([], [], root=workspace, source=core, seed_lock=None,
- environment=managed_environment(candidate))
- python = candidate / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
- validate_environment(python, env=env, cwd=workspace)
- shutil.rmtree(site_packages(candidate) / "dotenv")
- if damage == "distribution":
- for metadata in site_packages(candidate).glob("python_dotenv-*.dist-info"):
- shutil.rmtree(metadata)
- with pytest.raises(InstallError, match="startup validation failed"):
- validate_environment(python, env=env, cwd=workspace)
diff --git a/tests/pm/test_runtime.py b/tests/pm/test_runtime.py
index 09df4cf30a9..a78d4b08215 100644
--- a/tests/pm/test_runtime.py
+++ b/tests/pm/test_runtime.py
@@ -100,6 +100,7 @@ def test_cold_worker_bootstrap_reuses_the_requests_cache(tmp_path, monkeypatch):
assert dict(os.environ) == before
[email protected]("macos", "windows")
def test_sealed_worker_command_uses_only_its_recorded_site(tmp_path, monkeypatch):
from pm import paths
from pm.runtime import runtime_command
diff --git a/tests/pm/test_runtime_boot_gc.py b/tests/pm/test_runtime_boot_gc.py
index 5a09e25ecb6..f9cdd8dc4a3 100644
--- a/tests/pm/test_runtime_boot_gc.py
+++ b/tests/pm/test_runtime_boot_gc.py
@@ -1,7 +1,6 @@
"""A real bootstrap reader pins its generation before GC can select victims."""
import json
import os
-from pathlib import Path
import subprocess
import sys
@@ -14,11 +13,13 @@ def test_bootstrap_lease_survives_selection_change(tmp_path, monkeypatch):
repo.mkdir()
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
state = install_state_dir(repo)
- for name in ("first", "second"):
+ for name in ("first", "second", "unused"):
venv = state / "environments" / name / "venv"
site_packages(venv).mkdir(parents=True)
(venv / "pyvenv.cfg").write_text("version = 3.11")
(venv.parent / ".lease-managed").touch()
+ legacy = state / "environments" / "old-unleased"
+ legacy.mkdir()
def select(name):
environment = state / "environments" / name / "venv"
@@ -41,9 +42,12 @@ sys.stdin.readline()
select("second")
collect_generations(repo, min_age_seconds=0)
assert first.is_dir()
+ assert not (state / "environments" / "unused").exists()
+ assert legacy.is_dir()
finally:
child.communicate("done\n", timeout=15)
assert child.returncode == 0
collect_generations(repo, min_age_seconds=0)
assert not first.exists()
assert (state / "environments" / "second").is_dir()
+ assert legacy.is_dir()
diff --git a/tests/pm/test_runtime_recovery.py b/tests/pm/test_runtime_recovery.py
deleted file mode 100644
index 6e396f9ff52..00000000000
--- a/tests/pm/test_runtime_recovery.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""Publication survives process death; live dependency generations survive GC."""
-import json
-import os
-from pathlib import Path
-import subprocess
-import sys
-
-import pytest
-
-
[email protected]("commit_facts", [False, True])
-def test_killed_publication_recovers_before_boot(tmp_path, commit_facts):
-
- repo = tmp_path / "repo"
- repo.mkdir()
- home = tmp_path / "home"
- home.mkdir()
- config = home / "config.yaml"
- config.write_text("plugins:\n enabled: [old]\n")
- original = config.read_bytes()
- env = dict(os.environ, HERMES_HOME=str(home))
- code = '''
-import os, sys
-from pathlib import Path
-from pm.publication import PluginSelection
-from hermes_cli.runtime_paths import runtime_facts_path
-import pm.paths as paths
-from pm.lock import Facts
-repo, config = map(Path, sys.argv[1:3])
-paths.repo_root = lambda: repo
-PluginSelection({"home": str(config.parent), "enabled": ["new"], "disabled": []}).publish(repo)
-if sys.argv[3] == "True":
- Facts(runtime_facts_path(repo)).record_state("venv", "new", [])
-os._exit(17)
-'''
- proc = subprocess.run([sys.executable, "-c", code, str(repo), str(config), str(commit_facts)], env=env, capture_output=True, text=True)
- assert proc.returncode == 17, proc.stderr
- boot = """
-import sys
-from pathlib import Path
-from hermes_cli.runtime_paths import activate_dependencies, site_packages
-repo, config = map(Path, sys.argv[1:3])
-site_packages(repo / "venv").mkdir(parents=True, exist_ok=True)
-activate_dependencies(repo)
-print(config.read_text(), end="")
-"""
- recovered = subprocess.run([sys.executable, "-c", boot, str(repo), str(config)],
- env=env, capture_output=True, text=True, timeout=30)
- assert recovered.returncode == 0, recovered.stderr
- assert ("old" in recovered.stdout) is not commit_facts
- assert (config.read_bytes() == original) is not commit_facts
-
-
-def test_generation_gc_keeps_selected_and_live_leases(tmp_path, monkeypatch):
- from hermes_cli.runtime_paths import install_state_dir
- from hermes_cli.runtime_state import collect_generations
- repo = tmp_path / "repo"
- repo.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- state = install_state_dir(repo)
- gens = state / "environments"
- for name in ("selected", "live", "unused"):
- env = gens / name / "venv"
- env.mkdir(parents=True)
- (env / "pyvenv.cfg").write_text("version=3.11")
- (env.parent / ".lease-managed").touch()
- (gens / "old-unleased").mkdir()
- (state / "facts.json").write_text(json.dumps({"packages": {"venv": {"environment": str(gens / "selected" / "venv")}}}))
- code = '''
-from pathlib import Path
-from hermes_cli.runtime_state import lease_generation
-import sys
-lease_generation(Path(sys.argv[1]))
-print("leased", flush=True)
-sys.stdin.readline()
-'''
- child = subprocess.Popen([sys.executable, "-c", code, str(gens / "live" / "venv")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- try:
- assert child.stdout.readline().strip() == "leased"
- collect_generations(repo, min_age_seconds=0)
- assert (gens / "selected").exists()
- assert (gens / "live").exists()
- assert not (gens / "unused").exists()
- finally:
- child.communicate("stop\n", timeout=15)
- assert child.returncode == 0
- collect_generations(repo, min_age_seconds=0)
- assert not (gens / "live").exists()
- assert (gens / "selected").exists()
- assert (gens / "old-unleased").is_dir()
diff --git a/tests/pm/test_runtime_transaction.py b/tests/pm/test_runtime_transaction.py
deleted file mode 100644
index 0585d785589..00000000000
--- a/tests/pm/test_runtime_transaction.py
+++ /dev/null
@@ -1,133 +0,0 @@
-"""Preparing dependencies never mutates the selected environment or plugin config."""
-from pathlib import Path
-import importlib
-
-import pytest
-
-from pm.lock import Facts
-from pm.package import InstallError
-
[email protected](autouse=True)
-def isolated_machine_home(tmp_path, monkeypatch):
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
-
-
-
[email protected]("failure", ["build", "record", "missing", None])
-def test_sync_commits_only_a_successful_candidate(tmp_path, monkeypatch, failure):
- import pm.paths as paths
- import pm.registry as registry
- from hermes_cli.runtime_paths import selected_venv
- from pm.packages import Venv
-
- ensure = importlib.import_module("pm.ensure")
- root = tmp_path / "repo"
- root.mkdir()
- (root / "uv.lock").write_text("initial-lock")
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- monkeypatch.setattr(paths, "repo_root", lambda: root)
- monkeypatch.setattr(ensure, "sealed", lambda: False)
- monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: True)
- monkeypatch.setattr("pm.workspace.enabled_member_dirs", lambda: [])
- config = tmp_path / "home" / "config.yaml"
- config.parent.mkdir()
- config.write_text("plugins:\n enabled: [working]\n")
- original_config = config.read_bytes()
- runtime_facts = Facts(paths.runtime_facts_path())
- previous = paths.runtime_facts_path().parent / "environments" / "previous" / "venv"
- previous.mkdir(parents=True)
- (previous / "pyvenv.cfg").write_text("home = previous")
- runtime_facts.record_state("venv", "old", ["base"], environment=previous)
- if failure == "missing":
- (previous / "pyvenv.cfg").unlink()
- runtime_facts.record_state("venv", "new", ["base", "new-extra"], environment=previous)
- before = runtime_facts.path.read_bytes()
- candidate = previous.parent.parent / "candidate" / "venv"
-
- class TestVenv(Venv):
- def expected_stamp(self, extras):
- return "new"
-
- def apply(self, extras, *, explicit=False):
- if failure != "missing":
- assert selected_venv(root) == previous
- assert extras == ["base", "new-extra"]
- if failure == "build":
- raise InstallError("venv", "download unavailable")
- candidate.mkdir(parents=True)
- (candidate / "pyvenv.cfg").write_text("home = candidate")
- return {"environment": candidate}
-
- monkeypatch.setitem(registry._packages, "venv", TestVenv())
- if failure == "record":
- def refuse_record(self, *args, **kwargs):
- raise OSError("disk full")
- monkeypatch.setattr(Facts, "record_state", refuse_record)
- if failure in ("build", "record"):
- with pytest.raises((InstallError, OSError)):
- ensure.sync_venv(["new-extra"], explicit=True)
- assert runtime_facts.path.read_bytes() == before
- assert selected_venv(root) == previous
- else:
- ensure.sync_venv(["new-extra"], explicit=True)
- assert selected_venv(root) == candidate
- assert Facts(runtime_facts.path).get("venv")["extras"] == ["base", "new-extra"]
- assert previous.is_dir()
- assert config.read_bytes() == original_config
-
-
-def test_real_uv_builds_separate_environment_before_selection(tmp_path, monkeypatch):
- import shutil
- import subprocess
- import sys
- import pm.paths as paths
- from pm.packages import Venv
- from hermes_cli.runtime_paths import selected_venv
-
- uv = shutil.which("uv")
- assert uv is not None, "uv is required for the real environment contract"
- core = tmp_path / "core"
- core.mkdir()
- (core / "pyproject.toml").write_text(
- '[project]\nname="environment-test"\nversion="1"\nrequires-python=">=3.11"\n'
- '[tool.uv]\npackage=false\n', encoding="utf-8",
- )
- subprocess.run([uv, "lock", "--offline", "--python", sys.executable], cwd=core, check=True, capture_output=True)
- original_lock = (core / "uv.lock").read_bytes()
- base = core / "venv"
- base.mkdir()
- (base / "pyvenv.cfg").write_text("home = previous")
- monkeypatch.setattr(paths, "repo_root", lambda: core)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- monkeypatch.setattr("pm.workspace.enabled_member_dirs", lambda: [])
- monkeypatch.setattr("pm._uv._toolchain", lambda **kw: (Path(uv), Path(sys.executable)))
- prepared = Venv().apply([])
- assert selected_venv(core) == base
- candidate = prepared["environment"]
- assert candidate != base and (candidate / "pyvenv.cfg").is_file()
- python = candidate / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
- probe = subprocess.run([str(python), "-c", "import sys; print(sys.prefix)"], capture_output=True, text=True, check=True)
- assert Path(probe.stdout.strip()).resolve() == candidate.resolve()
- assert (core / "uv.lock").read_bytes() == original_lock
-
-
-def test_lazy_import_reports_restart_instead_of_importing_mixed_versions(tmp_path, monkeypatch):
- from hermes_cli.runtime_paths import runtime_facts_path
- import pm.extras as extras
- import pm.paths as paths
-
- root = tmp_path / "repo"
- root.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- monkeypatch.setattr(paths, "repo_root", lambda: root)
- monkeypatch.setattr(extras, "available", lambda _: False)
- monkeypatch.setattr(extras, "extra_supported", lambda _: True)
- candidate = runtime_facts_path(root).parent / "environments" / "new" / "venv"
- candidate.mkdir(parents=True)
- (candidate / "pyvenv.cfg").write_text("home = test")
- def prepare(requested):
- Facts(runtime_facts_path(root)).record_state("venv", "new", requested, environment=candidate)
- monkeypatch.setattr("pm.client.sync_venv", prepare)
- with pytest.raises(InstallError, match="restart"):
- extras.ensure_import("new-extra")
diff --git a/tests/pm/test_runtime_wheelhouse.py b/tests/pm/test_runtime_wheelhouse.py
index 79936b3af16..81b67698486 100644
--- a/tests/pm/test_runtime_wheelhouse.py
+++ b/tests/pm/test_runtime_wheelhouse.py
@@ -91,11 +91,27 @@ print(json.dumps({canonicalize_name(d.metadata['Name']): d.version
)
assert result.returncode == 0, result.stderr
assert json.loads(result.stdout) == versions
+ from pm import paths
+ from pm.runtime import runtime_command
+ repo = moved / "hermes-agent"
+ repo.mkdir()
+ (moved / "manifest.json").write_text('{"repo":"hermes-agent"}')
+ script = repo / "probe.py"
+ script.write_text("import sys,json; print(json.dumps(sys.path))")
+ with pytest.MonkeyPatch.context() as patcher:
+ patcher.setattr(paths, "repo_root", lambda: repo)
+ child = subprocess.run(runtime_command(script), cwd=tmp_path, env=runtime_environment(),
+ capture_output=True, text=True, check=True, timeout=30)
+ entries = json.loads(child.stdout)
+ assert str((runtime / marker["sitePackages"]).resolve()) in entries
+ recorded_site = (runtime / marker["sitePackages"]).resolve()
+ assert not any(Path(entry).name in {"site-packages", "dist-packages"}
+ and Path(entry).resolve() != recorded_site for entry in entries)
@pytest.mark.platforms("linux")
def test_offline_wheelhouse_rejects_missing_transitive_wheel(
- tmp_path, isolated_builder, locked_wheelhouse, capfd,
+ tmp_path, isolated_builder, locked_wheelhouse, capfd, monkeypatch,
):
from pm.package import InstallError
@@ -105,8 +121,10 @@ def test_offline_wheelhouse_rejects_missing_transitive_wheel(
native_wheel, = incomplete.glob("ruamel_yaml_clib-*.whl")
native_wheel.unlink()
destination = tmp_path / "pm-runtime"
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (isolated_builder, Path(sys.executable)))
with pytest.raises(InstallError, match="pip exited"):
- stage_runtime(isolated_builder, Path(sys.executable), destination,
- wheelhouse=incomplete, offline=True)
+ from pm import stage_manager_runtime
+ stage_manager_runtime(python=Path(sys.executable), destination=destination,
+ wheelhouse=incomplete, offline=True)
assert "ruamel-yaml-clib" in capfd.readouterr().err
- assert not (destination / "pm-runtime.json").exists()
+ assert not destination.exists()
diff --git a/tests/pm/test_security_consumers.py b/tests/pm/test_security_consumers.py
index 597d32b0374..3bc4526c586 100644
--- a/tests/pm/test_security_consumers.py
+++ b/tests/pm/test_security_consumers.py
@@ -223,10 +223,12 @@ def test_managed_consumers_run_their_business_protocol(consumer_store, monkeypat
"if '--version' in sys.argv: print('bws fixture')\n"
"else:\n"
" assert sys.argv[1:] == ['secret','list','project','--output','json']\n"
+ " assert os.environ['BWS_SERVER_URL'] == 'https://vault.example.invalid'\n"
" print(json.dumps([{'key':'FIXTURE_VALUE','value':os.environ['BWS_ACCESS_TOKEN']}]))\n"
).encode())
install_bws()
- assert fetch_bitwarden_secrets(access_token="local-token", project_id="project", use_cache=False) == (
+ assert fetch_bitwarden_secrets(access_token="local-token", project_id="project", use_cache=False,
+ server_url="https://vault.example.invalid") == (
{"FIXTURE_VALUE": "local-token"}, []
)
pin(consumer_store, "iron-proxy", payload=(
diff --git a/tests/pm/test_setup_lock_format.py b/tests/pm/test_setup_lock_format.py
index 5c04361ebfa..eaadbd06035 100644
--- a/tests/pm/test_setup_lock_format.py
+++ b/tests/pm/test_setup_lock_format.py
@@ -23,10 +23,11 @@ pytestmark = pytest.mark.platforms("posix")
REPO = Path(__file__).resolve().parents[2]
[email protected]("indent,blank_lines", [(2, False), (4, False), (0, False), ("\t", False), (4, True)],
- ids=["two-spaces", "four-spaces", "no-indent", "tabs", "blank-lines"])
[email protected]("mirror_indent", [2, 7], ids=["mirror-two-spaces", "mirror-seven-spaces"])
-def test_setup_reads_pins_independent_of_indentation(tmp_path, served, indent, blank_lines, mirror_indent):
[email protected]("indent,blank_lines,mirror_indent,fallback", [
+ (2, False, 2, False), (4, False, 7, False), (0, False, 2, False),
+ ("\t", False, 7, False), (4, True, 2, False), (2, False, 9, True),
+])
+def test_setup_reads_pins_independent_of_indentation(tmp_path, served, indent, blank_lines, mirror_indent, fallback):
bash = shutil.which("bash")
assert bash, "the shell bootstrap contract requires Bash"
core = tmp_path / "checkout with spaces"
@@ -59,6 +60,10 @@ def test_setup_reads_pins_independent_of_indentation(tmp_path, served, indent, b
docroot, base_url = served
filename, digest = make_tar(docroot, "uv.tar.gz", {"uv-fixture/uv": uv_script})
artifact = {"sha256": digest, "url": f"{base_url}/{filename}"}
+ if fallback:
+ (docroot / "mirror").mkdir()
+ shutil.copy2(docroot / filename, docroot / "mirror" / digest)
+ artifact["url"] = "http://127.0.0.1:1/uv.tar.gz"
decoy = {"sha256": "0" * 64, "url": f"{base_url}/wrong-target.tar.gz"}
target = current_target()
data = {"packages": {
@@ -94,71 +99,3 @@ def test_setup_reads_pins_independent_of_indentation(tmp_path, served, indent, b
assert not (home / ".hermes" / "skills").exists()
print(f"runtime-only bootstrap: indent={indent!r}, blank_lines={blank_lines}: exit {result.returncode}")
print(result.stdout)
-
-
-def test_setup_mirror_fallback_reads_any_layout(tmp_path, served):
- """The mirror fallback consumes artifact-mirror.json read pre-Python.
-
- The primary URL is a dead port (curl exit 7, in the retriable set), so the
- staged artifact must come from the mirror; the mirror json is written as a
- compact single line to prove the reader follows keys, not indentation.
- """
- bash = shutil.which("bash")
- assert bash, "the shell bootstrap contract requires Bash"
- core = tmp_path / "checkout"
- (core / "pm").mkdir(parents=True)
- shutil.copy2(REPO / "setup-hermes.sh", core / "setup-hermes.sh")
- home = tmp_path / "home"
- home.mkdir()
- runtime = tmp_path / "runtime"
- interpreter = str(Path(sys._base_executable).resolve())
- py_version = f"{sys.version_info.major}.{sys.version_info.minor}"
- uv_version = "fixture-pin"
- receipt = core / "handoff.json"
- (core / "pm" / "__init__.py").touch()
- (core / "pm" / "cli.py").write_text(
- "import json, pathlib, sys\n"
- "assert sys.argv[1:] == ['install'], sys.argv\n"
- f"pathlib.Path({str(receipt)!r}).write_text(json.dumps(sys.argv[1:]))\n",
- encoding="utf-8",
- )
- uv_script = (
- f"#!{bash}\nset -eu\n"
- f'case "$*" in\n'
- f' --version) printf \'%s\\n\' "uv {uv_version}" ;;\n'
- f' "python install --no-bin {py_version}") ;;\n'
- f' "python find --managed-python {py_version}") printf \'%s\\n\' {shlex.quote(interpreter)} ;;\n'
- f' *) exit 91 ;;\n'
- f'esac\n'
- )
- docroot, base_url = served
- mirror_dir = docroot / "mirror"
- mirror_dir.mkdir()
- filename, digest = make_tar(docroot, "uv.tar.gz", {"uv-fixture/uv": uv_script})
- shutil.copy2(docroot / filename, mirror_dir / digest)
- # Dead port: curl cannot connect (exit 7), which fetch_pinned treats as
- # retriable, forcing the mirror branch.
- dead = "http://127.0.0.1:1/uv.tar.gz"
- artifact = {"sha256": digest, "url": dead}
- target = current_target()
- data = {"packages": {
- "python": {"artifacts": {target: {"sha256": "0" * 64, "url": dead}},
- "version": f"{py_version}.7+fixture"},
- "uv": {"artifacts": {target: artifact}, "version": uv_version},
- }}
- (core / "pm" / "lock.json").write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
- # Hostile indentation (one member per line, 9 spaces): the reader must
- # follow keys, not the 2-space layout the real file ships with.
- (core / "pm" / "artifact-mirror.json").write_text(
- json.dumps({"origin": base_url, "prefix": "mirror/"}, indent=9) + "\n", encoding="utf-8",
- )
- env = {"PATH": os.environ["PATH"], "HOME": str(home),
- "HERMES_HOME": str(home / ".hermes"), "HERMES_RUNTIME_DIR": str(runtime),
- "PYTHONNOUSERSITE": "1"}
- result = subprocess.run(
- [bash, str(core / "setup-hermes.sh"), "--runtime-only"], cwd=tmp_path,
- env=env, capture_output=True, text=True, timeout=30,
- )
- assert result.returncode == 0, result.stdout + result.stderr
- assert (runtime / f"uv-{uv_version}-{target}" / "uv").read_text() == uv_script
- assert json.loads(receipt.read_text()) == ["install"]
diff --git a/tests/pm/test_stage_only.py b/tests/pm/test_stage_only.py
index 4d27499c557..319b5f0c341 100644
--- a/tests/pm/test_stage_only.py
+++ b/tests/pm/test_stage_only.py
@@ -1,39 +1,20 @@
-"""stage_only / _install regressions: a VALID published entry must never be
-deleted (verify() returns '' on success), and stage_only must honor a
-same-version hash repin (the entry marker design, like facts' identity).
-
-Everything runs inside a temp HERMES_RUNTIME_DIR sandbox: the store and
-facts live under tmp_path. Most tests use fake package definitions. The
-Node tests use the real package with local archives, without network access.
-"""
+"""Native/cross-target execution and Windows directory-hold staging contracts."""
from __future__ import annotations
import hashlib
import importlib
-import json
from pathlib import Path
import pytest
from pm.package import InstallError, Package
+from pm.lock import Lockfile
from pm.store import Store
ensure_mod = importlib.import_module("pm.ensure")
-class _FakeLockfile:
- def __init__(self, version: str, artifacts: list[dict]):
- self._version = version
- self._artifacts = artifacts
-
- def version(self, name: str):
- return self._version
-
- def artifacts(self, name: str, target: str):
- return self._artifacts
-
-
class _FakePackage(Package):
"""unpack() turns the verified archive bytes into one binary file."""
@@ -76,8 +57,12 @@ def sandbox(tmp_path, monkeypatch):
return store
-def _arm_lock(monkeypatch, artifacts: list[dict]):
- lock = _FakeLockfile("1.0", artifacts)
+def _arm_lock(monkeypatch, artifacts):
+ from pm import paths
+ lock = Lockfile(paths.store_root().parent / "stage-lock.json")
+ lock.set_pin("node", "1.0", {"any": artifacts})
+ lock.set_pin("stage-test", "1.0", {"any": artifacts})
+ lock.save()
monkeypatch.setattr(ensure_mod, "_lockfile", lambda: lock)
return lock
@@ -86,6 +71,38 @@ TARGET = "linux-arm64-bionic"
ENTRY = "stage-test-1.0-linux-arm64-bionic"
[email protected]("name,relative", [
+ ("python", "bin/python3.14"), ("uv", "bin/uv"), ("node", "bin/node"),
+])
+def test_bionic_deb_stages_real_packages_without_host_execution(tmp_path, monkeypatch, name, relative):
+ from pm import paths
+ from tests.pm.test_deb_safety import _build_deb
+ from pm.registry import get_package
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "store"))
+ lock = Lockfile(tmp_path / "lock.json")
+ monkeypatch.setattr(paths, "lockfile_path", lambda: lock.path)
+ deb = tmp_path / "tool.deb"
+ main = "data/data/com.termux/files/usr/" + relative
+ _build_deb(deb, [(main, b"bionic fixture"), ("data/data/com.termux/files/usr/lib/keep", b"library")])
+ digest = _sha(deb.read_bytes())
+ lock.set_pin(name, "1.0", {TARGET: {"url": "https://example.invalid/tool.deb", "sha256": digest}})
+ lock.save()
+ cached = paths.store_root() / f"fetch-{digest}"
+ cached.mkdir(parents=True)
+ (cached / "tool.deb").write_bytes(deb.read_bytes())
+ paths.facts_path().write_bytes(b'{"schema":1,"packages":{}}')
+ before = paths.facts_path().read_bytes()
+ monkeypatch.setattr("pm.packages.subprocess.run", lambda *a, **kw: pytest.fail("bionic executed on host"))
+ entry = ensure_mod.stage_only(name, TARGET)
+ assert get_package(name).binary(entry, TARGET) == entry / main
+ assert (entry / main).read_bytes() == b"bionic fixture"
+ assert paths.facts_path().read_bytes() == before
+ (entry / main).unlink()
+ assert get_package(name).verify(entry, TARGET)
+
+
@pytest.mark.platforms("linux", arch="x86_64")
def test_real_node_foreign_stage_checks_bytes_without_exec(tmp_path, monkeypatch):
import io
@@ -135,7 +152,8 @@ def test_real_node_foreign_stage_checks_bytes_without_exec(tmp_path, monkeypatch
@pytest.mark.platforms("posix")
-def test_real_node_native_install_keeps_smoke_validation(tmp_path, sandbox, monkeypatch):
[email protected]("compression", ["gz", "xz"])
+def test_real_node_native_install_keeps_smoke_validation(tmp_path, sandbox, monkeypatch, compression):
import io
import tarfile
@@ -146,16 +164,17 @@ def test_real_node_native_install_keeps_smoke_validation(tmp_path, sandbox, monk
probe = tmp_path / "native-probes"
script = f'#!/bin/sh\nprintf "%s\\n" "$1" >> "{probe}"\nexit 0\n'.encode()
archive = io.BytesIO()
- with tarfile.open(fileobj=archive, mode="w:gz") as payload:
+ with tarfile.open(fileobj=archive, mode=f"w:{compression}") as payload:
member = tarfile.TarInfo("node-v1.0/bin/node")
member.mode = 0o755
member.size = len(script)
payload.addfile(member, io.BytesIO(script))
data = archive.getvalue()
- _arm_lock(monkeypatch, [{"url": "https://example.test/node.tar.gz", "sha256": _sha(data)}])
+ _arm_lock(monkeypatch, [{"url": f"https://example.test/node.tar.{compression}", "sha256": _sha(data)}])
cached = sandbox.entry(f"fetch-{_sha(data)}")
cached.mkdir(parents=True)
- (cached / "node.tar.gz").write_bytes(data)
+ (cached / f"node.tar.{compression}").write_bytes(data)
+ monkeypatch.setenv("PATH", "")
package, facts = Nodejs(), ensure_mod._facts()
entry = ensure_mod._install(package, ensure_mod._lockfile(), facts, sandbox, current_target())
assert probe.read_text().splitlines() == ["--version", "--version"]
@@ -164,92 +183,6 @@ def test_real_node_native_install_keeps_smoke_validation(tmp_path, sandbox, monk
assert "23" in package.verify(entry, current_target())
-def test_stage_only_keeps_valid_entry(tmp_path, sandbox, monkeypatch):
- """A published entry that verifies must be returned as-is: the
- verify contract is '' on success, so an inverted predicate here would
- delete and re-fetch a perfectly good entry on every call."""
- payload_a = b"tool-bytes-a"
- _arm_lock(
- monkeypatch,
- [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_a)}],
- )
- _seed_fetch_cache(sandbox, payload_a)
-
- first = ensure_mod.stage_only("stage-test", TARGET)
- assert (first / "bin" / "tool").read_bytes() == payload_a
-
- # Mark the published entry: a delete-and-rebuild loses this file.
- (first / "sentinel").write_text("published")
-
- again = ensure_mod.stage_only("stage-test", TARGET)
- assert again == first
- assert (again / "sentinel").read_text() == "published", (
- "stage_only deleted and rebuilt a VALID published entry"
- )
-
-
-def test_install_repairs_unproven_entry_and_records_facts(tmp_path, sandbox, monkeypatch):
- """_install with no matching facts must RE-REALIZE the entry: an
- unproven entry (nothing vouches its bytes came from this pin) is
- fail-closed rebuilt, then facts are recorded. Same shape as the
- test_pm_authority repin repair, driven through _install directly."""
- payload_a = b"tool-bytes-a"
- _arm_lock(
- monkeypatch,
- [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_a)}],
- )
- _seed_fetch_cache(sandbox, payload_a)
-
- package = ensure_mod.get_package("stage-test")
- facts = ensure_mod._facts()
- store = sandbox
- entry_name = package.store_entry("1.0", TARGET)
- sandbox.entry(entry_name).mkdir(parents=True)
- (sandbox.entry(entry_name) / "bin").mkdir()
- (sandbox.entry(entry_name) / "bin" / "tool").write_bytes(b"stale-bytes")
- (sandbox.entry(entry_name) / "sentinel").write_text("unproven")
-
- ensure_mod._install(package, ensure_mod._lockfile(), facts, store, TARGET)
-
- assert (sandbox.entry(entry_name) / "bin" / "tool").read_bytes() == payload_a, (
- "_install kept an entry nothing proved against the pin"
- )
- assert not (sandbox.entry(entry_name) / "sentinel").exists()
- recorded = facts.get("stage-test")
- assert recorded and recorded["version"] == "1.0"
-
-
-def test_stage_only_repin_same_version_rebuilds(tmp_path, sandbox, monkeypatch):
- """Repinning the SAME version to a different sha256 must rebuild the
- staged entry: without an entry marker the stale bytes are handed back."""
- payload_a = b"tool-bytes-a"
- payload_b = b"tool-bytes-b-repin"
- assert payload_a != payload_b
-
- _arm_lock(
- monkeypatch,
- [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_a)}],
- )
- _seed_fetch_cache(sandbox, payload_a)
- first = ensure_mod.stage_only("stage-test", TARGET)
- assert (first / "bin" / "tool").read_bytes() == payload_a
-
- # Repin: same version, new digest.
- _arm_lock(
- monkeypatch,
- [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_b)}],
- )
- _seed_fetch_cache(sandbox, payload_b)
- repinned = ensure_mod.stage_only("stage-test", TARGET)
- assert (repinned / "bin" / "tool").read_bytes() == payload_b, (
- "stage_only returned stale bytes after a same-version hash repin"
- )
-
- # And the rebuilt entry is again idempotent.
- stable = ensure_mod.stage_only("stage-test", TARGET)
- assert (stable / "bin" / "tool").read_bytes() == payload_b
-
-
@pytest.mark.platforms("windows")
def test_stage_repin_refuses_a_native_directory_hold_then_recovers(sandbox, monkeypatch):
import ctypes
@@ -280,41 +213,3 @@ def test_stage_repin_refuses_a_native_directory_hold_then_recovers(sandbox, monk
kernel.CloseHandle(handle)
ensure_mod.stage_only("stage-test", TARGET)
assert (entry / "bin/tool").read_bytes() == replacement
-
-
[email protected]("error_name", ["HashError", "DownloadPaused"])
-def test_permanent_or_paused_download_is_not_retried(error_name):
- from pm import downloader
- from pm.network import retry_network
-
- def fail():
- raise getattr(downloader, error_name)("stop")
-
- with pytest.raises(getattr(downloader, error_name)):
- retry_network(fail, wait=lambda _: pytest.fail("permanent failure was retried"))
-
-
[email protected]("failure", ["fetch", "publish"])
-def test_repin_failure_preserves_previous_staged_entry(sandbox, monkeypatch, failure):
- payload = b"original"
- _arm_lock(monkeypatch, [{"url": "https://example.test/tool", "sha256": _sha(payload)}])
- _seed_fetch_cache(sandbox, payload)
- entry = ensure_mod.stage_only("stage-test", TARGET)
- marker = (entry / ".pm-stage-pin.json").read_bytes()
-
- replacement = b"replacement"
- _arm_lock(monkeypatch, [{"url": "https://example.test/tool", "sha256": _sha(replacement)}])
- _seed_fetch_cache(sandbox, replacement)
-
- def fail(*args, **kwargs):
- raise InstallError("stage-test", "injected staging failure")
-
- if failure == "fetch":
- monkeypatch.setattr(sandbox, "fetch_many", fail)
- else:
- monkeypatch.setattr(sandbox, "publish", fail)
- with pytest.raises(InstallError, match="injected staging failure"):
- ensure_mod.stage_only("stage-test", TARGET)
-
- assert (entry / "bin/tool").read_bytes() == payload
- assert (entry / ".pm-stage-pin.json").read_bytes() == marker
diff --git a/tests/pm/test_store_extensions.py b/tests/pm/test_store_extensions.py
index 5aad33bf21b..3b53c0b5f66 100644
--- a/tests/pm/test_store_extensions.py
+++ b/tests/pm/test_store_extensions.py
@@ -6,7 +6,7 @@ import pytest
import pm.paths as paths
from pm.lock import Facts, Lockfile
-from tests.pm.test_pm_authority import pm_env, served # noqa: F401 — fixtures
+from tests.pm.test_pm_authority import core_env, pm_env, served # noqa: F401 — fixtures
@pytest.mark.parametrize("sealed_install", [True, False])
diff --git a/tests/pm/test_store_resume.py b/tests/pm/test_store_resume.py
index 47a232028a6..9f5a9ee60b6 100644
--- a/tests/pm/test_store_resume.py
+++ b/tests/pm/test_store_resume.py
@@ -1,21 +1,8 @@
-"""Store.fetch resume end-to-end: a dropped archive download resumes on the
-second Store.fetch instead of re-fetching the whole archive.
-
-A real loopback Range-honoring server, a real tar.gz, no urllib mocking.
-The first fetch is cut short by the server closing the connection mid-body
-(so Store.fetch raises); the second fetch must resume from the durable
-byte-range prefix — requesting only the missing tail, not the whole archive —
-and return bytes that exactly match the original tar.gz. The managed partials
-live OUTSIDE the scratch tempdir (in the store's machine-scoped partials
-area), so the scratch context's finally-rmtree cannot destroy resume state.
-"""
+"""Store scratch cleanup retains resumable bytes outside the scratch directory."""
from __future__ import annotations
import hashlib
-import io
-import tarfile
-from pathlib import Path
import pytest
@@ -23,30 +10,9 @@ from pm.store import Store
import pm.paths as paths
-from tests.pm._range_server import RangeHandler as _Handler, dl_server, url as _url
-
-
-def _make_archive() -> bytes:
- """A real tar.gz, big enough to stream across several 64 KiB serve
- pieces yet small enough (< 1 MiB) that the downloader fans out to ONE
- byte range — keeping the resume shape a single 'missing tail' request
- that the assertions can check literally. The payload is pseudo-random
- (hash chain) so gzip cannot compress it down below the serve-piece
- size, which would collapse the whole body into one write and spare the
- mid-body abort."""
- data = b""
- seed = b"hermes-pm-resume"
- while len(data) < 512 * 1024:
- seed = hashlib.sha256(seed).digest()
- data += seed
- data = data[:512 * 1024]
- buf = io.BytesIO()
- with tarfile.open(fileobj=buf, mode="w:gz") as tf:
- info = tarfile.TarInfo("payload.bin")
- info.size = len(data)
- info.mode = 0o644
- tf.addfile(info, io.BytesIO(data))
- return buf.getvalue()
+from tests.pm._range_server import RangeHandler as _Handler, url as _url
+from tests.pm._range_server import dl_server as dl_server
+
def test_store_fetch_resumes_interrupted_download(tmp_path, dl_server, monkeypatch):
@@ -58,7 +24,7 @@ def test_store_fetch_resumes_interrupted_download(tmp_path, dl_server, monkeypat
# byte range (the shared fixture resets this to 1 MiB).
_Handler.chunk = 1 << 16
- archive_bytes = _make_archive()
+ archive_bytes = bytes(range(256)) * 2048
assert len(archive_bytes) < (1 << 20), "single-range resume assumes < 1 MiB"
name = "faketool-1.0.tar.gz"
_Handler.payloads[f"/{name}"] = archive_bytes
diff --git a/tests/pm/test_sync_failure_detail.py b/tests/pm/test_sync_failure_detail.py
deleted file mode 100644
index 3a1c9d441a3..00000000000
--- a/tests/pm/test_sync_failure_detail.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""A refused sync retains an actionable reason in its persisted receipt."""
-import importlib
-
-import pytest
-
-
-def test_lazy_refusal_records_reason_without_installing(tmp_path, monkeypatch):
- from pm import receipt
- from pm.package import InstallError
-
- ensure = importlib.import_module("pm.ensure")
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: False)
- monkeypatch.setattr("pm.features.read_features", lambda: ["base"])
-
- with pytest.raises(InstallError):
- ensure.sync_venv(["new-extra"])
-
- saved = receipt.latest()
- assert saved["refusal"]["code"] == "lazy-install"
- assert saved["outcome"] == "failed"
- assert saved["exit_code"] != 0
- assert saved["steps"][-1]["ok"] is False
- assert "new-extra" in saved["steps"][-1]["detail"]
- assert "hermes pm install" in saved["steps"][-1]["detail"]
diff --git a/tests/pm/test_update.py b/tests/pm/test_update.py
index 24cdf3f149e..ab461419098 100644
--- a/tests/pm/test_update.py
+++ b/tests/pm/test_update.py
@@ -1,17 +1,12 @@
-"""Pure unit tests for pm.update (no network, no store, no lockfile writes).
-
-The upstream index helpers (github_release_tags, npm_dist_tags, ...) are
-network I/O — covered by design, never in tests. The resolution engine is
-pure: candidate lists in, Resolved decision out.
-"""
+"""Independent resolution decisions; HTTP parsing lives in request-reuse tests."""
from __future__ import annotations
+import pytest
+
from pm.update import (
- Resolved,
best_in_minor,
minor_of,
- resolve_best,
resolve_package,
version_key,
)
@@ -32,9 +27,6 @@ def _pkg(pkg_name="node", version_style="semver", **latest):
return _P()
-# ── version parsing / comparison ───────────────────────────────────────────
-
-
def test_version_key_sorts_numeric_and_suffixes():
assert version_key("2.53.0+5") > version_key("2.53.0+3")
assert version_key("3.14.7+20260901") > version_key("3.14.7+20260900")
@@ -57,211 +49,18 @@ def test_best_in_minor():
assert best_in_minor(versions, (10, 0)) is None
-# ── semver resolution ──────────────────────────────────────────────────────
-
-
-def test_semver_picks_highest_shared_version():
- r = resolve_best(
- "node",
- {"win32-x64": ["26.8.1", "26.7.0"], "linux-x64": ["26.8.1", "26.7.0"]},
- locked="26.7.0",
- style="semver",
- )
- assert r.changed
- assert r.version == "26.8.1"
- assert r.per_target == {"win32-x64": "26.8.1", "linux-x64": "26.8.1"}
-
-
-def test_semver_no_update_when_up_to_date():
- r = resolve_best(
- "node",
- {"win32-x64": ["26.7.0"]},
- locked="26.7.0",
- style="semver",
- )
- assert not r.changed
- assert r.version == "26.7.0"
-
-
-def test_semver_divergent_targets_no_shared_version():
- r = resolve_best(
- "gh",
- {"win32-x64": ["2.97.0"], "linux-x64": ["2.96.0"]},
- locked="2.95.0",
- style="semver",
- )
- assert r.version is None
- assert r.reason == "no shared version"
- assert not r.changed
-
-
-# ── minor-style (ffmpeg) resolution ───────────────────────────────────────
-
-
-def test_minor_style_shared_minor_with_per_target_patches():
- """The cadence-mismatch case: posix and win32 drift in PATCH. The update
- moves to the highest shared major.minor; each target pins its own patch."""
- r = resolve_best(
- "ffmpeg",
- {"linux-x64": ["9.1.2", "9.0.1"], "win32-x64": ["9.1.0", "9.0.1"]},
- locked="9.0.1",
- style="minor",
- )
- assert r.changed
- assert r.version == "9.1"
- assert r.per_target == {"linux-x64": "9.1.2", "win32-x64": "9.1.0"}
-
-
-def test_minor_style_no_shared_minor_blocks_update():
- """posix on 9.1, win32 still on 9.0 — no minor every target serves."""
- r = resolve_best(
- "ffmpeg",
- {"linux-x64": ["9.1.2"], "win32-x64": ["9.0.3"]},
- locked="9.0.1",
- style="minor",
- )
- assert r.version is None
- assert r.reason == "no shared minor"
- assert not r.changed
-
-
-def test_minor_style_patch_drift_within_shared_minor_is_up_to_date():
- """Same minor, patch drift only — the lockfile version label doesn't
- move (patches live in per-target urls)."""
- r = resolve_best(
- "ffmpeg",
- {"linux-x64": ["9.1.2"], "win32-x64": ["9.1.0"]},
- locked="9.1",
- style="minor",
- )
- assert not r.changed
- assert r.version == "9.1"
-
-
-# ── source availability ────────────────────────────────────────────────────
-
-
-def test_no_source_anywhere():
- r = resolve_best("chromium", {"win32-x64": []}, locked="1208+145", style="semver")
- assert r.version is None
- assert r.reason == "no source"
- assert not r.changed
-
-
-def test_missing_source_for_one_target_skipped():
- """A target whose index is unreachable must not block the others."""
- r = resolve_best(
- "node",
- {"win32-x64": ["26.8.1"], "linux-x64": []},
- locked="26.7.0",
- style="semver",
- )
- assert r.changed
- assert r.version == "26.8.1"
-
-
-# ── resolve_package wiring ─────────────────────────────────────────────────
-
-
-def test_resolve_package_calls_latest_versions_per_target():
- pkg = _pkg(
- "node",
- **{
- "win32-x64": ["26.8.1", "26.7.0"],
- "linux-x64": ["26.8.1", "26.7.0"],
- },
- )
- r = resolve_package(pkg, ["win32-x64", "linux-x64"], locked="26.7.0")
- assert isinstance(r, Resolved)
- assert r.changed
- assert r.version == "26.8.1"
-
-
-# ── llama.app installer bucket helpers (pure, monkeypatched) ───────────────
-
-
-def test_llama_app_latest_parses_build_number(monkeypatch):
- from pm import update as u
-
- calls = []
- monkeypatch.setattr(
- u,
- "_get_text",
- lambda url, headers=None: (calls.append((url, headers)) or "b10679\n"),
- )
- assert u.llama_app_latest() == "10679"
- url, headers = calls[0]
- assert url.endswith("/resolve/latest")
- assert headers == {} # no HF_TOKEN → no auth header
-
-
-def test_llama_app_latest_honors_hf_token(monkeypatch):
- from pm import update as u
-
- monkeypatch.setenv("HF_TOKEN", "hf-secret")
- seen = {}
- monkeypatch.setattr(u, "_get_text", lambda url, headers=None: (seen.update(headers) or "b10612\n"))
- assert u.llama_app_latest() == "10612"
- assert seen.get("Authorization") == "Bearer hf-secret"
-
-
-def test_llama_app_latest_unreachable_returns_none(monkeypatch):
- from pm import update as u
-
- monkeypatch.setattr(u, "_get_text", lambda url, headers=None: (_ for _ in ()).throw(OSError("down")))
- assert u.llama_app_latest() is None
-
-
-def test_llama_app_bucket_versions_dedupes_and_sorts(monkeypatch):
- from pm import update as u
-
- # The HF tree API ignores offset and returns only the FIRST page —
- # the oldest ~1000 paths sorted by path ascending. The helper must
- # dedupe (the same build appears on many paths) and sort by build
- # number descending so the newest of what the tree can see comes first.
- page = [
- {"path": "b10326/aarch64/linux/cpu/kk/llama-app.zst"},
- {"path": "b10098/x86_64/linux/vulkan/kk/llama-app.zst"},
- {"path": "b10326/x86_64/windows/cuda/13/kk/llama-app.exe.zst"}, # dup
- {"path": "b9733/aarch64/macos/metal/kk/llama-app.zst"},
- {"path": "latest/whatever"}, # non-build path must be ignored
- ]
- monkeypatch.setattr(u, "_get_json", lambda url: page)
- assert u.llama_app_bucket_versions() == ["10326", "10098", "9733"]
-
-
-def test_llama_app_bucket_versions_unreachable_returns_empty(monkeypatch):
- from pm import update as u
-
- monkeypatch.setattr(u, "_get_json", lambda url: (_ for _ in ()).throw(OSError("down")))
- assert u.llama_app_bucket_versions() == []
-
-
-def test_llamacpp_latest_versions_prefers_bucket(monkeypatch):
- """The real LlamaCppCpu class: latest from the llama.app `latest`
- pointer first, then the bucket tree, GitHub only as a fallback.
- Patching targets the from-imported names in pm.packages (a from-import
- copies the reference at import time — patching pm.update would miss)."""
- import pm.packages as pkgs
-
- monkeypatch.setattr(pkgs, "llama_app_latest", lambda: "10679")
- monkeypatch.setattr(pkgs, "llama_app_bucket_versions", lambda: ["10679", "10612", "10362"])
- called = []
- monkeypatch.setattr(pkgs, "github_release_tags", lambda *a, **k: (called.append(a) or ["99999"]))
-
- pkg = pkgs.LlamaCppCpu()
- versions = pkg.latest_versions("linux-x64")
- assert versions == ["10679", "10679", "10612", "10362"]
- assert called == [] # GitHub never consulted when the bucket answered
-
-
-def test_llamacpp_latest_versions_github_fallback(monkeypatch):
- """Bucket unreachable → fall back to the GitHub releases tags."""
- import pm.packages as pkgs
-
- monkeypatch.setattr(pkgs, "llama_app_latest", lambda: None)
- monkeypatch.setattr(pkgs, "llama_app_bucket_versions", lambda: [])
- monkeypatch.setattr(pkgs, "github_release_tags", lambda *a, **k: ["10362", "10217"])
-
- pkg = pkgs.LlamaCppCpu()
- assert pkg.latest_versions("linux-x64") == ["10362", "10217"]
[email protected]("style, candidates, locked, version, per_target, changed, reason", [
+ ("semver", {"a": ["10.0.1", "9.0.3"], "b": ["9.0.3", "10.0.1"]}, "9.0.3", "10.0.1", {"a": "10.0.1", "b": "10.0.1"}, True, ""),
+ ("semver", {"a": ["26.7.0"]}, "26.7.0", "26.7.0", {"a": "26.7.0"}, False, ""),
+ ("semver", {"a": ["2.97.0"], "b": ["2.96.0"]}, "2.95.0", None, {}, False, "no shared version"),
+ ("minor", {"a": ["9.1.2", "9.0.1"], "b": ["9.1.0", "9.0.1"]}, "9.0.1", "9.1", {"a": "9.1.2", "b": "9.1.0"}, True, ""),
+ ("minor", {"a": ["9.1.2"], "b": ["9.0.3"]}, "9.0.1", None, {}, False, "no shared minor"),
+ ("minor", {"a": ["9.1.2"], "b": ["9.1.0"]}, "9.1", "9.1", {"a": "9.1.2", "b": "9.1.0"}, False, ""),
+ ("semver", {"a": []}, "1208+145", None, {}, False, "no source"),
+ ("semver", {"a": ["26.8.1"], "b": []}, "26.7.0", "26.8.1", {"a": "26.8.1"}, True, ""),
+])
+def test_resolve_package_decisions(style, candidates, locked, version, per_target, changed, reason):
+ result = resolve_package(_pkg(version_style=style, **candidates), list(candidates), locked=locked)
+ assert (result.version, result.per_target, result.changed) == (version, per_target, changed)
+ if reason:
+ assert result.reason == reason
diff --git a/tests/pm/test_update_request_reuse.py b/tests/pm/test_update_request_reuse.py
index db0d126057f..bb157a44555 100644
--- a/tests/pm/test_update_request_reuse.py
+++ b/tests/pm/test_update_request_reuse.py
@@ -166,6 +166,27 @@ def test_resolution_reuses_successful_responses_but_refreshes_next_operation(ups
assert Counter(path for path, _ in calls) == dict.fromkeys(RangeHandler.payloads, 1)
[email protected]("pointer, tree, expected", [
+ ("b10679\n", [{"path": "b10326/linux"}, {"path": "b10098/win"}, {"path": "b10326/mac"}, {"path": "b9733/mac"}, {"path": "latest/other"}], ["10679", "10326", "10098", "9733"]),
+ (None, [], ["10362", "10217"]),
+ ("malformed", [{"path": "not-a-build"}, {}], ["10362", "10217"]),
+])
+def test_llama_real_index_fallback(upstream, monkeypatch, pointer, tree, expected):
+ calls, _ = upstream
+ monkeypatch.delenv("HF_TOKEN", raising=False)
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ latest = "/buckets/ggml-org/install.sh/resolve/latest"
+ if pointer is not None:
+ RangeHandler.payloads[latest] = pointer.encode()
+ RangeHandler.payloads["/api/buckets/ggml-org/install.sh/tree?limit=1000&offset=0"] = json.dumps(tree).encode()
+ github = "/repos/ggml-org/llama.cpp/releases?per_page=30&page=1"
+ RangeHandler.payloads[github] = b'[{"tag_name":"b10362"},{"tag_name":"b10217"}]'
+ assert packages.LlamaCppCpu().latest_versions("linux-x64") == expected
+ assert all(auth is None for _, auth in calls)
+ assert any(path == github for path, _ in calls) is (pointer != "b10679\n")
+
+
def test_pinning_hashes_new_npm_url_once_and_keeps_existing_rows(upstream, tmp_path, monkeypatch):
calls, failures = upstream
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "store"))
diff --git a/tests/pm/test_uv_cache.py b/tests/pm/test_uv_cache.py
index 1b92803a470..e9c7fcab945 100644
--- a/tests/pm/test_uv_cache.py
+++ b/tests/pm/test_uv_cache.py
@@ -15,31 +15,6 @@ def isolated_machine_home(tmp_path, monkeypatch):
-def test_managed_environment_pins_cache_dir(monkeypatch, tmp_path):
- import shutil
- import sys
- from pm.environment import managed_environment
-
- uv = shutil.which("uv")
- assert uv
- monkeypatch.setattr("pm._uv._toolchain", lambda **kw: (Path(uv), Path(sys.executable)))
- cache = tmp_path / "cache"
- monkeypatch.setattr(pkgs, "uv_cache_dir", lambda: cache)
- hostile = tmp_path / "ambient-cache"
- monkeypatch.setenv("UV_CACHE_DIR", str(hostile))
- project = tmp_path / "project"
- project.mkdir()
- (project / "pyproject.toml").write_text(
- '[project]\nname="cache-proof"\nversion="1"\nrequires-python=">=3.11"\n'
- '[tool.uv]\npackage=false\n', encoding="utf-8",
- )
- environment = managed_environment(tmp_path / "candidate", offline=True)
- environment.create()
- environment.lock(project)
- environment.sync(project)
- assert cache.is_dir()
- assert not hostile.exists()
-
def test_uv_cache_dir_seeds_from_payload(monkeypatch, tmp_path):
home = tmp_path / "home"
@@ -81,10 +56,8 @@ def test_uv_cache_dir_cold_machine_no_payload(monkeypatch, tmp_path):
assert (machine / ".seeded").is_file()
[email protected]("lazy_allowed", [False, True])
-def test_bundle_uses_shipped_environment_until_an_extension_is_committed(monkeypatch, tmp_path, lazy_allowed):
+def test_bundle_uses_shipped_environment_until_an_extension_is_committed(monkeypatch, tmp_path):
import json
- import importlib
import pm.paths as paths
home = tmp_path / "home"
@@ -96,6 +69,6 @@ def test_bundle_uses_shipped_environment_until_an_extension_is_committed(monkeyp
shipped.mkdir()
(payload / "manifest.json").write_text(json.dumps({"repo": "hermes-agent", "venv": "venv"}))
monkeypatch.setattr(paths, "repo_root", lambda: core)
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "lazy_installs_allowed", lambda: lazy_allowed)
+
assert pkgs.Venv().venv_dir() == shipped
assert not home.exists(), "selecting shipped dependencies must not copy or mutate them"
diff --git a/tests/pm/test_venv_stamp.py b/tests/pm/test_venv_stamp.py
deleted file mode 100644
index f3cc3e15df9..00000000000
--- a/tests/pm/test_venv_stamp.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""Dependency freshness follows PM's interpreter identity, not unrelated tools."""
-from pm.lock import Lockfile
-from pm.packages import Venv
-from pm.store import current_target
-
-
-def test_venv_stamp_tracks_the_python_pin(tmp_path, monkeypatch):
- from pm import paths
-
- core = tmp_path / "core"
- core.mkdir()
- (core / "uv.lock").write_bytes(b"unchanged dependency lock")
- lock = Lockfile(tmp_path / "pm-lock.json")
- target = current_target()
- artifact = {"url": "https://example.invalid/python", "sha256": "1" * 64}
- lock.set_pin("python", "test.1", {target: artifact})
- lock.save()
- monkeypatch.setattr(paths, "repo_root", lambda: core)
- monkeypatch.setattr(paths, "lockfile_path", lambda: lock.path)
- venv = Venv()
- original = venv.expected_stamp([], plugin_dirs=[])
-
- lock.set_pin("uv", "unrelated", {target: artifact})
- lock.save()
- assert venv.expected_stamp([], plugin_dirs=[]) == original
-
- # Repacked interpreter bytes are a new input even at the same version.
- artifact = {**artifact, "sha256": "2" * 64}
- lock.set_pin("python", "test.1", {target: artifact})
- lock.save()
- repinned = venv.expected_stamp([], plugin_dirs=[])
- assert repinned != original
-
- lock.set_pin("python", "test.2", {target: artifact})
- lock.save()
- assert venv.expected_stamp([], plugin_dirs=[]) != repinned
diff --git a/tests/pm/test_venv_sync_ambient_config.py b/tests/pm/test_venv_sync_ambient_config.py
index af093f80e6e..e76e61e02bc 100644
--- a/tests/pm/test_venv_sync_ambient_config.py
+++ b/tests/pm/test_venv_sync_ambient_config.py
@@ -38,6 +38,7 @@ def test_ambient_uv_config_does_not_affect_pm_venv_sync(tmp_path, monkeypatch):
"UV_NO_CONFIG": "1", "UV_CONFIG_FILE": "/poison/uv.toml",
"UV_DEFAULT_INDEX": "https://poison.invalid/simple", "UV_PYTHON": "/poison/python",
"UV_PROJECT_ENVIRONMENT": str(tmp_path / "unrelated-environment"),
+ "UV_CACHE_DIR": str(tmp_path / "hostile-cache"),
"UV_PROJECT": "/poison/project", "VIRTUAL_ENV": "/poison/venv",
"PYTHONPATH": "/poison/imports", "XDG_CONFIG_HOME": str(config), "XDG_CONFIG_DIRS": str(config),
}.items():
@@ -51,6 +52,8 @@ def test_ambient_uv_config_does_not_affect_pm_venv_sync(tmp_path, monkeypatch):
environment.sync(project, locked=True)
environment.check()
assert environment.executable.is_file()
+ assert environment.cache.is_dir()
+ assert not (tmp_path / "hostile-cache").exists()
assert not (tmp_path / "unrelated-environment").exists()
assert (project / "uv.lock").read_bytes() == locked
assert dict(os.environ) == before
diff --git a/tests/pm/test_worker.py b/tests/pm/test_worker.py
index a602fba83f1..5dff704f07f 100644
--- a/tests/pm/test_worker.py
+++ b/tests/pm/test_worker.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import importlib
-import os
from pathlib import Path
import subprocess
import shutil
@@ -34,36 +33,6 @@ def test_isolated_worker_preserves_install_error(client, monkeypatch):
assert not paths.facts_path().exists()
-def test_worker_build_owns_creation_and_preserves_parent_environment(build_worker, tmp_path, monkeypatch):
- import json
- client = build_worker
- source = tmp_path / "project with spaces"
- source.mkdir()
- wheels = tmp_path / "wheels"
- wheels.mkdir()
- _wheel(wheels, "worker_dep")
- (source / "pyproject.toml").write_text(
- '[project]\nname="worker-proof"\nversion="1"\nrequires-python=">=3.11"\n'
- 'dependencies=["worker-dep==1.0"]\n[tool.uv]\npackage=false\nno-index=true\n'
- f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8",
- )
- monkeypatch.setenv("UV_PYTHON", "/not-the-interpreter")
- monkeypatch.setenv("UV_PROJECT_ENVIRONMENT", str(tmp_path / "wrong-environment"))
- monkeypatch.setenv("VIRTUAL_ENV", str(tmp_path / "wrong-environment"))
- before = dict(os.environ)
- python = client.build_environment(source=source, out=tmp_path / "dependency tree",
- frozen=False, offline=True, explicit=True)
- result = subprocess.run([str(python), "-I", "-c", "import json,sys,worker_dep; print(json.dumps([sys.prefix, worker_dep.__version__]))"],
- capture_output=True, text=True, timeout=30)
- assert result.returncode == 0, result.stderr
- assert json.loads(result.stdout) == [str(python.parent.parent), "1.0"]
- assert "worker_dep" not in sys.modules
- assert not (tmp_path / "wrong-environment").exists()
- assert dict(os.environ) == before
- with pytest.raises(OSError, match="already exists"):
- client.build_environment(source=source, out=python.parent.parent, explicit=True)
- assert python.is_file()
-
def test_refused_or_already_paused_install_does_not_acquire_runtime(client, monkeypatch):
import threading
@@ -138,6 +107,12 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, m
return {path.relative_to(tmp_path): (path.read_bytes() if path.is_file() else None)
for path in tmp_path.rglob("*")}
+ from pm.lock import Lockfile
+ pins = Lockfile(paths.lockfile_path())
+ pins.set_pin("python", "test.1", {"any": {"url": "https://example.invalid/python", "sha256": "1" * 64}})
+ pins.save()
+ Facts(facts_path).record_state("venv", Venv(repo).expected_stamp(recorded, plugin_dirs=members), recorded,
+ environment=environment)
before = snapshot()
assert client.venv_is_current(extras=["provider-extra"], plugin_dirs=members, **root_args)
assert client.venv_is_current(extras=[], plugin_dirs=members, **root_args)
@@ -145,6 +120,27 @@ def test_currency_probe_preserves_union_and_candidate_inputs(client, tmp_path, m
assert not client.venv_is_current(extras=recorded, plugin_dirs=[], **root_args)
assert snapshot() == before, "currency queries changed dependency state"
assert bool(acquisitions) is (route != "direct")
+ pins.set_pin("uv", "unrelated", {"any": {"url": "https://example.invalid/uv", "sha256": "3" * 64}})
+ pins.save()
+ unchanged = snapshot()
+ assert client.venv_is_current(extras=[], plugin_dirs=members, **root_args)
+ assert snapshot() == unchanged
+ for version, digest in [("test.1", "2" * 64), ("test.2", "1" * 64)]:
+ pins.set_pin("python", version, {"any": {"url": "https://example.invalid/python", "sha256": digest}})
+ pins.save()
+ changed = snapshot()
+ assert not client.venv_is_current(plugin_dirs=members, **root_args)
+ assert snapshot() == changed
+ pins.set_pin("python", "test.1", {"any": {"url": "https://example.invalid/python", "sha256": "1" * 64}})
+ pins.save()
+ marker = environment / "pyvenv.cfg"
+ contents = marker.read_bytes()
+ marker.unlink()
+ changed = snapshot()
+ assert not client.venv_is_current(plugin_dirs=members, **root_args)
+ assert snapshot() == changed
+ marker.write_bytes(contents)
+ assert client.venv_is_current(plugin_dirs=members, **root_args)
manifest.write_text('name: candidate\npython_dependencies: ["candidate-dep==2"]\n')
changed = snapshot()
@@ -174,7 +170,7 @@ def test_sync_discovers_profile_members_after_worker_acquires_lock(client, tmp_p
from concurrent.futures import ThreadPoolExecutor
import time
from hermes_cli.runtime_state import runtime_lock
- from tests.pm.test_worker_publication import worker_toolchain
+ from tests.pm._fixtures import worker_toolchain
sibling = tmp_path / "home/profiles/sibling/plugins/dependency"
sibling.mkdir(parents=True)
@@ -466,7 +462,7 @@ def test_resolution_conflict_survives_worker_and_receipt(client, tmp_path, monke
def test_failed_facts_write_restores_exact_config_before_reporting(client, tmp_path, monkeypatch, isolated_python):
- from tests.pm.test_worker_publication import worker_toolchain
+ from tests.pm._fixtures import worker_toolchain
from hermes_cli.runtime_paths import install_state_dir
repo = _current_environment(tmp_path, monkeypatch, [])
@@ -508,18 +504,8 @@ def test_foreign_checkout_sync_uses_its_own_pm_generation(client, tmp_path, monk
from pm import venv_is_current
from hermes_cli.runtime_paths import selected_venv, runtime_facts_path
- uv = shutil.which("uv")
- assert uv
- worker = Path(client.__file__).with_name("worker.py")
- script = (
- "import runpy, sys; "
- f"sys.path.insert(0, {str(worker.parent.parent)!r}); "
- "import pm._uv; "
- f"pm._uv._toolchain = lambda **kwargs: (__import__('pathlib').Path({uv!r}), "
- f"__import__('pathlib').Path({sys.executable!r})); "
- f"runpy.run_path({str(worker)!r}, run_name='__main__')"
- )
- monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])
+ from tests.pm._fixtures import worker_toolchain
+ worker_toolchain(client, monkeypatch, isolated_python)
foreign = tmp_path / "other checkout"
foreign.mkdir()
(foreign / "pyproject.toml").write_text(
@@ -562,18 +548,8 @@ def test_worker_side_environment_reuses_and_keeps_selection_on_failed_tool(clien
import zipfile
from pm import environment_python, python_tool
- uv = shutil.which("uv")
- assert uv
- worker = Path(client.__file__).with_name("worker.py")
- script = (
- "import runpy, sys; "
- f"sys.path.insert(0, {str(worker.parent.parent)!r}); "
- "import pm._uv; "
- f"pm._uv._toolchain = lambda **kwargs: (__import__('pathlib').Path({uv!r}), "
- f"__import__('pathlib').Path({sys.executable!r})); "
- f"runpy.run_path({str(worker)!r}, run_name='__main__')"
- )
- monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])
+ from tests.pm._fixtures import worker_toolchain
+ worker_toolchain(client, monkeypatch, isolated_python)
wheel = _wheel(tmp_path, "side_dep")
with zipfile.ZipFile(wheel, "a") as archive:
archive.writestr("side_dep/cli.py", "def main():\n print('real side dependency')\n")
diff --git a/tests/pm/test_worker_publication.py b/tests/pm/test_worker_publication.py
index 3209f32dd9a..dd2b6e4114f 100644
--- a/tests/pm/test_worker_publication.py
+++ b/tests/pm/test_worker_publication.py
@@ -11,6 +11,7 @@ from pathlib import Path
import pytest
from tests.pm.test_worker import client, isolated_python, _current_environment # noqa: F401
+from tests.pm._fixtures import worker_toolchain
def test_worker_publishes_selection_even_when_dependencies_are_current(client, tmp_path, monkeypatch):
@@ -40,19 +41,6 @@ def test_worker_publishes_selection_even_when_dependencies_are_current(client, t
assert json.loads((home / "logs/update_receipts/latest.json").read_text())["outcome"] == "ok"
-def worker_toolchain(client, monkeypatch, isolated_python, injection=""):
- uv = shutil.which("uv")
- assert uv
- worker = Path(client.__file__).with_name("worker.py")
- script = (
- "import runpy, sys, os; from pathlib import Path; "
- f"sys.path.insert(0, {str(worker.parent.parent)!r}); "
- "import pm._uv; "
- f"pm._uv._toolchain = lambda **kwargs: (Path({uv!r}), Path({sys.executable!r}));\n"
- + injection + f"\nrunpy.run_path({str(worker)!r}, run_name='__main__')"
- )
- monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])
-
@pytest.mark.parametrize("active", [False, True])
@pytest.mark.parametrize("missing", [False, True], ids=["existing", "missing"])
@@ -142,7 +130,7 @@ def test_selection_refuses_config_edits_during_preparation(client, tmp_path, mon
@pytest.mark.parametrize("invalid", ["name: [", "manifest_version: 999", "requires_hermes: '>=999'", "name: other"])
def test_worker_rejects_unloadable_staged_plugin_without_app_dependencies(client, tmp_path, monkeypatch, invalid):
from pm.store import tree_digest
- repo = _current_environment(tmp_path, monkeypatch, [])
+ _current_environment(tmp_path, monkeypatch, [])
target = tmp_path / "home/plugins/example"
target.mkdir(parents=True)
(target / "plugin.yaml").write_text("name: example\n")
@@ -252,9 +240,9 @@ def test_worker_death_recovers_at_each_durable_publication_boundary(
assert (state / "publication.json").exists()
source = Path(client.__file__).resolve().parent.parent
program = (f"import sys; sys.path.insert(0, {str(source)!r}); from pathlib import Path; "
- "from hermes_cli.runtime_state import runtime_lock, recover_publication; "
+ "from hermes_cli.runtime_paths import activate_dependencies; "
f"project = Path({str(project)!r})\n"
- "with runtime_lock(project):\n recover_publication(project)\n recover_publication(project)\n")
+ "activate_dependencies(project)\nactivate_dependencies(project)\n")
recovery = subprocess.run([sys.executable, "-I", "-S", "-c", program], capture_output=True, text=True,
env=dict(os.environ), timeout=30)
assert recovery.returncode == 0, recovery.stderr
diff --git a/tests/pm/test_worker_registry.py b/tests/pm/test_worker_registry.py
index 788ff343d26..b3e491ae4a3 100644
--- a/tests/pm/test_worker_registry.py
+++ b/tests/pm/test_worker_registry.py
@@ -10,7 +10,6 @@ import os
from pathlib import Path
import subprocess
import sys
-import shutil
import tarfile
import textwrap
@@ -18,6 +17,7 @@ import pytest
import pm
from pm import registry
+from tests.pm._fixtures import isolated_python as worker_python # noqa: F401
from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
@@ -26,15 +26,6 @@ def restore_registry(monkeypatch):
monkeypatch.setattr(registry, "_packages", dict(registry._packages))
[email protected](scope="module")
-def worker_python(tmp_path_factory):
- from pm.runtime_stage import stage_runtime
-
- environment = tmp_path_factory.mktemp("registry-worker-python")
- uv = shutil.which("uv")
- assert uv, "the worker contract requires real uv"
- return stage_runtime(Path(uv), Path(sys.executable), environment)
-
@pytest.mark.parametrize("operation", ["ensure", "stage_only"])
def test_registered_package_installs_archive_in_real_worker(tmp_path, monkeypatch, worker_python, dl_server, operation):
@@ -58,7 +49,8 @@ def test_registered_package_installs_archive_in_real_worker(tmp_path, monkeypatc
def verify(self, entry, target):
return '' if (entry / 'payload.txt').read_text() == 'plugin archive' else 'bad payload'
"""))
- _load_file(source, monkeypatch)
+ module = _load_file(source, monkeypatch)
+ pm.register(module.ArchivePackage)
payload = b"plugin archive"
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode="w:gz") as archive:
@@ -171,7 +163,6 @@ def test_file_registered_package_runs_its_own_definition_in_child(tmp_path, monk
source.write_text(textwrap.dedent("""\
from pm import Package, InstallError, register
- @register
class ExternalPackage(Package):
name = "external-worker-test"
diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.py
index 2f0e5a44fab..5382373ed48 100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@ -11,7 +11,6 @@ from __future__ import annotations
import os
import subprocess
-import json
import shutil
import sys
from pathlib import Path
@@ -20,6 +19,7 @@ import pytest
import pm.workspace as ws
from pm.environment import managed_environment
+from tests.pm.test_environment_build import locked_project # noqa: F401
@pytest.fixture(autouse=True)
@@ -29,76 +29,15 @@ def isolated_machine_home(tmp_path, monkeypatch):
@pytest.fixture
-def layout(tmp_path, monkeypatch):
- """A fake install: core repo with pyproject, plugin dirs, store."""
- from tests.pm._fixtures import _wheel
-
- wheels = tmp_path / "wheels"
- wheels.mkdir()
- _wheel(wheels, "httpx", "0.28.1")
- _wheel(wheels, "rich", "13.9.4")
- uv = shutil.which("uv")
- assert uv
- monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
- core = tmp_path / "core"
- core.mkdir()
- (core / "pyproject.toml").write_text(
- "[project]\n"
- 'name = "hermes-agent"\n'
- 'version = "0.1.0"\n'
- 'requires-python = ">=3.11"\n'
- 'dependencies = ["httpx==0.28.1"]\n'
- '[tool.uv]\npackage=false\nno-index=true\n'
- f'find-links=[{json.dumps(wheels.as_posix())}]\n',
- encoding="utf-8",
- )
- plugins = tmp_path / "home" / "plugins"
- plug_a = plugins / "plug-a"
- plug_a.mkdir(parents=True)
- (plug_a / "plugin.yaml").write_text("name: plug-a\n", encoding="utf-8")
- (plug_a / "pyproject.toml").write_text(
- "[project]\nname = \"plug-a\"\nversion = \"0.1.0\"\n"
- 'requires-python = ">=3.11"\ndependencies = ["rich==13.9.4"]\n',
- encoding="utf-8",
- )
- store = tmp_path / "store"
- store.mkdir()
+def layout(locked_project, tmp_path, monkeypatch):
+ core, uv, _ = locked_project
+ manifest = core / "pyproject.toml"
+ manifest.write_text(manifest.read_text().replace('[tool.uv.workspace]\nmembers=["member"]\n', ""))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (uv, Path(sys.executable)))
monkeypatch.setattr(ws.paths, "repo_root", lambda: core)
- monkeypatch.setattr(ws.paths, "store_root", lambda: store)
- return tmp_path, core, plug_a, store
+ return tmp_path, core, core / "member", tmp_path / "store"
-def test_build_writes_core_pyproject_verbatim(layout):
- tmp, core, plug_a, _ = layout
- root = tmp / "workspace"
- ws.lock_and_sync([plug_a], [], root=root, source=core, seed_lock=None,
- environment=managed_environment(tmp / "env"))
- text = (root / "pyproject.toml").read_text(encoding="utf-8")
- core_text = (core / "pyproject.toml").read_text(encoding="utf-8")
- # core's project table is carried verbatim (name, deps, requires-python)
- assert 'name = "hermes-agent"' in text
- assert 'dependencies = ["httpx==0.28.1"]' in text
- assert 'requires-python = ">=3.11"' in text
- # nothing else was invented
- for line in core_text.strip().splitlines():
- assert line in text
-
-
-def test_members_keep_their_source_with_the_generation(layout):
- import tomllib
-
- tmp, core, plug_a, _ = layout
- root = tmp / "workspace"
- ws.lock_and_sync([plug_a], [], root=root, source=core, seed_lock=None,
- environment=managed_environment(tmp / "env"))
- document = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
- [relative] = document["tool"]["uv"]["workspace"]["members"]
- copied = root / relative / "pyproject.toml"
- assert copied.resolve().is_relative_to(root.resolve())
- before = copied.read_bytes()
- assert before == (plug_a / "pyproject.toml").read_bytes()
- (plug_a / "pyproject.toml").write_bytes(b"changed after publication")
- assert copied.read_bytes() == before
def test_preparation_refuses_existing_workspace_without_mutating_it(layout):
@@ -125,126 +64,11 @@ def test_missing_explicit_seed_cannot_silently_resolve_new_versions(layout):
assert not (tmp / "env").exists()
-def test_zero_plugins_still_builds_a_root_with_no_members(layout):
- tmp, core, _, _ = layout
- root = tmp / "workspace"
- ws.lock_and_sync([], [], root=root, source=core, seed_lock=None,
- environment=managed_environment(tmp / "env"))
- text = (root / "pyproject.toml").read_text(encoding="utf-8")
- assert 'name = "hermes-agent"' in text
- assert "[tool.uv.workspace]" not in text or "members = []" in text
-
-
-def test_member_stamp_hash_changes_with_plugin_set(layout):
- _, _, plug_a, _ = layout
- stamp_empty = ws.members_stamp([])
- stamp_a = ws.members_stamp([plug_a])
- stamp_b = ws.members_stamp([plug_a, plug_a]) # dedupes to same set
- assert stamp_empty != stamp_a
- assert stamp_a == stamp_b
-
-
-def test_member_stamp_changes_when_pyproject_content_changes(tmp_path):
- """Task 4 contract: a pulled plugin with changed pins must move the
- stamp — path-only hashing left dep bumps invisible to the venv sync."""
- plug = tmp_path / "plug"
- plug.mkdir()
- (plug / "pyproject.toml").write_text(
- 'dependencies = ["pkg==1.0.0"]\n', encoding="utf-8"
- )
- before = ws.members_stamp([plug])
- # the plugin update: same dir, new pins
- (plug / "pyproject.toml").write_text(
- 'dependencies = ["pkg==2.0.0"]\n', encoding="utf-8"
- )
- after = ws.members_stamp([plug])
- assert before != after
- # no pyproject at all: still hashable (the dir identity carries it)
- bare = tmp_path / "bare"
- bare.mkdir()
- assert ws.members_stamp([bare]) != before
-
-
-def test_member_stamp_missing_pyproject_does_not_crash(tmp_path):
- """A member dir whose pyproject vanished mid-scan hashes on path only."""
- plug = tmp_path / "ghost"
- plug.mkdir()
- (plug / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
- first = ws.members_stamp([plug])
- (plug / "pyproject.toml").unlink()
- second = ws.members_stamp([plug])
- assert first != second # content term dropped out, stamp moved
-
-
-def test_enabled_member_dirs_finds_enabled_dep_plugins(tmp_path, monkeypatch):
- plugins = tmp_path / "plugins"
- plugins.mkdir(parents=True)
-
- # modern plugin: pyproject.toml
- modern = plugins / "modern-plug"
- modern.mkdir()
- (modern / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
-
- # legacy plugin: pip_dependencies in plugin.yaml, no pyproject
- legacy = plugins / "legacy-plug"
- legacy.mkdir()
- (legacy / "plugin.yaml").write_text(
- "name: legacy-plug\npip_dependencies:\n - \"requests>=2\"\n",
- encoding="utf-8",
- )
-
- # dep-less plugin: neither — not a member even when enabled
- plain = plugins / "plain-plug"
- plain.mkdir()
- (plain / "plugin.yaml").write_text("name: plain-plug\n", encoding="utf-8")
-
- # dep-carrying but NOT-ENABLED plugin — must not join the union
- orphan = plugins / "orphan-plug"
- orphan.mkdir()
- (orphan / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
-
- # enabled order = enable recency (legacy enabled first/older, modern
- # newest LAST) — discovery preserves the configured order.
- monkeypatch.setattr(
- "pm.plugins_state.enabled_plugins_ordered",
- lambda **kwargs: {plugins: ["legacy-plug", "modern-plug", "plain-plug"]},
- )
- found = ws.enabled_member_dirs()
- names = [p.name for p in found]
- assert names == ["legacy-plug", "modern-plug"]
- assert "orphan-plug" not in names
-
-
-def test_enabled_member_dirs_empty_when_nothing_enabled(tmp_path, monkeypatch):
- plugins = tmp_path / "plugins"
- plugins.mkdir(parents=True)
- member = plugins / "member"
- member.mkdir()
- (member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
-
- monkeypatch.setattr(
- "pm.plugins_state.enabled_plugins_ordered", lambda **kwargs: {}
- )
- assert ws.enabled_member_dirs() == []
-
-
-def test_enabled_member_dirs_ignores_non_profile_entries(tmp_path, monkeypatch):
- import pm.plugins_state as pstate
-
- home = tmp_path / "home"
- profiles = home / "profiles"
- profiles.mkdir(parents=True)
- member = profiles / "work" / "plugins" / "member"
- member.mkdir(parents=True)
- (member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
- (profiles / "work" / "config.yaml").write_text(
- "plugins:\n enabled: [member]\n", encoding="utf-8",
- )
- (profiles / "README.txt").write_text("not a profile", encoding="utf-8")
- monkeypatch.setattr("hermes_cli.runtime_paths.dependency_home_root", lambda: home)
-
- assert pstate._all_homes() == [home, profiles / "work"]
- assert ws.enabled_member_dirs() == [member]
+
+
+
+
+
# --- classified failures + staging surface (FINAL-RUNTIME-CONTRACT) ---
diff --git a/tests/pm/test_workspace_build_inputs.py b/tests/pm/test_workspace_build_inputs.py
index 3752b19f5f0..459e7b7793e 100644
--- a/tests/pm/test_workspace_build_inputs.py
+++ b/tests/pm/test_workspace_build_inputs.py
@@ -18,21 +18,51 @@ def isolated_machine_home(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+def _buildable_source(plugin):
+ (plugin / "build").mkdir(parents=True, exist_ok=True)
+ (plugin / "pyproject.toml").write_text(
+ '[project]\nname="replay-plugin"\nversion="1.0"\nrequires-python=">=3.11"\nreadme="README.md"\nlicense="MIT"\nlicense-files=["LICENSE"]\n'
+ '[build-system]\nrequires=[]\nbuild-backend="backend"\nbackend-path=["build"]\n',
+ encoding="utf-8",
+ )
+ (plugin / "plugin.yaml").write_text("name: replay-plugin\n", encoding="utf-8")
+ (plugin / "replay_plugin.py").write_text("VALUE = 'recorded plugin bytes'\n", encoding="utf-8")
+ (plugin / "README.md").write_text("# fixture readme")
+ (plugin / "LICENSE").write_text("MIT")
+ # The backend must consume the copied metadata inputs too.
+ (plugin / "build/backend.py").write_text('''
+from pathlib import Path
+from zipfile import ZipFile
+
+def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
+ assert Path("README.md").read_text() == "# fixture readme"
+ assert Path("LICENSE").read_text() == "MIT"
+ name = "replay_plugin-1.0-py3-none-any.whl"
+ dist = "replay_plugin-1.0.dist-info"
+ entries = {
+ "replay_plugin.py": Path("replay_plugin.py").read_bytes(),
+ dist + "/METADATA": "Metadata-Version: 2.1\\nName: replay-plugin\\nVersion: 1.0\\n",
+ dist + "/WHEEL": "Wheel-Version: 1.0\\nRoot-Is-Purelib: true\\nTag: py3-none-any\\n",
+ }
+ entries[dist + "/RECORD"] = "".join(path + ",,\\n" for path in entries)
+ with ZipFile(Path(wheel_directory) / name, "w") as wheel:
+ for path, body in entries.items():
+ wheel.writestr(path, body)
+ return name
+
+build_editable = build_wheel
+''', encoding="utf-8")
+
+
def test_real_build_inputs_stay_in_generated_root(tmp_path, monkeypatch):
core = tmp_path / "core"
core.mkdir()
- (core / "pyproject.toml").write_text(
- '[project]\nname="buildable-core"\nversion="1.0"\nreadme="README.md"\n'
- 'requires-python=">=3.11"\nlicense="MIT"\nlicense-files=["LICENSE"]\n'
- '[build-system]\nrequires=["setuptools==83.0.0","wheel==0.46.3"]\n'
- 'build-backend="setuptools.build_meta"\n'
- '[tool.setuptools.packages.find]\ninclude=["buildable_core", "buildable_core.*"]\n', encoding="utf-8",
- )
- (core / "README.md").write_text("# Real core\n")
- (core / "LICENSE").write_text("MIT\n")
- package = core / "buildable_core"
- package.mkdir()
- (package / "__init__.py").write_text("VALUE = 'from actual source'\n")
+ _buildable_source(core)
+ # Core snapshots exclude build/ output; the member replay below deliberately
+ # retains that backend-path. Keep the core backend at the source root.
+ (core / "build/backend.py").rename(core / "backend.py")
+ metadata = core / "pyproject.toml"
+ metadata.write_text(metadata.read_text().replace('backend-path=["build"]', 'backend-path=["."]'))
(core / ".env").write_text("must not copy")
monkeypatch.setattr(workspace.paths, "repo_root", lambda: core)
root, venv = tmp_path / "staging", tmp_path / "venv"
@@ -42,9 +72,9 @@ def test_real_build_inputs_stay_in_generated_root(tmp_path, monkeypatch):
workspace.lock_and_sync([], [], root=root, source=core, seed_lock=None,
environment=managed_environment(venv))
python = venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
- probe = subprocess.run([str(python), "-c", "import buildable_core; print(buildable_core.VALUE)"],
+ probe = subprocess.run([str(python), "-c", "import replay_plugin; print(replay_plugin.VALUE)"],
cwd=tmp_path, text=True, capture_output=True, check=True, timeout=30)
- assert probe.stdout.strip() == "from actual source"
+ assert probe.stdout.strip() == "recorded plugin bytes"
assert not (root / ".env").exists()
assert not list(core.glob("*.egg-info")), "build must not write into the original core"
assert not (core / "uv.lock").exists()
@@ -63,34 +93,7 @@ def test_repair_replays_saved_in_tree_build_backend(tmp_path):
'[project]\nname="replay-core"\nversion="1"\nrequires-python=">=3.11"\n'
'[tool.uv]\npackage=false\nno-index=true\n', encoding="utf-8",
)
- (plugin / "pyproject.toml").write_text(
- '[project]\nname="replay-plugin"\nversion="1.0"\nrequires-python=">=3.11"\n'
- '[build-system]\nrequires=[]\nbuild-backend="backend"\nbackend-path=["build"]\n',
- encoding="utf-8",
- )
- (plugin / "plugin.yaml").write_text("name: replay-plugin\n", encoding="utf-8")
- (plugin / "replay_plugin.py").write_text("VALUE = 'recorded plugin bytes'\n", encoding="utf-8")
- # A real, dependency-free PEP 517/660 backend. Its directory is source, not output.
- (plugin / "build/backend.py").write_text('''
-from pathlib import Path
-from zipfile import ZipFile
-
-def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
- name = "replay_plugin-1.0-py3-none-any.whl"
- dist = "replay_plugin-1.0.dist-info"
- entries = {
- "replay_plugin.py": Path("replay_plugin.py").read_bytes(),
- dist + "/METADATA": "Metadata-Version: 2.1\\nName: replay-plugin\\nVersion: 1.0\\n",
- dist + "/WHEEL": "Wheel-Version: 1.0\\nRoot-Is-Purelib: true\\nTag: py3-none-any\\n",
- }
- entries[dist + "/RECORD"] = "".join(path + ",,\\n" for path in entries)
- with ZipFile(Path(wheel_directory) / name, "w") as wheel:
- for path, body in entries.items():
- wheel.writestr(path, body)
- return name
-
-build_editable = build_wheel
-''', encoding="utf-8")
+ _buildable_source(plugin)
inputs = {p.relative_to(plugin): p.read_bytes() for p in plugin.rglob("*") if p.is_file()}
uv = shutil.which("uv")
assert uv, "saved backend replay test requires real uv"