The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
merge: integrate termux cli bundles into pm-clean
ethernet0b30c2484df0
diff --cc hermes_cli/update_channel.pyindex 0c8e6f3082d,afb82253877..4eb844a9ae1--- a/hermes_cli/update_channel.py+++ b/hermes_cli/update_channel.py@@@ -204,120 -229,66 +204,147 @@@ def set_install_channelreturn sha16+ def handle_metadata_args(args, project_root: Path) -> bool:+ """Handle metadata-only update commands before any update side effect."""+ if getattr(args, "install_id", False):+ print(install_id(project_root))+ return True+ channel = getattr(args, "set_channel", None)+ if channel is None:+ return False+ try:+ key = set_install_channel(channel, project_root)+ except ValueError as exc:+ print(str(exc))+ raise SystemExit(2) from exc+ print(f"Update channel for {key}: {channel}")+ if channel == CHANNEL_CANARY:+ print("Canary builds can write forward-incompatible state. Back up your data before switching.")+ elif channel == CHANNEL_STABLE:+ from hermes_cli.steward import read_install_stamp++ current = read_install_stamp(project_root).get("displayVersion", "")+ if "-canary." in current:+ stable = current.partition("-canary.")[0]+ print(f"You are on {current}. Wait for v{stable} or a newer stable release.")+ print("For a manual reinstall, see https://hermes-agent.nousresearch.com.")+ return True++def _write_channel_record(sha16: str, path: str, channel: str) -> None:- """Write ``update.installs.<sha16>`` into config.yaml, preserving the rest."""- import yaml+ """Write ``update.installs.<sha16>`` into config.yaml, preserving the rest.++ Persists through the shared comment-preserving atomic writer+ (:func:`utils.atomic_roundtrip_yaml_update` — the same ruamel round-trip+ path ``hermes config set`` uses), fail-closed via+ :func:`hermes_cli.config.require_readable_config_before_write`. Malformed+ ``update`` / ``update.installs`` values are refused, never replaced —+ the dotted writer would otherwise turn a scalar into a mapping and+ destroy whatever the user had there.+ """+ from utils import atomic_roundtrip_yaml_update- from hermes_cli.config import get_config_path+ from hermes_cli.config import (+ get_config_path,+ require_readable_config_before_write,+ )config_path = get_config_path()- try:- raw = yaml.safe_load(config_path.read_text(encoding="utf-8-sig")) or {}- except FileNotFoundError:- raw = {}- if not isinstance(raw, dict):- raise ValueError(f"config at {config_path} is not a mapping")-- update_cfg = raw.setdefault("update", {})- if not isinstance(update_cfg, dict):+ existing = require_readable_config_before_write(config_path)+ update_cfg = existing.get("update")+ if update_cfg is not None and not isinstance(update_cfg, dict):raise ValueError("config key 'update' is not a mapping")- installs = update_cfg.setdefault("installs", {})- if not isinstance(installs, dict):+ installs = update_cfg.get("installs") if isinstance(update_cfg, dict) else None+ if installs is not None and not isinstance(installs, dict):raise ValueError("config key 'update.installs' is not a mapping")- record = installs.setdefault(sha16, {})- if not isinstance(record, dict):- record = {}- installs[sha16] = record- record["path"] = path # DATA, for humans + doctor GC- record["channel"] = channel-- config_path.parent.mkdir(parents=True, exist_ok=True)- tmp = config_path.with_suffix(config_path.suffix + ".tmp")- tmp.write_text(- yaml.safe_dump(raw, sort_keys=False, allow_unicode=True), encoding="utf-8"- )- tmp.replace(config_path)+ record = installs.get(sha16) if isinstance(installs, dict) else None+ new_record = dict(record) if isinstance(record, dict) else {}+ new_record["path"] = path # DATA, for humans + doctor GC+ new_record["channel"] = channel+ atomic_roundtrip_yaml_update(config_path, f"update.installs.{sha16}", new_record)+++def _stable_wait_target(canary_version: str) -> str:+ """The stable release a canary install waits for: the canary's own base+ version (canary is current-stable patch+1; ``v0.28.0`` from+ ``v0.28.0-canary.20260818171926``)."""+ base = re.sub(r"-canary\.\d+$", "", canary_version.strip())+ return base if base.startswith("v") else f"v{base}"+++def _stamp_channel_hint(stamp: dict) -> Optional[str]:+ """The channel the RUNNING artifact implies, for stamps without a clean+ ``tag`` (desktop About-page stamps carry ``displayVersion`` like+ ``0.28.0-canary.20260818`` — the ``v`` prefix ``is_canary_tag`` requires+ is restored before the shape check, so validation stays with the single+ canary authority). Switch text only; resolution stays with+ :func:`resolve_update_channel`."""+ if stamp.get("updateMechanism") != "electron-updater":+ return None+ version = str(stamp.get("tag") or stamp.get("displayVersion") or "")+ if not version:+ return None+ candidate = version if version.startswith("v") else f"v{version}"+ return CHANNEL_CANARY if is_canary_tag(candidate) else None+++def _set_channel_from_cli(channel: str) -> None:+ """Persist ``--set-channel`` and print the switch text. Never updates.++ Runs before the update lock, git, network, backups, or process pause:+ this is a configuration action, not an update. The reported previous+ channel prefers the stored per-install record over what the running+ artifact implies.+ """+ from hermes_cli.config import read_raw_config++ root = _default_root()+ stamp = _read_stamp(root)+ stored = channel_record(read_raw_config(), root).get("channel")+ if isinstance(stored, str) and stored.strip().lower() in VALID_CHANNELS:+ previous = stored.strip().lower()+ else:+ previous = _stamp_channel_hint(stamp) or resolve_update_channel(None, root)+ try:+ sha16 = set_install_channel(channel, root)+ except ValueError as exc:+ print(f"error: {exc}")+ sys.exit(1)++ print(f"Channel set to '{channel}' (was '{previous}') for install {sha16}.")+ version = str(stamp.get("tag") or stamp.get("displayVersion") or "")+ if previous == CHANNEL_CANARY and channel == CHANNEL_STABLE:+ print(f" You are on canary build {version}.")+ print(+ f" Stable updates begin at { _stable_wait_target(version) } —"+ " canary outversions it until that release ships."+ )+ print(" Not patient? Switch back: hermes update --set-channel canary")+ print(" Docs: https://hermes-agent.nousresearch.com")+ elif channel == CHANNEL_CANARY:+ print(+ " Canary builds are forward-incompatible: a canary install"+ " only updates to artifacts that ship after it. Downgrading"+ " means reinstalling."+ )+ sys.exit(0)+++def handle_channel_flags(args) -> None:+ """Preflight for the informational update flags.++ ``--install-id`` prints this install's id and path; ``--set-channel``+ atomically persists a valid channel record. Both terminate the command+ here — the caller never reaches the update lock, git, network, backup,+ or process-pause paths.+ """+ if getattr(args, "install_id", False):+ root = _default_root()+ print(f"{install_id(root)} {root}")+ sys.exit(0)+ channel = getattr(args, "set_channel", None)+ if channel:+ _set_channel_from_cli(channel)def stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]:diff --cc hermes_cli/web_routers/memory_providers.pyindex 6538ae9b779,07a3a5aa930..c42f7ffe373--- a/hermes_cli/web_routers/memory_providers.py+++ b/hermes_cli/web_routers/memory_providers.py@@@ -330,57 -330,56 +330,60 @@@ def _command_resultdef _install_memory_provider_pip_dependencies(name: str, dependencies: List[str]) -> List[Dict[str, Any]]:- if not dependencies:- extra = str(_memory_provider_manifest(name).get("extra") or "").strip()++ import pm++++ manifest = _memory_provider_manifest(name)++ extra = str(manifest.get("extra") or "").strip()++ if not dependencies and not extra:+ return []missing = [dep for dep in dependencies if not _dependency_importable(dep)]- need_sync, already = bool(missing), False-- if not missing:- if not dependencies and not extra:- return [] # nothing declared, nothing pm owns- if extra:- # The pm extra may still be un-synced on this machine even when- # every declared pip name imports (fresh checkout, rebuilt venv).- try:- import pm- already = pm.available(extra)- except Exception:- already = False- need_sync = not already- if already and not dependencies:- return [] # extra healthy and nothing declared to report on- else:- already = True # declared deps all importable and no extra- if not need_sync:++ if not missing and (not extra or pm.available(extra)):++ if not dependencies:++ return []return [_command_result(kind="pip", name=", ".join(dependencies), status="already_installed")]- # Route through pm's venv sync of the provider's declared extra (NS-605- # lineage): pm owns HOW (uv sync inside the venv package), so installs- # honor the sealed/managed-venv policy. A direct- # ``pip install --python sys.executable`` would corrupt a sealed venv.- display = ", ".join(missing) or extra+ # Route through pm's venv sync — the ONE install authority (uv.lock owns the+ # pins; no pip against sys.executable, and tools.lazy_deps is deleted).+ # Extras come from the existing ``_provider_extras`` owner: the declared+ # plugin.yaml ``extra:`` — or, for legacy third-party declared python+ # dependencies, it materializes the specs into a generated pyproject and+ # admits the provider dir into the workspace union BEFORE the post-config+ # selection; one sync then carries the deps.- target = ", ".join(missing)- manifest = _memory_provider_manifest(name)++ target = ", ".join(missing) or extracommand = "hermes pm install"try:-- import pm-- extra = str(_memory_provider_manifest(name).get("extra") or "").strip()- if extra:- pm.sync_venv([extra], explicit=True)+ from hermes_cli.memory_setup import _provider_extras+ from plugins.memory import find_provider_dir++ plugin_dir = find_provider_dir(name)+ extras = _provider_extras(name, manifest, plugin_dir=plugin_dir)+ if extras:+ pm.sync_venv(extras, explicit=True)+ elif plugin_dir is not None and any(+ manifest.get(k) for k in ("pip_dependencies", "python_dependencies")+ ):+ # Legacy declared deps with no own extra: admit the provider dir+ # into the workspace union (materialize is idempotent; it also+ # covers the python_dependencies key _provider_extras doesn't+ # read), then one sync carries the deps.+ from pm.workspace import enabled_member_dirs++ members = enabled_member_dirs()+ candidate = Path(plugin_dir)+ pm.sync_venv(explicit=True, plugin_dirs=members + ([candidate] if candidate not in members else []))else:- # No ``extra:`` — the legacy third-party shape. Bridge the- # declared pip_dependencies into the pm workspace union (a- # generated pyproject.toml member) and sync the venv; the- # member stamp picks the specs up on the next apply.- from pathlib import Path as _Path- from plugins.memory import find_provider_dir- from pm.workspace import materialize_legacy_pyproject- plugin_dir = find_provider_dir(name)- if plugin_dir is not None:- materialize_legacy_pyproject(_Path(plugin_dir))- pm.sync_venv(explicit=True)+ return [_command_result(+ kind="pip", name=target, status="failed", command=command,+ error="no declared extra and no plugin directory to materialize declared dependencies from",+ )]except Exception as exc:- return [_command_result(kind="pip", name=display, status="failed", command=command, error=str(exc))]- return [_command_result(- kind="pip", name=display, status="installed", command=command,- completed=subprocess.CompletedProcess(args=command, returncode=0),- )]+ return [_command_result(kind="pip", name=target, status="failed", command=command, error=str(exc))]+ still_missing = [dep for dep in missing if not _dependency_importable(dep)]- if still_missing:++ if still_missing or (extra and not pm.available(extra)):+ # The environment is selected at boot: a sync that succeeded outside+ # this interpreter's sight is NOT immediate import success — report+ # the truth instead of stamping installed without the deps visible.+ return [_command_result(kind="pip", name=target, status="restart_required", command=command)]+ return [_command_result(kind="pip", name=target, status="installed", command=command)]def _run_setup_step(results: list, kind: str, name: str, command: str, status_of, **kwargs) -> Optional[int]:diff --cc pm/cli.pyindex ec86fce1436,60d3e41f0a2..fdb56d5f665--- a/pm/cli.py+++ b/pm/cli.py@@@ -108,13 -113,30 +113,21 @@@ def _bundle_package_names() -> list[strreturn names-def _drop_unloadable_runtime_files(store_dir: Path) -> None:- """Drop the x64 VC runtime that python-build-standalone ships beside ARM64 Python."""- if current_target() != "win32-arm64":- return- facts = _facts()- facts.reload()- python = facts.get("python")- if python and "entry" in python:- (store_dir / python["entry"] / "vcruntime140_1.dll").unlink(missing_ok=True)--def cmd_install(args) -> int:+ cross_target = getattr(args, "target", None)+ if cross_target:+ if cross_target not in ALL_TARGETS:+ print(f"✗ unknown target {cross_target!r}; known: {', '.join(ALL_TARGETS)}")+ return 1+ if not args.names:+ print("✗ --target requires explicit package names")+ return 1+ # Source-install launchers require the store interpreter, even though+ # Python remains optional when provisioning individual tools.names = args.names or [- n for n in _lockfile().names() if not get_package(n).optional+ n for n in _lockfile().names() if not get_package(n).optional or n == "python"]- failed = _install_names(names)+ failed = _install_names(names, target=cross_target)if not args.names:from pm.ensure import sync_venvdiff --cc pm/ensure.pyindex b12b6e2fa6c,08a1725dd25..7f6e38b7546--- a/pm/ensure.py+++ b/pm/ensure.py@@@ -275,6 -255,107 +277,116 @@@ def _installpackage.migrate(previous["version"], version)+ def _fetch_with_retry(store, url: str, sha256: str, scratch, progress=None, attempts: int = 5):+ """store.fetch with a bounded retry: release-asset CDNs (TUR's pool+ 302s to GitHub's) throw transient 404/403 windows at their edges --+ observed live, the identical request green minutes later. The digest+ still proves the bytes; a retry cannot smuggle anything past the pin.+ """+ import time+ from pm.downloader import DownloadPaused, HashError++ last: Exception | None = None+ for attempt in range(attempts):+ try:+ return store.fetch(url, sha256, scratch, progress=progress)+ except (HashError, DownloadPaused):+ raise+ except Exception as exc: # noqa: BLE001 -- transient fetch failures retain bounded retries+ last = exc+ if attempt + 1 < attempts:+ wait = 30 * (attempt + 1)+ logging.getLogger(__name__).warning(+ "fetch failed (attempt %d/%d) for %s: %s; retrying in %ds",+ attempt + 1, attempts, url, exc, wait,+ )+ time.sleep(wait)+ raise last+++ def stage_only(name: str, target: str, progress=None) -> "Path":+ """Cross-target staging: publish the pinned (package, version, target)+ entry into the store and return its path. No facts are written and no+ Runner is composed -- the staged binaries belong to ANOTHER machine+ (e.g. linux-arm64-bionic .debs staged on a glibc CI host); this host's+ installed-state must not learn about them. Idempotent: an already+ published + verifying entry is returned as-is.+ """+ lockfile = _lockfile()+ store = _store()+ package = get_package(name)+ version = lockfile.version(package.name)+ if version is None:+ raise InstallError(package.name, "not in the lockfile")+ reason = package.missing_reason(target)+ if reason is not None:+ raise InstallError(package.name, f"unavailable on {target}: {reason}")+ if getattr(package, "pin_only", False):+ # A pure pin (e.g. the termux-docker digest): no bytes, no store+ # entry, nothing to verify locally -- the pin IS the artifact.+ return store.root / package.store_entry(version, target)+ artifacts = lockfile.artifacts(package.name, target)+ entry_name = package.store_entry(version, target)+ # The stage pin marker (same identity shape as a fact's recorded+ # artifacts: target + artifact digests) lets stage_only honor a+ # same-version hash repin without any host-side facts: the entry+ # belongs to ANOTHER machine, so the marker travels inside the entry.+ pin = json.dumps({"target": target, "sha256": [a["sha256"] for a in artifacts]})+ with store.install_lock():+ entry = store.entry(entry_name)++ previous_entry = store.entry(f".previous-stage-{entry_name}")++ if previous_entry.exists():++ # A killed publisher may have installed only part of the new tree.++ _restore_previous_entry(store, entry, previous_entry)+ if store.published(entry_name):+ marker = entry / ".pm-stage-pin.json"+ try:+ recorded = marker.read_text(encoding="utf-8")+ except OSError:+ recorded = None- # verify() returns '' on success — a non-empty reason is the- # invalid case. A valid entry is NEVER deleted; an invalid one- # or one staged from a different pin (same version, repinned- # hash, or pre-marker) is rebuilt.- if package.verify(entry, target) or recorded != pin:- _remove_entry(store, entry_name)- if not store.published(entry_name):- if not artifacts:- raise InstallError(- package.name,- f"no artifact for {target} in the lockfile",- "run `hermes pm lock --bump` for this package",++ if not package.verify(entry, target) and recorded == pin:++ return entry++ if not artifacts:++ raise InstallError(++ package.name,++ f"no artifact for {target} in the lockfile",++ "run `hermes pm lock --bump` for this package",++ )++ with store.scratch() as scratch:++ staged = scratch / "tree"++ for index, artifact in enumerate(artifacts):++ archive = _fetch_with_retry(++ store, artifact["url"], artifact["sha256"], scratch,++ progress=_artifact_progress(progress, index, len(artifacts)),+ )- with store.scratch() as scratch:- staged = scratch / "tree"- for index, artifact in enumerate(artifacts):- archive = _fetch_with_retry(- store, artifact["url"], artifact["sha256"], scratch,- progress=_artifact_progress(progress, index, len(artifacts)),- )- if index == 0:- package.unpack(archive, staged, target)- else:- extra = scratch / f"extra-{index}"- package.unpack(archive, extra, target)- merge_tree(extra, staged)- package.stage(store, staged, version, target)- reason = package.verify(staged, target)- if reason:- raise InstallError(package.name, f"staged entry failed verification: {reason}")- (staged / ".pm-stage-pin.json").write_text(pin, encoding="utf-8")++ if index == 0:++ package.unpack(archive, staged, target)++ else:++ extra = scratch / f"extra-{index}"++ package.unpack(archive, extra, target)++ merge_tree(extra, staged)++ package.stage(store, staged, version, target)++ reason = package.verify(staged, target)++ if reason:++ raise InstallError(package.name, f"staged entry failed verification: {reason}")++ (staged / ".pm-stage-pin.json").write_text(pin, encoding="utf-8")++ # Keep the old pin usable until the replacement has been verified.++ if entry.exists() or entry.is_symlink():++ entry.rename(previous_entry)++ try:+ store.publish(staged, entry_name)- reason = package.verify(store.entry(entry_name), target)- if reason:- raise InstallError(package.name, f"published entry failed verification: {reason}")++ reason = package.verify(entry, target)++ if reason:++ raise InstallError(package.name, f"published entry failed verification: {reason}")++ except BaseException:++ if previous_entry.exists():++ _restore_previous_entry(store, entry, previous_entry)++ raise++ if previous_entry.exists():++ _remove_entry(store, previous_entry.name)+ return store.entry(entry_name)++def ensure(name: str,*,diff --cc pm/packages.pyindex 1524c6e364f,bf01ca5d934..0223e1815cf--- a/pm/packages.py+++ b/pm/packages.py@@@ -196,15 -249,11 +251,18 @@@ class Python(_BionicDebArm, BinaryPackabinary = self.binary(staged, target)if binary is not None:_macos_sign_managed_python(binary)+ # python-build-standalone ships the x64 VC runtime (vcruntime140_1.dll)+ # beside ARM64 Windows Python; it cannot load on ARM64 and would fail+ # the arch guard. Drop it HERE, before publish: the tree digest is+ # recorded over the shipped bytes, so a post-publish deletion (as the+ # old bundle-time drop did) makes doctor's re-hash mismatch.+ if target == "win32-arm64":+ (staged / "vcruntime140_1.dll").unlink(missing_ok=True)def fetch_url(self, version: str, target: str) -> str:+ if target == "linux-arm64-bionic":+ pyver = version.partition("+")[0]+ return f"https://tur.kcubeterm.com/pool/tur/python3.11_{pyver}_aarch64.deb"# lock version is "<python>+<release tag>", e.g. "3.11.13+202****0807"pyver, _, tag = version.partition("+")if not tag:@@@ -423,10 -562,40 +494,41 @@@ class Nodejs(_BionicDebArm, BinaryPackaext = "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 TermuxDocker(Package):+ """The termux/termux-docker container image, pinned by registry digest.++ The image is never downloaded or unpacked by pm -- docker pulls it by+ digest reference at build time. The lock row exists so the digest is+ pinned in the single pin authority beside every other third-party+ artifact: consumers read the digest string from the lock's url field+ (termux/termux-docker@sha256:...). verify() is presence-shaped: this+ package stages nothing.+ """++ name = "termux-docker"+ optional = True+ # Pure pin: no bytes are staged, so stage_only()/install skip the store+ # entirely -- the digest's consumers (docker pull) verify it.+ pin_only = True++ def missing_reason(self, target: str) -> Optional[str]:+ return None if target == "linux-arm64-bionic" else "docker image target is linux-arm64-bionic"++ def fetch_url(self, version: str, target: str) -> str:+ return f"docker://termux/termux-docker@{version}"++ def unpack(self, archive: Path, staged: Path, target: str) -> None:+ raise InstallError(self.name, "a docker image digest is a pin, not a downloadable artifact")++ def verify(self, entry: Path, target: str) -> str:+ return ""+- def latest_versions(self, target: str, locked=None) -> list[str]:- return node_latest_versions()-+@registerclass Npm(BinaryPackage):name = "npm"@@@ -442,14 -611,34 +544,36 @@@bundled npm instead. --offline pins the bytes to the verifiedtarball; --ignore-scripts + a sanitized env keep user npm/nodeconfig out of the staging."""+ if target == "linux-arm64-bionic":+ from pm.store import extract++ unpacked = staged / ".unpacked"+ extract(archive, unpacked)+ package = unpacked / "package"+ lib = staged / "lib/node_modules/npm"+ lib.parent.mkdir(parents=True, exist_ok=True)+ package.rename(lib)+ unpacked.rmdir()+ bindir = staged / "bin"+ bindir.mkdir()+ for name in ("npm", "npx"):+ wrapper = bindir / name+ wrapper.write_text(+ "#!/data/data/com.termux/files/usr/bin/sh\n"+ 'here="$(cd "$(dirname "$0")" && pwd)"\n'+ f'exec node "$here/../lib/node_modules/npm/bin/{name}-cli.js" "$@"\n',+ encoding="utf-8",+ )+ wrapper.chmod(0o755)+ return- from pm.ensure import _facts, _store+ from pm.ensure import _installed_location, _lockfilefrom pm.registry import get_package- facts = _facts()- store = _store()node = get_package("node")+ location = _installed_location(node, _lockfile(), target)+ if location is None:+ raise InstallError(self.name, "npm extends node, which is not installed")+ facts, store = locationnode_fact = facts.get("node")if node_fact is None:raise InstallError(self.name, "npm extends node, which is not installed")@@@ -595,30 -789,51 +724,31 @@@ class Ffmpeg(_BionicDebArm, BinaryPackaprobe_args = ["-version"]def fetch_url(self, version: str, target: str) -> str:+ if target == "linux-arm64-bionic":+ return f"https://packages.termux.dev/apt/termux-main/pool/main/f/ffmpeg/ffmpeg_{version}_aarch64.deb"osname, arch = target.split("-")if osname == "win32":- # 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"+ artifact = btbn_index().get(target, {}).get(version)+ if artifact is not None:+ tag, asset = artifact+ return f"https://github.com/BtbN/FFmpeg-Builds/releases/download/{tag}/{asset}"+ else:+ epoch = martin_riedl_index().get(target, {}).get(version)+ if epoch is not None:+ osdir = "macos" if osname == "darwin" else "linux"+ source_arch = "amd64" if arch == "x64" else arch+ return f"https://ffmpeg.martin-riedl.de/download/{osdir}/{source_arch}/{epoch}_{version}/ffmpeg.zip"+ # Existing installs read exact URLs from the lockfile. Re-pinning+ # must never silently substitute a different version or target.+ raise InstallError(self.name, f"no advertised {version} artifact for {target}",+ "retry when the upstream index is available, or keep the existing pin")def latest_versions(self, target: str, locked=None) -> list[str]:if target.startswith("win32"):- return btbn_versions()+ return btbn_versions(target)return martin_riedl_versions(target)- def _btbn_fallback(self, version: str, target: str) -> str:- arch = "arm64" if target.endswith("arm64") else "64"- return (- "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"- )--@registerclass Ripgrep(BinaryPackage):name = "ripgrep"diff --cc scripts/termux/stage_apt_repo.pyindex 00000000000,c42d6d08c55..bebbb8390aemode 000000,100644..100644--- a/scripts/termux/stage_apt_repo.py+++ b/scripts/termux/stage_apt_repo.py@@@ -1,0 -1,522 +1,523 @@@+ #!/usr/bin/env python3+ """Stage a static APT repository layout (dists/ + pool/) from a pool of .debs.++ Pure stdlib. Builds dists/<suite>/{Packages,Packages.gz,Release,InRelease,Release.gpg}+ and copies .debs into pool/<first-char>/.++ Usage:+ python stage_apt_repo.py --pool POOL_DIR --out OUT_DIR \+ --suite hermes-stable|hermes-canary [--gpg-key-file PATH]++ Exit codes:+ 0 - success+ 2 - usage/IO error+ 3 - Release emitted but not signed (gpg binary or key file missing);+ CI treats 3 as failure+ """++ from __future__ import annotations++ import argparse+ import gzip+ import hashlib+ import io+ import lzma+ import os+ import shutil+ import subprocess+ import sys+ import tarfile+ import tempfile+ import time+ from pathlib import Path++from typing import NoReturn++ ARCH = "aarch64"+ COMPONENT = "main"++ REQUIRED_CONTROL_FIELDS = ["Package", "Version", "Architecture"]+++ class StageError(Exception):+ """Fatal staging error."""++-def die(msg: str, code: int = 2) -> "NoReturn": # type: ignore[valid-type]++def die(msg: str, code: int = 2) -> NoReturn:+ print(f"stage_apt_repo: {msg}", file=sys.stderr)+ raise SystemExit(code)+++ # ---------------------------------------------------------------------------+ # .deb control parsing (stdlib ar + tar, no dpkg-deb)+ # ---------------------------------------------------------------------------++ def read_ar_entries(data: bytes):+ """Yield (name, size, payload) for each member of an ar archive."""+ if data[:8] != b"!<arch>\n":+ raise StageError("not an ar archive")+ pos = 8+ while pos + 60 <= len(data):+ header = data[pos : pos + 60]+ name = header[0:16].decode("ascii", "replace").strip()+ size_field = header[48:58].decode("ascii", "replace").strip()+ try:+ size = int(size_field)+ except ValueError:+ raise StageError(f"bad ar member size {size_field!r}")+ pos += 60+ yield name, size, data[pos : pos + size]+ pos += size + (size % 2) # members are 2-byte aligned+++ def deb_control_fields_and_bytes(deb_path: Path) -> tuple[dict, bytes]:+ """Parse a .deb's control member and return (fields, raw archive bytes).++ The caller gets the raw bytes too so hashing/pool-copy need no re-read.+ """+ data = deb_path.read_bytes()+ control_tar = None+ for name, size, payload in read_ar_entries(data):+ if name in ("control.tar", "control.tar.gz", "control.tar.xz", "control.tar.zst"):+ control_tar = (name, payload)+ break+ if control_tar is None:+ raise StageError(f"{deb_path.name}: no control.tar member found")+ name, payload = control_tar++ if name == "control.tar.gz":+ raw = gzip.decompress(payload)+ elif name == "control.tar.xz":+ raw = lzma.decompress(payload)+ elif name == "control.tar.zst":+ # zstd has no stdlib decoder; dpkg-deb -Zxz (our build default)+ # keeps control in xz, but tolerate zst debs from elsewhere when+ # the host has a zstd binary.+ try:+ raw = subprocess.run(+ ["zstd", "-d", "-c"], input=payload, check=True,+ capture_output=True,+ ).stdout+ except (FileNotFoundError, subprocess.CalledProcessError) as e:+ raise StageError(+ f"{deb_path.name}: control member is zstd-compressed and no zstd binary is available"+ ) from e+ elif name == "control.tar":+ raw = payload+ else:+ raise StageError(f"{deb_path.name}: unsupported control compression {name}")++ fields: dict = {}+ with tarfile.open(fileobj=io.BytesIO(raw), mode="r:") as tf:+ for member in tf.getmembers():+ if member.name.lstrip("./") == "control":+ f = tf.extractfile(member)+ if f is None:+ continue+ fields = _parse_debian_control(f.read().decode("utf-8", "replace"))+ break+ for req in REQUIRED_CONTROL_FIELDS:+ if req not in fields:+ raise StageError(f"{deb_path.name}: control missing {req}")+ return fields, data+++ def deb_control_fields(deb_path: Path) -> dict:+ """Parse Package/Version/Architecture/... from a .deb's control member."""+ fields, _ = deb_control_fields_and_bytes(deb_path)+ return fields+++ def _parse_debian_control(text: str) -> dict:+ fields: dict = {}+ last = None+ for line in text.splitlines():+ if not line.strip():+ last = None+ continue+ if line[0] in " \t" and last:+ fields[last] += " " + line.strip()+ elif ":" in line:+ key, _, val = line.partition(":")+ last = key.strip()+ fields[last] = val.strip()+ return fields+++ # ---------------------------------------------------------------------------+ # dpkg version ordering: '~' sorts before end-of-version (and before empty)+ # ---------------------------------------------------------------------------++ def _order_char(ch: str) -> int:+ if ch == "~":+ return -1+ if ch.isdigit():+ return 0+ if ch.isalpha():+ return ord(ch)+ return ord(ch) + 256+++ def deb_version_key(version: str):+ """Sort key implementing dpkg version comparison for our versions."""+ epoch, _, rest = version.partition(":")+ epoch_num = int(epoch) if epoch.isdigit() else 0+ if ":" not in version:+ rest = version+ up, _, rev = rest.rpartition("-")+ if not up:+ up, rev = rest, ""++ def cmp_part(s: str):+ parts = []+ i = 0+ while i < len(s):+ if s[i].isdigit():+ j = i+ while j < len(s) and s[j].isdigit():+ j += 1+ parts.append((0, int(s[i:j]), ""))+ i = j+ else:+ j = i+ while j < len(s) and not s[j].isdigit():+ j += 1+ parts.append((1, tuple(_order_char(c) for c in s[i:j]), ""))+ i = j+ return parts++ # dpkg: end-of-part sorts after everything except '~'; padding the shorter+ # part with (2, ...) achieves that ('~' yields order char -1 < any pad).+ def padded(parts):+ return parts + [(2, (), "")] * 4++ return (epoch_num, padded(cmp_part(up)), padded(cmp_part(rev)))+++ # ---------------------------------------------------------------------------+ # Staging+ # ---------------------------------------------------------------------------++ def existing_published(out_dir: Path, suite: str) -> set:+ """(package, version) pairs already published in dists/<suite>/Packages."""+ packages_file = out_dir / "dists" / suite / COMPONENT / f"binary-{ARCH}" / "Packages"+ published = set()+ if packages_file.exists():+ text = packages_file.read_text(encoding="utf-8")+ # deb822 records are separated by blank lines; never rely on field+ # order inside a record.+ for stanza in text.split("\n\n"):+ pkg = ver = None+ for line in stanza.splitlines():+ if line.startswith("Package: "):+ pkg = line[len("Package: "):].strip()+ elif line.startswith("Version: "):+ ver = line[len("Version: "):].strip()+ if pkg and ver:+ published.add((pkg, ver))+ return published+++ def stage(pool_dir: Path, out_dir: Path, suite: str, gpg_key_file: Path | None) -> int:+ debs = sorted(pool_dir.glob("*.deb"))+ if not debs:+ die(f"no .deb files found in pool {pool_dir}")++ published = existing_published(out_dir, suite)++ dists = out_dir / "dists" / suite+ binary_dir = dists / COMPONENT / f"binary-{ARCH}"+ binary_dir.mkdir(parents=True, exist_ok=True)++ stanzas = []+ for deb in debs:+ fields, raw = deb_control_fields_and_bytes(deb)+ key = (fields["Package"], fields["Version"])+ if key in published:+ die(+ f"refusing: {key[0]}_{key[1]} already published in dists/{suite} "+ "(published apt assets are immutable)"+ )+ arch = fields["Architecture"]+ target = out_dir / "pool" / deb.name[0].lower() / deb.name+ target.parent.mkdir(parents=True, exist_ok=True)+ # Unconditional write: the pool file must always equal the source so+ # the stanza hashes below can never describe a stale/different file.+ target.write_bytes(raw)+ filename = f"pool/{deb.name[0].lower()}/{deb.name}"+ size = len(raw)+ sha256 = hashlib.sha256(raw).hexdigest()+ stanzas.append(+ {+ "Package": fields["Package"],+ "Version": fields["Version"],+ "Architecture": arch,+ "Maintainer": fields.get("Maintainer", "Hermes Agent <[email protected]>"),+ "Installed-Size": fields.get("Installed-Size", "0"),+ "Description": fields.get("Description", "Hermes Agent"),+ "Filename": filename,+ "Size": str(size),+ "SHA256": sha256,+ }+ )++ # Packages stanzas MUST be separated by blank lines: apt parses the file+ # as deb822 records and a missing blank line merges consecutive records+ # into one garbled stanza (biting exactly when the repo carries multiple+ # versions of the same package -- the first thing a canary+stable repo+ # has). existing_published() below relies on the same blank-line layout.+ stanzas.sort(+ key=lambda s: (s["Package"], deb_version_key(s["Version"]))+ )+ packages_text = "\n\n".join(+ "\n".join(f"{k}: {v}" for k, v in stanza.items()) for stanza in stanzas+ ) + ("\n" if stanzas else "")++ (binary_dir / "Packages").write_text(packages_text, encoding="utf-8")+ with gzip.GzipFile(filename="", mode="wb", fileobj=open(binary_dir / "Packages.gz", "wb"), mtime=0) as gz:+ gz.write(packages_text.encode("utf-8"))++ # Date is REQUIRED by apt (it refuses a Release without one) and the+ # checksum sections must stay INSIDE the same deb822 stanza: a blank+ # line ends the record, and apt then never sees the hashes ("weak+ # security information"). One paragraph, no blank lines.+ release_fields = [+ "Origin: Hermes Agent",+ "Label: hermes-agent",+ f"Suite: {suite}",+ f"Codename: {suite}",+ f"Architectures: {ARCH}",+ f"Components: {COMPONENT}",+ "Acquire-By-Hash: yes",+ f"Description: Hermes Agent apt repository ({suite})",+ "Date: " + time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime()),+ ]+ checksums = []+ sha512 = []+ for name in ("Packages", "Packages.gz"):+ p = binary_dir / name+ rel = f"{COMPONENT}/binary-{ARCH}/{name}"+ size = p.stat().st_size+ data = p.read_bytes()+ for algorithm, rows in (("SHA256", checksums), ("SHA512", sha512)):+ digest = hashlib.new(algorithm.lower(), data).hexdigest()+ rows.append(f" {digest} {size:8d} {rel}")+ immutable = binary_dir / "by-hash" / algorithm / digest+ immutable.parent.mkdir(parents=True, exist_ok=True)+ immutable.write_bytes(data)+ release = "\n".join(release_fields) + "\n"+ release += "SHA256:\n" + "\n".join(checksums) + "\n"+ release += "SHA512:\n" + "\n".join(sha512) + "\n"++ release_path = dists / "Release"+ release_path.write_text(release, encoding="utf-8")++ if gpg_key_file is not None and shutil.which("gpg"):+ sign(dists, release_path, gpg_key_file)+ return 0+ print("warning: gpg binary or key file unavailable; emitted unsigned Release", file=sys.stderr)+ return 3+++ def _gpg_homedir_arg(path: Path) -> str:+ """Format a homedir path for the host's gpg.++ On Windows the commonly available gpg is the MSYS/Git-for-Windows build,+ which rejects native ``C:\\...`` paths for --homedir and needs the+ ``/c/...`` form. POSIX gpg (CI's ubuntu runner) needs paths untouched,+ so the conversion applies only to Windows drive-letter paths.+ """+ s = str(path)+ if os.name == "nt" and len(s) >= 2 and s[1] == ":":+ return f"/{s[0].lower()}{s[2:].replace(chr(92), '/')}"+ return s+++ def _gpg_run(+ homedir: Path,+ args: list,+ *,+ stdin: bytes | None = None,+ passphrase: str | None = None,+ ) -> subprocess.CompletedProcess:+ """Run gpg with an explicit isolated homedir.++ The passphrase, when the key needs one, is fed on STDIN via+ ``--passphrase-fd 0`` -- it is never placed in argv (visible in+ /proc or error output) and never written to disk.+ """+ cmd = ["gpg", "--batch", "--yes", "--homedir", _gpg_homedir_arg(homedir)]+ if passphrase is not None:+ cmd += ["--pinentry-mode", "loopback", "--passphrase-fd", "0"]+ if stdin is not None:+ raise StageError("internal error: passphrase and data stdin are the same fd")+ stdin = passphrase.encode("utf-8")++ # File-backed capture, not pipes: gpg's spawned gpg-agent can outlive+ # (and inherit) the child's stdout/stderr pipes, and a reader waiting+ # for pipe EOF would then hang forever after gpg itself has exited.+ # A wait() on files returns as soon as gpg exits.+ # Also guarantee HOME: hardened CI runners execute with a scrubbed+ # environment (env -i), and the gpg-agent spawned by gpg fails to start+ # with no HOME set.+ env = dict(os.environ)+ if not env.get("HOME"):+ env["HOME"] = str(homedir)+ with tempfile.TemporaryDirectory(prefix="apt-stage-gpg-io-") as io_dir:+ out_path = Path(io_dir) / "stdout"+ err_path = Path(io_dir) / "stderr"+ with open(out_path, "wb") as fo, open(err_path, "wb") as fe:+ result = subprocess.run(+ [*cmd, *args],+ input=stdin,+ stdin=subprocess.DEVNULL if stdin is None else None,+ stdout=fo, stderr=fe, env=env,+ )+ result.stdout = out_path.read_bytes()+ result.stderr = err_path.read_bytes()+ if result.returncode != 0:+ raise StageError(+ f"gpg {' '.join(args[:2])} failed: {result.stderr.decode(errors='replace').strip()}"+ )+ return result+++ def _sole_secret_key_fingerprint(homedir: Path) -> str:+ """Fingerprint of the ONLY signing-capable secret key in the homedir.++ The homedir is a fresh temp dir into which exactly the supplied key file+ was imported, so whatever is here came from the import -- never a+ pre-existing unrelated key from a user keyring. If the file carried+ multiple keys we fail closed rather than silently signing with the+ first one.+ """+ listing = _gpg_run(+ homedir, ["--with-colons", "--list-secret-keys"]+ ).stdout.decode("utf-8", "replace")+ fingerprints = []+ primary = False+ for line in listing.splitlines():+ fields = line.split(":")+ if fields[0] in ("sec", "ssb"):+ primary = fields[0] == "sec"+ elif fields[0] == "fpr" and primary:+ fingerprints.append(fields[9])+ primary = False+ if not fingerprints:+ raise StageError("supplied key file produced no secret key after import")+ if len(set(fingerprints)) != 1:+ raise StageError(+ f"supplied key file contains {len(set(fingerprints))} secret keys; "+ "refusing to guess which one signs the repository"+ )+ return fingerprints[0]+++ def _verify_signature(+ homedir: Path, expected_fpr: str, sig_path: Path, signed_path: Path | None+ ) -> None:+ """Fail-closed check that sig_path is a GOOD signature by expected_fpr.++ Verified via gpg --status-fd VALIDSIG (not exit code alone), and the+ fingerprint must match the key that was selected from the import.+ """+ args = ["--with-colons", "--status-fd", "1", "--verify", str(sig_path)]+ if signed_path is not None:+ args.append(str(signed_path))+ result = _gpg_run(homedir, args)+ valid = []+ for line in result.stdout.decode("utf-8", "replace").splitlines():+ if line.startswith("[GNUPG:] VALIDSIG "):+ fields = line.split()+ valid.append(fields[2])+ if len(fields) > 11:+ valid.append(fields[11]) # Primary key when a signing subkey made the signature.+ if expected_fpr not in valid:+ raise StageError(+ f"post-sign verification failed for {sig_path.name}: no VALIDSIG "+ f"for {expected_fpr}; refusing to publish the repository"+ )+++ def sign(dists: Path, release_path: Path, gpg_key_file: Path) -> None:+ """Sign Release as InRelease + detached Release.gpg in an ISOLATED+ temp GNUPGHOME, verify the signatures fail-closed, then publish the+ signing key's public half at the repo root.++ Nothing here touches the invoking user's real keyring: the gpg homedir+ is a throwaway temp directory whose only content is the supplied key+ file, and it is removed afterwards. Real signing keys are usually+ passphrase-protected; TERMUX_APT_GPG_PASSPHRASE (set only when the key+ needs one) reaches gpg via stdin, never argv.+ """+ passphrase = os.environ.get("TERMUX_APT_GPG_PASSPHRASE", "")+ homedir = Path(tempfile.mkdtemp(prefix="apt-stage-gnupg-"))+ try:+ secret = gpg_key_file.read_bytes()+ _gpg_run(homedir, ["--import"], stdin=secret)+ key_id = _sole_secret_key_fingerprint(homedir)++ _gpg_run(+ homedir,+ [+ "--clearsign", "--local-user", key_id,+ "--output", str(dists / "InRelease"),+ str(release_path),+ ],+ passphrase=passphrase,+ )+ _gpg_run(+ homedir,+ [+ "--detach-sign", "--armor", "--local-user", key_id,+ "--output", str(dists / "Release.gpg"),+ str(release_path),+ ],+ passphrase=passphrase,+ )++ # Fail closed: the run is only a success if both artifacts verify as+ # GOOD signatures from the exact imported key. A signature that does+ # not verify is worse than none -- apt would reject the repo, but so+ # would any mirror that already cached it.+ _verify_signature(homedir, key_id, dists / "InRelease", None)+ _verify_signature(homedir, key_id, dists / "Release.gpg", release_path)++ # Publish the signing key's public half at the repo root. The key is+ # exported from the exact key that signed THIS suite, so the two can+ # never drift -- a key rotation re-publishes itself on the next run.+ # Users verify it by fingerprint (see website/docs/getting-started/+ # termux.md); the fingerprint is the trust anchor, not the URL.+ pub = _gpg_run(homedir, ["--armor", "--export", key_id]).stdout+ if not pub.strip():+ raise StageError("gpg exported an empty public key")+ (dists.parent.parent / "key.asc").write_bytes(pub)+ finally:+ shutil.rmtree(homedir, ignore_errors=True)+++ def main(argv: list | None = None) -> int:+ ap = argparse.ArgumentParser(description="Stage a static APT repo layout.")+ ap.add_argument("--pool", required=True, type=Path)+ ap.add_argument("--out", required=True, type=Path)+ # hermes-nightly is the suite actually published today+ # (https://hermes-assets.nousresearch.com/releases/termux/nightly/,+ # verified 2026-09-06); hermes-stable/hermes-canary are what CI stages+ # for the stable/canary channels.+ ap.add_argument(+ "--suite", required=True,+ choices=["hermes-stable", "hermes-canary", "hermes-nightly"],+ )+ ap.add_argument("--gpg-key-file", type=Path, default=None)+ args = ap.parse_args(argv)++ if not args.pool.is_dir():+ die(f"pool dir not found: {args.pool}")+ args.out.mkdir(parents=True, exist_ok=True)+ try:+ return stage(args.pool, args.out, args.suite, args.gpg_key_file)+ except StageError as e:+ die(str(e))+++ if __name__ == "__main__":+ sys.exit(main())diff --cc tests-js/r2-release.test.mjsindex 2ddf7eec891,b85fd334f54..9e72762a88d--- a/tests-js/r2-release.test.mjs+++ b/tests-js/r2-release.test.mjs@@@ -24,14 -24,11 +24,15 @@@ importcanonicalRequest,channelForTag,contentTypeFor,+ cacheControlFor,encodeKeyPath,feedDirFor,+ feedReferencedKeys,mergeFeedYmls,canaryDoomedKeys,+ publishFeedUploads,+ referencedFeedBundleFilenames,+ staleFeedBundleKeys,rewriteFeedPaths,stagingKeyFor,parseListXml,diff --cc tests/hermes_cli/test_web_memory_provider_setup_install.pyindex d3227901e39,00000000000..99a6651a9a3mode 100644,000000..100644--- a/tests/hermes_cli/test_web_memory_provider_setup_install.py+++ b/tests/hermes_cli/test_web_memory_provider_setup_install.py@@@ -1,143 -1,0 +1,155 @@@+"""C16: web dashboard memory-provider setup must install declared provider+extras through pm's sync authority (plugin.yaml ``extra:`` / materialized+legacy ``python_dependencies``), never ``tools.lazy_deps`` or raw pip, and+must report restart-required truthfully when the boot-selected environment+can't see a fresh install."""++from types import SimpleNamespace+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from hermes_cli.web_routers import memory_providers as mp+++def routed(monkeypatch):+ """Mutable harness over the module-level collaborators."""+ state = SimpleNamespace(+ importable=set(), # dep names that import cleanly+ manifest={},+ plugin_dir=None,+ sync_calls=[], # (extras, explicit)+ materialized=[], # plugin_dir args+ sync_error=None,+ )++ monkeypatch.setattr(mp, "_memory_provider_manifest", lambda name: state.manifest)++ import plugins.memory as plugins_memory+ monkeypatch.setattr(+ plugins_memory, "find_provider_dir", lambda name: state.plugin_dir,+ raising=False,+ )++ import hermes_cli.web_server_memory as wsm+ _IMPORT_OF = {"mem0ai": "mem0", "honcho-ai": "honcho"}++ def fake_importable(dep):+ package = dep.split("[")[0]+ for ch in "<>=!~;":+ package = package.split(ch)[0]+ return _IMPORT_OF.get(package.strip(), package.strip().replace("-", "_")) in state.importable++ monkeypatch.setattr(mp, "_dependency_importable", fake_importable)++ import pm++ monkeypatch.setattr(pm, "available", lambda extra: extra in state.importable)+ def fake_sync_venv(extras=None, *, explicit=False, plugin_dirs=None):+ state.sync_calls.append((extras, explicit))+ state.materialized.extend(plugin_dirs or [])+ if state.sync_error:+ raise state.sync_error+ # A successful sync makes freshly installed dists importable in-process.+ if getattr(state, "sync_effect", True):+ state.importable |= {"mem0", "honcho", "freshpkg"}++ monkeypatch.setattr(pm, "sync_venv", fake_sync_venv)++ return state+++class TestDeclaredExtraRouting:++ @pytest.mark.parametrize("sync_effect, status", [(True, "installed"), (False, "restart_required")])++ def test_extra_without_legacy_pip_declarations_is_synced(self, routed, sync_effect, status):++ routed.manifest = {"extra": "mem0"}++ routed.sync_effect = sync_effect++++ rows = mp._install_memory_provider_pip_dependencies("mem0", [])++++ assert routed.sync_calls == [(["mem0"], True)]++ assert rows[0]["name"] == "mem0"++ assert rows[0]["status"] == status+++ def test_extra_synced_explicitly_when_import_missing(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.importable = set()++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert routed.sync_calls == [(["mem0"], True)]+ assert rows[0]["status"] == "installed"++ def test_no_sync_when_everything_imports(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.importable = {"mem0"}++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert routed.sync_calls == []+ assert rows[0]["status"] == "already_installed"++ def test_sync_failure_reports_failed_row(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.sync_error = RuntimeError("sealed venv refuses extras")++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert rows[0]["status"] == "failed"+ assert "sealed venv" in rows[0]["stderr"]+++class TestLegacyPythonDependencies:+ def test_third_party_python_dependencies_bridge(self, routed, tmp_path):+ routed.manifest = {"python_dependencies": ["freshpkg"]}+ routed.plugin_dir = tmp_path / "external-provider"+ routed.plugin_dir.mkdir()+ (routed.plugin_dir / "plugin.yaml").write_text("name: ext\npython_dependencies: [freshpkg]\n")+ routed.importable = set()++ rows = mp._install_memory_provider_pip_dependencies("ext", ["freshpkg"])++ assert routed.materialized == [routed.plugin_dir]+ assert routed.sync_calls == [(None, True)]+ assert rows[0]["status"] == "installed"++ def test_legacy_specs_without_plugin_dir_fail_honestly(self, routed):+ routed.manifest = {"python_dependencies": ["freshpkg"]}+ routed.plugin_dir = None++ rows = mp._install_memory_provider_pip_dependencies("ext", ["freshpkg"])++ assert routed.sync_calls == []+ assert rows[0]["status"] == "failed"+++class TestRestartTruthfulness:+ def test_install_that_boot_env_cannot_see_is_restart_required(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.importable = set()+ # Sync succeeds but the freshly installed dist stays invisible+ # to this boot-selected interpreter.+ routed.sync_effect = False++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert rows[0]["status"] == "restart_required"+ assert rows[0]["status"] != "failed"++ def test_setup_result_counts_restart_required_as_not_failed(self, routed, monkeypatch):+ routed.manifest = {"extra": "mem0"}+ monkeypatch.setattr(+ mp, "_install_memory_provider_pip_dependencies",+ lambda name, deps: [{"kind": "pip", "name": "mem0ai", "status": "restart_required",+ "command": "hermes pm install mem0", "returncode": None,+ "stdout": "", "stderr": ""}],+ )+ monkeypatch.setattr(mp, "_memory_provider_setup_manifest",+ lambda name: {"pip_dependencies": ["mem0ai"], "external_dependencies": [],+ "required_env": []})+ monkeypatch.setattr(mp, "_discover_memory_provider_statuses", lambda: {})++ result = mp._install_memory_provider_setup("mem0")++ assert result["ok"] is Truediff --cc tests/pm/test_install_default_closure.pyindex 394e2a3e17e,00000000000..cc1de5807b6mode 100644,000000..100644--- a/tests/pm/test_install_default_closure.py+++ b/tests/pm/test_install_default_closure.py@@@ -1,69 -1,0 +1,69 @@@+"""The default `pm install` closure must stage the interpreter boot requires.++A fresh source install emits boot launchers (scripts/install.sh stage_path,+hermes_cli/_launchers.py) that exec the pm STORE interpreter. The `python`+package is marked optional (dev installs use their own venv; sealed bundles+adopt a shipped one), so the old default closure — every non-optional+lockfile package — skipped it and left `hermes` unbootable (audit C05).++Behavioral: drive cmd_install with the real lockfile/registry and stub+installers, asserting on the requested package names, not on script text.+"""++from __future__ import annotations++import argparse+import importlib++import pytest++import pm.cli+from pm.lock import Lockfile+from pm.paths import repo_root+from pm.registry import get_package+++def install_spy(monkeypatch):+ calls = {"names": None, "sync_extras": None}+- def fake_install_names(names):++ def fake_install_names(names, target=None):+ calls["names"] = list(names)+ return 0++ def fake_sync_venv(extras=None, **kwargs):+ calls["sync_extras"] = list(extras or [])+ return None++ monkeypatch.setattr(pm.cli, "_install_names", fake_install_names)+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "sync_venv", fake_sync_venv)+ 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:+ assert pm.cli.cmd_install(argparse.Namespace(names=None)) == 0+ 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"]+ assert install_spy["sync_extras"] is Nonediff --cc tests/pm/test_node_release_candidates.pyindex 85ce499f03c,00000000000..e3ca41bd737mode 100644,000000..100644--- a/tests/pm/test_node_release_candidates.py+++ b/tests/pm/test_node_release_candidates.py@@@ -1,11 -1,0 +1,14 @@@+"""The package lock must never choose an unstable Node release."""+from pm import update+++def test_node_candidates_exclude_prereleases(monkeypatch):++ from pm.registry import get_package+++ monkeypatch.setattr(update, "_get_json", lambda url: [+ {"version": "v26.8.0-alpha.0"}, {"version": "v26.7.0"},+ {"version": "v24.0.0-rc.1"}, {"version": "v24.20.0"},+ ])- versions = update.node_latest_versions()++ versions = get_package("node").latest_versions("linux-x64")+ assert versions == ["26.7.0", "24.20.0"]++ assert get_package("termux-docker").latest_versions("linux-arm64-bionic") == []diff --cc tests/pm/test_stage_only.pyindex 00000000000,673947907c5..483d6d6a635mode 000000,100644..100644--- a/tests/pm/test_stage_only.py+++ b/tests/pm/test_stage_only.py@@@ -1,0 -1,183 +1,209 @@@+ """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, and the lockfile + package registry are faked,+ so no network and no real install state is touched.+ """++ from __future__ import annotations++ import hashlib+ import importlib+ import json+ from pathlib import Path++ import pytest++ from pm.package import InstallError, Package+ 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."""++ name = "stage-test"++ def missing_reason(self, target: str):+ return None++ def unpack(self, archive: Path, staged: Path, target: str) -> None:+ staged.mkdir(parents=True, exist_ok=True)+ (staged / "bin").mkdir(exist_ok=True)+ (staged / "bin" / "tool").write_bytes(archive.read_bytes())++ def verify(self, entry: Path, target: str) -> str:+ return "" if (entry / "bin" / "tool").is_file() else "bin/tool missing"+++ def _sha(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++ def _seed_fetch_cache(store: Store, payload: bytes) -> None:+ """Pre-populate the store's download cache so store.fetch() proves the+ digest from local bytes instead of touching the network."""+ entry = store.entry(f"fetch-{_sha(payload)}")+ entry.mkdir(parents=True)+ (entry / "payload.bin").write_bytes(payload)+++ @pytest.fixture()+ def sandbox(tmp_path, monkeypatch):+ runtime = tmp_path / "runtime"+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))+ store = Store(runtime)+ package = _FakePackage()+ monkeypatch.setattr(ensure_mod, "get_package", lambda name: package)+ monkeypatch.setattr(ensure_mod, "_store", lambda: store)+ return store+++ def _arm_lock(monkeypatch, artifacts: list[dict]):+ lock = _FakeLockfile("1.0", artifacts)+ monkeypatch.setattr(ensure_mod, "_lockfile", lambda: lock)+ return lock+++ TARGET = "linux-arm64-bionic"+ ENTRY = "stage-test-1.0-linux-arm64-bionic"+++ 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.parametrize("error_name", ["HashError", "DownloadPaused"])+ def test_permanent_or_paused_download_is_not_retried(monkeypatch, tmp_path, error_name):+ from pm import downloader++ class FailingStore:+ def fetch(self, *args, **kwargs):+ raise getattr(downloader, error_name)("stop")++ monkeypatch.setattr("time.sleep", lambda _: pytest.fail("permanent failure was retried"))+ with pytest.raises(getattr(downloader, error_name)):+ ensure_mod._fetch_with_retry(FailingStore(), "https://example.test/tool", "digest", tmp_path)++++[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(ensure_mod, "_fetch_with_retry", 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() == markerdiff --cc tests/tools/test_transcription_tools.pyindex 9492358b4d9,35fc5afe1bd..1cd4725e925--- a/tests/tools/test_transcription_tools.py+++ b/tests/tools/test_transcription_tools.py@@@ -1206,9 -1208,9 +1208,9 @@@ class TestRunCommandSttIdleTimeoutscript.write_text("\n".join(["import sys, time",- "for idx in range(4):",+ "for idx in range(6):"," print(f'tick {idx}', file=sys.stderr, flush=True)",- " time.sleep(0.5)",+ " time.sleep(0.6)","print('done', flush=True)",]),encoding="utf-8",