The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): refresh artifacts within the same minor version
ethernete86d31fade45
diff --git a/pm/cli.py b/pm/cli.pyindex ef2c72aacbb..08da8a3654f 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -299,7 +299,8 @@ def cmd_update(args) -> int:if not targets:continuetry:- decision = resolve_package(package, targets, lockfile.version(name))+ decision = resolve_package(package, targets, lockfile.version(name),+ artifacts=lockfile.pinned_artifacts(name))except Exception as e: # an upstream index outage must not kill the whole checkdecision = Resolved(name, lockfile.version(name), package.version_style, reason=f"resolve failed: {e}")failures.append(name)@@ -318,7 +319,10 @@ def cmd_update(args) -> int:per = ""if d.per_target and len(set(d.per_target.values())) > 1:per = " (" + ", ".join(f"{t}={v}" for t, v in sorted(d.per_target.items())) + ")"- print(f"{d.name:<{width}} {d.locked or '—'} → {d.version}{per}")+ if d.version == d.locked and d.artifact_updates:+ print(f"{d.name:<{width}} {d.version}: newer artifacts for {', '.join(sorted(d.artifact_updates))}")+ else:+ print(f"{d.name:<{width}} {d.locked or '—'} → {d.version}{per}")else:print(f"{d.name:<{width}} {d.locked} up to date")if failures:@@ -335,7 +339,7 @@ def cmd_update(args) -> int:if changed:for d in changed:package = get_package(d.name)- artifacts = _pin_artifacts(package, d)+ artifacts = _pin_artifacts(package, d, lockfile.pinned_artifacts(d.name))lockfile.set_pin(d.name, d.version, artifacts)print(f"✓ {d.name} pinned {d.locked or '—'} → {d.version}")lockfile.save()@@ -388,26 +392,25 @@ def cmd_update(args) -> int:return 0-def _pin_artifacts(package, decision) -> dict:- """The lockfile artifacts dict for a resolved update, mirroring cmd_lock's- per-target shape (identical single artifacts collapse to 'any'). For- minor-style packages each target pins its OWN patch version. The- lockfile always pins EVERY target the package serves — apply never- narrows to the current machine."""+def _pin_artifacts(package, decision, current: dict) -> dict:+ """Retain unresolved targets and reuse hashes for unchanged artifact URLs."""per_target = decision.per_target or {t: decision.version for t in ALL_TARGETS}- urls_by_target = {}- for t, version in per_target.items():- if package.missing_reason(t) is not None:+ artifacts = dict(current)+ for target, version in per_target.items():+ if package.missing_reason(target) is not None:continue- urls_by_target[t] = [- {"url": u, "sha256": package.known_sha256(version, u) or hash_url(u)}- for u in package.fetch_urls(version, t)- ]- distinct = {tuple(u["url"] for u in v) for v in urls_by_target.values()}- if len(distinct) == 1:- first = next(iter(urls_by_target.values()))- return {"any": first[0] if len(first) == 1 else first}- return urls_by_target+ old = current.get(target, current.get("any", []))+ old = old if isinstance(old, list) else [old]+ known = {row["url"]: row["sha256"] for row in old}+ urls = decision.artifact_updates.get(target)+ if urls is None:+ urls = package.fetch_urls(version, target)+ if urls == [row["url"] for row in old]:+ continue+ pinned = [{"url": url, "sha256": known.get(url) or package.known_sha256(version, url) or hash_url(url)}+ for url in urls]+ artifacts[target] = pinned[0] if len(pinned) == 1 else pinned+ return artifactsdef cmd_status(args) -> int:diff --git a/pm/lock.py b/pm/lock.pyindex d0994a75f9d..9c6215af781 100644--- a/pm/lock.py+++ b/pm/lock.py@@ -96,6 +96,10 @@ class Lockfile:return []return list(found) if isinstance(found, list) else [found]+ def pinned_artifacts(self, name: str) -> dict:+ """Return the complete pin table, including targets without discovery."""+ return deepcopy((self._packages.get(name) or {}).get("artifacts") or {})+def names(self) -> list[str]:return sorted(self._packages)diff --git a/pm/update.py b/pm/update.pyindex 26320f2adc8..bbd65ad87d0 100644--- a/pm/update.py+++ b/pm/update.py@@ -93,6 +93,7 @@ class Resolved:version: Optional[str] = None # lockfile label: full (semver) or X.Y (minor)per_target: dict[str, str] = field(default_factory=dict) # target -> exact versionreason: str = "" # "up to date" / "no source" / "no shared minor" / ""+ artifact_updates: dict[str, list[str]] = field(default_factory=dict)@propertydef changed(self) -> bool:@@ -101,7 +102,7 @@ class Resolved:if self.locked is None:return Trueif self.style == "minor":- return minor_of(self.version) != minor_of(self.locked)+ return bool(self.artifact_updates) or minor_of(self.version) != minor_of(self.locked)return version_key(self.version) > version_key(self.locked)@@ -149,13 +150,23 @@ def resolve_best(return Resolved(name, locked, style, version=version, per_target={t: version for t in present})-def resolve_package(package, targets: list[str], locked: Optional[str]) -> Resolved:- """Call a package's own latest_versions() per target, then intersect."""+def resolve_package(package, targets: list[str], locked: Optional[str], *, artifacts: dict | None = None) -> Resolved:+ """Resolve versions and detect new artifacts within a shared minor."""latest = {t: list(package.latest_versions(t, locked=locked) or [])for t in targets}- return resolve_best(package.name, targets, latest, locked, package.version_style)+ decision = resolve_best(package.name, targets, 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", []))+ current = current if isinstance(current, list) else [current]+ urls = package.fetch_urls(version, target)+ if urls != [row["url"] for row in current]:+ decision.artifact_updates[target] = urls+ if locked is not None and minor_of(decision.version) == minor_of(locked):+ decision.version = locked+ return decision# ---------------------------------------------------------------------------diff --git a/tests/pm/test_update_artifact_refresh.py b/tests/pm/test_update_artifact_refresh.pynew file mode 100644index 00000000000..c1c65638036--- /dev/null+++ b/tests/pm/test_update_artifact_refresh.py@@ -0,0 +1,91 @@+"""Minor-style updates follow advertised artifacts without dropping other pins."""+from __future__ import annotations++import hashlib+import importlib+import io+import json+import zipfile++import pytest++from pm import cli, paths, registry+from pm.lock import Facts, Lockfile+from pm.package import Package+from pm.store import current_target+from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401++[email protected]("next_version", ["1.2.3", "1.2.4"])+def test_same_minor_refresh_updates_real_bytes_and_preserves_unresolved_targets(+ tmp_path, dl_server, monkeypatch, next_version,+):+ class RollingPackage(Package):+ name = "rolling-tool"+ version_style = "minor"++ def latest_versions(self, target, locked=None):+ return [next_version] if target == current_target() else []++ def fetch_url(self, version, target):+ assert version == next_version+ assert target == current_target()+ return url(dl_server, "/new-build.zip")++ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ archive.writestr("tool.txt", b"new rolling build")+ body = buffer.getvalue()+ RangeHandler.payloads["/new-build.zip"] = body+ original_get = RangeHandler.do_GET+ requests = []++ def record(handler):+ requests.append(handler.path)+ original_get(handler)++ monkeypatch.setattr(RangeHandler, "do_GET", record)+ target = current_target()+ held_target = "linux-arm64-bionic" if target != "linux-arm64-bionic" else "win32-arm64"+ held = {"url": "https://upstream.invalid/held.deb", "sha256": "b" * 64}+ lock = Lockfile(tmp_path / "lock.json")+ lock.set_pin("rolling-tool", "1.2.3", {+ target: {"url": url(dl_server, "/old-build.zip"), "sha256": "a" * 64},+ held_target: held,+ })+ lock.set_pin("unrelated", "2.0", {"any": held})+ lock.save()+ store = tmp_path / "tools"+ monkeypatch.setitem(registry._packages, "rolling-tool", RollingPackage())+ monkeypatch.setattr(paths, "lockfile_path", lambda: lock.path)+ monkeypatch.setattr(paths, "repo_root", lambda: tmp_path)+ monkeypatch.setattr(paths, "partials_root", lambda: tmp_path / "partials")+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))+ syncs = []+ engine = importlib.import_module("pm.ensure")+ monkeypatch.setattr(engine, "sync_venv", lambda **kwargs: syncs.append(kwargs))+ before = lock.path.read_bytes()+ assert cli.main(["update", "rolling-tool", "--check"]) == 1+ assert lock.path.read_bytes() == before and not requests and not syncs+ assert not store.exists()++ assert cli.main(["update", "rolling-tool"]) == 0+ after = json.loads(lock.path.read_text(encoding="utf-8"))["packages"]+ original = json.loads(before)["packages"]+ assert after["unrelated"] == original["unrelated"]+ assert after["rolling-tool"]["version"] == original["rolling-tool"]["version"]+ assert after["rolling-tool"]["artifacts"][held_target] == held+ assert Lockfile(lock.path).artifacts("rolling-tool", target) == [{+ "url": url(dl_server, "/new-build.zip"), "sha256": hashlib.sha256(body).hexdigest(),+ }]+ fact = Facts(store / "facts.json").get("rolling-tool")+ assert (store / fact["entry"] / "tool.txt").read_bytes() == b"new rolling build"+ assert syncs == [{"explicit": True}]+ assert requests and all(path == "/new-build.zip" for path in requests)++ pinned = lock.path.read_bytes()+ requests.clear()+ syncs.clear()+ for flags in (["--check"], []):+ assert cli.main(["update", "rolling-tool", *flags]) == 0+ assert lock.path.read_bytes() == pinned and not requests and not syncs