Skip to content

The agent that grows with you

feat(pm): add `pm update` — resolve latest versions, re-pin the lockfile

ethernetc52974ce8a50
diff --git a/pm/cli.py b/pm/cli.py
index 1c22d859b44..52d3b8056ea 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import argparse
import json
+import os
import shutil
import subprocess
import sys
@@ -16,6 +17,7 @@ from pm.ensure import uv as pm_uv
from pm.package import InstallError
from pm.registry import get_package
from pm.store import ALL_TARGETS, current_target, hash_url
+from pm.update import Resolved, resolve_package
def cmd_lock(args) -> int:
@@ -398,6 +400,127 @@ def _run_live(cmd: list[str], *, cwd, env, timeout: int = 3600) -> tuple[int, st
return code, tail
+def cmd_update(args) -> int:
+ """`hermes pm update [names...] [--check] [--target T] [--uv] [--npm]`.
+
+ Resolve each package's latest via its own latest_versions() hook,
+ intersect across targets, and (real mode) re-pin the lockfile + install
+ the changed ones. --check is dry-run: hits upstream indexes, writes
+ nothing. --uv / --npm also refresh uv.lock (+sync venv) / package-lock.
+ """
+ lockfile = _lockfile()
+ names = args.names or [n for n in lockfile.names() if not get_package(n).internal or n == "uv"]
+ if args.target and not args.check:
+ print("::warning::--target is a CHECK-only cross-resolution flag; ignoring it for apply (the lockfile pins every target)")
+ args.target = None
+ target = args.target or current_target()
+
+ resolved = []
+ for name in names:
+ package = get_package(name)
+ targets = [t for t in ALL_TARGETS if package.missing_reason(t) is None]
+ if args.target: # cross-target check: only the requested target matters
+ targets = [t for t in targets if t == args.target]
+ if not targets:
+ continue
+ try:
+ decision = resolve_package(package, targets, lockfile.version(name))
+ except Exception as e: # an upstream index outage must not kill the whole check
+ decision = Resolved(name, lockfile.version(name), package.version_style, reason=f"resolve failed: {e}")
+ resolved.append(decision)
+
+ # ── report ────────────────────────────────────────────────────────────
+ changed = [d for d in resolved if d.changed]
+ if not resolved:
+ print("pm update: nothing to check (no resolvable packages)")
+ return 0
+ width = max(len(d.name) for d in resolved)
+ for d in resolved:
+ if d.version is None:
+ print(f"{d.name:<{width}} {d.reason or 'up to date'}")
+ elif d.changed:
+ 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}")
+ else:
+ print(f"{d.name:<{width}} {d.locked} up to date")
+ if args.check:
+ if args.uv:
+ print("uv deps: would run `uv update` + venv sync")
+ if args.npm:
+ print("npm deps: would run `npm update`")
+ return 1 if changed else 0
+
+ # ── apply ─────────────────────────────────────────────────────────────
+ if changed:
+ for d in changed:
+ package = get_package(d.name)
+ artifacts = _pin_artifacts(package, d)
+ lockfile.set_pin(d.name, d.version, artifacts)
+ print(f"✓ {d.name} pinned {d.locked or '—'} → {d.version}")
+ lockfile.save()
+ failed = _install_names([d.name for d in changed])
+ if failed:
+ return 1
+ try:
+ from pm.ensure import sync_venv
+ sync_venv(explicit=True)
+ print("✓ venv")
+ except InstallError as e:
+ print(f"✗ {e}")
+ return 1
+ else:
+ print("pm update: nothing to update")
+
+ if args.uv:
+ uv_bin, env = pm_uv()
+ if uv_bin is None:
+ print("✗ uv: not installed")
+ return 1
+ code, tail = _run_live([uv_bin, "update"], cwd=".", env=env)
+ if code != 0:
+ print(f"✗ uv update failed:\n{tail}")
+ return 1
+ print("✓ uv.lock refreshed")
+ try:
+ from pm.ensure import sync_venv
+ sync_venv(explicit=True)
+ print("✓ venv")
+ except InstallError as e:
+ print(f"✗ {e}")
+ return 1
+ if args.npm:
+ code, tail = _run_live(["npm", "update"], cwd=".", env=dict(os.environ))
+ if code != 0:
+ print(f"✗ npm update failed:\n{tail}")
+ return 1
+ print("✓ package-lock.json refreshed")
+ 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."""
+ 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:
+ 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
+
+
def cmd_bundle(args) -> int:
"""Stage a complete payload for THIS machine's target into --out:
repo snapshot + store + facts (via the normal install path, redirected)
@@ -579,6 +702,15 @@ def main(argv=None) -> int:
p.add_argument("--ref", help="git ref for the repo snapshot (default HEAD)")
p.set_defaults(func=cmd_bundle)
+ p = sub.add_parser("update", help="resolve latest versions and re-pin the lockfile")
+ p.add_argument("names", nargs="*", help="packages to check/update (default: all with a latest source)")
+ p.add_argument("--check", action="store_true",
+ help="dry-run: print what would change, write nothing (exit 1 if updates exist)")
+ p.add_argument("--target", help="resolve for a different target instead of this machine (e.g. win32-arm64)")
+ p.add_argument("--uv", action="store_true", help="also refresh uv.lock + venv (uv update + sync)")
+ p.add_argument("--npm", action="store_true", help="also refresh package-lock.json (npm update)")
+ p.set_defaults(func=cmd_update)
+
args = parser.parse_args(argv)
return args.func(args)
diff --git a/pm/package.py b/pm/package.py
index ee392b4bb75..a1e5ba4918d 100644
--- a/pm/package.py
+++ b/pm/package.py
@@ -69,6 +69,12 @@ class Package:
on_path: bool = True
url: str = ""
gaps: dict[str, str] = {}
+ # How the lockfile `version` field labels this package for `pm update`:
+ # "semver" — one shared version across targets (node 26.7.0, uv 0.12.3).
+ # "minor" — the version label is major.minor; each target's exact
+ # patch lives in ITS artifact urls (ffmpeg's posix vs win32
+ # builds have no shared release cadence).
+ version_style: str = "semver"
# Targets where this package's binary is the x64 build run under
# Windows ARM64 built-in emulation (no native arm64 artifact exists).
# The arch guard accepts the x64 PE on these targets.
@@ -77,6 +83,20 @@ class Package:
def missing_reason(self, target: str) -> Optional[str]:
return self.gaps.get(target)
+ def latest_versions(self, target: str, locked: Optional[str] = None) -> list[str]:
+ """Newest-first candidate versions for `target` — the "how do I find
+ latest" hook for `hermes pm update`. Empty list = this package has
+ no auto-update source (chromium follows agent-browser; venv is a
+ state; Playwright browsers are revision-pinned by playwright).
+
+ Subclasses resolve their upstream's real release index here; the
+ update driver intersects across targets (per version_style) and
+ only ever pins a version every relevant target can serve. ``locked``
+ is the current lockfile version when the resolver needs it (python
+ keeps its 3.11 line and bumps only the +<build-tag>)."""
+ return []
+
+
def fetch_url(self, version: str, target: str) -> str:
if not self.url:
raise InstallError(self.name, "package has no download url")
diff --git a/pm/packages.py b/pm/packages.py
index c1a4c23a28e..e1e174b2ccd 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -20,6 +20,14 @@ from pm.package import (
)
from pm.registry import register
from pm.store import ALL_TARGETS, Store, flatten_single_dir, merge_tree
+from pm.update import (
+ btbn_versions,
+ github_release_tags,
+ martin_riedl_versions,
+ node_latest_versions,
+ npm_dist_tags,
+ pbs_build_tags,
+)
_RUST_TRIPLE = {
"win32-x64": "x86_64-pc-windows-msvc",
@@ -116,6 +124,9 @@ class Uv(BinaryPackage):
ext = "zip" if target.startswith("win32") else "tar.gz"
return f"https://github.com/astral-sh/uv/releases/download/{version}/uv-{triple}.{ext}"
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ return github_release_tags("astral-sh/uv")
+
_MACOS_MANAGED_PYTHON_IDENTIFIER = "com.nousresearch.hermes.managed-python"
@@ -183,7 +194,7 @@ class Python(BinaryPackage):
_macos_sign_managed_python(binary)
def fetch_url(self, version: str, target: str) -> str:
- # lock version is "<python>+<release tag>", e.g. "3.11.13+20250807"
+ # lock version is "<python>+<release tag>", e.g. "3.11.13+202****0807"
pyver, _, tag = version.partition("+")
if not tag:
raise InstallError(self.name, f"version {version!r} needs the +<release> tag")
@@ -193,6 +204,16 @@ class Python(BinaryPackage):
f"{tag}/cpython-{pyver}+{tag}-{triple}-install_only.tar.gz"
)
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ # Stay on the locked python minor line (3.11); bump only the
+ # +<build-tag>. A major/minor bump is a deliberate decision, never
+ # an auto-update.
+ if not locked or "+" not in locked:
+ return []
+ pyver = locked.partition("+")[0]
+ minor = ".".join(pyver.split(".")[:2])
+ return [f"{pyver}+{tag}" for tag in pbs_build_tags(minor, target)]
+
def _uv_lock_digest(path: Path) -> bytes:
"""sha256 of uv.lock, cached on (mtime_ns, size) — check() runs at
@@ -315,6 +336,9 @@ class Nodejs(BinaryPackage):
ext = "zip" if target.startswith("win32") else "tar.xz"
return f"https://nodejs.org/dist/v{version}/node-v{version}-{plat}.{ext}"
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ return node_latest_versions()
+
@register
class Npm(BinaryPackage):
@@ -377,6 +401,10 @@ class Npm(BinaryPackage):
self.name, f"self-install exited {proc.returncode}: {proc.stderr[-400:]}"
)
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ latest = npm_dist_tags("npm").get("latest")
+ return [latest] if latest else []
+
@register
class Git(BinaryPackage):
@@ -403,6 +431,15 @@ class Git(BinaryPackage):
f"v{tag}.windows.{build}/Git-{tag}.{build}-{arch}.tar.bz2"
)
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ # Tag is v2.53.0.windows.3; the lock version is 2.53.0+3.
+ out = []
+ for tag in github_release_tags("git-for-windows/git", strip_prefix="v"):
+ if ".windows." in tag:
+ base, _, build = tag.partition(".windows.")
+ out.append(f"{base}+{build}")
+ return out
+
def unpack(self, archive: Path, staged: Path, target: str) -> None:
"""stdlib tar extract, but skip members the data filter refuses —
the MSYS tree ships dev/fd → /proc/self/fd style links that mean
@@ -437,6 +474,9 @@ class Gh(BinaryPackage):
f"gh_{version}_{plat}_{arch}.{ext}"
)
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ return github_release_tags("cli/cli", strip_prefix="v")
+
@register
class Ffmpeg(BinaryPackage):
@@ -451,6 +491,10 @@ class Ffmpeg(BinaryPackage):
name = "ffmpeg"
optional = False
+ # The posix (martin-riedl) and win32 (BtbN) build streams have no shared
+ # release cadence — they drift in PATCH. The lockfile version label is
+ # major.minor; each target's exact patch lives in its artifact urls.
+ version_style = "minor"
# martin-riedl (posix) zips are a single `ffmpeg` file at the zip root;
# BtbN (win32) zips carry bin/ffmpeg.exe under one top-level dir that
# flatten hoists.
@@ -464,26 +508,43 @@ class Ffmpeg(BinaryPackage):
def fetch_url(self, version: str, target: str) -> str:
osname, arch = target.split("-")
if osname == "win32":
- # BtbN ships branch builds; the URL is the immutable dated tag.
- return (
- "https://github.com/BtbN/FFmpeg-Builds/releases/download/"
- f"autobuild-{self._btbn_tag}/{self._btbn_asset(target)}"
- )
+ # BtbN: the newest autobuild tag whose assets carry this version.
+ for tag, asset in btbn_index().get(version, [])[:1]:
+ return (
+ "https://github.com/BtbN/FFmpeg-Builds/releases/download/"
+ f"{tag}/{asset}"
+ )
+ # Fall back to the pinned build (index unreachable) — this must
+ # match what the lockfile's own urls carry for the same version.
+ return self._btbn_fallback(version, target)
+ # martin-riedl: /download/<os>/<arch>/<epoch>_<version>/ffmpeg.zip
martin = {
("linux", "x64"): "linux/amd64/1787074600_9.0.1",
("linux", "arm64"): "linux/arm64/1787072884_9.0.1",
("darwin", "x64"): "macos/amd64/1787081194_9.0.1",
("darwin", "arm64"): "macos/arm64/1787073674_9.0.1",
}
+ epoch = None
+ for t, by_version in martin_riedl_index().items():
+ if t == target and version in by_version:
+ epoch = by_version[version]
+ break
+ if epoch is not None:
+ osdir = "macos" if osname == "darwin" else "linux"
+ return f"https://ffmpeg.martin-riedl.de/download/{osdir}/{arch}/{epoch}_{version}/ffmpeg.zip"
+ # Fall back to the hardcoded pinned path (index unreachable).
return f"https://ffmpeg.martin-riedl.de/download/{martin[(osname, arch)]}/ffmpeg.zip"
- def _btbn_tag(self) -> str:
- return "2026-08-28-17-08"
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ if target.startswith("win32"):
+ return btbn_versions()
+ return martin_riedl_versions(target)
- def _btbn_asset(self, target: str) -> str:
+ def _btbn_fallback(self, version: str, target: str) -> str:
arch = "arm64" if target.endswith("arm64") else "64"
return (
- "ffmpeg-n9.0.1-11-ge47273f4d9-"
+ "https://github.com/BtbN/FFmpeg-Builds/releases/download/"
+ f"autobuild-2026-08-28-17-08/ffmpeg-n{version}-11-ge47273f4d9-"
f"win{arch}-gpl-9.0.zip"
)
@@ -502,6 +563,9 @@ class Ripgrep(BinaryPackage):
f"ripgrep-{version}-{triple}.{ext}"
)
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ return github_release_tags("BurntSushi/ripgrep")
+
@register
class CuaDriver(BinaryPackage):
@@ -524,6 +588,9 @@ class CuaDriver(BinaryPackage):
f"cua-driver-rs-{version}-{arch}-binary.{ext}"
)
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ return github_release_tags("trycua/cua", strip_prefix="cua-driver-rs-v")
+
def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
flatten_single_dir(staged)
sdk = staged / "sdk"
@@ -553,6 +620,10 @@ class AgentBrowser(BinaryPackage):
# to x64 on arm64). chromium is likewise the x64 build on win32-arm64.
emulated_arch_targets = frozenset({"win32-arm64"})
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ latest = npm_dist_tags("agent-browser").get("latest")
+ return [latest] if latest else []
+
def _rel(self, target: str) -> Optional[str]:
ext = ".exe" if target.startswith("win32") else ""
# Windows ARM64 runs the x64 binary under built-in emulation:
@@ -700,6 +771,11 @@ class LlamaCpp(BinaryPackage):
def fetch_url(self, version: str, target: str) -> str:
return self.fetch_urls(version, target)[0]
+ def latest_versions(self, target: str, locked=None) -> list[str]:
+ # llama.cpp tags are b<build> (b10362); the lock version is the
+ # bare build number (10362).
+ return github_release_tags("ggml-org/llama.cpp", strip_prefix="b")
+
def known_sha256(self, version: str, url: str) -> Optional[str]:
"""GitHub's release API serves every asset's digest, so pinning a
280 MB engine costs one API call instead of the download."""
diff --git a/pm/update.py b/pm/update.py
new file mode 100644
index 00000000000..433db6e2f22
--- /dev/null
+++ b/pm/update.py
@@ -0,0 +1,347 @@
+"""hermes pm update: resolve the latest versions and re-pin the lockfile.
+
+Each Package subclass declares how to find its own latest via
+``latest_versions(target)`` (see pm/package.py); this module is the driver:
+it intersects those candidate lists across the targets the package serves,
+compares against the lockfile, and (in real mode) re-pins + reinstalls.
+
+Two version styles (``Package.version_style``):
+
+ semver — one shared version across targets (node 26.7.0, uv 0.12.3).
+ The update is the highest version every relevant target serves.
+ minor — the lockfile ``version`` field is major.minor; each target's
+ exact patch lives in ITS artifact urls. Used when the package
+ has no shared release cadence across its sources (ffmpeg's posix
+ martin-riedl builds vs win32 BtbN autobuilds drift in patch).
+ An update moves to the highest MAJOR.MINOR every relevant target
+ serves; within it each target pins its own newest patch.
+
+The ``--check`` command is dry-run only: it hits the upstream indexes (small
+HTTP GETs) but never writes the lockfile, the store, or the venv, and never
+downloads an artifact. Real ``pm update`` re-pins changed packages
+(``pm lock``-style artifact hashing), installs them, then refreshes the
+venv (uv sync) — and with the dep legs enabled, uv.lock + package-lock.json.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import urllib.request
+from dataclasses import dataclass, field
+from typing import Optional
+
+from pm.registry import get_package
+
+# ---------------------------------------------------------------------------
+# Version parsing / comparison (pure)
+# ---------------------------------------------------------------------------
+
+_VERSION_PART_RE = re.compile(r"\d+|[A-Za-z]+")
+
+
+def version_key(version: str) -> tuple:
+ """A sortable key for a version string. Handles dot-separated numerics,
+ +suffixes (python's 3.11.16+20260814, git's 2.53.0+3), and plain build
+ numbers (llamacpp's 10362). Non-numeric segments sort after numerics so
+ a prerelease never beats its release."""
+ key = []
+ for chunk in version.replace("-", ".").split("."):
+ for m in _VERSION_PART_RE.findall(chunk):
+ if m.isdigit():
+ key.append((0, int(m)))
+ else:
+ key.append((1, m))
+ return tuple(key)
+
+
+def minor_of(version: str) -> Optional[tuple[int, int]]:
+ """(major, minor) of a semver-ish string; None when not 2-part numeric."""
+ nums = [int(m) for m in _VERSION_PART_RE.findall(version) if m.isdigit()]
+ if len(nums) < 2:
+ return None
+ return (nums[0], nums[1])
+
+
+def version_in_minor(version: str, minor: tuple[int, int]) -> bool:
+ return minor_of(version) == minor
+
+
+def best_in_minor(versions: list[str], minor: tuple[int, int]) -> Optional[str]:
+ """The highest version in `versions` whose major.minor == `minor`."""
+ best = None
+ for v in versions:
+ if minor_of(v) == minor and (best is None or version_key(v) > version_key(best)):
+ best = v
+ return best
+
+
+# ---------------------------------------------------------------------------
+# Per-target intersection (pure)
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class Resolved:
+ """What `pm update` decided for ONE package."""
+
+ name: str
+ locked: Optional[str]
+ style: str
+ version: Optional[str] = None # lockfile label: full (semver) or X.Y (minor)
+ per_target: dict[str, str] = field(default_factory=dict) # target -> exact version
+ reason: str = "" # "up to date" / "no source" / "no shared minor" / ""
+
+ @property
+ def changed(self) -> bool:
+ if self.version is None:
+ return False
+ if self.locked is None:
+ return True
+ if self.style == "minor":
+ return minor_of(self.version) != minor_of(self.locked)
+ return version_key(self.version) > version_key(self.locked)
+
+
+def resolve_best(
+ name: str,
+ targets: list[str],
+ latest_by_target: dict[str, list[str]],
+ locked: Optional[str],
+ style: str,
+) -> Resolved:
+ """Intersect per-target candidate lists into one update decision.
+
+ ``latest_by_target[target]`` is newest-first. Empty candidates for a
+ target mean "no auto-update source" — the target is skipped (a missing
+ index must not block the others).
+ """
+ present = {t: vs for t, vs in latest_by_target.items() if vs}
+ if not present:
+ return Resolved(name, locked, style, reason="no source")
+
+ if style == "minor":
+ # Highest major.minor every target has; per-target exact patch.
+ minor_sets = [set(minor_of(v) for v in vs if minor_of(v)) for vs in present.values()]
+ common = set.intersection(*minor_sets) if len(minor_sets) > 1 else set(minor_sets[0])
+ if not common:
+ return Resolved(name, locked, style, reason="no shared minor")
+ shared_minor = max(common)
+ per_target = {
+ t: best_in_minor(vs, shared_minor) for t, vs in present.items()
+ }
+ return Resolved(
+ name,
+ locked,
+ style,
+ version=f"{shared_minor[0]}.{shared_minor[1]}",
+ per_target=per_target,
+ )
+
+ # semver: highest version every target serves.
+ sets = [set(vs) for vs in present.values()]
+ common = set.intersection(*sets) if len(sets) > 1 else set(sets[0])
+ if not common:
+ return Resolved(name, locked, style, reason="no shared version")
+ version = max(common, key=version_key)
+ 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."""
+ 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)
+
+
+# ---------------------------------------------------------------------------
+# Upstream index helpers (small GETs; used by package latest_versions())
+# ---------------------------------------------------------------------------
+
+_UA = {"User-Agent": "hermes-pm"}
+
+
+def _get_json(url: str) -> dict | list:
+ with urllib.request.urlopen(
+ urllib.request.Request(url, headers=_UA), timeout=60
+ ) as resp:
+ return json.load(resp)
+
+
+def _get_text(url: str) -> str:
+ with urllib.request.urlopen(
+ urllib.request.Request(url, headers=_UA), timeout=60
+ ) as resp:
+ return resp.read().decode("utf-8", "replace")
+
+
+def github_release_tags(repo: str, *, strip_prefix: str = "") -> list[str]:
+ """Newest-first release tag names for a GitHub repo (releases, not all
+ tags — no drafts/prereleases, and a rolling 'latest' pseudo-release is
+ skipped). ``strip_prefix`` removes a tag prefix (e.g. 'v', 'b'). Only
+ version-shaped tags survive the strip — cua-driver's repo also tags
+ sandbox/experimental builds (cua-driver-rs-vsandbox-v0.4.3) that must
+ never appear as update candidates."""
+ tags = []
+ for page in range(1, 4): # up to 90 releases — far beyond any cadence
+ data = _get_json(f"https://api.github.com/repos/{repo}/releases?per_page=30&page={page}")
+ if not data:
+ break
+ for release in data:
+ if release.get("draft") or release.get("prerelease"):
+ continue
+ tag = release.get("tag_name", "")
+ if tag == "latest":
+ continue
+ if strip_prefix and tag.startswith(strip_prefix):
+ tag = tag[len(strip_prefix):]
+ if not tag or not tag[0].isdigit():
+ continue
+ tags.append(tag)
+ if len(data) < 30:
+ break
+ return tags
+
+
+def npm_dist_tags(name: str) -> dict:
+ return _get_json(f"https://registry.npmjs.org/{name}").get("dist-tags", {})
+
+
+def node_latest_versions() -> list[str]:
+ """Newest-first node versions from nodejs.org's index (strip the 'v')."""
+ out = []
+ for entry in _get_json("https://nodejs.org/dist/index.json"):
+ v = entry.get("version", "")
+ if v.startswith("v"):
+ v = v[1:]
+ out.append(v)
+ return out
+
+
+def martin_riedl_index() -> dict[str, dict[str, str]]:
+ """ffmpeg.martin-riedl.de index, cached: target -> {version: epoch}.
+
+ The site has no directory listing or API — the root page is the index,
+ and it lists the CURRENT build per platform (both snapshot builds like
+ N-126314-g... and release builds like 9.0.1). Parse every
+ <epoch>_<semver> download dir; snapshots never match the numeric
+ pattern. The epoch is needed to reconstruct the download URL at pin
+ time, so the index maps version -> epoch per target."""
+ cached = _martin_cache.get()
+ if cached is not None:
+ return cached
+ try:
+ page = _get_text("https://ffmpeg.martin-riedl.de/")
+ except Exception:
+ _martin_cache.set({})
+ return {}
+ out: dict[str, dict[str, str]] = {}
+ # /download/<os>/<arch>/<epoch>_<version>/ffmpeg.zip
+ for m in re.finditer(
+ r"/download/(macos|linux)/(amd64|arm64)/(\d+)_(\d+\.\d+\.\d+)/ffmpeg\.zip",
+ page,
+ ):
+ osname, arch, epoch, version = m.groups()
+ target = f"{'darwin' if osname == 'macos' else 'linux'}-{arch}"
+ out.setdefault(target, {})[version] = epoch
+ _martin_cache.set(out)
+ return out
+
+
+def martin_riedl_versions(target: str) -> list[str]:
+ """Newest-first release versions the martin-riedl index lists for `target`."""
+ return list((martin_riedl_index().get(target) or {}).keys())
+
+
+def btbn_index() -> dict[str, list[tuple[str, str]]]:
+ """BtbN/FFmpeg-Builds autobuild index, cached: version -> [(tag, asset)].
+
+ The release tag is a dated autobuild (autobuild-2026-08-28-17-08); the
+ ffmpeg version lives in the asset names (ffmpeg-n9.0.1-11-g<hash>-
+ win64-gpl-9.0.zip). Building the download URL at pin time needs BOTH
+ the tag and the full asset name, so the index keeps them per version."""
+ cached = _btbn_cache.get()
+ if cached is not None:
+ return cached
+ out: dict[str, list[tuple[str, str]]] = {}
+ for page in range(1, 4):
+ data = _get_json(f"https://api.github.com/repos/BtbN/FFmpeg-Builds/releases?per_page=30&page={page}")
+ if not data:
+ break
+ for release in data:
+ if release.get("draft") or release.get("prerelease"):
+ continue
+ tag = release.get("tag_name", "")
+ if tag == "latest":
+ continue
+ for asset in release.get("assets", []):
+ name = asset.get("name", "")
+ m = re.search(r"(?:^|-)n(\d+\.\d+\.\d+)(?:-|$)", name)
+ if m and m.group(1) not in out:
+ out[m.group(1)] = [(tag, name)]
+ if len(data) < 30:
+ break
+ _btbn_cache.set(out)
+ return out
+
+
+def btbn_versions() -> list[str]:
+ """Newest-first ffmpeg versions BtbN autobuilds currently ship."""
+ return list(btbn_index().keys())
+
+
+def pbs_build_tags(minor: str, target: str) -> list[str]:
+ """python-build-standalone release tags (20260814, ...) newest-first that
+ actually ship the requested cpython <minor> install_only asset for
+ `target`. The release list carries assets + digests, so one fetch per
+ page is enough — scan newest-first and stop at the first tag with the
+ asset (pbs builds every supported line per release)."""
+ triple = {
+ "win32-x64": "x86_64-pc-windows-msvc",
+ "win32-arm64": "aarch64-pc-windows-msvc",
+ "linux-x64": "x86_64-unknown-linux-gnu",
+ "linux-arm64": "aarch64-unknown-linux-gnu",
+ "darwin-x64": "x86_64-apple-darwin",
+ "darwin-arm64": "aarch64-apple-darwin",
+ }[target]
+ wanted = f"cpython-{minor}."
+ for page in range(1, 3):
+ data = _get_json(f"https://api.github.com/repos/astral-sh/python-build-standalone/releases?per_page=30&page={page}")
+ if not data:
+ break
+ for release in data:
+ if release.get("draft") or release.get("prerelease"):
+ continue
+ tag = release.get("tag_name", "")
+ if not re.fullmatch(r"\d{8}", tag):
+ continue
+ if any(
+ a["name"].startswith(wanted)
+ and a["name"].endswith(f"-{triple}-install_only.tar.gz")
+ for a in release.get("assets", [])
+ ):
+ return [tag]
+ if len(data) < 30:
+ break
+ return []
+
+
+class _TTL:
+ """Tiny per-process cache so --check and the pin step share one fetch."""
+
+ def __init__(self) -> None:
+ self._value: object = None
+ self._set = False
+
+ def get(self):
+ return self._value if self._set else None
+
+ def set(self, value: object) -> None:
+ self._value = value
+ self._set = True
+
+
+_martin_cache = _TTL()
+_btbn_cache = _TTL()
diff --git a/tests/pm/test_update.py b/tests/pm/test_update.py
new file mode 100644
index 00000000000..547bc6f6a84
--- /dev/null
+++ b/tests/pm/test_update.py
@@ -0,0 +1,184 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+from pm.update import (
+ Resolved,
+ best_in_minor,
+ minor_of,
+ resolve_best,
+ resolve_package,
+ version_key,
+)
+
+
+def _pkg(pkg_name="node", version_style="semver", **latest):
+ """A stub package whose latest_versions returns canned per-target lists."""
+
+ class _P:
+ def __init__(self):
+ self.name = pkg_name
+ self.version_style = version_style
+ self._latest = dict(latest)
+
+ def latest_versions(self, target, locked=None):
+ return list(self._latest.get(target, []))
+
+ 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.11.16+20260814") > version_key("3.11.16+20260801")
+ assert version_key("26.8.1") > version_key("26.7.0")
+ assert version_key("10362") > version_key("10361")
+ # prerelease-ish segments sort after numerics
+ assert version_key("9.0.1") < version_key("9.0.1-rc1")
+
+
+def test_minor_of():
+ assert minor_of("26.7.0") == (26, 7)
+ assert minor_of("3.11.16+20260814") == (3, 11)
+ assert minor_of("10362") is None # single component
+
+
+def test_best_in_minor():
+ versions = ["9.0.3", "9.0.1", "9.1.0", "8.4.9"]
+ assert best_in_minor(versions, (9, 0)) == "9.0.3"
+ assert best_in_minor(versions, (9, 1)) == "9.1.0"
+ assert best_in_minor(versions, (10, 0)) is None
+
+
+# ── semver resolution ──────────────────────────────────────────────────────
+
+
+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",
+ )
+ 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"],
+ {"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", "linux-x64"],
+ {"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", "win32-x64"],
+ {"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", "win32-x64"],
+ {"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", "win32-x64"],
+ {"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"], {"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", "linux-x64"],
+ {"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"