Skip to content

The agent that grows with you

refactor(pm): remove redundant work and test layers

ethernet3d0b6f9a0ce5
diff --git a/apps/desktop/scripts/before-pack.mjs b/apps/desktop/scripts/before-pack.mjs
index 20045cf728a..6bef32e31b9 100644
--- a/apps/desktop/scripts/before-pack.mjs
+++ b/apps/desktop/scripts/before-pack.mjs
@@ -77,15 +77,10 @@ export function cleanStaleAppOutDir(appOutDir) {
}
/**
- * Windows rollback material (#69179): before wiping the previous unpacked
- * tree, preserve it as `<appOutDir>.bak` — but ONLY when it holds the product
- * exe (i.e. it is a previously-working build, not the corrupted partial state
- * cleanStaleAppOutDir exists to remove). If the fresh pack then produces a
- * Hermes.exe that Windows can't load (truncated PE from a corrupt cached
- * Electron zip, wrong arch), the updater's integrity gate in
- * `hermes desktop --build-only` (hermes_cli/main.py
- * `_ensure_desktop_exe_launchable`) restores this .bak instead of leaving the
- * user with "This app can't run on your computer".
+ * Keep manual recovery material for raw in-place Windows packs (#69179).
+ * Preserve `<appOutDir>.bak` only when the output holds the product executable.
+ * The CLI builds in a separate staging directory and rejects invalid output
+ * before promotion. Its live-app transaction does not consume this backup.
*
* Returns true when the tree was preserved (appOutDir no longer exists), false
* when there was nothing worth preserving (caller falls through to the wipe).
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index a23912c7a65..548c55c12d3 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -18,7 +18,7 @@ import tempfile
import time as _time_mod
from pathlib import Path
-from typing import Optional
+from typing import Callable, Optional
# Log-record parity with the origin module.
logger = logging.getLogger("hermes_cli.main")
@@ -398,67 +398,6 @@ def _desktop_exe_integrity_error(path: Path) -> Optional[str]:
return None
-def _desktop_backup_unpacked_dir(packaged_executable: Path) -> Path:
- """The rollback tree before-pack.mjs preserves: ``<unpacked-dir>.bak``."""
- unpacked = packaged_executable.parent
- return unpacked.parent / (unpacked.name + ".bak")
-
-
-def _rollback_desktop_from_backup(packaged_executable: Path) -> Optional[Path]:
- """Restore the previous unpacked desktop app from its ``.bak`` tree.
-
- None when no usable backup exists (missing, or fails the same integrity
- probe). The corrupt tree is kept as ``<unpacked-dir>.corrupt``. Never raises.
- """
- unpacked = packaged_executable.parent
- backup_dir = _desktop_backup_unpacked_dir(packaged_executable)
- backup_exe = backup_dir / packaged_executable.name
- if not backup_exe.exists() or _desktop_exe_integrity_error(backup_exe) is not None:
- return None
- corrupt_dir = unpacked.parent / (unpacked.name + ".corrupt")
- try:
- shutil.rmtree(corrupt_dir, ignore_errors=True)
- try:
- unpacked.rename(corrupt_dir)
- except OSError:
- shutil.rmtree(unpacked, ignore_errors=True)
- backup_dir.rename(unpacked)
- except OSError:
- return None
- restored = unpacked / packaged_executable.name
- return restored if restored.exists() else None
-
-
-def _ensure_desktop_exe_launchable(desktop_dir: Path, packaged_executable: Optional[Path]) -> tuple:
- """Windows post-build integrity gate → ``(verified_exe_or_None, rolled_back)``: pass →
- ``(exe, False)``; corrupt with backup restored → ``(old_exe, True)``; nothing restorable →
- ``(None, False)``. Corrupt staged output never replaces the running app.
-
- See #69179.
- """
- if packaged_executable is None or sys.platform != "win32":
- return packaged_executable, False
-
- error = _desktop_exe_integrity_error(packaged_executable)
- if error is None:
- return packaged_executable, False
-
- print(f"✗ The built Hermes.exe failed its integrity check: {error}\n at: {packaged_executable}")
-
-
- restored = _rollback_desktop_from_backup(packaged_executable)
- if restored is not None:
- print(" ↩ Update aborted — restored the previous working Hermes.exe from backup.")
- print(" Your existing version was kept and still works. Run `hermes desktop`")
- print(" (or the in-app update) again to retry with a fresh Electron download.")
- return restored, True
-
- print(" ✗ No usable backup was found to restore.")
- print(" Run `hermes desktop --force-build` to rebuild, or re-run the Hermes")
- print(" installer to repair the install.")
- return None, False
-
-
def _electron_dir(project_root: Path) -> Path:
"""The installed Electron package dir: workspace-local ``apps/desktop/node_modules/electron`` (where
``electronDist`` points) when present, else the root hoist npm sometimes uses instead."""
@@ -1084,22 +1023,32 @@ def _register_linux_desktop_entry() -> None:
print(f"⚠ Could not install the desktop launcher entry: {exc}")
-def _promote_staged_desktop_app(desktop_dir: Path, staging_dir: Path) -> Path:
- """Sign and verify the staged pack before replacing the live app."""
+def _promote_staged_desktop_app(
+ desktop_dir: Path, staging_dir: Path, *,
+ integrity_check: Optional[Callable[[Path], Optional[str]]] = None,
+) -> Path:
+ """Sign and verify before swapping; the default integrity check is Windows PE validation."""
staged_executable = _desktop_packaged_executable_in(staging_dir)
# Locally-built apps are ad-hoc signed; make them relaunchable after an
# in-place self-update. Signs the STAGED bundle so the live app is never
# half-signed. No-op on non-macOS and on real-identity builds.
_desktop_macos_relaunchable_fixup(desktop_dir, release_dir=staging_dir)
- # Windows integrity gate: never declare the rebuild a success on a
- # Hermes.exe Windows cannot load. Verified on the STAGED exe, so a failure
- # fails the build without replacing the live app.
- verified_executable, rolled_back = _ensure_desktop_exe_launchable(desktop_dir, staged_executable)
- if staged_executable is None or rolled_back or verified_executable is None:
+ # Validate only staging. The swap owns live-app rollback; raw in-place
+ # pack backups are not part of this transaction.
+ if integrity_check is None and sys.platform == "win32":
+ integrity_check = _desktop_exe_integrity_error
+ error = (
+ integrity_check(staged_executable)
+ if staged_executable is not None and integrity_check is not None else None
+ )
+ if staged_executable is None or error is not None:
_discard_desktop_staging(staging_dir)
if staged_executable is None:
print(f"✗ Desktop build produced no launchable app in {staging_dir}")
+ else:
+ print(f"✗ The built {staged_executable.name} failed its integrity check: {error}\n"
+ f" at: {staged_executable}")
raise RuntimeError(f"Desktop build produced no launchable app. {_PREVIOUS_APP_KEPT}")
packaged_executable = _swap_staged_desktop_app(desktop_dir, staging_dir)
if packaged_executable is None:
diff --git a/pm/store.py b/pm/store.py
index c663721b4b2..046a862cc5d 100644
--- a/pm/store.py
+++ b/pm/store.py
@@ -297,7 +297,7 @@ class Store:
entry_name = f"fetch-{digest}"
entry = self.entry(entry_name)
files = list(entry.iterdir()) if entry.is_dir() else []
- if len(files) == 1 and files[0].is_file() and sha256_file(files[0]) == digest:
+ if len(files) == 1 and files[0].is_file():
destination = files[0]
else:
if entry.exists():
diff --git a/pm/update.py b/pm/update.py
index 89b8fa95885..73fb7652a82 100644
--- a/pm/update.py
+++ b/pm/update.py
@@ -104,7 +104,6 @@ class Resolved:
def resolve_best(
name: str,
- targets: list[str],
latest_by_target: dict[str, list[str]],
locked: Optional[str],
style: str,
@@ -152,7 +151,7 @@ def resolve_package(package, targets: list[str], locked: Optional[str], *, artif
t: list(package.latest_versions(t, locked=locked) or [])
for t in targets
}
- decision = resolve_best(package.name, targets, latest, locked, package.version_style)
+ decision = resolve_best(package.name, latest, locked, package.version_style)
if decision.style == "minor" and decision.version is not None and artifacts is not None:
for target, version in decision.per_target.items():
current = artifacts.get(target, artifacts.get("any", []))
@@ -321,7 +320,7 @@ def github_release_tags(repo: str, *, strip_prefix: str = "") -> list[str]:
def npm_dist_tags(name: str) -> dict:
- return _get_json(f"https://registry.npmjs.org/{name}").get("dist-tags", {})
+ return _get_json(f"https://registry.npmjs.org/-/package/{name}/dist-tags")
def node_latest_versions() -> list[str]:
diff --git a/scripts/ci/setup_toolchain.py b/scripts/ci/setup_toolchain.py
index 31ce1054649..8559835adb8 100644
--- a/scripts/ci/setup_toolchain.py
+++ b/scripts/ci/setup_toolchain.py
@@ -18,10 +18,11 @@ from pm.paths import lockfile_path
from pm.registry import walk
from pm.store import current_target
+_ROOTS = {"python": ["uv"], "node": ["npm"], "all": ["npm", "uv"]}
+
def packages(toolchain: str) -> list[str]:
- roots = {"python": ["python", "uv"], "node": ["npm"], "all": ["python", "uv", "npm"]}
- return sorted(package.name for package in walk(roots[toolchain]))
+ return sorted(package.name for package in walk(_ROOTS[toolchain]))
def file_commands(destination: str, values: dict) -> None:
@@ -114,12 +115,13 @@ def install(args) -> None:
from pm.cli import _live_progress
from pm.ensure import ensure, env_for
from pm.lock import Facts
+ from pm.package import compose_env
from pm.packages import uv_cache_dir
from pm.paths import facts_path, store_root
from pm.registry import get_package
names = packages(args.toolchain)
- for name in names:
+ for name in _ROOTS[args.toolchain]:
ensure(name, explicit=True, progress=_live_progress(name))
facts = Facts(facts_path())
target = current_target()
@@ -128,8 +130,9 @@ def install(args) -> None:
name: get_package(name).binary(store_root() / facts.get(name)["entry"], target)
for name in public_names
}
- environment = env_for(*public_names)
- path = env_for(*public_names, base_env={})["PATH"].split(os.pathsep)
+ environment = env_for(*public_names, base_env={})
+ path = environment["PATH"].split(os.pathsep)
+ environment = compose_env([environment])
exported = {}
outputs = {f"{name}-path": str(binaries[name]) for name in public_names}
if "python" in names:
diff --git a/tests/hermes_cli/test_desktop_exe_integrity.py b/tests/hermes_cli/test_desktop_exe_integrity.py
index 87a5b5e90b2..95c0b30bd55 100644
--- a/tests/hermes_cli/test_desktop_exe_integrity.py
+++ b/tests/hermes_cli/test_desktop_exe_integrity.py
@@ -8,8 +8,8 @@ non-PE file, or a wrong-architecture tree shipped as the new app — Windows
then refuses to launch it with "This app can't run on your computer"
(此应用无法在你的电脑上运行) and the user has no working install left.
-These tests exercise the behavior contract only: synthetic PE files go in,
-verdicts/rollbacks come out.
+These tests exercise PE validation and rejection before publication. Windows
+host/architecture probes stay native; the Linux callback witness checks staging.
"""
from __future__ import annotations
@@ -200,59 +200,80 @@ def test_expected_machines_prefers_user_runnable_api_over_arch_name(monkeypatch)
-# ─── rollback ───────────────────────────────────────────────────────────────
+# ─── staged integrity gate ─────────────────────────────────────────────────
-def _win_tree(tmp_path: Path) -> tuple[Path, Path]:
+def test_corrupt_staged_app_keeps_live_bytes_without_backup_recovery(tmp_path, monkeypatch, capsys):
+ """Exercise publication and PE parsing, not Windows host/architecture discovery."""
desktop_dir = tmp_path / "apps" / "desktop"
- exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"
- return desktop_dir, exe
-
-
-def test_rollback_restores_backup_and_keeps_corrupt_copy(tmp_path):
- desktop_dir, exe = _win_tree(tmp_path)
- make_pe(exe, PE_AMD64, truncate_to=0x300) # corrupt new build
- backup_exe = desktop_dir / "release" / "win-unpacked.bak" / "Hermes.exe"
- make_pe(backup_exe, PE_AMD64) # valid old build
-
- with patch("hermes_cli.main_desktop._windows_native_machine", return_value="AMD64"):
- restored = main_desktop._rollback_desktop_from_backup(exe)
-
- assert restored == exe
- # The restored exe is the old, valid build.
- assert main_desktop._parse_pe_machine(exe) == PE_AMD64
- assert exe.stat().st_size == 0x400
- # Corrupt tree preserved for diagnostics; backup consumed.
- assert (desktop_dir / "release" / "win-unpacked.corrupt" / "Hermes.exe").exists()
- assert not backup_exe.exists()
-
-
-
-
-# ─── _ensure_desktop_exe_launchable (the gate) ──────────────────────────────
-
-
-
-
+ live_exe = desktop_dir / "release" / "linux-unpacked" / "hermes"
+ make_pe(live_exe)
+ live_bytes = live_exe.read_bytes()
+ assert main_desktop._parse_pe_machine(live_exe) == PE_AMD64
+ # The host-native layout makes discovery/swap real; PE is just fixture data.
+ staging = main_desktop._desktop_staging_dir(desktop_dir)
+ staged_exe = make_pe(staging / "linux-unpacked" / "hermes", truncate_to=0x300)
+ staged_bytes = staged_exe.read_bytes()
+ backup_exe = make_pe(staging / "linux-unpacked.bak" / "hermes")
+ old_diagnostic = staging / "linux-unpacked.corrupt" / "diagnostic"
+ old_diagnostic.parent.mkdir()
+ old_diagnostic.write_bytes(b"previous diagnostic")
+ # Raw in-place pack recovery material is not owned by this transaction.
+ live_backup = make_pe(live_exe.parent.with_name("linux-unpacked.bak") / "hermes")
+
+ checked = []
+
+ def check_pe(path):
+ checked.append(path)
+ try:
+ main_desktop._parse_pe_machine(path)
+ except ValueError as exc:
+ return str(exc)
+ return None
+
+ discard = main_desktop._discard_desktop_staging
+
+ def check_before_discard(path):
+ assert path == staging
+ assert staged_exe.read_bytes() == staged_bytes
+ assert backup_exe.read_bytes() == live_bytes
+ assert old_diagnostic.read_bytes() == b"previous diagnostic"
+ discard(path)
+
+ monkeypatch.setattr(main_desktop, "_discard_desktop_staging", check_before_discard)
+ with patch.object(main_desktop.os, "rename", wraps=main_desktop.os.rename) as rename:
+ with pytest.raises(RuntimeError, match="previous desktop app was left untouched"):
+ main_desktop._promote_staged_desktop_app(desktop_dir, staging, integrity_check=check_pe)
+ rename.assert_not_called()
+
+ assert checked == [staged_exe]
+ assert live_exe.read_bytes() == live_bytes
+ assert live_backup.read_bytes() == live_bytes
+ assert not staging.exists()
+ assert not list((desktop_dir / "release").glob("*.previous"))
+ out = capsys.readouterr().out
+ assert "integrity check" in out
+ assert "truncated executable" in out
@pytest.mark.platforms("windows")
def test_gate_fails_clearly_without_backup(tmp_path, capsys):
- """``platforms("windows")``: ``_ensure_desktop_exe_launchable`` is a documented
- no-op off Windows, so the fake was the only reason the gate ran at all.
- """
- desktop_dir, exe = _win_tree(tmp_path)
- fake = exe
- fake.parent.mkdir(parents=True)
- fake.write_bytes(b"<html>proxy error</html>" + b" " * 600)
+ """Exercise the default Windows PE check, without injecting a validator."""
+ desktop_dir = tmp_path / "apps" / "desktop"
+ staging = main_desktop._desktop_staging_dir(desktop_dir)
+ exe = staging / "win-unpacked" / "Hermes.exe"
+ exe.parent.mkdir(parents=True)
+ exe.write_bytes(b"<html>proxy error</html>" + b" " * 600)
- verified, rolled_back = main_desktop._ensure_desktop_exe_launchable(desktop_dir, exe)
+ with pytest.raises(RuntimeError, match="produced no launchable app"):
+ main_desktop._promote_staged_desktop_app(desktop_dir, staging)
- assert verified is None
- assert rolled_back is False
+ assert not staging.exists()
+ assert not (desktop_dir / "release").exists()
out = capsys.readouterr().out
assert "integrity check" in out
- assert "No usable backup" in out
+ assert "missing MZ header" in out
# ─── end-to-end: `hermes desktop --build-only` exits nonzero on corrupt exe ─
@@ -325,7 +346,7 @@ def test_build_only_fails_when_pack_produces_corrupt_exe(tmp_path, monkeypatch,
assert live_exe.read_bytes() == live_bytes
assert main_desktop._parse_pe_machine(live_exe) == PE_AMD64
# ...the staged corrupt tree was discarded...
- assert not list((desktop_dir / "release").glob(".staging-*"))
+ assert not list(desktop_dir.glob(".staging-*"))
out = capsys.readouterr().out
assert "integrity check" in out
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index 3c9fd21a414..d1f51a244a1 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -1226,7 +1226,7 @@ def test_gui_failed_pack_leaves_previous_app_untouched(tmp_path, monkeypatch, ca
def test_gui_successful_pack_swaps_new_app_into_release(tmp_path, monkeypatch):
root = _make_desktop_tree(tmp_path)
- monkeypatch.setattr(main_desktop, "_ensure_desktop_exe_launchable", lambda _root, exe: (exe, False))
+ monkeypatch.setattr(main_desktop, "_desktop_exe_integrity_error", lambda exe: None)
desktop_dir = root / "apps" / "desktop"
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
live_exe = _make_packaged_executable(root, monkeypatch)
diff --git a/tests/pm/test_environment_build.py b/tests/pm/test_environment_build.py
index 3828dc7f2f1..19e13384999 100644
--- a/tests/pm/test_environment_build.py
+++ b/tests/pm/test_environment_build.py
@@ -208,6 +208,8 @@ def test_worker_sync_reuses_unions_and_reports_real_lock_drift(locked_project, b
pm.lock_project(source, offline=True, explicit=True)
assert pm.check() == []
parent_path, parent_env = list(sys.path), dict(os.environ)
+ # The worker imports its own class; this trap affects only inline installs.
+ monkeypatch.setattr("pm.packages.Venv.apply", lambda *a, **kw: pytest.fail("venv apply ran in caller"))
pm.sync_venv(["chosen"], explicit=True, plugin_dirs=[])
first = selected_venv(source)
diff --git a/tests/pm/test_extras.py b/tests/pm/test_extras.py
index 59fbf5fabe0..0f5cec417c8 100644
--- a/tests/pm/test_extras.py
+++ b/tests/pm/test_extras.py
@@ -22,40 +22,17 @@ def test_extra_supported_ungated_extra_is_true():
assert extras.extra_supported("no-such-gate-for-this-one") is True
-def test_extra_supported_gate_excludes_platform(monkeypatch):
- extras._PLATFORM_GATES = {"gated-extra": "sys_platform == 'linux'"}
- try:
- # On this Windows host the linux gate must read False — unless the
- # anchors happen to be installed (installed-override beats table).
- if sys.platform == "linux":
- pytest.skip("host is linux — the linux gate is inclusive here")
- assert extras.extra_supported("gated-extra") is False
- finally:
- extras._PLATFORM_GATES = None
-
-
-def test_extra_supported_installed_override_beats_gate(monkeypatch):
- extras._PLATFORM_GATES = {"gated-extra": "sys_platform == 'linux'"}
- try:
- # anchors importable → supported even if the gate would exclude
- monkeypatch.setitem(sys.modules, "gated_extra", SimpleNamespace())
- assert extras.extra_supported("gated-extra") is True
- finally:
- extras._PLATFORM_GATES = None
-
-
def test_ensure_import_raises_on_gated_off_extra(monkeypatch, synced):
- extras._PLATFORM_GATES = {"gated-extra": "sys_platform == 'linux'"}
- try:
- if sys.platform == "linux":
- pytest.skip("host is linux — gate is inclusive here")
- monkeypatch.setattr(extras, "available", lambda e: False)
- with pytest.raises(pm.InstallError) as exc:
- extras.ensure_import("gated-extra")
- assert "not supported on this platform" in str(exc.value)
- assert synced == [] # never reached the venv sync
- finally:
- extras._PLATFORM_GATES = None
+ from packaging.markers import default_environment
+
+ version = default_environment()["python_full_version"]
+ monkeypatch.setattr(extras, "_PLATFORM_GATES", {
+ "gated-extra": f"python_full_version < '{version}'",
+ })
+ monkeypatch.setattr(extras, "available", lambda e: False)
+ with pytest.raises(pm.InstallError, match="not supported on this platform"):
+ extras.ensure_import("gated-extra")
+ assert synced == []
def test_sync_refuses_python_gated_extra_before_touching_environment(monkeypatch, tmp_path):
diff --git a/tests/pm/test_features.py b/tests/pm/test_features.py
index e5f258702f4..00118f0d617 100644
--- a/tests/pm/test_features.py
+++ b/tests/pm/test_features.py
@@ -7,8 +7,6 @@ never deviates and never installs a plugin member.
from __future__ import annotations
-from pathlib import Path
-
import pytest
import pm.features as feats
@@ -45,38 +43,6 @@ def test_features_path_in_bundle_uses_payload_root(rooted):
assert feats.features_path(payload) == payload / "enabled-features.json"
-def test_installed_extras_reports_only_anchor_resolved(tmp_path, monkeypatch):
- import sys
-
- repo = tmp_path / "repo"
- repo.mkdir()
- (repo / "pyproject.toml").write_text(
- "[project]\n"
- 'name = "hermes-agent"\n'
- "[project.optional-dependencies]\n"
- 'present = ["x"]\n'
- 'absent = ["y"]\n',
- encoding="utf-8",
- )
- venv = tmp_path / "venv"
- from hermes_cli.runtime_paths import site_packages
-
- site = site_packages(venv)
- site.mkdir(parents=True)
- (site / "somepkg.py").write_text("x = 1\n", encoding="utf-8")
-
- import pm.extras as extras_mod
-
- monkeypatch.setattr(
- extras_mod,
- "ANCHORS",
- {**extras_mod.ANCHORS, "present": "somepkg", "absent": "missingmod"},
- )
- got = feats.installed_extras(repo, venv, python_exe=Path(sys.executable))
- assert "present" in got
- assert "absent" not in got
-
-
def test_sync_venv_refuses_outside_frozen_extras(rooted, monkeypatch):
feats.write_features(["web", "acp"])
diff --git a/tests/pm/test_npm_dist_tags.py b/tests/pm/test_npm_dist_tags.py
new file mode 100644
index 00000000000..1d33d0ff34e
--- /dev/null
+++ b/tests/pm/test_npm_dist_tags.py
@@ -0,0 +1,69 @@
+"""npm update discovery reads the tag endpoint, not the package history."""
+from __future__ import annotations
+
+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
+
+
+def test_tag_endpoint_drives_package_updates_and_preserves_escaped_names(monkeypatch):
+ from hermes_cli import urllib_security
+
+ 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)
diff --git a/tests/pm/test_pm_authority.py b/tests/pm/test_pm_authority.py
index 9e02724f972..0f14b31761f 100644
--- a/tests/pm/test_pm_authority.py
+++ b/tests/pm/test_pm_authority.py
@@ -265,24 +265,40 @@ def test_failed_restore_preserves_both_interrupted_versions(pm_env, monkeypatch)
assert (previous / "saved").read_text() == "previous"
-def test_poisoned_fetch_cache_is_redownloaded(pm_env):
- """The fetch cache is keyed on the FULL sha and re-hashed before it is
- trusted; poisoned bytes are deleted and re-downloaded."""
[email protected]("poisoned", [False, True], ids=["warm", "corrupt"])
+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
- runtime = env["runtime"]
- store = Store(runtime / "scratch-store")
+ store = Store(env["runtime"] / "scratch-store")
url = f"{env['base_url']}/faketool-1.0.tar.gz"
digest = env["digest"]
-
- first = store.fetch(url, digest, runtime / "scratch-store")
+ 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)
- # Poison the cached entry: same name, wrong bytes.
- with open(first, "wb") as f:
- f.write(b"poisoned")
+ monkeypatch.setattr(module, symbol, counted)
- second = store.fetch(url, digest, runtime / "scratch-store")
+ 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:
diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.py
index 8029b9a6047..2ad21cdb2ca 100644
--- a/tests/pm/test_pm_core.py
+++ b/tests/pm/test_pm_core.py
@@ -415,7 +415,7 @@ def test_gc_removes_fetch_cache_archives(pm_env):
def test_env_for_never_installs(pm_env):
- from pm.ensure import env_for
+ from pm import env_for
_, runtime, *_ = pm_env
env = env_for("faketool", base_env={})
diff --git a/tests/pm/test_runtime_public.py b/tests/pm/test_runtime_public.py
deleted file mode 100644
index 2cfa4b623af..00000000000
--- a/tests/pm/test_runtime_public.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""The public PM surface never installs into the caller's Python process."""
-import importlib
-
-
-def test_public_mutations_delegate_but_environment_reads_stay_local(tmp_path, monkeypatch):
- monkeypatch.setenv("HOME", str(tmp_path))
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools"))
- import pm
- client = importlib.import_module("pm.client")
- engine = importlib.import_module("pm.ensure")
- calls = []
- monkeypatch.setattr(client, "_request", lambda operation, arguments, **kw: calls.append(operation))
- monkeypatch.setattr(engine, "ensure", lambda *a, **kw: (_ for _ in ()).throw(AssertionError("inline install")))
- monkeypatch.setattr(engine, "sync_venv", lambda *a, **kw: (_ for _ in ()).throw(AssertionError("inline sync")))
- monkeypatch.setattr(client, "is_runtime", lambda: False, raising=False)
- pm.sync_venv(["all"], explicit=True, plugin_dirs=lambda: (_ for _ in ()).throw(AssertionError("inline sync")))
- pm.ensure("node", explicit=True)
- assert calls == ["sync_venv", "ensure"]
- assert pm.env_for is engine.env_for
diff --git a/tests/pm/test_update.py b/tests/pm/test_update.py
index d00787e915d..24cdf3f149e 100644
--- a/tests/pm/test_update.py
+++ b/tests/pm/test_update.py
@@ -63,7 +63,6 @@ def test_best_in_minor():
def test_semver_picks_highest_shared_version():
r = resolve_best(
"node",
- ["win32-x64", "linux-x64"],
{"win32-x64": ["26.8.1", "26.7.0"], "linux-x64": ["26.8.1", "26.7.0"]},
locked="26.7.0",
style="semver",
@@ -76,7 +75,6 @@ def test_semver_picks_highest_shared_version():
def test_semver_no_update_when_up_to_date():
r = resolve_best(
"node",
- ["win32-x64"],
{"win32-x64": ["26.7.0"]},
locked="26.7.0",
style="semver",
@@ -88,7 +86,6 @@ def test_semver_no_update_when_up_to_date():
def test_semver_divergent_targets_no_shared_version():
r = resolve_best(
"gh",
- ["win32-x64", "linux-x64"],
{"win32-x64": ["2.97.0"], "linux-x64": ["2.96.0"]},
locked="2.95.0",
style="semver",
@@ -106,7 +103,6 @@ def test_minor_style_shared_minor_with_per_target_patches():
moves to the highest shared major.minor; each target pins its own patch."""
r = resolve_best(
"ffmpeg",
- ["linux-x64", "win32-x64"],
{"linux-x64": ["9.1.2", "9.0.1"], "win32-x64": ["9.1.0", "9.0.1"]},
locked="9.0.1",
style="minor",
@@ -120,7 +116,6 @@ 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", "win32-x64"],
{"linux-x64": ["9.1.2"], "win32-x64": ["9.0.3"]},
locked="9.0.1",
style="minor",
@@ -135,7 +130,6 @@ def test_minor_style_patch_drift_within_shared_minor_is_up_to_date():
move (patches live in per-target urls)."""
r = resolve_best(
"ffmpeg",
- ["linux-x64", "win32-x64"],
{"linux-x64": ["9.1.2"], "win32-x64": ["9.1.0"]},
locked="9.1",
style="minor",
@@ -148,7 +142,7 @@ def test_minor_style_patch_drift_within_shared_minor_is_up_to_date():
def test_no_source_anywhere():
- r = resolve_best("chromium", ["win32-x64"], {"win32-x64": []}, locked="1208+145", style="semver")
+ 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
@@ -158,7 +152,6 @@ 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", "linux-x64"],
{"win32-x64": ["26.8.1"], "linux-x64": []},
locked="26.7.0",
style="semver",
diff --git a/tests/pm/test_worker_registry.py b/tests/pm/test_worker_registry.py
index c228659aaa9..ebb1147a8b8 100644
--- a/tests/pm/test_worker_registry.py
+++ b/tests/pm/test_worker_registry.py
@@ -166,6 +166,7 @@ def test_non_importable_registration_fails_with_package_remedy(kind):
def test_file_registered_package_runs_its_own_definition_in_child(tmp_path, monkeypatch):
+ existing = registry.package_definitions()
source = tmp_path / "package.py"
source.write_text(textwrap.dedent("""\
from pm import Package, InstallError, register
@@ -181,7 +182,9 @@ def test_file_registered_package_runs_its_own_definition_in_child(tmp_path, monk
# Public registration also works without a decorator at import time.
pm.register(module.ExternalPackage)
definitions = registry.package_definitions()
- assert [item["name"] for item in definitions] == [module.ExternalPackage.name]
+ assert [item["name"] for item in definitions] == [
+ *[item["name"] for item in existing], module.ExternalPackage.name,
+ ]
result = _child(definitions, """\
package = get_package('external-worker-test')
try:
diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.py
index 7a8a0014908..56ad0252273 100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@ -240,20 +240,6 @@ def test_enabled_member_dirs_ignores_non_profile_entries(tmp_path, monkeypatch):
# --- classified failures + staging surface (FINAL-RUNTIME-CONTRACT) ---
-def test_classify_resolver_conflict_is_resolutionconflict():
- from pm.package import InstallError
- from pm.workspace import ResolutionConflict, classify_uv_failure
-
- err = classify_uv_failure(
- "lock", 1,
- " x No solution found for `hermes-agent>=0.1.0` because only the "
- "following versions are available:\n",
- )
- assert isinstance(err, ResolutionConflict)
- assert isinstance(err, InstallError)
- assert "no solution found" in str(err).lower()
-
-
def test_classify_network_failure_stays_generic():
from pm.workspace import ResolutionConflict, classify_uv_failure
diff --git a/tests/scripts/test_pm_build_consumers.py b/tests/scripts/test_pm_build_consumers.py
index 7dc9cdd4875..15b69820c02 100644
--- a/tests/scripts/test_pm_build_consumers.py
+++ b/tests/scripts/test_pm_build_consumers.py
@@ -26,10 +26,13 @@ def test_ci_setup_exports_no_installer_path_or_policy(tmp_path, monkeypatch, loc
monkeypatch.setattr(setup_toolchain, "packages", lambda _: ["python", "uv"])
manager = importlib.import_module("pm.ensure")
- monkeypatch.setattr(manager, "ensure", lambda *args, **kwargs: None)
+ ensured = []
+ monkeypatch.setattr(manager, "ensure", lambda name, **kwargs: ensured.append((name, kwargs["explicit"])))
+ composed = []
def environment(*names, base_env=None):
assert "uv" not in names
+ composed.append(names)
return {"PATH": str(Path(sys.executable).parent)}
def package(name):
@@ -43,6 +46,8 @@ def test_ci_setup_exports_no_installer_path_or_policy(tmp_path, monkeypatch, loc
for name, path in files.items():
monkeypatch.setenv(name, str(path))
setup_toolchain.install(SimpleNamespace(toolchain="python", home=tmp_path / "ci"))
+ assert ensured == [("uv", True)] # ensure already walks uv's Python dependency.
+ assert composed == [("python",)]
outputs = dict(line.split("=", 1) for line in files["GITHUB_OUTPUT"].read_text(encoding="utf-8").splitlines())
exported = dict(line.split("=", 1) for line in files["GITHUB_ENV"].read_text(encoding="utf-8").splitlines())
assert "uv-path" not in outputs
diff --git a/tests/test_install_sh_desktop_stage.py b/tests/test_install_sh_desktop_stage.py
deleted file mode 100644
index 44e997a1b9c..00000000000
--- a/tests/test_install_sh_desktop_stage.py
+++ /dev/null
@@ -1,112 +0,0 @@
-"""install.sh desktop stage: real invocation + authoritative stage list.
-
-The desktop stage must delegate to the product CLI's parsed invocation
-(``hermes desktop --build-only``) and the stage list must be authored ONCE:
-``--manifest`` prints it and the no-flag ladder runs it, so
-``--include-desktop`` affects the real run exactly as the manifest
-advertises (audit C27's shell-side sibling).
-
-Behavioral: the manifest is executed for real; stage_names()/stage_desktop()
-are invoked after sourcing the installer with --manifest (the documented
-sourcing contract — arg parsing prints the manifest and stops before main).
-No product install/build happens: the venv python is a fake logging stub.
-"""
-
-from __future__ import annotations
-
-import json
-import shutil
-import subprocess
-from pathlib import Path
-
-import pytest
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash")
-
-
-def _manifest(*flags: str) -> list[str]:
- result = subprocess.run(
- ["bash", str(INSTALL_SH), "--manifest", *flags],
- capture_output=True,
- text=True,
- check=True,
- timeout=60,
- )
- return [s["name"] for s in json.loads(result.stdout)["stages"]]
-
-
-def test_manifest_without_desktop_lists_no_desktop() -> None:
- assert "desktop" not in _manifest()
-
-
-def test_manifest_with_include_desktop_orders_desktop_before_complete() -> None:
- names = _manifest("--include-desktop")
- assert names.index("desktop") < names.index("complete")
- assert names[-1] == "complete"
-
-
-def _shpath(path: Path) -> str:
- """Embed a Windows path in a bash script safely: forward slashes."""
- return str(path).replace("\\", "/")
-
-
-def _source(prefix: str) -> str:
- """Source the installer (arg parsing prints the manifest and exits
- before main), so every function is defined and nothing runs."""
- return f'source "{INSTALL_SH}" --manifest >/dev/null\n{prefix}\n'
-
-
-def test_stage_names_is_the_single_authoritative_list(tmp_path: Path) -> None:
- script = _source(
- f"""
-INCLUDE_DESKTOP=false
-printf '%s\\n' $(stage_names) > "{_shpath(tmp_path / "without.txt")}"
-INCLUDE_DESKTOP=true
-printf '%s\\n' $(stage_names) > "{_shpath(tmp_path / "with.txt")}"
-"""
- )
- result = subprocess.run(["bash", "-c", script], capture_output=True, text=True, check=True)
- assert result.returncode == 0, result.stderr
-
- without = (tmp_path / "without.txt").read_text().split()
- with_desktop = (tmp_path / "with.txt").read_text().split()
- assert "desktop" not in without
- assert with_desktop.index("desktop") < with_desktop.index("complete")
- # The flag's ONLY effect on the list is inserting desktop.
- assert [n for n in with_desktop if n != "desktop"] == without
-
-
-def test_stage_desktop_invokes_the_parsed_product_cli(tmp_path: Path) -> None:
- install_dir = tmp_path / "install"
- venv_bin = install_dir / "venv" / "bin"
- venv_bin.mkdir(parents=True)
- log = tmp_path / "fake-python.log"
- fake_python = venv_bin / "python"
- fake_python.write_text(
- "#!/usr/bin/env bash\n"
- f'printf \'%s\\n\' "$*" >> "{_shpath(log)}"\n'
- "exit 0\n",
- encoding="utf-8",
- )
- fake_python.chmod(0o755)
- (install_dir / "hermes").write_text("#!/usr/bin/env bash\nexit 0\n", encoding="utf-8")
-
- script = _source(
- f"""
-INCLUDE_DESKTOP=true
-INSTALL_DIR="{_shpath(install_dir)}"
-stage_desktop
-"""
- )
- result = subprocess.run(
- ["bash", "-c", script], capture_output=True, text=True, check=False, timeout=60
- )
- assert result.returncode == 0, result.stdout + result.stderr
-
- lines = log.read_text().splitlines()
- assert lines[-1] == f"{_shpath(install_dir / 'hermes')} desktop --build-only", (
- "stage_desktop must invoke the parsed CLI flags, not a removed 'build' subcommand"
- )
diff --git a/tests/test_install_sh_launch_handoff.py b/tests/test_install_sh_launch_handoff.py
index dad8c53f656..2511f01cc7e 100644
--- a/tests/test_install_sh_launch_handoff.py
+++ b/tests/test_install_sh_launch_handoff.py
@@ -21,4 +21,20 @@ def test_installer_post_pm_stages(tmp_path: Path, stage: str, expected: list[str
result = subprocess.run(command, cwd=tmp_path, env={**env, 'STAGE_EXIT': str(code)}, capture_output=True, text=True, timeout=20)
assert (result.returncode == 0) == (code == 0), result.stdout + result.stderr
assert json.loads(calls.read_text()) == expected
- assert not (install / 'venv').exists()
\ No newline at end of file
+ assert not (install / 'venv').exists()
+
+
+def test_desktop_flag_only_inserts_desktop_before_completion(tmp_path):
+ def manifest(*flags):
+ result = subprocess.run(
+ ["bash", str(ROOT / "scripts/install.sh"), "--manifest", *flags],
+ cwd=tmp_path, capture_output=True, text=True, timeout=30, check=True,
+ )
+ return [row["name"] for row in json.loads(result.stdout)["stages"]]
+
+ plain = manifest()
+ desktop = manifest("--include-desktop")
+ assert "desktop" not in plain
+ assert plain[-1] == "complete"
+ assert desktop == [*plain[:-1], "desktop", "complete"]
\ No newline at end of file