Skip to content

The agent that grows with you

fix(pm): preserve runtime and user state across failure paths

ethernet1c8fae61808f
diff --git a/.github/actions/setup-pm/action.yml b/.github/actions/setup-pm/action.yml
index cfd5ddc5b72..2dda0343ac1 100644
--- a/.github/actions/setup-pm/action.yml
+++ b/.github/actions/setup-pm/action.yml
@@ -5,7 +5,7 @@ inputs:
description: python (Python and uv), node (Node and npm), or all.
default: python
extras:
- description: 'JSON array of Python project extras. Omit for tools only; [] installs core; ["dev"] adds dev.'
+ description: 'JSON extras: omit for tools; [] installs core; dev selects an isolated test environment plus the test dependency group.'
default: ''
cache:
description: Cache the verified PM tool store.
@@ -50,7 +50,7 @@ outputs:
description: PM-provisioned uv executable.
value: ${{ steps.install.outputs.uv-path }}
venv:
- description: PM-selected dependency environment, if extras were supplied.
+ description: Dependency environment; isolated test environment for dev, otherwise PM-selected runtime.
value: ${{ steps.dependencies.outputs.venv }}
target:
description: Native PM target, independent of the bootstrap interpreter architecture.
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index ec5c6829712..a27ea3c137b 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -14,13 +14,12 @@ import os
import re
import time
from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING
+from typing import Any, Callable, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import yaml
-if TYPE_CHECKING: # pragma: no cover — runtime import is lazy (see below)
- import requests
+from agent import model_metadata_http
from utils import atomic_json_write, atomic_yaml_write, base_url_host_matches, base_url_hostname
@@ -29,50 +28,6 @@ from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS
logger = logging.getLogger(__name__)
-# ``requests`` costs ~27 ms of the `import cli` waterfall, so it is resolved lazily:
-# ``_ensure_requests()`` at runtime, PEP 562 ``__getattr__`` for ``patch("agent.model_metadata.requests.get")``.
-
-
-def _ensure_requests():
- if "requests" not in globals():
- import requests as _requests
- globals()["requests"] = _requests
- return globals()["requests"]
-
-
-def __getattr__(name: str):
- if name == "requests":
- return _ensure_requests()
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
-
-
-def _resolve_requests_verify(base_url: str = "") -> bool | str:
- """SSL verify for the ``requests``-based ``/models`` probes.
-
- Per-provider config only (``ssl_verify: false``, then ``ssl_ca_cert``);
- otherwise the OS trust store. Same authority as the httpx chat client,
- so a probe and a completion never disagree about a chain.
- """
- from agent.ssl_verify import resolve_requests_verify
-
- ssl_verify = None
- ca_cert = None
- if base_url:
- try:
- from hermes_cli.config import get_custom_provider_tls_settings
- tls = get_custom_provider_tls_settings(base_url)
- if tls.get("ssl_verify") is False:
- ssl_verify = False
- ca = tls.get("ssl_ca_cert")
- if isinstance(ca, str) and ca:
- ca_cert = ca
- except Exception:
- pass # never break a probe on a config lookup
- return resolve_requests_verify(
- ca_bundle=ca_cert, ssl_verify=ssl_verify, base_url=base_url
- )
-
-
# Snapshot for callers inspecting this constant; prefix routing queries the registry live.
try:
from providers import list_providers as _list_providers
@@ -178,14 +133,10 @@ def _note_if_connect_timeout(exc: BaseException, base_url: str) -> None:
def _is_connect_timeout(exc: BaseException) -> bool:
- """True for connect-phase timeouts raised by httpx or requests. Read timeouts are
- excluded: the server accepted the connection, the opposite of a blackhole."""
- try:
- import httpx
- from requests.exceptions import ConnectTimeout
- return isinstance(exc, (httpx.ConnectTimeout, ConnectTimeout))
- except Exception:
- return False
+ """Read timeouts prove the server accepted a connection, not a blackhole."""
+ import httpx
+
+ return isinstance(exc, httpx.ConnectTimeout)
# Disk L2 for local-endpoint probes so back-to-back CLI cold starts skip the waterfall.
@@ -662,7 +613,7 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]:
)
result: Optional[str] = None
try:
- with httpx.Client(timeout=2.0, headers=_auth_headers(api_key)) as client:
+ with httpx.Client(timeout=2.0, headers=_auth_headers(api_key), verify=model_metadata_http.resolve_verify(base_url)) as client:
for name, urls, check in waterfall:
try:
for url in urls:
@@ -791,10 +742,9 @@ def fetch_model_metadata(force_refresh: bool = False) -> Dict[str, Dict[str, Any
_model_metadata_cache_time = time.time() - disk_age
return _model_metadata_cache
try:
- _ensure_requests()
# (connect, read) tuple: a flat timeout lets urllib3 block per retry stage through proxies that 403 CONNECT.
# See #46620.
- response = requests.get(OPENROUTER_MODELS_URL, timeout=(5, 10), verify=_resolve_requests_verify())
+ response = model_metadata_http.get(OPENROUTER_MODELS_URL, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
response.raise_for_status()
cache = {}
for model in response.json().get("data", []):
@@ -844,7 +794,7 @@ def _lmstudio_loaded_context(model: Dict[str, Any]) -> Optional[int]:
def _lmstudio_native_models(normalized: str, headers: Dict[str, str]) -> Dict[str, Dict[str, Any]]:
"""LM Studio ``/api/v1/models`` → cache; context comes from the first loaded instance."""
- response = requests.get(_lmstudio_server_root(normalized).rstrip("/") + "/api/v1/models", headers=headers, timeout=(5, 10), verify=_resolve_requests_verify(normalized))
+ response = model_metadata_http.get(_lmstudio_server_root(normalized).rstrip("/") + "/api/v1/models", headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify(normalized))
response.raise_for_status()
cache: Dict[str, Dict[str, Any]] = {}
for model in response.json().get("models", []):
@@ -865,28 +815,28 @@ def _apply_llamacpp_props(cache: Dict[str, Dict[str, Any]], request_candidate: s
via ``/props?model=``; unloaded children are skipped — probing could autoload them."""
base = request_candidate.rstrip("/").replace("/v1", "")
def _props(params=None):
- resp = requests.get(base + "/v1/props", params=params, headers=headers, timeout=5, verify=verify)
- if not resp.ok:
- resp = requests.get(base + "/props", params=params, headers=headers, timeout=5, verify=verify)
+ resp = model_metadata_http.get(base + "/v1/props", params=params, headers=headers, timeout=5, verify=verify)
+ if resp.is_error:
+ resp = model_metadata_http.get(base + "/props", params=params, headers=headers, timeout=5, verify=verify)
return resp
def _n_ctx(props: Dict[str, Any]) -> Any:
return (props.get("default_generation_settings") or {}).get("n_ctx")
props_resp = _props()
- if props_resp.ok:
+ if not props_resp.is_error:
props = props_resp.json()
n_ctx, model_alias = _n_ctx(props), props.get("model_alias", "")
if n_ctx and model_alias and model_alias in cache:
cache[model_alias]["context_length"] = n_ctx
return
- native = requests.get(base + "/models", headers=headers, timeout=5, verify=verify)
- if not native.ok:
+ native = model_metadata_http.get(base + "/models", headers=headers, timeout=5, verify=verify)
+ if native.is_error:
return
for child in (native.json() or {}).get("data", [])[:16]:
child_id = child.get("id") if isinstance(child, dict) else None
if not child_id or child_id not in cache or (child.get("status") or {}).get("value") not in ("loaded", "ready"):
continue
pr = _props({"model": child_id})
- child_ctx = _n_ctx(pr.json()) if pr.ok else None
+ child_ctx = _n_ctx(pr.json()) if not pr.is_error else None
if child_ctx:
cache[child_id]["context_length"] = child_ctx
@@ -911,7 +861,6 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
normalized = _normalize_base_url(base_url)
if not normalized or base_url_host_matches(normalized, "openrouter.ai"):
return {}
- _ensure_requests()
local = is_local_endpoint(normalized)
if not force_refresh:
cached = _endpoint_model_metadata_cache.get(normalized)
@@ -926,7 +875,7 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
alternate = normalized[:-3].rstrip("/") if normalized.endswith("/v1") else normalized + "/v1"
candidates = [normalized] + ([alternate] if alternate != normalized else [])
headers = _auth_headers(api_key)
- verify = _resolve_requests_verify(normalized)
+ verify = model_metadata_http.resolve_verify(normalized)
last_error: Optional[Exception] = None
if local:
try:
@@ -942,14 +891,14 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
# Cache keys stay unrewritten; only the outbound target is IPv4-resolved.
request_candidate = _localhost_to_ipv4(candidate)
url = request_candidate.rstrip("/") + "/models"
- response = None
try:
- response = requests.get(url, headers=headers, timeout=(5, 10), verify=verify, stream=True)
- if response.status_code in (401, 403):
- logger.debug("Model metadata probe received HTTP %s from %s; stopping candidate probing", response.status_code, url)
- break
- response.raise_for_status()
- payload = response.json()
+ with model_metadata_http.stream(url, headers=headers, timeout=(5, 10), verify=verify) as response:
+ if response.status_code in (401, 403):
+ logger.debug("Model metadata probe received HTTP %s from %s; stopping candidate probing", response.status_code, url)
+ break
+ response.raise_for_status()
+ response.read()
+ payload = response.json()
cache = _parse_models_payload(payload)
if any(m.get("owned_by") == "llamacpp" for m in payload.get("data", []) if isinstance(m, dict)):
with contextlib.suppress(Exception):
@@ -960,9 +909,6 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
except Exception as exc:
last_error = exc
_note_if_connect_timeout(exc, normalized)
- finally:
- if response is not None:
- response.close()
if last_error:
logger.debug("Failed to fetch model metadata from %s/models: %s", normalized, last_error)
return _remember_endpoint_models(normalized, {})
@@ -1192,7 +1138,7 @@ def _ollama_show(server_url: str, api_key: str, bare_model: str, timeout: float
"""Ollama ``/api/show`` JSON for ``bare_model``, or None on any failure (``note_blackhole``: connect timeouts condemn the host)."""
import httpx
try:
- with httpx.Client(timeout=timeout, headers=_auth_headers(api_key)) as client:
+ with httpx.Client(timeout=timeout, headers=_auth_headers(api_key), verify=model_metadata_http.resolve_verify(server_url)) as client:
resp = client.post(f"{server_url}/api/show", json={"name": bare_model})
return resp.json() if resp.status_code == 200 else None
except Exception as exc:
@@ -1409,7 +1355,7 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str
}.get(server_type)
probes = ([typed] if typed else []) + [_model_detail_ctx, lambda client: _openai_models_list_context(client, server_url, model)]
try:
- with httpx.Client(timeout=3.0, headers=_auth_headers(api_key)) as client:
+ with httpx.Client(timeout=3.0, headers=_auth_headers(api_key), verify=model_metadata_http.resolve_verify(base_url)) as client:
return next((ctx for ctx in (probe(client) for probe in probes) if ctx is not None), None)
except Exception as exc:
_note_if_connect_timeout(exc, server_url)
@@ -1428,8 +1374,7 @@ def _query_anthropic_context_length(model: str, base_url: str, api_key: str) ->
try:
base = base_url.rstrip("/").removesuffix("/v1")
headers = {"x-api-key": api_key, "anthropic-version": "2023-06-01"}
- _ensure_requests()
- resp = requests.get(f"{base}/v1/models?limit=1000", headers=headers, timeout=(5, 10), verify=_resolve_requests_verify(base_url))
+ resp = model_metadata_http.get(f"{base}/v1/models?limit=1000", headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify(base_url))
if resp.status_code != 200:
return None
for m in resp.json().get("data", []):
@@ -1560,8 +1505,7 @@ def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[D
if acct_id:
headers["ChatGPT-Account-Id"] = acct_id
try:
- _ensure_requests()
- resp = requests.get("https://chatgpt.com/backend-api/codex/models?client_version=1.0.0", headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())
+ resp = model_metadata_http.get("https://chatgpt.com/backend-api/codex/models?client_version=1.0.0", headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
if resp.status_code != 200:
logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", resp.status_code)
return {}, False
diff --git a/agent/model_metadata_http.py b/agent/model_metadata_http.py
new file mode 100644
index 00000000000..b408724c632
--- /dev/null
+++ b/agent/model_metadata_http.py
@@ -0,0 +1,55 @@
+"""Model probes share chat's TLS policy, with scoped redirect credentials."""
+from __future__ import annotations
+
+from contextlib import contextmanager
+
+
+def resolve_verify(base_url: str = ""):
+ from agent.ssl_verify import resolve_httpx_verify
+
+ settings = {}
+ if base_url:
+ try:
+ from hermes_cli.config import get_custom_provider_tls_settings
+
+ settings = get_custom_provider_tls_settings(base_url)
+ except Exception:
+ pass # Metadata remains optional when config discovery fails.
+ return resolve_httpx_verify(
+ ca_bundle=settings.get("ssl_ca_cert"),
+ ssl_verify=settings.get("ssl_verify"),
+ base_url=base_url,
+ )
+
+
+@contextmanager
+def stream(url: str, *, headers=None, params=None, timeout=10.0, verify=None):
+ import httpx
+ from hermes_cli.urllib_security import url_origin
+
+ origin = url_origin(url)
+ private_headers = {name.lower() for name in headers or {} if name.lower() not in {"accept", "user-agent"}}
+ private_headers.update({"authorization", "cookie", "proxy-authorization"})
+
+ def scope_credentials(request):
+ if url_origin(str(request.url)) != origin:
+ for name in private_headers:
+ request.headers.pop(name, None)
+
+ if isinstance(timeout, tuple):
+ connect, read = timeout
+ timeout = httpx.Timeout(read, connect=connect)
+ with httpx.Client(
+ verify=resolve_verify() if verify is None else verify,
+ timeout=timeout,
+ follow_redirects=True,
+ event_hooks={"request": [scope_credentials]},
+ ) as client:
+ with client.stream("GET", url, headers=headers, params=params) as response:
+ yield response
+
+
+def get(url: str, *, headers=None, params=None, timeout=10.0, verify=None):
+ with stream(url, headers=headers, params=params, timeout=timeout, verify=verify) as response:
+ response.read()
+ return response
diff --git a/agent/ssl_verify.py b/agent/ssl_verify.py
index 37fe2b3e351..4453ed1366e 100644
--- a/agent/ssl_verify.py
+++ b/agent/ssl_verify.py
@@ -69,22 +69,27 @@ def _coerce_insecure(ssl_verify: Any) -> bool:
return False
-_CA_CONTEXTS: dict[str, ssl.SSLContext] = {}
+_CA_CONTEXTS: dict[str | None, ssl.SSLContext] = {}
_CA_CONTEXTS_LOCK = threading.Lock()
-def _context_for_ca_bundle(ca_path: str) -> ssl.SSLContext:
- """One ``SSLContext`` per CA bundle path, process-wide.
-
- ``ssl.create_default_context(cafile=...)`` parses the whole bundle each call, and httpx
- transport sharing keys on context identity — so a per-agent context cost one parsed bundle
- AND one private connection pool per agent (and per delegated child). An ``SSLContext`` is
- safe to share across connections.
- """
+def _shared_context(ca_path: str | None) -> ssl.SSLContext:
+ """A stable context identity lets clients reuse the existing transport pool."""
with _CA_CONTEXTS_LOCK:
ctx = _CA_CONTEXTS.get(ca_path)
if ctx is None:
- ctx = ssl.create_default_context(cafile=ca_path)
+ if ca_path is not None:
+ from truststore._ssl_constants import _original_SSLContext
+
+ # An explicit bundle replaces OS trust, not augments it.
+ # PROTOCOL_TLS_CLIENT sets hostname checking and CERT_REQUIRED;
+ # assigning the original class's properties after injection recurses.
+ ctx = _original_SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+ ctx.load_verify_locations(cafile=ca_path)
+ else:
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+ if not _installed:
+ ctx.load_default_certs()
_CA_CONTEXTS[ca_path] = ctx
return ctx
@@ -120,60 +125,16 @@ def resolve_httpx_verify(
if effective_ca:
path = Path(effective_ca).expanduser()
if path.is_file():
- # An explicit bundle REPLACES the platform store for this client.
- # inject_into_ssl() rebinds ssl.SSLContext to truststore's class,
- # which ignores loaded CA files and verifies against the OS store
- # anyway — so build from the ORIGINAL class, which truststore
- # keeps for exactly this purpose. Without it a pinned
- # ssl_ca_cert silently means "trust the machine" instead.
- #
- # Do NOT assign verify_mode/check_hostname here: the stock
- # class's setters resolve ``super(SSLContext, SSLContext)``
- # against the PATCHED module global and recurse to the stack
- # limit. PROTOCOL_TLS_CLIENT already implies CERT_REQUIRED and
- # check_hostname, so there is nothing to set.
- from truststore._ssl_constants import _original_SSLContext
-
- ctx = _original_SSLContext(ssl.PROTOCOL_TLS_CLIENT)
- ctx.load_verify_locations(cafile=str(path))
- return ctx
+ return _shared_context(str(path.resolve()))
logger.warning(
"ssl_ca_cert path does not exist: %s — using the OS trust store instead",
effective_ca,
)
- return True
-
+ # HTTPX reads CA env vars before the injected verifier gets control. Pass
+ # the platform context directly so stale paths cannot break construction;
+ # proxy environment handling remains enabled.
+ import os
-def resolve_requests_verify(
- *,
- ca_bundle: Optional[str] = None,
- ssl_verify: Any = None,
- base_url: str = "",
-) -> bool | str:
- """The same decision for ``requests``, which takes a path, not a context.
-
- With the platform store installed process-wide, ``True`` already means
- "verify against the OS store" here — urllib3 builds its context through
- the patched ``ssl.SSLContext``.
- """
- install_truststore()
-
- if _coerce_insecure(ssl_verify):
- logger.warning(
- "TLS certificate verification DISABLED (ssl_verify: false) for %s — "
- "this is intended for local development only and is unsafe on any "
- "network you do not fully control.",
- base_url or "a custom provider endpoint",
- )
- return False
-
- bundle = (ca_bundle or "").strip()
- if bundle:
- path = Path(bundle).expanduser()
- if path.is_file():
- return str(path)
- logger.warning(
- "ssl_ca_cert path does not exist: %s — using the OS trust store instead",
- bundle,
- )
+ if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"):
+ return _shared_context(None)
return True
diff --git a/gateway/__init__.py b/gateway/__init__.py
index 7bf895717c9..873f114326a 100644
--- a/gateway/__init__.py
+++ b/gateway/__init__.py
@@ -1,16 +1,27 @@
"""Hermes Gateway - multi-platform messaging integration (sessions, context
injection, delivery routing, platform-specific toolsets)."""
-from .config import GatewayConfig, PlatformConfig, HomeChannel, load_gateway_config
-from .session import (
- SessionContext,
- SessionStore,
- build_session_context_prompt,
-)
-from .delivery import DeliveryRouter, DeliveryTarget
+from importlib import import_module
-__all__ = [
- "GatewayConfig", "PlatformConfig", "HomeChannel", "load_gateway_config",
- "SessionContext", "SessionStore", "build_session_context_prompt",
- "DeliveryRouter", "DeliveryTarget",
-]
+# Control/status clients must not initialize config, plugins or user data.
+# The existing package exports remain available when actually requested.
+_EXPORTS = {
+ "GatewayConfig": ".config",
+ "PlatformConfig": ".config",
+ "HomeChannel": ".config",
+ "load_gateway_config": ".config",
+ "SessionContext": ".session",
+ "SessionStore": ".session",
+ "build_session_context_prompt": ".session",
+ "DeliveryRouter": ".delivery",
+ "DeliveryTarget": ".delivery",
+}
+
+__all__ = list(_EXPORTS)
+
+
+def __getattr__(name):
+ module = _EXPORTS.get(name)
+ if module is None:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ return getattr(import_module(module, __name__), name)
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 0373ea7d501..b4b57b3bdda 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -23,6 +23,8 @@ from utils import (
_preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,
)
+from hermes_cli.archive_safe import normalize_archive_parts
+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, profile_root_entry
from hermes_cli.sizefmt import format_bytes as _format_size
from hermes_cli.backup_restore import (
@@ -72,15 +74,12 @@ _EXCLUDED_DIRS = {
# Hermes-managed runtime downloads (GGUF models, llama.cpp runtimes, managed Node): re-downloaded
# on demand and routinely tens to hundreds of GB. Matched ONLY at the root of HERMES_HOME and at
# ``profiles/<name>/`` — a deeper dir of the same name (a skill's ``models/``) is user data.
-_EXCLUDED_ROOT_DIRS = {"models", "runtimes", "node"}
+_EXCLUDED_ROOT_DIRS = {"models", "runtimes", "node"} | PM_RUNTIME_ROOT_DIRS
def _in_excluded_root_dir(rel_path: Path) -> bool:
"""True when *rel_path* is, or sits inside, a managed runtime tree at a profile-home root."""
- parts = rel_path.parts
- return bool(parts) and (
- parts[0] in _EXCLUDED_ROOT_DIRS
- or (len(parts) >= 3 and parts[0] == "profiles" and parts[2] in _EXCLUDED_ROOT_DIRS))
+ return profile_root_entry(rel_path.parts) in _EXCLUDED_ROOT_DIRS
# SQLite sidecars are excluded because ``*.db`` is snapshotted via ``sqlite3.backup()``:
@@ -888,13 +887,25 @@ def run_import(args) -> None:
if not rel:
continue
+ try:
+ parts = tuple(normalize_archive_parts(rel))
+ except ValueError:
+ errors.append(f" {rel}: path traversal blocked")
+ continue
+
# Never overwrite volatile gateway/process runtime state. These are
# namespaced to the machine/container the backup was taken on;
# clobbering them (especially gateway_state.json) breaks the gateway
# reconciler on the target and disconnects hosted instances from the
# Nous portal. Matched by basename so both the root profile and
# named profiles (profiles/<name>/gateway_state.json) are covered.
- if Path(rel).name in _IMPORT_SKIP_NAMES:
+ if parts[-1] in _IMPORT_SKIP_NAMES:
+ skipped_runtime.append(rel)
+ continue
+
+ # Older archives may contain PM selections pointing at another machine.
+ # Match their home-root paths; a plugin's own facts.json is user data.
+ if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:
skipped_runtime.append(rel)
continue
@@ -908,7 +919,7 @@ def run_import(args) -> None:
skipped_runtime.append(rel)
continue
- target = hermes_root / rel
+ target = hermes_root.joinpath(*parts)
# Security: reject absolute paths and traversals
try:
diff --git a/hermes_cli/data_cleanup.py b/hermes_cli/data_cleanup.py
new file mode 100644
index 00000000000..dc9d38293b6
--- /dev/null
+++ b/hermes_cli/data_cleanup.py
@@ -0,0 +1,101 @@
+"""Data-only deletion separates user state from the runtime that must survive."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+import stat
+
+
+@dataclass(frozen=True)
+class DataRemovalPlan:
+ home: Path
+ remove: tuple[Path, ...]
+ keep: tuple[Path, ...]
+
+
+def plan_data_removal(home: Path, project: Path, userdata: Path | None = None) -> DataRemovalPlan:
+ from hermes_constants import get_default_hermes_root
+ from hermes_cli.runtime_paths import base_venv, installs_root, store_root
+ from hermes_cli.steward import is_bundled_payload
+ from tools.checkpoint_pruning import store_lock_path
+
+ home = home.resolve()
+ if home == Path(home.anchor) or home == Path.home().resolve():
+ raise ValueError(f"refusing to erase an entire filesystem or user home: {home}")
+ machine = get_default_hermes_root(home=home).resolve()
+ protected = {
+ project.resolve(), base_venv(project).resolve(), store_root(project).resolve(),
+ installs_root().resolve(), machine / "tools", machine / "bin", machine / "cache",
+ machine / "spawn-ledger.json", home / "gateway.lock", home / ".backup.lock",
+ home / "runtime" / "active_sessions.lock", home / "cron" / ".tick.lock",
+ store_lock_path(home / "checkpoints"),
+ }
+ if home == machine:
+ protected.add(machine / "profiles")
+ if is_bundled_payload(project):
+ from hermes_cli.bundled_app import NotBundledApp, resolve_bundle_layout
+
+ try:
+ protected.add(resolve_bundle_layout(project).app_root)
+ except NotBundledApp as exc:
+ raise ValueError(str(exc)) from exc
+ # The canonical source installation may coexist with the invoking package.
+ canonical = home / "hermes-agent"
+ if (canonical / "hermes_cli" / "__init__.py").is_file():
+ protected.add(canonical)
+ remove: list[Path] = []
+ keep: set[Path] = set()
+
+ def visit(path: Path) -> None:
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ return
+ resolved = path.resolve()
+ if any(path == root or resolved == root or path.is_relative_to(root) for root in protected):
+ keep.add(path)
+ elif path.is_symlink() or path.is_junction():
+ remove.append(path) # Remove the directory entry, never its target.
+ elif any(root.is_relative_to(path) for root in protected):
+ if stat.S_ISDIR(mode):
+ for child in sorted(path.iterdir()):
+ visit(child)
+ else:
+ keep.add(path)
+ else:
+ remove.append(path)
+
+ if home.is_dir():
+ for child in sorted(home.iterdir()):
+ visit(child)
+ if home != machine:
+ userdata = None # Desktop preferences belong to the app, not a named profile.
+ if userdata is not None and not userdata.resolve().is_relative_to(home):
+ if userdata.resolve() == Path.home().resolve() or home.is_relative_to(userdata.resolve()):
+ raise ValueError(f"desktop data directory must not contain the Hermes or user home: {userdata}")
+ visit(userdata.parent.resolve() / userdata.name)
+ return DataRemovalPlan(home, tuple(remove), tuple(sorted(keep)))
+
+
+def remove_data(plan: DataRemovalPlan) -> tuple[list[Path], list[tuple[Path, str]]]:
+ import shutil
+
+ removed: list[Path] = []
+ failed: list[tuple[Path, str]] = []
+ for path in plan.remove:
+ try:
+ if path.parent.resolve() != path.parent:
+ raise OSError("parent directory changed after confirmation; refusing to follow a link")
+ mode = path.lstat().st_mode
+ if path.is_symlink() or not stat.S_ISDIR(mode):
+ path.unlink()
+ elif path.is_junction():
+ path.rmdir()
+ else:
+ shutil.rmtree(path)
+ removed.append(path)
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ failed.append((path, str(exc)))
+ return removed, failed
diff --git a/hermes_cli/data_cleanup_holders.py b/hermes_cli/data_cleanup_holders.py
new file mode 100644
index 00000000000..37c04f4def4
--- /dev/null
+++ b/hermes_cli/data_cleanup_holders.py
@@ -0,0 +1,149 @@
+"""Home-scoped runtime coordination for an explicitly confirmed data wipe."""
+from __future__ import annotations
+
+from contextlib import ExitStack, contextmanager
+from pathlib import Path
+import time
+
+
+_OWNER_STOP_HINTS = {
+ "systemd": "stop its systemd unit with systemctl before retrying",
+ "launchd": "stop its LaunchAgent with launchctl before retrying",
+ "desktop": "quit the owning desktop app before retrying",
+ "external": "stop the gateway through its external supervisor before retrying",
+}
+
+
+def _drain_manual_gateway(home: Path) -> None:
+ from gateway.control_socket import identify_gateway, pause_gateway_for_update
+ from gateway.status import get_process_start_time, get_running_pid_identity_strict, _pid_exists
+
+ identity = identify_gateway(home)
+ if identity is None:
+ if get_running_pid_identity_strict(home / "gateway.pid") is not None:
+ raise RuntimeError(f"gateway has no usable control socket for {home}; stop it through its owner and retry")
+ return
+ if not identity.get("hermes_home") or Path(identity["hermes_home"]).resolve() != home:
+ raise RuntimeError(f"gateway control identity does not match {home}")
+ owner = identity.get("supervisor")
+ if owner != "manual":
+ hint = _OWNER_STOP_HINTS.get(owner, "stop it through its supervisor before retrying")
+ raise RuntimeError(f"{owner or 'unknown'} gateway still owns {home}; {hint}")
+ if identity.get("served_profiles"):
+ raise RuntimeError("gateway serves multiple profiles; stop it explicitly before deleting one profile's data")
+ pid = identity.get("pid")
+ start = identity.get("start_time")
+ if type(pid) is not int or pid <= 0 or start is None or get_process_start_time(pid) != start:
+ raise RuntimeError(f"gateway process identity is unverified for {home}")
+ response = pause_gateway_for_update(home)
+ if not response or response.get("pid") != identity.get("pid") or not (
+ response.get("pausing") or response.get("already_stopping")
+ ):
+ raise RuntimeError(f"gateway refused to drain for {home}")
+ deadline = time.monotonic() + min(120.0, max(5.0, float(response.get("drain_timeout", 30.0)) + 5.0))
+ while time.monotonic() < deadline:
+ current = get_process_start_time(pid)
+ original_gone = not _pid_exists(pid) or (current is not None and current != start)
+ if original_gone and identify_gateway(home) is None and get_running_pid_identity_strict(home / "gateway.pid") is None:
+ return
+ time.sleep(0.05)
+ raise RuntimeError(f"gateway did not exit for {home}; no data removed")
+
+
+def _refuse_backend_writers(home: Path) -> None:
+ from hermes_constants import get_default_hermes_root
+ from hermes_cli.process_identity import LEDGER_FILENAME, _pid_alive_matches, _read_ledger
+
+ root = get_default_hermes_root(home=home).resolve()
+ rows = _read_ledger(root / LEDGER_FILENAME)
+ if rows is None:
+ raise RuntimeError(f"cannot read backend ownership: {root / LEDGER_FILENAME}")
+ for row in rows:
+ if row.get("purpose") not in {"serve", "dashboard"}:
+ continue
+ # The recorded profile is the initial UI selection, not the backend's
+ # write scope: it can serve any profile under this machine root.
+ pid = row.get("pid")
+ if type(pid) is not int or pid <= 0:
+ raise RuntimeError("backend ownership contains an invalid PID")
+ if _pid_alive_matches(pid, row.get("create_time")) is not False:
+ raise RuntimeError(f"backend PID {pid} still owns {home}; close its desktop/dashboard before retrying")
+
+
+def _refuse_cron_writers(home: Path) -> None:
+ from contextlib import closing
+ import sqlite3
+ from gateway.status import get_process_start_time, _pid_exists
+
+ path = home / "cron" / "executions.db"
+ try:
+ path.stat()
+ except FileNotFoundError:
+ return
+ # Importing cron initializes scheduler/config defaults. A deletion probe
+ # must only read the existing ledger, not recreate the data being removed.
+ try:
+ with closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=0.25)) as conn:
+ conn.row_factory = sqlite3.Row
+ rows = conn.execute("SELECT * FROM executions WHERE status IN ('claimed','running')").fetchall()
+ except sqlite3.Error as exc:
+ raise RuntimeError(f"cannot inspect cron owners in {path}: {exc}") from exc
+ for raw in rows:
+ row = dict(raw)
+ pid = row["pid"]
+ if row.get("handoff_pending"):
+ raise RuntimeError(f"cron execution {row['id']} is being handed to a worker; wait for it to finish")
+ if not _pid_exists(pid):
+ continue
+ current = get_process_start_time(pid)
+ recorded = row.get("process_started_at")
+ if current is None or recorded is None or current == recorded:
+ raise RuntimeError(f"cron execution {row['id']} still owns {home} (PID {pid}); stop it before retrying")
+
+
+def _refuse_multiplexer(home: Path) -> None:
+ from hermes_constants import get_default_hermes_root
+ from gateway.control_socket import identify_gateway
+ from gateway.status import get_running_pid_identity_strict
+
+ root = get_default_hermes_root(home=home).resolve()
+ if home == root:
+ return
+ identity = identify_gateway(root)
+ if identity is not None:
+ if home.name in identity.get("served_profiles", []):
+ raise RuntimeError(f"the default gateway serves {home}; stop the multiplexer explicitly before retrying")
+ elif get_running_pid_identity_strict(root / "gateway.pid") is not None:
+ raise RuntimeError("the default gateway's profile scope is unverified; stop it explicitly before retrying")
+
+
+@contextmanager
+def quiescent_home(home: Path):
+ """Hold existing writer locks through deletion; do not remove their inodes."""
+ from gateway.status import _release_file_lock, _try_acquire_file_lock
+ from hermes_cli.active_sessions import _FileLock, _prune_dead, _read_entries
+ from hermes_cli.runtime_state import _lock
+ from tools.checkpoint_pruning import store_lock
+
+ home = home.resolve()
+ _refuse_backend_writers(home)
+ _refuse_multiplexer(home)
+ _drain_manual_gateway(home)
+ with ExitStack() as stack:
+ stack.enter_context(store_lock(home / "checkpoints"))
+ gateway_lock = stack.enter_context((home / "gateway.lock").open("a+", encoding="utf-8"))
+ if not _try_acquire_file_lock(gateway_lock):
+ raise RuntimeError(f"gateway is still active for {home}")
+ stack.callback(_release_file_lock, gateway_lock)
+ stack.enter_context(_FileLock(home / "runtime" / "active_sessions.lock"))
+ sessions = _prune_dead(_read_entries(home / "runtime" / "active_sessions.json", strict=True), strict=True)
+ if sessions:
+ pids = sorted({entry["pid"] for entry in sessions})
+ raise RuntimeError(f"live chat sessions still own {home} (PIDs {pids}); close them before retrying")
+ for path in (home / ".backup.lock", home / "cron" / ".tick.lock"):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = stack.enter_context(path.open("a+b"))
+ if not _lock(handle.fileno(), wait=False):
+ raise RuntimeError(f"an active writer still owns {path}")
+ _refuse_cron_writers(home)
+ yield
diff --git a/hermes_cli/home_data_layout.py b/hermes_cli/home_data_layout.py
new file mode 100644
index 00000000000..72be9bb82ee
--- /dev/null
+++ b/hermes_cli/home_data_layout.py
@@ -0,0 +1,13 @@
+"""Machine-specific state excluded from portable home transfers."""
+from __future__ import annotations
+
+
+# Dependency generations, downloaded tools, and partial transfers belong to this machine.
+PM_RUNTIME_ROOT_DIRS = frozenset({"installs", "tools", "cache"})
+
+
+def profile_root_entry(parts: tuple[str, ...]) -> str | None:
+ """Locate a home-root entry without excluding same-named skill/plugin data."""
+ if len(parts) >= 3 and parts[0] == "profiles":
+ return parts[2]
+ return parts[0] if parts else None
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 1828d127bed..7f1d0a55068 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2105,6 +2105,14 @@ def cmd_uninstall(args):
print(json.dumps(gui_install_summary()))
return
+ if getattr(args, "data", False):
+ if not getattr(args, "yes", False) and not getattr(args, "dry_run", False):
+ _require_tty("uninstall --data")
+ from hermes_cli.uninstall import run_data_uninstall
+
+ run_data_uninstall(args)
+ return
+
if getattr(args, "gui", False):
if not getattr(args, "yes", False):
_require_tty("uninstall --gui")
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 44ed9973c7a..3eb4ff12a11 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -120,30 +120,20 @@ def _merge_unique(primary: list[str], secondary: list[str], key=lambda m: str(m)
def _custom_provider_ssl_context(base_url: str):
- """``ssl.SSLContext`` honoring a custom provider's ``ssl_ca_cert`` / ``ssl_verify`` (mirrors the
- httpx TLS resolution), or None so the urllib ``/models`` probe keeps the default policy."""
+ """Use the same trust decision for urllib catalogs and HTTPX metadata/chat."""
+ from agent.model_metadata_http import resolve_verify
- if not base_url:
+ verify = resolve_verify(base_url)
+ if verify is True:
return None
- try:
- from hermes_cli.config import get_custom_provider_tls_settings
-
- tls = get_custom_provider_tls_settings(base_url)
- if not tls:
- return None
+ if verify is False:
import ssl
- if tls.get("ssl_verify") is False:
- ctx = ssl.create_default_context()
- ctx.check_hostname = False
- ctx.verify_mode = ssl.CERT_NONE
- return ctx
- ca = tls.get("ssl_ca_cert")
- if isinstance(ca, str) and ca and os.path.isfile(ca):
- return ssl.create_default_context(cafile=ca)
- except Exception:
- return None # never break discovery on a TLS-config lookup
- return None
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
+ context.check_hostname = False
+ context.verify_mode = ssl.CERT_NONE
+ return context
+ return verify
# Process-lifetime picker lists refreshed from the live catalogs (see fetch_*_models).
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index f9aa5bf662a..b062815f20b 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -14,12 +14,13 @@ import subprocess
import tempfile
from dataclasses import dataclass, field
from datetime import datetime, timezone
-from pathlib import Path, PurePosixPath
+from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import yaml
from hermes_cli._subprocess_compat import noninteractive_git_env
+from hermes_cli.archive_safe import normalize_archive_parts
MANIFEST_FILENAME = "distribution.yaml"
@@ -34,7 +35,7 @@ DEFAULT_DIST_OWNED: Tuple[str, ...] = ("SOUL.md", "config.yaml", "mcp.json", "sk
from hermes_cli.profiles import DEFAULT_EXPORT_EXCLUDE_ROOT
USER_OWNED_EXCLUDE: frozenset = DEFAULT_EXPORT_EXCLUDE_ROOT | frozenset({
- "memories", "sessions", "plans", "workspace", "home", "backups", "cache", "local",
+ "memories", "sessions", "plans", "workspace", "home", "backups", "local",
})
@@ -329,10 +330,11 @@ def _owned_entries(staged: Path, manifest: DistributionManifest):
return
# Path-aware allowlist: copy exactly the declared paths.
for rel in explicit_owned:
- rel_parts = PurePosixPath(rel).parts
- if not rel_parts or rel_parts[0] in USER_OWNED_EXCLUDE:
+ try:
+ rel_parts = tuple(normalize_archive_parts(rel))
+ except ValueError:
continue
- if ".." in rel_parts or PurePosixPath(rel).is_absolute():
+ if rel_parts[0] in USER_OWNED_EXCLUDE:
continue
src = staged.joinpath(*rel_parts)
if src.exists():
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index de817bd1f1a..47ddba90db5 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -17,6 +17,7 @@ from typing import Dict, List, Optional, Tuple
from agent.skill_utils import is_excluded_skill_path
from hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz
+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS
from hermes_constants import clear_named_profile_deleted, mark_named_profile_deleted, named_profile_is_deleted
logger = logging.getLogger(__name__)
@@ -135,7 +136,7 @@ _DEFAULT_EXPORT_EXCLUDE_ROOT = DEFAULT_EXPORT_EXCLUDE_ROOT = frozenset({
"browser_screenshots", "checkpoints",
"sandboxes",
"logs", # gateway logs
-})
+}) | PM_RUNTIME_ROOT_DIRS
# Allow-list for ``export_profile("default")``: when HERMES_HOME equals the
# cwd (Docker/custom deployments), the default profile home is the working
@@ -1566,7 +1567,10 @@ def export_profile(name: str, output_path: str, extra_files: Optional[Dict[str,
# copy under a temp dir named after the canonical id: root allow-list for default,
# credential exclusion for named profiles.
def _ignore_credentials(directory: str, contents: list) -> set:
- return _EXPORT_CREDENTIAL_FILES & set(contents)
+ ignored = _EXPORT_CREDENTIAL_FILES & set(contents)
+ if Path(directory) == profile_dir:
+ ignored |= PM_RUNTIME_ROOT_DIRS & set(contents)
+ return ignored
ignore = _default_export_ignore(profile_dir) if canon == "default" else _ignore_credentials
with tempfile.TemporaryDirectory() as tmpdir:
@@ -1619,6 +1623,14 @@ def import_profile(archive_path: str, name: Optional[str] = None) -> Path:
if archive_root != canon:
final_source = staging_root / canon
extracted.rename(final_source)
+ # Remove foreign runtime state before publishing, including file-shaped roots.
+ # A failed removal must abort import rather than install a stale PM selection.
+ for child in final_source.iterdir():
+ if child.name in PM_RUNTIME_ROOT_DIRS:
+ if child.is_dir():
+ shutil.rmtree(child)
+ else:
+ child.unlink()
shutil.move(str(final_source), str(profile_dir))
return profile_dir
diff --git a/hermes_cli/subcommands/uninstall.py b/hermes_cli/subcommands/uninstall.py
index ebee0f1f54d..a9d6906767a 100644
--- a/hermes_cli/subcommands/uninstall.py
+++ b/hermes_cli/subcommands/uninstall.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import argparse
from typing import Callable
from hermes_cli.subcommands._shared import add_yes_flag
@@ -12,16 +13,17 @@ def build_uninstall_parser(subparsers, *, cmd_uninstall: Callable) -> None:
uninstall_parser = subparsers.add_parser(
"uninstall", help="Uninstall Hermes Agent",
description="Remove Hermes Agent from your system. Can keep configs/data for reinstall.")
- uninstall_parser.add_argument(
+ modes = uninstall_parser.add_mutually_exclusive_group()
+ modes.add_argument(
"--full", action="store_true",
help="Full uninstall - remove everything including configs and data")
- uninstall_parser.add_argument(
+ modes.add_argument(
"--gui", action="store_true",
help="Uninstall only the desktop Chat GUI, leaving the agent intact")
- uninstall_parser.add_argument(
+ modes.add_argument(
"--data",
action="store_true",
- help="Remove only Hermes user data (~/.hermes), leaving installed code "
+ help="Remove only the active Hermes home's user data, leaving installed code "
"intact — the one mode that works on Nix / bundled-app / Docker installs",
)
uninstall_parser.add_argument(
@@ -33,4 +35,5 @@ def build_uninstall_parser(subparsers, *, cmd_uninstall: Callable) -> None:
uninstall_parser.add_argument(
"--dry-run", action="store_true",
help="Print what uninstall would remove without changing anything")
+ uninstall_parser.add_argument("--desktop-userdata", help=argparse.SUPPRESS)
uninstall_parser.set_defaults(func=cmd_uninstall)
diff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.py
index 9233491675b..18c88656c08 100644
--- a/hermes_cli/uninstall.py
+++ b/hermes_cli/uninstall.py
@@ -219,9 +219,8 @@ def remove_node_symlinks(hermes_home: Path) -> list:
# Only act on symlinks — never delete a real binary the user put here.
if not link.is_symlink():
return False
- # os.readlink + manual join handles dangling links too (Path.resolve() on a dangling
- # link still returns the target path); the link must point into OUR node dir.
- target = (link.parent / os.readlink(link)).resolve()
+ # resolve() normalizes native Windows extended-path prefixes too.
+ target = link.resolve()
if target != node_dir and node_dir not in target.parents:
return False
link.unlink()
@@ -553,82 +552,49 @@ def _uninstall_profile(profile) -> None:
def run_data_uninstall(args):
- """Remove Hermes user data only — no code, on any install kind.
-
- This is the one destructive action that is valid everywhere: source
- checkouts, the bundled desktop app, Nix, Docker. It removes everything
- under ``$HERMES_HOME`` EXCEPT the ``hermes-agent`` checkout (which is
- code, owned by the code-removal modes / the steward), plus the desktop
- app's Electron userData directory.
- """
- hermes_home = get_hermes_home()
- agent_root = hermes_home / "hermes-agent"
- skip_confirm = bool(getattr(args, "yes", False))
-
- targets = []
- if hermes_home.exists():
- targets = sorted(
- (p for p in hermes_home.iterdir() if p.name != "hermes-agent"),
- key=lambda p: p.name,
- )
-
+ """Erase this home's data, preserving installed runtimes and sibling profiles."""
+ from hermes_cli.data_cleanup import plan_data_removal, remove_data
from hermes_cli.gui_uninstall import desktop_userdata_dir
- userdata = desktop_userdata_dir()
-
- if not targets and not userdata.exists():
- print("No Hermes user data found.")
- print(f" Checked: {hermes_home}")
+ home = get_hermes_home()
+ try:
+ userdata = getattr(args, "desktop_userdata", None)
+ plan = plan_data_removal(home, get_project_root(), Path(userdata) if userdata else desktop_userdata_dir())
+ except (OSError, ValueError, RuntimeError) as exc:
+ log_warn(str(exc))
+ raise SystemExit(1) from exc
+ if not plan.remove:
+ print(f"No Hermes user data found in {home}.")
return
+ print("Data-only removal: installed code and other profiles stay intact.")
+ print("Will remove:")
+ for path in plan.remove:
+ print(f" {path}")
+ if plan.keep:
+ print("Kept intact:")
+ for path in plan.keep:
+ print(f" {path}")
+ if bool(getattr(args, "dry_run", False)):
+ print("Dry run: no data or processes changed.")
+ return
+ if not bool(getattr(args, "yes", False)) and not _confirm_yes("to remove this home's data"):
+ return
+ from hermes_cli.data_cleanup_holders import quiescent_home
- print()
- print(color("This removes your Hermes data — config, chats, secrets, logs.", Colors.YELLOW, Colors.BOLD))
- print(color("Installed code is not touched.", Colors.CYAN))
- print()
- print(color("Will remove:", Colors.YELLOW, Colors.BOLD))
- for p in targets:
- print(f" • {p}")
- if userdata.exists():
- print(f" • {userdata} (desktop app data)")
- if agent_root.exists():
- print()
- print(color("Kept intact:", Colors.GREEN, Colors.BOLD))
- print(f" • {agent_root}")
- print()
-
- if not skip_confirm:
- try:
- confirm = input(f"Type '{color('yes', Colors.YELLOW)}' to remove your Hermes data: ").strip().lower()
- except (KeyboardInterrupt, EOFError):
- print()
- print("Cancelled.")
- return
- if confirm != "yes":
- print()
- print("Uninstall cancelled.")
- return
-
- print()
- for p in targets:
- try:
- if p.is_symlink() or p.is_file():
- p.unlink()
- else:
- shutil.rmtree(p)
- log_success(f"Removed {p}")
- except Exception as e:
- log_warn(f"Could not remove {p}: {e}")
-
- if userdata.exists():
- try:
- shutil.rmtree(userdata)
- log_success(f"Removed {userdata}")
- except Exception as e:
- log_warn(f"Could not remove {userdata}: {e}")
-
- print()
- print(color("✓ Hermes data removed.", Colors.GREEN, Colors.BOLD))
- print()
+ try:
+ with quiescent_home(plan.home):
+ removed, failed = remove_data(plan)
+ except (OSError, ValueError, RuntimeError) as exc:
+ log_warn(f"No data removed: {exc}")
+ raise SystemExit(1) from exc
+ for path in removed:
+ log_success(f"Removed {path}")
+ if failed:
+ print("Hermes data was only partially removed. Surviving targets:")
+ for path, reason in failed:
+ log_warn(f"{path}: {reason}")
+ raise SystemExit(1)
+ log_success("Hermes data removed.")
def run_gui_uninstall(args):
@@ -964,12 +930,13 @@ _RELOAD_HINT = {
class _UninstallArgs:
"""Lightweight args namespace for the module entrypoint below."""
- def __init__(self, *, mode: str):
+ def __init__(self, *, mode: str, desktop_userdata: Path | None = None):
self.gui = mode == "gui"
self.gui_summary = False
self.full = mode == "full"
self.data = mode == "data"
self.yes = True # the module entrypoint is always non-interactive
+ self.desktop_userdata = desktop_userdata
def main(argv=None) -> int:
@@ -986,9 +953,9 @@ def main(argv=None) -> int:
steward-owned installs (Nix, the bundled desktop app, Docker); the
code-removing modes hard-fail there with the steward's instructions.
- This module imports only stdlib + ``hermes_constants`` + ``hermes_cli.colors``
- (and lazily ``hermes_cli.gui_uninstall`` / ``hermes_cli.steward``), so it
- runs fine under a bare system Python with no site-packages from the venv.
+ Data-only mode keeps the runtime installed and uses its dependencies to
+ coordinate live writers. Code-removing modes can still run outside the
+ environment being removed.
"""
import argparse
parser = argparse.ArgumentParser(prog="python -m hermes_cli.uninstall")
@@ -999,8 +966,11 @@ def main(argv=None) -> int:
help="gui = Chat GUI only; lite = GUI + agent, keep data; "
"full = everything; data = user data only, keep code",
)
+ parser.add_argument("--desktop-userdata", type=Path, help=argparse.SUPPRESS)
ns = parser.parse_args(argv)
- args = _UninstallArgs(mode=ns.mode)
+ if ns.desktop_userdata is not None and ns.mode != "data":
+ parser.error("--desktop-userdata requires --mode data")
+ args = _UninstallArgs(mode=ns.mode, desktop_userdata=ns.desktop_userdata)
if args.data:
run_data_uninstall(args)
diff --git a/pm/cli.py b/pm/cli.py
index 6c2f870b1f8..db76357e267 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -203,7 +203,7 @@ def _gc_store(store, facts) -> tuple[int, int]:
facts) and partials an in-flight download still owns. Returns
(removed, kept).
"""
- from pm.downloader import gc_protected_names
+ from pm.download_state import collect_partials
from pm import paths
partials_dir = paths.partials_root()
@@ -213,22 +213,7 @@ def _gc_store(store, facts) -> tuple[int, int]:
with store.install_lock():
facts.reload()
keep = facts.entries_in_use()
- # Partials an in-flight (or recently interrupted) download still
- # owns must survive the sweep. They live in the writable partials
- # area, NOT the store root, so sweep that area directly.
- protected_partials = gc_protected_names(partials_dir)
- if partials_dir.is_dir():
- for child in sorted(partials_dir.iterdir()):
- if child.name in protected_partials:
- continue
- print(f"removing partials/{child.name}")
- if child.is_dir():
- shutil.rmtree(child, ignore_errors=True)
- else:
- try:
- child.unlink()
- except OSError:
- pass
+ collect_partials(partials_dir)
for item in sorted(store.root.iterdir()):
if not item.is_dir() or item.name.startswith("."):
continue
diff --git a/pm/download_state.py b/pm/download_state.py
new file mode 100644
index 00000000000..9905e7418e2
--- /dev/null
+++ b/pm/download_state.py
@@ -0,0 +1,53 @@
+"""Cross-process ownership of resumable partials and their GC boundary."""
+from __future__ import annotations
+
+from contextlib import contextmanager
+import os
+from pathlib import Path
+import time
+
+from hermes_cli.runtime_state import _lock
+
+
+@contextmanager
+def partial_lock(root: Path, key: str, *, cancelled=None, wait: bool = True):
+ # Lock inodes must survive release: removing one lets a new owner lock a
+ # different inode while an older waiter still holds the original handle.
+ locks = root / ".locks"
+ locks.mkdir(parents=True, exist_ok=True)
+ fd = os.open(locks / key, os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ while not _lock(fd, wait=False):
+ if not wait:
+ yield False
+ return
+ if cancelled is not None and cancelled():
+ yield False
+ return
+ time.sleep(0.05)
+ yield True
+ finally:
+ os.close(fd)
+
+
+GC_GRACE_SECONDS = 6 * 60 * 60
+
+
+def collect_partials(root: Path, *, grace_seconds: float = GC_GRACE_SECONDS) -> None:
+ """Do not let a GC snapshot race a downloader acquiring ownership."""
+ if not root.is_dir():
+ return
+ keys = {path.stem for path in root.iterdir() if path.suffix in {".part", ".ranges"}}
+ now = time.time()
+ for key in sorted(keys):
+ with partial_lock(root, key, wait=False) as acquired:
+ if not acquired:
+ continue
+ pair = [root / f"{key}{suffix}" for suffix in (".part", ".ranges")]
+ try:
+ if any(path.exists() and grace_seconds > 0 and now - path.stat().st_mtime < grace_seconds for path in pair):
+ continue
+ for path in pair:
+ path.unlink(missing_ok=True)
+ except OSError:
+ continue # An inaccessible partial is not evidence it is unused.
diff --git a/pm/downloader.py b/pm/downloader.py
index e7fff1b07b6..ccc9e307f99 100644
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@ -6,11 +6,12 @@ unverified — catalog sizes may lag an upstream re-upload, so sha256 is
optional per source).
Partial state is the downloader's own. Files land in a managed
-partials area keyed by sha256(url), and a finished file is MOVED into
-its real destination, so a caller only ever sees a complete file or
-nothing. An interrupted download leaves its partial + a .ranges sidecar
-(the durable byte-range bitmap) behind, and the next run re-fetches
-exactly the ranges the bitmap says are missing.
+partials area keyed by sha256(url). One process owns each key while it
+transfers or publishes. Complete bytes are copied to destination-local
+staging before atomic replacement; a failed copy leaves the old destination
+intact. An interrupted download keeps its durable ranges bound to the remote
+length, strong ETag and optional pinned hash. Unidentified data restarts
+instead of mixing bytes from different upstream versions.
The progress callback reports the whole job AND the per-dest bitmap:
``progress(overall_done, overall_total, ranges)`` where ``ranges`` maps
@@ -22,6 +23,7 @@ from __future__ import annotations
import hashlib
import json
+import re
import shutil
import logging
import threading
@@ -35,7 +37,7 @@ from typing import Callable, Optional, Sequence
# TUR's pool 302s to) 403s unknown tool UAs from CI runner IP ranges --
# their docs require a real User-Agent. A browser-shaped one is the
# least-privileged string every asset CDN accepts.
-_UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) hermes-pm/1.0"}
+_UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) hermes-pm/1.0", "Accept-Encoding": "identity"}
_LOOPBACK = ("http://127.0.0.1:", "http://localhost:", "http://[::1]:")
_CHUNK = 1 << 20 # read/write block, also the minimum range size
@@ -48,17 +50,9 @@ class _HttpsRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
if not (newurl.startswith("https://") or newurl.startswith(_LOOPBACK)):
raise DownloadError(f"refusing redirect to non-https url: {newurl}")
- forwarded = super().redirect_request(req, fp, code, msg, headers, newurl)
- if forwarded is not None:
- # urllib's default redirect DROPS custom headers (rebuilds the
- # request from the URL alone). Release-asset CDNs (GitHub's,
- # TUR's) 403 requests without a real User-Agent, so the pin
- # fetch died on the redirect hop. Carry our headers forward.
- carried = dict(req.headers)
- carried.pop("Host", None)
- for k, v in carried.items():
- forwarded.add_header(k, v)
- return forwarded
+ # urllib preserves our User-Agent and range headers. Do not re-add
+ # arbitrary headers after its redirect policy has processed them.
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
_OPENER = urllib.request.build_opener(_HttpsRedirectHandler())
@@ -68,6 +62,38 @@ class DownloadError(RuntimeError):
"""Base class for downloader failures."""
+def _validate_range(response, start: int, end: int, total: int | None = None) -> int:
+ """A range body is useful only for the exact requested interval."""
+ match = re.fullmatch(r"bytes (\d+)-(\d+)/(\d+)", response.headers.get("Content-Range", ""))
+ if response.status != 206 or match is None:
+ raise _RangeError("server did not honor the requested byte range")
+ first, last, size = map(int, match.groups())
+ if (first, last) != (start, end - 1) or size < end or (total is not None and size != total):
+ raise _RangeError("server returned a different byte range or representation size")
+ length = response.headers.get("Content-Length")
+ if length is not None and (not length.isdecimal() or int(length) != end - start):
+ raise _RangeError("range Content-Length does not match its bounds")
+ if response.headers.get("Content-Encoding", "identity").lower() != "identity":
+ raise _RangeError("encoded response cannot be written into an identity byte range")
+ return size
+
+
+class _RangeError(DownloadError):
+ """Range or representation identity changed; partial bytes cannot be reused."""
+
+
+@dataclass(frozen=True)
+class _Remote:
+ total: int
+ ranged: bool
+ etag: str = ""
+
+
+def _strong_etag(response) -> str:
+ value = response.headers.get("ETag", "")
+ return value if value.startswith('"') and value.endswith('"') else ""
+
+
class HashError(DownloadError):
"""The downloaded bytes did not match the pinned sha256."""
@@ -126,10 +152,11 @@ def _sha256_file(path: Path) -> str:
def _existing_dest_ok(source: "Source") -> bool:
- """A dest already on disk counts as done only when it is a genuine
- complete download. No pinned hash (model-catalog policy): a present
- file is accepted — size is the tripwire, same as a fresh fetch. With a
- pinned sha256 the existing file must match, or it is re-fetched."""
+ """Pinned destinations are rehashed; unpinned model files are accepted as-is.
+
+ Catalog policy does not supply their expected hash or stable length.
+ Only this downloader's publication path guarantees complete new files.
+ """
if not source.dest.exists():
return False
if not source.sha256:
@@ -140,45 +167,6 @@ def _existing_dest_ok(source: "Source") -> bool:
return False
-# `pm gc` must not delete partials an in-flight download is still writing.
-# A sidecar's mtime is the heartbeat: it is (re)written whenever a download
-# pauses or errors, and the .part grows on every chunk. Anything touched
-# within the grace window is live; everything older is fair game.
-GC_GRACE_SECONDS = 6 * 60 * 60
-
-
-def gc_protected_names(
- partials_dir: Path, *, grace_seconds: float = GC_GRACE_SECONDS
-) -> set[str]:
- """Entry names under ``partials_dir`` an in-flight (or recently
- interrupted) download still owns — ``<key>.part`` / ``<key>.ranges``
- pairs whose newest mtime is within ``grace_seconds`` of now.
-
- gc sweeps call this BEFORE rmtree-ing store entries: partials live in
- the store root, and the old name-prefix skip (``startswith(".")``)
- does not cover the "partials" directory. A caller deletes only the
- names absent from the returned set.
- """
- import time
-
- partials_dir = Path(partials_dir)
- now = time.time()
- protected: set[str] = set()
- if not partials_dir.is_dir():
- return protected
- for entry in partials_dir.iterdir():
- try:
- # Strict < : grace_seconds=0 protects nothing (the test
- # contract for "sweep everything"). mtime can tick a hair
- # NEWER than `now` on some filesystems, which <= would
- # wrongly treat as inside a zero window.
- if grace_seconds > 0 and now - entry.stat().st_mtime < grace_seconds:
- protected.add(entry.name)
- except OSError:
- protected.add(entry.name) # unreadable → assume live
- return protected
-
-
class Download:
"""One resumable download job: a plan of sources, run in parallel.
@@ -188,9 +176,9 @@ class Download:
thread. A lock-protected bitmap records which ranges are actually
durable; on resume only the missing ranges are re-fetched.
- A finished source is MOVED into ``Source.dest``. ``pause()`` stops
- between chunks and ``run()`` raises :class:`DownloadPaused`,
- leaving every partial + sidecar intact for a later resume.
+ ``Source.dest`` is atomically replaced only after successful transfer.
+ ``pause()`` stops between chunks or while waiting for a partial's owner;
+ ``run()`` raises :class:`DownloadPaused` and preserves resumable bytes.
"""
CONNECTIONS = 8
@@ -227,223 +215,226 @@ class Download:
or source.url.startswith(_LOOPBACK)):
raise ValueError(f"refusing non-https url: {source.url}")
- # Probe every source up front so overall_total is the whole job.
- probed = [] # (source, total, range_supported)
- for source in self.sources:
- if _existing_dest_ok(source):
- probed.append((source, source.dest.stat().st_size, True))
- continue
- # A pre-existing dest that fails its pinned hash is stale — clear
- # it so the fetch below replaces it rather than trusting it.
- if source.dest.exists():
- source.dest.unlink(missing_ok=True)
- total, supported = self._probe(source.url)
- probed.append((source, total, supported))
- overall_total = sum(t for _, t, _ in probed)
-
- moved: list[Path] = []
+ # Probe every source up front so progress covers the whole plan.
+ probed = [(source, _Remote(source.dest.stat().st_size, False) if _existing_dest_ok(source)
+ else self._probe(source.url)) for source in self.sources]
+ overall_total = sum(remote.total for _, remote in probed)
+ completed: dict[str, _Ranges] = {}
done_base = 0
- completed: dict = {}
- for source, total, supported in probed:
- if _existing_dest_ok(source):
- size = source.dest.stat().st_size
+ from pm.download_state import partial_lock
+
+ for source, initial in probed:
+ with partial_lock(self.partials_dir, self._key(source.url), cancelled=self._paused.is_set) as acquired:
+ if not acquired or self._paused.is_set():
+ raise DownloadPaused(source.url)
+ if _existing_dest_ok(source):
+ size = source.dest.stat().st_size
+ else:
+ # Remote data can change while another process owns this URL.
+ remote = self._probe(source.url)
+ overall_total += remote.total - initial.total
+
+ def tick(covered: _Ranges) -> None:
+ if progress is not None:
+ progress(done_base + sum(end - start for start, end in covered),
+ overall_total, {**completed, source.dest.name: covered})
+
+ if remote.total and remote.ranged and (source.sha256 or remote.etag):
+ size = self._fetch_ranged(source, remote, tick)
+ else:
+ size = self._fetch_single(source, remote, tick)
+ overall_total += size - remote.total
completed[source.dest.name] = [(0, size)]
done_base += size
- moved.append(source.dest)
- continue
-
- def tick(written: _Ranges) -> None:
if progress is not None:
- ranges = dict(completed)
- ranges[source.dest.name] = written
- progress(done_base + sum(b - a for a, b in written),
- overall_total, ranges)
-
- if total and supported:
- self._fetch_ranged(source, total, tick)
- else:
- self._fetch_single(source, total, tick)
- done_base += total
- completed[source.dest.name] = [(0, total)]
- moved.append(source.dest)
- return moved
+ progress(done_base, overall_total, dict(completed))
+ return [source.dest for source in self.sources]
# ── internals ─────────────────────────────────────────────
@staticmethod
- def _probe(url: str) -> tuple[int, bool]:
- """(total bytes, range_supported). A server that ignores Range
- reports its Content-Length instead; 0 means unknown (the
- single-stream fallback judges completeness by the body)."""
+ def _probe(url: str) -> _Remote:
req = urllib.request.Request(url, headers={**_UA, "Range": "bytes=0-0"})
try:
- with _OPENER.open(req, timeout=60) as r:
- if r.status == 206:
- content_range = r.headers.get("Content-Range", "")
- if "/" in content_range:
- return int(content_range.rsplit("/", 1)[1]), True
- return 0, False
- length = int(r.headers.get("Content-Length") or 0)
- return length, False
+ with _OPENER.open(req, timeout=60) as response:
+ etag = _strong_etag(response)
+ if response.status == 206:
+ total = _validate_range(response, 0, 1)
+ if len(response.read(2)) != 1:
+ raise _RangeError("range probe returned the wrong byte count")
+ return _Remote(total, True, etag)
+ if response.status != 200:
+ raise DownloadError(f"unexpected download probe status: {response.status}")
+ return _Remote(int(response.headers.get("Content-Length") or 0), False, etag)
except urllib.error.HTTPError as exc:
if exc.code in (401, 403):
- raise DownloadError(
- "the host refused the download (gated or moved). "
- "This is a catalog problem, not yours — please report it."
- ) from exc
+ raise DownloadError("the host refused the download; check source access and URL") from exc
+ raise
+ except DownloadError:
raise
- except Exception: # noqa: BLE001 - unknown length, fall back
- return 0, False
+ except (OSError, ValueError):
+ return _Remote(0, False)
def _key(self, url: str) -> str:
return hashlib.sha256(url.encode("utf-8")).hexdigest()
- def _load_sidecar(self, side: Path) -> _Ranges:
- if not self.resume or not side.is_file():
+ def _load_sidecar(self, side: Path, part: Path, remote: _Remote, sha256: str) -> _Ranges:
+ if not self.resume or not (sha256 or remote.etag):
return []
try:
- return [tuple(r) for r in json.loads(side.read_text(encoding="utf-8"))]
- except (OSError, ValueError):
+ data = json.loads(side.read_text(encoding="utf-8"))
+ if (data["total"], data["etag"], data["sha256"]) != (remote.total, remote.etag, sha256):
+ return []
+ size = part.stat().st_size
+ ranges = data["ranges"]
+ if not isinstance(ranges, list) or any(
+ not isinstance(row, list) or len(row) != 2
+ or any(type(value) is not int for value in row)
+ or not 0 <= row[0] < row[1] <= min(size, remote.total)
+ for row in ranges
+ ):
+ return []
+ return _coalesce([tuple(row) for row in ranges])
+ except (OSError, ValueError, KeyError, TypeError):
return []
@staticmethod
- def _write_sidecar(side: Path, covered: _Ranges) -> None:
- side.parent.mkdir(parents=True, exist_ok=True)
- side.write_text(json.dumps(covered), encoding="utf-8")
-
- def _fetch_ranged(self, source: Source, total: int, tick) -> None:
+ def _write_sidecar(side: Path, part: Path, covered: _Ranges, remote: _Remote, sha256: str) -> None:
+ import os
+ from hermes_cli.runtime_state import _atomic_bytes
+
+ # All writers have closed before coverage is persisted. A sidecar can
+ # describe durable bytes, never data still buffered in a worker.
+ with part.open("r+b") as stream:
+ os.fsync(stream.fileno())
+ record = {"total": remote.total, "etag": remote.etag, "sha256": sha256, "ranges": covered}
+ _atomic_bytes(side, json.dumps(record).encode("utf-8"))
+
+ def _fetch_ranged(self, source: Source, remote: _Remote, tick) -> int:
key = self._key(source.url)
part = self.partials_dir / f"{key}.part"
side = self.partials_dir / f"{key}.ranges"
- covered = self._load_sidecar(side)
- if any(b > total for _, b in covered):
- covered = [] # server now serves a smaller file: stale partial
- # Create the file WITHOUT truncating an existing partial (resume),
- # then size it to total (extends with zeros / shrinks stale tails).
- open(part, "ab").close()
- with open(part, "r+b") as f:
- f.truncate(total)
- if covered:
- ranges = _missing(total, covered)
- else:
- n = max(1, min(self.connections, (total + _CHUNK - 1) // _CHUNK))
- ranges = [(i * total // n, (i + 1) * total // n) for i in range(n)]
- # NOT coalesced: the fresh split is the parallel fan-out, and
- # adjacent chunks must stay separate workers. (_missing already
- # returns disjoint gaps, so resume needs no merge either.)
- ranges = [r for r in ranges if r[1] > r[0]]
-
+ covered = self._load_sidecar(side, part, remote, source.sha256)
+ with part.open("r+b" if covered else "w+b") as stream:
+ stream.truncate(remote.total)
+ gap_count = len(_missing(remote.total, covered)) if covered else (remote.total + _CHUNK - 1) // _CHUNK
+ connections = max(1, min(self.connections, gap_count))
+ attempts = (connections, 1) if connections > 1 else (1,)
+ for connections in attempts:
+ covered, errors = self._ranged_attempt(source, remote, part, covered, connections, tick)
+ protocol_error = next((error for error in errors if isinstance(error, _RangeError)), None)
+ if protocol_error is not None:
+ part.unlink(missing_ok=True)
+ side.unlink(missing_ok=True)
+ raise protocol_error
+ self._write_sidecar(side, part, covered, remote, source.sha256)
+ if self._paused.is_set():
+ raise DownloadPaused(source.url)
+ if errors:
+ if connections == 1:
+ raise errors[0]
+ logging.getLogger(__name__).warning(
+ "parallel range fetch failed for %s; retrying with one connection", source.url,
+ )
+ continue
+ written = sum(end - start for start, end in covered)
+ if written != remote.total:
+ raise DownloadError(f"download incomplete ({written} of {remote.total} bytes)")
+ self._finalize(source, part, side)
+ return written
+ raise DownloadError("ranged download exhausted its retry")
+
+ def _ranged_attempt(self, source: Source, remote: _Remote, part: Path,
+ covered: _Ranges, connections: int, tick) -> tuple[_Ranges, list[Exception]]:
+ from concurrent.futures import ThreadPoolExecutor
+
+ ranges = _missing(remote.total, covered)
+ if not covered:
+ count = max(1, min(connections, (remote.total + _CHUNK - 1) // _CHUNK))
+ ranges = [(index * remote.total // count, (index + 1) * remote.total // count)
+ for index in range(count)]
lock = threading.Lock()
errors: list[Exception] = []
stop = threading.Event()
- written = [sum(b - a for a, b in covered)]
+ covered = list(covered)
def worker(start: int, end: int) -> None:
+ if self._paused.is_set() or stop.is_set():
+ return
try:
- req = urllib.request.Request(
- source.url,
- headers={**_UA, "Range": f"bytes={start}-{end - 1}"})
- with _OPENER.open(req, timeout=120) as r, \
- open(part, "r+b") as f:
- f.seek(start)
- pos = start
- while pos < end:
+ headers = {**_UA, "Range": f"bytes={start}-{end - 1}"}
+ if remote.etag:
+ headers["If-Range"] = remote.etag
+ request = urllib.request.Request(source.url, headers=headers)
+ with _OPENER.open(request, timeout=120) as response, part.open("r+b") as stream:
+ _validate_range(response, start, end, remote.total)
+ if remote.etag and _strong_etag(response) != remote.etag:
+ raise _RangeError("remote representation changed during download")
+ stream.seek(start)
+ position = start
+ while position < end:
if self._paused.is_set() or stop.is_set():
return
- chunk = r.read(min(_CHUNK, end - pos))
+ chunk = response.read(min(_CHUNK, end - position))
if not chunk:
- break
- f.write(chunk)
- pos += len(chunk)
+ raise DownloadError("range body ended before its declared bounds")
+ stream.write(chunk)
+ position += len(chunk)
with lock:
- covered[:] = _coalesce(covered + [(start, pos)])
- written[0] += len(chunk)
- tick(list(covered))
- except Exception as exc: # noqa: BLE001
+ covered[:] = _coalesce(covered + [(start, position)])
+ snapshot = list(covered)
+ tick(snapshot)
+ if response.read(1):
+ raise _RangeError("range body exceeds its declared bounds")
+ except Exception as exc:
with lock:
errors.append(exc)
stop.set()
- threads = [
- threading.Thread(target=worker, args=b, daemon=True,
- name=f"dl-{key[:8]}-{i}")
- for i, b in enumerate(ranges)
- ]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
-
- if self._paused.is_set():
- self._write_sidecar(side, covered)
- raise DownloadPaused(source.url)
- if errors:
- self._write_sidecar(side, covered)
- # Parallel ranged GETs trip edge/CDN rate limits that a single
- # connection does not (observed live: every single-request probe
- # green while the 4-thread fetch 404ed, same runner, same URL).
- # Retry once single-stream; the digest check still proves the
- # bytes. A partial from the failed attempt is kept (covered is
- # persisted above), so the retry only fetches the gaps.
- if self.connections > 1:
- logging.getLogger(__name__).warning(
- "parallel ranged fetch failed for %s (%s); retrying single-stream",
- source.url, errors[0],
- )
- saved = self.connections
- try:
- self.connections = 1
- self._fetch_ranged(source, total, tick)
- finally:
- self.connections = saved
- return
- raise errors[0]
- if written[0] != total:
- self._write_sidecar(side, covered)
- raise DownloadError(
- f"download incomplete ({written[0]} of {total} bytes)")
- self._finalize(source, part, side)
+ with ThreadPoolExecutor(max_workers=connections, thread_name_prefix="hermes-download") as pool:
+ futures = [pool.submit(worker, start, end) for start, end in ranges]
+ for future in futures:
+ future.result()
+ return covered, errors
- def _fetch_single(self, source: Source, total: int, tick) -> None:
- """No-Range fallback: one stream. A server without Range support
- cannot resume, so each run restarts the file."""
+ def _fetch_single(self, source: Source, remote: _Remote, tick) -> int:
+ # A stream with no strong validator cannot safely reuse earlier bytes.
key = self._key(source.url)
part = self.partials_dir / f"{key}.part"
side = self.partials_dir / f"{key}.ranges"
covered: _Ranges = []
- req = urllib.request.Request(source.url, headers=_UA)
+ request = urllib.request.Request(source.url, headers=_UA)
try:
- with _OPENER.open(req, timeout=120) as r, open(part, "wb") as f:
- declared = int(r.headers.get("Content-Length") or 0)
- pos = 0
+ with _OPENER.open(request, timeout=120) as response, part.open("wb") as stream:
+ if response.status != 200:
+ raise DownloadError(f"unexpected download status: {response.status}")
+ if remote.etag and _strong_etag(response) != remote.etag:
+ raise _RangeError("remote representation changed during download")
+ if response.headers.get("Content-Encoding", "identity").lower() != "identity":
+ raise DownloadError("encoded response cannot be used as an identity download")
+ declared = int(response.headers.get("Content-Length") or 0)
+ position = 0
while True:
if self._paused.is_set():
- self._write_sidecar(side, covered)
raise DownloadPaused(source.url)
- chunk = r.read(_CHUNK)
+ chunk = response.read(_CHUNK)
if not chunk:
break
- f.write(chunk)
- pos += len(chunk)
- covered = [(0, pos)]
+ stream.write(chunk)
+ position += len(chunk)
+ covered = [(0, position)]
tick(list(covered))
if self._paused.is_set():
- self._write_sidecar(side, covered)
raise DownloadPaused(source.url)
- if declared and pos != declared:
- raise DownloadError(
- f"download ended at {pos:,} bytes but the server "
- f"said {declared:,} — connection dropped?")
- if total and pos != total:
- raise DownloadError(
- f"download incomplete ({pos} of {total} bytes)")
- except DownloadError:
- self._write_sidecar(side, covered)
- raise
- except Exception:
- self._write_sidecar(side, covered)
+ if (declared and position != declared) or (remote.total and position != remote.total):
+ raise DownloadError(f"download incomplete ({position} bytes, expected {declared or remote.total})")
+ except BaseException:
+ if part.exists():
+ self._write_sidecar(side, part, covered, remote, source.sha256)
raise
+ self._write_sidecar(side, part, covered, remote, source.sha256)
self._finalize(source, part, side)
+ return position
def _finalize(self, source: Source, part: Path, side: Path) -> None:
if source.sha256:
@@ -454,6 +445,21 @@ class Download:
raise HashError(
f"sha256 mismatch for {source.url}: pinned "
f"{source.sha256}, got {actual}")
+ import os
+ import tempfile
+
source.dest.parent.mkdir(parents=True, exist_ok=True)
- shutil.move(str(part), str(source.dest))
+ fd, name = tempfile.mkstemp(prefix=f".{source.dest.name}-", suffix=".download", dir=source.dest.parent)
+ staged = Path(name)
+ try:
+ with os.fdopen(fd, "wb") as target, part.open("rb") as incoming:
+ shutil.copyfileobj(incoming, target, _CHUNK)
+ target.flush()
+ os.fsync(target.fileno())
+ if staged.stat().st_size != part.stat().st_size:
+ raise DownloadError("destination copy did not preserve the complete download")
+ os.replace(staged, source.dest)
+ finally:
+ staged.unlink(missing_ok=True)
+ part.unlink(missing_ok=True)
side.unlink(missing_ok=True)
diff --git a/pm/plugins_state.py b/pm/plugins_state.py
index d65190b8df4..8344d1c7b2d 100644
--- a/pm/plugins_state.py
+++ b/pm/plugins_state.py
@@ -22,25 +22,44 @@ def _profiles_root() -> Path:
def _read_home_config(home: Path) -> Optional[dict[str, Any]]:
- """Parse ONE home's config.yaml, or None when absent/unparseable.
+ """Read a selection once; only an absent file means an unknown home.
- The single parse site: every query about a home (plugins.enabled,
- memory.provider) derives from this one read — config.yaml is parsed
- once per home, not once per question.
+ An unreadable selection must not shrink the next dependency generation.
+ Empty YAML is an explicit empty configuration, as in the CLI loader.
"""
config_path = home / "config.yaml"
- if not config_path.is_file():
+ try:
+ text = config_path.read_text(encoding="utf-8-sig")
+ except FileNotFoundError:
return None
+ except (OSError, UnicodeError) as exc:
+ raise ValueError(f"could not read plugin selection: {config_path}") from exc
+
# Missing YAML support is a broken runtime, not an empty plugin selection.
import utils
+ from yaml import YAMLError
try:
- config = utils.fast_safe_load(config_path.read_text(encoding="utf-8-sig"))
- return config if isinstance(config, dict) else None
- except ImportError:
- raise
- except Exception:
- return None
+ config = utils.fast_safe_load(text)
+ except YAMLError as exc:
+ raise ValueError(f"could not parse plugin selection: {config_path}") from exc
+ if config is None:
+ return {}
+ if not isinstance(config, dict):
+ raise ValueError(f"configuration must be a mapping: {config_path}")
+ for section in ("plugins", "memory"):
+ if config.get(section) is not None and not isinstance(config[section], dict):
+ raise ValueError(f"{section} must be a mapping: {config_path}")
+ plugins = config.get("plugins") or {}
+ for key in ("enabled", "disabled"):
+ names = plugins.get(key)
+ if names is not None and (not isinstance(names, list)
+ or any(not isinstance(name, str) for name in names)):
+ raise ValueError(f"plugins.{key} must be a list of names: {config_path}")
+ provider = (config.get("memory") or {}).get("provider")
+ if provider is not None and not isinstance(provider, str):
+ raise ValueError(f"memory.provider must be a name: {config_path}")
+ return config
def _enabled_from_config(config: dict[str, Any]) -> list[str]:
@@ -61,23 +80,30 @@ def _enabled_from_config(config: dict[str, Any]) -> list[str]:
return out
-def _all_homes() -> list[Path]:
- """The default home + every profile home (the union's scope)."""
- homes: list[Path] = []
+def _is_directory(path: Path) -> bool:
+ import stat
+
try:
- from hermes_cli.runtime_paths import dependency_home_root
+ return stat.S_ISDIR(path.stat().st_mode)
+ except FileNotFoundError:
+ return False
+ except OSError as exc:
+ raise ValueError(f"could not inspect plugin directory: {path}") from exc
+
+
+def _all_homes() -> list[Path]:
+ """Enumerate the complete union or refuse; a partial scan cannot remove members."""
+ from hermes_cli.runtime_paths import dependency_home_root
- homes.append(dependency_home_root())
- except Exception:
- pass
+ homes = [dependency_home_root()]
+ root = _profiles_root()
try:
- root = _profiles_root()
- if root.is_dir():
- for profile in sorted(root.iterdir(), key=str):
- if profile.is_dir():
- homes.append(profile)
- except OSError:
- pass
+ profiles = sorted(root.iterdir(), key=str)
+ except FileNotFoundError:
+ return homes
+ except OSError as exc:
+ raise ValueError(f"could not enumerate profiles: {root}") from exc
+ homes.extend(profile for profile in profiles if _is_directory(profile))
return homes
@@ -109,16 +135,11 @@ def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None)
def _provider_from_config(home: Path, config: dict[str, Any]) -> Optional[str]:
"""The ``memory.provider`` key of an already-parsed config, when its
plugin dir exists (no dir = not a member)."""
- try:
- provider = (config.get("memory") or {}).get("provider")
- if not isinstance(provider, str) or not provider.strip():
- return None
- name = provider.strip()
- if (home / "plugins" / name).is_dir():
- return name
- return None
- except Exception:
+ provider = (config.get("memory") or {}).get("provider")
+ if not provider or not provider.strip():
return None
+ name = provider.strip()
+ return name if _is_directory(home / "plugins" / name) else None
def disable_plugins(names: list[str]) -> dict[str, list[str]]:
@@ -143,13 +164,9 @@ def disable_plugins(names: list[str]) -> dict[str, list[str]]:
for home in _all_homes():
config_path = home / "config.yaml"
- if not config_path.is_file():
- continue
- config = _read_home_config(config_path.parent)
+ config = _read_home_config(home)
if config is None:
- raise ValueError(
- f"could not parse existing config: {config_path}"
- )
+ continue
plugins_cfg = config.get("plugins")
if not isinstance(plugins_cfg, dict):
continue
diff --git a/pm/update.py b/pm/update.py
index f7008193fe5..b2a5a425c68 100644
--- a/pm/update.py
+++ b/pm/update.py
@@ -175,18 +175,33 @@ def _github_headers() -> dict:
return headers
+def _index_headers(url: str) -> dict:
+ from hermes_cli.urllib_security import url_origin
+
+ origin = url_origin(url)
+ if origin == ("https", "api.github.com", 443):
+ return _github_headers()
+ if origin == ("https", "huggingface.co", 443):
+ return {**_UA, **_hf_headers()}
+ return dict(_UA)
+
+
def _get_json(url: str) -> dict | list:
- with urllib.request.urlopen(
- urllib.request.Request(url, headers=_github_headers()), timeout=60
+ from hermes_cli.urllib_security import open_credentialed_url
+
+ with open_credentialed_url(
+ urllib.request.Request(url, headers=_index_headers(url)), timeout=60
) as resp:
return json.load(resp)
def _get_text(url: str, headers: Optional[dict] = None) -> str:
- hdrs = dict(_UA)
+ from hermes_cli.urllib_security import open_credentialed_url
+
+ hdrs = _index_headers(url)
if headers:
hdrs.update(headers)
- with urllib.request.urlopen(
+ with open_credentialed_url(
urllib.request.Request(url, headers=hdrs), timeout=60
) as resp:
return resp.read().decode("utf-8", "replace")
diff --git a/pm/workspace.py b/pm/workspace.py
index 1e824495939..ba4bf561c39 100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@ -199,51 +199,35 @@ def _seed_lock(root: Path, seed_lock: Optional[Path] = None) -> None:
(root / "uv.lock").write_bytes(seed_lock.read_bytes())
-def _plugin_dir_roots() -> set[Path]:
- """All profile plugin dirs + the default home's, machine-wide.
- Profile roots derive from get_default_hermes_root() — the ONE
- authority (custom HERMES_HOME → that root directly; profile-mode
- → its parent), so Docker/custom-root profiles join the union the
- same as standard ones."""
- roots: set[Path] = set()
- try:
- from hermes_constants import get_default_hermes_root
-
- profiles_root = get_default_hermes_root() / "profiles"
- if profiles_root.is_dir():
- for profile in profiles_root.iterdir():
- if profile.is_dir():
- roots.add(profile / "plugins")
- except OSError:
- pass
- try:
- from hermes_constants import get_default_hermes_root
-
- roots.add(get_default_hermes_root() / "plugins")
- except Exception:
- pass
- return roots
-
-
def _is_member_candidate(plugin_dir: Path) -> bool:
"""A plugin dir is a workspace-member candidate when it declares python
deps: a pyproject.toml (modern), or legacy pip_dependencies/
python_dependencies in plugin.yaml (the bridge materializes those)."""
- try:
- if (plugin_dir / "pyproject.toml").is_file():
+ import stat
+
+ for name in ("pyproject.toml", "plugin.yaml"):
+ path = plugin_dir / name
+ try:
+ mode = path.stat().st_mode
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ raise ValueError(f"could not inspect plugin metadata: {path}") from exc
+ if not stat.S_ISREG(mode):
+ continue
+ if name == "pyproject.toml":
return True
- manifest = plugin_dir / "plugin.yaml"
- if manifest.is_file():
- text = manifest.read_text(encoding="utf-8-sig")
- return "pip_dependencies" in text or "python_dependencies" in text
- except OSError:
- return False
+ try:
+ text = path.read_text(encoding="utf-8-sig")
+ except (OSError, UnicodeError) as exc:
+ raise ValueError(f"could not read plugin metadata: {path}") from exc
+ return "pip_dependencies" in text or "python_dependencies" in text
return False
def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:
"""Dependency members from the same effective plugin selection on every path."""
- from pm.plugins_state import enabled_plugins_ordered
+ from pm.plugins_state import _is_directory, enabled_plugins_ordered
selection = enabled_plugins_ordered() if proposed_home is None else enabled_plugins_ordered(
proposed_home=proposed_home, enabled=enabled, disabled=disabled,
@@ -255,9 +239,9 @@ def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> l
if relative.is_absolute() or ".." in relative.parts:
raise InstallError("venv", f"invalid plugin key: {name}")
plugin_dir = plugins_dir / relative
- if not plugin_dir.is_dir():
+ if not _is_directory(plugin_dir):
plugin_dir = paths.repo_root() / "plugins" / relative
- if plugin_dir.is_dir() and _is_member_candidate(plugin_dir):
+ if _is_directory(plugin_dir) and _is_member_candidate(plugin_dir):
members.append(plugin_dir)
return list(dict.fromkeys(members))
diff --git a/pyproject.toml b/pyproject.toml
index 72b66496df8..44a69cc4d4a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -444,6 +444,8 @@ all = [
# Build tooling is not a runtime extra: payloads select --all-extras.
# --only-group supplies Pillow without installing the Hermes application.
icon-build = ["Pillow==12.3.0", "resvg-py==0.4.0"]
+# Native launcher acceptance is required in test environments, not payloads.
+test = ["distlib==0.4.3; sys_platform == 'win32'"]
[build-system]
# setuptools.build_meta + our setup.py bdist_wheel guard import wheel during
diff --git a/scripts/ci/setup_toolchain.py b/scripts/ci/setup_toolchain.py
index 61b02430d7b..bf98fb8652f 100644
--- a/scripts/ci/setup_toolchain.py
+++ b/scripts/ci/setup_toolchain.py
@@ -176,8 +176,17 @@ def dependencies(args) -> None:
environment.pop("UV_NO_CONFIG", None) # keep project indexes and exclude-newer
# PM's frozen sync must not turn a stale project lock into a green job.
subprocess.run([uv_bin, "lock", "--check"], cwd=project, env=environment, check=True, timeout=1800)
- sync_venv(args.extras, explicit=True, plugin_dirs=[])
- venv = selected_venv(project)
+ if "dev" in args.extras:
+ # Test-only groups must not enter PM facts or a shipped generation.
+ venv = args.home.resolve() / "test-environment"
+ environment["UV_PROJECT_ENVIRONMENT"] = str(venv)
+ command = [uv_bin, "sync", "--locked", "--group", "test", "--no-install-project"]
+ for extra in args.extras:
+ command.extend(["--extra", extra])
+ subprocess.run(command, cwd=project, env=environment, check=True, timeout=1800)
+ else:
+ sync_venv(args.extras, explicit=True, plugin_dirs=[])
+ venv = selected_venv(project)
bindir = venv / ("Scripts" if os.name == "nt" else "bin")
python = bindir / ("python.exe" if os.name == "nt" else "python")
python3_alias(python)
diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh
index 92e45a41e70..2e9000e9443 100755
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@ -68,7 +68,7 @@ if [ -z "$VENV_PYTHON" ]; then
VENV_PYTHON="$HERMES_PYTHON"
else
echo "✗ No venv with pytest found. Install dev extras:" >&2
- echo " uv sync --extra dev" >&2
+ echo " uv sync --extra dev --group test" >&2
if [ -n "$SKIPPED_VENVS" ]; then
echo " (skipped for missing pytest:$SKIPPED_VENVS — install dev extras there, or create $REPO_ROOT/.venv)" >&2
fi
diff --git a/tests/agent/test_custom_provider_ca_probes.py b/tests/agent/test_custom_provider_ca_probes.py
index e1ebc40ac80..243308b26ad 100644
--- a/tests/agent/test_custom_provider_ca_probes.py
+++ b/tests/agent/test_custom_provider_ca_probes.py
@@ -4,9 +4,9 @@ Regression coverage for provider-scoped ``ssl_ca_cert`` / ``ssl_verify`` being
ignored by the discovery/pricing probes. Two probe families share the root
cause and are covered here:
-* ``requests``-based endpoint metadata / pricing probe
+* HTTPX endpoint metadata / pricing probe
(``agent.model_metadata.fetch_endpoint_model_metadata`` via
- ``_resolve_requests_verify``).
+ ``resolve_verify``).
* ``urllib``-based ``/models`` catalog discovery probe
(``hermes_cli.models.probe_api_models`` via ``_custom_provider_ssl_context``).
@@ -21,6 +21,7 @@ provider list and a patched request seam.
from __future__ import annotations
+from contextlib import contextmanager
import ssl
import urllib.error
from unittest.mock import MagicMock, patch
@@ -28,7 +29,8 @@ from unittest.mock import MagicMock, patch
import certifi
import pytest
-from agent.model_metadata import _resolve_requests_verify
+from agent.model_metadata_http import resolve_verify
+from agent.ssl_verify import resolve_httpx_verify
from hermes_cli.models import _custom_provider_ssl_context
_CA_ENV_VARS = (
@@ -52,19 +54,14 @@ def clean_env(monkeypatch):
@pytest.fixture
def bundle_file(tmp_path):
path = tmp_path / "provider-ca.pem"
- path.write_text("-----BEGIN CERTIFICATE-----\nstub\n-----END CERTIFICATE-----\n")
+ from pathlib import Path
+ path.write_bytes(Path(certifi.where()).read_bytes())
return str(path)
@pytest.fixture
def real_ca():
- """A real, parseable CA bundle on disk.
-
- ``ssl.create_default_context(cafile=...)`` parses the file eagerly, so the
- urllib context path needs a genuine bundle rather than a stub. The
- ``requests`` path only stores the path string (parsed lazily by requests at
- call time), so it can use the ``bundle_file`` stub.
- """
+ """Both probe transports parse this actual bundle before connecting."""
return certifi.where()
@@ -74,15 +71,15 @@ def _providers(base_url, **tls):
return [entry]
-class TestResolveRequestsVerifyProviderScoped:
- """``_resolve_requests_verify(base_url)`` — the requests probe path."""
+class TestResolveVerifyProviderScoped:
+ """Provider configuration resolves before the probe's transport is built."""
def test_provider_ca_used_for_matching_base_url(self, clean_env, bundle_file):
with patch(
"hermes_cli.config.get_compatible_custom_providers",
return_value=_providers(_BASE, ssl_ca_cert=bundle_file),
):
- assert _resolve_requests_verify(_BASE) == bundle_file
+ assert resolve_verify(_BASE) is resolve_httpx_verify(ca_bundle=bundle_file)
def test_provider_ca_overrides_env_ssl_cert_file(self, clean_env, tmp_path, bundle_file):
env_bundle = tmp_path / "env-ca.pem"
@@ -92,21 +89,21 @@ class TestResolveRequestsVerifyProviderScoped:
"hermes_cli.config.get_compatible_custom_providers",
return_value=_providers(_BASE, ssl_ca_cert=bundle_file),
):
- assert _resolve_requests_verify(_BASE) == bundle_file
+ assert resolve_verify(_BASE) is resolve_httpx_verify(ca_bundle=bundle_file)
def test_provider_ssl_verify_false_disables(self, clean_env):
with patch(
"hermes_cli.config.get_compatible_custom_providers",
return_value=_providers(_BASE, ssl_verify=False),
):
- assert _resolve_requests_verify(_BASE) is False
+ assert resolve_verify(_BASE) is False
def test_no_base_url_does_not_consult_config(self, clean_env, bundle_file):
"""Existing callers pass no base_url — no config read, and env never steers trust."""
clean_env.setenv("HERMES_CA_BUNDLE", bundle_file)
probe = MagicMock(return_value=[])
with patch("hermes_cli.config.get_compatible_custom_providers", probe):
- assert _resolve_requests_verify() is True
+ assert resolve_verify() is True
probe.assert_not_called()
def test_unmatched_base_url_env_ignored_returns_true(self, clean_env, bundle_file):
@@ -116,16 +113,16 @@ class TestResolveRequestsVerifyProviderScoped:
"hermes_cli.config.get_compatible_custom_providers",
return_value=_providers("https://other.example.invalid/v1", ssl_ca_cert="/nope.pem"),
):
- assert _resolve_requests_verify(_BASE) is True
+ assert resolve_verify(_BASE) is True
def test_unmatched_base_url_no_env_returns_true(self, clean_env):
with patch(
"hermes_cli.config.get_compatible_custom_providers",
return_value=[],
):
- assert _resolve_requests_verify(_BASE) is True
+ assert resolve_verify(_BASE) is True
- def test_provider_ca_missing_file_env_ignored_returns_true(self, clean_env):
+ def test_provider_ca_missing_file_keeps_platform_trust(self, clean_env):
"""A configured bundle that does not exist warns and verifies against the OS store —
an ambient ``SSL_CERT_FILE`` does not become the fallback authority."""
clean_env.setenv("SSL_CERT_FILE", "/does/not/matter.pem")
@@ -133,16 +130,20 @@ class TestResolveRequestsVerifyProviderScoped:
"hermes_cli.config.get_compatible_custom_providers",
return_value=_providers(_BASE, ssl_ca_cert="/does/not/exist.pem"),
):
- assert _resolve_requests_verify(_BASE) is True
+ context = resolve_verify(_BASE)
+ assert type(context).__module__.startswith("truststore")
+ assert context.verify_mode == ssl.CERT_REQUIRED
- def test_config_lookup_failure_env_ignored_returns_true(self, clean_env):
+ def test_config_lookup_failure_keeps_platform_trust(self, clean_env):
"""A config crash must not silently swap in an ambient env var as trust authority."""
clean_env.setenv("SSL_CERT_FILE", "/does/not/matter.pem")
with patch(
"hermes_cli.config.get_compatible_custom_providers",
side_effect=RuntimeError("config boom"),
):
- assert _resolve_requests_verify(_BASE) is True
+ context = resolve_verify(_BASE)
+ assert type(context).__module__.startswith("truststore")
+ assert context.verify_mode == ssl.CERT_REQUIRED
class TestCustomProviderSSLContext:
@@ -154,7 +155,7 @@ class TestCustomProviderSSLContext:
return_value=_providers(_BASE, ssl_ca_cert=real_ca),
):
ctx = _custom_provider_ssl_context(_BASE)
- assert isinstance(ctx, ssl.SSLContext)
+ assert ctx is resolve_httpx_verify(ca_bundle=real_ca)
assert ctx.verify_mode == ssl.CERT_REQUIRED
def test_ssl_verify_false_returns_unverified_context(self):
@@ -193,51 +194,25 @@ class TestCustomProviderSSLContext:
class TestMetadataProbeThreadsProviderCA:
- """End-to-end: the requests metadata probe carries the provider CA to the wire."""
-
- def test_fetch_endpoint_model_metadata_uses_provider_ca(self, clean_env, bundle_file):
- import agent.model_metadata as mm
-
- captured = {}
-
- def fake_get(url, headers=None, timeout=None, verify=None, **kwargs):
- captured["verify"] = verify
- resp = MagicMock()
- resp.raise_for_status.return_value = None
- resp.json.return_value = {"data": []}
- return resp
-
- mm._endpoint_model_metadata_cache.clear()
- mm._endpoint_model_metadata_cache_time.clear()
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert=bundle_file),
- ), patch.object(mm.requests, "get", side_effect=fake_get):
- mm.fetch_endpoint_model_metadata(_BASE, force_refresh=True)
-
- assert captured["verify"] == bundle_file
-
- def test_public_endpoint_keeps_env_default(self, clean_env):
- import agent.model_metadata as mm
-
- captured = {}
+ @pytest.mark.parametrize("pinned", [False, True])
+ def test_provider_policy_reaches_the_transport(self, clean_env, real_ca, pinned):
+ import httpx
+ from agent import model_metadata as mm
+ from agent import model_metadata_http
+ from agent.ssl_verify import resolve_httpx_verify
- def fake_get(url, headers=None, timeout=None, verify=None, **kwargs):
- captured["verify"] = verify
- resp = MagicMock()
- resp.raise_for_status.return_value = None
- resp.json.return_value = {"data": []}
- return resp
+ @contextmanager
+ def response(*args, **kwargs):
+ yield httpx.Response(200, json={"data": []}, request=httpx.Request("GET", args[0]))
mm._endpoint_model_metadata_cache.clear()
mm._endpoint_model_metadata_cache_time.clear()
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=[],
- ), patch.object(mm.requests, "get", side_effect=fake_get):
- mm.fetch_endpoint_model_metadata(_BASE, force_refresh=True)
-
- assert captured["verify"] is True
+ providers = _providers(_BASE, ssl_ca_cert=real_ca) if pinned else []
+ with patch("hermes_cli.config.get_compatible_custom_providers", return_value=providers), \
+ patch.object(model_metadata_http, "stream", side_effect=response) as stream:
+ assert mm.fetch_endpoint_model_metadata(_BASE, force_refresh=True) == {}
+ expected = resolve_httpx_verify(ca_bundle=real_ca) if pinned else True
+ assert stream.call_args.kwargs["verify"] is expected
class TestCatalogProbeThreadsSSLContext:
@@ -258,7 +233,7 @@ class TestCatalogProbeThreadsSSLContext:
), patch.object(models, "open_credentialed_url", side_effect=fake_open):
models.probe_api_models(None, _BASE, timeout=1)
- assert isinstance(captured["ssl_context"], ssl.SSLContext)
+ assert captured["ssl_context"] is resolve_httpx_verify(ca_bundle=real_ca)
assert captured["ssl_context"].verify_mode == ssl.CERT_REQUIRED
def test_probe_api_models_public_endpoint_uses_default_policy(self, clean_env):
diff --git a/tests/agent/test_endpoint_blackhole.py b/tests/agent/test_endpoint_blackhole.py
index b3bdc93a08a..fb7d64b5151 100644
--- a/tests/agent/test_endpoint_blackhole.py
+++ b/tests/agent/test_endpoint_blackhole.py
@@ -21,7 +21,6 @@ from unittest.mock import MagicMock, patch
import httpx
import pytest
-import requests
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
@@ -160,8 +159,8 @@ class TestFetchEndpointModelMetadataBlackhole:
with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
patch(
- "agent.model_metadata.requests.get",
- side_effect=requests.exceptions.ConnectTimeout("timed out"),
+ "agent.model_metadata_http.stream",
+ side_effect=httpx.ConnectTimeout("timed out"),
) as get:
assert fetch_endpoint_model_metadata(self.URL) == {}
@@ -173,8 +172,8 @@ class TestFetchEndpointModelMetadataBlackhole:
with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
patch(
- "agent.model_metadata.requests.get",
- side_effect=requests.exceptions.ConnectionError("refused"),
+ "agent.model_metadata_http.stream",
+ side_effect=httpx.ConnectError("refused"),
) as get:
assert fetch_endpoint_model_metadata(self.URL) == {}
@@ -187,7 +186,7 @@ class TestFetchEndpointModelMetadataBlackhole:
_note_endpoint_blackholed(self.URL)
with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
- patch("agent.model_metadata.requests.get") as get:
+ patch("agent.model_metadata_http.stream") as get:
assert fetch_endpoint_model_metadata(self.URL, force_refresh=True) == {}
get.assert_not_called()
@@ -276,13 +275,6 @@ class TestIsConnectTimeout:
assert _is_connect_timeout(httpx.ConnectTimeout("x")) is True
- def test_requests_connect_timeout(self):
- from requests.exceptions import ConnectTimeout
-
- from agent.model_metadata import _is_connect_timeout
-
- assert _is_connect_timeout(ConnectTimeout("x")) is True
-
def test_unrelated_errors_are_not_connect_timeouts(self):
from agent.model_metadata import _is_connect_timeout
diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py
index 3f8aaf5a838..d40c973575b 100644
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@ -11,6 +11,7 @@ Coverage levels:
"""
import time
+from contextlib import contextmanager
import pytest
import yaml
@@ -425,7 +426,7 @@ class TestCodexOAuthContextLength:
}
with patch(
- "agent.model_metadata.requests.get",
+ "agent.model_metadata_http.get",
side_effect=[first_response, second_response],
) as mock_get, patch("agent.model_metadata.save_context_length") as mock_save:
first = get_model_context_length(
@@ -466,7 +467,7 @@ class TestCodexOAuthContextLength:
fake_response.status_code = 401
fake_response.json.return_value = {}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -509,7 +510,7 @@ class TestCodexOAuthContextLength:
# Exercise real persistence here: this test verifies that a live value
# replaces the stale on-disk entry. Failure-path tests below mock the
# writer because they assert that fallback values are not persisted.
- with patch("agent.model_metadata.requests.get", return_value=fake_response) as mock_get:
+ with patch("agent.model_metadata_http.get", return_value=fake_response) as mock_get:
ctx = mm.get_model_context_length(
model="gpt-5.5",
base_url=base_url,
@@ -548,7 +549,7 @@ class TestCodexOAuthContextLength:
fake_response.json.return_value = {
"models": [{"slug": slug, "context_window": 272_000}]
}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -581,7 +582,7 @@ class TestCodexOAuthContextLength:
}
import agent.model_metadata as mm
mm._codex_oauth_context_cache = {}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -606,7 +607,7 @@ class TestCodexOAuthContextLength:
}
import agent.model_metadata as mm
mm._codex_oauth_context_cache = {}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -629,7 +630,7 @@ class TestCodexOAuthContextLength:
fake_response.json.return_value = {
"models": [{"slug": slug, "context_window": 272_000}]
}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -650,7 +651,7 @@ class TestCodexOAuthContextLength:
fake_response = MagicMock()
fake_response.status_code = 401
fake_response.json.return_value = {}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -670,7 +671,7 @@ class TestCodexOAuthContextLength:
fake_response = MagicMock()
fake_response.status_code = 401
fake_response.json.return_value = {}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -728,7 +729,7 @@ class TestCodexOAuthContextLength:
}
import agent.model_metadata as mm
mm._codex_oauth_context_cache = {}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -747,6 +748,20 @@ class TestCodexOAuthContextLength:
# =========================================================================
class TestFetchEndpointModelMetadata:
+ @pytest.fixture(autouse=True)
+ def streamed_responses(self, monkeypatch):
+ from agent import model_metadata_http
+
+ @contextmanager
+ def stream(*args, **kwargs):
+ response = model_metadata_http.get(*args, **kwargs)
+ try:
+ yield response
+ finally:
+ response.close()
+
+ monkeypatch.setattr(model_metadata_http, "stream", stream)
+
def setup_method(self):
import agent.model_metadata as mm
mm._endpoint_model_metadata_cache.clear()
@@ -760,12 +775,12 @@ class TestFetchEndpointModelMetadata:
response.status_code = status_code
response.raise_for_status.side_effect = RuntimeError(str(status_code))
- with patch("agent.model_metadata.requests.get", return_value=response) as mock_get:
+ with patch("agent.model_metadata_http.get", return_value=response) as mock_get:
result = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
assert result == {}
mock_get.assert_called_once()
- assert mock_get.call_args.kwargs["stream"] is True
+ response.read.assert_not_called()
response.raise_for_status.assert_not_called()
response.json.assert_not_called()
response.close.assert_called_once()
@@ -777,7 +792,7 @@ class TestFetchEndpointModelMetadata:
response.status_code = 401
response.raise_for_status.side_effect = RuntimeError("401")
- with patch("agent.model_metadata.requests.get", return_value=response) as mock_get:
+ with patch("agent.model_metadata_http.get", return_value=response) as mock_get:
first = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
second = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
@@ -798,7 +813,7 @@ class TestFetchEndpointModelMetadata:
}
with patch(
- "agent.model_metadata.requests.get",
+ "agent.model_metadata_http.get",
side_effect=[not_found, success],
) as mock_get:
result = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
@@ -809,7 +824,8 @@ class TestFetchEndpointModelMetadata:
"https://custom.example/v1/models",
"https://custom.example/models",
]
- assert all(call.kwargs["stream"] is True for call in mock_get.call_args_list)
+ not_found.read.assert_not_called()
+ success.read.assert_called_once()
not_found.json.assert_not_called()
not_found.close.assert_called_once()
success.close.assert_called_once()
@@ -827,7 +843,7 @@ class TestFetchEndpointModelMetadata:
success.status_code = 200
success.json.return_value = {"data": [{"id": "test/model", "context_length": 32768}]}
- with patch("agent.model_metadata.requests.get", return_value=success) as mock_get:
+ with patch("agent.model_metadata_http.get", return_value=success) as mock_get:
assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768
# "New process": drop the in-memory cache only.
mm._endpoint_model_metadata_cache.clear()
@@ -839,7 +855,7 @@ class TestFetchEndpointModelMetadata:
mm._endpoint_model_metadata_cache.clear()
mm._endpoint_model_metadata_cache_time.clear()
with patch("agent.model_metadata.time.time", return_value=time.time() + mm._ENDPOINT_MODEL_CACHE_TTL + 1), patch(
- "agent.model_metadata.requests.get", return_value=success
+ "agent.model_metadata_http.get", return_value=success
) as mock_get:
mm.fetch_endpoint_model_metadata("https://custom.example/v1")
mock_get.assert_called_once()
@@ -1333,7 +1349,7 @@ class TestFetchModelMetadata:
}
mock_response.raise_for_status = MagicMock()
- with patch("agent.model_metadata.requests.get", return_value=mock_response):
+ with patch("agent.model_metadata_http.get", return_value=mock_response):
fetch_model_metadata(force_refresh=True)
assert cache_path.exists()
@@ -1350,12 +1366,12 @@ class TestFetchModelMetadata:
import os
os.utime(cache_path, (old, old))
- with patch("agent.model_metadata.requests.get", side_effect=Exception("Network error")):
+ with patch("agent.model_metadata_http.get", side_effect=Exception("Network error")):
result = fetch_model_metadata(force_refresh=True)
assert result["stale/model"]["context_length"] == 50000
- @patch("agent.model_metadata.requests.get")
+ @patch("agent.model_metadata_http.get")
def test_caches_result(self, mock_get):
self._reset_cache()
mock_response = MagicMock()
@@ -1375,7 +1391,7 @@ class TestFetchModelMetadata:
- @patch("agent.model_metadata.requests.get")
+ @patch("agent.model_metadata_http.get")
def test_canonical_slug_aliasing(self, mock_get):
"""Models with canonical_slug get indexed under both IDs."""
self._reset_cache()
diff --git a/tests/agent/test_model_metadata_http.py b/tests/agent/test_model_metadata_http.py
new file mode 100644
index 00000000000..e81b08b9caa
--- /dev/null
+++ b/tests/agent/test_model_metadata_http.py
@@ -0,0 +1,104 @@
+"""Exercise probe transport redirects, proxies, and early response closure."""
+from __future__ import annotations
+
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from threading import Thread
+
+import pytest
+
+from agent import model_metadata, model_metadata_http
+
+
+def servers():
+ active = []
+
+ def start(handler):
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ server.daemon_threads = True
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ active.append((server, thread))
+ return f"http://127.0.0.1:{server.server_port}"
+
+ yield start
+ for server, thread in reversed(active):
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+def test_redirect_credentials_and_proxy_routing_are_preserved(servers, monkeypatch):
+ seen = []
+ sink_url = ""
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ seen.append((self.path, dict(self.headers)))
+ if self.path == "/redirect":
+ self.send_response(302)
+ self.send_header("Location", sink_url + "/models")
+ self.end_headers()
+ return
+ body = b'{"data":[]}'
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ source_url = servers(Handler)
+ sink_url = servers(Handler)
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")
+ headers = {"Authorization": "Bearer dummy", "X-Custom-Auth": "dummy", "Accept": "application/json"}
+ assert model_metadata_http.get(source_url + "/redirect", headers=headers).status_code == 200
+ assert seen[0][1]["Authorization"] == "Bearer dummy"
+ redirected = {key.lower(): value for key, value in seen[-1][1].items()}
+ assert "authorization" not in redirected and "x-custom-auth" not in redirected
+ assert redirected["accept"] == "application/json"
+
+ # A real HTTP proxy responds to an absolute URI; the .invalid destination
+ # cannot answer without the configured proxy. No external network is used.
+ monkeypatch.setenv("HTTP_PROXY", source_url)
+ monkeypatch.setenv("NO_PROXY", "")
+ assert model_metadata_http.get("http://probe.invalid/models").status_code == 200
+ assert seen[-1][0] == "http://probe.invalid/models"
+
+
[email protected]("status", [401, 403])
+def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch, status):
+ requests = []
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_GET(self):
+ requests.append(self.path)
+ self.send_response(status)
+ self.send_header("Content-Length", "1000000")
+ self.end_headers()
+ # Intentionally send no body. The client must close on the headers,
+ # not wait for a read timeout or try the alternate /v1 URL.
+
+ def log_message(self, *args):
+ pass
+
+ url = servers(Handler)
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")
+ monkeypatch.setattr(model_metadata, "detect_local_server_type", lambda *args, **kwargs: None)
+ import httpx
+
+ responses = []
+ original_client = httpx.Client
+
+ def recorded_client(**kwargs):
+ kwargs["event_hooks"]["response"] = [responses.append]
+ return original_client(**{**kwargs, "timeout": 2.0})
+
+ monkeypatch.setattr(httpx, "Client", recorded_client)
+ assert model_metadata.fetch_endpoint_model_metadata(url, force_refresh=True) == {}
+ assert requests == ["/models"]
+ assert len(responses) == 1 and responses[0].is_closed
+ assert not responses[0].is_stream_consumed, "auth rejection read the absent body"
diff --git a/tests/agent/test_model_metadata_local_ctx.py b/tests/agent/test_model_metadata_local_ctx.py
index 1472efa55af..d591b10299b 100644
--- a/tests/agent/test_model_metadata_local_ctx.py
+++ b/tests/agent/test_model_metadata_local_ctx.py
@@ -675,7 +675,7 @@ class TestFetchEndpointModelMetadataLmStudio:
)
with patch("agent.model_metadata.detect_local_server_type", return_value="lm-studio"), \
- patch("agent.model_metadata.requests.get", return_value=native_resp) as mock_get:
+ patch("agent.model_metadata_http.get", return_value=native_resp) as mock_get:
result = fetch_endpoint_model_metadata(
"http://localhost:1234/v1",
api_key="lm-token",
@@ -708,7 +708,7 @@ class TestFetchEndpointModelMetadataLmStudio:
)
with patch("agent.model_metadata.detect_local_server_type", return_value="lm-studio"), \
- patch("agent.model_metadata.requests.get", return_value=native_resp) as mock_get:
+ patch("agent.model_metadata_http.get", return_value=native_resp) as mock_get:
result = fetch_endpoint_model_metadata(
"http://localhost:1234/api/v1",
force_refresh=True,
diff --git a/tests/agent/test_model_metadata_ssl.py b/tests/agent/test_model_metadata_ssl.py
index 8624cfde4ea..5639a569649 100644
--- a/tests/agent/test_model_metadata_ssl.py
+++ b/tests/agent/test_model_metadata_ssl.py
@@ -1,60 +1,19 @@
-"""Tests for _resolve_requests_verify() trust-source contract.
-
-The requests-based ``/models`` probes resolve TLS from per-provider config only
-(``ssl_verify: false``, then ``ssl_ca_cert``); otherwise the OS trust store via
-the process-wide ``truststore`` install. Ambient CA env vars
-(HERMES_CA_BUNDLE, REQUESTS_CA_BUNDLE, SSL_CERT_FILE) were removed as a trust
-authority — these tests assert they no longer steer verification, and that
-missing files / config failures degrade to plain "verify against the OS store".
-
-No network I/O: CA env vars point at tmp_path stand-in files only; the OS
-trust store is never written.
-"""
-
+"""Metadata discovery uses chat's resolved TLS policy without ambient CA files."""
from __future__ import annotations
-from pathlib import Path
+import ssl
+import httpx
import pytest
-from agent.model_metadata import _resolve_requests_verify
-
-
-_CA_ENV_VARS = ("HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE")
-
-
-def clean_env(monkeypatch):
- """Clear all three SSL env vars so each test starts from a known state."""
- for var in _CA_ENV_VARS:
- monkeypatch.delenv(var, raising=False)
- return monkeypatch
-
-
-def bundle_file(tmp_path: Path) -> str:
- """Create a placeholder CA bundle file and return its absolute path."""
- path = tmp_path / "ca.pem"
- path.write_text("-----BEGIN CERTIFICATE-----\nstub\n-----END CERTIFICATE-----\n")
- return str(path)
-
-
-class TestResolveRequestsVerify:
- def test_no_env_returns_true(self, clean_env):
- assert _resolve_requests_verify() is True
+from agent.model_metadata_http import resolve_verify
- def test_env_vars_do_not_steer_trust(self, clean_env, tmp_path, bundle_file):
- """Every legacy CA env var is ignored: trust comes from the OS store, not ambient env."""
- other = tmp_path / "other.pem"
- other.write_text("stub")
- clean_env.setenv("HERMES_CA_BUNDLE", bundle_file)
- clean_env.setenv("REQUESTS_CA_BUNDLE", str(other))
- clean_env.setenv("SSL_CERT_FILE", str(other))
- assert _resolve_requests_verify() is True
- def test_stale_env_var_path_returns_true_not_the_path(self, clean_env, bundle_file):
- """HERMES_CA_BUNDLE pointing at a real file still resolves to plain ``True`` —
- the path must never leak into ``verify=`` as the trust source."""
- clean_env.setenv("HERMES_CA_BUNDLE", bundle_file)
- assert _resolve_requests_verify() is not bundle_file
- assert _resolve_requests_verify() is True
[email protected]("variable", ["HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR"])
+def test_ambient_ca_paths_do_not_break_metadata_clients(monkeypatch, tmp_path, variable):
+ monkeypatch.setenv(variable, str(tmp_path / "missing-ca"))
+ verify = resolve_verify()
+ with httpx.Client(verify=verify) as client:
+ context = client._transport._pool._ssl_context
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname
diff --git a/tests/agent/test_probe_cache_followups.py b/tests/agent/test_probe_cache_followups.py
index 32ac7ceee18..f108c0de4c8 100644
--- a/tests/agent/test_probe_cache_followups.py
+++ b/tests/agent/test_probe_cache_followups.py
@@ -7,6 +7,7 @@ Covers:
from __future__ import annotations
+from contextlib import contextmanager
from unittest.mock import MagicMock, patch
import pytest
@@ -164,6 +165,20 @@ class TestLocalhostIPv4SiblingSites:
"""#37595 widened: every probe helper rewrites localhost→127.0.0.1,
not just detect_local_server_type."""
+ @pytest.fixture(autouse=True)
+ def streamed_responses(self, monkeypatch):
+ from agent import model_metadata_http
+
+ @contextmanager
+ def stream(*args, **kwargs):
+ response = model_metadata_http.get(*args, **kwargs)
+ try:
+ yield response
+ finally:
+ response.close()
+
+ monkeypatch.setattr(model_metadata_http, "stream", stream)
+
def test_rewrite_is_host_only_not_substring(self):
"""A URL that merely EMBEDS 'http://localhost' in its path/query must
@@ -201,7 +216,7 @@ class TestLocalhostIPv4SiblingSites:
resp.json.return_value = {"data": []}
with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
- patch("agent.model_metadata.requests.get", return_value=resp) as mock_get:
+ patch("agent.model_metadata_http.get", return_value=resp) as mock_get:
fetch_endpoint_model_metadata("http://localhost:8000/v1")
assert mock_get.call_args[0][0].startswith("http://127.0.0.1:8000")
@@ -223,7 +238,7 @@ class TestLocalhostIPv4SiblingSites:
}
props_resp = MagicMock()
- props_resp.ok = True
+ props_resp.is_error = False
props_resp.json.return_value = {
"default_generation_settings": {"n_ctx": 32768},
"model_alias": "llama-3-8b",
@@ -231,7 +246,7 @@ class TestLocalhostIPv4SiblingSites:
with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
patch(
- "agent.model_metadata.requests.get",
+ "agent.model_metadata_http.get",
side_effect=[models_resp, props_resp],
) as mock_get:
result = fetch_endpoint_model_metadata("http://localhost:8000/v1")
diff --git a/tests/agent/test_ssl_transport_contracts.py b/tests/agent/test_ssl_transport_contracts.py
new file mode 100644
index 00000000000..3a36b1fac93
--- /dev/null
+++ b/tests/agent/test_ssl_transport_contracts.py
@@ -0,0 +1,130 @@
+"""TLS assertions reach real client transports, never the host certificate store."""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from ipaddress import ip_address
+import ssl
+from threading import Thread
+
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.x509.oid import NameOID
+import httpx
+import pytest
+from truststore._ssl_constants import _original_SSLContext
+
+from agent import model_metadata, process_bootstrap, ssl_verify
+
+
+def local_tls(tmp_path, monkeypatch):
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "test loopback")])
+ now = datetime.now(timezone.utc)
+ cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
+ .public_key(key.public_key()).serial_number(x509.random_serial_number())
+ .not_valid_before(now - timedelta(days=1)).not_valid_after(now + timedelta(days=1))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
+ .add_extension(x509.SubjectAlternativeName([x509.IPAddress(ip_address("127.0.0.1"))]), critical=False)
+ .sign(key, hashes.SHA256()))
+ bundle = tmp_path / "loopback.pem"
+ bundle.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
+ private_key = tmp_path / "loopback.key"
+ private_key.write_bytes(key.private_bytes(serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption()))
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_GET(self):
+ body = b'{"data":[{"id":"test-model","context_length":2048}]}'
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ context = _original_SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(bundle, private_key)
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.daemon_threads = True
+ server.socket = context.wrap_socket(server.socket, server_side=True)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")
+ process_bootstrap.close_shared_transports()
+ try:
+ yield f"https://127.0.0.1:{server.server_port}", bundle
+ finally:
+ process_bootstrap.close_shared_transports()
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
[email protected]("probe", ["metadata", "catalog"])
+def test_provider_ca_reaches_the_real_probe_transport(local_tls, monkeypatch, probe):
+ import certifi
+ from hermes_cli import models
+
+ url, bundle = local_tls
+ monkeypatch.setattr(model_metadata, "detect_local_server_type", lambda *args, **kwargs: None)
+ settings = {"ssl_ca_cert": certifi.where()}
+ monkeypatch.setattr("hermes_cli.config.get_custom_provider_tls_settings", lambda base_url: dict(settings))
+
+ def discover():
+ if probe == "metadata":
+ return list(model_metadata.fetch_endpoint_model_metadata(url, force_refresh=True))
+ return models.probe_api_models(None, url)["models"]
+
+ assert discover() == ([] if probe == "metadata" else None)
+ settings["ssl_ca_cert"] = str(bundle)
+ assert discover() == ["test-model"]
+
+ # Model probing must use the same resolver as chat, not a path whose TLS
+ # semantics change after truststore's process-wide injection.
+ seen = []
+ original = ssl_verify.resolve_httpx_verify
+
+ def record(**kwargs):
+ context = original(**kwargs)
+ seen.append(context)
+ return context
+
+ monkeypatch.setattr(ssl_verify, "resolve_httpx_verify", record)
+ assert discover() == ["test-model"]
+ assert seen and seen[-1] is original(ca_bundle=str(bundle))
+
+
[email protected]("variable", ["SSL_CERT_FILE", "SSL_CERT_DIR"])
+def test_ambient_ca_cannot_break_the_shared_client(variable, tmp_path, monkeypatch):
+ monkeypatch.setenv(variable, str(tmp_path / "missing-ca"))
+ verify = ssl_verify.resolve_httpx_verify()
+ with httpx.Client(verify=verify) as client:
+ assert not client.is_closed
+ client = process_bootstrap.build_keepalive_http_client("https://example.invalid", verify=verify)
+ assert client is not None
+ client.close()
+
+
+def test_pinned_clients_share_transport_not_close_state(local_tls):
+ url, bundle = local_tls
+ first = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle))
+ second = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle))
+ assert first is second
+ a = process_bootstrap.build_keepalive_http_client(url, verify=first)
+ b = process_bootstrap.build_keepalive_http_client(url, verify=second)
+ assert a is not None and b is not None
+ try:
+ assert a._transport._inner is b._transport._inner
+ assert a.get(url, timeout=5).status_code == 200
+ a.close()
+ assert b.get(url, timeout=5).status_code == 200
+ finally:
+ a.close()
+ b.close()
diff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.py
index ee6f81a936e..a6b1ce4e6cc 100644
--- a/tests/agent/test_ssl_verify.py
+++ b/tests/agent/test_ssl_verify.py
@@ -12,7 +12,6 @@ from agent import ssl_verify
from agent.ssl_verify import (
install_truststore,
resolve_httpx_verify,
- resolve_requests_verify,
)
@@ -39,7 +38,6 @@ def test_default_verify_defers_to_the_platform_store():
# True means "verify normally", which after the install means the OS
# store. No CA bundle path is threaded through.
assert resolve_httpx_verify() is True
- assert resolve_requests_verify() is True
def test_env_ca_bundle_vars_no_longer_steer_trust(monkeypatch, tmp_path):
@@ -52,13 +50,17 @@ def test_env_ca_bundle_vars_no_longer_steer_trust(monkeypatch, tmp_path):
"""
import certifi
- for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
- monkeypatch.setenv(var, certifi.where())
- assert resolve_httpx_verify() is True
+ import httpx
- for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
- monkeypatch.setenv(var, str(tmp_path / "does-not-exist.pem"))
- assert resolve_httpx_verify() is True
+ for path in (certifi.where(), str(tmp_path / "does-not-exist.pem")):
+ for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
+ monkeypatch.setenv(var, path)
+ verify = resolve_httpx_verify()
+ with httpx.Client(verify=verify) as client:
+ context = client._transport._pool._ssl_context
+ assert type(context).__module__.startswith("truststore")
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname
def test_explicit_ca_bundle_replaces_the_platform_store():
@@ -88,24 +90,16 @@ def test_explicit_ca_bundle_replaces_the_platform_store():
assert len(ctx.get_ca_certs()) > 0
-def test_requests_explicit_ca_bundle_is_returned_as_a_path():
- import certifi
-
- assert resolve_requests_verify(ca_bundle=certifi.where()) == certifi.where()
-
-
def test_missing_explicit_bundle_falls_back_to_the_platform_store(tmp_path, caplog):
missing = str(tmp_path / "nope.pem")
assert resolve_httpx_verify(ca_bundle=missing) is True
- assert resolve_requests_verify(ca_bundle=missing) is True
assert "does not exist" in caplog.text
@pytest.mark.parametrize("value", [False, "false", "0", "no", "off", "FALSE"])
def test_insecure_disables_verification(value):
assert resolve_httpx_verify(ssl_verify=value) is False
- assert resolve_requests_verify(ssl_verify=value) is False
def test_insecure_beats_an_explicit_bundle():
diff --git a/tests/conftest.py b/tests/conftest.py
index f6fa9383060..e1471f456e8 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1225,6 +1225,9 @@ def pytest_configure(config): # noqa: D401 — pytest hook
"(only for tests that genuinely need real os.kill / subprocess "
"behaviour — e.g. PTY tests that signal their own child).",
)
+ config.addinivalue_line(
+ "markers", "allow_real_home_io: explicitly bypass the test-only home I/O guard."
+ )
config.addinivalue_line(
"markers",
f"{_REQUIRES_WAL_MARK}: test needs the runtime to actually enable "
@@ -1908,102 +1911,15 @@ def _capture_real_hermes_root() -> list[Path]:
_REAL_HERMES_ROOT_CANDIDATES = _capture_real_hermes_root()
-def _path_hits_real_home(candidate) -> bool:
- """True when candidate resolves under any guarded real root."""
- try:
- resolved = Path(candidate).expanduser().resolve()
- except Exception:
- return False
- for root in _REAL_HERMES_ROOT_CANDIDATES:
- try:
- resolved.relative_to(root)
- return True
- except ValueError:
- continue
- return False
-
-
@pytest.fixture(autouse=True)
def _forbid_real_hermes_home_io(monkeypatch, request):
- """Fail ANY test that opens/mkdirs/stats under the REAL hermes home.
+ """Guard Python file/metadata/deletion calls and SQLite against real state.
- Opt-out for the (rare) test that legitimately inspects the guard
- itself or documents a real-path read: @pytest.mark.allow_real_home_io.
- Everything else gets the tripwire.
-
- Implementation: wrap builtins.open (covers ~all file I/O incl. pathlib
- read_text/write_text which call io.open) plus os.mkdir/os.makedirs for
- directory creation. Guard the check itself with try/except so a weird
- path never breaks the wrapper.
+ Native libraries and subprocesses still need their own temporary-home
+ contracts. The opt-out is for explicit guard tests, never implicit repair.
"""
if request.node.get_closest_marker("allow_real_home_io"):
return
+ from tests.home_io_guard import HomeIOGuard
- import builtins as _builtins
-
- real_open = _builtins.open
-
- def _guarded_open(file, *args, **kwargs):
- try:
- if _path_hits_real_home(file):
- raise AssertionError(
- f"TEST BUG: file I/O against the REAL hermes home: "
- f"{file}\n"
- "The hermetic sandbox redirects get_hermes_home(); this "
- "path bypasses it (hardcoded Path.home()/.hermes, a "
- "frozen import-time path, or an explicit real path). "
- "Use get_hermes_home()/the isolated fixture instead."
- )
- except AssertionError:
- raise
- except Exception:
- pass
- return real_open(file, *args, **kwargs)
-
- monkeypatch.setattr(_builtins, "open", _guarded_open)
-
- real_mkdir = os.mkdir
- real_makedirs = os.makedirs
-
- def _guarded_mkdir(path, *args, **kwargs):
- if _path_hits_real_home(path):
- pytest.fail(
- f"TEST BUG: mkdir against the REAL hermes home: {path}",
- pytrace=False,
- )
- return real_mkdir(path, *args, **kwargs)
-
- def _guarded_makedirs(path, *args, **kwargs):
- if _path_hits_real_home(path):
- pytest.fail(
- f"TEST BUG: makedirs against the REAL hermes home: {path}",
- pytrace=False,
- )
- return real_makedirs(path, *args, **kwargs)
-
- monkeypatch.setattr(os, "mkdir", _guarded_mkdir)
- monkeypatch.setattr(os, "makedirs", _guarded_makedirs)
-
-
[email protected](autouse=True)
-def _forbid_real_hermes_home_sqlite(monkeypatch, request):
- """sqlite3.connect bypasses builtins.open (C-level open) — guard it
- directly: a DB path resolving under the REAL hermes home fails the
- test (the state.db-under-~/.hermes leak the session sandbox docs the
- history of). Same opt-out marker as the file guard."""
- if request.node.get_closest_marker("allow_real_home_io"):
- return
-
- import sqlite3 as _sqlite3
-
- real_connect = _sqlite3.connect
-
- def _guarded_connect(database, *args, **kwargs):
- if isinstance(database, (str, bytes, Path)) and _path_hits_real_home(database):
- pytest.fail(
- f"TEST BUG: sqlite connect against the REAL hermes home: {database}",
- pytrace=False,
- )
- return real_connect(database, *args, **kwargs)
-
- monkeypatch.setattr(_sqlite3, "connect", _guarded_connect)
+ HomeIOGuard(lambda: _REAL_HERMES_ROOT_CANDIDATES).install(monkeypatch)
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index c6a9ab0bf32..bfd1948b919 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -376,8 +376,9 @@ class TestGetProcessStartTime:
def test_live_process_is_stable_int(self):
import subprocess
+ import sys
import time
- p = subprocess.Popen(["sleep", "20"])
+ p = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(20)"], stdin=subprocess.DEVNULL)
try:
a = status._get_process_start_time(p.pid)
time.sleep(0.2)
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 49dc7ecffff..7a97d9e9405 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -1173,6 +1173,8 @@ class TestSafeCopyDb:
def test_aborts_when_source_remains_busy_past_deadline(
self, tmp_path, monkeypatch
):
+ from types import SimpleNamespace
+
from hermes_cli import backup as backup_mod
src = tmp_path / "locked.db"
@@ -1212,7 +1214,8 @@ class TestSafeCopyDb:
return next(connections)
monkeypatch.setattr(backup_mod.sqlite3, "connect", fake_connect)
- monkeypatch.setattr(backup_mod.time, "monotonic", lambda: next(clock))
+ # Rebind this module's clock; asyncio must retain the process-wide one.
+ monkeypatch.setattr(backup_mod, "time", SimpleNamespace(monotonic=lambda: next(clock)))
monkeypatch.setattr(Path, "unlink", assert_closed_before_unlink)
assert backup_mod._safe_copy_db(src, dst, timeout_seconds=1.0) is False
diff --git a/tests/hermes_cli/test_cmd_uninstall.py b/tests/hermes_cli/test_cmd_uninstall.py
new file mode 100644
index 00000000000..8ba48600c50
--- /dev/null
+++ b/tests/hermes_cli/test_cmd_uninstall.py
@@ -0,0 +1,77 @@
+"""The real uninstall parser must select the data path, never code removal."""
+from __future__ import annotations
+
+import argparse
+import pytest
+
+from hermes_cli import main, uninstall
+from hermes_cli.subcommands.uninstall import build_uninstall_parser
+from tests.hermes_cli.test_data_uninstall import layout # noqa: F401 — isolated home
+
+
[email protected]("entry", ["cli", "module", "cli-dry-run"])
+def test_data_entrypoints_preserve_runtime(layout, monkeypatch, entry):
+ _, witnesses, data = layout
+
+ def no_code_removal(*args, **kwargs):
+ pytest.fail("data-only dispatch reached code removal")
+
+ monkeypatch.setattr(uninstall, "run_uninstall", no_code_removal)
+ monkeypatch.setattr(uninstall, "run_gui_uninstall", no_code_removal)
+ monkeypatch.setattr(main, "_require_tty", no_code_removal)
+ if entry == "module":
+ assert uninstall.main(["--mode", "data"]) == 0
+ else:
+ parser = argparse.ArgumentParser()
+ build_uninstall_parser(parser.add_subparsers(dest="command"), cmd_uninstall=main.cmd_uninstall)
+ args = parser.parse_args(["uninstall", "--data", "--dry-run" if entry == "cli-dry-run" else "--yes"])
+ args.func(args)
+ assert all(path.exists() for path in witnesses)
+ assert all(path.exists() is (entry == "cli-dry-run") for path in data)
+
+
[email protected]("other", ["--full", "--gui"])
+def test_conflicting_data_mode_is_rejected_before_dispatch(other):
+ parser = argparse.ArgumentParser()
+ build_uninstall_parser(parser.add_subparsers(dest="command"), cmd_uninstall=main.cmd_uninstall)
+ with pytest.raises(SystemExit) as error:
+ parser.parse_args(["uninstall", "--data", other, "--yes"])
+ assert error.value.code == 2
+
+
+def test_module_subprocess_removes_only_the_disposable_home(layout, tmp_path):
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ home, witnesses, data = layout
+ root = Path(uninstall.__file__).resolve().parents[1]
+ env = {key: value for key, value in os.environ.items() if key.upper() in {
+ "PATH", "SYSTEMROOT", "WINDIR", "SYSTEMDRIVE", "TEMP", "TMP",
+ }}
+ env.update(HERMES_HOME=str(home), HERMES_RUNTIME_DIR=str(home / "machine" / "tool-store"),
+ HOME=str(tmp_path), USERPROFILE=str(tmp_path), APPDATA=str(tmp_path),
+ LOCALAPPDATA=str(tmp_path), PYTHONPATH=str(root), PYTHONUTF8="1")
+ result = subprocess.run([sys.executable, "-m", "hermes_cli.uninstall", "--mode", "data"],
+ cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, encoding="utf-8", timeout=30)
+ assert result.returncode == 0, result.stdout + result.stderr
+ # This process's actual source is outside the temp home, unlike layout's
+ # declared source. Managed tools, launchers and sibling profiles survive.
+ assert all(path.exists() for path in witnesses[1:])
+ assert all(not path.exists() for path in data)
+ assert not (home / "skills").exists()
+ assert not (home / "SOUL.md").exists()
+
+
+def test_module_uses_the_desktop_instances_explicit_data_path(layout, tmp_path):
+ _, _, _ = layout
+ ordinary = tmp_path / "user" / "desktop-data"
+ variant = tmp_path / "variant-desktop-data"
+ for directory in (ordinary, variant):
+ directory.mkdir()
+ (directory / "preferences.json").write_text("{}", encoding="utf-8")
+ assert uninstall.main(["--mode", "data", "--desktop-userdata", str(variant)]) == 0
+ assert not variant.exists()
+ assert (ordinary / "preferences.json").read_text(encoding="utf-8") == "{}"
diff --git a/tests/hermes_cli/test_data_uninstall.py b/tests/hermes_cli/test_data_uninstall.py
new file mode 100644
index 00000000000..5dae9459d86
--- /dev/null
+++ b/tests/hermes_cli/test_data_uninstall.py
@@ -0,0 +1,137 @@
+"""Data deletion respects declared runtime ownership, confirmation and scope."""
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+import hermes_cli.uninstall as uninstall
+
+
+def layout(tmp_path, monkeypatch):
+ user = tmp_path / "user"
+ user.mkdir()
+ home = user / "hermes-data"
+ source = home / "workspace" / "custom-source"
+ store = home / "machine" / "tool-store"
+ userdata = user / "desktop-data"
+ witnesses = [source / "hermes_cli" / "__init__.py", store / "python" / "python.exe",
+ home / "installs" / "other-install" / "facts.json", home / "bin" / "hermes.cmd",
+ home / "profiles" / "sibling" / "config.yaml",
+ home / "cache" / "partials" / ".locks" / "other-profile-transfer"]
+ for path in witnesses:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("keep", encoding="utf-8")
+ data = [home / "config.yaml", home / "sessions" / "session.json", home / "workspace" / "notes.txt"]
+ for path in data:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("{}" if path.suffix in {".yaml", ".json"} else "user data", encoding="utf-8")
+ monkeypatch.setattr(Path, "home", lambda: user)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ monkeypatch.setattr(uninstall, "get_project_root", lambda: source)
+ monkeypatch.setattr(uninstall, "get_hermes_home", lambda: home)
+ monkeypatch.setattr("hermes_cli.gui_uninstall.desktop_userdata_dir", lambda: userdata)
+ return home, witnesses, data
+
+
[email protected]("mode", ["confirmed", "cancel", "dry-run"])
+def test_data_only_preserves_runtime_and_sibling_homes(layout, monkeypatch, mode):
+ import json
+ from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path, selected_venv
+
+ home, witnesses, data = layout
+ source = uninstall.get_project_root()
+ generation = install_state_dir(source) / "environments" / "selected"
+ generation.mkdir(parents=True)
+ (generation / "pyvenv.cfg").write_text("include-system-site-packages = false", encoding="utf-8")
+ runtime_facts_path(source).write_text(json.dumps({"packages": {"venv": {"environment": str(generation)}}}), encoding="utf-8")
+ monkeypatch.setattr("builtins.input", lambda *args: "no")
+ uninstall.run_data_uninstall(SimpleNamespace(yes=mode != "cancel", dry_run=mode == "dry-run"))
+ assert selected_venv(source) == generation
+ assert all(path.read_text(encoding="utf-8") == "keep" for path in witnesses)
+ assert all(path.exists() is (mode != "confirmed") for path in data)
+ assert home.is_dir()
+
+
+def test_data_only_reports_a_failed_removal(layout, monkeypatch, capsys):
+ home, witnesses, _ = layout
+ real = uninstall.shutil.rmtree
+
+ def refuse(path, *args, **kwargs):
+ if Path(path) == home / "sessions":
+ raise PermissionError("fixture holds sessions")
+ return real(path, *args, **kwargs)
+
+ monkeypatch.setattr(uninstall.shutil, "rmtree", refuse)
+ with pytest.raises(SystemExit) as failure:
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True, dry_run=False))
+ assert failure.value.code != 0
+ output = capsys.readouterr().out
+ assert "Hermes data removed" not in output
+ assert str(home / "sessions") in output
+ assert all(path.exists() for path in witnesses)
+
+
+def test_named_home_does_not_erase_siblings_or_desktop_data(layout, monkeypatch):
+ home, witnesses, _ = layout
+ active = home / "profiles" / "active"
+ active.mkdir()
+ config = active / "config.yaml"
+ config.write_text("model: selected", encoding="utf-8")
+ userdata = home.parent / "desktop-data"
+ userdata.mkdir()
+ (userdata / "preferences.json").write_text("keep", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(active))
+ monkeypatch.setattr(uninstall, "get_hermes_home", lambda: active)
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert not config.exists()
+ assert all(path.exists() for path in witnesses)
+ assert (userdata / "preferences.json").read_text(encoding="utf-8") == "keep"
+
+
+def test_directory_replaced_with_a_link_does_not_expand_removal(layout, tmp_path):
+ from hermes_cli.data_cleanup import plan_data_removal, remove_data
+
+ home, _, _ = layout
+ original = home / "workspace"
+ foreign = tmp_path / "foreign"
+ foreign.mkdir()
+ witness = foreign / "notes.txt"
+ witness.write_text("not Hermes data", encoding="utf-8")
+ probe = tmp_path / "symlink-probe"
+ try:
+ probe.symlink_to(foreign, target_is_directory=True)
+ except OSError as exc:
+ pytest.skip(f"native symlink creation unavailable: {exc}")
+ probe.unlink()
+ plan = plan_data_removal(home, uninstall.get_project_root())
+ original.rename(home / "workspace-moved")
+ original.symlink_to(foreign, target_is_directory=True)
+ _, failures = remove_data(plan)
+ assert failures
+ assert witness.read_text(encoding="utf-8") == "not Hermes data"
+
+
+def test_data_only_preserves_the_containing_bundled_application(layout, monkeypatch):
+ import json
+ from hermes_cli.bundled_app import PAYLOAD_DIR_NAME
+
+ home, _, data = layout
+ app = home / "installed-app"
+ payload = app / "resources" / PAYLOAD_DIR_NAME
+ project = payload / "repo"
+ project.mkdir(parents=True)
+ (project / "install-stamp.json").write_text(json.dumps({"payload": "bundled"}), encoding="utf-8")
+ shell = app / "Hermes.exe"
+ shell.write_bytes(b"retained app bytes")
+ (payload / "venv").mkdir()
+ manifest = payload / "manifest.json"
+ manifest.write_text(json.dumps({"repo": "repo", "venv": "venv"}), encoding="utf-8")
+ monkeypatch.setattr(uninstall, "get_project_root", lambda: project)
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert shell.read_bytes() == b"retained app bytes"
+ assert manifest.is_file()
+ assert all(not path.exists() for path in data)
diff --git a/tests/hermes_cli/test_data_uninstall_holders.py b/tests/hermes_cli/test_data_uninstall_holders.py
new file mode 100644
index 00000000000..6d8954ff07e
--- /dev/null
+++ b/tests/hermes_cli/test_data_uninstall_holders.py
@@ -0,0 +1,165 @@
+"""Data deletion must establish quiescence, never infer it from a signal count."""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import uninstall
+from tests.hermes_cli.test_data_uninstall import layout # noqa: F401 — isolated layout
+
+
[email protected]("mode", ["confirmed", "cancel", "dry-run"])
+def test_unconfirmed_removal_never_contacts_the_gateway(layout, monkeypatch, mode):
+ home, _, data = layout
+ calls = []
+
+ def identify(target, **kwargs):
+ calls.append(target)
+ return {"pid": 42, "hermes_home": str(home), "supervisor": "systemd"}
+
+ monkeypatch.setattr("gateway.control_socket.identify_gateway", identify)
+ monkeypatch.setattr("builtins.input", lambda *args: "no")
+ args = SimpleNamespace(yes=mode != "cancel", dry_run=mode == "dry-run")
+ if mode == "confirmed":
+ with pytest.raises(SystemExit):
+ uninstall.run_data_uninstall(args)
+ assert calls == [home]
+ else:
+ uninstall.run_data_uninstall(args)
+ assert calls == []
+ assert all(path.exists() for path in data)
+
+
+def test_live_chat_lease_blocks_data_deletion(layout):
+ from hermes_cli.active_sessions import release_active_session, try_acquire_active_session
+
+ home, _, data = layout
+ lease, refusal = try_acquire_active_session(
+ session_id="fixture-session", surface="cli", config={}, registry_home=home,
+ track_liveness=True,
+ )
+ assert lease is not None and refusal is None
+ try:
+ with pytest.raises(SystemExit):
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert all(path.exists() for path in data)
+ finally:
+ release_active_session(lease)
+
+
+def test_manual_gateway_drains_over_real_control_transport_before_deletion(layout):
+ import asyncio
+ import subprocess
+ import sys
+ from threading import Event, Thread
+ from gateway.control_socket import GatewayControlServer
+ from gateway.status import get_process_start_time
+
+ home, _, data = layout
+ # A disposable child is the declared process. Control dispatch is real;
+ # the fixture handler stops only that child, never any running gateway.
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"], cwd=home)
+ loop = asyncio.new_event_loop()
+ ready = Event()
+ paused = Event()
+ holders = []
+
+ def identify():
+ return {"pid": child.pid, "start_time": get_process_start_time(child.pid),
+ "hermes_home": str(home), "supervisor": "manual"}
+
+ def drain():
+ paused.set()
+ child.terminate()
+ child.wait(timeout=5)
+ loop.call_soon_threadsafe(loop.stop)
+ return {"pid": child.pid, "pausing": True, "drain_timeout": 0}
+
+ server = GatewayControlServer(home, verb_handlers={"identify": identify, "pause-for-update": drain})
+
+ def serve():
+ asyncio.set_event_loop(loop)
+ started = loop.run_until_complete(server.start())
+ holders.append(started)
+ ready.set()
+ if started:
+ loop.run_forever()
+ loop.run_until_complete(server.stop())
+ loop.close()
+
+ thread = Thread(target=serve, daemon=True)
+ thread.start()
+ try:
+ assert ready.wait(timeout=10) and holders == [True]
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert paused.is_set() and child.poll() is not None
+ assert all(not path.exists() for path in data)
+ finally:
+ if child.poll() is None:
+ child.terminate()
+ child.wait(timeout=5)
+ if thread.is_alive():
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(timeout=10)
+ assert not thread.is_alive()
+
+
[email protected]("profile", ["", "sibling"])
+def test_backend_initial_profile_is_not_its_write_scope(layout, profile):
+ from hermes_cli.process_identity import register_self
+
+ _, _, data = layout
+ assert register_self("serve", project_root=uninstall.get_project_root(), detail={"profile": profile})
+ with pytest.raises(SystemExit):
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert all(path.exists() for path in data)
+
+
[email protected]("terminal", [False, True])
+def test_detached_cron_attempt_must_finish_before_data_removal(layout, monkeypatch, terminal):
+ from cron import executions
+
+ _, _, data = layout
+ monkeypatch.setattr(executions, "_emit_execution_state", lambda *args, **kwargs: None)
+ record = executions.create_execution("temporary-job", source="manual")
+ if terminal:
+ executions.finish_execution(record["id"], success=True)
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert all(not path.exists() for path in data)
+ else:
+ with pytest.raises(SystemExit):
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert all(path.exists() for path in data)
+
+
+def test_named_profile_cannot_delete_data_served_by_the_default_multiplexer(layout, monkeypatch):
+ home, _, _ = layout
+ profile = home / "profiles" / "active"
+ profile.mkdir()
+ config = profile / "config.yaml"
+ config.write_text("{}", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(profile))
+ monkeypatch.setattr(uninstall, "get_hermes_home", lambda: profile)
+
+ def identify(target, **kwargs):
+ if target == home:
+ return {"pid": 42, "hermes_home": str(home), "served_profiles": ["active"]}
+ return None
+
+ monkeypatch.setattr("gateway.control_socket.identify_gateway", identify)
+ monkeypatch.setattr("gateway.control_socket.pause_gateway_for_update",
+ lambda *args, **kwargs: pytest.fail("must not stop other profiles' gateway"))
+ with pytest.raises(SystemExit):
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert config.read_text(encoding="utf-8") == "{}"
+
+
+def test_data_removal_respects_the_checkpoint_store_owner(layout):
+ from tools.checkpoint_pruning import store_lock
+
+ home, _, data = layout
+ with store_lock(home / "checkpoints"):
+ with pytest.raises(SystemExit):
+ uninstall.run_data_uninstall(SimpleNamespace(yes=True))
+ assert all(path.exists() for path in data)
diff --git a/tests/hermes_cli/test_plugins_admission_setter.py b/tests/hermes_cli/test_plugins_admission_setter.py
index 168e3bb4468..a0bbcb37571 100644
--- a/tests/hermes_cli/test_plugins_admission_setter.py
+++ b/tests/hermes_cli/test_plugins_admission_setter.py
@@ -213,26 +213,22 @@ def test_facts_failure_triggers_undo_inside_one_transaction(plugin_home, monkeyp
order.append("before_publish")
return adm._config_commit({"dep-plug"}, set())
- # Facts stub needs a working reload/get but a failing record_state:
- class _Facts:
- def __init__(self, path):
- self.path = path
-
- def reload(self):
- pass
-
- def get(self, name):
- return None
-
- def record_state(self, *a, **k):
- order.append("record_state")
- raise OSError("facts disk full")
-
- monkeypatch.setattr(ensure, "Facts", _Facts)
- with pytest.raises(OSError):
+ facts_path = plugin_home / "runtime" / "facts.json"
+ ensure.Facts(facts_path).record_state("venv", "previous-stamp", [])
+ previous_facts = facts_path.read_bytes()
+ monkeypatch.setattr(ensure.paths, "runtime_facts_path", lambda: facts_path)
+ monkeypatch.setattr(ensure.paths, "repo_root", lambda: plugin_home / "runtime")
+
+ def fail_publication(self, *args, **kwargs):
+ order.append("record_state")
+ raise OSError("facts disk full")
+
+ monkeypatch.setattr(ensure.Facts, "record_state", fail_publication)
+ with pytest.raises(OSError, match="facts disk full"):
ensure.sync_venv(explicit=True, plugin_dirs=[plug], before_publish=before_publish)
assert order == ["before_publish", "record_state"] # config committed under the lock first
assert (plugin_home / "config.yaml").read_bytes() == previous # undone atomically
+ assert facts_path.read_bytes() == previous_facts
latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))
assert latest["outcome"] == "failed"
diff --git a/tests/hermes_cli/test_profile_distribution.py b/tests/hermes_cli/test_profile_distribution.py
index 43b4dbad627..1761b6712f5 100644
--- a/tests/hermes_cli/test_profile_distribution.py
+++ b/tests/hermes_cli/test_profile_distribution.py
@@ -275,13 +275,13 @@ class TestInstall:
staged = _make_staging_dir(profile_env, "legacy_all")
# Extra top-level payload not covered by DEFAULT_DIST_OWNED
(staged / "extra.txt").write_text("bonus\n")
- (staged / "tools").mkdir()
- (staged / "tools" / "helper.py").write_text("# helper\n")
+ (staged / "assets").mkdir()
+ (staged / "assets" / "helper.py").write_text("# helper\n")
plan = install_distribution(str(staged), name="legacy_all")
assert (plan.target_dir / "extra.txt").read_text() == "bonus\n", \
"omitted distribution_owned must keep copying undeclared files"
- assert (plan.target_dir / "tools" / "helper.py").exists(), \
+ assert (plan.target_dir / "assets" / "helper.py").exists(), \
"omitted distribution_owned must keep copying undeclared dirs"
def test_install_allowlist_supports_nested_paths(self, profile_env):
@@ -509,20 +509,20 @@ class TestSecurity:
class TestNestedUserOwnedExcludeNotFiltered:
def test_nested_bin_dir_is_preserved(self, profile_env):
- """A distribution shipping tools/bin/ must not have tools/bin/ dropped
+ """A distribution shipping assets/bin/ must not have assets/bin/ dropped
during install even though 'bin' is in USER_OWNED_EXCLUDE."""
mf = DistributionManifest(
name="nested_bin",
version="0.1.0",
- distribution_owned=list(DEFAULT_DIST_OWNED) + ["tools"],
+ distribution_owned=list(DEFAULT_DIST_OWNED) + ["assets"],
)
staged = _make_staging_dir(profile_env, "src", manifest=mf)
- (staged / "tools" / "bin").mkdir(parents=True)
- (staged / "tools" / "bin" / "tool.py").write_text("# tool\n")
+ (staged / "assets" / "bin").mkdir(parents=True)
+ (staged / "assets" / "bin" / "tool.py").write_text("# tool\n")
plan = install_distribution(str(staged), name="nested_bin")
- assert (plan.target_dir / "tools" / "bin").is_dir(), "nested bin/ was dropped"
- assert (plan.target_dir / "tools" / "bin" / "tool.py").exists()
+ assert (plan.target_dir / "assets" / "bin").is_dir(), "nested bin/ was dropped"
+ assert (plan.target_dir / "assets" / "bin" / "tool.py").exists()
def test_nested_logs_dir_is_preserved(self, profile_env):
mf = DistributionManifest(
@@ -560,21 +560,21 @@ class TestNestedUserOwnedExcludeNotFiltered:
"staged logs/ content should not leak into target"
def test_both_nested_and_top_level_coexist(self, profile_env):
- """Top-level bin/ filtered, but tools/bin/ kept."""
+ """Top-level bin/ filtered, but assets/bin/ kept."""
mf = DistributionManifest(
name="coexist",
version="0.1.0",
- distribution_owned=list(DEFAULT_DIST_OWNED) + ["tools"],
+ distribution_owned=list(DEFAULT_DIST_OWNED) + ["assets"],
)
staged = _make_staging_dir(profile_env, "src", manifest=mf)
(staged / "bin").mkdir(exist_ok=True)
(staged / "bin" / "top.sh").write_text("# top\n")
- (staged / "tools" / "bin").mkdir(parents=True)
- (staged / "tools" / "bin" / "helper.py").write_text("# helper\n")
+ (staged / "assets" / "bin").mkdir(parents=True)
+ (staged / "assets" / "bin" / "helper.py").write_text("# helper\n")
plan = install_distribution(str(staged), name="coexist")
assert not (plan.target_dir / "bin").exists()
- assert (plan.target_dir / "tools" / "bin" / "helper.py").exists()
+ assert (plan.target_dir / "assets" / "bin" / "helper.py").exists()
# ===========================================================================
diff --git a/tests/hermes_cli/test_profile_pm_portability.py b/tests/hermes_cli/test_profile_pm_portability.py
new file mode 100644
index 00000000000..633cc0da115
--- /dev/null
+++ b/tests/hermes_cli/test_profile_pm_portability.py
@@ -0,0 +1,186 @@
+"""Portable transfers keep user files, not machine-specific PM state."""
+from argparse import Namespace
+from pathlib import Path
+import tarfile
+import zipfile
+
+import pytest
+
+
+def transfer_home(tmp_path, monkeypatch):
+ home = tmp_path / "source-home"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ from hermes_cli import backup, gateway, profiles
+
+ # Restoring data must not install host services or modify the test user's shell.
+ monkeypatch.setattr(gateway, "ensure_gateway_service", lambda **kwargs: False)
+ monkeypatch.setattr(gateway, "_is_service_running", lambda: False)
+ monkeypatch.setattr(profiles, "check_alias_collision", lambda name: "test has no aliases")
+ monkeypatch.setattr(backup, "_collect_memory_provider_external_paths", lambda: [])
+ return home
+
+
+def _write_files(root, files):
+ for rel, content in files.items():
+ target = root / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+
+
[email protected]("route", ["backup", "default", "named", "distribution", "explicit"])
+def test_transfers_preserve_user_files_without_porting_pm_state(
+ transfer_home, tmp_path, monkeypatch, route
+):
+ from hermes_cli.backup import run_backup, run_import
+ from hermes_cli.profile_distribution import (
+ DistributionManifest, install_distribution, write_manifest,
+ )
+ from hermes_cli.profiles import export_profile, get_profile_dir, import_profile
+
+ portable = {
+ "config.yaml": "model:\n model: portable\n",
+ "SOUL.md": "Be kind.\n",
+ "plugins/example/facts.json": '{"owner": "plugin"}\n',
+ "skills/example/tools/helper.py": "print('portable tool')\n",
+ "skills/example/cache/notes.txt": "user-authored data\n",
+ }
+ runtime = {
+ "installs/install-id/facts.json": '{"environment": "C:/other-machine/generation"}\n',
+ "installs/install-id/environments/generation/pyvenv.cfg": "home = other-machine\n",
+ "tools/uv/bin/uv": "machine executable\n",
+ "cache/partials/transfer.partial": "unfinished transfer\n",
+ }
+ source = get_profile_dir("porter") if route == "named" else transfer_home
+ _write_files(source, portable | runtime)
+ if route == "backup":
+ portable |= {f"profiles/coder/{rel}": text for rel, text in list(portable.items())}
+ runtime |= {f"profiles/coder/{rel}": text for rel, text in list(runtime.items())}
+ _write_files(source, portable | runtime)
+ archive = tmp_path / "portable.zip"
+ run_backup(Namespace(output=str(archive)))
+ with zipfile.ZipFile(archive) as reader:
+ names = set(reader.namelist())
+ elif route in {"default", "named"}:
+ name = "porter" if route == "named" else "default"
+ archive = export_profile(name, str(tmp_path / "portable.tar.gz"))
+ with tarfile.open(archive) as reader:
+ names = {member.name.removeprefix(f"{name}/") for member in reader if member.isfile()}
+ else:
+ owned = sorted({Path(rel).parts[0] for rel in portable | runtime}) if route == "explicit" else []
+ write_manifest(source, DistributionManifest(name="portable", distribution_owned=owned))
+ names = None
+
+ if names is not None:
+ assert set(portable) <= names
+ assert not (set(runtime) & names)
+
+ target_home = tmp_path / "target-home"
+ target_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(target_home))
+ if route == "backup":
+ run_import(Namespace(zipfile=str(archive), force=True))
+ restored = target_home
+ elif route in {"default", "named"}:
+ restored = import_profile(str(archive), name="restored")
+ else:
+ restored = install_distribution(str(source), name="restored").target_dir
+
+ for rel, content in portable.items():
+ assert (restored / rel).read_text(encoding="utf-8") == content, (route, rel)
+ for rel, content in runtime.items():
+ assert not (restored / rel).exists(), (route, rel)
+ assert (source / rel).read_text(encoding="utf-8") == content
+
+
[email protected]("route", ["backup", "profile", "profile-denied", "distribution", "explicit"])
+def test_incoming_runtime_state_never_replaces_target_runtime(
+ transfer_home, tmp_path, monkeypatch, route
+):
+ from hermes_cli.backup import run_import
+ from hermes_cli.profile_distribution import (
+ DistributionManifest, install_distribution, write_manifest,
+ )
+ from hermes_cli.profiles import get_profile_dir, import_profile
+
+ incoming = {
+ "config.yaml": "model:\n model: restored\n",
+ "plugins/example/facts.json": '{"owner": "plugin"}\n',
+ "skills/example/tools/helper.py": "print('user tool')\n",
+ "skills/example/cache/notes.txt": "keep user files\n",
+ }
+ machine = {
+ "installs/key/facts.json": "foreign generation\n",
+ "tools/uv/bin/uv": "foreign executable\n",
+ "cache": "foreign cache file\n",
+ }
+ if route == "backup":
+ incoming |= {f"profiles/coder/{rel}": text for rel, text in list(incoming.items())}
+ machine |= {f"profiles/coder/{rel}": text for rel, text in list(machine.items())}
+ staged = tmp_path / "archive-source"
+ _write_files(staged, incoming | machine)
+ target = transfer_home if route == "backup" else get_profile_dir("restored")
+ if not route.startswith("profile"):
+ _write_files(target, dict.fromkeys(machine, "target-owned runtime\n"))
+
+ if route == "backup":
+ archive = tmp_path / "legacy.zip"
+ with zipfile.ZipFile(archive, "w") as writer:
+ for rel, content in (incoming | machine).items():
+ writer.writestr(f".hermes/{rel}", content)
+ run_import(Namespace(zipfile=str(archive), force=True))
+ elif route.startswith("profile"):
+ archive = tmp_path / "legacy.tar.gz"
+ with tarfile.open(archive, "w:gz") as writer:
+ writer.add(staged, arcname="legacy")
+ if route == "profile-denied":
+ from hermes_cli import profiles
+
+ real_rmtree = profiles.shutil.rmtree
+
+ def deny_runtime_removal(path, *args, **kwargs):
+ if Path(path).name == "installs":
+ if kwargs.get("ignore_errors"):
+ return
+ raise PermissionError("staged runtime is locked")
+ return real_rmtree(path, *args, **kwargs)
+
+ with monkeypatch.context() as scoped:
+ scoped.setattr(profiles.shutil, "rmtree", deny_runtime_removal)
+ with pytest.raises(PermissionError, match="staged runtime is locked"):
+ import_profile(str(archive), name="restored")
+ assert not target.exists()
+ return
+ target = import_profile(str(archive), name="restored")
+ else:
+ owned = sorted({Path(rel).parts[0] for rel in incoming | machine}) if route == "explicit" else []
+ write_manifest(staged, DistributionManifest(name="legacy", distribution_owned=owned))
+ target = install_distribution(str(staged), name="restored", force=True).target_dir
+
+ for rel, content in incoming.items():
+ assert (target / rel).read_text(encoding="utf-8") == content, (route, rel)
+ for rel, content in machine.items():
+ if route == "profile":
+ assert not (target / rel).exists(), rel
+ else:
+ assert (target / rel).read_text(encoding="utf-8") == "target-owned runtime\n", (route, rel)
+ assert (staged / rel).read_text(encoding="utf-8") == content
+
+ if route == "explicit":
+ # Windows-authored manifests use separators that must not bypass ownership.
+ write_manifest(staged, DistributionManifest(
+ name="legacy", distribution_owned=[rel.replace("/", "\\") for rel in incoming | machine],
+ ))
+ install_distribution(str(staged), name="restored", force=True)
+ for rel in machine:
+ assert (target / rel).read_text(encoding="utf-8") == "target-owned runtime\n", rel
+ elif route == "backup":
+ # An in-home traversal must not bypass the runtime-root classification.
+ with zipfile.ZipFile(archive, "w") as writer:
+ writer.writestr(".hermes/config.yaml", incoming["config.yaml"])
+ writer.writestr(".hermes/skills/../installs/key/facts.json", "foreign generation\n")
+ run_import(Namespace(zipfile=str(archive), force=True))
+ assert (target / "installs/key/facts.json").read_text(encoding="utf-8") == "target-owned runtime\n"
diff --git a/tests/hermes_cli/test_real_home_tripwire.py b/tests/hermes_cli/test_real_home_tripwire.py
index dc939ae3820..d3f61d132f7 100644
--- a/tests/hermes_cli/test_real_home_tripwire.py
+++ b/tests/hermes_cli/test_real_home_tripwire.py
@@ -1,91 +1,100 @@
-"""The real-home tripwire: tests touching the REAL hermes home must fail.
-
-The guard (conftest _forbid_real_hermes_home_io) exists to catch the
-hardcoded-restatement bug class — code writing Path.home()/".hermes"
-instead of get_hermes_home(). These tests prove the tripwire fires.
-"""
-
+"""Real-home guards are exercised against disposable protected roots only."""
from __future__ import annotations
+import io
+import os
from pathlib import Path
+import shutil
+import sqlite3
import pytest
-def test_read_from_real_home_fails():
- """Reading production state in a test is a leak — must trip."""
- from tests.conftest import _REAL_HERMES_ROOT_CANDIDATES
-
- assert _REAL_HERMES_ROOT_CANDIDATES, "guard roots not captured"
- root = _REAL_HERMES_ROOT_CANDIDATES[0]
- sentinel = root / "tripwire-probe-should-fail.txt"
- # the wrapper must raise AssertionError (not create/read anything)
- with pytest.raises(AssertionError, match="REAL hermes home"):
- # open() for READ on a nonexistent file still trips the guard
- # BEFORE the OS error — the check is path-based, not result-based
- with open(sentinel, "r", encoding="utf-8"):
- pass
-
-
-def test_write_to_real_home_fails():
- root = Path.home() / ".hermes"
- sentinel = root / "tripwire-probe-write-should-fail.json"
- with pytest.raises(AssertionError, match="REAL hermes home"):
- with open(sentinel, "w", encoding="utf-8") as f:
- f.write("should never land")
-
-
-def test_mkdir_under_real_home_fails(tmp_path):
- # os.mkdir with a real-home target (parent must exist for mkdir; use
- # makedirs which creates parents — both are guarded)
- with pytest.raises(pytest.fail.Exception):
- import os
-
- os.makedirs(str(Path.home() / ".hermes" / "tripwire-deep" / "dir"), exist_ok=True)
-
-
-def test_isolated_home_io_still_works(tmp_path):
- """The happy path: tempdir (the sandboxed HERMES_HOME shape) is NOT
- under the real root — ordinary I/O must be completely unaffected."""
- target = tmp_path / "fine.json"
- with open(target, "w", encoding="utf-8") as f:
- f.write("ok")
- with open(target, encoding="utf-8") as f:
- assert f.read() == "ok"
-
-
-def test_profile_paths_under_real_root_also_trip():
- """<root>/profiles/<name> is inside the guarded root — the deployment
- bug class (pm/plugins_state Path.home()/.hermes/profiles) trips."""
- with pytest.raises(AssertionError, match="REAL hermes home"):
- with open(
- Path.home() / ".hermes" / "profiles" / "some-profile" / "config.yaml",
- "r",
- encoding="utf-8",
- ):
- pass
+def protected_home(tmp_path, monkeypatch):
+ from tests import conftest
+
+ root = tmp_path / "protected"
+ root.mkdir()
+ (root / "file.txt").write_text("unchanged", encoding="utf-8")
+ (root / "empty").mkdir()
+ monkeypatch.setattr(conftest, "_REAL_HERMES_ROOT_CANDIDATES", [root])
+ yield root
+ # Restore access before tmp_path/pytest cleanup even when an assertion fails.
+ monkeypatch.setattr(conftest, "_REAL_HERMES_ROOT_CANDIDATES", [])
+
+
+def _open_close(path):
+ with open(path, encoding="utf-8"):
+ pass
+
+
+def _io_open_close(path):
+ with io.open(path, encoding="utf-8"):
+ pass
+
+
+def _os_open_close(path):
+ descriptor = os.open(path, os.O_RDONLY)
+ os.close(descriptor)
+
+
+_OPERATIONS = {
+ "builtin-open": _open_close,
+ "io-open": _io_open_close,
+ "os-open": _os_open_close,
+ "read-text": lambda path: path.read_text(encoding="utf-8"),
+ "write-text": lambda path: path.write_text("changed", encoding="utf-8"),
+ "read-bytes": lambda path: path.read_bytes(),
+ "write-bytes": lambda path: path.write_bytes(b"changed"),
+ "stat": lambda path: path.stat(),
+ "lstat": lambda path: path.lstat(),
+ "unlink": lambda path: path.unlink(),
+ "remove": lambda path: os.remove(path),
+ "rename-out": lambda path: path.rename(path.parent.parent / "moved.txt"),
+ "replace-out": lambda path: path.replace(path.parent.parent / "replaced.txt"),
+ "mkdir": lambda path: (path.parent / "new").mkdir(),
+ "makedirs": lambda path: os.makedirs(path.parent / "deep" / "child"),
+ "rmdir": lambda path: (path.parent / "empty").rmdir(),
+ "rmtree": lambda path: shutil.rmtree(path.parent),
+ "listdir": lambda path: os.listdir(path.parent),
+ "scandir": lambda path: list(os.scandir(path.parent)),
+ "sqlite": lambda path: sqlite3.connect(path.parent / "state.db").close(),
+}
+
+
[email protected]("operation", _OPERATIONS, ids=_OPERATIONS)
+def test_io_guard_denies_protected_roots_before_mutation(protected_home, operation):
+ with pytest.raises((AssertionError, pytest.fail.Exception), match="REAL hermes home"):
+ _OPERATIONS[operation](protected_home / "file.txt")
+
+
+def test_rename_cannot_overwrite_a_protected_destination(protected_home, tmp_path):
+ source = tmp_path / "source.txt"
+ source.write_text("external", encoding="utf-8")
+ with pytest.raises((AssertionError, pytest.fail.Exception), match="REAL hermes home"):
+ source.replace(protected_home / "file.txt")
+ assert source.read_text(encoding="utf-8") == "external"
+
+
+def test_unprotected_paths_and_open_descriptors_still_work(protected_home, tmp_path):
+ target = tmp_path / "allowed" / "file.txt"
+ target.parent.mkdir()
+ target.write_text("ok", encoding="utf-8")
+ assert target.read_text(encoding="utf-8") == "ok"
+ fd = os.open(target, os.O_RDONLY)
+ with os.fdopen(fd, "r", encoding="utf-8") as stream:
+ assert stream.read() == "ok"
+ moved = target.replace(target.with_name("moved.txt"))
+ assert list(moved.parent.iterdir()) == [moved]
+ moved.unlink()
+ moved.parent.rmdir()
+ connection = sqlite3.connect(tmp_path / "allowed.db")
+ connection.close()
@pytest.mark.allow_real_home_io
-def test_opt_out_marker_bypasses_guard(tmp_path):
- """The documented escape hatch: marked tests read real paths freely
- (the guard's own tests inspect conftest internals)."""
- # just exercising that the fixture returns without wrapping
- assert True
-
-
-def test_sqlite_connect_to_real_home_fails():
- """sqlite3 bypasses builtins.open (C-level) — the dedicated hook must
- catch a state.db-shaped leak under ~/.hermes."""
- import sqlite3
-
- with pytest.raises(pytest.fail.Exception):
- sqlite3.connect(str(Path.home() / ".hermes" / "state.db"))
-
-
-def test_sqlite_connect_to_tempdir_still_works(tmp_path):
- import sqlite3
-
- con = sqlite3.connect(str(tmp_path / "fine.db"))
- con.execute("CREATE TABLE t (x)")
- con.close()
+def test_explicit_opt_out_allows_only_the_disposable_canary(protected_home):
+ target = protected_home / "file.txt"
+ target.write_text("opted out", encoding="utf-8")
+ assert target.read_text(encoding="utf-8") == "opted out"
diff --git a/tests/hermes_cli/test_uninstall_node_symlinks.py b/tests/hermes_cli/test_uninstall_node_symlinks.py
index 4bf37cda2fc..0908bbf8b48 100644
--- a/tests/hermes_cli/test_uninstall_node_symlinks.py
+++ b/tests/hermes_cli/test_uninstall_node_symlinks.py
@@ -6,7 +6,6 @@ PATH, shadowing an existing nvm. Uninstall must remove those symlinks, but
only when they still resolve into the Hermes-managed node dir.
"""
-import os
from pathlib import Path
import pytest
@@ -21,6 +20,7 @@ def fake_home(tmp_path, monkeypatch):
home = tmp_path / "home"
home.mkdir()
monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ monkeypatch.setenv("HERMES_HOME", str(home / ".hermes"))
(home / ".local" / "bin").mkdir(parents=True)
return home
@@ -30,7 +30,7 @@ def _make_hermes_node(hermes_home: Path) -> Path:
node_bin = hermes_home / "node" / "bin"
node_bin.mkdir(parents=True)
for name in ("node", "npm", "npx"):
- (node_bin / name).write_text("#!/bin/sh\n")
+ (node_bin / name).write_text("#!/bin/sh\n", encoding="utf-8")
(node_bin / name).chmod(0o755)
return node_bin
@@ -41,15 +41,18 @@ def _make_hermes_node(hermes_home: Path) -> Path:
def test_node_link_cleanup_respects_resolved_owner(fake_home, monkeypatch, owned):
home = fake_home / ".hermes"
link = fake_home / ".local" / "bin" / "node"
- link.write_text("link stand-in", encoding="utf-8")
target = home / "node" / "bin" / "node" if owned else fake_home / "other" / "node"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text("retained binary", encoding="utf-8")
+ try:
+ link.symlink_to(target)
+ except OSError as exc:
+ pytest.skip(f"native symlink creation unavailable: {exc}")
monkeypatch.setattr(uninstall, "_node_symlink_candidate_dirs", lambda: [link.parent])
- # Exercise the owner decision on hosts that cannot create symlinks.
- monkeypatch.setattr(Path, "is_symlink", lambda path: path == link)
- monkeypatch.setattr(os, "readlink", lambda path: str(target))
removed = uninstall.remove_node_symlinks(home)
assert removed == ([link] if owned else [])
assert link.exists() is (not owned)
+ assert target.read_text(encoding="utf-8") == "retained binary"
@pytest.mark.require_symlinks
diff --git a/tests/home_io_guard.py b/tests/home_io_guard.py
new file mode 100644
index 00000000000..16a923270e1
--- /dev/null
+++ b/tests/home_io_guard.py
@@ -0,0 +1,94 @@
+"""Guard Python filesystem calls in tests, not arbitrary native/subprocess I/O."""
+from __future__ import annotations
+
+import builtins
+from functools import wraps
+import io
+import os
+from pathlib import Path
+import shutil
+import sqlite3
+import threading
+
+
+class HomeIOGuard:
+ def __init__(self, roots):
+ self.roots = roots
+ self.checking = threading.local()
+ self.directories: dict[int, Path] = {}
+
+ def check(self, value, *, dir_fd=None):
+ if value is None or isinstance(value, int) or getattr(self.checking, "active", False):
+ return
+ self.checking.active = True
+ try:
+ candidate = Path(os.fsdecode(value)).expanduser()
+ if dir_fd is not None and not candidate.is_absolute():
+ parent = self.directories.get(dir_fd)
+ if parent is None:
+ raise AssertionError("TEST BUG: untracked dir_fd in guarded filesystem I/O")
+ candidate = parent / candidate
+ absolute = Path(os.path.abspath(candidate))
+ roots = self.roots()
+ # Check the lexical path first: resolving must not probe a protected
+ # tree merely to decide that the original path was forbidden.
+ if any(absolute.is_relative_to(root) for root in roots):
+ self.refuse(value)
+ resolved = absolute.resolve()
+ if any(resolved.is_relative_to(root) for root in roots):
+ self.refuse(value)
+ finally:
+ self.checking.active = False
+
+ @staticmethod
+ def refuse(value):
+ raise AssertionError(
+ f"TEST BUG: file I/O against the REAL hermes home: {value}\n"
+ "Use the isolated HERMES_HOME or a temporary fixture instead."
+ )
+
+ def install(self, monkeypatch):
+ def wrap(module, name, parameters):
+ original = getattr(module, name)
+
+ @wraps(original)
+ def guarded(*args, **kwargs):
+ for index, (parameter, descriptor) in enumerate(parameters):
+ value = args[index] if index < len(args) else kwargs.get(parameter)
+ self.check(value, dir_fd=kwargs.get(descriptor) if descriptor else None)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(module, name, guarded)
+
+ for module in (builtins, io):
+ wrap(module, "open", (("file", None),))
+ for name in ("mkdir", "stat", "lstat", "unlink", "remove", "rmdir", "chmod", "utime", "readlink", "access"):
+ wrap(os, name, (("path", "dir_fd"),))
+ for name in ("makedirs", "listdir", "scandir"):
+ wrap(os, name, (("name" if name == "makedirs" else "path", None),))
+ for name in ("rename", "replace"):
+ wrap(os, name, (("src", "src_dir_fd"), ("dst", "dst_dir_fd")))
+ wrap(shutil, "rmtree", (("path", "dir_fd"),))
+ wrap(sqlite3, "connect", (("database", None),))
+
+ original_open, original_close = os.open, os.close
+
+ @wraps(original_open)
+ def guarded_open(path, flags, *args, **kwargs):
+ self.check(path, dir_fd=kwargs.get("dir_fd"))
+ fd = original_open(path, flags, *args, **kwargs)
+ candidate = Path(os.fsdecode(path))
+ if kwargs.get("dir_fd") is not None and not candidate.is_absolute():
+ candidate = self.directories[kwargs["dir_fd"]] / candidate
+ self.directories[fd] = candidate.absolute()
+ return fd
+
+ @wraps(original_close)
+ def guarded_close(fd):
+ try:
+ return original_close(fd)
+ finally:
+ self.directories.pop(fd, None)
+
+ monkeypatch.setattr(os, "open", guarded_open)
+ monkeypatch.setattr(os, "close", guarded_close)
diff --git a/tests/pm/_range_server.py b/tests/pm/_range_server.py
index 414b061fa92..ebfeeb94d0e 100644
--- a/tests/pm/_range_server.py
+++ b/tests/pm/_range_server.py
@@ -8,6 +8,7 @@ fixture starts one and resets its state.
from __future__ import annotations
+import hashlib
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
@@ -21,11 +22,18 @@ class RangeHandler(BaseHTTPRequestHandler):
abort_after: int | None = None # close the connection after this many bytes
slow_per_chunk: float = 0.0 # sleep per served piece (pause tests)
no_range: bool = False # ignore Range, serve 200 full body
+ etags: bool = True
chunk: int = 1 << 20 # serve piece size
def log_message(self, *args): # noqa: A002 - silence request logging
pass
+ def end_headers(self):
+ payload = self.payloads.get(self.path)
+ if payload is not None and self.etags:
+ self.send_header("ETag", '"' + hashlib.sha256(payload).hexdigest() + '"')
+ super().end_headers()
+
def do_GET(self): # noqa: N802 - http.server API
payload = self.payloads.get(self.path)
if payload is None:
@@ -56,7 +64,7 @@ class RangeHandler(BaseHTTPRequestHandler):
# probe: 206 with total from Content-Range, 1 byte body
total = len(payload)
self.send_response(206)
- self.send_header("Content-Range", f"bytes 0-{total - 1}/{total}")
+ self.send_header("Content-Range", f"bytes 0-0/{total}")
self.send_header("Content-Length", "1")
self.end_headers()
self.wfile.write(payload[:1])
@@ -97,6 +105,7 @@ def dl_server():
RangeHandler.abort_after = None
RangeHandler.slow_per_chunk = 0.0
RangeHandler.no_range = False
+ RangeHandler.etags = True
RangeHandler.chunk = 1 << 20
server = HTTPServer(("127.0.0.1", 0), RangeHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
diff --git a/tests/pm/test_download_state.py b/tests/pm/test_download_state.py
new file mode 100644
index 00000000000..35697dd85e1
--- /dev/null
+++ b/tests/pm/test_download_state.py
@@ -0,0 +1,77 @@
+"""GC and downloads acquire the same partial owner before changing its files."""
+from __future__ import annotations
+
+from contextlib import nullcontext
+import os
+import time
+
+import pytest
+
+from pm.cli import _gc_store
+from pm.download_state import partial_lock
+from pm.lock import Facts
+from pm.store import Store
+
+
[email protected]("state", ["held", "recent-pair", "unused"])
+def test_gc_respects_partial_ownership_and_recent_resume(tmp_path, monkeypatch, state):
+ partials = tmp_path / "partials"
+ partials.mkdir()
+ part = partials / "example.part"
+ side = partials / "example.ranges"
+ part.write_bytes(b"partial")
+ side.write_text("[]", encoding="utf-8")
+ old = time.time() - 10 * 24 * 60 * 60
+ for path in (part, side):
+ os.utime(path, (old, old))
+ if state == "recent-pair":
+ side.touch()
+ monkeypatch.setattr("pm.paths.partials_root", lambda: partials)
+ store = Store(tmp_path / "store")
+ with partial_lock(partials, "example") if state == "held" else nullcontext():
+ _gc_store(store, Facts(store.root / "facts.json"))
+ assert part.exists() is (state != "unused")
+ assert side.exists() is (state != "unused")
+ if state == "held":
+ assert (partials / ".locks" / "example").is_file()
+ _gc_store(store, Facts(store.root / "facts.json"))
+ assert not part.exists() and not side.exists()
+ assert (partials / ".locks" / "example").is_file()
+
+
+def test_pause_interrupts_an_owner_wait(tmp_path):
+ from threading import Event, Thread
+ from pm.downloader import Download, DownloadPaused, Source
+
+ destination = tmp_path / "already-present"
+ destination.write_bytes(b"complete")
+ download = Download([Source("https://example.invalid/model", destination)], partials_dir=tmp_path / "partials")
+ waiting = Event()
+ finished = Event()
+ errors = []
+ original_key = download._key
+
+ def key(url):
+ waiting.set()
+ return original_key(url)
+
+ download._key = key
+
+ def run():
+ try:
+ download.run()
+ except Exception as exc:
+ errors.append(exc)
+ finally:
+ finished.set()
+
+ with partial_lock(download.partials_dir, original_key(download.sources[0].url)):
+ worker = Thread(target=run)
+ worker.start()
+ assert waiting.wait(timeout=5)
+ download.pause()
+ stopped_while_locked = finished.wait(timeout=5)
+ worker.join(timeout=5)
+ assert stopped_while_locked
+ assert len(errors) == 1 and isinstance(errors[0], DownloadPaused)
+ assert destination.read_bytes() == b"complete"
diff --git a/tests/pm/test_downloader.py b/tests/pm/test_downloader.py
index fb1461610a9..3cf113962b9 100644
--- a/tests/pm/test_downloader.py
+++ b/tests/pm/test_downloader.py
@@ -17,7 +17,7 @@ from pathlib import Path
import pytest
from pm.downloader import (Download, DownloadError, DownloadPaused,
- HashError, Source, gc_protected_names)
+ HashError, Source)
from tests.pm._range_server import RangeHandler as _Handler, dl_server, url as _url
@@ -76,7 +76,7 @@ def test_hash_mismatch_raises_and_deletes_part(dl_server, tmp_path):
with pytest.raises(HashError):
dl.run()
assert not dest.exists()
- assert list(partials.iterdir()) == [] # .part + .ranges both deleted
+ assert not [path for path in partials.iterdir() if path.name != ".locks"] # .part + .ranges both deleted
def test_no_hash_accepts_any_bytes_of_right_size(dl_server, tmp_path):
@@ -122,7 +122,10 @@ def test_resume_after_crash_reads_sidecar(dl_server, tmp_path):
partials.mkdir()
key = hashlib.sha256(_url(dl_server, "/c").encode("utf-8")).hexdigest()
(partials / f"{key}.part").write_bytes(payload[: 1 << 20])
- (partials / f"{key}.ranges").write_text(json.dumps([[0, 1 << 20]]))
+ (partials / f"{key}.ranges").write_text(json.dumps({
+ "total": len(payload), "etag": '"' + _sha(payload) + '"',
+ "sha256": _sha(payload), "ranges": [[0, 1 << 20]],
+ }), encoding="utf-8")
dl = Download([Source(_url(dl_server, "/c"), dest, _sha(payload))],
partials_dir=partials)
dl.run()
@@ -141,7 +144,7 @@ def test_partials_never_in_scratch_or_dest(dl_server, tmp_path):
# dest is the only file in its dir; partials dir is empty after mv.
# (The test harness may drop its own marker dir into tmp_path.)
assert dest.exists()
- assert list(partials.iterdir()) == []
+ assert not [path for path in partials.iterdir() if path.name != ".locks"]
assert not [p for p in tmp_path.iterdir()
if p.suffix in (".part", ".ranges")]
@@ -398,31 +401,3 @@ def test_pause_mid_plan_resumes_to_completion(dl_server, tmp_path):
dl.run()
assert da.read_bytes() == p_a
assert db.read_bytes() == p_b
-
-
-def test_gc_protected_names_live_partial(tmp_path):
- """gc protection: entries touched inside the grace window are live."""
- import os
-
- partials = tmp_path / "partials"
- partials.mkdir()
- (partials / "abc.part").write_bytes(b"p")
- (partials / "abc.ranges").write_text("[]")
- (partials / "old.part").write_bytes(b"p")
- # Backdate the stale entry beyond any plausible grace window.
- old = time.time() - 10 * 24 * 3600
- os.utime(partials / "old.part", (old, old))
-
- protected = gc_protected_names(partials)
- assert "abc.part" in protected
- assert "abc.ranges" in protected # either half protects the pair
- assert "old.part" not in protected
-
- # Filesystem timestamps can be slightly ahead of the wall clock.
- future = time.time() + 60
- os.utime(partials / "abc.part", (future, future))
- assert gc_protected_names(partials, grace_seconds=0) == set()
-
-
-def test_gc_protected_names_missing_dir(tmp_path):
- assert gc_protected_names(tmp_path / "nope") == set()
diff --git a/tests/pm/test_downloader_integrity.py b/tests/pm/test_downloader_integrity.py
new file mode 100644
index 00000000000..9b58460cef6
--- /dev/null
+++ b/tests/pm/test_downloader_integrity.py
@@ -0,0 +1,307 @@
+"""Every ranged worker must prove which representation and bytes it received."""
+from __future__ import annotations
+
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import re
+from threading import Thread
+
+import pytest
+
+from pm.downloader import Download, DownloadError, Source
+from tests.pm._range_server import dl_server # noqa: F401 — fixture
+
+
[email protected]("reply", ["whole-body", "wrong-bounds", "changed-size", "changed-etag", "short-body"])
+def test_invalid_worker_response_cannot_publish(reply, tmp_path):
+ payload = bytes(range(256)) * (12 * 1024)
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ bounds = self.headers.get("Range")
+ if bounds == "bytes=0-0":
+ status, content_range, body = 206, f"bytes 0-0/{len(payload)}", payload[:1]
+ else:
+ start, end = map(int, re.fullmatch(r"bytes=(\d+)-(\d+)", bounds).groups())
+ status, total, reported_start = 206, len(payload), start
+ body = payload[start:end + 1]
+ if reply == "whole-body":
+ status, body = 200, payload
+ elif reply == "wrong-bounds":
+ reported_start += 1
+ elif reply == "changed-size":
+ total += 1
+ elif reply == "short-body":
+ body = body[:-1]
+ content_range = f"bytes {reported_start}-{end}/{total}"
+ self.send_response(status)
+ self.send_header("Content-Range", content_range)
+ self.send_header("Content-Length", str(len(body)))
+ etag = '"new"' if reply == "changed-etag" and bounds != "bytes=0-0" else '"original"'
+ self.send_header("ETag", etag)
+ self.end_headers()
+ try:
+ self.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError):
+ pass # The client correctly refuses headers before reading this body.
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.daemon_threads = True
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ destination = tmp_path / "model.gguf"
+ try:
+ source = Source(f"http://127.0.0.1:{server.server_port}/model", destination)
+ with pytest.raises(DownloadError):
+ Download([source], partials_dir=tmp_path / "partials", connections=1).run()
+ assert not destination.exists()
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
[email protected]("previous", [None, b"previous complete model"])
+def test_failed_cross_volume_publication_keeps_destination_atomic(tmp_path, monkeypatch, previous):
+ import errno
+ import os
+ from pathlib import Path
+ import shutil
+
+ part = tmp_path / "partials" / "model.part"
+ part.parent.mkdir()
+ payload = b"new complete model bytes"
+ part.write_bytes(payload)
+ side = part.with_suffix(".ranges")
+ side.write_text("[]", encoding="utf-8")
+ destination = tmp_path / "other-volume" / "model.gguf"
+ destination.parent.mkdir()
+ if previous is not None:
+ destination.write_bytes(previous)
+ source = Source("https://example.invalid/model", destination)
+ download = Download([source], partials_dir=part.parent)
+
+ original_rename = os.rename
+
+ def cross_device(src, dst, *args, **kwargs):
+ if Path(src) == part:
+ raise OSError(errno.EXDEV, "cross-volume fixture")
+ return original_rename(src, dst, *args, **kwargs)
+
+ def interrupted_copy(src, dst, *args, **kwargs):
+ Path(dst).write_bytes(Path(src).read_bytes()[:4])
+ raise OSError(errno.ENOSPC, "destination full")
+
+ def interrupted_stream(src, dst, *args, **kwargs):
+ dst.write(src.read(4))
+ raise OSError(errno.ENOSPC, "destination full")
+
+ monkeypatch.setattr(os, "rename", cross_device)
+ monkeypatch.setattr(shutil.move, "__defaults__", (interrupted_copy,))
+ monkeypatch.setattr(shutil, "copyfileobj", interrupted_stream)
+ with pytest.raises(OSError, match="destination full"):
+ download._finalize(source, part, side)
+
+ assert (destination.read_bytes() if destination.exists() else None) == previous
+ assert part.read_bytes() == payload
+ assert side.exists()
+ assert set(destination.parent.iterdir()) == ({destination} if previous is not None else set())
+
+
+def test_fragmented_resume_obeys_connection_limit(tmp_path):
+ import hashlib
+ import json
+ from threading import Event, Lock
+ import time
+
+ payload = bytes(range(256)) * 16
+ entered = Event()
+ release = Event()
+ lock = Lock()
+ active = 0
+ maximum = 0
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ nonlocal active, maximum
+ start, end = map(int, re.fullmatch(r"bytes=(\d+)-(\d+)", self.headers["Range"]).groups())
+ is_probe = (start, end) == (0, 0)
+ self.send_response(206)
+ self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
+ self.send_header("Content-Length", str(end - start + 1))
+ self.send_header("ETag", '"same-object"')
+ self.end_headers()
+ if not is_probe:
+ with lock:
+ active += 1
+ maximum = max(maximum, active)
+ entered.set()
+ release.wait(timeout=8)
+ try:
+ self.wfile.write(payload[start:end + 1])
+ finally:
+ if not is_probe:
+ with lock:
+ active -= 1
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.daemon_threads = True
+ serving = Thread(target=server.serve_forever, daemon=True)
+ serving.start()
+ url = f"http://127.0.0.1:{server.server_port}/fragmented"
+ partials = tmp_path / "partials"
+ partials.mkdir()
+ key = hashlib.sha256(url.encode()).hexdigest()
+ (partials / f"{key}.part").write_bytes(payload)
+ (partials / f"{key}.ranges").write_text(json.dumps({
+ "total": len(payload), "etag": '"same-object"',
+ "sha256": hashlib.sha256(payload).hexdigest(),
+ "ranges": [[0, 512], [1024, 1536], [2048, 2560]],
+ }), encoding="utf-8")
+ source = Source(url, tmp_path / "result", hashlib.sha256(payload).hexdigest())
+ errors = []
+
+ def run():
+ try:
+ Download([source], partials_dir=partials, connections=1).run()
+ except Exception as exc:
+ errors.append(exc)
+
+ worker = Thread(target=run)
+ worker.start()
+ try:
+ assert entered.wait(timeout=8)
+ # Existing scheduler launches every gap. Leave the response pending
+ # while its sibling sockets enter the real server.
+ time.sleep(2)
+ finally:
+ release.set()
+ worker.join(timeout=15)
+ server.shutdown()
+ server.server_close()
+ serving.join(timeout=5)
+ assert not worker.is_alive() and not errors, errors
+ assert source.dest.read_bytes() == payload
+ assert maximum == 1
+
+
+def test_processes_share_partial_ownership_without_losing_destinations(tmp_path):
+ import os
+ from pathlib import Path
+ import subprocess
+ import sys
+ from threading import Event, Lock
+
+ payload = bytes(range(256)) * (4096 * 2)
+ entered = Event()
+ both = Event()
+ release = Event()
+ lock = Lock()
+ active = 0
+ maximum = 0
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ nonlocal active, maximum
+ start, end = map(int, re.fullmatch(r"bytes=(\d+)-(\d+)", self.headers["Range"]).groups())
+ probe = (start, end) == (0, 0)
+ self.send_response(206)
+ self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
+ self.send_header("Content-Length", str(end - start + 1))
+ self.send_header("ETag", '"unchanged"')
+ self.end_headers()
+ if not probe:
+ with lock:
+ active += 1
+ maximum = max(maximum, active)
+ entered.set()
+ if active > 1:
+ both.set()
+ release.wait(timeout=15)
+ try:
+ self.wfile.write(payload[start:end + 1])
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ finally:
+ if not probe:
+ with lock:
+ active -= 1
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.daemon_threads = True
+ serving = Thread(target=server.serve_forever, daemon=True)
+ serving.start()
+ script = (
+ "from pathlib import Path\nimport sys\nfrom pm.downloader import Download, Source\n"
+ "url,destination,partials = sys.argv[1:]\n"
+ "Download([Source(url,Path(destination))],partials_dir=Path(partials),connections=1).run()\n"
+ )
+ env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[2])}
+ children = []
+ destinations = [tmp_path / "first" / "model", tmp_path / "second" / "model"]
+ try:
+ for destination in destinations:
+ children.append(subprocess.Popen(
+ [sys.executable, "-c", script, f"http://127.0.0.1:{server.server_port}/model",
+ str(destination), str(tmp_path / "partials")],
+ cwd=tmp_path, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, encoding="utf-8",
+ ))
+ assert entered.wait(timeout=10)
+ both.wait(timeout=2)
+ finally:
+ release.set()
+ results = []
+ for child in children:
+ try:
+ output, error = child.communicate(timeout=25)
+ except subprocess.TimeoutExpired:
+ child.kill()
+ output, error = child.communicate(timeout=5)
+ results.append((child.returncode, output, error))
+ server.shutdown()
+ server.server_close()
+ serving.join(timeout=5)
+ assert all(code == 0 for code, _, _ in results), results
+ assert [destination.read_bytes() for destination in destinations] == [payload, payload]
+ assert maximum == 1, "two processes wrote one partial concurrently"
+
+
[email protected]("damage", ["changed-etag", "missing-part", "invalid-bounds", "no-validator"])
+def test_resume_never_trusts_unbound_coverage(tmp_path, dl_server, damage):
+ import hashlib
+ import json
+ from tests.pm._range_server import RangeHandler, url
+
+ payload = b"new remote data" * 1000
+ RangeHandler.payloads["/fresh"] = payload
+ source_url = url(dl_server, "/fresh")
+ key = hashlib.sha256(source_url.encode()).hexdigest()
+ partials = tmp_path / "partials"
+ partials.mkdir()
+ part = partials / f"{key}.part"
+ if damage != "missing-part":
+ part.write_bytes(b"x" * len(payload))
+ etag = '"' + hashlib.sha256(payload).hexdigest() + '"'
+ if damage == "changed-etag":
+ etag = '"previous-object"'
+ if damage == "no-validator":
+ etag = ""
+ RangeHandler.etags = False
+ ranges = [[0, len(payload)]] if damage != "invalid-bounds" else [[-1, len(payload)]]
+ (partials / f"{key}.ranges").write_text(json.dumps({
+ "total": len(payload), "etag": etag, "sha256": "", "ranges": ranges,
+ }), encoding="utf-8")
+
+ destination = tmp_path / "model"
+ Download([Source(source_url, destination)], partials_dir=partials).run()
+
+ assert destination.read_bytes() == payload
diff --git a/tests/pm/test_features.py b/tests/pm/test_features.py
index d80c245b96e..a347d46c050 100644
--- a/tests/pm/test_features.py
+++ b/tests/pm/test_features.py
@@ -19,12 +19,7 @@ def rooted(tmp_path, monkeypatch):
"""Point features_path at a temp runtime dir (store_root().parent)."""
store = tmp_path / "tools"
store.mkdir()
- monkeypatch.setattr(
- feats,
- "features_path",
- lambda base=None: (base if base is not None else store.parent)
- / feats.FEATURES_FILENAME,
- )
+ monkeypatch.setattr("pm.paths.store_root", lambda: store)
return tmp_path
diff --git a/tests/pm/test_plugins_state.py b/tests/pm/test_plugins_state.py
index f541891cd0d..48a068f88f8 100644
--- a/tests/pm/test_plugins_state.py
+++ b/tests/pm/test_plugins_state.py
@@ -50,6 +50,38 @@ def test_enabled_plugins_ordered_reads_all_homes(homes):
assert by_root.get(profile_home / "plugins") == ["c-plug"]
[email protected]("boundary", ["profile-listing", "profile-stat", "config-read", "plugin-stat", "manifest-read", "provider-stat"])
+def test_unreadable_profile_state_is_not_an_empty_selection(homes, monkeypatch, boundary):
+ from pm.workspace import enabled_member_dirs
+
+ default_home, profile_home = homes
+ _write_config(profile_home, ["keep-plug"])
+ plugin = profile_home / "plugins" / "keep-plug"
+ plugin.mkdir(parents=True)
+ manifest = plugin / "plugin.yaml"
+ manifest.write_text("python_dependencies: [fixture-dep]\n", encoding="utf-8")
+ if boundary == "provider-stat":
+ (profile_home / "config.yaml").write_text("memory:\n provider: keep-plug\n", encoding="utf-8")
+ method, target = {
+ "profile-listing": ("iterdir", profile_home.parent),
+ "profile-stat": ("stat", profile_home),
+ "config-read": ("read_text", profile_home / "config.yaml"),
+ "plugin-stat": ("stat", plugin),
+ "manifest-read": ("read_text", manifest),
+ "provider-stat": ("stat", plugin),
+ }[boundary]
+ original = getattr(Path, method)
+
+ def unreadable(path, *args, **kwargs):
+ if path == target:
+ raise PermissionError("access denied by fixture")
+ return original(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, method, unreadable)
+ with pytest.raises(ValueError, match=re.escape(str(target))):
+ enabled_member_dirs()
+
+
def test_missing_config_parser_is_not_an_empty_plugin_selection(homes, monkeypatch):
import sys
@@ -94,9 +126,21 @@ def test_disable_plugins_noop_when_not_enabled(homes):
assert by_root[default_home / "plugins"] == ["keep-plug"]
-def test_enabled_read_survives_garbage_config(homes):
[email protected]("content", ["{ not yaml", "[]", "plugins: wrong", "plugins:\n enabled: wrong", "memory: wrong"])
+def test_enabled_read_refuses_invalid_existing_config(homes, content):
+ default_home, _ = homes
+ config = default_home / "config.yaml"
+ config.write_text(content, encoding="utf-8")
+ before = config.read_bytes()
+ with pytest.raises(ValueError, match=re.escape(str(config))):
+ pstate.enabled_plugins_ordered()
+ assert config.read_bytes() == before
+
+
[email protected]("content", ["", "# empty config\n", "null", "{}", "plugins: {}", "plugins:\n enabled: []"])
+def test_empty_config_is_an_explicit_empty_selection(homes, content):
default_home, _ = homes
- (default_home / "config.yaml").write_text("{ not yaml", encoding="utf-8")
+ (default_home / "config.yaml").write_text(content, encoding="utf-8")
assert pstate.enabled_plugins_ordered() == {}
diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.py
index 7a85b53789b..3e042a1e024 100644
--- a/tests/pm/test_pm_core.py
+++ b/tests/pm/test_pm_core.py
@@ -713,10 +713,14 @@ def test_arch_guard_allows_emulated_x64_on_win32_arm64(monkeypatch, tmp_path):
bin_dir.mkdir(parents=True)
# A real x64 PE header (MZ + PE sig + machine 0x8664).
x64_pe = (
- b"MZ" + b"\0" * 58 + (0x80).to_bytes(4, "little")
+ b"MZ" + b"\0" * 58 + (0x80).to_bytes(4, "little") + b"\0" * 64
+ b"PE\0\0" + (0x8664).to_bytes(2, "little") + b"\0" * 54
)
- (bin_dir / "agent-browser-win32-x64.exe").write_bytes(x64_pe)
+ binary = bin_dir / "agent-browser-win32-x64.exe"
+ binary.write_bytes(x64_pe)
+ from pm.package import machine_matches_binary
+
+ assert machine_matches_binary(binary, "win32-arm64") is False
lock = Lockfile(tmp_path / "lock.json")
lock.set_pin("agent-browser", "0.35.1", {"any": {"url": "x", "sha256": "0" * 64}})
diff --git a/tests/pm/test_recovery.py b/tests/pm/test_recovery.py
index 3426c752a22..4421ac489b7 100644
--- a/tests/pm/test_recovery.py
+++ b/tests/pm/test_recovery.py
@@ -114,3 +114,76 @@ def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, m
assert Path(new_fact["resolved_lock"]).read_bytes() == old_lock
assert old.is_dir() and not (site_packages(old) / "plugin_dep").exists()
assert config.read_bytes() == config_before
+
+
+def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_path, monkeypatch):
+ import pm.paths as paths
+ from hermes_cli.plugins_admission import AdmissionRefused, admit_plugin_set_change
+ from hermes_cli.runtime_paths import install_state_dir, selected_venv, site_packages
+
+ engine = importlib.import_module("pm.ensure")
+ uv = shutil.which("uv")
+ assert uv
+ core = tmp_path / "core"
+ core.mkdir()
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ _wheel(wheels, "core_dep", "1.0")
+ _wheel(wheels, "plugin_dep", "1.0")
+ (core / "pyproject.toml").write_text(
+ '[project]\nname="uncertain-core"\nversion="1"\nrequires-python=">=3.11"\n'
+ 'dependencies=["core-dep==1.0"]\n[tool.uv]\npackage=false\nno-index=true\n'
+ f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8",
+ )
+ home = tmp_path / "home"
+ sibling = home / "profiles" / "worker"
+ plugin = sibling / "plugins" / "worker-deps"
+ plugin.mkdir(parents=True)
+ (plugin / "pyproject.toml").write_text(
+ '[project]\nname="worker-deps"\nversion="1"\nrequires-python=">=3.11"\n'
+ 'dependencies=["plugin-dep==1.0"]\n[tool.uv]\npackage=false\n', encoding="utf-8",
+ )
+ active_config = home / "config.yaml"
+ active_config.write_text("plugins:\n enabled: []\n", encoding="utf-8")
+ sibling_config = sibling / "config.yaml"
+ sibling_config.write_text("plugins:\n enabled: [worker-deps]\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(paths, "repo_root", lambda: core)
+ monkeypatch.setattr(engine, "uv", lambda **kwargs: (
+ uv, {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"},
+ ))
+ monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)
+ env = {**uv_env(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
+ env.pop("UV_NO_CONFIG")
+ subprocess.run([uv, "lock"], cwd=core, env=env, check=True, capture_output=True, timeout=60)
+ engine.sync_venv([], explicit=True)
+ old = selected_venv(core)
+ before_facts = paths.runtime_facts_path().read_bytes()
+ before_config = active_config.read_bytes()
+ before_generations = set((install_state_dir(core) / "environments").iterdir())
+ old_lock = Path(Facts(paths.runtime_facts_path()).get("venv")["resolved_lock"]).read_bytes()
+ sibling_config.write_text("plugins:\n enabled: [unclosed\n", encoding="utf-8")
+ damaged_config = sibling_config.read_bytes()
+
+ with pytest.raises(ValueError, match="config.yaml"):
+ engine.sync_venv(explicit=True)
+ with pytest.raises(AdmissionRefused, match="config.yaml"):
+ admit_plugin_set_change(set(), set(), active_plugins_dir=home / "plugins")
+ assert paths.runtime_facts_path().read_bytes() == before_facts
+ assert active_config.read_bytes() == before_config
+ assert selected_venv(core) == old
+ assert set((install_state_dir(core) / "environments").iterdir()) == before_generations
+
+ shutil.rmtree(site_packages(old) / "plugin_dep")
+ engine.sync_venv(repair=True)
+ repaired = selected_venv(core)
+ assert repaired != old
+ python = repaired / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ result = subprocess.run(
+ [str(python), "-I", "-c", "import plugin_dep; print(plugin_dep.__version__)"],
+ cwd=tmp_path, capture_output=True, text=True, check=True, timeout=30,
+ )
+ assert result.stdout.strip() == "1.0"
+ assert Path(Facts(paths.runtime_facts_path()).get("venv")["resolved_lock"]).read_bytes() == old_lock
+ assert active_config.read_bytes() == before_config
+ assert sibling_config.read_bytes() == damaged_config
diff --git a/tests/pm/test_startup_recovery.py b/tests/pm/test_startup_recovery.py
index db6e5852df1..7fd81708764 100644
--- a/tests/pm/test_startup_recovery.py
+++ b/tests/pm/test_startup_recovery.py
@@ -13,7 +13,7 @@ import pytest
from pm.lock import Facts, Lockfile
from pm.packages import uv_env
-from pm.store import current_target, tree_digest
+from pm.store import current_target, sha256_file, tree_digest
from tests.pm.test_workspace_build_inputs import _wheel
@@ -81,10 +81,19 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, m
python_entry = tools / "python"
(python_entry / "bin").mkdir(parents=True)
(python_entry / "bin/python3").symlink_to(Path(sys._base_executable).resolve())
+ from pm.registry import get_package
+
+ target = current_target()
for name, directory in (("uv", uv_entry), ("python", python_entry)):
- lock.set_pin(name, "fixture", {})
+ package = get_package(name)
+ binary = package.binary(directory, target)
+ assert not package.verify(directory, target), (
+ f"startup recovery requires native {target} tools: {binary}"
+ )
+ digest = sha256_file(binary)
+ lock.set_pin(name, "fixture", {target: {"url": binary.as_uri(), "sha256": digest}})
facts.record(name, "fixture", str(directory), {}, tools,
- target=current_target(), digest=tree_digest(directory))
+ target=target, artifacts=[digest], digest=tree_digest(directory))
lock.save()
launcher = core / "launch.py"
launcher.write_text(
diff --git a/tests/pm/test_update_auth_scope.py b/tests/pm/test_update_auth_scope.py
new file mode 100644
index 00000000000..4bec67d8604
--- /dev/null
+++ b/tests/pm/test_update_auth_scope.py
@@ -0,0 +1,77 @@
+"""Index credentials stay on their exact HTTPS origin, including redirects."""
+from __future__ import annotations
+
+from email.message import Message
+import io
+import urllib.request
+import urllib.response
+
+import pytest
+
+from pm import update
+
+
+class IndexTransport(urllib.request.HTTPHandler, urllib.request.HTTPSHandler):
+ def __init__(self, redirects=None):
+ super().__init__()
+ self.redirects = redirects or {}
+ self.sent = []
+
+ def http_open(self, request):
+ self.sent.append((request.full_url, dict(request.header_items())))
+ headers = Message()
+ destination = self.redirects.get(request.full_url)
+ if destination:
+ headers["Location"] = destination
+ response = urllib.response.addinfourl(
+ io.BytesIO(b'{}'), headers, request.full_url, 302 if destination else 200,
+ )
+ response.msg = "Found" if destination else "OK"
+ return response
+
+ https_open = http_open
+
+
[email protected]("url,token", [
+ ("https://api.github.com/repos/example/tool/releases", "dummy-gh"),
+ ("https://api.github.com:443/repos/example/tool/releases", "dummy-gh"),
+ ("https://huggingface.co/api/buckets/example/tool/tree", "dummy-hf"),
+ ("https://nodejs.org/dist/index.json", None),
+ ("https://registry.npmjs.org/npm", None),
+ ("https://evilhuggingface.co/index", None),
+ ("https://api.github.com.evil.invalid/index", None),
+ ("https://api.github.com:444/index", None),
+ ("http://api.github.com/index", None),
+])
+def test_index_credentials_match_the_exact_origin(monkeypatch, url, token):
+ transport = IndexTransport()
+ monkeypatch.setattr(urllib.request, "_opener", urllib.request.build_opener(transport))
+ monkeypatch.setenv("GH_TOKEN", "dummy-gh")
+ monkeypatch.setenv("HF_TOKEN", "dummy-hf")
+
+ assert update._get_json(url) == {}
+
+ headers = {key.lower(): value for key, value in transport.sent[-1][1].items()}
+ assert headers.get("authorization") == (f"Bearer {token}" if token else None)
+ assert headers["user-agent"] == "hermes-pm"
+
+
[email protected]("reader", [update._get_json, update._get_text], ids=["json", "text"])
[email protected]("destination,credential_survives", [
+ ("https://api.github.com/second", True),
+ ("https://unrelated.invalid/second", False),
+ ("https://api.github.com:444/second", False),
+ ("http://api.github.com/second", False),
+])
+def test_index_redirects_use_the_credential_safe_opener(monkeypatch, reader, destination, credential_survives):
+ origin = "https://api.github.com/first"
+ transport = IndexTransport({origin: destination})
+ monkeypatch.setattr(urllib.request, "_opener", urllib.request.build_opener(transport))
+ monkeypatch.setenv("GH_TOKEN", "dummy-gh")
+
+ reader(origin)
+
+ assert [url for url, _ in transport.sent] == [origin, destination]
+ initial, redirected = [{key.lower(): value for key, value in headers.items()} for _, headers in transport.sent]
+ assert initial["authorization"] == "Bearer dummy-gh"
+ assert (redirected.get("authorization") == "Bearer dummy-gh") is credential_survives
diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.py
index a2b2c6cb66d..763102f04f6 100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@ -166,7 +166,6 @@ def test_enabled_member_dirs_finds_enabled_dep_plugins(tmp_path, monkeypatch):
orphan.mkdir()
(orphan / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
- monkeypatch.setattr(ws, "_plugin_dir_roots", lambda: {plugins})
# enabled order = enable recency (legacy enabled first/older, modern
# newest LAST) — order must carry through for the bisect tiebreak.
monkeypatch.setattr(
@@ -186,7 +185,6 @@ def test_enabled_member_dirs_empty_when_nothing_enabled(tmp_path, monkeypatch):
member.mkdir()
(member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
- monkeypatch.setattr(ws, "_plugin_dir_roots", lambda: {plugins})
monkeypatch.setattr(
"pm.plugins_state.enabled_plugins_ordered", lambda: {}
)
@@ -211,25 +209,23 @@ def test_scan_plugin_classifies_dep_surfaces(tmp_path):
assert scan["legacy_deps"] and not scan["pyproject"]
-def test_enabled_member_dirs_survives_unreadable_roots(tmp_path, monkeypatch):
- # an OSError mid-scan (dangling junction etc.) must not lose other roots
- good = tmp_path / "good-plugins"
- good.mkdir()
- member = good / "member"
- member.mkdir()
- (member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+def test_enabled_member_dirs_ignores_non_profile_entries(tmp_path, monkeypatch):
+ import pm.plugins_state as pstate
- class _Broken:
- def is_dir(self):
- raise OSError("dangling junction")
-
- monkeypatch.setattr(ws, "_plugin_dir_roots", lambda: {good, _Broken()})
- monkeypatch.setattr(
- "pm.plugins_state.enabled_plugins_ordered",
- lambda: {good: ["member"]},
+ home = tmp_path / "home"
+ profiles = home / "profiles"
+ profiles.mkdir(parents=True)
+ member = profiles / "work" / "plugins" / "member"
+ member.mkdir(parents=True)
+ (member / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+ (profiles / "work" / "config.yaml").write_text(
+ "plugins:\n enabled: [member]\n", encoding="utf-8",
)
- found = ws.enabled_member_dirs()
- assert [p.name for p in found] == ["member"]
+ (profiles / "README.txt").write_text("not a profile", encoding="utf-8")
+ monkeypatch.setattr("hermes_cli.runtime_paths.dependency_home_root", lambda: home)
+
+ assert pstate._all_homes() == [home, profiles / "work"]
+ assert ws.enabled_member_dirs() == [member]
# --- classified failures + staging surface (FINAL-RUNTIME-CONTRACT) ---
diff --git a/tests/pm/test_zip_symlinks.py b/tests/pm/test_zip_symlinks.py
index 6f54888fd22..452a034e6e5 100644
--- a/tests/pm/test_zip_symlinks.py
+++ b/tests/pm/test_zip_symlinks.py
@@ -31,11 +31,6 @@ import pytest
from pm.store import extract
-posix_only = pytest.mark.skipif(
- sys.platform == "win32", reason="symlink resolution semantics are POSIX"
-)
-
-
def _add_symlink(zf: zipfile.ZipFile, member: str, target: str) -> None:
"""Append a symlink entry the way zip tools actually encode one."""
info = zipfile.ZipInfo(member)
@@ -59,7 +54,7 @@ def _write_zip(path: Path, build) -> Path:
return path
-@posix_only
def test_framework_shaped_links_round_trip(tmp_path: Path) -> None:
"""The CfT .framework shape: links out of the versioned dir, intact."""
@@ -84,7 +79,7 @@ def test_framework_shaped_links_round_trip(tmp_path: Path) -> None:
assert (dest / "app/F.framework/Versions/A/F").stat().st_mode & 0o111
-@posix_only
def test_intree_dotdot_target_is_kept(tmp_path: Path) -> None:
"""`..` in a target is fine while it stays under dest — real layouts
(lib/foo -> ../share/foo) depend on it."""
@@ -147,7 +142,7 @@ def test_file_written_through_earlier_link_entry_cannot_escape(
assert written.is_file() and not (dest / "outdir").is_symlink()
[email protected](sys.platform != "win32", reason="pins the win32 degradation")
def test_win32_safe_link_degrades_without_escaping(tmp_path: Path) -> None:
"""On win32 pm attempts a real symlink (works with Developer Mode /
admin) and otherwise degrades to a text placeholder holding the
diff --git a/tests/scripts/test_mint_launchers.py b/tests/scripts/test_mint_launchers.py
index 1527cbe6295..346920b84d5 100644
--- a/tests/scripts/test_mint_launchers.py
+++ b/tests/scripts/test_mint_launchers.py
@@ -11,8 +11,8 @@ experiments proved it once; these tests keep proving it on every run):
dispatches to the entry module with argv forwarded and the exit code
returned.
-Skipped off-windows (POSIX payloads ship $0-relative bash trampolines
-instead) and when neither distlib nor pip is importable.
+Runs on Windows with the locked ``test`` dependency group. POSIX payloads
+use $0-relative bash trampolines instead.
"""
from __future__ import annotations
@@ -34,21 +34,6 @@ pytestmark = [
]
-def _distlib_available() -> bool:
- try:
- import distlib.scripts # noqa: F401
- return True
- except ImportError:
- try:
- from pip._vendor import distlib # noqa: F401
- return True
- except ImportError:
- return False
-
-
-pytestmark.append(pytest.mark.skipif(not _distlib_available(), reason="no distlib (nor pip's vendored copy)"))
-
-
@pytest.fixture()
def payload_tree(tmp_path: Path):
"""A miniature payload: bin/, repo snapshot with a stub hermes_cli,
@@ -82,7 +67,8 @@ def payload_tree(tmp_path: Path):
# Exercise the real bootstrap before the fixture entry point.
for relative in ("hermes_bootstrap.py", "hermes_constants.py", "hermes_cli/__init__.py",
- "hermes_cli/runtime_paths.py", "hermes_cli/runtime_state.py"):
+ "hermes_cli/runtime_paths.py", "hermes_cli/runtime_state.py",
+ "hermes_cli/_early_recovery.py", "hermes_cli/_parser.py"):
shutil.copy2(_REPO / relative, repo / relative)
(repo / "hermes_cli" / "main.py").write_text(
"import os, sys\n"
diff --git a/tests/scripts/test_setup_toolchain.py b/tests/scripts/test_setup_toolchain.py
index b2d2469ce1b..8ade61c765c 100644
--- a/tests/scripts/test_setup_toolchain.py
+++ b/tests/scripts/test_setup_toolchain.py
@@ -14,6 +14,57 @@ from pm.paths import lockfile_path
from pm.store import current_target
[email protected]("extras", [[], ["dev"]], ids=["runtime", "tests"])
+def test_development_setup_keeps_test_groups_out_of_the_runtime(tmp_path, monkeypatch, extras):
+ from types import SimpleNamespace
+ import shutil
+
+ from scripts.ci import setup_toolchain
+ from pm.packages import uv_env
+ from tests.pm.test_workspace_build_inputs import _wheel
+
+ core = tmp_path / "core"
+ core.mkdir()
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ _wheel(wheels, "test_only_dep", "1.0")
+ (core / "pyproject.toml").write_text(
+ '[project]\nname="ci-test-environment"\nversion="1"\nrequires-python=">=3.11"\n'
+ '[project.optional-dependencies]\ndev=[]\n'
+ '[dependency-groups]\ntest=["test-only-dep==1.0"]\n'
+ '[tool.uv]\npackage=false\nno-index=true\n'
+ f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8",
+ )
+ uv = shutil.which("uv")
+ assert uv
+ environment = {**uv_env(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
+ environment.pop("UV_NO_CONFIG")
+ subprocess.run([uv, "lock"], cwd=core, env=environment, check=True, capture_output=True, timeout=60)
+ home = tmp_path / "ci-home"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr("pm.paths.repo_root", lambda: core)
+ import importlib
+ engine = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(engine, "uv", lambda **kwargs: (uv, dict(environment)))
+ files = {name: tmp_path / name for name in ("GITHUB_ENV", "GITHUB_OUTPUT", "GITHUB_PATH")}
+ for name, file in files.items():
+ monkeypatch.setenv(name, str(file))
+
+ setup_toolchain.dependencies(SimpleNamespace(extras=extras, home=home))
+
+ outputs = dict(line.split("=", 1) for line in files["GITHUB_OUTPUT"].read_text(encoding="utf-8").splitlines())
+ result = subprocess.run(
+ [outputs["python-path"], "-I", "-c", "import importlib.util; print(importlib.util.find_spec('test_only_dep') is not None)"],
+ cwd=tmp_path, capture_output=True, text=True, timeout=30,
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == str("dev" in extras)
+ assert Path(outputs["venv"]).is_relative_to(home)
+ assert not (core / ".venv").exists()
+ from hermes_cli.runtime_paths import runtime_facts_path
+ assert runtime_facts_path(core).exists() == ("dev" not in extras)
+
+
@pytest.mark.parametrize("toolchain,names", [
("python", {"python", "uv"}),
("node", {"node", "npm"}),
diff --git a/tests/tools/test_checkpoint_manager.py b/tests/tools/test_checkpoint_manager.py
index aad32bf74fc..915e01bae20 100644
--- a/tests/tools/test_checkpoint_manager.py
+++ b/tests/tools/test_checkpoint_manager.py
@@ -53,6 +53,7 @@ def fake_home(tmp_path, monkeypatch):
home = tmp_path / "home"
home.mkdir()
monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("HERMES_HOME", str(home / ".hermes"))
monkeypatch.setenv("USERPROFILE", str(home))
monkeypatch.delenv("HOMEDRIVE", raising=False)
monkeypatch.delenv("HOMEPATH", raising=False)
@@ -578,6 +579,19 @@ class TestSafeRestore:
# =========================================================================
class TestWorkingDirResolution:
+ def test_registered_project_owns_writes_even_below_an_ancestor_marker(self, mgr, work_dir):
+ (work_dir.parent / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+ assert mgr.ensure_checkpoint(str(work_dir), "original")
+ checkpoint = mgr.list_checkpoints(str(work_dir))[0]["hash"]
+ target = work_dir / "main.py"
+ target.write_text("agent\n", encoding="utf-8")
+ mgr.record_agent_write(str(target))
+ target.write_text("user\n", encoding="utf-8")
+ result = mgr.restore(str(work_dir), checkpoint, safe=True)
+ assert result["success"]
+ assert target.read_text(encoding="utf-8") == "user\n"
+ assert mgr.get_working_dir_for_path(str(target)) == str(work_dir)
+
def test_resolves_project_root_markers(self, tmp_path, fake_home):
m = CheckpointManager(enabled=True)
@@ -598,28 +612,12 @@ class TestWorkingDirResolution:
f"~/{py_proj.name}/src/file.py"
) == str(py_proj)
- def test_falls_back_to_parent(self, tmp_path, monkeypatch):
+ def test_falls_back_to_parent(self, fake_home):
m = CheckpointManager(enabled=True)
- filepath = tmp_path / "random" / "file.py"
+ filepath = fake_home / "random" / "file.py"
filepath.parent.mkdir(parents=True)
- filepath.write_text("x\n")
-
- import pathlib as _pl
- _real_exists = _pl.Path.exists
-
- def _guarded_exists(self):
- s = str(self)
- stop = str(tmp_path)
- if not s.startswith(stop) and any(
- s.endswith("/" + m) or s == "/" + m
- for m in (".git", "pyproject.toml", "package.json",
- "Cargo.toml", "go.mod", "Makefile", "pom.xml",
- ".hg", "Gemfile")
- ):
- return False
- return _real_exists(self)
-
- monkeypatch.setattr(_pl.Path, "exists", _guarded_exists)
+ filepath.write_text("x\n", encoding="utf-8")
+ (fake_home / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
assert m.get_working_dir_for_path(str(filepath)) == str(filepath.parent)
diff --git a/tests/tools/test_checkpoint_size_cap.py b/tests/tools/test_checkpoint_size_cap.py
new file mode 100644
index 00000000000..06f113956fc
--- /dev/null
+++ b/tests/tools/test_checkpoint_size_cap.py
@@ -0,0 +1,132 @@
+"""Real history retention and failure propagation at the public pruning callers."""
+from __future__ import annotations
+
+import os
+
+import pytest
+
+from tools import checkpoint_manager as checkpoints
+
+
+def history(tmp_path, monkeypatch):
+ base = tmp_path / "checkpoints"
+ monkeypatch.setattr(checkpoints, "CHECKPOINT_BASE", base)
+ project = min((tmp_path / name for name in ("project-a", "project-b")),
+ key=lambda path: checkpoints._project_hash(str(path)))
+ project.mkdir()
+ manager = checkpoints.CheckpointManager(enabled=True, max_total_size_mb=0)
+ blob = project / "old.bin"
+ blob.write_bytes(os.urandom(1_300_000))
+ assert manager.ensure_checkpoint(str(project), "large-oldest")
+ blob.unlink()
+ for index in range(5):
+ (project / "small.txt").write_text(str(index), encoding="utf-8")
+ manager.new_turn()
+ assert manager.ensure_checkpoint(str(project), f"small-{index}")
+ return base, project, manager
+
+
[email protected]("entry", ["maintenance", "snapshot"])
+def test_size_cap_retains_every_snapshot_after_the_only_large_one(history, entry):
+ base, project, manager = history
+ store = checkpoints._store_path(base)
+ assert checkpoints._dir_size_bytes(store) > 1024 * 1024
+ expected = [f"small-{index}" for index in reversed(range(5))]
+ if entry == "maintenance":
+ result = checkpoints.prune_checkpoints(retention_days=0, checkpoint_base=base, max_total_size_mb=1)
+ assert result["errors"] == 0
+ else:
+ manager.max_total_size_mb = 1
+ (project / "new.txt").write_text("new snapshot", encoding="utf-8")
+ manager.new_turn()
+ assert manager.ensure_checkpoint(str(project), "newest")
+ expected.insert(0, "newest")
+ assert [row["reason"] for row in manager.list_checkpoints(str(project))] == expected
+ assert checkpoints._dir_size_bytes(store) <= 1024 * 1024
+ assert (project / "small.txt").read_text(encoding="utf-8") == "4"
+
+
+def test_reclaim_stops_before_touching_another_projects_history(history):
+ base, first, manager = history
+ # Real ref sorting chooses the first victim. Pick the other project so
+ # this is a discriminating reclaim-before-next-project assertion.
+ other = next(first.parent / name for name in ("project-a", "project-b") if first.name != name)
+ other.mkdir()
+ for index in range(3):
+ (other / "small.txt").write_text(str(index), encoding="utf-8")
+ manager.new_turn()
+ assert manager.ensure_checkpoint(str(other), f"other-{index}")
+ before = manager.list_checkpoints(str(other))
+ result = checkpoints.prune_checkpoints(retention_days=0, checkpoint_base=base, max_total_size_mb=1)
+ assert result["errors"] == 0
+ assert manager.list_checkpoints(str(other)) == before
+ assert len(manager.list_checkpoints(str(first))) == 5
+
+
[email protected]("failure", ["gc", "reflog", "for-each-ref", "rev-list", "log", "update-ref", "delete-ref"])
+def test_maintenance_stops_on_failed_git_without_losing_a_second_snapshot(history, monkeypatch, failure):
+ import json
+
+ base, project, manager = history
+ original = checkpoints._run_git
+ rewrites = []
+ retention = 0
+ if failure == "delete-ref":
+ meta = checkpoints._project_meta_path(checkpoints._store_path(base), checkpoints._project_hash(str(project)))
+ state = json.loads(meta.read_text(encoding="utf-8"))
+ state["last_touch"] = 1
+ meta.write_text(json.dumps(state), encoding="utf-8")
+ retention = 1
+
+ def fail_one(args, *rest, **kwargs):
+ if args[0] == failure or (failure == "delete-ref" and args[:2] == ["update-ref", "-d"]):
+ return False, "", "injected Git failure"
+ result = original(args, *rest, **kwargs)
+ if args[0] == "update-ref" and result[0]:
+ rewrites.append(args)
+ return result
+
+ with monkeypatch.context() as patcher:
+ patcher.setattr(checkpoints, "_run_git", fail_one)
+ result = checkpoints.prune_checkpoints(retention_days=retention, checkpoint_base=base, max_total_size_mb=1)
+ assert result["errors"] > 0
+ assert len(rewrites) <= 1
+ assert len(manager.list_checkpoints(str(project))) >= 5
+ if failure == "delete-ref":
+ assert meta.is_file()
+ assert result["deleted_stale"] == 0
+
+
+def test_snapshot_pruning_does_not_enter_size_pass_after_failed_count_reclaim(history, monkeypatch, caplog):
+ _, project, manager = history
+ manager.max_snapshots = 5
+ manager.max_total_size_mb = 1
+ (project / "later.txt").write_text("newest", encoding="utf-8")
+ manager.new_turn()
+ original = checkpoints._run_git
+ changed_refs = []
+
+ def refuse_gc(args, *rest, **kwargs):
+ if args[0] == "gc":
+ return False, "", "injected reclamation failure"
+ result = original(args, *rest, **kwargs)
+ if args[0] == "update-ref" and result[0]:
+ changed_refs.append(args)
+ return result
+
+ monkeypatch.setattr(checkpoints, "_run_git", refuse_gc)
+ assert manager.ensure_checkpoint(str(project), "latest")
+ assert len(changed_refs) == 2 # The new checkpoint plus one count trim.
+ assert "injected reclamation failure" in caplog.text
+ assert len(manager.list_checkpoints(str(project))) == 5
+
+
+def test_restore_keeps_its_target_alive_while_taking_the_safety_snapshot(history):
+ _, project, manager = history
+ target = manager.list_checkpoints(str(project))[-1]["hash"]
+ manager.max_snapshots = 1
+ (project / "small.txt").write_text("changed before restore", encoding="utf-8")
+ result = manager.restore(str(project), target)
+ assert result["success"], result
+ assert (project / "old.bin").stat().st_size == 1_300_000
diff --git a/tests/tools/test_checkpoint_store_ownership.py b/tests/tools/test_checkpoint_store_ownership.py
new file mode 100644
index 00000000000..458983cb965
--- /dev/null
+++ b/tests/tools/test_checkpoint_store_ownership.py
@@ -0,0 +1,55 @@
+"""Maintenance cannot prune objects another checkpoint process has not published."""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from queue import Queue
+import subprocess
+import sys
+from threading import Thread
+
+from tools import checkpoint_manager as checkpoints
+
+
+def test_active_snapshot_owns_store_until_its_ref_is_published(tmp_path, monkeypatch):
+ base = tmp_path / "checkpoints"
+ monkeypatch.setattr(checkpoints, "CHECKPOINT_BASE", base)
+ project = tmp_path / "project"
+ project.mkdir()
+ (project / "initial.txt").write_text("initial", encoding="utf-8")
+ manager = checkpoints.CheckpointManager(enabled=True, max_total_size_mb=0)
+ assert manager.ensure_checkpoint(str(project), "initial")
+ (project / "concurrent.txt").write_text("new unpublished bytes", encoding="utf-8")
+ program = '''
+import sys
+from pathlib import Path
+from tools import checkpoint_manager as c
+c.CHECKPOINT_BASE = Path(sys.argv[1])
+c._managed_git = lambda: None
+run = c._run_git
+def paused(args, *rest, **kwargs):
+ result = run(args, *rest, **kwargs)
+ if args[0] == "write-tree" and result[0]:
+ print("tree-written", flush=True)
+ sys.stdin.readline()
+ return result
+c._run_git = paused
+assert c.CheckpointManager(enabled=True, max_total_size_mb=0).ensure_checkpoint(sys.argv[2], "concurrent")
+'''
+ env = {**os.environ, "PYTHONPATH": str(Path(checkpoints.__file__).resolve().parents[1])}
+ child = subprocess.Popen([sys.executable, "-u", "-c", program, str(base), str(project)],
+ cwd=tmp_path, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True, encoding="utf-8")
+ ready = Queue()
+ reader = Thread(target=lambda: ready.put(child.stdout.readline()), daemon=True)
+ reader.start()
+ try:
+ assert ready.get(timeout=20).strip() == "tree-written"
+ result = checkpoints.prune_checkpoints(retention_days=0, checkpoint_base=base)
+ assert result["errors"] > 0, "maintenance must refuse an active store writer"
+ assert not checkpoints.clear_all(base)["deleted"]
+ finally:
+ output, error = child.communicate(input="publish\n", timeout=30)
+ reader.join(timeout=5)
+ assert child.returncode == 0, output + error
+ assert [row["reason"] for row in manager.list_checkpoints(str(project))] == ["concurrent", "initial"]
diff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.py
index 742032fa921..eb76d268190 100644
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@ -214,17 +214,6 @@ def _store_path(base: Optional[Path] = None) -> Path:
return (base or CHECKPOINT_BASE) / _STORE_DIRNAME
-def _shadow_repo_path(working_dir: str) -> Path: # pragma: no cover — kept for BC
- """Return the shared store path.
-
- Retained for backward-compatibility with callers / tests that imported
- this helper. Under v2 the shadow git storage is shared across all
- projects — per-project isolation lives in refs and indexes, not in
- separate repo directories.
- """
- return _store_path()
-
-
def _index_path(store: Path, dir_hash: str) -> Path:
return store / _INDEXES_DIRNAME / dir_hash
@@ -358,28 +347,6 @@ def _git_env(
return env
-def _repair_bare_repo_dirs(store: Path) -> None:
- """Recreate refs/ and branches/ dirs that ``git gc`` may have removed.
-
- ``git gc --prune=now`` on a bare repo with only packed refs can remove
- the empty ``refs/heads/`` directory. Git 2.34+ requires ``refs/`` (and
- some versions require ``branches/``) to exist even when all refs are
- packed in ``packed-refs``. Without them, ``git add -A`` returns
- ``fatal: not a git repository`` and all checkpoint operations fail
- silently.
- """
- for subdir in ("refs/heads", "branches"):
- path = store / subdir
- if not path.exists():
- try:
- path.mkdir(parents=True, exist_ok=True)
- logger.debug("Repaired missing %s in checkpoint store", subdir)
- except OSError as exc:
- logger.warning(
- "Cannot create %s in checkpoint store: %s", subdir, exc,
- )
-
-
def _run_git(
args: List[str],
store: Path,
@@ -387,6 +354,7 @@ def _run_git(
timeout: int = _GIT_TIMEOUT,
allowed_returncodes: Optional[Set[int]] = None,
index_file: Optional[Path] = None,
+ extra_env: Optional[Dict[str, str]] = None,
) -> Tuple[bool, str, str]:
"""Run a git command against the shared store. Returns (ok, stdout, stderr).
@@ -405,6 +373,8 @@ def _run_git(
return False, "", msg
env = _git_env(store, str(normalized_working_dir), index_file=index_file)
+ if extra_env:
+ env.update(extra_env)
managed = _managed_git()
if managed:
cmd, path_dirs = managed
@@ -764,34 +734,6 @@ def _dir_size_bytes(path: Path) -> int:
return total
-# Backwards-compatibility shim — some tests import ``_init_shadow_repo`` and
-# look for ``HEAD``/``info/exclude``/``HERMES_WORKDIR``. In v2 we also write
-# those markers, but inside the shared store + under ``projects/<hash>.json``.
-# The shim initialises the store and registers the project so the old
-# surface keeps roughly the same shape.
-def _init_shadow_repo(shadow_repo: Path, working_dir: str) -> Optional[str]:
- """Backwards-compatible initialiser.
-
- In v1 ``shadow_repo`` was a per-project dir; in v2 it's the shared
- ``store/`` path (or a test path that we respect). We initialise the
- store at ``shadow_repo``, create per-project markers, and return None
- on success.
- """
- err = _init_store(shadow_repo, working_dir)
- if err:
- return err
- _register_project(shadow_repo, working_dir)
- # Compat marker for tests that look at HERMES_WORKDIR
- # (write in addition to the JSON metadata).
- try:
- (shadow_repo / "HERMES_WORKDIR").write_text(
- str(_normalize_path(working_dir)) + "\n", encoding="utf-8"
- )
- except OSError:
- pass
- return None
-
-
# ---------------------------------------------------------------------------
# CheckpointManager
# ---------------------------------------------------------------------------
@@ -857,20 +799,23 @@ class CheckpointManager:
if not self.enabled:
return
try:
+ from tools.checkpoint_pruning import store_lock
+
path = _normalize_path(file_path)
digest = _hash_file(path)
if digest is None:
return
- working_dir = self.get_working_dir_for_path(str(path))
- store = _store_path(CHECKPOINT_BASE)
- dir_hash = _project_hash(working_dir)
- ledger = _load_ledger(store, dir_hash)
- ledger[str(path)] = {"sha256": digest, "ts": time.time()}
- _save_ledger(store, dir_hash, ledger)
+ with store_lock(CHECKPOINT_BASE):
+ working_dir = self.get_working_dir_for_path(str(path))
+ store = _store_path(CHECKPOINT_BASE)
+ dir_hash = _project_hash(working_dir)
+ ledger = _load_ledger(store, dir_hash)
+ ledger[str(path)] = {"sha256": digest, "ts": time.time()}
+ _save_ledger(store, dir_hash, ledger)
except Exception as exc:
logger.debug("record_agent_write failed for %s: %s", file_path, exc)
- def safe_restore_plan(self, working_dir: str, commit_hash: str) -> Dict:
+ def _safe_restore_plan(self, working_dir: str, commit_hash: str) -> Dict:
"""Classify files changed since ``commit_hash`` for a safe restore.
Returns ``{"success", "restore": [rel...], "skipped": [rel...],
@@ -963,7 +908,10 @@ class CheckpointManager:
self._checkpointed_dirs.add(abs_dir)
try:
- return self._take(abs_dir, reason)
+ from tools.checkpoint_pruning import store_lock
+
+ with store_lock(CHECKPOINT_BASE):
+ return self._take(abs_dir, reason)
except Exception as e:
logger.debug("Checkpoint failed (non-fatal): %s", e)
return False
@@ -1047,6 +995,15 @@ class CheckpointManager:
def diff(self, working_dir: str, commit_hash: str) -> Dict:
"""Show diff between a checkpoint and the current working tree."""
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
+ with store_lock(CHECKPOINT_BASE):
+ return self._diff(working_dir, commit_hash)
+ except (PruneError, OSError) as exc:
+ return {"success": False, "error": str(exc)}
+
+ def _diff(self, working_dir: str, commit_hash: str) -> Dict:
hash_err = _validate_commit_hash(commit_hash)
if hash_err:
return {"success": False, "error": hash_err}
@@ -1144,6 +1101,15 @@ class CheckpointManager:
them from every checkpoint, and — only when a delete failed —
``failed_deletes`` listing paths that could not be removed.
"""
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
+ with store_lock(CHECKPOINT_BASE):
+ return self._restore(working_dir, commit_hash, file_path, safe)
+ except (PruneError, OSError) as exc:
+ return {"success": False, "error": str(exc)}
+
+ def _restore(self, working_dir: str, commit_hash: str, file_path: str | None, safe: bool) -> Dict:
hash_err = _validate_commit_hash(commit_hash)
if hash_err:
return {"success": False, "error": hash_err}
@@ -1172,7 +1138,7 @@ class CheckpointManager:
failed_deletes: List[str] = []
restore_paths: Optional[List[str]] = None
if safe and not file_path:
- plan = self.safe_restore_plan(abs_dir, commit_hash)
+ plan = self._safe_restore_plan(abs_dir, commit_hash)
if not plan.get("success"):
return {"success": False, "error": plan.get("error", "Safe-restore plan failed")}
if plan.get("ledger_empty"):
@@ -1194,7 +1160,7 @@ class CheckpointManager:
}
# Take a pre-rollback snapshot so you can undo the undo.
- self._take(abs_dir, f"pre-rollback snapshot (restoring to {commit_hash[:8]})")
+ self._take(abs_dir, f"pre-rollback snapshot (restoring to {commit_hash[:8]})", prune=False)
dir_hash = _project_hash(abs_dir)
index_file = _index_path(store, dir_hash)
@@ -1279,6 +1245,9 @@ class CheckpointManager:
result["skipped_oversize"] = kept_oversize
if failed_deletes:
result["failed_deletes"] = failed_deletes
+ # The selected tree was needed until checkout completed. Only now may
+ # the safety snapshot's count/size budget make that tree unreachable.
+ self._prune(store, abs_dir, _ref_name(dir_hash))
return result
def get_working_dir_for_path(self, file_path: str) -> str:
@@ -1289,10 +1258,18 @@ class CheckpointManager:
else:
candidate = path.parent
+ # An explicitly checkpointed root owns its ledger even when an
+ # ancestor carries a project marker. Prefer the nearest owner.
+ roots = [Path(meta["workdir"]) for meta in _list_projects(_store_path()) if meta.get("workdir")]
+ owners = [root for root in roots if candidate.is_relative_to(root)]
+ if owners:
+ return str(max(owners, key=lambda root: len(root.parts)))
markers = {".git", "pyproject.toml", "package.json", "Cargo.toml",
"go.mod", "Makefile", "pom.xml", ".hg", "Gemfile"}
+ home = Path.home().resolve()
+ broad = {home, *home.parents}
check = candidate
- while check != check.parent:
+ while check != check.parent and check not in broad:
if any((check / m).exists() for m in markers):
return str(check)
check = check.parent
@@ -1303,7 +1280,7 @@ class CheckpointManager:
# Internal
# ------------------------------------------------------------------
- def _take(self, working_dir: str, reason: str) -> bool:
+ def _take(self, working_dir: str, reason: str, *, prune: bool = True) -> bool:
"""Take a snapshot. Returns True on success."""
store = _store_path(CHECKPOINT_BASE)
@@ -1429,11 +1406,9 @@ class CheckpointManager:
logger.debug("Checkpoint taken in %s: %s (%s)", working_dir, reason, new_sha[:8])
- # Real pruning — drop old commits beyond max_snapshots.
- self._prune(store, working_dir, ref)
-
- # Enforce global size cap.
- self._enforce_size_cap(store)
+ # Count and size budgets share one failure boundary.
+ if prune:
+ self._prune(store, working_dir, ref)
return True
@@ -1497,159 +1472,16 @@ class CheckpointManager:
)
def _prune(self, store: Path, working_dir: str, ref: str) -> None:
- """Keep only the last ``max_snapshots`` commits on the per-project ref.
+ """Apply both budgets through one checked pruning owner."""
+ from tools.checkpoint_pruning import Pruner, PruneError
- v1's ``_prune`` was documented as a no-op (``git``'s pack mechanism
- was supposed to handle it, but only the log view was limited — loose
- objects accumulated forever). v2 actually rewrites the ref to drop
- commits older than ``max_snapshots`` and then runs ``git gc`` on the
- store so unreachable objects are reclaimed.
- """
- ok, stdout, _ = _run_git(
- ["rev-list", "--count", ref], store, working_dir,
- allowed_returncodes={128},
- )
- if not ok:
- return
+ pruner = Pruner(_run_git, store, working_dir, _GIT_TIMEOUT, _dir_size_bytes, _REFS_PREFIX)
try:
- count = int(stdout)
- except ValueError:
- return
- if count <= self.max_snapshots:
- return
-
- # Collect commits oldest → newest, take last N.
- ok_list, list_out, _ = _run_git(
- ["rev-list", "--reverse", ref], store, working_dir,
- )
- if not ok_list or not list_out:
- return
- commits = list_out.splitlines()
- keep = commits[-self.max_snapshots:]
-
- # Rebuild a linear chain off keep[0]'s tree.
- new_parent: Optional[str] = None
- for sha in keep:
- ok_tree, tree_sha, _ = _run_git(
- ["rev-parse", f"{sha}^{{tree}}"], store, working_dir,
- )
- if not ok_tree or not tree_sha:
- return
- ok_msg, msg, _ = _run_git(
- ["log", "--format=%s", "-1", sha], store, working_dir,
- )
- commit_msg = msg if ok_msg and msg else "checkpoint"
- args = ["commit-tree", tree_sha, "-m", commit_msg, "--no-gpg-sign"]
- if new_parent is not None:
- args = ["commit-tree", tree_sha, "-p", new_parent,
- "-m", commit_msg, "--no-gpg-sign"]
- ok_commit, new_sha, _ = _run_git(args, store, working_dir)
- if not ok_commit or not new_sha:
- return
- new_parent = new_sha
-
- if new_parent is None:
- return
- _run_git(["update-ref", ref, new_parent], store, working_dir)
-
- # Reclaim objects from the dropped commits.
- _run_git(
- ["reflog", "expire", "--expire=now", "--all"],
- store, working_dir,
- )
- _run_git(
- ["gc", "--prune=now", "--quiet"],
- store, working_dir, timeout=_GIT_TIMEOUT * 3,
- )
- _repair_bare_repo_dirs(store)
-
- def _enforce_size_cap(self, store: Path) -> None:
- """If total store size exceeds ``max_total_size_mb``, drop oldest
- checkpoints across ALL projects until under the cap.
- """
- if self.max_total_size_mb <= 0:
- return
- cap_bytes = self.max_total_size_mb * 1024 * 1024
- size = _dir_size_bytes(store)
- if size <= cap_bytes:
- return
- logger.info(
- "Checkpoint store exceeded %d MB (actual %d MB) — pruning oldest",
- self.max_total_size_mb, size // (1024 * 1024),
- )
-
- # Collect (commit_time, ref, sha) across all per-project refs.
- ok, stdout, _ = _run_git(
- ["for-each-ref", "--format=%(refname)", _REFS_PREFIX],
- store, str(store.parent),
- allowed_returncodes={128},
- )
- if not ok or not stdout:
- return
- refs = [r for r in stdout.splitlines() if r.strip()]
-
- any_dropped = False
- # Round-robin-drop oldest commit per ref until under cap.
- for _ in range(20): # hard upper bound to avoid pathological loops
- size = _dir_size_bytes(store)
- if size <= cap_bytes:
- break
- for ref in refs:
- ok_count, count_out, _ = _run_git(
- ["rev-list", "--count", ref], store, str(store.parent),
- allowed_returncodes={128},
- )
- try:
- count = int(count_out) if ok_count else 0
- except ValueError:
- count = 0
- if count <= 1:
- continue # keep at least one snapshot per project
- ok_list, list_out, _ = _run_git(
- ["rev-list", "--reverse", ref], store, str(store.parent),
- )
- if not ok_list or not list_out:
- continue
- commits = list_out.splitlines()
- keep = commits[1:] # drop oldest
- new_parent: Optional[str] = None
- fail = False
- for sha in keep:
- ok_tree, tree_sha, _ = _run_git(
- ["rev-parse", f"{sha}^{{tree}}"], store, str(store.parent),
- )
- if not ok_tree or not tree_sha:
- fail = True
- break
- ok_msg, msg, _ = _run_git(
- ["log", "--format=%s", "-1", sha], store, str(store.parent),
- )
- commit_msg = msg if ok_msg and msg else "checkpoint"
- args = ["commit-tree", tree_sha, "-m", commit_msg, "--no-gpg-sign"]
- if new_parent is not None:
- args = ["commit-tree", tree_sha, "-p", new_parent,
- "-m", commit_msg, "--no-gpg-sign"]
- ok_commit, new_sha, _ = _run_git(args, store, str(store.parent))
- if not ok_commit or not new_sha:
- fail = True
- break
- new_parent = new_sha
- if fail or new_parent is None:
- continue
- _run_git(["update-ref", ref, new_parent], store, str(store.parent))
- any_dropped = True
- if not any_dropped:
- break
-
- _run_git(
- ["reflog", "expire", "--expire=now", "--all"],
- store, str(store.parent),
- )
- _run_git(
- ["gc", "--prune=now", "--quiet"],
- store, str(store.parent), timeout=_GIT_TIMEOUT * 3,
- )
- _repair_bare_repo_dirs(store)
+ pruner.trim(ref, self.max_snapshots)
+ if not pruner.enforce_size(self.max_total_size_mb * 1024 * 1024):
+ logger.warning("Checkpoint store remains over its size cap; minimum history retained")
+ except (PruneError, OSError) as exc:
+ logger.warning("Checkpoint pruning stopped: %s", exc)
def format_checkpoint_list(checkpoints: List[Dict], directory: str) -> str:
@@ -1859,6 +1691,21 @@ def prune_checkpoints(
if not base.exists():
return result
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
+ with store_lock(base):
+ return _prune_checkpoints(base, result, retention_days, delete_orphans, max_total_size_mb, orphan_allowlist)
+ except (PruneError, OSError) as exc:
+ result["errors"] += 1
+ logger.warning("Checkpoint maintenance stopped: %s", exc)
+ return result
+
+
+def _prune_checkpoints(
+ base: Path, result: Dict[str, int], retention_days: int, delete_orphans: bool,
+ max_total_size_mb: int, orphan_allowlist: Optional[set],
+) -> Dict[str, int]:
size_before = _dir_size_bytes(base)
# --- Legacy pre-v2 per-project shadow repos (kept directly under base) ---
@@ -1978,7 +1825,9 @@ def prune_checkpoints(
if reason is None:
continue
ref = _ref_name(dir_hash)
- _delete_ref(store, ref)
+ if not _delete_ref(store, ref):
+ result["errors"] += 1
+ return result
# Drop per-project index and metadata.
try:
idx = _index_path(store, dir_hash)
@@ -1997,88 +1846,17 @@ def prune_checkpoints(
else:
result["deleted_stale"] += 1
- # GC the store to reclaim unreachable objects from dropped refs.
- _run_git(
- ["reflog", "expire", "--expire=now", "--all"],
- store, str(base),
- )
- _run_git(
- ["gc", "--prune=now", "--quiet"],
- store, str(base), timeout=_GIT_TIMEOUT * 3,
- )
- _repair_bare_repo_dirs(store)
-
- # Size-cap pass across remaining projects.
- if max_total_size_mb > 0:
- cap_bytes = max_total_size_mb * 1024 * 1024
- for _i in range(20):
- size = _dir_size_bytes(store)
- if size <= cap_bytes:
- break
- ok, stdout, _ = _run_git(
- ["for-each-ref", "--format=%(refname)", _REFS_PREFIX],
- store, str(base),
- allowed_returncodes={128},
- )
- refs = [r for r in stdout.splitlines() if r.strip()] if ok else []
- if not refs:
- break
- any_drop = False
- for ref in refs:
- ok_c, count_out, _ = _run_git(
- ["rev-list", "--count", ref], store, str(base),
- allowed_returncodes={128},
- )
- try:
- count = int(count_out) if ok_c else 0
- except ValueError:
- count = 0
- if count <= 1:
- continue
- ok_l, lo, _ = _run_git(
- ["rev-list", "--reverse", ref], store, str(base),
- )
- if not ok_l or not lo:
- continue
- commits = lo.splitlines()
- keep = commits[1:]
- new_parent: Optional[str] = None
- fail = False
- for sha in keep:
- ok_t, tsha, _ = _run_git(
- ["rev-parse", f"{sha}^{{tree}}"], store, str(base),
- )
- if not ok_t or not tsha:
- fail = True
- break
- ok_m, m, _ = _run_git(
- ["log", "--format=%s", "-1", sha], store, str(base),
- )
- msg = m if ok_m and m else "checkpoint"
- args = ["commit-tree", tsha, "-m", msg, "--no-gpg-sign"]
- if new_parent is not None:
- args = ["commit-tree", tsha, "-p", new_parent,
- "-m", msg, "--no-gpg-sign"]
- ok_cm, new_sha, _ = _run_git(args, store, str(base))
- if not ok_cm or not new_sha:
- fail = True
- break
- new_parent = new_sha
- if fail or new_parent is None:
- continue
- _run_git(["update-ref", ref, new_parent], store, str(base))
- any_drop = True
- if not any_drop:
- break
- _run_git(
- ["reflog", "expire", "--expire=now", "--all"],
- store, str(base),
- )
- _run_git(
- ["gc", "--prune=now", "--quiet"],
- store, str(base), timeout=_GIT_TIMEOUT * 3,
- )
- _repair_bare_repo_dirs(store)
+ from tools.checkpoint_pruning import Pruner, PruneError
+
+ pruner = Pruner(_run_git, store, str(base), _GIT_TIMEOUT, _dir_size_bytes, _REFS_PREFIX)
+ try:
+ pruner.reclaim()
+ if not pruner.enforce_size(max_total_size_mb * 1024 * 1024):
+ result["errors"] += 1
+ logger.warning("Checkpoint store remains over its size cap; minimum history retained")
+ except (PruneError, OSError) as exc:
+ result["errors"] += 1
+ logger.warning("Checkpoint pruning stopped: %s", exc)
size_after = _dir_size_bytes(base)
delta = size_before - size_after
@@ -2259,10 +2037,13 @@ def clear_all(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
return out
size = _dir_size_bytes(base)
try:
- _rmtree_force(base)
+ from tools.checkpoint_pruning import store_lock
+
+ with store_lock(base):
+ _rmtree_force(base)
out["bytes_freed"] = size
out["deleted"] = True
- except OSError as exc:
+ except (OSError, RuntimeError) as exc:
logger.warning("Could not clear checkpoint base %s: %s", base, exc)
return out
@@ -2276,14 +2057,20 @@ def clear_legacy(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
out = {"bytes_freed": 0, "deleted": 0}
if not base.exists():
return out
- for child in list(base.iterdir()):
- if not child.is_dir() or not child.name.startswith(_LEGACY_PREFIX):
- continue
- try:
- size = _dir_size_bytes(child)
- _rmtree_force(child)
- out["bytes_freed"] += size
- out["deleted"] += 1
- except OSError as exc:
- logger.warning("Could not delete legacy archive %s: %s", child, exc)
+ from tools.checkpoint_pruning import store_lock
+
+ try:
+ with store_lock(base):
+ for child in list(base.iterdir()):
+ if not child.is_dir() or not child.name.startswith(_LEGACY_PREFIX):
+ continue
+ try:
+ size = _dir_size_bytes(child)
+ _rmtree_force(child)
+ out["bytes_freed"] += size
+ out["deleted"] += 1
+ except OSError as exc:
+ logger.warning("Could not delete legacy archive %s: %s", child, exc)
+ except (OSError, RuntimeError) as exc:
+ logger.warning("Could not clear legacy archives: %s", exc)
return out
diff --git a/tools/checkpoint_pruning.py b/tools/checkpoint_pruning.py
new file mode 100644
index 00000000000..9c03fa1c92d
--- /dev/null
+++ b/tools/checkpoint_pruning.py
@@ -0,0 +1,112 @@
+"""Checked history rewrites shared by snapshot limits and store maintenance."""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from dataclasses import dataclass
+import os
+from pathlib import Path
+from typing import Callable
+
+
+class PruneError(RuntimeError):
+ """Pruning stopped without permission to discard another snapshot."""
+
+
+def store_lock_path(base: Path) -> Path:
+ base = base.resolve()
+ return base.with_name(f".{base.name}.lock")
+
+
+@contextmanager
+def store_lock(base: Path):
+ """Serialize whole operations, including GC and clear, across processes."""
+ from hermes_cli.runtime_state import _lock
+
+ base.parent.mkdir(parents=True, exist_ok=True)
+ # Outside base so clear_all and legacy migration cannot replace its inode.
+ fd = os.open(store_lock_path(base), os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ if not _lock(fd, wait=False):
+ raise PruneError(f"checkpoint store is busy: {base}")
+ yield
+ finally:
+ os.close(fd)
+
+
+@dataclass(frozen=True)
+class Pruner:
+ run_git: Callable
+ store: Path
+ cwd: str
+ timeout: int
+ dir_size: Callable[[Path], int]
+ refs_prefix: str
+
+ def _git(self, args: list[str], **kwargs) -> str:
+ ok, output, error = self.run_git(args, self.store, self.cwd, **kwargs)
+ if not ok:
+ raise PruneError(f"checkpoint {args[0]} failed: {error}")
+ return output
+
+ def reclaim(self) -> None:
+ self._git(["reflog", "expire", "--expire=now", "--all"])
+ self._git(["gc", "--prune=now", "--quiet"], timeout=self.timeout * 3)
+ # Bare stores must remain usable when gc packs all refs.
+ for name in ("refs/heads", "branches"):
+ (self.store / name).mkdir(parents=True, exist_ok=True)
+
+ def _commits(self, ref: str) -> list[str]:
+ commits = self._git(["rev-list", "--reverse", ref]).splitlines()
+ if not commits:
+ raise PruneError(f"checkpoint ref has no readable history: {ref}")
+ return commits
+
+ def _rewrite(self, ref: str, original: list[str], keep: list[str]) -> None:
+ parent = None
+ for sha in keep:
+ metadata = self._git(["log", "-1", "--format=%T%x00%aI%x00%cI%x00%s", sha])
+ fields = metadata.split("\x00", 3)
+ if len(fields) != 4:
+ raise PruneError(f"invalid checkpoint metadata: {sha}")
+ tree, author_date, committer_date, message = fields
+ args = ["commit-tree", tree, "--no-gpg-sign", "-m", message]
+ if parent is not None:
+ args += ["-p", parent]
+ parent = self._git(args, extra_env={"GIT_AUTHOR_DATE": author_date, "GIT_COMMITTER_DATE": committer_date})
+ if not parent:
+ raise PruneError("commit-tree returned no checkpoint identity")
+ if parent is None:
+ raise PruneError("cannot remove a project's last snapshot")
+ # Never overwrite a snapshot published since we read this history.
+ self._git(["update-ref", ref, parent, original[-1]])
+ self.reclaim()
+
+ def trim(self, ref: str, keep_count: int) -> None:
+ commits = self._commits(ref)
+ keep_count = max(1, keep_count)
+ if len(commits) > keep_count:
+ self._rewrite(ref, commits, commits[-keep_count:])
+
+ def enforce_size(self, cap_bytes: int) -> bool:
+ """Return whether the cap fits; a failed Git step raises immediately."""
+ if cap_bytes <= 0 or self.dir_size(self.store) <= cap_bytes:
+ return True
+ self.reclaim()
+ if self.dir_size(self.store) <= cap_bytes:
+ return True
+ refs = self._git(["for-each-ref", "--format=%(refname)", self.refs_prefix]).splitlines()
+ # Keep the existing round-robin policy, remeasure after EACH rewrite.
+ # Twenty rounds bound maintenance when many large histories remain.
+ for _ in range(20):
+ changed = False
+ for ref in refs:
+ commits = self._commits(ref)
+ if len(commits) <= 1:
+ continue
+ self._rewrite(ref, commits, commits[1:])
+ changed = True
+ if self.dir_size(self.store) <= cap_bytes:
+ return True
+ if not changed:
+ break
+ return False
diff --git a/uv.lock b/uv.lock
index 01c03415149..7593eb69d40 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1084,6 +1084,15 @@ voice = [
{ name = "pynacl" },
]
+[[package]]
+name = "distlib"
+version = "0.4.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/02/bd72be9134d25ed783ecbbc38a539ffaefbf90c78418c7fb7229600dbac7/distlib-0.4.3.tar.gz", hash = "sha256:f152097224a0ae24be5a0f6bae1b9359af82133bce63f98a95f86cae1aede9ed", size = 615141, upload-time = "2026-06-12T08:04:52.847Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/02/08/9c41fb51ab5b43eb21674aff13df270e8ba6c4b29c8624e328dc7a9482af/distlib-0.4.3-py2.py3-none-any.whl", hash = "sha256:4b0ce306c966eb73bc3a7b6abad017c556dadd92c44701562cd528ac7fde4d5b", size = 470628, upload-time = "2026-06-12T08:04:50.506Z" },
+]
+
[[package]]
name = "distro"
version = "1.9.0"
@@ -1838,6 +1847,9 @@ icon-build = [
{ name = "pillow" },
{ name = "resvg-py" },
]
+test = [
+ { name = "distlib", marker = "sys_platform == 'win32'" },
+]
[package.metadata]
requires-dist = [
@@ -2000,6 +2012,7 @@ icon-build = [
{ name = "pillow", specifier = "==12.3.0" },
{ name = "resvg-py", specifier = "==0.4.0" },
]
+test = [{ name = "distlib", marker = "sys_platform == 'win32'", specifier = "==0.4.3" }]
[[package]]
name = "hf-xet"
diff --git a/website/docs/developer-guide/contributing.md b/website/docs/developer-guide/contributing.md
index d30d431c7d0..d6b9fadb6b5 100644
--- a/website/docs/developer-guide/contributing.md
+++ b/website/docs/developer-guide/contributing.md
@@ -79,7 +79,7 @@ POSIX:
```bash
uv venv "$HOME/.hermes/venvs/hermes-dev" --python 3.14
export UV_PROJECT_ENVIRONMENT="$HOME/.hermes/venvs/hermes-dev"
-uv sync --locked --extra all --extra dev
+uv sync --locked --extra all --extra dev --group test
export HERMES_PYTHON="$UV_PROJECT_ENVIRONMENT/bin/python"
"$HERMES_PYTHON" hermes --version
```
@@ -90,7 +90,7 @@ PowerShell:
$devEnv = Join-Path $env:LOCALAPPDATA 'hermes-dev-env'
uv venv $devEnv --python 3.14
$env:UV_PROJECT_ENVIRONMENT = $devEnv
-uv sync --locked --extra all --extra dev
+uv sync --locked --extra all --extra dev --group test
$env:HERMES_PYTHON = Join-Path $devEnv 'Scripts/python.exe'
& $env:HERMES_PYTHON hermes --version
```
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index 275788ffb1e..9f47b468dc9 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -72,6 +72,14 @@ environment before third-party imports. Processes retain their existing imports
until they restart. Garbage collection preserves selected generations and
lease-managed generations with live readers.
+Downloads share a lock per partial URL. A failed or paused transfer cannot
+publish a partial destination, and garbage collection cannot delete a live
+transfer's files. Resume reuses ranges only when their recorded length,
+validator, and optional hash still match. Without a strong ETag or pinned
+hash, an interrupted transfer restarts instead of mixing different versions.
+The small `.locks/` files remain after completion so waiting processes use
+the same lock.
+
## Optional Python dependencies and plugins
A built-in feature requests a project extra through `pm.ensure_import`.
@@ -265,8 +273,10 @@ are not durable and can disappear when PM selects a new environment.
PM's `dev` extra does not make a bare store Python suitable for the canonical
test runner. The runner clears `PYTHONPATH` and needs an interpreter with pytest
installed in its own environment. Use the contributor guide's
-[independent test environment](/developer-guide/contributing#manual-development-and-test-environment),
-then run `scripts/run_tests.sh` (through Bash on Windows).
+[independent test environment](/developer-guide/contributing#manual-development-and-test-environment)
+with `uv sync --extra dev --group test`, then run `scripts/run_tests.sh`
+(through Bash on Windows). The `test` dependency group includes native launcher
+test dependencies and does not enter a packaged runtime.
The runner checks repository `.venv`, repository `venv`, and the standard
source-install venv before using `HERMES_PYTHON` as a fallback. Read its startup
diff --git a/website/docs/user-guide/checkpoints-and-rollback.md b/website/docs/user-guide/checkpoints-and-rollback.md
index 1a14d7c1be3..5ca89631394 100644
--- a/website/docs/user-guide/checkpoints-and-rollback.md
+++ b/website/docs/user-guide/checkpoints-and-rollback.md
@@ -235,10 +235,11 @@ Restore just one file from a checkpoint without affecting the rest of the direct
- **Directory scope** — Hermes skips overly broad directories (root `/`, home `$HOME`).
- **Repository size** — directories with more than 50,000 files are skipped.
- **Per-file size cap** — files larger than `max_file_size_mb` (default 10 MB) are excluded from the snapshot. Prevents accidentally swallowing datasets, model weights, or generated media.
-- **Total store size cap** — when the store exceeds `max_total_size_mb` (default 500 MB), the oldest commit per project is dropped round-robin until under the cap.
+- **Total store size cap** — when the store exceeds `max_total_size_mb` (default 500 MB), the oldest commit per project is dropped round-robin. Each drop is reclaimed before deciding whether another is necessary. Every project keeps at least one snapshot. A failed Git operation stops pruning and is reported; maintenance never discards more history to compensate for failed reclamation.
- **Real pruning** — `max_snapshots` is enforced by rewriting the per-project ref and running `git gc --prune=now` afterwards, so loose objects don't accumulate.
+- **Concurrent operations** — snapshots, restores, diffs and maintenance use one process-shared store lock. An operation reports a busy store rather than running GC over another process's unpublished objects. A restore applies its selected tree before pruning the safety snapshot's history.
- **No-change snapshots** — if there are no changes since the last snapshot, the checkpoint is skipped.
-- **Non-fatal errors** — all errors inside the Checkpoint Manager are logged at debug level; your tools continue to run.
+- **Non-fatal errors** — snapshot failures do not block your tools. Pruning failures are logged as warnings; explicit maintenance reports an error count.
## Where Checkpoints Live
@@ -256,6 +257,8 @@ Restore just one file from a checkpoint without affecting the rest of the direct
Each `<hash>` is derived from the absolute path of the working directory. You normally never need to touch these manually — use `hermes checkpoints status` / `prune` / `clear` instead.
+The sibling `.checkpoints.lock` coordinates processes and survives a store clear. Do not remove it while Hermes is running.
+
### Migration from v1
Before the v2 rewrite, each working directory got its own complete shadow git repo directly under `~/.hermes/checkpoints/<hash>/`. That layout couldn't dedup objects across projects and had a documented no-op pruner — the store would grow without bound.
diff --git a/website/docs/user-guide/profiles.md b/website/docs/user-guide/profiles.md
index ca3349defd7..ddb91e752d1 100644
--- a/website/docs/user-guide/profiles.md
+++ b/website/docs/user-guide/profiles.md
@@ -335,6 +335,14 @@ A profile you built on one machine can go to another — your own workstation, a
**Send a file.** `/export` packs the profile into one `.tar.gz` — skills, memory, persona, crons, plugins, settings, and (from the desktop) your theme and layout. API keys are stripped. The recipient runs `/import`.
+Machine-specific PM state is not portable. Export, import, and distribution
+install exclude `installs/`, `tools/`, and `cache/` at a profile's root.
+Backup and restore apply the same rule to the default home and named profiles.
+Older archives cannot replace the destination machine's PM selections or tools.
+Files such as `plugins/example/facts.json` and `skills/example/tools/helper.py`
+remain user data and are preserved. Install dependencies on the destination
+through [PM](/reference/package-management), rather than copying environments.
+
```bash
# In chat, run /export, hand over the file, and they run /import on it
hermes profile export coder
diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.md
index 2c7e3c7820e..f9b3cdd2344 100644
--- a/website/docs/user-guide/security.md
+++ b/website/docs/user-guide/security.md
@@ -819,10 +819,16 @@ operating-system trust procedure. Hermes' provider resolver no longer selects
trust through `HERMES_CA_BUNDLE` or the old CA-environment-variable ladder.
Sandboxed subprocesses can have their own separate CA configuration.
-A custom provider can declare `ssl_ca_cert` for its endpoint. A missing file
-produces a warning and falls back to platform trust. `ssl_verify: false`
-disables certificate verification and is unsafe for untrusted networks.
-Do not use it as a permanent fix for a missing corporate root.
+A custom provider can declare `ssl_ca_cert` for its endpoint. That bundle
+replaces platform trust for chat, model metadata, and model catalog probes.
+A missing file produces a warning and falls back to platform trust.
+`ssl_verify: false` disables certificate verification and is unsafe for
+untrusted networks. Do not use it as a permanent fix for a missing corporate root.
+
+Provider HTTP clients keep proxy configuration separate from certificate
+selection. A stale ambient CA-file path cannot prevent those clients from
+starting. PM index credentials are sent only to their exact HTTPS origin;
+redirects to another origin do not receive them.
## Supply-chain advisory checking