The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): integrate audited runtime and lifecycle repairs
ethernet92686159d13c
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex 6a89779febb..8c1e770271b 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -197,6 +197,11 @@ jobs:needs: detectuses: ./.github/workflows/case-collision-check.yml+ lazy-deps-guard:+ name: No imports of deleted tools.lazy_deps+ needs: detect+ uses: ./.github/workflows/lazy-deps-guard.yml+lockfile-diff:name: package-lock.json diffneeds: detect@@ -261,6 +266,7 @@ jobs:- contributor-check- uv-lockfile- case-collision-check+ - lazy-deps-guard- lockfile-diff- docker-lint- profile-artifact-checkdiff --git a/.github/workflows/lazy-deps-guard.yml b/.github/workflows/lazy-deps-guard.ymlnew file mode 100644index 00000000000..8d4adf490ae--- /dev/null+++ b/.github/workflows/lazy-deps-guard.yml@@ -0,0 +1,36 @@+name: Lazy-deps import guard++# Rejects any tracked production code that imports tools/lazy_deps.py,+# which was deleted by the pm migration (pm.extras — available /+# ensure_import / ensure_and_bind — is the only lazy-install surface). A+# remaining import is an ImportError at call time.+#+# Runs unconditionally (no change-classifier gate): the deleted module+# must stay unimported on every change, in any kind of PR — the same+# "passive rule that cannot enforce a policy" reasoning as the+# case-collision check. Not folded into lint.yml because the lint lane is+# language-gated by the orchestrator's detect outputs.+#+# The checker builds the tracked inventory (git ls-files), does AST import+# analysis (comments/prose ignored by construction), and FAILS on+# inventory errors — it can never pass by scanning nothing. Exit 1 lists+# the exact offender sites; their migration is owned by the lazy-deps+# owner, not this gate. Contract tests (fixture repos prove red/green):+# tests/pm/test_no_lazy_deps.py.++on:+ workflow_call:++permissions:+ contents: read++jobs:+ lazy-deps-guard:+ name: No imports of deleted tools.lazy_deps+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2++ - name: Check tools.lazy_deps imports in tracked production code+ run: python3 scripts/ci/check_lazy_deps_imports.pydiff --git a/acp_adapter/content.py b/acp_adapter/content.pyindex d2137ffd38e..17d07ed3bb3 100644--- a/acp_adapter/content.py+++ b/acp_adapter/content.py@@ -76,6 +76,9 @@ def _path_from_file_uri(uri: str) -> Path | None:if not raw:return None+ # urlparse treats a bare Windows drive as a URI scheme.+ if len(raw) >= 3 and raw[0].isalpha() and raw[1] == ":" and raw[2] in "/\\":+ raw = "file:///" + raw.replace("\\", "/")parsed = urlparse(raw)if parsed.scheme and parsed.scheme != "file":return None@@ -91,7 +94,11 @@ def _path_from_file_uri(uri: str) -> Path | None:drive, rest = path_text[0], path_text[2:]else:return Path(path_text)- return Path("/mnt") / drive.lower() / rest.lstrip("/\\").replace("\\", "/")+ import os+ rest = rest.lstrip("/\\").replace("\\", "/")+ if os.name == "nt":+ return Path(f"{drive}:/{rest}")+ return Path("/mnt") / drive.lower() / restdef _decode_text_bytes(data: bytes, mime_type: str | None) -> str | None:diff --git a/acp_adapter/edit_approval.py b/acp_adapter/edit_approval.pyindex f60c55ddce6..f081f77b990 100644--- a/acp_adapter/edit_approval.py+++ b/acp_adapter/edit_approval.py@@ -59,7 +59,7 @@ def reset_edit_approval_requester(token: Token) -> None:def _read_text_if_exists(path: str) -> str | None:p = Path(path).expanduser()if p.is_file():- return p.read_text(encoding=utf-8-sig, errors="replace")+ return p.read_text(encoding="utf-8-sig", errors="replace")if p.exists():raise OSError(f"Cannot edit non-file path: {path}")return Nonediff --git a/activate b/activateindex 5e8dd5b6919..eb7e48da22d 100644--- a/activate+++ b/activate@@ -20,89 +20,29 @@ fi_HERMES_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-# --- target detection (same rules as pm.sh: msys on Windows must report the-# machine's truth from the registry, not the emulated shell's) ----_hermes_os="$(uname -s)"-case "$_hermes_os" in- Linux) _hermes_os=linux ;;- Darwin) _hermes_os=darwin ;;- MINGW*|MSYS*|CYGWIN*) _hermes_os=win32 ;;- *) echo "activate: unsupported OS $(uname -s)" >&2; return 1 2>/dev/null || exit 1 ;;-esac-if [ "$_hermes_os" = win32 ]; then- _hermes_winarch="$(reg.exe query 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' /v PROCESSOR_ARCHITECTURE 2>/dev/null | tr -d '-' | awk '/PROCESSOR_ARCHITECTURE/ {print $NF}')"- # PROCESSOR_ARCHITECTURE reports the EMULATED arch inside an x64-on-- # arm64 shell, and uname -m does too. The registry is the machine's- # truth; when reg.exe is unreachable, uname -s's release token (e.g.- # MINGW64_NT-10.0-28000-ARM64) still names the real machine arch.- if [ -z "$_hermes_winarch" ]; then- case "$(uname -s)" in- *ARM64) _hermes_winarch=ARM64 ;;- *AMD64) _hermes_winarch=AMD64 ;;- esac- fi- case "${_hermes_winarch:-}" in- ARM64) _hermes_arch=arm64 ;;- AMD64) _hermes_arch=x64 ;;- *) : ;; # probe unavailable — the store probe below decides- esac-fi-if [ -z "${_hermes_arch:-}" ] && [ "$_hermes_os" != win32 ]; then- case "$(uname -m)" in- arm64|aarch64) _hermes_arch=arm64 ;;- x86_64|amd64) _hermes_arch=x64 ;;- *) : ;; # unknown — the store probe below decides- esac-fi-# Resolve the pm store root here so the arch probe below can consult it.-_hermes_store="${HERMES_RUNTIME_DIR:-$HOME/.hermes/tools}"-if [ -n "${_hermes_arch:-}" ]; then- _hermes_target="$_hermes_os-$_hermes_arch"-else- # Registry + env both unavailable (blanked PATH): ask the store which- # target it actually holds instead of guessing an arch. First- # python-<ver>-<os>-<arch> entry wins.- _hermes_target=""- for _hermes_entry in "$_hermes_store"/python-*; do- [ -d "$_hermes_entry" ] || continue- case "${_hermes_entry##*/}" in- python-*-linux-*|python-*-darwin-*|python-*-win32-*)- _hermes_target="${_hermes_entry##*python-}"- _hermes_target="${_hermes_target#*-}"- break- ;;- esac- done- if [ -z "$_hermes_target" ]; then- echo "activate: cannot determine target arch and the store holds no python entry — run ./setup-hermes.sh first" >&2- unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store _hermes_py- return 1 2>/dev/null || exit 1- fi-fi+# Bootstrap Python only emits the environment; it does not install anything.+_hermes_repo="$_HERMES_REPO"_hermes_py=""-for _hermes_entry in "$_hermes_store"/python-*-"$_hermes_target"; do- if [ -x "$_hermes_entry/bin/python" ]; then- _hermes_py="$_hermes_entry/bin/python"- elif [ -x "$_hermes_entry/bin/python.exe" ]; then- _hermes_py="$_hermes_entry/bin/python.exe"- fi- [ -n "$_hermes_py" ] && break+for _hermes_candidate in "$_hermes_repo/.venv/bin/python" "$_hermes_repo/.venv/Scripts/python.exe" \+ "$_hermes_repo/venv/bin/python" "$_hermes_repo/venv/Scripts/python.exe"; do+ [ -x "$_hermes_candidate" ] && { _hermes_py="$_hermes_candidate"; break; }doneif [ -z "$_hermes_py" ]; then- for _hermes_venvpy in "$_hermes_repo/venv/bin/python" "$_hermes_repo/venv/bin/python.exe" \- "$_hermes_repo/venv/Scripts/python.exe"; do- [ -x "$_hermes_venvpy" ] && { _hermes_py="$_hermes_venvpy"; break; }+ for _hermes_store in "${HERMES_RUNTIME_DIR:-}" "$_hermes_repo/../tools" "${HERMES_HOME:-$HOME/.hermes}/tools"; do+ [ -n "$_hermes_store" ] || continue+ for _hermes_candidate in "$_hermes_store"/python-*/bin/python3 "$_hermes_store"/python-*/python.exe "$_hermes_store"/python-*/bin/python "$_hermes_store"/python-*/bin/python.exe; do+ [ -x "$_hermes_candidate" ] && { _hermes_py="$_hermes_candidate"; break; }+ done+ [ -n "$_hermes_py" ] && breakdonefiif [ -z "$_hermes_py" ]; then- echo "activate: no pm python found — run ./setup-hermes.sh first" >&2- unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store _hermes_py+ echo "activate: no bootstrap Python found; run setup-hermes.sh" >&2return 1 2>/dev/null || exit 1fi# --- emit export lines from `pm env` ----_hermes_json="$(PYTHONPATH="$_hermes_repo${PYTHONPATH:+:$PYTHONPATH}" "$_hermes_py" -m pm.cli env 2>/dev/null)"+_hermes_json="$(PYTHONHOME= PYTHONPATH="$_hermes_repo" "$_hermes_py" -m hermes_cli.runtime_paths)"if [ -z "$_hermes_json" ] || [ "${_hermes_json#*{}" = "$_hermes_json" ]; thenecho "activate: could not read pm env (run ./setup-hermes.sh first)" >&2unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store _hermes_py _hermes_jsondiff --git a/activate.ps1 b/activate.ps1index 82bfdfb3005..0b979a92f97 100644--- a/activate.ps1+++ b/activate.ps1@@ -1,73 +1,53 @@-# ============================================================================-# venv-style activation for the Hermes dev environment (pm-managed tools).-#-# .\activate.ps1 (repo root; if script execution is disabled:-# powershell -ExecutionPolicy Bypass -File .\activate.ps1, or set-# Set-ExecutionPolicy RemoteSigned -Scope CurrentUser once)-#-# Emits the composed pm env (PATH + tool vars) into the CURRENT session, with-# save/restore: `deactivate` undoes exactly what activation changed.-#-# Requires a completed .\setup-hermes.ps1 — it never invokes uv. It runs the-# pm store's pinned python (fallback: the repo venv) to emit the env JSON.-# ============================================================================+# Source this file to apply the installed PM environment; deactivate restores it.$ErrorActionPreference = 'Stop'--# Guard against double-sourcing: re-activating deactivates first.if (Test-Path function:deactivate) { deactivate }-$repo = $PSScriptRoot-$machineArch = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment').PROCESSOR_ARCHITECTURE-$arch = if ($machineArch -eq 'ARM64') { 'arm64' } else { 'x64' }-$target = "win32-$arch"--$store = if ($env:HERMES_RUNTIME_DIR) { $env:HERMES_RUNTIME_DIR } else { Join-Path $HOME '.hermes/tools' }-$py = $null-$entry = Get-ChildItem -Path $store -Directory -Filter "python-*-$target" -ErrorAction SilentlyContinue |- Sort-Object Name | Select-Object -Last 1-if ($entry -and (Test-Path (Join-Path $entry.FullName 'bin/python.exe'))) {- $py = Join-Path $entry.FullName 'bin/python.exe'+foreach ($candidate in @("$repo\.venv\Scripts\python.exe", "$repo\venv\Scripts\python.exe")) {+ if (Test-Path -LiteralPath $candidate) { $py = $candidate; break }}if (-not $py) {- foreach ($candidate in @(- (Join-Path $repo 'venv/Scripts/python.exe'),- (Join-Path $repo 'venv/bin/python.exe'))) {- if (Test-Path $candidate) { $py = $candidate; break }+ $roots = @($env:HERMES_RUNTIME_DIR, "$repo\..\tools")+ $homeRoot = if ($env:HERMES_HOME) { $env:HERMES_HOME } else { "$env:LOCALAPPDATA\hermes" }+ $roots += (Join-Path $homeRoot 'tools')+ foreach ($root in $roots) {+ if (-not $root) { continue }+ foreach ($entry in @(Get-ChildItem -LiteralPath $root -Directory -Filter 'python-*' -ErrorAction SilentlyContinue)) {+ $candidate = Join-Path $entry.FullName 'python.exe'+ if (Test-Path -LiteralPath $candidate) { $py = $candidate; break }+ }+ if ($py) { break }}}-if (-not $py) {- Write-Error 'activate: no pm python found - run .\setup-hermes.ps1 first'-}--$envJSON = (& $py -m pm.cli env 2>$null) -join "`n"-if (-not $envJSON) {- Write-Error 'activate: could not read pm env - run .\setup-hermes.ps1 first'+if (-not $py) { throw 'activate: no bootstrap Python found; run setup-hermes.ps1' }+$priorPath = $env:PYTHONPATH+$priorHome = $env:PYTHONHOME+try {+ $env:PYTHONPATH = $repo+ Remove-Item env:PYTHONHOME -ErrorAction SilentlyContinue+ $json = (& $py -m hermes_cli.runtime_paths) -join "`n"+ if ($LASTEXITCODE -ne 0) { throw 'activate: could not read the installed environment' }+ $composed = $json | ConvertFrom-Json+} finally {+ if ($null -eq $priorPath) { Remove-Item env:PYTHONPATH -ErrorAction SilentlyContinue } else { $env:PYTHONPATH = $priorPath }+ if ($null -eq $priorHome) { Remove-Item env:PYTHONHOME -ErrorAction SilentlyContinue } else { $env:PYTHONHOME = $priorHome }}-$composed = $envJSON | ConvertFrom-Json--# --- snapshot what we are about to change (deactivate restores this) ---$global:_hermesKeys = @($composed.PSObject.Properties.Name)$global:_hermesSaved = @{}-foreach ($k in $global:_hermesKeys) {- $global:_hermesSaved[$k] = [pscustomobject]@{- WasSet = (Test-Path "env:$k")- Value = [Environment]::GetEnvironmentVariable($k)+foreach ($key in $global:_hermesKeys) {+ $global:_hermesSaved[$key] = [pscustomobject]@{+ WasSet = (Test-Path "env:$key")+ Value = [Environment]::GetEnvironmentVariable($key)}}--foreach ($prop in $composed.PSObject.Properties) {- Set-Item -Path "env:$($prop.Name)" -Value ([string]$prop.Value)+foreach ($property in $composed.PSObject.Properties) {+ Set-Item -Path "env:$($property.Name)" -Value ([string]$property.Value)}-function global:deactivate {- foreach ($k in $global:_hermesKeys) {- $saved = $global:_hermesSaved[$k]- if ($saved.WasSet) {- Set-Item -Path "env:$k" -Value $saved.Value- } else {- Remove-Item -Path "env:$k" -ErrorAction SilentlyContinue- }+ foreach ($key in $global:_hermesKeys) {+ $saved = $global:_hermesSaved[$key]+ if ($saved.WasSet) { Set-Item -Path "env:$key" -Value $saved.Value }+ else { Remove-Item -Path "env:$key" -ErrorAction SilentlyContinue }}$global:_hermesKeys = $null$global:_hermesSaved = $nulldiff --git a/agent/agent_init.py b/agent/agent_init.pyindex 3421e26df8c..5ca050ff462 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -919,8 +919,6 @@ def _init_openai_client(agent, api_key, base_url, fallback_model, _provider_timeagent.api_key = client_kwargs.get("api_key", "")agent.base_url = client_kwargs.get("base_url", agent.base_url)try:- from agent.ssl_guard import verify_ca_bundle- verify_ca_bundle()agent.client = agent._create_openai_client(client_kwargs, reason="agent_init", shared=True)if not agent.quiet_mode:print(f"🤖 AI Agent initialized with model: {agent.model}")diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex c332d8479f9..ee492ef6fe6 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -127,7 +127,7 @@ _LOGGED_UNSUPPORTED_OAUTH_KEYS: set = set()def _resolve_aux_verify(base_url: Optional[str]) -> Any:"""httpx ``verify`` for an aux base_url, mirroring the main client (per-provider ``ssl_ca_cert`` /- ``ssl_verify``, ``HERMES_CA_BUNDLE`` / ``SSL_CERT_FILE``); any failure → httpx default (``True``)."""+ ``ssl_verify``; otherwise the OS trust store); any failure → httpx default (``True``)."""try:from agent.ssl_verify import resolve_httpx_verifyfrom hermes_cli.config import get_custom_provider_tls_settings, load_config_readonlydiff --git a/agent/image_routing.py b/agent/image_routing.pyindex 475653d5941..8b531bcc7f1 100644--- a/agent/image_routing.py+++ b/agent/image_routing.py@@ -55,10 +55,13 @@ def _matches_outside_code(pattern: re.Pattern, text: str) -> Iterable[str]:def _existing_file(candidate: str) -> Optional[str]:- """Expanded path when it is a regular file; None otherwise (incl. OSError on pathological input)."""+ """Normalized path when it is a regular file; None otherwise (incl. OSError on pathological input).+ The return value is the OS-canonical spelling of the real file (same norm class as+ ``str(Path(...))``), so callers can compare it against actual paths — ``~`` expansion+ alone would leave the textual ``/`` separators of the source text in place on Windows."""expanded = os.path.expanduser(candidate)try:- return expanded if os.path.isfile(expanded) else None+ return os.path.normpath(expanded) if os.path.isfile(expanded) else Noneexcept OSError:return Nonediff --git a/agent/learning_mutations.py b/agent/learning_mutations.pyindex f1962639f85..2c5016e667b 100644--- a/agent/learning_mutations.py+++ b/agent/learning_mutations.py@@ -56,113 +56,6 @@ def _locate_memory(node_id: str) -> tuple[Path, list[str], int]:return path, chunks, local-# MERGE-CHECK: upstream removed this section in #102117 refactor; kept our node detail/delete/edit API-# ── Inspect (edit prefill) ──────────────────────────────────────────────────---def node_detail(node_id: str) -> dict[str, Any]:- """Current content for an edit prefill. ``content`` is the full SKILL.md- (skills) or the raw memory chunk (memories)."""- try:- return _node_detail(node_id)- except (ValueError, IndexError) as exc:- return {"ok": False, "message": str(exc)}---def _node_detail(node_id: str) -> dict[str, Any]:- if parse_node_kind(node_id) == "memory":- source, gidx = _parse_memory_id(node_id)- _, chunks, local = _locate_memory(source, gidx)- body = chunks[local].strip()-- return {"ok": True, "kind": "memory", "id": node_id, "label": body.splitlines()[0][:80], "content": body}-- from tools.skill_manager_tool import _find_skill-- found = _find_skill(node_id)- if not found:- return {"ok": False, "message": f"skill '{node_id}' not found"}- skill_md = Path(found["path"]) / "SKILL.md"- if not skill_md.exists():- return {"ok": False, "message": f"SKILL.md missing for '{node_id}'"}-- return {- "ok": True,- "kind": "skill",- "id": node_id,- "label": node_id,- "content": skill_md.read_text(encoding="utf-8-sig"),- }---# ── Delete ──────────────────────────────────────────────────────────────────---def delete_node(node_id: str) -> dict[str, Any]:- try:- return _delete_memory(node_id) if parse_node_kind(node_id) == "memory" else _delete_skill(node_id)- except (ValueError, IndexError) as exc:- return {"ok": False, "message": str(exc)}---def _delete_skill(name: str) -> dict[str, Any]:- from tools import skill_usage-- if skill_usage.get_record(name).get("pinned"):- return {"ok": False, "message": f"'{name}' is pinned — unpin it first (hermes curator unpin {name})"}-- ok, message = skill_usage.archive_skill(name)- if ok:- _clear_skill_cache()-- return {"ok": ok, "message": f"archived '{name}' — restore with: hermes curator restore {name}" if ok else message}---def _delete_memory(node_id: str) -> dict[str, Any]:- source, gidx = _parse_memory_id(node_id)- path, chunks, local = _locate_memory(source, gidx)-- del chunks[local]- _write_memory(path, chunks)-- return {"ok": True, "message": f"deleted memory from {path.name}"}---# ── Edit ────────────────────────────────────────────────────────────────────---def edit_node(node_id: str, content: str) -> dict[str, Any]:- try:- return _edit_memory(node_id, content) if parse_node_kind(node_id) == "memory" else _edit_skill(node_id, content)- except (ValueError, IndexError) as exc:- return {"ok": False, "message": str(exc)}---def _edit_skill(name: str, content: str) -> dict[str, Any]:- from tools.skill_manager_tool import _edit_skill as _do_edit-- result = _do_edit(name, content)- if result.get("success"):- _clear_skill_cache()-- return {"ok": True, "message": f"updated '{name}'"}-- return {"ok": False, "message": result.get("error", "edit failed")}---def _edit_memory(node_id: str, content: str) -> dict[str, Any]:- source, gidx = _parse_memory_id(node_id)- body = content.strip()- if not body:- return {"ok": False, "message": "empty memory — use delete to remove it"}- path, chunks, local = _locate_memory(source, gidx)-- chunks[local] = body- _write_memory(path, chunks)-- return {"ok": True, "message": f"updated memory in {path.name}"}--# ── Helpers ─────────────────────────────────────────────────────────────────diff --git a/agent/monitoring/gateway_health_export.py b/agent/monitoring/gateway_health_export.pyindex ecf1a5a3354..45c63e40990 100644--- a/agent/monitoring/gateway_health_export.py+++ b/agent/monitoring/gateway_health_export.py@@ -287,9 +287,7 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRusdk: Optional[Dict[str, Any]] = Noneif metrics_on or diagnostics_on:try:- sdk = otlp_exporter._require_sdk(_METRICS_SDK, auto_install=True, prompt=False)- # MERGE-CHECK: depends on otlp_exporter._require_sdk(names, auto_install, prompt) upstream signature;- # pm lazy-install wiring ('otlp' extra) lives inside otlp_exporter._require_sdk itself.+ sdk = otlp_exporter._require_sdk(_METRICS_SDK, auto_install=True)except Exception:logger.warning("monitoring.gateway_health_export.enabled but OTLP SDK is unavailable; install 'hermes-agent[otlp]'", exc_info=True)return GatewayHealthExportRuntime(enabled=False, reason="otlp_unavailable")diff --git a/agent/provider_registry.py b/agent/provider_registry.pyindex 0c563e5c243..fa2a90c19a2 100644--- a/agent/provider_registry.py+++ b/agent/provider_registry.py@@ -15,7 +15,7 @@ import loggingimport threadingfrom typing import Any, Callable, Dict, FrozenSet, Generic, List, Optional, TypeVar-from hermes_constants import hermes_home_key+from hermes_constants import hermes_home_key, normalize_scopeP = TypeVar("P")@@ -54,6 +54,7 @@ class ProviderRegistry(Generic[P]):self._log_label = label if label.isupper() else label[0].lower() + label[1:]def _target(self, scope: Optional[str], *, create: bool) -> Dict[str, P]:+ scope = normalize_scope(scope)if scope is None:return self._providersif create:@@ -61,6 +62,7 @@ class ProviderRegistry(Generic[P]):return self._scoped_providers.get(scope, {})def _bump(self, scope: Optional[str]) -> None:+ scope = normalize_scope(scope)if scope is None:self._generation += 1else:@@ -100,7 +102,7 @@ class ProviderRegistry(Generic[P]):"""Global map overlaid with the active profile's scoped map (a copy)."""with self._lock:merged = dict(self._providers)- merged.update(self._scoped_providers.get(scope or hermes_home_key(), {}))+ merged.update(self._scoped_providers.get(hermes_home_key(scope), {}))return mergeddef list_providers(self, *, scope: Optional[str] = None) -> List[P]:@@ -114,13 +116,13 @@ class ProviderRegistry(Generic[P]):key = self.normalize(name)with self._lock:return (- self._scoped_providers.get(scope or hermes_home_key(), {}).get(key)+ self._scoped_providers.get(hermes_home_key(scope), {}).get(key)or self._providers.get(key))def registry_generation(self, *, scope: Optional[str] = None) -> tuple:"""Cache fingerprint ``(global_generation, scoped_generation)``."""- active_scope = scope or hermes_home_key()+ active_scope = hermes_home_key(scope)with self._lock:return self._generation, self._scoped_generations.get(active_scope, 0)@@ -134,6 +136,7 @@ class ProviderRegistry(Generic[P]):) -> bool:"""Restore *previous* only when *current* is still installed under *name*."""key = self.normalize(name)+ scope = normalize_scope(scope)with self._lock:target = self._target(scope, create=True)if target.get(key) is not current:diff --git a/agent/proxy_sources/iron_proxy.py b/agent/proxy_sources/iron_proxy.pyindex a6df4deb8fa..4d19919af81 100644--- a/agent/proxy_sources/iron_proxy.py+++ b/agent/proxy_sources/iron_proxy.py@@ -387,38 +387,29 @@ def _read_text_or_none(p: Path) -> Optional[str]:return None+def _management_token_path() -> Path:+ """Management-token location; resolving it never creates or changes state."""+ return _proxy_state_dir_ro() / "management.token"++def ensure_management_token(*, force: bool = False) -> str:"""Return the management-API bearer key, minting it on first call.- Stored at ``<hermes_home>/proxy/management.token`` with 0600 perms.+ Stored at the path from :func:`_management_token_path` with 0600 perms.The daemon receives it via the ``HERMES_IRON_PROXY_MGMT_KEY`` env var(named in the generated config's ``management.api_key_env``);``hermes egress reload`` reads the same file to authenticate."""+ _proxy_state_dir()p = _management_token_path()- if not force and p.exists():- try:- existing = p.read_text(encoding="utf-8-sig").strip()- if existing:- return existing- except OSError:- pass+ if not force and (existing := _read_text_or_none(p)):+ return existingtoken = mint_proxy_token(prefix="hermes-mgmt")_write_private_file(p, token.encode("utf-8"))return token-# MERGE-CHECK: kept our utf-8-sig token reader; no in-file caller after upstream's #102117 refactor-def _read_management_token() -> Optional[str]:- p = _proxy_state_dir_ro() / "management.token"- try:- token = p.read_text(encoding="utf-8-sig").strip()- except OSError:- return None- return token or None--def _yaml():"""PyYAML module or None (it is a Hermes dep, but never a hard requirement here)."""@@ -477,7 +468,7 @@ def reload_proxy() -> bool:raise RuntimeError("The generated proxy.yaml has no management listener (written before reload support). Re-run `hermes egress setup` and use `hermes egress restart` this one time.")- if not (token := _read_text_or_none(_proxy_state_dir_ro() / "management.token")):+ if not (token := _read_text_or_none(_management_token_path())):raise RuntimeError("management.token is missing — re-run `hermes egress setup`, then `hermes egress restart`.")host, port = mgmtreq = urllib.request.Request(f"http://{host}:{port}/v1/reload", method="POST", headers={"Authorization": f"Bearer {token}"}, data=b"")diff --git a/agent/secret_sources/registry.py b/agent/secret_sources/registry.pyindex b3003d5aecd..3dc3d29b6d3 100644--- a/agent/secret_sources/registry.py+++ b/agent/secret_sources/registry.py@@ -133,7 +133,7 @@ def register_source(source: SecretSource, *, replace: bool = False, builtin: boodef _merged(scope: Optional[str]) -> Dict[str, SecretSource]:"""Global sources overlaid with the scope's (default: current home) registrations."""merged = dict(_SOURCES)- merged.update(_SCOPED_SOURCES.get(scope or hermes_home_key(), {}))+ merged.update(_SCOPED_SOURCES.get(hermes_home_key(scope), {}))return mergeddiff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex aaf05d0c381..ea7a2ee6e51 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -217,7 +217,7 @@ def _setup_note(loaded_skill: dict[str, Any]) -> Optional[str]:def _supporting_files(loaded_skill: dict[str, Any], skill_dir: Path | None) -> list[str]:"""Skill-relative support file paths: from ``linked_files`` or a disk walk."""linked = (loaded_skill.get("linked_files") or {}).values()- supporting = [entry for entries in linked if isinstance(entries, list) for entry in entries]+ supporting = [Path(entry).as_posix() for entries in linked if isinstance(entries, list) for entry in entries]if not supporting and skill_dir:for subdir in ("references", "templates", "scripts", "assets"):files = sorted((skill_dir / subdir).rglob("*"))diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 4dd2f1b5a19..6fd3fbb25b5 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -693,10 +693,10 @@ def nonretryable_client_error_result(agent," 💡 The TLS certificate chain could not be verified. This fails the same"," way on every retry — fix the environment, then try again:",- " • Corporate TLS-inspecting proxy? Point Python at its CA bundle:",- " export SSL_CERT_FILE=/path/to/corp-ca.pem (also REQUESTS_CA_BUNDLE)",- " • Missing/stale system CA store? Install/refresh it:",- " pip install --upgrade certifi (macOS: run 'Install Certificates.command')",+ " • Corporate TLS-inspecting proxy? Ask your administrator to install",+ " its root certificate in the operating system trust store.",+ " • Missing/stale system CA store? Refresh the OS certificate store.",+ " A provider-specific CA can also be configured with ssl_ca_cert."," • Self-signed local endpoint (llama.cpp, LM Studio, vLLM)? Use http://"," for localhost, or add the server's cert to your trust store.",)diff --git a/apps/desktop/electron/appinstaller-checker.test.ts b/apps/desktop/electron/appinstaller-checker.test.tsnew file mode 100644index 00000000000..aa6fa38333d--- /dev/null+++ b/apps/desktop/electron/appinstaller-checker.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it, vi } from 'vitest'++import { APPINSTALLER_CHECK_TIMEOUT_MS, type ExecFileImpl, runAppInstallerChecker } from './appinstaller-checker'++type Callback = Parameters<ExecFileImpl>[3]++interface CapturedCall {+ file: string+ args: readonly string[]+ options: { encoding: string; timeout: number; windowsHide: boolean; env?: NodeJS.ProcessEnv }+ callback: Callback+}++function stubExecFile(behavior: (call: CapturedCall) => void) {+ const calls: CapturedCall[] = []++ const impl = (+ file: string,+ args: readonly string[],+ options: CapturedCall['options'],+ callback: Callback+ ) => {+ const call: CapturedCall = { file, args, options, callback }++ calls.push(call)+ behavior(call)++ return { kill: vi.fn() }+ }++ return { impl: impl as unknown as ExecFileImpl, calls }+}++const UNKNOWN_JSON = JSON.stringify({ available: null, error: 'checker timed out after 50ms' })++describe('runAppInstallerChecker', () => {+ it('runs python on the script, hidden and with the default deadline', async () => {+ const { impl, calls } = stubExecFile(call => call.callback(null, '{"available": false}', ''))+ const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl })++ expect(result).toEqual({ code: 0, stdout: '{"available": false}' })+ expect(calls[0].file).toBe('python.exe')+ expect(calls[0].args).toEqual(['check.py'])+ expect(calls[0].options.windowsHide).toBe(true)+ expect(calls[0].options.timeout).toBe(APPINSTALLER_CHECK_TIMEOUT_MS)+ })++ it('a nonzero exit keeps the checker stdout (the JSON "unknown" contract)', async () => {+ const stdout = '{"available": null, "error": "winrt import failed"}'+ const { impl } = stubExecFile(call => call.callback(Object.assign(new Error('exited'), { code: 1 }), stdout, ''))++ const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl })++ expect(result).toEqual({ code: 1, stdout })+ })++ it('a kill at the deadline resolves the caller-unknown shape', async () => {+ const { impl } = stubExecFile(call =>+ call.callback(Object.assign(new Error('killed'), { code: null, killed: true }), '', '')+ )++ const result = await runAppInstallerChecker('python.exe', 'check.py', {+ execFileImpl: impl,+ timeoutMs: 50+ })++ expect(result.code).toBe(1)+ expect(JSON.parse(result.stdout)).toEqual({ available: null, error: 'checker timed out after 50ms' })+ })++ it('resolves at the deadline even when the child never emits close', async () => {+ // The old main.ts helper killed the child and then waited on 'close'+ // forever. The deadline here is an independent bound: with a stub child+ // that never calls back and never exits, the promise still settles.+ const { impl, calls } = stubExecFile(() => undefined) // no callback, ever+ const started = Date.now()++ const result = await runAppInstallerChecker('python.exe', 'check.py', {+ execFileImpl: impl,+ timeoutMs: 50+ })++ expect(Date.now() - started).toBeLessThan(2000)+ expect(result).toEqual({ code: 1, stdout: UNKNOWN_JSON })+ expect(calls[0].options.timeout).toBe(50)+ })++ it('an interpreter that cannot spawn resolves unknown, never "no update"', async () => {+ const { impl } = stubExecFile(call => call.callback(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }), '', ''))++ const result = await runAppInstallerChecker('missing-python.exe', 'check.py', { execFileImpl: impl })++ expect(result.code).toBe(1)+ expect(JSON.parse(result.stdout)).toEqual({ available: null, error: 'ENOENT' })+ })++ it('forwards checker stderr to the diagnostic sink without breaking the result', async () => {+ const onStderr = vi.fn(() => {+ throw new Error('sink exploded')+ })++ const { impl } = stubExecFile(call => call.callback(null, '{}', 'some warning'))++ const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl, onStderr })++ expect(result).toEqual({ code: 0, stdout: '{}' })+ expect(onStderr).toHaveBeenCalledWith('some warning')+ })++ it('a synchronously throwing execFile resolves unknown and leaves no pending timer', async () => {+ const impl = (() => {+ throw new Error('bad arguments')+ }) as unknown as ExecFileImpl++ const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl, timeoutMs: 50 })++ expect(result.code).toBe(1)+ expect(JSON.parse(result.stdout)).toEqual({ available: null, error: 'bad arguments' })+ })++ it('passes the caller env through (PYTHONPATH for the payload site-packages)', async () => {+ const { impl, calls } = stubExecFile(call => call.callback(null, '', ''))++ await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl, env: { PYTHONPATH: 'C:\\sp' } })++ expect(calls[0].options.env).toEqual({ PYTHONPATH: 'C:\\sp' })+ })+})diff --git a/apps/desktop/electron/appinstaller-checker.ts b/apps/desktop/electron/appinstaller-checker.tsnew file mode 100644index 00000000000..70e093dda64--- /dev/null+++ b/apps/desktop/electron/appinstaller-checker.ts@@ -0,0 +1,116 @@+/**+ * appinstaller-checker.ts+ *+ * Bounded child run for the App Installer update checker+ * (scripts/check-appinstaller-update.py). The checker runs on the+ * update-check path, so a wedged child must never hang the check: the+ * deadline resolves the promise AT the deadline with an honest unknown,+ * while execFile's own timeout performs the bounded kill. Two independent+ * bounds on purpose — a kill that the child never answers (no 'close' ever)+ * still cannot hold the check hostage.+ */++import { execFile } from 'node:child_process'++export const APPINSTALLER_CHECK_TIMEOUT_MS = 20_000++export interface AppInstallerCheckerDeps {+ env?: NodeJS.ProcessEnv+ timeoutMs?: number+ /** Diagnostic sink for checker stderr; never breaks the result. */+ onStderr?: (text: string) => void+ execFileImpl?: ExecFileImpl+}++export interface AppInstallerCheckResult {+ code: number+ stdout: string+}++type CheckerError = Error & { code?: string | number; killed?: boolean }++/** Shape of the injected exec primitive (node's execFile in production). */+export type ExecFileImpl = (+ file: string,+ args: readonly string[],+ options: { encoding: 'utf8'; timeout: number; windowsHide: boolean; env?: NodeJS.ProcessEnv },+ callback: (error: CheckerError | null, stdout: string, stderr: string) => void+) => unknown++/**+ * Run `python <script>` with a hard deadline. Resolves (never rejects):+ * exit code and stdout map through unchanged so the checker's own JSON+ * contract survives; a deadline hit or an unspawnable interpreter resolves+ * the caller's "unknown" shape instead of a fake "no update".+ */+export function runAppInstallerChecker(+ python: string,+ script: string,+ deps: AppInstallerCheckerDeps = {}+): Promise<AppInstallerCheckResult> {+ const timeoutMs = deps.timeoutMs ?? APPINSTALLER_CHECK_TIMEOUT_MS+ const exec = deps.execFileImpl ?? execFile++ const deadlineResult = (): AppInstallerCheckResult => ({+ code: 1,+ stdout: JSON.stringify({ available: null, error: `checker timed out after ${timeoutMs}ms` })+ })++ return new Promise((resolve) => {+ let settled = false++ const finish = (result: AppInstallerCheckResult): void => {+ if (settled) {+ return+ }++ settled = true+ clearTimeout(deadline)+ resolve(result)+ }++ // The resolve deadline is independent of the callback below: if the+ // killed child never emits 'close', this still fires at the deadline.+ const deadline = setTimeout(() => finish(deadlineResult()), timeoutMs)++ try {+ exec(+ python,+ [script],+ { encoding: 'utf8', timeout: timeoutMs, windowsHide: true, env: deps.env },+ (error, stdout, stderr) => {+ if (stderr) {+ // A throwing diagnostic sink must never break the checker result.+ try {+ deps.onStderr?.(String(stderr))+ } catch {+ /* ignore */+ }+ }++ if (error?.killed) {+ finish(deadlineResult())++ return+ }++ if (error) {+ if (typeof error.code === 'number') {+ finish({ code: error.code, stdout: String(stdout || '') })+ } else {+ finish({ code: 1, stdout: JSON.stringify({ available: null, error: error.message }) })+ }++ return+ }++ finish({ code: 0, stdout: String(stdout || '') })+ }+ )+ } catch (err) {+ // execFile can throw synchronously (bad arguments); the deadline timer+ // must not be left pending — resolve the unknown shape right here.+ finish({ code: 1, stdout: JSON.stringify({ available: null, error: (err as Error).message }) })+ }+ })+}diff --git a/apps/desktop/electron/desktop-installation.test.ts b/apps/desktop/electron/desktop-installation.test.tsindex c8e8c78a288..dbb15ac557f 100644--- a/apps/desktop/electron/desktop-installation.test.ts+++ b/apps/desktop/electron/desktop-installation.test.ts@@ -38,7 +38,7 @@ test('loadOrCreateInstallationId persists and reuses one installation ID', () =>loadOrCreateInstallationId(filePath, () => ID_B),ID_A)- assert.equal(fs.statSync(filePath).mode & 0o777, 0o600)+ if (process.platform !== 'win32') assert.equal(fs.statSync(filePath).mode & 0o777, 0o600)}))test('loadOrCreateInstallationId tightens an existing identity file', () =>diff --git a/apps/desktop/electron/git-repo-scan.test.ts b/apps/desktop/electron/git-repo-scan.test.tsindex 683b56cd3ac..c519f7c6739 100644--- a/apps/desktop/electron/git-repo-scan.test.ts+++ b/apps/desktop/electron/git-repo-scan.test.ts@@ -74,7 +74,7 @@ describe('scanGitRepos', () => {})})-describe('macOS TCC-protected media exclusions (issue #57611 salvage)', () => {+describe.runIf(process.platform !== 'win32')('macOS TCC-protected media exclusions (issue #57611 salvage)', () => {it('finds a normal repo but skips root-level media folders on darwin', async () => {const root = tempDir()const dev = makeRepoAt(root, 'dev', 'proj')diff --git a/apps/desktop/electron/git-worktree-ops.ts b/apps/desktop/electron/git-worktree-ops.tsindex 384e8c3fbe3..f8bc1bf2ff9 100644--- a/apps/desktop/electron/git-worktree-ops.ts+++ b/apps/desktop/electron/git-worktree-ops.ts@@ -381,10 +381,15 @@ async function listBranches(repoPath, gitBin) {}try {- const [localOut, remoteOut] = await Promise.all([+ // Both children own cwd handles: a failed probe must still wait for its+ // sibling before the caller may remove or switch the repository directory.+ const probes = await Promise.allSettled([runGit(gitBin, ['for-each-ref', '--format=%(refname:short)', '--sort=-committerdate', 'refs/heads'], resolved),runGit(gitBin, ['for-each-ref', '--format=%(refname:short)', '--sort=-committerdate', 'refs/remotes'], resolved)])+ const [local, remote] = probes+ if (local.status === 'rejected' || remote.status === 'rejected') return []+ const [localOut, remoteOut] = [local.value, remote.value]const trees = await listWorktrees(resolved, gitBin)const pathByBranch = new Map(trees.filter(tree => tree.branch).map(tree => [tree.branch, tree.path]))diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.tsindex aa2cdfc0301..b0638777f75 100644--- a/apps/desktop/electron/hardening.test.ts+++ b/apps/desktop/electron/hardening.test.ts@@ -154,7 +154,7 @@ test('encryptDesktopSecret stores safeStorage base64 payload', () => {// ─── Owner-only credential files (connection.json) ─────────────────────────-test('writeSecretFileAtomic creates the file owner-only, not at the 0644 umask default', () => {+test.runIf(process.platform !== 'win32')('writeSecretFileAtomic creates the file owner-only, not at the 0644 umask default', () => {withTempDir(dir => {const target = path.join(dir, 'connection.json')const payload = JSON.stringify({ remote: { token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' } } })@@ -381,7 +381,7 @@ test('resolvePersistedRemoteToken keeps the existing token when no new token isassert.equal(called, false, 'an empty incoming token must not re-encrypt anything')})-test('writeSecretFileAtomic does not inherit loose bits from a stale temp file', () => {+test.runIf(process.platform !== 'win32')('writeSecretFileAtomic does not inherit loose bits from a stale temp file', () => {// renameSync keeps the TEMP file's permissions, and writeFileSync's `mode`// is ignored when the path already exists — so a temp left by a crashed// earlier write would otherwise hand 0644 straight to the target.@@ -409,8 +409,8 @@ function fsWith(overrides: Record<string, unknown>) {return { ...fs, ...overrides } as any}-test('the written file is owner-only even where chmod does nothing', () => {- // Windows, and any mount that refuses chmod. The create-time `mode` is what+test.runIf(process.platform !== 'win32')('the written file is owner-only even where chmod does nothing', () => {+ // A POSIX filesystem where chmod is unavailable. The create-time `mode` is what// covers this — there is no second chance to tighten.withTempDir(dir => {const target = path.join(dir, 'connection.json')@@ -434,7 +434,7 @@ test('the written file is owner-only even where chmod does nothing', () => {})})-test('the written file is owner-only even when a stale temp cannot be removed', () => {+test.runIf(process.platform !== 'win32')('the written file is owner-only even when a stale temp cannot be removed', () => {// The unlink is best-effort; if the stale temp survives, writeFileSync's// `mode` is ignored on an existing path and only the chmod before the rename// can still fix the bits.@@ -478,7 +478,7 @@ test('writeSecretFileAtomic cannot be redirected through a symlink planted at th})})-test('tightenSecretFileMode tightens a pre-existing world-readable config in place', () => {+test.runIf(process.platform !== 'win32')('tightenSecretFileMode tightens a pre-existing world-readable config in place', () => {// The upgrade path: a connection.json written by an older build sits at 0644// with a real (encrypted) token in it. Tightening must change the mode and// nothing else — the token has to stay readable or the user loses their@@ -505,7 +505,7 @@ test('tightenSecretFileMode tightens a pre-existing world-readable config in pla})})-test('tightenSecretFileMode leaves a non-safeStorage token payload readable', () => {+test.runIf(process.platform !== 'win32')('tightenSecretFileMode leaves a non-safeStorage token payload readable', () => {// A hand-edited config (or one from a pre-release build) can hold a// non-safeStorage token payload, which decryptDesktopSecret still reads// verbatim on purpose. Tightening the mode must not disturb that fallback —@@ -527,7 +527,7 @@ test('tightenSecretFileMode leaves a non-safeStorage token payload readable', ()})})-test('tightenSecretFileMode is idempotent and never throws on an unusable path', () => {+test.runIf(process.platform !== 'win32')('tightenSecretFileMode is idempotent and never throws on an unusable path', () => {withTempDir(dir => {const target = path.join(dir, 'connection.json')writeSecretFileAtomic(target, '{}')@@ -566,7 +566,7 @@ test('tightenSecretFileMode refuses to chmod a symlink instead of following it t})})-test('tightenSecretFileMode only touches a regular file the current user owns', () => {+test.runIf(process.platform !== 'win32')('tightenSecretFileMode only touches a regular file the current user owns', () => {// Directories, sockets, fifos and files owned by another account are all// "not ours to chmod". Injected lstat so the foreign-owner branch is// reachable without a second OS account.diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex cbcb4306a59..1ef349835ed 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -34,6 +34,7 @@ import { classifyActiveRuntime } from './active-runtime-state'import { destroyKeepaliveAgents, downloadAgentFor, jsonAgentFor, withRetry } from './api-transport'import { appIconCandidates, resolveAppIcon } from './app-icon'import { PLACEHOLDER_FEED_BASE_URL } from './app-updater'+import { runAppInstallerChecker } from './appinstaller-checker'import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate } from './backend-child'import {type BackendOutputTail,@@ -3395,11 +3396,12 @@ function isLightVariant(): boolean {}/**- * Run a bundled payload python script. The payload python needs the payload- * venv's site-packages on PYTHONPATH to import the winrt module — the same- * way the bundled CLI launcher sets it (the launcher-wrapper.py shebang- * overlay puts the venv's site-packages on sys.path). Without it the- * checker would always fail with "winrt import failed".+ * Run a bundled payload python script (the App Installer update checker).+ * The payload python needs the payload venv's site-packages on PYTHONPATH to+ * import the winrt module — the same way the bundled CLI launcher sets it.+ * Bounded via runAppInstallerChecker: a wedged child is killed at the+ * deadline and reported as an unknown, and the deadline resolves even if the+ * child never emits close (see appinstaller-checker.ts).*/async function runPayloadPython(python: string, script: string): Promise<{ code: number; stdout: string }> {const payload = resolvePayload(process.resourcesPath, { fileExists, directoryExists, isWindows: IS_WINDOWS })@@ -3409,22 +3411,9 @@ async function runPayloadPython(python: string, script: string): Promise<{ code:env.PYTHONPATH = payload.sitePackages}- return new Promise((resolve) => {- const child = spawn(python, [script], {- windowsHide: true,- stdio: ['ignore', 'pipe', 'pipe'],- env- })-- let stdout = ''- let stderr = ''- child.stdout.on('data', chunk => { stdout += chunk.toString() })- child.stderr.on('data', chunk => { stderr += chunk.toString() })- child.on('error', (error) => resolve({ code: 1, stdout: JSON.stringify({ available: null, error: error.message }) }))- child.on('close', (code) => {- if (stderr) {console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`)}- resolve({ code: code ?? 1, stdout })- })+ return runAppInstallerChecker(python, script, {+ env,+ onStderr: stderr => console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`)})}@@ -12974,29 +12963,14 @@ async function stopAllPoolBackends() {}/**- * Last teardown act on Windows: kill anything still running out of THIS- * install's roots, so no straggler holds an image open.- *- * Two roots, because two install shapes have the same daemon problem:- *- * - The artifact resources dir (bundled/MSIX). A live process rooted in the- * package family pins the family's container silo, and every later- * activation then fails the job → silo conversion with 0x80070020 — the app- * never launches again. Live cause on windows-11-arm was the payload's- * bundled-git gpg-agent, which daemonizes out of our process tree and so is- * unreachable by taskkill /T.- * - The managed tool store (mutable install.ps1 / install.sh checkout), where- * pm stages node, git and uv. A daemonized tool there keeps its own image- * open, and Windows cannot overwrite a running image — so the next- * `hermes update` fails to replace exactly those files.- *- * HERMES_RUNTIME_DIR is the store when pm is aimed at one (a bundled payload- * aims it at its own, where the roots overlap harmlessly); otherwise the store- * is <hermes root>/tools, mirroring pm.paths.store_root().- *- * Runs AFTER the graceful backend teardown and skips the pids it owned, so- * this is only the net for what detached. Best effort throughout: quit must- * never hang or fail on it. See package-process-reap.ts for the evidence.+ * Last teardown act on Windows: kill orphaned tools still running out of+ * THIS install's artifact root, so no straggler pins the package silo+ * (0x80070020 on the next activation). The managed tool store is NOT a quit+ * root — it is machine-scoped and shared with the surviving gateway and+ * other installs; image locks there are the updater's pause/resume job.+ * Runs after the graceful backend teardown, skips the pids it owned and+ * every live Hermes runtime process, so it is only the net for what+ * detached. Best effort throughout; see package-process-reap.ts.*/function reapInstallRootedStragglers(excludePids: number[]): void {if (!IS_WINDOWS) {@@ -13004,12 +12978,10 @@ function reapInstallRootedStragglers(excludePids: number[]): void {}const payloadRoot = isBundledInstall(process.resourcesPath, { fileExists }) ? process.resourcesPath : null- // HERMES_HOME is already root-normalized by resolveHermesHome().- const managedStore = process.env.HERMES_RUNTIME_DIR || path.join(HERMES_HOME, 'tools')try {reapPackageRootedProcesses({- installRoots: [payloadRoot, managedStore],+ installRoots: [payloadRoot],listProcesses: () => listWindowsProcesses((file, args, options) => execFileSync(file, args, {...hiddenWindowsChildOptions({ encoding: 'utf8', timeout: options.timeout }),windowsHide: options.windowsHidediff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.tsindex 9f224029316..b5640e46ba5 100644--- a/apps/desktop/electron/managed-ssh-update.test.ts+++ b/apps/desktop/electron/managed-ssh-update.test.ts@@ -280,7 +280,7 @@ test('POSIX managed launcher is detached, correlation-scoped, and never publisheassert.match(command, /while \[ ! -e/)})-test('POSIX managed launcher executes the updater command and atomically publishes its status', async () => {+test.runIf(process.platform !== 'win32')('POSIX managed launcher executes the updater command and atomically publishes its status', async () => {const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-launch-'))try {@@ -359,7 +359,7 @@ test('remote observation rejects a receipt for another correlation', () => {)})-test('POSIX observer reads the exact correlation receipt and terminal marker from disk', async () => {+test.runIf(process.platform !== 'win32')('POSIX observer reads the exact correlation receipt and terminal marker from disk', async () => {const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-update-'))try {@@ -401,7 +401,7 @@ test('POSIX observer reads the exact correlation receipt and terminal marker fro}})-test('managed observer unwraps a named profile home for the install-wide marker', async () => {+test.runIf(process.platform !== 'win32')('managed observer unwraps a named profile home for the install-wide marker', async () => {const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-profile-marker-'))const profileHome = path.join(root, 'profiles', 'research')diff --git a/apps/desktop/electron/package-process-reap.test.ts b/apps/desktop/electron/package-process-reap.test.tsindex e4afe552773..b9b90198726 100644--- a/apps/desktop/electron/package-process-reap.test.ts+++ b/apps/desktop/electron/package-process-reap.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest'import {isUnderInstallRoot,listWindowsProcesses,+ protectedRuntimePids,reapPackageRootedProcesses,type RunningProcess} from './package-process-reap'@@ -17,9 +18,23 @@ const GPG_AGENT = `${ROOT}\\app\\resources\\agent-payload\\tools\\git-2.53.0+3-wconst PAYLOAD_PYTHON = `${ROOT}\\app\\resources\\agent-payload\\tools\\python-3.11.16+20260814-win32-arm64\\python.exe`const MAIN_EXE = `${ROOT}\\app\\Hermes.exe`+/** Live-observed daemon command line (payload git gpg-agent, C09). */+const DAEMON_CMDLINE = `"${GPG_AGENT}" --use-standard-socket --daemon`+/** Same class, mutable install: pm-staged node holding its own image open. */const STORE_NODE = `${TOOLS_ROOT}\\node-26.7.0-win32-arm64\\node.exe`+/**+ * The gateway that survives desktop quit: payload python running the Hermes+ * gateway under the user-logon Scheduled Task (bundled installs run it out+ * of the payload, so its image IS under the artifact root).+ */+const GATEWAY_CMDLINE = `"${PAYLOAD_PYTHON}" -m hermes_cli.main gateway run`+/** Legacy/alternate module launcher of the same runtime. */+const GATEWAY_RUN_MODULE_CMDLINE = `"${PAYLOAD_PYTHON}" -m gateway.run --profile work`+/** Script-path launcher of the same runtime. */+const GATEWAY_RUN_SCRIPT_CMDLINE = `"${PAYLOAD_PYTHON}" C:\\Hermes\\hermes-agent\\gateway\\run.py --profile work`+function reap(processes: RunningProcess[], overrides: Record<string, unknown> = {}) {const killProcess = vi.fn()@@ -35,6 +50,15 @@ function reap(processes: RunningProcess[], overrides: Record<string, unknown> =return { outcome, killProcess }}+function proc(+ pid: number,+ path: string | null,+ commandLine: string | null = null,+ parentPid: number | null = null+): RunningProcess {+ return { pid, parentPid, path, commandLine }+}+describe('isUnderInstallRoot', () => {it('matches an image nested under the root regardless of case or separator', () => {expect(isUnderInstallRoot(GPG_AGENT, ROOT)).toBe(true)@@ -53,7 +77,8 @@ describe('isUnderInstallRoot', () => {})it('does not match another vendor, an unreadable path, or an empty root', () => {- const other = 'C:\\Program Files\\WindowsApps\\8bitSolutionsLLC.bitwardendesktop_2026.7.0.0_arm64__x\\app\\Bitwarden.exe'+ const other =+ 'C:\\Program Files\\WindowsApps\\8bitSolutionsLLC.bitwardendesktop_2026.7.0.0_arm64__x\\app\\Bitwarden.exe'expect(isUnderInstallRoot(other, ROOT)).toBe(false)expect(isUnderInstallRoot(null, ROOT)).toBe(false)@@ -84,29 +109,29 @@ describe('reapPackageRootedProcesses', () => {it('kills a detached package-rooted daemon that a tree-kill cannot reach', () => {// The regression: gpg-agent reparented away from us, so it is in no tree we// own. Path scoping is what catches it.- const { outcome, killProcess } = reap([{ pid: 48236, path: GPG_AGENT }])+ const { outcome, killProcess } = reap([proc(48236, GPG_AGENT, DAEMON_CMDLINE)])expect(outcome.matched).toBe(1)expect(outcome.killed).toEqual([48236])expect(killProcess).toHaveBeenCalledWith(48236)})- it('reaps every package-rooted process, whatever the image name', () => {+ it('leaves shared interpreters and entry points to their lifecycle owners', () => {const { outcome } = reap([- { pid: 10, path: MAIN_EXE },- { pid: 11, path: PAYLOAD_PYTHON },- { pid: 12, path: GPG_AGENT }+ proc(10, MAIN_EXE, `${MAIN_EXE} --app`),+ proc(11, PAYLOAD_PYTHON, 'idle-python'),+ proc(12, GPG_AGENT, DAEMON_CMDLINE)])- expect(outcome.matched).toBe(3)- expect(outcome.killed).toEqual([10, 11, 12])+ expect(outcome.matched).toBe(1)+ expect(outcome.killed).toEqual([12])})it('never kills processes outside the install root', () => {const { outcome, killProcess } = reap([- { pid: 20, path: 'C:\\Program Files\\Git\\usr\\bin\\gpg-agent.exe' },- { pid: 21, path: 'C:\\Users\\arilo\\AppData\\Local\\Programs\\HermesBundled\\app\\Hermes.exe' },- { pid: 22, path: GPG_AGENT }+ proc(20, 'C:\\Program Files\\Git\\usr\\bin\\gpg-agent.exe', 'gpg-agent --daemon'),+ proc(21, 'C:\\Users\\arilo\\AppData\\Local\\Programs\\HermesBundled\\app\\Hermes.exe'),+ proc(22, GPG_AGENT, DAEMON_CMDLINE)])// The user's OWN gpg-agent is exactly what a GNUPGHOME-scoped@@ -122,50 +147,136 @@ describe('reapPackageRootedProcesses', () => {// the next `hermes update` fails to replace exactly those files.const { outcome, killProcess } = reap([- { pid: 70, path: STORE_NODE },- { pid: 71, path: `${TOOLS_ROOT}\\git-2.53.0+3-win32-arm64\\usr\\bin\\gpg-agent.exe` },- { pid: 72, path: 'C:\\Windows\\System32\\node.exe' }+ proc(70, STORE_NODE, `${STORE_NODE} daemon.js`),+ proc(71, `${TOOLS_ROOT}\\git-2.53.0+3-win32-arm64\\usr\\bin\\gpg-agent.exe`, DAEMON_CMDLINE),+ proc(72, 'C:\\Windows\\System32\\node.exe', 'node server.js')],{ installRoots: [null, TOOLS_ROOT] })- expect(outcome.killed).toEqual([70, 71])+ expect(outcome.killed).toEqual([71])expect(killProcess).not.toHaveBeenCalledWith(72)})it('reaps both roots in one pass when an install has both', () => {const { outcome } = reap(+ [proc(80, GPG_AGENT, DAEMON_CMDLINE), proc(81, STORE_NODE, `${STORE_NODE} daemon.js`)],+ { installRoots: [ROOT, TOOLS_ROOT] }+ )++ expect(outcome.matched).toBe(1)+ expect(outcome.killed).toEqual([80])+ })++ it('never reaps a live Hermes runtime process rooted in the payload', () => {+ // Bundled installs run the surviving gateway out of the payload, so its+ // image IS under the artifact root — but the gateway survives desktop+ // quit by contract. The `-m hermes_cli.main` invocation is what proves a+ // process is a legitimate Hermes surface rather than an orphan.+ const { outcome, killProcess } = reap([+ proc(90, PAYLOAD_PYTHON, GATEWAY_CMDLINE),+ proc(91, PAYLOAD_PYTHON, `"${PAYLOAD_PYTHON}" -m hermes_cli.main serve --port 8080`)+ ])++ expect(outcome.matched).toBe(0)+ expect(killProcess).not.toHaveBeenCalled()+ })++ it('the ordinary-quit selector kills the daemon but not the gateway or shared-store consumers', () => {+ // Recorder for the wired quit call (roots = the artifact root only): a+ // store-python gateway session and a store-node process are unrelated+ // users of the machine-scoped store; the payload gateway survives the+ // quit. Only the daemonized tool is selected.+ const storePython = 'C:\\Users\\arilo\\AppData\\Local\\hermes\\tools\\python-3.11.16\\python.exe'++ const { outcome, killProcess } = reap([- { pid: 80, path: GPG_AGENT },- { pid: 81, path: STORE_NODE }+ proc(100, storePython, `"${storePython}" -m hermes_cli.main gateway run`),+ proc(101, STORE_NODE, `${STORE_NODE} script.js`),+ proc(102, PAYLOAD_PYTHON, GATEWAY_CMDLINE),+ proc(103, GPG_AGENT, `"${GPG_AGENT}" --use-standard-socket --daemon`)],- { installRoots: [ROOT, TOOLS_ROOT] }+ { installRoots: [ROOT] })- expect(outcome.matched).toBe(2)- expect(outcome.killed).toEqual([80, 81])+ expect(outcome.killed).toEqual([103])+ expect(killProcess).toHaveBeenCalledTimes(1)+ expect(killProcess).toHaveBeenCalledWith(103)+ })++ it('protects the alternate runtime launcher shapes: -m gateway.run and gateway/run.py', () => {+ // The Scheduled-Task launcher, elevated-handoff respawn and older+ // releases do not all use `-m hermes_cli.main`; every launcher of the+ // live runtime is protected (C06-09 review).+ const { outcome, killProcess } = reap([+ proc(91, PAYLOAD_PYTHON, GATEWAY_RUN_MODULE_CMDLINE),+ proc(92, PAYLOAD_PYTHON, GATEWAY_RUN_SCRIPT_CMDLINE)+ ])++ expect(outcome.matched).toBe(0)+ expect(killProcess).not.toHaveBeenCalled()+ })++ it('protects the live runtime DESCENDANTS (venv launcher / worker / tool chain)', () => {+ // gateway -> venv launcher shim -> worker python -> payload git: every+ // one is a legitimate user of the payload while its ancestor lives.+ const launcher = `${ROOT}\\app\\resources\\agent-payload\\venv\\Scripts\\python.exe`+ const worker = `${launcher} -c "import worker"`+ const git = `${ROOT}\\app\\resources\\agent-payload\\tools\\git-2.53.0+3-win32-arm64\\bin\\git.exe status`++ const { outcome, killProcess } = reap([+ proc(120, PAYLOAD_PYTHON, GATEWAY_CMDLINE),+ proc(121, launcher, worker, 120),+ proc(122, launcher, null, 121), // unreadable cmdline, but runtime-descended+ proc(123, `${ROOT}\\app\\resources\\agent-payload\\tools\\git\\bin\\git.exe`, git, 121)+ ])++ expect(outcome.matched).toBe(0)+ expect(killProcess).not.toHaveBeenCalled()+ })++ it('protects flagged interpreters and children of unidentified processes', () => {+ const { outcome } = reap([+ proc(130, PAYLOAD_PYTHON, `"${PAYLOAD_PYTHON}" -u -X utf8 -m gateway.run`),+ proc(131, GPG_AGENT, DAEMON_CMDLINE, 130),+ proc(140, null, null),+ proc(141, GPG_AGENT, DAEMON_CMDLINE, 140),+ proc(150, GPG_AGENT, DAEMON_CMDLINE)+ ])++ expect(outcome.killed).toEqual([150])+ })++ it('conservatively skips a process whose command line cannot be read', () => {+ // An unreadable cmdline cannot prove the process is not a live runtime.+ // Missing one pinner reproduces a bug we already have; killing an+ // unidentified process is unbounded damage.+ const { outcome, killProcess } = reap([proc(40, PAYLOAD_PYTHON, null), proc(41, PAYLOAD_PYTHON, '')])++ expect(outcome.matched).toBe(0)+ expect(killProcess).not.toHaveBeenCalled()})it('never kills itself', () => {- const { outcome, killProcess } = reap([{ pid: 99, path: MAIN_EXE }], { selfPid: 99 })+ const { outcome, killProcess } = reap([proc(99, MAIN_EXE, `${MAIN_EXE} --app`)], { selfPid: 99 })expect(outcome.matched).toBe(0)expect(killProcess).not.toHaveBeenCalled()})it('skips pids the graceful backend teardown already owns', () => {- const { outcome } = reap([- { pid: 30, path: MAIN_EXE },- { pid: 31, path: PAYLOAD_PYTHON }- ], { excludePids: [30] })+ const { outcome } = reap(+ [proc(30, MAIN_EXE, `${MAIN_EXE} --app`), proc(31, PAYLOAD_PYTHON, 'idle-python')],+ { excludePids: [30] }+ )- expect(outcome.killed).toEqual([31])+ expect(outcome.killed).toEqual([])})it('leaves a process whose path cannot be read alone', () => {// Missing one pinner reproduces a bug we already have; killing an// unidentified process is unbounded damage.- const { outcome, killProcess } = reap([{ pid: 40, path: null }])+ const { outcome, killProcess } = reap([proc(40, null)])expect(outcome.matched).toBe(0)expect(killProcess).not.toHaveBeenCalled()@@ -180,10 +291,7 @@ describe('reapPackageRootedProcesses', () => {const outcome = reapPackageRootedProcesses({installRoots: [ROOT],- listProcesses: () => [- { pid: 50, path: MAIN_EXE },- { pid: 51, path: GPG_AGENT }- ],+ listProcesses: () => [proc(50, GPG_AGENT, DAEMON_CMDLINE), proc(51, GPG_AGENT, DAEMON_CMDLINE)],killProcess,selfPid: 1,isWindows: true@@ -213,7 +321,7 @@ describe('reapPackageRootedProcesses', () => {const posix = reapPackageRootedProcesses({installRoots: [ROOT],- listProcesses: () => [{ pid: 60, path: MAIN_EXE }],+ listProcesses: () => [proc(60, MAIN_EXE, `${MAIN_EXE} --app`)],killProcess,selfPid: 1,isWindows: false@@ -221,7 +329,7 @@ describe('reapPackageRootedProcesses', () => {const rootless = reapPackageRootedProcesses({installRoots: [null, ''],- listProcesses: () => [{ pid: 61, path: MAIN_EXE }],+ listProcesses: () => [proc(61, MAIN_EXE, `${MAIN_EXE} --app`)],killProcess,selfPid: 1,isWindows: true@@ -233,32 +341,49 @@ describe('reapPackageRootedProcesses', () => {})})+describe('protectedRuntimePids', () => {+ it('extends protection transitively through parentage and stays empty with no runtime', () => {+ const running = [+ proc(10, PAYLOAD_PYTHON, GATEWAY_CMDLINE, 2),+ proc(11, PAYLOAD_PYTHON, 'worker', 10),+ proc(12, PAYLOAD_PYTHON, 'grandchild', 11),+ proc(13, GPG_AGENT, 'gpg-agent --daemon', null)+ ]++ expect(protectedRuntimePids(running)).toEqual(new Set([10, 11, 12]))+ expect(protectedRuntimePids([proc(14, GPG_AGENT, 'gpg-agent --daemon')])).toEqual(new Set())+ })+})+describe('listWindowsProcesses', () => {- it('parses Get-Process output, mapping an unreadable path to null', () => {- // The real shape: `.Path` throws for processes we cannot open, so the- // script emits an empty tail for those.+ it('parses Win32_Process output (pid|parent|path|command line), mapping unreadable fields to null', () => {+ // The real shape: ExecutablePath / CommandLine are null for processes we+ // cannot open, so the script emits empty middle/tail fields.const stdout = [- `48236|${GPG_AGENT}`,- `22660|${MAIN_EXE}`,- '4|',+ `48236|61728|${GPG_AGENT}|gpg-agent --daemon`,+ `22660|4|${MAIN_EXE}|`,+ '4|0||',''].join('\r\n')const parsed = listWindowsProcesses(() => stdout)expect(parsed).toEqual([- { pid: 48236, path: GPG_AGENT },- { pid: 22660, path: MAIN_EXE },- { pid: 4, path: null }+ { pid: 48236, parentPid: 61728, path: GPG_AGENT, commandLine: 'gpg-agent --daemon' },+ { pid: 22660, parentPid: 4, path: MAIN_EXE, commandLine: '' },+ { pid: 4, parentPid: 0, path: null, commandLine: '' }])})- it('keeps paths that contain spaces intact', () => {- // "C:\Program Files\..." — splitting on the FIRST separator is what- // preserves the rest of the path.- const parsed = listWindowsProcesses(() => `10|${MAIN_EXE}`)+ it('keeps paths and command lines that contain pipes and spaces intact', () => {+ // Splitting on the FIRST three separators is what preserves the rest —+ // a command line may contain "|", a path never does.+ const cmd = 'python -c "x = a | b"'+ const parsed = listWindowsProcesses(() => `10|99|${MAIN_EXE}|${cmd}`)expect(parsed[0].path).toBe(MAIN_EXE)+ expect(parsed[0].commandLine).toBe(cmd)+ expect(parsed[0].parentPid).toBe(99)})it('ignores malformed lines instead of inventing pids', () => {@@ -270,11 +395,7 @@ describe('listWindowsProcesses', () => {it('runs hidden and bounded so it cannot stall or flash a console on quit', () => {const calls: Array<{ file: string; options: { timeout: number; windowsHide: boolean } }> = []- const execFile = (- file: string,- _args: string[],- options: { timeout: number; windowsHide: boolean }- ): string => {+ const execFile = (file: string, _args: string[], options: { timeout: number; windowsHide: boolean }): string => {calls.push({ file, options })return ''diff --git a/apps/desktop/electron/package-process-reap.ts b/apps/desktop/electron/package-process-reap.tsindex 13076e9935a..b3960865fee 100644--- a/apps/desktop/electron/package-process-reap.ts+++ b/apps/desktop/electron/package-process-reap.ts@@ -1,101 +1,38 @@-/**- * package-process-reap.ts- *- * Reap every process still running out of our MSIX package root at shutdown.- *- * Why this exists. A Desktop-Bridge (Centennial) MSIX package activates inside- * a Desktop AppX container: Windows creates a Job Object for the package family- * and converts it to a silo. One live process rooted in the family pins that- * silo. While it is pinned, EVERY later activation of the family fails at the- * conversion step:- *- * AppModel-Runtime/Admin- * [215] 0x80070020: Cannot create the Desktop AppX container for package- * <full name> because an error was encountered converting the job.- * [208] 0x80070020: Cannot create the process for package <full name>- * because an error was encountered while configuring runtime.- * [LaunchProcess]- *- * 0x80070020 is ERROR_SHARING_VIOLATION, which Windows surfaces to the user as- * "The process cannot access the file because it is being used by another- * process" — a file-lock message for what is really a container-layer failure.- *- * Observed live on windows-11-arm: the payload's own bundled-git gpg-agent.exe- * (under tools/git-<version>/usr/bin/) had daemonized, outlived its package by- * a week, and pinned the family. Killing that ONE pid turned [215]/[208] into- * [210] Created / [211] Added on the very next activation, with nothing else- * changed.- *- * Why the platform does not save us. Deployment already asks for the shutdown- * (ForceApplicationShutdownOption + ForceTargetApplicationShutdownOption) and- * it still missed the daemon; the old package folder then failed to move with- * `0x80070005` and Windows logged `[503] The file system entries ... could not- * be cleaned up after reboot. The package is removed from the purge list.`- * Once that happens not even a reboot clears it. Our daemon defeated the- * platform's own mechanism, so the reap is ours to do.- *- * Why not a process-TREE kill. `taskkill /T` walks parentage, and a daemon that- * detaches is by construction no longer in our tree — that is what daemonizing- * means. Tree scoping is the actual bug. Install-root scoping is what matches- * the silo: the pin is "a process whose image lives under this package", so- * that is exactly the predicate to kill on.- *- * Why not a gpg-specific kill. `gpgconf --kill all` is scoped by GNUPGHOME, not- * by install root, so it can reach the user's OWN gpg-agent outside our package- * — real collateral harm for a case the generic path reap already covers. One- * mechanism, no per-daemon special cases: any future payload tool that- * daemonizes is caught with no new code.- *- * Scoping. Two roots hold binaries this install owns, and either can hold the- * straggler:- *- * 1. The artifact itself — resources/ on a bundled/MSIX install, which- * contains agent-payload (repo + venv + its own tool store).- * 2. The per-install managed tool store — where pm stages node, git, uv,- * ripgrep and friends for a MUTABLE install (an install.ps1 / install.sh- * checkout). That is HERMES_RUNTIME_DIR when set, else <hermes root>/tools.- * A bundled payload sets HERMES_RUNTIME_DIR at its own store, so the two- * roots coincide there and the overlap is harmless.- *- * A mutable install has exactly the same daemon problem with none of the MSIX- * framing: node tooling, a language server, or bundled git's gpg-agent under- * <hermes root>/tools keeps running and holds an open handle on the very files- * the next `hermes update` wants to replace. On Windows a running image cannot- * be overwritten, which is the same 0x80070020 the user reads as "used by- * another process". Reaping both roots covers both install shapes with one- * predicate.- *- * The roots are deliberately the CURRENT install's, not the package family or- * every Hermes on the box: once this ships, each shutdown reaps its own- * processes, so no install leaves a daemon behind. Cleaning up a straggler- * that a PREVIOUS version already leaked needs a repair path outside the- * install (the app cannot launch to clean up after itself) and is tracked- * separately.- *- * Live-verified on windows-11-arm at Medium Mandatory Level (admin=False, the- * integrity level the app actually runs at): all 6 package-rooted processes- * enumerated, all killed, 0 remaining, 0 with an unreadable path — then the- * next activation logged [210]/[211] and the app came up clean.- *- * Pure module: no electron import, no process globals reached directly, every- * dependency injected — so the predicate and the ordering are asserted against- * the real function rather than by grepping main.ts.+/** Clean up detached package tools without touching shared runtimes.+ * Package-owned gpg-agent can outlive its parent and pin an MSIX silo,+ * preventing subsequent activation. A root claim never includes the shared+ * tool store. Interpreters, launchers, unidentified processes and their+ * descendants belong to other lifecycle owners and are protected.*//** One running process, reduced to what the reap decision needs. */export interface RunningProcess {pid: number+ /**+ * Parent pid (Win32_Process.ParentProcessId), or null when unavailable.+ * Descendants of a live Hermes runtime process are protected too — see+ * reapPackageRootedProcesses.+ */+ parentPid: number | null/*** Absolute path of the process image, or null when it cannot be read.* A path we cannot read is never a match — see reapPackageRootedProcesses.*/path: string | null+ /**+ * Full command line, or null when it cannot be read. A live Hermes runtime+ * process is identified by its command line and never reaped — see+ * protectedRuntimePids. An UNREADABLE command line is conservatively+ * skipped as well: the cost of missing one pinner is the bug we already+ * have; killing a process we could not identify is unbounded damage.+ */+ commandLine: string | null}export interface ReapPackageRootedProcessesDeps {/**- * Absolute roots to scope on: the artifact resources dir and/or the managed- * tool store. Empty/nullish entries are ignored, and an empty list disables+ * Absolute roots to scope on: the artifact resources dir (never the shared+ * tool store). Empty/nullish entries are ignored, and an empty list disables* the reap entirely.*/installRoots: ReadonlyArray<string | null | undefined>@@ -127,15 +64,24 @@ export interface ReapOutcome {skipped: boolean}+/** Shared interpreters and entry points are not owned by a desktop window.+ * Do not parse argv to decide which Python flags or launcher forms qualify.+ * The updater owns their lifecycle; quit only sweeps detached tools.+ */+function isSharedRuntime(imagePath: string): boolean {+ const image = imagePath.replace(/^.*[\\/]/, '').toLowerCase()+ return /^(?:pythonw?(?:[0-9.]+)?|node|hermes(?:-agent|-acp)?)(?:\.exe|\.cmd)?$/.test(image)+}+/**- * Enumerate running processes with their image paths, via PowerShell's- * Get-Process.+ * Enumerate running processes with image path, parent pid and command line,+ * via PowerShell's Win32_Process query (Get-Process does not carry the+ * command line, and the ownership decision needs it).*- * Live-verified at Medium Mandatory Level (admin=False): all package-rooted- * processes were enumerated with readable paths and killed, so this needs no- * elevation and no WMI. `.Path` throws for processes the caller cannot open,- * which is why each read is guarded and reported as a null path rather than- * aborting the sweep.+ * Probed READ-ONLY on windows-11-arm at Medium Mandatory Level (admin=False,+ * the integrity level the app actually runs at): all processes enumerated+ * with readable pids/parents and ~45% null ExecutablePath/CommandLine —+ * each null is reported as such rather than aborting the sweep.** Bounded and best effort: this runs on the quit path, so it takes a hard* timeout and returns an empty list rather than delaying shutdown.@@ -145,9 +91,8 @@ export function listWindowsProcesses(): RunningProcess[] {const script ='$ErrorActionPreference = "SilentlyContinue"; ' +- 'Get-Process | ForEach-Object { ' +- '$p = $null; try { $p = $_.Path } catch { $p = $null }; ' +- '"{0}|{1}" -f $_.Id, $p }'+ 'Get-CimInstance Win32_Process | ForEach-Object { ' ++ '"{0}|{1}|{2}|{3}" -f $_.ProcessId, $_.ParentProcessId, $_.ExecutablePath, $_.CommandLine }'const stdout = execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {timeout: 10_000,@@ -157,20 +102,29 @@ export function listWindowsProcesses(const processes: RunningProcess[] = []for (const line of String(stdout).split(/\r?\n/)) {- const separator = line.indexOf('|')+ const first = line.indexOf('|')+ const second = first >= 0 ? line.indexOf('|', first + 1) : -1+ const third = second >= 0 ? line.indexOf('|', second + 1) : -1- if (separator <= 0) {+ if (first <= 0 || second < 0 || third < 0) {continue}- const pid = Number.parseInt(line.slice(0, separator), 10)+ const pid = Number.parseInt(line.slice(0, first), 10)+ const parentPid = Number.parseInt(line.slice(first + 1, second), 10)if (!Number.isInteger(pid)) {continue}- const imagePath = line.slice(separator + 1).trim()- processes.push({ pid, path: imagePath === '' ? null : imagePath })+ const imagePath = line.slice(second + 1, third).trim()++ processes.push({+ pid,+ parentPid: Number.isInteger(parentPid) ? parentPid : null,+ path: imagePath === '' ? null : imagePath,+ commandLine: line.slice(third + 1)+ })}return processes@@ -217,13 +171,63 @@ export function isUnderInstallRoot(}/**- * Kill every process whose image lives under the install root.+ * The set of pids the reap must never touch: every shared runtime or unidentified+ * process plus ALL of its descendants (Win32_Process parentage). The virtualenv+ * launcher/worker chain — the gateway's python spawning venv shims, workers,+ * and in-flight tools like git — is exactly how a live runtime's children come+ * to be rooted in the payload, so parentage, not just the launcher argv, is+ * the ownership boundary. A stale ParentProcessId that happens to point at a+ * runtime pid errs on the protected side: conservative by design.+ */+export function protectedRuntimePids(running: RunningProcess[]): Set<number> {+ const children = new Map<number, number[]>()++ for (const entry of running) {+ if (entry.parentPid == null) {+ continue+ }++ const siblings = children.get(entry.parentPid)++ if (siblings) {+ siblings.push(entry.pid)+ } else {+ children.set(entry.parentPid, [entry.pid])+ }+ }++ const protectedPids = new Set<number>()++ for (const entry of running) {+ if (!entry.path || !entry.commandLine?.trim() || isSharedRuntime(entry.path)) {+ protectedPids.add(entry.pid)+ }+ }++ const queue = [...protectedPids]++ while (queue.length > 0) {+ const parent = queue.pop() as number++ for (const child of children.get(parent) ?? []) {+ if (!protectedPids.has(child)) {+ protectedPids.add(child)+ queue.push(child)+ }+ }+ }++ return protectedPids+}++/**+ * Reap package-rooted tools outside the protected runtime trees.** Best effort by construction: this runs on the quit path, so a failure to* enumerate or to kill is logged and swallowed rather than allowed to hang or- * crash the shutdown. A process whose path cannot be read is left alone — the- * cost of missing one pinner is the bug we already have, while killing a- * process we could not identify is unbounded damage.+ * crash the shutdown. A process whose path OR command line cannot be read is+ * left alone — the cost of missing one pinner is the bug we already have,+ * while killing a process we could not identify is unbounded damage.*/export function reapPackageRootedProcesses(deps: ReapPackageRootedProcessesDeps): ReapOutcome {const isWindows = deps.isWindows ?? process.platform === 'win32'@@ -246,12 +250,24 @@ export function reapPackageRootedProcesses(deps: ReapPackageRootedProcessesDeps)}const excluded = new Set<number>(deps.excludePids ?? [])+ const runtimeProtected = protectedRuntimePids(running)const killed: number[] = []const failed: number[] = []let matched = 0for (const candidate of running) {- if (!Number.isInteger(candidate.pid) || candidate.pid === deps.selfPid || excluded.has(candidate.pid)) {+ if (+ !Number.isInteger(candidate.pid) ||+ candidate.pid === deps.selfPid ||+ excluded.has(candidate.pid) ||+ runtimeProtected.has(candidate.pid)+ ) {+ continue+ }++ // Conservative skip: an unreadable command line cannot prove the process+ // is not a live Hermes runtime, so it is never a candidate.+ if (typeof candidate.commandLine !== 'string' || candidate.commandLine.trim() === '') {continue}diff --git a/apps/desktop/electron/pool-spawn-coordinator.test.ts b/apps/desktop/electron/pool-spawn-coordinator.test.tsindex 73b2291fe1e..a9207ccfc93 100644--- a/apps/desktop/electron/pool-spawn-coordinator.test.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.test.ts@@ -110,7 +110,7 @@ test('100 real child processes never exceed twelve simultaneous local slots', asconst limit = 12const coordinator = new LocalBackendSpawnCoordinator(limit)const livePids = new Set<number>()- const seenPids = new Set<number>()+ let completed = 0let maxLive = 0await Promise.all(@@ -124,7 +124,6 @@ test('100 real child processes never exceed twelve simultaneous local slots', asassert.ok(child.pid)livePids.add(child.pid)- seenPids.add(child.pid)maxLive = Math.max(maxLive, livePids.size)await new Promise<void>((resolve, reject) => {@@ -139,13 +138,14 @@ test('100 real child processes never exceed twelve simultaneous local slots', as})livePids.delete(child.pid)+ completed += 1} finally {release()}}))- assert.equal(seenPids.size, 100)+ assert.equal(completed, 100) // PID values may be reused after a child exits.assert.equal(maxLive, limit)assert.equal(livePids.size, 0)assert.equal(coordinator.activeCount, 0)diff --git a/apps/desktop/electron/ssh-config.test.ts b/apps/desktop/electron/ssh-config.test.tsindex 01eb8991055..54a8dd55618 100644--- a/apps/desktop/electron/ssh-config.test.ts+++ b/apps/desktop/electron/ssh-config.test.ts@@ -1,4 +1,5 @@import assert from 'node:assert/strict'+import path from 'node:path'import { test } from 'vitest'@@ -36,7 +37,7 @@ test('collectSshConfigHosts follows Include directives (read-only)', () => {const hosts = collectSshConfigHosts('/home/u/.ssh/config', {homeDir: '/home/u',- readFile: p => files[p] ?? null+ readFile: p => files[p.replaceAll(path.sep, "/")] ?? null})assert.deepEqual(hosts.sort(), ['deep', 'home-abs', 'main', 'work-box'].sort())@@ -54,7 +55,7 @@ test('collectSshConfigHosts does not loop on a self-include cycle', () => {const hosts = collectSshConfigHosts('/home/u/.ssh/config', {homeDir: '/home/u',- readFile: p => files[p] ?? null+ readFile: p => files[p.replaceAll(path.sep, "/")] ?? null})assert.deepEqual(hosts.sort(), ['a', 'b'])@@ -69,9 +70,9 @@ test('collectSshConfigHosts expands globbed includes via injected globSync', ()const hosts = collectSshConfigHosts('/home/u/.ssh/config', {homeDir: '/home/u',- readFile: p => files[p] ?? null,+ readFile: p => files[p.replaceAll(path.sep, "/")] ?? null,globSync: pattern =>- pattern.endsWith('config.d/*') ? ['/home/u/.ssh/config.d/10-work', '/home/u/.ssh/config.d/20-home'] : [pattern]+ pattern.replaceAll(path.sep, '/').endsWith('config.d/*') ? ['/home/u/.ssh/config.d/10-work', '/home/u/.ssh/config.d/20-home'] : [pattern]})assert.deepEqual(hosts.sort(), ['home', 'root', 'work'].sort())diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.tsindex fa954cebbda..05095ef0fcc 100644--- a/apps/desktop/electron/ssh-connection.test.ts+++ b/apps/desktop/electron/ssh-connection.test.ts@@ -87,7 +87,7 @@ test('controlSocketPath is stable, short, and host-distinct', () => {assert.equal(a, a2, 'same triple → same socket (ControlMaster reuse)')assert.notEqual(a, b, 'different host → different socket')// 16 hex chars + .sock keeps the basename short for sun_path 104-byte limit- assert.match(a, /\/[0-9a-f]{16}\.sock$/)+ assert.match(path.basename(a), /^[0-9a-f]{16}\.sock$/)})test('controlSocketPath default base stays under sun_path even with the temp-listener suffix', () => {@@ -279,7 +279,7 @@ test('open() establishes the master when not already alive', async () => {return { code: 0 }})- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: '/tmp/d' })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d' })await conn.open()assert.deepEqual(ops, ['check', 'master'], 'probes liveness first, then opens the master')})@@ -311,7 +311,7 @@ test('open() is a no-op when the master is already alive and execs verify', asynreturn { code: 0 } // check succeeds → alive; verify exec succeeds → trusted})- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: '/tmp/d' })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d' })await conn.open()assert.deepEqual(ops, ['check', 'verify'], 'alive master is exec-verified, then trusted without reopening')})@@ -346,7 +346,7 @@ test('open() evicts a wedged master (check passes, exec hangs) and dials fresh',return { code: 0 }})- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: '/tmp/d', connectTimeoutMs: 50 })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d', connectTimeoutMs: 50 })await conn.open()assert.deepEqual(@@ -372,7 +372,7 @@ test('close() removes the control socket when -O exit fails', async () => {return { code: 255, stderr: 'mux: master gone' } // -O exit fails})- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: dir })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: dir })await conn.open()fs.writeFileSync(conn.controlPath, '') // simulate the lingering socket fileawait conn.close()@@ -384,7 +384,7 @@ test('open() creates the control-socket directory if it does not exist', async (const dir = path.join(os.tmpdir(), `hermes-ssh-test-${process.pid}-${Date.now()}`)assert.ok(!fs.existsSync(dir), 'precondition: control dir absent')const spawnFn = scriptedSpawn(args => (args.includes('check') ? { code: 255 } : { code: 0 }))- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: dir })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: dir })try {await conn.open()@@ -451,7 +451,7 @@ test('exec() treats a hung ssh as a timeout (half-open connection)', async () =>test('forward() issues -O forward with a loopback-bound -L spec', async () => {const spawnFn = scriptedSpawn([{ code: 0 }])- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: '/tmp/d' })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d' })await conn.forward(5000, 6000)const args = spawnFn.calls[0]assert.equal(args[0], '-O')@@ -465,7 +465,7 @@ test('lifecycle logging passes through redaction', async () => {const conn = new SshConnection({ host: 'box', user: 'me' },- { spawnFn, controlDir: '/tmp/d', rememberLog: l => logs.push(l) }+ { spawnFn, mux: true, controlDir: '/tmp/d', rememberLog: l => logs.push(l) })await conn.open()@@ -920,7 +920,7 @@ test('runSsh delivers stdinData to the child and does not log it', async () => {assert.equal(stdinWritten, 'secret-token-value', 'stdinData must be written to child.stdin')})-test('open() rejects a control-dir that is a symlink', async () => {+test.runIf(process.platform !== 'win32')('open() rejects a control-dir that is a symlink', async () => {const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ssh-test-'))const real = path.join(tmp, 'real')const link = path.join(tmp, 'link')@@ -1006,7 +1006,7 @@ test('closing one scope addresses only that scope control master', async () => {{ host: 'box', user: 'me' },{spawnFn: firstSpawn,- controlDir: '/tmp/d',+ mux: true, controlDir: '/tmp/d',ownershipId: 'installation',scope: 'first'}@@ -1016,7 +1016,7 @@ test('closing one scope addresses only that scope control master', async () => {{ host: 'box', user: 'me' },{spawnFn: secondSpawn,- controlDir: '/tmp/d',+ mux: true, controlDir: '/tmp/d',ownershipId: 'installation',scope: 'second'}@@ -1037,7 +1037,7 @@ test('failed ControlMaster close disowns the master instead of retrying it', asy// contract: a master that refuses -O exit is disowned — socket dropped,// connection marked closed — so the next open dials fresh.const spawnFn = scriptedSpawn([{ code: 255, stderr: 'master refused exit' }])- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: '/tmp/d' })+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d' })conn._opened = trueawait conn.close()assert.equal(conn._opened, false)diff --git a/apps/desktop/scripts/before-build.mjs b/apps/desktop/scripts/before-build.mjsindex 9dd0ba38562..acb4d5b14c8 100644--- a/apps/desktop/scripts/before-build.mjs+++ b/apps/desktop/scripts/before-build.mjs@@ -102,53 +102,12 @@ function writeMsixExtensions() {</uap3:Properties></uap3:AppExtension></uap3:Extension>-${aliases}${serviceExtensions()}`+${aliases}`fs.mkdirSync(path.dirname(file), { recursive: true })fs.writeFileSync(file, copilot)}-/**- * The desktop6:Service fragment registering HermesGateway as a Windows- * Service (plan: gateway-msix-windows-service; Task 2).- *- * The service Executable is the payload's own launcher (hermes.exe —- * the distlib-minted PE that already serves the AppExecutionAliases):- * its `gateway run --service` mode is the SCM frontend- * (gateway/windows_service.py). NO separate shim binary.- *- * Settled decisions baked here (2026-09-03, ethie): user-context- * service (StartAccount omitted — desktop6 defaults to the installing- * user's context; localSystem explicitly rejected), demand StartupType- * (config-only posture: the service arrives STOPPED; `hermes gateway- * service on` flips it to automatic-at-logon).- *- * Content rules (the 0x80080204 playbook): xmlns:desktop6 rides the- * fragment root; ONE extension block; Executable must name a real in-- * package exe. Requires Win10 1903+ — the minVersion bump in- * gen-msix-manifest.mjs matches. Exported pure for tests.- */-export function serviceExtensions({- name = 'HermesGateway',- executable = ['app', 'resources', 'agent-payload', 'bin', 'hermes.exe'].join(String.fromCharCode(92)),- variant = 'bundled',-} = {}) {- // light variant ships no payload → no service; the store variant is- // decided by Store policy separately (plan risk item) — both render- // service-less for now.- if (variant === 'light' || variant === 'store') return ''- return `<desktop6:Extension- xmlns:desktop6="http://schemas.microsoft.com/appx/manifest/desktop/windows10/6"- Category="windows.service"- Executable="${executable}"- EntryPoint="Windows.FullTrustApplication">- <desktop6:Service- Name="${name}"- StartupType="demand" />-</desktop6:Extension>-`-}-/*** One uap5:Extension block per payload CLI launcher, each naming its own* Executable (the distlib-minted launcher exes under bin/) and the aliasdiff --git a/apps/desktop/scripts/check-appinstaller-update.py b/apps/desktop/scripts/check-appinstaller-update.pyindex ea50803eb99..5fd8272c692 100644--- a/apps/desktop/scripts/check-appinstaller-update.py+++ b/apps/desktop/scripts/check-appinstaller-update.py@@ -14,45 +14,74 @@ Exit codes:0 no update available (or no App Installer source — nothing to do)2 update available (the caller decides whether to prompt/teardown)1 error (update availability unknown; the caller reports it honestly)++API shape (pywinrt projection, verified against the installed winrt 3.2.1):+``Package.current`` is a static PROPERTY; the update check is the instance+method ``Package.check_update_availability_async`` — ``PackageManager`` has+no such method. ``PackageUpdateAvailability`` members (verified live in the+installed projection): UNKNOWN=0, NO_UPDATES=1, AVAILABLE=2, REQUIRED=3,+ERROR=4. Only the specific "no package identity" HRESULT (0x80073D54) means+not-packaged; every other failure is an unknown, never a "no update"."""import jsonimport sys+# HRESULT 0x80073D54 — "The process has no package identity." The one+# failure that positively identifies a non-packaged (dev) run.+_NO_PACKAGE_IDENTITY_HRESULT = -2147009196+++def _load_projection():+ from winrt.windows.applicationmodel import Package, PackageUpdateAvailability++ return Package, PackageUpdateAvailability+def main() -> int:try:- from winrt.windows.applicationmodel import Package, PackageUpdateAvailability- from winrt.windows.management.deployment import PackageManager+ Package, PackageUpdateAvailability = _load_projection()except ImportError as exc:# The winrt module is absent (older payload without the dep): the# update check cannot run. Report unknown, not "no update".print(json.dumps({"available": None, "error": f"winrt import failed: {exc}"}))return 1+ # Property access, not a call: a packaged process gets the Package+ # instance; a dev run raises the package-identity HRESULT.try:- package = Package.current()- except Exception as exc: # noqa: BLE001 — the API raises on non-packaged runs- # Not running as a packaged app (dev run) — nothing to check.- print(json.dumps({"available": False, "reason": "not-packaged"}))- return 0+ package = Package.current+ except OSError as exc:+ if getattr(exc, "winerror", None) == _NO_PACKAGE_IDENTITY_HRESULT:+ print(json.dumps({"available": False, "reason": "not-packaged"}))+ return 0+ print(json.dumps({"available": None, "error": f"package identity failed: {exc}"}))+ return 1+ except Exception as exc: # noqa: BLE001 — projection shape surprises are unknowns+ print(json.dumps({"available": None, "error": f"package identity failed: {exc}"}))+ return 1- package_family_name = package.id.family_name- manager = PackageManager()try:- result = manager.check_package_update_availability_async(package_family_name).get()+ result = package.check_update_availability_async().get()+ availability = PackageUpdateAvailability(result.availability)except Exception as exc: # noqa: BLE001print(json.dumps({"available": None, "error": f"check failed: {exc}"}))return 1- availability = PackageUpdateAvailability(result.availability)- # Available / Required both mean "a newer package exists on the source".- available = availability in (- PackageUpdateAvailability.AVAILABLE,- PackageUpdateAvailability.REQUIRED,- )- print(json.dumps({"available": available, "availability": str(availability)}))- return 2 if available else 0+ # Only AVAILABLE / REQUIRED mean "a newer package exists". NO_UPDATES is+ # the one honest "no". UNKNOWN and ERROR are NOT "no update" — reporting+ # them as such would suppress a real update prompt — so they surface as+ # an unknown with the availability name as the extended error.+ if availability == PackageUpdateAvailability.NO_UPDATES:+ print(json.dumps({"available": False, "availability": availability.name}))+ return 0++ if availability in (PackageUpdateAvailability.AVAILABLE, PackageUpdateAvailability.REQUIRED):+ print(json.dumps({"available": True, "availability": availability.name}))+ return 2++ print(json.dumps({"available": None, "error": f"availability unknown: {availability.name}"}))+ return 1if __name__ == "__main__":diff --git a/apps/desktop/scripts/cli-launchers.test.mjs b/apps/desktop/scripts/cli-launchers.test.mjsindex 446c5344a8a..c75f2f2a001 100644--- a/apps/desktop/scripts/cli-launchers.test.mjs+++ b/apps/desktop/scripts/cli-launchers.test.mjs@@ -1,10 +1,15 @@import assert from 'node:assert/strict'+import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'import { test } from 'vitest'-import { CLI_LAUNCHER_SPECS, posixTrampolineScripts, renderWinWrapper } from '../../../scripts/desktop-cli/cli-entrypoints.mjs'+import {+ CLI_LAUNCHER_SPECS,+ posixTrampolineScripts,+ renderWinWrapper+} from '../../../scripts/desktop-cli/cli-entrypoints.mjs'import { appExecutionAliasExtensions } from './before-build.mjs'const scriptDir = path.dirname(fileURLToPath(import.meta.url))@@ -18,18 +23,23 @@ const RELS = {}test('three launcher specs mirror [project.scripts] in pyproject.toml', () => {- assert.deepEqual(CLI_LAUNCHER_SPECS.map((s) => s.name), ['hermes', 'hermes-agent', 'hermes-acp'])- assert.deepEqual(CLI_LAUNCHER_SPECS.map((s) => `${s.module}:${s.func}`), [- 'hermes_cli.main:main',- 'run_agent:main',- 'acp_adapter.entry:main'- ])+ assert.deepEqual(+ CLI_LAUNCHER_SPECS.map(s => s.name),+ ['hermes', 'hermes-agent', 'hermes-acp']+ )+ assert.deepEqual(+ CLI_LAUNCHER_SPECS.map(s => `${s.module}:${s.func}`),+ ['hermes_cli.main:main', 'run_agent:main', 'acp_adapter.entry:main']+ )})const scripts = posixTrampolineScripts(RELS)test('one POSIX trampoline per entry, named plainly (no suffix)', () => {- assert.deepEqual(scripts.map((s) => s.name), ['hermes', 'hermes-agent', 'hermes-acp'])+ assert.deepEqual(+ scripts.map(s => s.name),+ ['hermes', 'hermes-agent', 'hermes-acp']+ )})test('trampoline is $0-relative: shebang, symlink-chain resolution, own-dir cd', () => {@@ -70,7 +80,7 @@ test('trampoline fails loudly (exit 2) when the bundled interpreter is missing',})test('each trampoline execs its own entry module', () => {- const modules = scripts.map((s) => /exec "\$PYTHON" -m (\S+) "\$@"/.exec(s.text)?.[1])+ const modules = scripts.map(s => /exec "\$PYTHON" -m (\S+) "\$@"/.exec(s.text)?.[1])assert.deepEqual(modules, ['hermes_cli.main', 'run_agent', 'acp_adapter.entry'])})@@ -116,45 +126,18 @@ test('light variant emits no alias fragments', () => {assert.ok(scriptDir.length > 0)})-// ── HermesGateway Windows Service fragment (Task 2, plan:-// gateway-msix-windows-service) ────────────────────────────────────────-import { serviceExtensions } from './before-build.mjs'--test('bundled variant registers HermesGateway, demand-start, launcher exe', () => {- const frag = serviceExtensions()- assert.ok(frag.includes('Category="windows.service"'), 'service category')- assert.ok(frag.includes('Name="HermesGateway"'), 'the service name the CLI verbs key off')- assert.ok(frag.includes('StartupType="demand"'), 'config-only posture: arrives stopped')- // Compose the expected path the same way the source does — no escaping- // ambiguity (the appExecutionAliasExtensions precedent).- const bs = String.fromCharCode(92)- const launcherPath = ['app', 'resources', 'agent-payload', 'bin', 'hermes.exe'].join(bs)- assert.ok(- frag.includes(`Executable="${launcherPath}"`),- 'the service Executable is the payload launcher (no shim binary)'- )- assert.ok(!frag.includes('StartAccount'), 'user-context by default — localSystem rejected')-})--test('light and store variants render service-less', () => {- assert.equal(serviceExtensions({ variant: 'light' }), '')- assert.equal(serviceExtensions({ variant: 'store' }), '')-})--test('one desktop6 extension block with xmlns on the fragment root', () => {- const frag = serviceExtensions()- assert.equal(- (frag.match(/<desktop6:Extension/g) || []).length,- 1,- 'the 0x80080204 playbook: ONE extension block'- )- assert.ok(- frag.includes('xmlns:desktop6="http://schemas.microsoft.com/appx/manifest/desktop/windows10/6"'),- 'namespace rides the fragment root (the copilot-fragment precedent)'- )-})--test('custom name propagates (per-install namespacing)', () => {- const frag = serviceExtensions({ name: 'HermesGateway_Tag1' })- assert.ok(frag.includes('Name="HermesGateway_Tag1"'))+// ── HermesGateway Windows Service fragment (removed) ──────────────────────+// The MSIX SCM service feature was removed (settled 2026-09-03: the existing+// user-logon Scheduled Task supervises the gateway; a desktop6:Service+// cannot run as the installing user — the desktop6 schema requires+// StartAccount in localSystem|localService|networkService). This pins the+// removal so the invalid fragment cannot silently come back.++test('the manifest extension writer registers no windows.service', () => {+ // writeMsixExtensions is the one writer; its source must carry no+ // desktop6:Service emission (this is a removal pin, not a shape snapshot:+ // any NEW extension fragments may be added freely).+ const source = fs.readFileSync(new URL('./before-build.mjs', import.meta.url), 'utf8')+ assert.ok(!source.includes('windows.service'), 'no windows.service Category emitted')+ assert.ok(!source.includes('desktop6:Service'), 'no desktop6:Service fragment emitted')})diff --git a/apps/desktop/scripts/gen-msix-manifest.mjs b/apps/desktop/scripts/gen-msix-manifest.mjsindex 798dc36d220..1a5e5373261 100644--- a/apps/desktop/scripts/gen-msix-manifest.mjs+++ b/apps/desktop/scripts/gen-msix-manifest.mjs@@ -105,8 +105,10 @@ const manifest = substituteManifestMacros(template, (m) => {case "resourceLanguages": return resourceLanguageTag(options.languages)case "capabilities": return `<Capabilities>\n${buildCapabilitiesXml(options.capabilities)}\n</Capabilities>`case "extensions": return extensions- // Win10 1903 (build 18362) floor: desktop6:Service — the MSIX-shipped- // HermesGateway Windows Service — requires 1903+; settled 2026-09-03.+ // Win10 1903 (build 18362) floor, settled 2026-09-03. (An earlier+ // desktop6:Service fragment rode this floor; the service feature was+ // removed — the Scheduled Task supervises the gateway instead — but the+ // shipped floor stays put rather than churning the release minimum.)// 1809 is a 2018 OS; the bump rides the release notes.case "minVersion": return options.minVersion || "10.0.18362.0"case "maxVersionTested": return options.maxVersionTested || options.minVersion || "10.0.18362.0"diff --git a/apps/desktop/scripts/stage-native-deps.test.mjs b/apps/desktop/scripts/stage-native-deps.test.mjsindex 9d20a039fbb..3971346d3c4 100644--- a/apps/desktop/scripts/stage-native-deps.test.mjs+++ b/apps/desktop/scripts/stage-native-deps.test.mjs@@ -594,7 +594,7 @@ test('darwin staging ships the Swift helper executable and the rewritten windowsstageGetWindowsInto(srcRoot, destRoot, { platform: 'darwin' })- assert.equal(fs.statSync(join(destRoot, 'main')).mode & 0o777, 0o755)+ if (process.platform !== 'win32') assert.equal(fs.statSync(join(destRoot, 'main')).mode & 0o777, 0o755)const staged = fs.readFileSync(join(destRoot, 'lib', 'windows.js'), 'utf8')assert.match(staged, /Rewritten by stage-native-deps\.mjs/)assert.ok(!staged.includes('node-pre-gyp'), 'pre-gyp loader must not survive staging')diff --git a/apps/desktop/src/components/update-status.test.tsx b/apps/desktop/src/components/update-status.test.tsxindex a7a2c5e250b..cb7d99d95b4 100644--- a/apps/desktop/src/components/update-status.test.tsx+++ b/apps/desktop/src/components/update-status.test.tsx@@ -1,10 +1,31 @@-import { describe, expect, it } from 'vitest'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'-import type { DesktopUpdateStatus } from '@/global'+import type { DesktopUpdateStatus, DesktopVersionInfo } from '@/global'import { en } from '@/i18n/en'import type { UpdateApplyState } from '@/store/updates'-import { deriveUpdateStatus } from './update-status'+import { deriveUpdateStatus, VersionHero } from './update-status'++// VersionHero is the shared About/overlay hero. Its module imports the real+// updates store graph; mock it shallowly — these tests exercise the hero's+// own rendering, not the store.+vi.mock('@/store/updates', async () => {+ const { atom } = await import('nanostores')++ return {+ $backendUpdateApply: atom<UpdateApplyState | null>(null),+ $backendUpdateChecking: atom<boolean>(false),+ $backendUpdateStatus: atom<DesktopUpdateStatus | null>(null),+ $updateApply: atom<UpdateApplyState | null>(null),+ $updateChecking: atom<boolean>(false),+ $updateStatus: atom<DesktopUpdateStatus | null>(null),+ checkBackendUpdates: vi.fn(),+ checkUpdates: vi.fn(),+ openUpdateOverlayFor: vi.fn(),+ startActiveUpdate: vi.fn()+ }+})const IDLE_APPLY: UpdateApplyState = {applying: false,@@ -89,3 +110,66 @@ describe('deriveUpdateStatus', () => {expect(view.line).toBe(en.updates.latestBodyBackend)})})++describe('VersionHero bundle banners', () => {+ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ const version = (over: Partial<DesktopVersionInfo>): DesktopVersionInfo =>+ ({ appVersion: '0.19.0', ...over }) as DesktopVersionInfo++ const stubRelaunch = () => {+ const relaunchApp = vi.fn().mockResolvedValue(undefined)+ const original = window.hermesDesktop+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { ...original, openExternal: vi.fn(), relaunchApp }+ })++ return relaunchApp+ }++ // FAIL-BEFORE (C19): the shared About extraction dropped the swap-pending+ // restart affordance even though main still produces bundleSwapPending and+ // exposes the relaunchApp IPC — users could no longer finish an applied+ // update from the UI.+ it('swap-pending: restart banner wired to relaunchApp, not the installer link', () => {+ const relaunchApp = stubRelaunch()++ render(<VersionHero version={version({ bundleSwapPending: true })} />)++ expect(screen.getByText(en.updates.bundleSwapPending)).toBeTruthy()+ expect(screen.queryByText(en.updates.bundleOutOfSync)).toBeNull()++ fireEvent.click(screen.getByRole('button', { name: en.updates.bundleSwapPendingAction }))+ expect(relaunchApp).toHaveBeenCalledTimes(1)+ })++ it('out-of-sync without a pending swap: keeps the get-installer banner', () => {+ stubRelaunch()++ render(<VersionHero version={version({ bundleOutOfSync: true })} />)++ expect(screen.getByText(en.updates.bundleOutOfSync)).toBeTruthy()+ expect(screen.queryByText(en.updates.bundleSwapPending)).toBeNull()+ expect(screen.queryByRole('button', { name: en.updates.bundleSwapPendingAction })).toBeNull()+ })++ it('a pending swap wins over the out-of-sync banner — restart, not reinstall', () => {+ stubRelaunch()++ render(<VersionHero version={version({ bundleOutOfSync: true, bundleSwapPending: true })} />)++ expect(screen.getByText(en.updates.bundleSwapPending)).toBeTruthy()+ expect(screen.queryByText(en.updates.bundleOutOfSync)).toBeNull()+ })++ it('no flags: no banner at all', () => {+ render(<VersionHero version={version({})} />)++ expect(screen.queryByText(en.updates.bundleOutOfSync)).toBeNull()+ expect(screen.queryByText(en.updates.bundleSwapPending)).toBeNull()+ })+})diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsxindex 56305b318d0..e5afb23dc4a 100644--- a/apps/desktop/src/components/update-status.tsx+++ b/apps/desktop/src/components/update-status.tsx@@ -154,27 +154,41 @@ export function VersionHero({{version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}</p></div>- {version?.bundleOutOfSync && (+ {(version?.bundleSwapPending || version?.bundleOutOfSync) && (<div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm"><div className="flex items-start gap-2"><AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" /><div className="min-w-0">- <p className="font-medium">{u.bundleOutOfSync}</p>- <p className="mt-1 text-xs text-muted-foreground">{u.bundleOutOfSyncDesc}</p>- <Button asChild className="mt-2" size="sm" variant="textStrong">- <a- href={INSTALLER_URL}- onClick={event => {- event.preventDefault()- void window.hermesDesktop?.openExternal?.(INSTALLER_URL)- }}- rel="noreferrer"- target="_blank"+ <p className="font-medium">{version.bundleSwapPending ? u.bundleSwapPending : u.bundleOutOfSync}</p>+ <p className="mt-1 text-xs text-muted-foreground">+ {version.bundleSwapPending ? u.bundleSwapPendingDesc : u.bundleOutOfSyncDesc}+ </p>+ {version.bundleSwapPending ? (+ <Button+ className="mt-2"+ onClick={() => void window.hermesDesktop?.relaunchApp?.()}+ size="sm"+ variant="textStrong">- <ExternalLink className="size-3" />- {u.bundleOutOfSyncAction}- </a>- </Button>+ <RefreshCw className="size-3" />+ {u.bundleSwapPendingAction}+ </Button>+ ) : (+ <Button asChild className="mt-2" size="sm" variant="textStrong">+ <a+ href={INSTALLER_URL}+ onClick={event => {+ event.preventDefault()+ void window.hermesDesktop?.openExternal?.(INSTALLER_URL)+ }}+ rel="noreferrer"+ target="_blank"+ >+ <ExternalLink className="size-3" />+ {u.bundleOutOfSyncAction}+ </a>+ </Button>+ )}</div></div></div>diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 899213afc5e..a162eae3f98 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -673,40 +673,7 @@ export const ar = defineLocale({'عندما يحدّث Hermes نفسه من التطبيق دون موجه طرفية، احتفظ بتعديلات المصدر المحلية أو تجاهلها.'},about: {- heading: 'حول Hermes',- version: value => `الإصدار ${value}`,- versionUnavailable: 'الإصدار غير متاح',- bundleOutOfSync: 'إصدار التطبيق قديم',- bundleOutOfSyncDesc:- 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',- bundleOutOfSyncAction: 'الحصول على المثبّت',- bundleSwapPending: 'أعد التشغيل لإكمال التحديث',- bundleSwapPendingDesc:- 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',- bundleSwapPendingAction: 'إعادة تشغيل Hermes',updates: 'التحديثات',- checkNow: 'التحقق الآن',- checking: 'جار التحقق...',- seeWhatsNew: 'عرض الجديد',- updateNow: 'تحديث الآن',- releaseNotes: 'ملاحظات الإصدار',- onLatest: 'أنت على أحدث إصدار',- installing: 'جار التثبيت...',- cantUpdate: 'تعذر التحديث',- cantReach: 'تعذر الوصول لخدمة التحديث',- tapCheck: 'اضغط للتحقق من التحديثات.',- updateReady: count => `${count} تحديث متاح`,- updateReadyUnknown: 'تحديث جديد جاهز.',- lastChecked: age => `آخر تحقق ${age}`,- justNowSuffix: 'الآن',- automaticUpdates: 'التحديثات التلقائية',- automaticUpdatesDesc: 'اسمح لـ Hermes بالتحقق من التحديثات وتثبيتها.',- branchCommit: (branch, commit) => `${branch} عند ${commit}`,- never: 'أبدا',- justNow: 'الآن',- minAgo: count => `قبل ${count} دقيقة`,- hoursAgo: count => `قبل ${count} ساعة`,- daysAgo: count => `قبل ${count} يوم`},config: {@@ -2006,6 +1973,9 @@ export const ar = defineLocale({}},updates: {+ bundleSwapPending: 'أعد التشغيل لإكمال التحديث',+ bundleSwapPendingDesc: 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',+ bundleSwapPendingAction: 'إعادة تشغيل Hermes',stages: {idle: 'جار التحضير...',prepare: 'جار التحضير...',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 5bc867abce1..44ce4af8c76 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -682,42 +682,7 @@ export const en: Translations = {fieldLabels: FIELD_LABELS,fieldDescriptions: FIELD_DESCRIPTIONS,about: {- heading: 'Hermes Desktop',- version: value => `Version ${value}`,- versionUnavailable: 'Version unavailable',- bundleOutOfSync: 'App build out of date',- bundleOutOfSyncDesc:- 'The Hermes runtime was updated, but the desktop app itself is still an older build — new interface features (like Bot Mode) will be missing until it updates. Run the update below to rebuild the app. If that doesn\u2019t clear this warning, reinstall from the latest desktop installer.',- bundleOutOfSyncAction: 'Get the installer',- bundleSwapPending: 'Restart to finish the update',- bundleSwapPendingDesc:- 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',- bundleSwapPendingAction: 'Restart Hermes',updates: 'Updates',- checkNow: 'Check now',- checking: 'Checking…',- seeWhatsNew: "See what's new",- updateNow: 'Update now',- releaseNotes: 'Release notes',- onLatest: "You're on the latest version.",- installing: 'An update is currently installing.',- cantUpdate: "This build can't update itself from inside the app.",- cantReach: "We couldn't reach the update server.",- tapCheck: 'Tap "Check now" to look for updates.',- updateReady: count => `A new update is ready (${count} change${count === 1 ? '' : 's'} included).`,- updateReadyUnknown: 'A new update is ready.',- availableBodyRelease: tag => `Version ${tag} is ready to install.`,- lastChecked: age => `Last checked ${age}`,- justNowSuffix: ' · just now',- automaticUpdates: 'Automatic updates',- automaticUpdatesDesc:- 'Hermes checks for updates automatically in the background and lets you know when one is ready.',- branchCommit: (branch, commit) => `Branch ${branch} · Commit ${commit}`,- never: 'never',- justNow: 'just now',- minAgo: count => `${count} min ago`,- hoursAgo: count => `${count} hours ago`,- daysAgo: count => `${count} days ago`},config: {none: 'None',@@ -2736,6 +2701,9 @@ export const en: Translations = {},updates: {+ bundleSwapPending: 'Restart to finish the update',+ bundleSwapPendingDesc: 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',+ bundleSwapPendingAction: 'Restart Hermes',stages: {idle: 'Getting ready…',prepare: 'Getting ready…',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex dc0f68c26a5..feb0b9f9a2a 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -724,40 +724,7 @@ export const ja = defineLocale({}}),about: {- heading: 'Hermes Desktop',- version: value => `バージョン ${value}`,- versionUnavailable: 'バージョンを取得できません',- bundleOutOfSync: 'アプリのビルドが古くなっています',- bundleOutOfSyncDesc:- 'Hermes ランタイムは更新されましたが、デスクトップアプリ自体は古いビルドのままです。アプリを更新するまで、新しいインターフェース機能(Bot Mode など)は表示されません。下の更新を実行してアプリを再ビルドしてください。それでもこの警告が消えない場合は、最新のデスクトップインストーラーから再インストールしてください。',- bundleOutOfSyncAction: 'インストーラーを入手',- bundleSwapPending: '再起動して更新を完了',- bundleSwapPendingDesc:- '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',- bundleSwapPendingAction: 'Hermes を再起動',updates: '更新',- checkNow: '今すぐ確認',- checking: '確認中…',- seeWhatsNew: '新機能を見る',- updateNow: '今すぐ更新',- releaseNotes: 'リリースノート',- onLatest: '最新バージョンです。',- installing: '更新をインストール中です。',- cantUpdate: 'このビルドはアプリ内から更新できません。',- cantReach: '更新サーバーに接続できませんでした。',- tapCheck: '更新を探すには「今すぐ確認」を押してください。',- updateReady: count => `新しい更新の準備ができました (${count} 件の変更を含みます)。`,- updateReadyUnknown: '新しい更新の準備ができました。',- lastChecked: age => `前回確認: ${age}`,- justNowSuffix: ' · たった今',- automaticUpdates: '自動更新',- automaticUpdatesDesc: 'Hermes はバックグラウンドで自動的に更新を確認し、利用可能になったら通知します。',- branchCommit: (branch, commit) => `ブランチ ${branch} · コミット ${commit}`,- never: '未確認',- justNow: 'たった今',- minAgo: count => `${count} 分前`,- hoursAgo: count => `${count} 時間前`,- daysAgo: count => `${count} 日前`},config: {none: 'なし',@@ -2356,6 +2323,9 @@ export const ja = defineLocale({},updates: {+ bundleSwapPending: '再起動して更新を完了',+ bundleSwapPendingDesc: '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',+ bundleSwapPendingAction: 'Hermes を再起動',stages: {idle: '準備中…',prepare: '準備中…',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 3a0d3ed3fd6..a3080a94c93 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -904,37 +904,7 @@ export const ru = defineLocale({}}),about: {- heading: 'Hermes Desktop',- version: value => `Версия ${value}`,- versionUnavailable: 'Версия недоступна',- bundleOutOfSync: 'Сборка приложения устарела',- bundleOutOfSyncDesc:- 'Рантайм Hermes обновлён, но само приложение — ещё старая сборка: новые функции интерфейса (например, Bot Mode) не появятся до обновления. Запустите обновление ниже, чтобы пересобрать приложение. Если предупреждение не исчезнет, переустановите с последнего установщика.',- bundleOutOfSyncAction: 'Скачать установщик',updates: 'Обновления',- checkNow: 'Проверить сейчас',- checking: 'Проверка…',- seeWhatsNew: 'Смотреть, что нового',- updateNow: 'Обновить сейчас',- releaseNotes: 'Заметки о выпуске',- onLatest: 'У вас последняя версия.',- installing: 'Сейчас устанавливается обновление.',- cantUpdate: 'Эта сборка не может обновляться изнутри приложения.',- cantReach: 'Не удалось связаться с сервером обновлений.',- tapCheck: 'Нажмите «Проверить сейчас», чтобы найти обновления.',- updateReady: count =>- `Готово новое обновление (включено ${count} ${RU_PLURAL(count, 'изменение', 'изменения', 'изменений')}).`,- updateReadyUnknown: 'Готово новое обновление.',- lastChecked: age => `Проверено ${age}`,- justNowSuffix: ' · только что',- automaticUpdates: 'Автоматические обновления',- automaticUpdatesDesc: 'Hermes автоматически проверяет обновления в фоне и сообщает, когда они готовы.',- branchCommit: (branch, commit) => `Ветка ${branch} · Коммит ${commit}`,- never: 'никогда',- justNow: 'только что',- minAgo: count => `${count} ${RU_NOUN(count, 'минуту', 'минуты', 'минут')} назад`,- hoursAgo: count => `${count} ${RU_NOUN(count, 'час', 'часа', 'часов')} назад`,- daysAgo: count => `${count} ${RU_NOUN(count, 'день', 'дня', 'дней')} назад`},config: {none: 'Нет',@@ -2756,6 +2726,9 @@ export const ru = defineLocale({}},updates: {+ bundleSwapPending: 'Перезапустите, чтобы завершить обновление',+ bundleSwapPendingDesc: 'Обновлённое приложение уже установлено — достаточно перезапустить Hermes, чтобы загрузить его. Чаты и настройки не пострадают.',+ bundleSwapPendingAction: 'Перезапустить Hermes',stages: {idle: 'Готовимся…',prepare: 'Готовимся…',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 632b20b3a94..f7aaf9c7e32 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -565,39 +565,7 @@ export interface Translations {fieldLabels: Record<string, string>fieldDescriptions: Record<string, string>about: {- heading: string- version: (value: string) => string- versionUnavailable: string- bundleOutOfSync: string- bundleOutOfSyncDesc: string- bundleOutOfSyncAction: string- bundleSwapPending: string- bundleSwapPendingDesc: string- bundleSwapPendingAction: stringupdates: string- checkNow: string- checking: string- seeWhatsNew: string- updateNow: string- releaseNotes: string- onLatest: string- installing: string- cantUpdate: string- cantReach: string- tapCheck: string- updateReady: (count: number) => string- updateReadyUnknown: string- availableBodyRelease: (tag: string) => string- lastChecked: (age: string) => string- justNowSuffix: string- automaticUpdates: string- automaticUpdatesDesc: string- branchCommit: (branch: string, commit: string) => string- never: string- justNow: string- minAgo: (count: number) => string- hoursAgo: (count: number) => string- daysAgo: (count: number) => string}config: {none: string@@ -2329,6 +2297,9 @@ export interface Translations {}updates: {+ bundleSwapPending: string+ bundleSwapPendingDesc: string+ bundleSwapPendingAction: stringstages: Record<string, string>checking: stringcheckFailedTitle: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 780ce48033a..7300eadbcbd 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -705,40 +705,7 @@ export const zhHant = defineLocale({}}),about: {- heading: 'Hermes Desktop',- version: value => `版本 ${value}`,- versionUnavailable: '版本不可用',- bundleOutOfSync: '應用程式建置版本過舊',- bundleOutOfSyncDesc:- 'Hermes 執行環境已更新,但桌面應用程式本身仍是舊建置——在應用程式更新之前,新的介面功能(如 Bot Mode)不會顯示。請執行下方的更新以重新建置應用程式。如果此警告仍未消除,請從最新的桌面安裝程式重新安裝。',- bundleOutOfSyncAction: '取得安裝程式',- bundleSwapPending: '重新啟動以完成更新',- bundleSwapPendingDesc:- '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',- bundleSwapPendingAction: '重新啟動 Hermes',updates: '更新',- checkNow: '立即檢查',- checking: '檢查中…',- seeWhatsNew: '查看新增內容',- updateNow: '立即更新',- releaseNotes: '發行說明',- onLatest: '你已是最新版本。',- installing: '正在安裝更新。',- cantUpdate: '此版本無法從應用程式內自行更新。',- cantReach: '無法連線到更新伺服器。',- tapCheck: '點選「立即檢查」以尋找更新。',- updateReady: count => `新更新已就緒(包含 ${count} 項變更)。`,- updateReadyUnknown: '新更新已就緒。',- lastChecked: age => `上次檢查:${age}`,- justNowSuffix: ' · 剛剛',- automaticUpdates: '自動更新',- automaticUpdatesDesc: 'Hermes 會在背景自動檢查更新,並在有可用更新時通知你。',- branchCommit: (branch, commit) => `分支 ${branch} · 提交 ${commit}`,- never: '從未',- justNow: '剛剛',- minAgo: count => `${count} 分鐘前`,- hoursAgo: count => `${count} 小時前`,- daysAgo: count => `${count} 天前`},config: {none: '無',@@ -2275,6 +2242,9 @@ export const zhHant = defineLocale({},updates: {+ bundleSwapPending: '重新啟動以完成更新',+ bundleSwapPendingDesc: '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',+ bundleSwapPendingAction: '重新啟動 Hermes',stages: {idle: '準備中…',prepare: '準備中…',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 36b2fd788ed..1f7e72f3256 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -883,40 +883,7 @@ export const zh: Translations = {}}),about: {- heading: 'Hermes Desktop',- version: value => `版本 ${value}`,- versionUnavailable: '版本不可用',- bundleOutOfSync: '应用构建版本过旧',- bundleOutOfSyncDesc:- 'Hermes 运行时已更新,但桌面应用本身仍是旧构建——在应用更新之前,新的界面功能(如 Bot Mode)不会显示。请运行下方的更新以重新构建应用。如果此警告仍未消除,请从最新的桌面安装程序重新安装。',- bundleOutOfSyncAction: '获取安装程序',- bundleSwapPending: '重启以完成更新',- bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',- bundleSwapPendingAction: '重启 Hermes',updates: '更新',- checkNow: '立即检查',- checking: '检查中…',- seeWhatsNew: '查看新增内容',- updateNow: '立即更新',- releaseNotes: '发行说明',- onLatest: '你已是最新版本。',- installing: '正在安装更新。',- cantUpdate: '此版本无法在应用内自我更新。',- cantReach: '无法连接更新服务器。',- tapCheck: '点击"立即检查"以查找更新。',- updateReady: count => `已准备好新更新 (包含 ${count} 项更改)。`,- updateReadyUnknown: '新更新已就绪。',- lastChecked: age => `上次检查:${age}`,- justNowSuffix: ' · 刚刚',- automaticUpdates: '自动更新',- automaticUpdatesDesc: 'Hermes 会在后台自动检查更新,并在有可用更新时通知你。',- branchCommit: (branch, commit) => `分支 ${branch} · 提交 ${commit}`,- never: '从未',- justNow: '刚刚',- minAgo: count => `${count} 分钟前`,- hoursAgo: count => `${count} 小时前`,- daysAgo: count => `${count} 天前`,- availableBodyRelease: (tag: string) => `版本 ${tag} 已可安装。`,},config: {none: '无',@@ -2899,6 +2866,9 @@ export const zh: Translations = {},updates: {+ bundleSwapPending: '重启以完成更新',+ bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',+ bundleSwapPendingAction: '重启 Hermes',stages: {idle: '准备中…',prepare: '准备中…',diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.tsindex a3a7c9cc810..58397f5a067 100644--- a/apps/desktop/src/store/updates.test.ts+++ b/apps/desktop/src/store/updates.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { DesktopUpdateStatus } from '@/global'+import { en } from '@/i18n/en'const storage = new Map<string, string>()@@ -174,7 +175,7 @@ describe('maybeNotifyUpdateAvailable', () => {expect(notifySpy).not.toHaveBeenCalled()})- // FAIL-BEFORE: a shallow installer clone reports behind:null + updateAvailable+ // FAIL-BEFORE (#C19): a shallow installer clone reports behind:null + updateAvailable// (exact count unknowable without a merge-base). The guard treated null as 0// and silently swallowed the notification entirely.it('still notifies with generic copy when the exact behind count is unknown', () => {@@ -182,6 +183,32 @@ describe('maybeNotifyUpdateAvailable', () => {expect(notifySpy).toHaveBeenCalledTimes(1)expect(notifySpy.mock.calls[0]?.[0]).toMatchObject({ message: 'A new update is available.' })})++ // FAIL-BEFORE (C19): an App Installer check legitimately carries no+ // targetSha — the OS reports availability against the .appinstaller feed,+ // so there is no commit identity to name. Requiring targetSha made the+ // mechanism-specific App Installer toast unreachable forever.+ it('notifies for an App Installer check even though it has no targetSha', () => {+ maybeNotifyUpdateAvailable(+ status({+ behind: null,+ currentVersion: '0.19.0',+ mechanism: 'app-installer',+ targetSha: undefined,+ updateAvailable: true+ })+ )++ expect(notifySpy).toHaveBeenCalledTimes(1)+ expect(notifySpy.mock.calls[0]?.[0]).toMatchObject({ message: en.notifications.updateReadyMessageAppInstaller })+ })++ // Eligibility stays mechanism-specific: a git-style check must still prove+ // there is a target commit before the toast fires — never a made-up SHA.+ it('stays quiet for a git-style check that names no target commit', () => {+ maybeNotifyUpdateAvailable(status({ targetSha: undefined }))+ expect(notifySpy).not.toHaveBeenCalled()+ })})describe('reportBackendContract', () => {diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex 746d8e85649..45204a6bea4 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -212,8 +212,19 @@ export function reportInstallMethodWarning(message: string | undefined): void {*/export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null, target: UpdateTarget = 'client') {// Either signal means "update ready": behind > 0 (git checkout) or- // updateAvailable (app-installer, shallow clone).- if (!status || status.supported === false || status.error || !status.targetSha) {+ // updateAvailable (shallow clone, App Installer feed).+ if (!status || status.supported === false || status.error) {+ return+ }++ // Eligibility is mechanism-specific: a git-style check proves an update is+ // waiting by naming the target commit (targetSha). An App Installer check+ // legitimately has no commit identity — the OS reports availability against+ // the .appinstaller feed — so its eligibility signal is updateAvailable+ // itself. Never fabricate a SHA to satisfy the key.+ const hasTargetIdentity = Boolean(status.targetSha) || status.mechanism === 'app-installer'++ if (!hasTargetIdentity) {return}diff --git a/cron/scheduler_script.py b/cron/scheduler_script.pyindex 55a67153e70..f0f9cd78526 100644--- a/cron/scheduler_script.py+++ b/cron/scheduler_script.py@@ -129,6 +129,20 @@ def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, strif sibling.exists():interpreter = sibling+ from hermes_cli._launchers import resolve_store_python+ from hermes_cli.runtime_paths import selected_venv, site_packages as dependency_site++ repo = Path(__file__).resolve().parents[1]+ managed_python = resolve_store_python(repo)+ if managed_python is not None:+ # A packaged caller may hand us the old venv launcher; select bytes+ # from the install record rather than interpreting relocated pyvenv.cfg.+ dependencies = dependency_site(selected_venv(repo))+ payload_dependencies = venv_dir / "Lib" / "site-packages"+ if (venv_dir.parent / "manifest.json").is_file() and payload_dependencies.is_dir():+ dependencies = payload_dependencies+ return str(managed_python), {"PYTHONPATH": os.pathsep.join([str(repo), str(dependencies)])}+cfg = _read_windows_pyvenv_cfg(venv_dir)home = cfg.get("home", "")site_packages = venv_dir / "Lib" / "site-packages"@@ -234,7 +248,9 @@ def _windows_cron_bootstrap_argv(the venv on ``PYTHONPATH``, but ``.pth`` files are only processed by ``site.addsitedir()``, soeditable installs would be invisible; bootstrap via addsitedir + ``runpy.run_path`` (keeps``__file__``/``sys.path[0]`` semantics). Plain invocation if the venv is unresolvable."""- site_packages = _sched.Path(env_overlay.get("VIRTUAL_ENV", "")) / "Lib" / "site-packages"+ site_packages = next((Path(item) for item in env_overlay.get("PYTHONPATH", "").split(os.pathsep)+ if Path(item).name == "site-packages"),+ _sched.Path(env_overlay.get("VIRTUAL_ENV", "")) / "Lib" / "site-packages")if not site_packages.is_dir():# Warn: silent fallback would make "editable installs invisible" undiagnosable.logger.warning(diff --git a/docs/pm-audit-status.md b/docs/pm-audit-status.mdnew file mode 100644index 00000000000..72df4a9c791--- /dev/null+++ b/docs/pm-audit-status.md@@ -0,0 +1,76 @@+# PM audit remediation status++This change integrates repairs from the aggregate branch audit. It is not a+release certificate. The audit compared `49945b14029e09fef608db9ede899377cdb54e11`+with merge base `433f7196760e5d76f77ea6d5464ee7f1b602a4ee`.++## Implemented repairs++| Findings | Implementation |+| --- | --- |+| C01, C11, C12, C24 | Remove the deleted TLS import; fix ACP file decoding, proxy path ownership, and the monitoring SDK call. |+| C02 | Restore code-execution schema, registration, and child lifecycle handling. |+| C03, C04, C17 | Keep update metadata commands read-only; synchronize plugin updates; compare feed identities correctly. |+| C05, C27, C28 | Include managed Python in the install closure; repair installer stage dispatch and runtime selection. |+| C06, C07, C09 | Remove the unsupported SCM surface. Retain Scheduled Task supervision and protect unrelated runtimes on desktop quit. |+| C08, C19 | Correct the App Installer checker and restore meaningful update states. |+| C10 | Repair uninstall dispatch and owned-link removal. |+| C13, C14 | Prepare one complete dependency environment before publication. Preserve declared constraints and explicit pins; permit compatible transitive upgrades. Infrastructure failures do not disable plugins. |+| C15, C18 | Retain recoverable tool-store entries on failed publication. Use atomic facts/config writes and context-local receipts. |+| C16, C29 | Migrate removed dependency helpers and restore missing-dependency hints. Run the embedded Hindsight service from its separate environment. |+| C20, C21 | Correct platform-test selection and make the removed-import guard inspect actual source. |+| C22, C23 | Publish immutable release artifacts before feeds and resolve FFmpeg artifacts by target. |+| C25 | Preserve paused downloads, resume handles, and single-worker ownership. |+| C26 | Wire the boot and plugin-cadence paths to their existing owners. |++Implementation does not mean that every platform acceptance test is complete.+The updater, backup, setup, voice-text helpers, and several plugins now use+one implementation per reconciled concern. Runtime paths have a shared owner+in `hermes_cli/runtime_paths.py`.++## Verification limits++The first broad native-Windows run completed its file list with 43,358 passed,+257 failed, and 1,390 skipped tests. Eight files had no completed result.+Repairs overlapped that run, so it does not certify the final tree.++A later run selected all changed Python test files plus the broad run's failed+files. Its 206 files reported 4,630 passed, one failed, and 330 skipped tests.+There were no files without completed results. The remaining failure was a+Hindsight setup fixture that crossed into dependency installation. The fixture+now isolates that boundary. The final six-file rerun reported 234 passed and+two skipped tests, including Hindsight setup, PM state, admission, environment+sanitization, and terminal timeout output. A separate four-file store review+rerun reported 83 passed and one skipped test.++Desktop renderer tests reported 7,225 passed. Electron tests reported 2,295+passed and 23 skipped. Both desktop TypeScript checks also passed after the+locked development packages were restored. These are unit/type checks, not an+installer or signed-release lifecycle test.++A real Hindsight side-environment daemon started in a disposable home, answered+its health endpoint with HTTP 200, and stopped successfully. This verifies+startup, health, and shutdown, not an LLM retain/recall operation.++## Remaining acceptance work++- Run the full Python suite on one fixed final tree and the relevant native+ platform CI lanes. Targeted reruns do not substitute for this gate.+- Complete packaged install, update, relaunch, and uninstall checks. Verify+ that the messaging gateway survives ordinary desktop quit.+- Complete the remaining updater-strategy and warning-surface contracts from+ the audit. Manual update checks alone do not prove those surfaces.+- Define and verify safe collection of obsolete dependency generations while+ older processes still use them. The current conservative retention avoids+ deleting a live generation but does not bound storage use.+- Strengthen publication recovery for process death between plugin-config and+ runtime-facts writes. Exception rollback is tested; those two files are not+ one crash-atomic transaction.+- Complete receipt correlation and failure-reporting checks across nested PM+ and updater operations.+- Reconcile the remaining documentation and complete the final aggregate diff+ review. The bounded pre-commit review does not cover every moved updater line.++The external audit directory contains the original reports, per-batch logs,+review adjudication, and the exact test-file selection. No remote release,+service installation, or push is implied by this commit.diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 6e40a97af77..3ed05ac3b69 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2622,7 +2622,8 @@ class BasePlatformAdapter(ABC):logger.info("[%s] Sending image: %s (alt=%s)", self.name,safe_url_for_log(image_url), alt_text[:30] if alt_text else "")if image_url.startswith("file://"):- sender, url_kw = self.send_image_file, {"image_path": _unquote(image_url[7:])}+ from urllib.request import url2pathname+ sender, url_kw = self.send_image_file, {"image_path": url2pathname(image_url[7:])}elif self._is_animation_url(image_url):sender, url_kw = self.send_animation, {"animation_url": image_url}else:diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.pyindex bd3c3062804..9442805501c 100644--- a/gateway/platforms/whatsapp_common.py+++ b/gateway/platforms/whatsapp_common.py@@ -15,6 +15,7 @@ import jsonimport loggingimport osimport re+from pathlib import Pathfrom typing import Any, Dict, Optionalfrom gateway.platforms._shared import get_scoped_secret as _get_wsecret@@ -310,9 +311,8 @@ def resolve_whatsapp_bridge_dir() -> Path:"""Bridge directory for CLI and adapter. A read-only install tree (e.g. Docker/opt/hermes) is mirrored to HERMES_HOME so npm install works."""import shutil- from pathlib import Path as _Pathfrom hermes_constants import get_hermes_home- install_bridge = _Path(__file__).resolve().parents[2] / "scripts" / "whatsapp-bridge"+ install_bridge = Path(__file__).resolve().parents[2] / "scripts" / "whatsapp-bridge"hermes_home_bridge = get_hermes_home() / "scripts" / "whatsapp-bridge"try:(install_bridge / ".write_test").touch()diff --git a/gateway/run.py b/gateway/run.pyindex 0f15ed3e959..3f947f3a961 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -27,7 +27,7 @@ from collections import OrderedDictfrom contextvars import copy_contextfrom pathlib import Pathfrom datetime import datetime-from typing import Callable, Dict, Optional, Any, List, Tuple, cast+from typing import Callable, Dict, Optional, Any, List, Tuple, cast, TYPE_CHECKINGfrom agent.async_utils import safe_schedule_threadsafefrom agent.conversation_compression import (@@ -41,6 +41,9 @@ from agent.turn_context import compression_made_progressfrom hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_getfrom hermes_cli.fallback_config import get_fallback_chain+if TYPE_CHECKING:+ from agent.session_activity import ActivityProvenance+# Per-session AIAgent cache bounds (agents are heavy); see _enforce_agent_cache_cap/_session_expiry_watcher._AGENT_CACHE_MAX_SIZE = 128_AGENT_CACHE_IDLE_TTL_SECS = 3600.0 # evict agents idle for >1h@@ -1467,20 +1470,24 @@ _ensure_ssl_certs()# pm startup: same contract as the CLI dispatch path (hermes_cli/main.py)# — the gateway daemon never passes through the CLI fast-launch checks, so# the store's tools (git/bash/ffmpeg/...) must be on PATH here. O(1) stamp-# checks, no network, no installs; warns, never blocks.-try:- import pm-- pm.adopt()- problems = pm.check()- if problems:- logging.getLogger("gateway.run").warning(- f"install out of sync ({'; '.join(problems)}) — run `hermes pm install`"- )- else:- pm.activate()-except Exception:- logging.getLogger("gateway.run").debug("pm startup check failed", exc_info=True)+# checks, no network, no installs; warns, never blocks. Runs from main(),+# not import time: importers of this module (relay runtime, platform+# actions, enrollment) need helpers, not PATH provisioning or a pm verdict+# on their behalf.+def _run_pm_startup() -> None:+ try:+ import pm++ pm.adopt()+ problems = pm.check()+ if problems:+ logging.getLogger("gateway.run").warning(+ f"install out of sync ({'; '.join(problems)}) — run `hermes pm install`"+ )+ else:+ pm.activate()+ except Exception:+ logging.getLogger("gateway.run").debug("pm startup check failed", exc_info=True)sys.path.insert(0, str(Path(__file__).parent.parent))@@ -4431,6 +4438,16 @@ def _housekeeping_org_skill_sync() -> None:maybe_pull_org_skills()+def _housekeeping_plugin_update_check() -> None:+ """Plugin update-check cadence (plugins_cadence): due-gated by+ plugins.auto_update_check_hours, read-only, receipt-surfaced; the+ opt-in auto-apply rides the manual update pipeline. A network error+ costs one warning and a stamped marker — never an apply."""+ from hermes_cli.plugins_cadence import maybe_run_gateway_check++ maybe_run_gateway_check(log=logger)++def _housekeeping_auto_archive() -> None:"""Stale-session auto-archive on a live timer (the startup hook fires once); maybe_auto_archive()is gated by sessions.min_interval_hours. Opens its own SessionDB — SQLite connections are thread-bound."""@@ -4516,6 +4533,7 @@ def _start_gateway_housekeeping((60, "Sync pull tick", _housekeeping_skill_sync),(60, "Org sync pull tick", _housekeeping_org_skill_sync),(60, "Auto-archive tick", _housekeeping_auto_archive),+ (60, "Plugin update check", _housekeeping_plugin_update_check),(1, "Deferred FTS retry tick", _housekeeping_deferred_fts_retry),(1, "gateway housekeeping memory trim", _housekeeping_memory_trim)]@@ -5346,6 +5364,21 @@ def main():for _step in (_register_identity, _arm_watchdog, _utf8_stdio):_best_effort(_step)+ # pm startup contract (PATH provisioning for the store's tools), then+ # the post-update bootstrap: the same one-pass record-gated maintenance+ # registry the CLI dispatch path runs (hermes_cli/main.py) — this+ # entrypoint bypasses that dispatch, so run it here too. Never raises.+ _best_effort(_run_pm_startup)+ try:+ from hermes_cli.boot_bootstrap import (+ default_project_root,+ maybe_run_boot_bootstrap,+ )++ maybe_run_boot_bootstrap(default_project_root())+ except Exception:+ logger.debug("boot bootstrap failed", exc_info=True)+import argparseparser = argparse.ArgumentParser(description="Hermes Gateway - Multi-platform messaging")parser.add_argument("--config", "-c", help="Path to gateway config file")diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 467ef345b85..0c6b9d2f241 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -28,6 +28,7 @@ from gateway.slash_commands_goals import GatewayGoalCommandsMixinfrom gateway.slash_commands_model import GatewayModelCommandsMixinfrom gateway.slash_commands_session import GatewaySessionCommandsMixinfrom gateway.slash_commands_status import GatewayStatusCommandsMixin+from gateway.slash_commands_status import HISTORY_UNREADABLEfrom hermes_cli.config import atomic_config_write, cfg_getfrom utils import atomic_json_write, is_truthy_valuediff --git a/gateway/windows_service.py b/gateway/windows_service.pydeleted file mode 100644index 4ac3d07a72e..00000000000--- a/gateway/windows_service.py+++ /dev/null@@ -1,179 +0,0 @@-"""`gateway run --service`: the Windows SCM frontend for the gateway.--The MSIX registers HermesGateway as a Windows Service whose Executable-is the payload's own launcher (hermes.exe — the distlib-minted PE; no-rust, no separate shim binary, plan: gateway-msix-windows-service).-When the SCM starts the service, this module IS the service process:-- SCM START → this frontend reports Running in well under a second- (stdlib + pywin32 imports only — the heavy hermes import happens in- the CHILD it spawns: `hermes gateway run` with no --service), then- spawns the gateway as a child and waits.-- SCM STOP → writes the EXISTING planned-stop marker- (write_planned_stop_marker(child_pid)) — the gateway's own watcher- thread (the #33778 windows-graceful-stop path) drains it exactly like- `hermes gateway stop` does. The frontend waits out the drain window- (below the SCM's WaitToKillServiceTimeout, with margin — Task 3),- then force-kills the child and reports Stopped.--The graceful-drain logic is NOT duplicated here — it is the gateway's-own, exercised daily by `hermes gateway stop`. This file is only the SCM-protocol translation layer.-"""--from __future__ import annotations--import os-import subprocess-import sys-import time-from typing import Optional--SERVICE_NAME = "HermesGateway"--# Task 3's contract: the SCM force-kills a service that hasn't reported-# Stopped within WaitToKillServiceTimeout (30s default, but hardening-# guides set 5s). The frontend enforces its own deadline BELOW the-# window so the force-kill decision stays hermes-owned (receipt-visible-# in the gateway's own log tail), never an SCM surprise.-_SCM_WINDOW_FALLBACK_S = 30-_STOP_MARGIN_S = 5---def run_as_service() -> int:- """The SCM frontend loop. Returns the process exit code."""- try:- import win32serviceutil # noqa: F401- import servicemanager- except ImportError:- # Started outside the SCM (a user ran --service by hand): say so,- # never hang. The real gateway doesn't need this flag.- print(- "gateway --service is the Windows service frontend; it is started "- "by the Service Control Manager (or `hermes gateway service on`). "- "For a foreground gateway run: hermes gateway run",- file=sys.stderr,- )- return 2-- import win32service- import win32serviceutil as svcutil-- class _GatewayFrontend(win32serviceutil.ServiceFramework):- _svc_name_ = SERVICE_NAME- _svc_display_name_ = "Hermes Gateway"- _svc_description_ = (- "Hermes messaging gateway — bots keep running without the "- "desktop app. Managed by hermes; enable via "- "`hermes gateway service on`."- )-- def __init__(self, args):- super().__init__(args)- self.stop_requested = False- self.child: Optional[subprocess.Popen] = None- self.sewh = None-- def SvcStop(self):- """SCM stop: nudge the child GRACEFULLY (the planned-stop- marker — the gateway's own drain path), then honor the- frontend's own deadline in SvcRun."""- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)- self.stop_requested = True- if self.child and self.child.poll() is None:- _write_stop_marker(self.child.pid)-- def SvcDoRun(self):- import servicemanager-- servicemanager.LogMsg(- servicemanager.EVENTLOG_INFORMATION_TYPE,- servicemanager.PYS_SERVICE_STARTED,- (self._svc_name_, ""),- )- try:- self._run_child()- except Exception:- import traceback-- servicemanager.LogErrorMsg(- "HermesGateway frontend failure:\n" + traceback.format_exc()- )- finally:- servicemanager.LogMsg(- servicemanager.EVENTLOG_INFORMATION_TYPE,- servicemanager.PYS_SERVICE_STOPPED,- (self._svc_name_, ""),- )-- def _run_child(self):- # The REAL gateway: this launcher, no --service, so every- # code path (watchdog, planned-stop watcher, graceful drain)- # is the one `hermes gateway run` uses daily.- argv = [- sys.executable,- "-m",- "hermes_cli.main",- "gateway",- "run",- ]- self.child = subprocess.Popen(- argv,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- cwd=os.getcwd(),- )-- # Wait for exit or the graceful-stop request.- drain_deadline = None- while True:- rc = self.child.poll()- if rc is not None:- return- if self.stop_requested:- if drain_deadline is None:- drain_deadline = time.monotonic() + _drain_window_s()- elif time.monotonic() >= drain_deadline:- # Drain window exhausted — force-kill the child.- # (Deliberately NOT a tree-walk taskkill: the- # #85265 class. The child's own children die with- # it under job semantics; the receipt-visible- # unclean-stop class is what remains.)- self.child.kill()- self.child.wait()- return- time.sleep(0.25)-- svcutil.Initialize(_GatewayFrontend, None)- svcutil.StartServiceCtrlDispatcher()- return 0---def _drain_window_s() -> float:- """The frontend's stop deadline: the gateway's configured drain- timeout, capped below the SCM's WaitToKillServiceTimeout."""- fallback = float(_SCM_WINDOW_FALLBACK_S - _STOP_MARGIN_S)- try:- raw = os.environ.get("HERMES_RESTART_DRAIN_TIMEOUT", "").strip()- if raw:- return min(float(raw), fallback)- except (TypeError, ValueError):- pass- return fallback---def _write_stop_marker(child_pid: int) -> None:- """The graceful nudge: the SAME marker `hermes gateway stop` writes;- the child's planned-stop watcher thread consumes it and drains."""- try:- from gateway.status import write_planned_stop_marker-- write_planned_stop_marker(child_pid)- except Exception:- # Marker machinery unavailable (partial payload): fall back to- # terminate, which the child's #53107 hardening handles.- try:- os.kill(child_pid, 15) # SIGTERM-shaped nudge on windows = TerminateProcess- except Exception:- passdiff --git a/hermes_bootstrap.py b/hermes_bootstrap.pyindex 8d1464544c5..ecd2b0402ef 100644--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@ -100,8 +100,18 @@ def harden_import_path(src_root: str | None = None) -> None:# (or ``from hermes_bootstrap import apply_windows_utf8_bootstrap``) at# the very top of their module, before importing anything else. The# import side effect does the right thing.-# Upstream's ``activate_durable_lazy_target`` (tools.lazy_deps durable-# lazy-install dir) is deliberately NOT merged: lazy_deps was removed on-# this branch (pm replaced it). Do not reintroduce.apply_windows_utf8_bootstrap()suppress_platform_ver_console()++# Every entry point imports this module before its dependency graph.+from pathlib import Path+from hermes_cli.runtime_paths import activate_dependencies++try:+ activate_dependencies(Path(__file__).resolve().parent)+except RuntimeError as exc:+ # The repair command must remain usable even when the committed tree+ # disappeared. Other commands must not silently run the wrong libraries.+ if sys.argv[1:3] not in (["pm", "install"], ["pm", "doctor"]):+ print(f"hermes: {exc}; run `hermes pm install` to repair", file=sys.stderr)+ raise SystemExit(1) from Nonediff --git a/hermes_cli/_install_repair.py b/hermes_cli/_install_repair.pyindex 19e4a4fbf80..31dcebe6e8f 100644--- a/hermes_cli/_install_repair.py+++ b/hermes_cli/_install_repair.py@@ -217,13 +217,14 @@ def ensure_windows_bin_launchers(mint_launcher,resolve_store_python,stage_launcher,- venv_site_packages,)from hermes_constants import project_venv_dirvenv_dir = project_venv_dir(root)- site_packages = venv_site_packages(venv_dir) if venv_dir else None+ from hermes_cli.runtime_paths import site_packages as dependency_site++ site_packages = dependency_site(venv_dir) if venv_dir else Nonestore_python = resolve_store_python(root)@@ -280,6 +281,11 @@ def ensure_windows_bin_launchers(else:final = stage_launcher(name, root, target)if final is not None:+ # Windows resolves .exe before .cmd. A surviving venv-bound+ # launcher would shadow the successfully staged fallback.+ obsolete = target / f"{name}.exe"+ if final.suffix == ".cmd" and exe_is_venv_bound(obsolete, venv_dir):+ obsolete.unlink()restored.append(str(final))if restored:# Guarded like everything else in this never-raises helper: adiff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.pyindex 172843f33f8..07912adacc4 100644--- a/hermes_cli/_launchers.py+++ b/hermes_cli/_launchers.py@@ -15,11 +15,9 @@ Two consumers:- ``hermes_cli/_install_repair.py`` calls the same machinery per-name whena launcher is missing or still boots through the venv.-Store-root resolution mirrors ``pm/paths.py`` (HERMES_RUNTIME_DIR →-install-stamp.json ``runtimeDir`` → the pm default root); it is re-implemented-here because this module must stay importable from a bare interpreter-(stdlib + distlib only) during repair/bootstrap where ``pm`` imports are not-guaranteed. If pm's layout changes, keep the two in lockstep.+Store paths come from the stdlib-only runtime_paths owner, shared with PM.+Launchers import hermes_bootstrap before the entry point: the dependency+selection is read at boot, not frozen when the launcher is minted.The exe form uses distlib's ScriptMaker with a customized script templatethat inserts the repo root and the venv's site-packages into ``sys.path``@@ -35,6 +33,9 @@ import jsonimport osfrom pathlib import Path+from hermes_constants import project_venv_dir+from hermes_cli.runtime_paths import site_packages, store_root+#: Launcher command names — keep in lockstep with scripts/install.ps1#: Stage-Path and hermes_cli/_install_repair.py.WINDOWS_BIN_LAUNCHERS = ("hermes", "hermes-acp")@@ -51,36 +52,6 @@ def _is_windows() -> bool:return os.name == "nt"-def project_venv_dir(repo_root: Path) -> Path | None:- """The uv-sync target venv of the install (``venv`` preferred, ``.venv``- for dev checkouts)."""- for name in ("venv", ".venv"):- candidate = Path(repo_root) / name- if candidate.is_dir():- return candidate- return None---def store_root(repo_root: Path) -> Path:- """The pm byte store, resolved exactly like pm/paths.store_root()."""- env = os.environ.get("HERMES_RUNTIME_DIR")- if env:- return Path(env)- stamp = Path(repo_root) / "install-stamp.json"- if stamp.is_file():- try:- runtime_dir = json.loads(stamp.read_text(encoding="utf-8-sig")).get(- "runtimeDir"- )- except (OSError, ValueError):- runtime_dir = None- if runtime_dir:- return Path(runtime_dir)- from hermes_constants import get_default_hermes_root-- return Path(get_default_hermes_root()) / "tools"--def resolve_store_python(repo_root: Path) -> Path | None:"""The interpreter the store installed from the ``python`` package(facts.json entry first, newest ``python-*`` entry as fallback), or@@ -109,19 +80,6 @@ def resolve_store_python(repo_root: Path) -> Path | None:return None-def venv_site_packages(venv_dir: Path) -> Path | None:- """The venv directory uv sync fills (Windows ``Lib\\site-packages``;- POSIX ``lib/python3.X/site-packages``)."""- venv_dir = Path(venv_dir)- if _is_windows():- candidate = venv_dir / "Lib" / "site-packages"- return candidate if candidate.is_dir() else None- for candidate in sorted(venv_dir.glob("lib/python3.*/site-packages")):- if candidate.is_dir():- return candidate- return None--def _load_script_maker():"""distlib's ScriptMaker — standalone first, then pip's vendored copy."""try:@@ -216,6 +174,7 @@ def mint_launcher("import sys\n"f"sys.path.insert(0, {esc(repo_root)!r})\n"f"{site_line}"+ "import hermes_bootstrap\n""if __name__ == '__main__':\n"" from %(module)s import %(import_name)s\n"" sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n"@@ -236,7 +195,7 @@ def mint_launcher(# distlib ran but produced no exe (unexpected) — fall through to cmd.site = f";{site_packages}" if site_packages else ""- code = f"import sys; from {module} import {func}; sys.exit({func}())"+ code = f"import sys; import hermes_bootstrap; from {module} import {func}; sys.exit({func}())"body = ("@echo off\r\n""chcp 65001 >nul\r\n"@@ -260,13 +219,13 @@ def stage_launcher(name: str, repo_root: Path, out_dir: Path) -> Path | None:Never raises; returns the written path or None."""repo_root = Path(repo_root)venv_dir = project_venv_dir(repo_root)- site_packages = venv_site_packages(venv_dir) if venv_dir else None+ dependencies = site_packages(venv_dir) if venv_dir else Nonestore_python = resolve_store_python(repo_root)if store_python is not None:- path = mint_launcher(name, repo_root, out_dir, store_python, site_packages)+ path = mint_launcher(name, repo_root, out_dir, store_python, dependencies)if path is not None:return path- return _write_runtime_cmd(name, repo_root, site_packages, out_dir)+ return _write_runtime_cmd(name, repo_root, dependencies, out_dir)def ensure_install_launchers(repo_root: Path, out_dir: Path) -> list[str]:@@ -316,7 +275,7 @@ def _write_runtime_cmd(")\r\n"f'endlocal & set "PYTHONPATH=%HERMES_REPO%{site}" & set "PM_PY=%PM_PY%"\r\n''set "PYTHONHOME="\r\n'- f'set "PM_ENTRY=import sys; from {module} import {func}; sys.exit({func}())"\r\n'+ f'set "PM_ENTRY=import sys; import hermes_bootstrap; from {module} import {func}; sys.exit({func}())"\r\n''"%PM_PY%" -c "%PM_ENTRY%" %*\r\n')return _write_atomic(diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 4d74c441cbe..0373ea7d501 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -11,7 +11,7 @@ import tempfileimport threadingimport timeimport zipfile-from contextlib import closing, contextmanager, suppress+from contextlib import contextmanager, suppressfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple@@ -25,6 +25,16 @@ from utils import (from hermes_cli.sizefmt import format_bytes as _format_size+from hermes_cli.backup_restore import (+ _count_session_rows,+ _default_new_file_mode,+ _detect_prefix,+ _extract_member_atomically,+ _import_db_member,+ _safe_restore_db,+ _validate_backup_zip,+)+logger = logging.getLogger(__name__)# --- Exclusion rules ---@@ -168,11 +178,6 @@ def _atomic_output_path(final_path: Path):raise-def _is_within(path: Path, root: Path) -> bool:- """True when *path* resolves inside the already-resolved *root* (traversal / symlink guard)."""- return path.resolve().is_relative_to(root)--def _collect_memory_provider_external_paths() -> List[Path]:"""Existing paths the active memory provider declares via ``backup_paths()``; ``[]`` on anyprovider failure (backup must never fail because of a flaky plugin)."""@@ -404,642 +409,13 @@ def verify_sqlite_integrity(return _done("header check passed", valid=True, size=size)-def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:- """PIDs of OTHER processes holding *db_path* or its WAL/SHM open (Linux ``/proc`` scan).-- An already-unlinked ``(deleted)`` sidecar — the #90950 split-brain fingerprint — still- counts as held. None off-Linux or when /proc fails.- """- if not sys.platform.startswith("linux"):- return None-- def _canonical(path: str) -> str:- return os.path.normcase(os.path.abspath(path.removesuffix(" (deleted)")))-- def _holds_watched(fds: List[str], fd_dir: str) -> bool:- for fd in fds:- try:- target = os.readlink(f"{fd_dir}/{fd}")- except OSError:- continue- if _canonical(target) in watched:- return True- return False-- canonical_db = _canonical(os.fspath(db_path))- watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}- pids: List[int] = []- try:- own_pid = os.getpid()- for pid_str in os.listdir("/proc"):- if not pid_str.isdigit() or int(pid_str) == own_pid:- continue- fd_dir = f"/proc/{pid_str}/fd"- try:- fds = os.listdir(fd_dir)- except OSError:- continue- if _holds_watched(fds, fd_dir):- pids.append(int(pid_str))- except OSError:- return None- return pids---def _safe_restore_db(src: Path, dst: Path) -> bool:- """Restore snapshot *src* into live *dst* through the backup() API; unlink+move fallback.-- Writing pages into the live file preserves its inode and WAL state, so other holders (gateway,- dashboard, another CLI) see the restored data instead of stale pages from a replaced inode.- The fallback runs ONLY when no other process or in-process connection holds the file- (replacing the inode under a live holder is the #90950 split-brain); otherwise it fails closed- (``False``) and the caller reports the file as skipped.- """- try:- dst_conn = sqlite3.connect(str(dst))- # Checkpoint first so the backup starts clean rather than writing on top of a deep WAL.- with suppress(Exception):- dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")- with closing(sqlite3.connect(f"file:{src}?mode=ro", uri=True)) as src_conn:- src_conn.backup(dst_conn)- dst_conn.close()- with suppress(Exception):- dst.chmod(src.stat().st_mode)- return True- except Exception as exc:- logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)- return _unlink_move_restore_db(src, dst)---def _unlink_move_restore_db(src: Path, dst: Path) -> bool:- """Fallback restore: unlink+move. Only safe when no process holds the DB open.-- Replacing the inode under a live holder is the #90950 corruption class (the holder keeps- writing through a deleted-inode fd and loses its WAL index), so fail closed. The foreign-pid- scan excludes THIS process, so ``offline_file_access`` also fails CLOSED on any live- in-process connection to *dst* and holds the connection-lifecycle lock across the swap.- """- from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access- try:- holders = _foreign_db_holder_pids(dst)- if holders:- logger.error("Refusing unlink+move restore of %s: process(es) %s still "- "hold the database or its WAL open. Stop them and retry.", dst, holders)- return False- with offline_file_access(dst, what="unlink+move restore of"):- tmp = dst.parent / f".{dst.name}.snap_restore"- shutil.copy2(src, tmp)- dst.unlink(missing_ok=True)- # The snapshot owns no WAL, so any -wal/-shm here belongs to the DB just unlinked (a- # killed gateway leaves them — exactly when a restore runs); SQLite would replay that- # foreign WAL over the restored file: "malformed" or resurrected post-snapshot rows.- for _sidecar_suffix in ("-wal", "-shm", "-journal"):- dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)- shutil.move(str(tmp), str(dst))- return True- except LiveConnectionError as exc2:- logger.error("Refusing unlink+move restore of %s: %s Close the in-process "- "database handles (or restart Hermes) and retry.", dst, exc2)- return False- except Exception as exc2:- logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)- return False---def _zip_sqlite_snapshot(zf: zipfile.ZipFile, abs_path: Path, rel_path: Path, out_path: Path) -> Optional[int]:- """Add a WAL-safe snapshot of *abs_path* to *zf*; return its byte size, or None on failure.-- Staged beside the output zip: /tmp may be a small tmpfs that cannot hold large databases.- """- with tempfile.NamedTemporaryFile(suffix=".db", delete=False, dir=str(out_path.parent)) as tmp:- tmp_db = Path(tmp.name)- try:- if not _safe_copy_db(abs_path, tmp_db):- return None- zf.write(tmp_db, arcname=str(rel_path))- return tmp_db.stat().st_size- finally:- tmp_db.unlink(missing_ok=True)---def _write_zip_entries(- zf: zipfile.ZipFile, files_to_add: List[Tuple[Path, Path]], out_path: Path,- *, on_db_failure, on_error, on_progress, track_bytes: bool) -> int:- """Add every ``(abs_path, rel_path)`` to *zf*, WAL-safe for ``*.db``; return bytes archived.-- ``on_db_failure(rel_path)`` runs when a SQLite snapshot fails (may raise to abort);- ``on_error(rel_path, exc)`` records a read failure; ``on_progress(i)`` fires every 500 files;- ``track_bytes`` stats plain files for the size total.- """- total_bytes = 0- for i, (abs_path, rel_path) in enumerate(files_to_add, 1):- try:- if abs_path.suffix == ".db":- size = _zip_sqlite_snapshot(zf, abs_path, rel_path, out_path)- if size is None:- on_db_failure(rel_path)- continue- total_bytes += size- else:- zf.write(abs_path, arcname=str(rel_path))- if track_bytes:- total_bytes += abs_path.stat().st_size- except (PermissionError, OSError, ValueError) as exc:- on_error(rel_path, exc)- continue- if i % 500 == 0:- on_progress(i)- return total_bytes---def _print_capped(header: str, lines: List[str], indent: str) -> None:- """Print *header*, then at most 10 of *lines* (each prefixed by *indent*) and a "... and N more" tail."""- print(header)- for line in lines[:10]:- print(f"{indent}{line}")- if len(lines) > 10:- print(f"{indent}... and {len(lines) - 10} more")--# --- Backup ----def _resolve_backup_output_path(output: Optional[str]) -> Path:- """Turn ``--output`` (file, directory, or None) into a ``.zip`` path whose parent exists;- an unwritable path exits with a one-line error, not a traceback."""- out_path = None- default_name = f"hermes-backup-{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.zip"- try:- if output:- out_path = Path(output).expanduser().resolve()- if out_path.is_dir():- out_path = out_path / default_name- else:- out_path = Path.home() / default_name- if out_path.suffix.lower() != ".zip":- out_path = out_path.with_suffix(out_path.suffix + ".zip")- out_path.parent.mkdir(parents=True, exist_ok=True)- except OSError as exc:- print(f"Error: cannot write backup to {output or out_path}: {exc}")- raise SystemExit(1) from exc- return out_path---def _collect_external_entries() -> tuple[list[tuple[Path, str]], list[str]]:- """``([(abs_path, arcname)], [skipped])`` for the memory provider's external state, arc-named- ``_external/<home-relative>``; paths outside home are skipped (security + portability)."""- home_dir = Path.home().resolve()- external_to_add: list[tuple[Path, str]] = []- skipped_external: list[str] = []- for base in _collect_memory_provider_external_paths():- try:- base.resolve().relative_to(home_dir)- except (ValueError, OSError):- skipped_external.append(str(base))- continue- for fpath in _iter_external_files(base):- with suppress(ValueError, OSError):- rel_to_home = fpath.resolve().relative_to(home_dir)- external_to_add.append((fpath, _EXTERNAL_PREFIX + rel_to_home.as_posix()))- return external_to_add, skipped_external---def run_backup(args) -> None:- """Create a zip backup of the Hermes home directory."""- hermes_root = get_default_hermes_root()-- if not hermes_root.is_dir():- print(f"Error: Hermes home directory not found at {hermes_root}")- sys.exit(1)-- try:- with _backup_operation_lock(hermes_root):- _run_backup_locked(args, hermes_root)- except BackupInProgressError as exc:- print(f"Error: {exc}")- raise SystemExit(2) from exc---def _run_backup_locked(args, hermes_root: Path) -> None:- """Write a full backup while the cross-process backup slot is held."""- out_path = _resolve_backup_output_path(args.output)- scan_started = time.monotonic()- logger.info("backup phase=scan status=started")- print(f"Scanning {display_hermes_home()} ...")- skipped_dirs: set = set()- files_to_add: list[tuple[Path, Path]] = list(_iter_backup_files(hermes_root, out_path, skipped_dirs))- external_to_add, skipped_external = _collect_external_entries()- if not files_to_add and not external_to_add:- logger.info("backup phase=scan status=empty duration_ms=%.1f", (time.monotonic() - scan_started) * 1000)- print("No files to back up.")- return-- file_count = len(files_to_add) + len(external_to_add)- logger.info("backup phase=scan status=complete duration_ms=%.1f files=%d",- (time.monotonic() - scan_started) * 1000, file_count)- logger.info("backup phase=archive status=started files=%d", file_count)- print(f"Backing up {file_count} files ...")- errors = []- t0 = time.monotonic()-- def _progress(i: int) -> None:- print(f" {i}/{file_count} files ...")- logger.info("backup phase=archive status=progress completed=%d total=%d", i, file_count)-- with _atomic_output_path(out_path) as archive_path, zipfile.ZipFile(- archive_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zf:- total_bytes = _write_zip_entries(- zf, files_to_add, out_path, on_progress=_progress, track_bytes=True,- on_db_failure=lambda rel: errors.append(f"{rel}: SQLite safe copy failed"),- on_error=lambda rel, exc: errors.append(f"{rel}: {exc}"))- # External memory-provider state never includes ``.db`` files in practice, so a- # straight zf.write is fine.- for abs_path, arcname in external_to_add:- try:- zf.write(abs_path, arcname=arcname)- total_bytes += abs_path.stat().st_size- except (PermissionError, OSError, ValueError) as exc:- errors.append(f"{arcname}: {exc}")- elapsed = time.monotonic() - t0- zip_size = out_path.stat().st_size- logger.info("backup phase=archive status=complete duration_ms=%.1f files=%d errors=%d bytes=%d",- elapsed * 1000, file_count, len(errors), zip_size)- print(f"\nBackup {'incomplete' if errors else 'complete'}: {out_path}\n"- f" Files: {file_count}\n"- f" Original: {_format_size(total_bytes)}\n"- f" Compressed: {_format_size(zip_size)}\n"- f" Time: {elapsed:.1f}s")- if external_to_add:- print(f"\n Included {len(external_to_add)} memory-provider file(s) stored outside {display_hermes_home()}.")- if skipped_external:- print(f"\n Skipped {len(skipped_external)} memory-provider path(s) outside your home directory "- "(not portable):\n" + "\n".join(f" {p}" for p in sorted(skipped_external)[:10]))- if skipped_dirs:- print("\n Excluded directories:\n" + "\n".join(f" {d}/" for d in sorted(skipped_dirs)))- if errors:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")- else:- print(f"\nRestore with: hermes import {out_path.name}")-# --- Import ----def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:- """Check that a zip looks like a Hermes backup."""- names = zf.namelist()- if not names:- return False, "zip archive is empty"- # Telltale files a hermes home has — at the root or one level deep (zipped directory).- if not any(Path(n).name in {"config.yaml", ".env", "state.db"} for n in names):- return False, "zip does not appear to be a Hermes backup (no config.yaml, .env, or state databases found)"- return True, ""---def _detect_prefix(zf: zipfile.ZipFile) -> str:- """Detect if the zip has a common directory prefix wrapping all entries."""- names = [n for n in zf.namelist() if not n.endswith("/")]- first_parts = {Path(n).parts[0] for n in names if len(Path(n).parts) > 1}- if len(first_parts) == 1 and first_parts <= {".hermes", "hermes"}:- return first_parts.pop() + "/"- return ""---def _default_new_file_mode() -> Optional[int]:- """The mode ``open(path, "wb")`` gives a file it has to create.-- ``mkstemp`` always creates at 0600, so staging an import through a temp file would tighten- every *newly created* file to owner-only — the Docker/NAS volume-mount hazard- ``utils._restore_file_mode`` documents.- """- try:- current = os.umask(0o077)- os.umask(current)- except OSError:- return None- return 0o666 & ~current---def _extract_member_atomically(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Restore one zip member onto *target* with no truncation window.-- ``open(target, "wb")`` would truncate the user's file before any replacement bytes exist.- ``atomic_replace`` (not bare ``os.replace``) resolves a symlinked target first, so a- dotfiles-linked ``config.yaml`` keeps the link (#16743), and falls back to copy/fsync/unlink- on ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.- """- # Mode is None when the target does not exist: the umask-derived create-mode applies.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- if mode is None:- mode = new_file_mode- else:- # Deliberately NOT a faithful copy: setuid/setgid are dropped. The bytes come from the- # archive, so carrying elevated bits would hand the zip's author the identity an existing- # setuid file runs as — and ``_external/`` publishes members anywhere under ``$HOME``.- mode &= ~(stat.S_ISUID | stat.S_ISGID)- # Truncate the stem: mkstemp adds ~16 chars and a member near NAME_MAX would otherwise fail.- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial")- try:- with os.fdopen(fd, "wb") as dst:- if mode is not None:- # Apply the mode BEFORE the replace so the target never transits through mkstemp's- # 0600 and the EXDEV/EBUSY ``copystat`` fallback copies the intended bits.- if hasattr(os, "fchmod"): # Unix-only; Windows takes the path-based chmod- os.fchmod(dst.fileno(), mode)- else:- os.chmod(tmp_name, mode)- # Stream: a multi-gigabyte state.db member must not be held in memory in one piece.- with zf.open(member) as src:- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- real_path = Path(atomic_replace(tmp_name, target))- # Owner first, mode second (as ``atomic_yaml_write``): chown drops setuid/setgid and- # ``mode`` no longer carries them, so neither step can re-elevate the restored file.- _restore_file_owner(real_path, owner)- _restore_file_mode(real_path, mode)- except BaseException:- with suppress(OSError):- os.unlink(tmp_name)- raise---def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:- """``(sessions, messages)`` in session database *path*; read-only, best effort.-- ``None`` means "unknown" (missing, not a Hermes session store, unreadable) — never "zero":- acting on an unreadable database would mask the very loss this count exists to surface.- Same contract as :func:`_count_cron_jobs`.- """- if not path.is_file():- return None- try:- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)- except sqlite3.Error:- return None- try:- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]- return int(sessions), int(messages)- except (sqlite3.Error, TypeError, ValueError):- return None- finally:- conn.close()---def _import_db_member(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.-- A rename-publish over a live database is the #65942 / #90950 corruption class: a gateway,- dashboard, or WebUI holding it open keeps serving the unlinked inode and writing sessions no- other process will see, and a sidecar WAL beside the new file describes the old database —- nothing fails, the sessions are simply gone (#100960). Route the member through the same- ``_safe_restore_db`` page copy ``/snapshot restore`` uses, so the live inode is preserved and- every open connection converges. A target that does not exist yet has no holders, so it takes- the ordinary atomic publish. Raises ``OSError`` when the database could not be replaced- safely, so the caller reports a skipped file instead of a silent success.- """- if not target.exists():- _extract_member_atomically(zf, member, target, new_file_mode)- return- # The database keeps its own mode/ownership: the bytes come from the archive, the file does not.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport")- try:- with os.fdopen(fd, "wb") as dst:- with zf.open(member) as src: # stream: never hold a multi-GB state.db in memory- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- if not _safe_restore_db(Path(tmp_name), target):- raise OSError(- "live-safe restore refused or failed; the existing database was "- "left untouched. Stop the gateway/dashboard processes holding it "- "open and re-run the import."- )- _restore_file_owner(target, owner)- _restore_file_mode(target, mode)- finally:- with suppress(OSError):- os.unlink(tmp_name)---def _confirm_import_overwrite(hermes_root: Path) -> bool:- """Prompt before importing over an existing installation; True when import may proceed."""- if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):- return True- print("\nWarning: Target directory already has Hermes configuration.\n"- "Importing will overwrite existing files with backup contents.\n")- try:- answer = input("Continue? [y/N] ").strip().lower()- except (EOFError, KeyboardInterrupt):- print("\nAborted.")- sys.exit(1)- if answer in {"y", "yes"}:- return True- print("Aborted.")- return False---def _import_members(- zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int-) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:- """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.-- ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the- import replaced with one holding fewer rows — allowed, but never silent (#100960).- """- errors: list[str] = []- skipped_runtime: list[str] = []- db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []- restored = restored_external = 0- home_dir = Path.home().resolve()- new_file_mode = _default_new_file_mode() # once: every member is published via mkstemp (0600)- for member in members:- # ``_external/`` members restore to their home-relative location (~/.honcho/config.json),- # NOT under HERMES_HOME; provider configs commonly hold credentials, so tighten to 0600.- external = member.startswith(_EXTERNAL_PREFIX)- if external:- rel = member[len(_EXTERNAL_PREFIX):]- target = home_dir / rel- root = home_dir- tighten = target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES- else:- rel = member[len(prefix):] if prefix and member.startswith(prefix) else member- if rel and Path(rel).name in _IMPORT_SKIP_NAMES: # see ``_IMPORT_SKIP_NAMES``- skipped_runtime.append(rel)- continue- # A ``.db`` member is page-restored into the live file; an archived WAL/SHM/journal- # describes a different database image and installed beside it (over a live sidecar)- # would replay a foreign WAL on next open. Current backups never ship these- # (_EXCLUDED_SUFFIXES); older or hand-built archives might.- if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):- skipped_runtime.append(rel)- continue- target = hermes_root / rel- root = hermes_root.resolve()- tighten = target.name in _SECRET_FILE_NAMES- if not rel:- continue-- label = member if external else rel- if not _is_within(target, root):- errors.append(f"{label}: path traversal blocked")- else:- try:- target.parent.mkdir(parents=True, exist_ok=True)- if target.suffix == ".db":- # Count before the write: afterwards the dropped rows are gone.- before = _count_session_rows(target)- _import_db_member(zf, member, target, new_file_mode)- after = _count_session_rows(target)- if before and after and after[1] < before[1]:- db_shrunk.append((rel, before, after))- else:- _extract_member_atomically(zf, member, target, new_file_mode)- if tighten:- try:- os.chmod(target, 0o600)- except OSError:- if not external: # external configs are tightened best-effort only- raise- restored += 1- restored_external += external- except (PermissionError, OSError) as exc:- errors.append(f"{label}: {exc}")-- if restored % 500 == 0:- print(f" {restored}/{file_count} files ...")-- return restored, restored_external, errors, skipped_runtime, db_shrunk---def run_import(args) -> None:- """Restore a Hermes backup from a zip file."""- zip_path = Path(args.zipfile).expanduser().resolve()- if not zip_path.is_file():- print(f"Error: File not found: {zip_path}")- sys.exit(1)- if not zipfile.is_zipfile(zip_path):- print(f"Error: Not a valid zip file: {zip_path}")- sys.exit(1)- # The restore target is the home the command operates under (the printed "Target:");- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.- hermes_root = get_hermes_home()- with zipfile.ZipFile(zip_path, "r") as zf:- ok, reason = _validate_backup_zip(zf)- if not ok:- print(f"Error: {reason}")- sys.exit(1)- prefix = _detect_prefix(zf)- members = [n for n in zf.namelist() if not n.endswith("/")]- file_count = len(members)- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")- if prefix:- print(f"Detected archive prefix: {prefix!r} (will be stripped)")- if not args.force and not _confirm_import_overwrite(hermes_root):- return- print(f"\nImporting {file_count} files ...")- hermes_root.mkdir(parents=True, exist_ok=True)- t0 = time.monotonic()- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(- zf, members, prefix, hermes_root, file_count)- elapsed = time.monotonic() - t0- print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")- if restored_external:- print(f"\n Restored {restored_external} memory-provider file(s) to "- f"their original location(s) outside {display_hermes_home()}.")- if errors:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")- if db_shrunk:- # The backup predates work that is now overwritten — say so (#100960: twelve sessions- # disappeared with nothing logged anywhere).- print("\n ⚠ Session data replaced by older backup contents:")- for rel, before, after in db_shrunk:- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"- f" -> {after[0]} / {after[1]}")- print(" Anything recorded after the backup was taken is not in it. "- "Recover from a newer backup or snapshot: hermes snapshot list")- if skipped_runtime:- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "- f"file(s) (kept this machine's, not the backup's):",- sorted(skipped_runtime), " ")- restored_profiles = _restore_profile_wrappers(hermes_root)- print()- if not (hermes_root / "hermes-agent").is_dir():- print("Note: The hermes-agent codebase was not included in the backup.\n"- " If this is a fresh install, run: hermes update")- if restored_profiles:- print("\nTo re-enable gateway services for profiles:")- for pname in restored_profiles:- print(f" hermes -p {pname} gateway install")- _revive_gateway_after_import(hermes_root)- print("Done. Your Hermes configuration has been restored.")--def _restore_profile_wrappers(hermes_root: Path) -> List[str]:- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""- profiles_dir = hermes_root / "profiles"- restored_profiles: list[tuple[str, bool]] = []- if not profiles_dir.is_dir():- return []- try:- from hermes_cli.profiles import (- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)- for entry in sorted(profiles_dir.iterdir()):- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):- continue # only profiles with config get wrappers- profile_name = entry.name- collision = check_alias_collision(profile_name)- if collision:- print(f" Skipped alias '{profile_name}': {collision}")- restored_profiles.append(- (profile_name, not collision and create_wrapper_script(profile_name) is not None))- if restored_profiles:- created = [n for n, ok in restored_profiles if ok]- skipped = [n for n, ok in restored_profiles if not ok]- if created:- print(f"\n Profile aliases restored: {', '.join(created)}")- if skipped:- print(f" Profile aliases skipped: {', '.join(skipped)}")- if not _is_wrapper_dir_in_path():- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"- ' export PATH="$HOME/.local/bin:$PATH"')- except ImportError: # hermes_cli.profiles unavailable (fresh install)- if any(profiles_dir.iterdir()):- print("\n Profiles detected but aliases could not be created.\n"- " Run: hermes profile list (after installing hermes)")- return [n for n, _ in restored_profiles]---def _revive_gateway_after_import(hermes_root: Path) -> None:- """Install/start the gateway service after a restore, best-effort and prompt-free.-- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so- this is safe for any backup); failures print a manual fallback, never fail the import. Only- revived when the restore landed in the default home or no other install exists: a sandbox or- profile restore must not install a second gateway on the default service name.- """- native_default = _get_platform_default_hermes_home()- if hermes_root != native_default and any(- (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):- print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "- f"with the install at {native_default}.\n"- "To start a gateway for this home, run: hermes gateway install")- return- try:- from hermes_cli.gateway import ensure_gateway_service, _is_service_running- if not _is_service_running():- print()- ensure_gateway_service(context="import")- except Exception:- print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")---# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---+# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---# Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is# regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR@@ -1055,442 +431,39 @@ _QUICK_STATE_FILES = ("response_store.db", # gateway conversation history / tool payloads"memory_store.db", # holographic memory facts/entities"verification_evidence.db", # agent verification audit trail- "kanban.db", # default board (back-compat <root>/kanban.db)- "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)- # Pairing stores (generic + per-platform JSONs outside state.db)- "pairing", # legacy location (gateway/pairing.py)- "platforms/pairing", # new location (gateway/pairing.py)- "feishu_comment_pairing.json", # Feishu comment subscription pairings-)--_QUICK_DEFAULT_KEEP = 20---def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:- home = hermes_home or get_hermes_home()- return home / _QUICK_SNAPSHOTS_DIR---def create_quick_snapshot(- label: Optional[str] = None, hermes_home: Optional[Path] = None, keep: Optional[int] = None,- max_file_size: Optional[int] = None) -> Optional[str]:- """Create one atomic quick snapshot while holding the shared backup slot."""- home = hermes_home or get_hermes_home()- with _backup_operation_lock(home):- return _create_quick_snapshot_locked(label, home, keep, max_file_size)---def _quick_snapshot_candidates(home: Path):- """Yield ``(src, rel_posix, in_dir)`` for every regular file a quick snapshot captures; heavy- regenerable per-board subtrees (workspaces, attachments) are skipped."""- for rel in _QUICK_STATE_FILES:- src = home / rel- if src.is_dir():- for sub in filter(Path.is_file, src.rglob("*")):- sub_rel = sub.relative_to(home).as_posix()- if "/workspaces/" in f"/{sub_rel}/" or "/attachments/" in f"/{sub_rel}/":- continue- yield sub, sub_rel, True- elif src.is_file():- yield src, rel, False---def _copy_quick_snapshot_files(- home: Path, staging_dir: Path, max_file_size: Optional[int]-) -> tuple[Dict[str, int], list[str], list[str]]:- """Copy every quick-snapshot candidate into *staging_dir*.-- Returns ``(manifest {rel: size}, failed_dbs, oversized_skipped)``. The last two are snapshot- incompleteness (#68805): the caller must suppress pruning so the older snapshot that may hold- the only recoverable DB survives.- """- manifest: Dict[str, int] = {}- failed_dbs: list[str] = []- oversized_skipped: list[str] = []- for src, rel, in_dir in _quick_snapshot_candidates(home):- if max_file_size is not None:- try:- size = src.stat().st_size- except OSError:- size = None- if size is not None and size > max_file_size:- print(f" ⚠ Snapshot: skipping {rel} "- f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)")- logger.warning("Quick snapshot skipped %s: %d bytes exceeds %d byte limit", rel, size, max_file_size)- if src.suffix == ".db":- oversized_skipped.append(rel)- continue- dst = staging_dir / rel- dst.parent.mkdir(parents=True, exist_ok=True)- try:- # SQLite DBs go through the WAL-safe backup() path (the gateway may hold the WAL open).- if src.suffix == ".db":- if not _safe_copy_db(src, dst):- failed_dbs.append(rel)- print(f" ⚠ Snapshot: SQLite safe copy FAILED for {rel} — file may be locked or corrupted")- if is_zeroed_sqlite_file(src):- nuls = " of NULs?" if in_dir else ""- print(f" ⚠ Snapshot: {rel} looks ZEROED "- f"(no SQLite header; {src.stat().st_size} bytes{nuls})")- continue- else:- shutil.copy2(src, dst)- manifest[rel] = dst.stat().st_size- except (OSError, PermissionError) as exc:- logger.warning("Could not snapshot %s: %s", rel, exc)- return manifest, failed_dbs, oversized_skipped---def _create_quick_snapshot_locked(- label: Optional[str], home: Path, keep: Optional[int], max_file_size: Optional[int]-) -> Optional[str]:- """Copy the quick-snapshot set to a timestamped dir under state-snapshots/ and prune old ones.-- ``max_file_size`` skips (with a warning) larger files: the pre-update snapshot uses it so a- multi-GB ``state.db`` never stalls ``hermes update`` while the small files are always captured.- """- root = _quick_snapshot_root(home)- ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")- base_snap_id = f"{ts}-{label}" if label else ts- snap_id, suffix = base_snap_id, 2- while (root / snap_id).exists():- snap_id = f"{base_snap_id}-{suffix}"- suffix += 1- staging_dir = root / f".{snap_id}.{os.getpid()}.partial"- shutil.rmtree(staging_dir, ignore_errors=True)- staging_dir.mkdir(parents=True, exist_ok=False)- logger.info("quick snapshot phase=copy status=started id=%s", snap_id)- manifest, failed_dbs, oversized_skipped = _copy_quick_snapshot_files(home, staging_dir, max_file_size)- if failed_dbs:- # Surface on stdout: a log-and-continue made a missing state.db backup look like a- # successful pre-update snapshot (#68474).- print(f" ⚠ CRITICAL: could not snapshot DB file(s): {', '.join(failed_dbs)}\n"- f" ⚠ If sessions disappear after update, check {root} and run: hermes snapshot list")- logger.error("Quick snapshot failed to capture DB file(s): %s", ", ".join(failed_dbs))- if not manifest:- shutil.rmtree(staging_dir, ignore_errors=True)- if failed_dbs:- # Distinguish "nothing to snapshot" from "state.db present but unreadable"- print(f" ⚠ Snapshot aborted: no files captured (failed DBs: {', '.join(failed_dbs)})")- return None- meta = {- "id": snap_id, "timestamp": ts, "label": label, "file_count": len(manifest),- "total_size": sum(manifest.values()), "files": manifest,- "failed_dbs": failed_dbs, "oversized_skipped": oversized_skipped,- }- with open(staging_dir / "manifest.json", "w", encoding="utf-8") as f:- json.dump(meta, f, indent=2)- os.replace(staging_dir, root / snap_id)- # Auto-prune (pre-update callers pass a smaller keep so state.db copies don't accumulate).- # Skip when a DB failed to capture OR was skipped for size (#68805): the snapshot is- # incomplete and the older one may hold the only recoverable database.- if not (failed_dbs or oversized_skipped):- _prune_oldest(_snapshot_dirs(root), _QUICK_DEFAULT_KEEP if keep is None else keep, shutil.rmtree, "snapshot")- else:- if oversized_skipped:- print(" ⚠ Skipping snapshot prune: DB file(s) skipped for size: " + ", ".join(oversized_skipped))- logger.warning("Quick snapshot skipped oversized DB file(s): %s", ", ".join(oversized_skipped))- logger.warning(- "Skipping snapshot prune because %d DB(s) failed to capture and/or %d were oversized "- "— preserving older snapshots as recovery source",- len(failed_dbs), len(oversized_skipped))- logger.info("quick snapshot phase=copy status=complete id=%s files=%d bytes=%d",- snap_id, len(manifest), sum(manifest.values()))- return snap_id---def _newest_first(root: Path, keep_entry) -> List[Path]:- """Entries of *root* passing ``keep_entry``, newest (by name) first; ``[]`` if *root* is missing."""- if not root.exists():- return []- return sorted(filter(keep_entry, root.iterdir()), key=lambda p: p.name, reverse=True)---def _snapshot_dirs(root: Path) -> List[Path]:- """Published snapshot directories under *root*, newest first."""- return _newest_first(root, lambda d: d.is_dir() and not d.name.startswith(".")- and not d.name.endswith(".partial"))---def list_quick_snapshots(limit: int = 20, hermes_home: Optional[Path] = None) -> List[Dict[str, Any]]:- """List existing quick state snapshots, most recent first."""- results = []- for d in _snapshot_dirs(_quick_snapshot_root(hermes_home)):- manifest_path = d / "manifest.json"- if manifest_path.exists():- try:- results.append(json.loads(manifest_path.read_text(encoding="utf-8-sig")))- except (json.JSONDecodeError, OSError):- results.append({"id": d.name, "file_count": 0, "total_size": 0})- if len(results) >= limit:- break- return results---def restore_quick_snapshot(snapshot_id: str, hermes_home: Optional[Path] = None) -> bool:- """Restore state from a quick snapshot."""- home = hermes_home or get_hermes_home()- root = _quick_snapshot_root(home)- # Reject ids with separators or traversal so ``root / snapshot_id`` stays inside root.- if not snapshot_id or "/" in snapshot_id or "\\" in snapshot_id or snapshot_id in (".", ".."):- logger.error("Invalid snapshot_id: %s", snapshot_id)- return False- snap_dir = root / snapshot_id- if not _is_within(snap_dir, root.resolve()): # handles symlinks etc.- logger.error("Snapshot path traversal blocked for id: %s", snapshot_id)- return False- manifest_path = snap_dir / "manifest.json"- if not snap_dir.is_dir() or not manifest_path.exists():- return False- with open(manifest_path, encoding="utf-8-sig") as f:- meta = json.load(f)- snap_res, home_res = snap_dir.resolve(), home.resolve()- restored = 0- for rel in meta.get("files", {}):- src = snap_dir / rel- dst = home / rel- if not (_is_within(src, snap_res) and _is_within(dst, home_res)):- logger.error("Manifest path traversal blocked: %s", rel)- continue- if not src.exists():- continue- dst.parent.mkdir(parents=True, exist_ok=True)- try:- if dst.suffix == ".db":- # Through the backup API so live connections see the restored data instead of- # stale pages from a replaced inode (#65942).- if not _safe_restore_db(src, dst):- # Refused (live holder) or failed: destination untouched — a failure, not a restore.- logger.error("Failed to restore %s: live-safe restore refused", rel)- continue- else:- shutil.copy2(src, dst)- restored += 1- except (OSError, PermissionError) as exc:- logger.error("Failed to restore %s: %s", rel, exc)- logger.info("Restored %d files from snapshot %s", restored, snapshot_id)- return restored > 0---# Kept in sync with ``_QUICK_STATE_FILES`` and ``cron/jobs.py``'s ``JOBS_FILE``.-_CRON_JOBS_REL = "cron/jobs.json"---def _count_cron_jobs(path: Path) -> Optional[int]:- """Number of cron jobs in ``path`` (canonical ``{"jobs": [...]}`` or legacy bare list).-- ``None`` if missing or unparseable — "unknown", not zero: acting on an unreadable file could- mask a real corruption the user needs to see.- """- if not path.is_file():- return None- try:- # utf-8-sig as cron/jobs.load_jobs: a Windows-editor BOM would otherwise read as- # "unreadable" and silently disable the post-update auto-restore safety net.- with open(path, "r", encoding="utf-8-sig") as f:- data = json.load(f)- except (OSError, json.JSONDecodeError):- return None- if isinstance(data, dict):- data = data.get("jobs", [])- return len(data) if isinstance(data, list) else None---def restore_cron_jobs_if_emptied(snapshot_id: str, hermes_home: Optional[Path] = None) -> Optional[Dict[str, Any]]:- """Safety net for silent cron-job loss across ``hermes update``.-- Conservative: restores only when the snapshot had MORE jobs than the live file (a user who- deleted jobs is never second-guessed); an unreadable live file is left so corruption surfaces.-- Config-version migrations have been observed to leave ``cron/jobs.json`` valid-but-empty after an- update, silently dropping every scheduled job (issue #34600). The desktop scheduler can also overwrite- the file with its own small set of internally-tracked crons, causing partial loss (issue 52144).- """- if not snapshot_id:- return None- home = hermes_home or get_hermes_home()- live_path = home / _CRON_JOBS_REL- live_count = _count_cron_jobs(live_path)- if live_count is None:- return None- snap_path = _quick_snapshot_root(home) / snapshot_id / _CRON_JOBS_REL- snap_count = _count_cron_jobs(snap_path)- # Fewer live jobs than the snapshot catches both total loss (0 vs N) and partial loss- # (1 vs 19) — the desktop scheduler can overwrite jobs.json with its own small set.- if not snap_count or live_count >= snap_count: # None or 0 — nothing worth restoring- return None- try:- live_path.parent.mkdir(parents=True, exist_ok=True)- shutil.copy2(snap_path, live_path)- except (OSError, PermissionError) as exc:- logger.error("Cron jobs were emptied during update but auto-restore failed: %s", exc)- return None- logger.warning(- "Restored %d cron job(s) from pre-update snapshot %s "- "(live file had %d job(s), snapshot had %d — jobs were lost during migration)",- snap_count, snapshot_id, live_count, snap_count)- return {"restored": True, "job_count": snap_count, "snapshot_id": snapshot_id}---def _sibling_profile_homes(invoking_home: Path) -> list[tuple[str, Path]]:- """(name, home) for every OTHER profile on this install (the invoking one is snapshotted- separately). The update's code swap touches every profile, so its snapshot must too (#66140).- Never raises."""- homes: list[tuple[str, Path]] = []- try:- from hermes_cli.profiles import _get_default_hermes_home, _get_profiles_root, _PROFILE_ID_RE- invoking = invoking_home.resolve()- default_home = _get_default_hermes_home()- if default_home.is_dir() and default_home.resolve() != invoking:- homes.append(("default", default_home))- root = _get_profiles_root()- if root.is_dir():- for entry in sorted(root.iterdir()):- if (entry.is_dir() and entry.name != "default" and _PROFILE_ID_RE.match(entry.name)- and entry.resolve() != invoking):- homes.append((entry.name, entry))- except Exception as exc:- logger.debug("Sibling profile enumeration failed: %s", exc)- return homes---def create_pre_update_snapshots_all_profiles(- invoking_home: Optional[Path] = None, keep: Optional[int] = None, max_file_size: Optional[int] = None-) -> Dict[str, str]:- """Pre-update quick snapshots for every SIBLING profile (#66140), same set/size cap/keep policy- as the invoking profile's; each lands under its OWN ``<home>/state-snapshots/``."""- results: Dict[str, str] = {}- home = invoking_home or get_hermes_home()- for name, profile_home in _sibling_profile_homes(home):- try:- snap_id = create_quick_snapshot(- label="pre-update", hermes_home=profile_home, keep=keep, max_file_size=max_file_size)- if snap_id:- results[name] = snap_id- except Exception as exc:- logger.debug("Pre-update snapshot for profile %s failed: %s", name, exc)- return results---# Config paths the update flow must never change (#64160): model routing and the MoA section are-# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid-# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.-_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (- ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),- ("moa",))---def _read_raw_yaml_dict(path: Path) -> Optional[Dict[str, Any]]:- """Parse ``path`` as a YAML mapping. ``None`` = missing/unreadable/non-dict."""- if not path.is_file():- return None- try:- import yaml- data = yaml.safe_load(path.read_text(encoding="utf-8-sig"))- except Exception:- return None- return data if isinstance(data, dict) else None---def _get_config_path_value(data: Dict[str, Any], dotted: Tuple[str, ...]) -> Any:- node: Any = data- for key in dotted:- if not isinstance(node, dict):- return None- node = node.get(key)- return node---def _set_config_path_value(data: Dict[str, Any], dotted: Tuple[str, ...], value: Any) -> None:- node = data- for key in dotted[:-1]:- if not isinstance(node.get(key), dict):- node[key] = {}- node = node[key]- node[dotted[-1]] = value---def restore_config_model_settings_if_rewritten(- snapshot_id: str, hermes_home: Optional[Path] = None) -> Optional[Dict[str, Any]]:- """Safety net for silent config.yaml model/MoA loss across ``hermes update``.-- Mirrors :func:`restore_cron_jobs_if_emptied`: restore only the protected keys — never the- whole file — whose user-set value in the same-run pre-update snapshot changed or vanished.- """- if not snapshot_id:- return None- home = hermes_home or get_hermes_home()- live_path = home / "config.yaml"- snap = _read_raw_yaml_dict(_quick_snapshot_root(home) / snapshot_id / "config.yaml")- if not snap:- return None # no snapshot copy — nothing to compare against- live = _read_raw_yaml_dict(live_path)- if live is None:- # Missing/unparseable live config is a failure the user should see (matches the cron net).- return None- restored_keys: list[str] = []- for dotted in _PROTECTED_CONFIG_PATHS:- snap_val = _get_config_path_value(snap, dotted)- if snap_val in (None, "", {}, []):- continue # user never set it — nothing to protect- if _get_config_path_value(live, dotted) != snap_val:- _set_config_path_value(live, dotted, snap_val)- restored_keys.append(".".join(dotted))- if not restored_keys:- return None- try:- from utils import atomic_yaml_write- atomic_yaml_write(live_path, live)- except (OSError, PermissionError) as exc:- logger.error("config.yaml model settings were rewritten during update but auto-restore failed: %s", exc)- return None- logger.warning(- "Restored user config value(s) %s from pre-update snapshot %s — "- "the update flow rewrote them (#64160)", ", ".join(restored_keys), snapshot_id)- return {"restored": True, "keys": restored_keys, "snapshot_id": snapshot_id}+ "kanban.db", # default board (back-compat <root>/kanban.db)+ "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)+ # Pairing stores (generic + per-platform JSONs outside state.db)+ "pairing", # legacy location (gateway/pairing.py)+ "platforms/pairing", # new location (gateway/pairing.py)+ "feishu_comment_pairing.json", # Feishu comment subscription pairings+)+_QUICK_DEFAULT_KEEP = 20-def _restore_all_sibling_profiles(- profile_snapshots: Dict[str, str], invoking_home: Optional[Path], restore_fn, failure_log: str-) -> list[Dict[str, Any]]:- """Run ``restore_fn(snap_id, hermes_home=...)`` for every sibling against ITS OWN- same-generation snapshot; one result dict (plus ``profile`` key) per restored profile.- Never raises."""- restored: list[Dict[str, Any]] = []- if not profile_snapshots:- return restored- home = invoking_home or get_hermes_home()- by_name = dict(_sibling_profile_homes(home))- for name, snap_id in profile_snapshots.items():- profile_home = by_name.get(name)- if profile_home is None:- continue- try:- result = restore_fn(snap_id, hermes_home=profile_home)- except Exception as exc:- logger.debug(failure_log, name, exc)- continue- if result:- result["profile"] = name- restored.append(result)- return restored++def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:+ home = hermes_home or get_hermes_home()+ return home / _QUICK_SNAPSHOTS_DIR-def restore_config_model_settings_all_profiles(- profile_snapshots: Dict[str, str], invoking_home: Optional[Path] = None) -> list[Dict[str, Any]]:- """Run the config model-settings safety net for every sibling profile (see ``_restore_all_sibling_profiles``)."""- return _restore_all_sibling_profiles(- profile_snapshots, invoking_home, restore_config_model_settings_if_rewritten,- "Config model-settings restore check for profile %s failed: %s")+def _newest_first(root: Path, keep_entry) -> List[Path]:+ """Entries of *root* passing ``keep_entry``, newest (by name) first; ``[]`` if *root* is missing."""+ if not root.exists():+ return []+ return sorted(filter(keep_entry, root.iterdir()), key=lambda p: p.name, reverse=True)-def restore_cron_jobs_all_profiles(- profile_snapshots: Dict[str, str], invoking_home: Optional[Path] = None) -> list[Dict[str, Any]]:- """Run the cron-jobs safety net for every sibling profile (#66140); ``profile_snapshots`` comes- from :func:`create_pre_update_snapshots_all_profiles`, so restores are same-generation."""- return _restore_all_sibling_profiles(- profile_snapshots, invoking_home, restore_cron_jobs_if_emptied,- "Cron restore check for profile %s failed: %s")+# Kept in sync with ``_QUICK_STATE_FILES`` and ``cron/jobs.py``'s ``JOBS_FILE``.+_CRON_JOBS_REL = "cron/jobs.json"+++# Config paths the update flow must never change (#64160): model routing and the MoA section are+# consumed machine-wide, so an update/repair cycle that rewrites them silently redirects paid+# inference. Dotted paths into raw config.yaml; a single-element tuple protects a whole section.+_PROTECTED_CONFIG_PATHS: Tuple[Tuple[str, ...], ...] = (+ ("model", "provider"), ("model", "default"), ("model", "base_url"), ("model", "api_key"),+ ("moa",))def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> int:@@ -1505,70 +478,8 @@ def _prune_oldest(newest_first: List[Path], keep: int, remove, what: str) -> intreturn deleted-def prune_quick_snapshots(keep: int = _QUICK_DEFAULT_KEEP, hermes_home: Optional[Path] = None) -> int:- """Remove oldest quick snapshots beyond the keep limit. Returns count deleted."""- return _prune_oldest(_snapshot_dirs(_quick_snapshot_root(hermes_home)), keep, shutil.rmtree, "snapshot")---def run_quick_backup(args) -> None:- """CLI entry point for hermes backup --quick."""- snap_id = create_quick_snapshot(label=getattr(args, "label", None))- if snap_id:- print(f"State snapshot created: {snap_id}\n"- f" {len(list_quick_snapshots())} snapshot(s) stored in {display_hermes_home()}/state-snapshots/\n"- f" Restore with: /snapshot restore {snap_id}")- else:- print("No state files found to snapshot.")--# --- Shared full-zip backup helper ----def _write_full_zip_backup(out_path: Path, hermes_root: Path) -> Optional[Path]:- """Full zip snapshot of ``hermes_root`` to ``out_path`` under the backup slot (same rules as- :func:`run_backup`); None when nothing to back up, another backup running, or write error."""- try:- with _backup_operation_lock(hermes_root):- return _write_full_zip_backup_locked(out_path, hermes_root)- except BackupInProgressError as exc:- logger.warning("Full-zip backup skipped: %s", exc)- return None---def _write_full_zip_backup_locked(out_path: Path, hermes_root: Path) -> Optional[Path]:- scan_started = time.monotonic()- logger.info("automatic backup phase=scan status=started")- try:- files_to_add = list(_iter_backup_files(hermes_root, out_path))- except OSError as exc:- logger.warning("Full-zip backup: walk failed: %s", exc)- return None- if not files_to_add:- return None- logger.info("automatic backup phase=scan status=complete duration_ms=%.1f files=%d",- (time.monotonic() - scan_started) * 1000, len(files_to_add))-- def _db_failure(rel_path: Path) -> None:- logger.warning("Full-zip backup aborted: SQLite snapshot failed for %s", rel_path)- raise _SQLiteSnapshotError(str(rel_path))-- archive_started = time.monotonic()- try:- with _atomic_output_path(out_path) as archive_path, zipfile.ZipFile(- archive_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zf:- _write_zip_entries(- zf, files_to_add, out_path, on_db_failure=_db_failure, track_bytes=False,- on_error=lambda rel, exc: logger.debug("Skipping %s in zip backup: %s", rel, exc),- on_progress=lambda i: logger.info(- "automatic backup phase=archive status=progress completed=%d total=%d", i, len(files_to_add)))- except (OSError, _SQLiteSnapshotError) as exc:- # The hidden partial is already gone; ``out_path`` may be a previous valid backup: keep it.- logger.warning("Full-zip backup: zip write failed: %s", exc)- return None- logger.info("automatic backup phase=archive status=complete duration_ms=%.1f files=%d bytes=%d",- (time.monotonic() - archive_started) * 1000, len(files_to_add),- out_path.stat().st_size)- return out_path-# --- Pre-update / pre-migration auto-backups ---@@ -1652,164 +563,7 @@ def copy_db_and_verify(src: Path, dst: Path) -> bool:return True-def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:- """PIDs of OTHER processes holding *db_path* or its WAL/SHM open.-- Linux-only ``/proc/<pid>/fd`` scan (no psutil dependency), preserving the- kernel's ``(deleted)`` suffix so an already-unlinked sidecar generation —- the #90950 split-brain fingerprint — still counts as held. Returns- ``None`` when the scan is unavailable (non-Linux, or /proc unreadable);- callers must treat ``None`` as "unknown", not as "no holders".- """- if not sys.platform.startswith("linux"):- return None-- def _canonical(path: str) -> str:- return os.path.normcase(- os.path.abspath(path.removesuffix(" (deleted)"))- )-- canonical_db = _canonical(os.fspath(db_path))- watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}- pids: List[int] = []- try:- own_pid = os.getpid()- for pid_str in os.listdir("/proc"):- if not pid_str.isdigit():- continue- pid = int(pid_str)- if pid == own_pid:- continue- fd_dir = f"/proc/{pid}/fd"- try:- fds = os.listdir(fd_dir)- except OSError:- continue- for fd in fds:- try:- target = os.readlink(f"{fd_dir}/{fd}")- except OSError:- continue- if _canonical(target) in watched:- pids.append(pid)- break- except OSError:- return None- return pids---def _safe_restore_db(src: Path, dst: Path) -> bool:- """Restore a SQLite database from snapshot *src* into live *dst*.-- Uses SQLite's backup() API to write snapshot pages into the live- database file, preserving the file's inode and WAL state so that- any other process still holding the DB open (gateway, dashboard,- another CLI session) sees the restored data on the next read —- instead of continuing to serve stale cached pages from a replaced- inode.-- The old approach was ``unlink() + move()``, which replaced the file- under any live connection. SQLite connections cache pages in- per-connection page caches keyed by inode; after an unlink+move the- old inode still existed (the live connection held a reference), so- that connection continued serving the pre-restore data while new- connections saw the restored snapshot — a partial/inconsistent- state (issue #65942).-- By writing pages through the backup API the file inode is preserved,- the WAL journal is updated correctly, and all connections (old and- new) converge on the restored data.-- Falls back to the unlink+move approach on failure ONLY when no other- process or in-process connection holds the file: replacing the inode- under a live holder is the #90950 split-brain, so that branch fails- closed (returns ``False``) and the caller reports the file as skipped.- """- try:- dst_conn = sqlite3.connect(str(dst))- try:- # Force a WAL checkpoint so the backup starts from a clean- # state rather than writing on top of a deep WAL.- dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")- except Exception:- pass- src_conn = sqlite3.connect(f"file:{src}?mode=ro", uri=True)- try:- src_conn.backup(dst_conn)- finally:- src_conn.close()- dst_conn.close()- # Restore original file permissions from the snapshot- try:- mode = src.stat().st_mode- dst.chmod(mode)- except Exception:- pass- return True- except Exception as exc:- logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)- # Fallback: unlink+move (the old approach). This still works for- # the common case where no other process holds the DB open.- from hermes_cli.sqlite_safe_read import (- LiveConnectionError,- offline_file_access,- )-- try:- holders = _foreign_db_holder_pids(dst)- if holders:- # Replacing the inode under a live holder is the #90950- # corruption class: the holder keeps writing through a- # deleted-inode fd (split brain), and removing its sidecars- # detaches the WAL index it is checkpointing through. The- # backup-API path above is the live-safe route; if it failed,- # fail closed rather than corrupt.- logger.error(- "Refusing unlink+move restore of %s: process(es) %s still "- "hold the database or its WAL open. Stop them and retry.",- dst, holders,- )- return False- # The foreign-pid scan above deliberately excludes THIS process,- # but an in-process SessionDB (the agent's own handle during- # /snapshot restore, a second SessionDB instance, a read pool)- # is exactly as much of a live holder: unlinking the DB and its- # sidecars under it leaves this process on deleted-inode fds —- # the same #90950 split brain, produced first-party (proven live- # on main: `/proc/self/fd` shows `state.db-wal (deleted)` right- # after this fallback ran under a tracked connection).- # ``offline_file_access`` fails CLOSED when any tracked- # connection to *dst* is live and holds the connection-lifecycle- # lock across the whole swap so no new connection can appear- # mid-replace.- with offline_file_access(dst, what="unlink+move restore of"):- tmp = dst.parent / f".{dst.name}.snap_restore"- shutil.copy2(src, tmp)- dst.unlink(missing_ok=True)- # Drop the destination's sidecars before installing the- # snapshot. The snapshot is a checkpointed ``sqlite3.backup()``- # image (see ``_safe_copy_db``) that owns no WAL, so any- # ``-wal``/``-shm`` still sitting here describes the database we- # just unlinked — an ungracefully killed gateway leaves them- # behind, which is exactly when a restore gets run. SQLite- # replays that foreign WAL over the restored file on the next- # open and the database comes up "malformed" (or silently- # resurrects post-snapshot rows). Same reasoning as- # ``_EXCLUDED_SUFFIXES``, applied to the restore destination.- for _sidecar_suffix in ("-wal", "-shm", "-journal"):- dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)- shutil.move(str(tmp), str(dst))- return True- except LiveConnectionError as exc2:- logger.error(- "Refusing unlink+move restore of %s: %s Close the in-process "- "database handles (or restart Hermes) and retry.",- dst, exc2,- )- return False- except Exception as exc2:- logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)- return False+# ---- END PLUGIN-COMPAT ----# ---------------------------------------------------------------------------@@ -2021,269 +775,6 @@ def _run_backup_locked(args, hermes_root: Path) -> None:# Import# ----------------------------------------------------------------------------def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:- """Check that a zip looks like a Hermes backup.-- Returns (ok, reason).- """- names = zf.namelist()- if not names:- return False, "zip archive is empty"-- # Look for telltale files that a hermes home would have- markers = {"config.yaml", ".env", "state.db"}- found = set()- for n in names:- # Could be at the root or one level deep (if someone zipped the directory)- basename = Path(n).name- if basename in markers:- found.add(basename)-- if not found:- return False, (- "zip does not appear to be a Hermes backup "- "(no config.yaml, .env, or state databases found)"- )-- return True, ""---def _detect_prefix(zf: zipfile.ZipFile) -> str:- """Detect if the zip has a common directory prefix wrapping all entries.-- Some tools zip as `.hermes/config.yaml` instead of `config.yaml`.- Returns the prefix to strip (empty string if none).- """- names = [n for n in zf.namelist() if not n.endswith("/")]- if not names:- return ""-- # Find common prefix- parts_list = [Path(n).parts for n in names]-- # Check if all entries share a common first directory- first_parts = {p[0] for p in parts_list if len(p) > 1}- if len(first_parts) == 1:- prefix = first_parts.pop()- # Only strip if it looks like a hermes dir name- if prefix in {".hermes", "hermes"}:- return prefix + "/"-- return ""---def _default_new_file_mode() -> Optional[int]:- """Return the mode ``open(path, "wb")`` gives a file it has to create.-- ``tempfile.mkstemp`` always creates at 0600, so staging an import through a- temp file would tighten every *newly created* file to owner-only — the same- hazard ``utils._restore_file_mode`` documents for Docker/NAS volume mounts- that rely on broader permissions. The umask can only be read by setting it,- so this is resolved once per import rather than once per member. The probe- installs a *restrictive* mask rather than 0 so that anything another thread- creates inside the two-syscall window is owner-only, never world-writable.- Returns ``None`` if the umask cannot be read, in which case the caller- leaves mkstemp's mode alone.- """- try:- current = os.umask(0o077)- os.umask(current)- except OSError:- return None- return 0o666 & ~current---def _extract_member_atomically(- zf: zipfile.ZipFile,- member: str,- target: Path,- new_file_mode: Optional[int] = None,-) -> None:- """Restore one zip member onto *target* with no truncation window.-- ``open(target, "wb")`` truncates the user's existing file to zero *before*- any replacement bytes exist. A Ctrl-C, an ENOSPC, a corrupt member, or a- crash between the truncate and the write therefore leaves that file empty- with nothing behind it — during ``hermes import``, which is the- disaster-recovery path a user reaches for *because* they already lost- something. Staging into the target's own directory and publishing with a- rename means the target only ever moves from its old contents to the- complete new contents.-- ``atomic_replace`` rather than a bare ``os.replace``: it resolves a- symlinked target first, so a deployment that links ``config.yaml`` into a- dotfiles repo keeps the link instead of having it silently swapped for a- regular file (GitHub #16743), and it falls back to copy/fsync/unlink on- ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs. That- fallback uses ``shutil.copyfile``, which does truncate in place, so on the- cross-device path the guarantee above degrades to today's behaviour rather- than improving on it; closing that belongs in ``utils.atomic_replace``,- where every atomic writer in the repo would benefit, not here.-- Permission bits *and* ownership are carried across the replace so routing- through mkstemp does not change the file the caller would otherwise have- produced. ``os.replace`` swaps in a temp file owned by the *writing* user,- so without the chown a ``sudo hermes import`` would silently re-own every- restored file to root — on the disaster-recovery path, and on exactly the- Docker/NAS installs ``utils._restore_file_owner`` documents. Both concerns- delegate to the shared ``utils`` helpers rather than being re-derived here.- The temp file is removed on any failure so a partial import leaves no- residue.-- The one bit of the old file *not* carried across is setuid/setgid. The- replacement bytes come out of the zip, so preserving those would let an- archive take over the identity an existing privileged file executes as —- and unlike the other ``utils`` writers, which re-serialize content this- process produced, the trust boundary here is an untrusted archive. The- mask is applied once, before the temp file is chmod'd, so neither the- pre-replace ``fchmod`` nor the post-replace restore can re-elevate the- target.- """- # ``_preserve_file_mode`` returns None when the target does not exist (or- # cannot be stat'd), in which case the umask-derived create-mode applies —- # the same shape as ``atomic_yaml_write``'s ``create_mode`` fallback.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- if mode is None:- mode = new_file_mode- else:- # Deliberately NOT a faithful mode copy: setuid/setgid are dropped.- # ``_preserve_file_mode`` returns ``stat.S_IMODE``, i.e. all twelve- # bits, and the content replacing this file comes from the archive.- # Carrying the elevated bits across would let archive-controlled bytes- # take over an existing setuid/setgid file, so ``hermes import`` would- # hand whoever produced the zip the identity that file runs as. Nothing- # constrains that to Hermes' own state either: the ``_external/`` branch- # of ``run_import`` publishes members anywhere under ``$HOME``. The- # sticky bit is kept — it is inert on a regular file.- mode &= ~(stat.S_ISUID | stat.S_ISGID)-- # Truncate the stem: mkstemp adds ~16 characters, and a member already near- # NAME_MAX would otherwise fail here on a write that used to succeed.- fd, tmp_name = tempfile.mkstemp(- dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial"- )- try:- with os.fdopen(fd, "wb") as dst:- if mode is not None:- # Apply the mode to the temp file BEFORE the replace so the- # target never transits through mkstemp's 0600, and so- # ``atomic_replace``'s EXDEV/EBUSY ``shutil.copystat`` fallback- # copies the intended bits rather than 0600. fchmod is- # Unix-only; Windows takes the path-based chmod.- if hasattr(os, "fchmod"):- os.fchmod(dst.fileno(), mode)- else:- os.chmod(tmp_name, mode)- # Stream instead of ``src.read()``: a multi-gigabyte state.db member- # must not be held in memory in one piece.- with zf.open(member) as src:- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- real_path = Path(atomic_replace(tmp_name, target))- # Owner first, mode second — the ordering ``atomic_yaml_write`` uses,- # because chown drops setuid/setgid and a mode restore that ran first- # would be partly undone. Here ``mode`` no longer carries those bits,- # so the two agree: neither step can re-elevate the restored file.- _restore_file_owner(real_path, owner)- _restore_file_mode(real_path, mode)- except BaseException:- try:- os.unlink(tmp_name)- except OSError:- pass- raise---def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:- """Return ``(sessions, messages)`` stored in the session database *path*.-- Read-only and best effort. ``None`` means "unknown" — a missing file, a- database that is not a Hermes session store, or one that cannot be read.- Callers must never read ``None`` as "zero rows": acting on an unreadable- database would mask the very loss this count exists to surface. Same- contract as :func:`_count_cron_jobs`.- """- if not path.is_file():- return None- try:- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)- except sqlite3.Error:- return None- try:- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]- return int(sessions), int(messages)- except (sqlite3.Error, TypeError, ValueError):- return None- finally:- conn.close()---def _import_db_member(- zf: zipfile.ZipFile,- member: str,- target: Path,- new_file_mode: Optional[int] = None,-) -> None:- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.-- ``_extract_member_atomically`` publishes with a rename. For an ordinary- file that is the safest write available; for a live SQLite database it is- the #65942 / #90950 corruption class. A gateway, dashboard, or WebUI- process holding the database open keeps its descriptor on the now-unlinked- inode: it goes on serving pre-import pages and writing sessions that no- other process will ever see, and any sidecar WAL left beside the new file- describes the database that was just unlinked. Nothing fails, so nothing- is reported — the sessions simply are not there afterwards (issue #100960).-- ``hermes import`` is the disaster-recovery path, so that failure mode lands- on users who have already lost something once. Route the member through- the same ``_safe_restore_db`` page copy that ``/snapshot restore`` has used- since #65942: the live inode is preserved, every open connection converges- on the imported data, and the sidecars are handled there. A target that- does not exist yet has no holders and no inode worth preserving, so it- takes the ordinary atomic publish.-- Raises ``OSError`` when the database could not be replaced safely, so the- caller reports a skipped file instead of counting a silent success.- """- if not target.exists():- _extract_member_atomically(zf, member, target, new_file_mode)- return-- # The database keeps its own mode/ownership: the bytes come from the- # archive but the file does not, so the archive has no say in either.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)-- fd, tmp_name = tempfile.mkstemp(- dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport"- )- try:- with os.fdopen(fd, "wb") as dst:- # Stream: a multi-gigabyte state.db member must not be held in- # memory in one piece.- with zf.open(member) as src:- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- if not _safe_restore_db(Path(tmp_name), target):- raise OSError(- "live-safe restore refused or failed; the existing database was "- "left untouched. Stop the gateway/dashboard processes holding it "- "open and re-run the import."- )- _restore_file_owner(target, owner)- _restore_file_mode(target, mode)- finally:- try:- os.unlink(tmp_name)- except OSError:- pass--def run_import(args) -> None:"""Restore a Hermes backup from a zip file."""zip_path = Path(args.zipfile).expanduser().resolve()@@ -2630,11 +1121,6 @@ _QUICK_STATE_FILES = (_QUICK_DEFAULT_KEEP = 20-def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:- home = hermes_home or get_hermes_home()- return home / _QUICK_SNAPSHOTS_DIR--def create_quick_snapshot(label: Optional[str] = None,hermes_home: Optional[Path] = None,@@ -3501,165 +1987,3 @@ def _write_full_zip_backup_locked(out_path: Path, hermes_root: Path) -> Optional# ----------------------------------------------------------------------------# Pre-update auto-backup-# -----------------------------------------------------------------------------_PRE_UPDATE_BACKUPS_DIR = "backups"-_PRE_UPDATE_PREFIX = "pre-update-"-_PRE_UPDATE_DEFAULT_KEEP = 5---def _pre_update_backup_dir(hermes_home: Optional[Path] = None) -> Path:- home = hermes_home or get_hermes_home()- return home / _PRE_UPDATE_BACKUPS_DIR---def _prune_pre_update_backups(backup_dir: Path, keep: int) -> int:- """Remove oldest pre-update backups beyond the keep limit.-- Returns the number of files deleted. Only touches files matching- ``pre-update-*.zip`` so hand-made zips dropped in the same directory- are never touched.-- ``keep`` is floored to 1 because this helper is only called immediately- after a fresh backup is written: deleting that backup right after the- user paid the disk/CPU cost to create it would leave them worse off- than no backup at all (and the wrapper in ``main.py`` would still print- a misleading ``Saved: <path>`` line for a file that no longer exists).- Operators who genuinely don't want a backup should set- ``updates.pre_update_backup: off`` in config — that gates creation.- """- keep = max(keep, 1)- if not backup_dir.exists():- return 0-- backups = sorted(- (p for p in backup_dir.iterdir()- if p.is_file() and p.name.startswith(_PRE_UPDATE_PREFIX) and p.suffix.lower() == ".zip"),- key=lambda p: p.name,- reverse=True,- )-- deleted = 0- for p in backups[keep:]:- try:- p.unlink()- deleted += 1- except OSError as exc:- logger.warning("Failed to prune backup %s: %s", p.name, exc)-- return deleted---def create_pre_update_backup(- hermes_home: Optional[Path] = None,- keep: int = _PRE_UPDATE_DEFAULT_KEEP,-) -> Optional[Path]:- """Create a full zip backup of HERMES_HOME under ``backups/``.-- Mirrors :func:`run_backup` (same exclusion rules, same SQLite safe-copy)- but writes to ``<HERMES_HOME>/backups/pre-update-<timestamp>.zip`` and- auto-prunes old pre-update backups.-- Returns the path to the created zip, or ``None`` if no files were- found or the backup could not be created. Never raises — the caller- (``hermes update``) should continue even if the backup fails.- """- hermes_root = hermes_home or get_default_hermes_root()- if not hermes_root.is_dir():- return None-- backup_dir = _pre_update_backup_dir(hermes_root)- try:- backup_dir.mkdir(parents=True, exist_ok=True)- except OSError as exc:- logger.warning("Could not create pre-update backup dir %s: %s", backup_dir, exc)- return None-- stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")- out_path = backup_dir / f"{_PRE_UPDATE_PREFIX}{stamp}.zip"-- result = _write_full_zip_backup(out_path, hermes_root)- if result is None:- return None-- _prune_pre_update_backups(backup_dir, keep=keep)- return out_path---# ----------------------------------------------------------------------------# Pre-migration auto-backup (used by `hermes claw migrate`)-# -----------------------------------------------------------------------------_PRE_MIGRATION_PREFIX = "pre-migration-"-_PRE_MIGRATION_DEFAULT_KEEP = 5---def _prune_pre_migration_backups(backup_dir: Path, keep: int) -> int:- """Remove oldest pre-migration backups beyond the keep limit.-- Only touches files matching ``pre-migration-*.zip`` so other backups in- the same directory are never touched.- """- keep = max(keep, 0)- if not backup_dir.exists():- return 0-- backups = sorted(- (p for p in backup_dir.iterdir()- if p.is_file() and p.name.startswith(_PRE_MIGRATION_PREFIX) and p.suffix.lower() == ".zip"),- key=lambda p: p.name,- reverse=True,- )-- deleted = 0- for p in backups[keep:]:- try:- p.unlink()- deleted += 1- except OSError as exc:- logger.warning("Failed to prune pre-migration backup %s: %s", p.name, exc)-- return deleted---def create_pre_migration_backup(- hermes_home: Optional[Path] = None,- keep: int = _PRE_MIGRATION_DEFAULT_KEEP,-) -> Optional[Path]:- """Create a full zip backup of HERMES_HOME under ``backups/`` before a- ``hermes claw migrate`` apply.-- Shares implementation with :func:`create_pre_update_backup` via- ``_write_full_zip_backup`` — same exclusions, same SQLite safe-copy,- restorable with ``hermes import <archive>``. Writes to- ``<HERMES_HOME>/backups/pre-migration-<timestamp>.zip`` and auto-prunes- old pre-migration backups.-- Returns the path to the created zip, or ``None`` if nothing was found- to back up (fresh install) or the write failed. Never raises — the- caller decides whether to abort or proceed.- """- hermes_root = hermes_home or get_default_hermes_root()- if not hermes_root.is_dir():- return None-- # Reuses the shared backups/ directory so `hermes import` and the- # update-backup listing pick up pre-migration archives too.- backup_dir = _pre_update_backup_dir(hermes_root)- try:- backup_dir.mkdir(parents=True, exist_ok=True)- except OSError as exc:- logger.warning("Could not create pre-migration backup dir %s: %s", backup_dir, exc)- return None-- stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")- out_path = backup_dir / f"{_PRE_MIGRATION_PREFIX}{stamp}.zip"-- result = _write_full_zip_backup(out_path, hermes_root)- if result is None:- return None-- _prune_pre_migration_backups(backup_dir, keep=keep)- return out_path-# ---- END PLUGIN-COMPAT ----diff --git a/hermes_cli/backup_restore.py b/hermes_cli/backup_restore.pynew file mode 100644index 00000000000..e075bcc37cb--- /dev/null+++ b/hermes_cli/backup_restore.py@@ -0,0 +1,456 @@+"""SQLite-safe restore and archive-member publish plumbing for backups.++Owns the restore side of ``hermes_cli.backup``: the page-copy SQLite restore+(``_safe_restore_db`` plus the foreign-holder scan) and the zip-member publish+helpers used by ``hermes import`` and ``/snapshot restore``. Backup+*creation* (``run_backup``, full-zip writing) stays in ``hermes_cli.backup``,+which composes these helpers.+"""++import logging+import os+import shutil+import sqlite3+import stat+import sys+import tempfile+import zipfile+from pathlib import Path+from typing import List, Optional, Tuple++from utils import (+ _preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,+)++logger = logging.getLogger(__name__)++def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:+ """PIDs of OTHER processes holding *db_path* or its WAL/SHM open.++ Linux-only ``/proc/<pid>/fd`` scan (no psutil dependency), preserving the+ kernel's ``(deleted)`` suffix so an already-unlinked sidecar generation —+ the #90950 split-brain fingerprint — still counts as held. Returns+ ``None`` when the scan is unavailable (non-Linux, or /proc unreadable);+ callers must treat ``None`` as "unknown", not as "no holders".+ """+ if not sys.platform.startswith("linux"):+ return None++ def _canonical(path: str) -> str:+ return os.path.normcase(+ os.path.abspath(path.removesuffix(" (deleted)"))+ )++ canonical_db = _canonical(os.fspath(db_path))+ watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}+ pids: List[int] = []+ try:+ own_pid = os.getpid()+ for pid_str in os.listdir("/proc"):+ if not pid_str.isdigit():+ continue+ pid = int(pid_str)+ if pid == own_pid:+ continue+ fd_dir = f"/proc/{pid}/fd"+ try:+ fds = os.listdir(fd_dir)+ except OSError:+ continue+ for fd in fds:+ try:+ target = os.readlink(f"{fd_dir}/{fd}")+ except OSError:+ continue+ if _canonical(target) in watched:+ pids.append(pid)+ break+ except OSError:+ return None+ return pids+++def _safe_restore_db(src: Path, dst: Path) -> bool:+ """Restore a SQLite database from snapshot *src* into live *dst*.++ Uses SQLite's backup() API to write snapshot pages into the live+ database file, preserving the file's inode and WAL state so that+ any other process still holding the DB open (gateway, dashboard,+ another CLI session) sees the restored data on the next read —+ instead of continuing to serve stale cached pages from a replaced+ inode.++ The old approach was ``unlink() + move()``, which replaced the file+ under any live connection. SQLite connections cache pages in+ per-connection page caches keyed by inode; after an unlink+move the+ old inode still existed (the live connection held a reference), so+ that connection continued serving the pre-restore data while new+ connections saw the restored snapshot — a partial/inconsistent+ state (issue #65942).++ By writing pages through the backup API the file inode is preserved,+ the WAL journal is updated correctly, and all connections (old and+ new) converge on the restored data.++ Falls back to the unlink+move approach on failure ONLY when no other+ process or in-process connection holds the file: replacing the inode+ under a live holder is the #90950 split-brain, so that branch fails+ closed (returns ``False``) and the caller reports the file as skipped.+ """+ dst_conn: Optional[sqlite3.Connection] = None+ try:+ dst_conn = sqlite3.connect(str(dst))+ try:+ # Force a WAL checkpoint so the backup starts from a clean+ # state rather than writing on top of a deep WAL.+ dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ except Exception:+ pass+ src_conn = sqlite3.connect(f"file:{src}?mode=ro", uri=True)+ try:+ src_conn.backup(dst_conn)+ finally:+ src_conn.close()+ dst_conn.close()+ # Restore original file permissions from the snapshot+ try:+ mode = src.stat().st_mode+ dst.chmod(mode)+ except Exception:+ pass+ return True+ except Exception as exc:+ logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)+ # Release our own handle on *dst* before the fallback: on Windows an+ # open connection blocks unlink() with WinError 32, which would make+ # the fallback below dead code exactly when it is needed.+ if dst_conn is not None:+ try:+ dst_conn.close()+ except Exception:+ pass+ # Fallback: unlink+move (the old approach). This still works for+ # the common case where no other process holds the DB open.+ from hermes_cli.sqlite_safe_read import (+ LiveConnectionError,+ offline_file_access,+ )++ try:+ holders = _foreign_db_holder_pids(dst)+ if holders:+ # Replacing the inode under a live holder is the #90950+ # corruption class: the holder keeps writing through a+ # deleted-inode fd (split brain), and removing its sidecars+ # detaches the WAL index it is checkpointing through. The+ # backup-API path above is the live-safe route; if it failed,+ # fail closed rather than corrupt.+ logger.error(+ "Refusing unlink+move restore of %s: process(es) %s still "+ "hold the database or its WAL open. Stop them and retry.",+ dst, holders,+ )+ return False+ # The foreign-pid scan above deliberately excludes THIS process,+ # but an in-process SessionDB (the agent's own handle during+ # /snapshot restore, a second SessionDB instance, a read pool)+ # is exactly as much of a live holder: unlinking the DB and its+ # sidecars under it leaves this process on deleted-inode fds —+ # the same #90950 split brain, produced first-party (proven live+ # on main: `/proc/self/fd` shows `state.db-wal (deleted)` right+ # after this fallback ran under a tracked connection).+ # ``offline_file_access`` fails CLOSED when any tracked+ # connection to *dst* is live and holds the connection-lifecycle+ # lock across the whole swap so no new connection can appear+ # mid-replace.+ with offline_file_access(dst, what="unlink+move restore of"):+ tmp = dst.parent / f".{dst.name}.snap_restore"+ shutil.copy2(src, tmp)+ dst.unlink(missing_ok=True)+ # Drop the destination's sidecars before installing the+ # snapshot. The snapshot is a checkpointed ``sqlite3.backup()``+ # image (see ``_safe_copy_db``) that owns no WAL, so any+ # ``-wal``/``-shm`` still sitting here describes the database we+ # just unlinked — an ungracefully killed gateway leaves them+ # behind, which is exactly when a restore gets run. SQLite+ # replays that foreign WAL over the restored file on the next+ # open and the database comes up "malformed" (or silently+ # resurrects post-snapshot rows). Same reasoning as+ # ``_EXCLUDED_SUFFIXES``, applied to the restore destination.+ for _sidecar_suffix in ("-wal", "-shm", "-journal"):+ dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)+ shutil.move(str(tmp), str(dst))+ return True+ except LiveConnectionError as exc2:+ logger.error(+ "Refusing unlink+move restore of %s: %s Close the in-process "+ "database handles (or restart Hermes) and retry.",+ dst, exc2,+ )+ return False+ except Exception as exc2:+ logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)+ return False+++def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:+ """Check that a zip looks like a Hermes backup.++ Returns (ok, reason).+ """+ names = zf.namelist()+ if not names:+ return False, "zip archive is empty"++ # Look for telltale files that a hermes home would have+ markers = {"config.yaml", ".env", "state.db"}+ found = set()+ for n in names:+ # Could be at the root or one level deep (if someone zipped the directory)+ basename = Path(n).name+ if basename in markers:+ found.add(basename)++ if not found:+ return False, (+ "zip does not appear to be a Hermes backup "+ "(no config.yaml, .env, or state databases found)"+ )++ return True, ""+++def _detect_prefix(zf: zipfile.ZipFile) -> str:+ """Detect if the zip has a common directory prefix wrapping all entries.++ Some tools zip as `.hermes/config.yaml` instead of `config.yaml`.+ Returns the prefix to strip (empty string if none).+ """+ names = [n for n in zf.namelist() if not n.endswith("/")]+ if not names:+ return ""++ # Find common prefix+ parts_list = [Path(n).parts for n in names]++ # Check if all entries share a common first directory+ first_parts = {p[0] for p in parts_list if len(p) > 1}+ if len(first_parts) == 1:+ prefix = first_parts.pop()+ # Only strip if it looks like a hermes dir name+ if prefix in {".hermes", "hermes"}:+ return prefix + "/"++ return ""+++def _default_new_file_mode() -> Optional[int]:+ """Return the mode ``open(path, "wb")`` gives a file it has to create.++ ``tempfile.mkstemp`` always creates at 0600, so staging an import through a+ temp file would tighten every *newly created* file to owner-only — the same+ hazard ``utils._restore_file_mode`` documents for Docker/NAS volume mounts+ that rely on broader permissions. The umask can only be read by setting it,+ so this is resolved once per import rather than once per member. The probe+ installs a *restrictive* mask rather than 0 so that anything another thread+ creates inside the two-syscall window is owner-only, never world-writable.+ Returns ``None`` if the umask cannot be read, in which case the caller+ leaves mkstemp's mode alone.+ """+ try:+ current = os.umask(0o077)+ os.umask(current)+ except OSError:+ return None+ return 0o666 & ~current+++def _extract_member_atomically(+ zf: zipfile.ZipFile,+ member: str,+ target: Path,+ new_file_mode: Optional[int] = None,+) -> None:+ """Restore one zip member onto *target* with no truncation window.++ ``open(target, "wb")`` truncates the user's existing file to zero *before*+ any replacement bytes exist. A Ctrl-C, an ENOSPC, a corrupt member, or a+ crash between the truncate and the write therefore leaves that file empty+ with nothing behind it — during ``hermes import``, which is the+ disaster-recovery path a user reaches for *because* they already lost+ something. Staging into the target's own directory and publishing with a+ rename means the target only ever moves from its old contents to the+ complete new contents.++ ``atomic_replace`` rather than a bare ``os.replace``: it resolves a+ symlinked target first, so a deployment that links ``config.yaml`` into a+ dotfiles repo keeps the link instead of having it silently swapped for a+ regular file (GitHub #16743), and it falls back to copy/fsync/unlink on+ ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs. That+ fallback uses ``shutil.copyfile``, which does truncate in place, so on the+ cross-device path the guarantee above degrades to today's behaviour rather+ than improving on it; closing that belongs in ``utils.atomic_replace``,+ where every atomic writer in the repo would benefit, not here.++ Permission bits *and* ownership are carried across the replace so routing+ through mkstemp does not change the file the caller would otherwise have+ produced. ``os.replace`` swaps in a temp file owned by the *writing* user,+ so without the chown a ``sudo hermes import`` would silently re-own every+ restored file to root — on the disaster-recovery path, and on exactly the+ Docker/NAS installs ``utils._restore_file_owner`` documents. Both concerns+ delegate to the shared ``utils`` helpers rather than being re-derived here.+ The temp file is removed on any failure so a partial import leaves no+ residue.++ The one bit of the old file *not* carried across is setuid/setgid. The+ replacement bytes come out of the zip, so preserving those would let an+ archive take over the identity an existing privileged file executes as —+ and unlike the other ``utils`` writers, which re-serialize content this+ process produced, the trust boundary here is an untrusted archive. The+ mask is applied once, before the temp file is chmod'd, so neither the+ pre-replace ``fchmod`` nor the post-replace restore can re-elevate the+ target.+ """+ # ``_preserve_file_mode`` returns None when the target does not exist (or+ # cannot be stat'd), in which case the umask-derived create-mode applies —+ # the same shape as ``atomic_yaml_write``'s ``create_mode`` fallback.+ mode = _preserve_file_mode(target)+ owner = _preserve_file_owner(target)+ if mode is None:+ mode = new_file_mode+ else:+ # Deliberately NOT a faithful mode copy: setuid/setgid are dropped.+ # ``_preserve_file_mode`` returns ``stat.S_IMODE``, i.e. all twelve+ # bits, and the content replacing this file comes from the archive.+ # Carrying the elevated bits across would let archive-controlled bytes+ # take over an existing setuid/setgid file, so ``hermes import`` would+ # hand whoever produced the zip the identity that file runs as. Nothing+ # constrains that to Hermes' own state either: the ``_external/`` branch+ # of ``run_import`` publishes members anywhere under ``$HOME``. The+ # sticky bit is kept — it is inert on a regular file.+ mode &= ~(stat.S_ISUID | stat.S_ISGID)++ # Truncate the stem: mkstemp adds ~16 characters, and a member already near+ # NAME_MAX would otherwise fail here on a write that used to succeed.+ fd, tmp_name = tempfile.mkstemp(+ dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial"+ )+ try:+ with os.fdopen(fd, "wb") as dst:+ if mode is not None:+ # Apply the mode to the temp file BEFORE the replace so the+ # target never transits through mkstemp's 0600, and so+ # ``atomic_replace``'s EXDEV/EBUSY ``shutil.copystat`` fallback+ # copies the intended bits rather than 0600. fchmod is+ # Unix-only; Windows takes the path-based chmod.+ if hasattr(os, "fchmod"):+ os.fchmod(dst.fileno(), mode)+ else:+ os.chmod(tmp_name, mode)+ # Stream instead of ``src.read()``: a multi-gigabyte state.db member+ # must not be held in memory in one piece.+ with zf.open(member) as src:+ shutil.copyfileobj(src, dst)+ dst.flush()+ os.fsync(dst.fileno())+ real_path = Path(atomic_replace(tmp_name, target))+ # Owner first, mode second — the ordering ``atomic_yaml_write`` uses,+ # because chown drops setuid/setgid and a mode restore that ran first+ # would be partly undone. Here ``mode`` no longer carries those bits,+ # so the two agree: neither step can re-elevate the restored file.+ _restore_file_owner(real_path, owner)+ _restore_file_mode(real_path, mode)+ except BaseException:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ raise+++def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:+ """Return ``(sessions, messages)`` stored in the session database *path*.++ Read-only and best effort. ``None`` means "unknown" — a missing file, a+ database that is not a Hermes session store, or one that cannot be read.+ Callers must never read ``None`` as "zero rows": acting on an unreadable+ database would mask the very loss this count exists to surface. Same+ contract as :func:`_count_cron_jobs`.+ """+ if not path.is_file():+ return None+ try:+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)+ except sqlite3.Error:+ return None+ try:+ sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]+ messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]+ return int(sessions), int(messages)+ except (sqlite3.Error, TypeError, ValueError):+ return None+ finally:+ conn.close()+++def _import_db_member(+ zf: zipfile.ZipFile,+ member: str,+ target: Path,+ new_file_mode: Optional[int] = None,+) -> None:+ """Publish a SQLite ``.db`` member onto *target* without replacing its inode.++ ``_extract_member_atomically`` publishes with a rename. For an ordinary+ file that is the safest write available; for a live SQLite database it is+ the #65942 / #90950 corruption class. A gateway, dashboard, or WebUI+ process holding the database open keeps its descriptor on the now-unlinked+ inode: it goes on serving pre-import pages and writing sessions that no+ other process will ever see, and any sidecar WAL left beside the new file+ describes the database that was just unlinked. Nothing fails, so nothing+ is reported — the sessions simply are not there afterwards (issue #100960).++ ``hermes import`` is the disaster-recovery path, so that failure mode lands+ on users who have already lost something once. Route the member through+ the same ``_safe_restore_db`` page copy that ``/snapshot restore`` has used+ since #65942: the live inode is preserved, every open connection converges+ on the imported data, and the sidecars are handled there. A target that+ does not exist yet has no holders and no inode worth preserving, so it+ takes the ordinary atomic publish.++ Raises ``OSError`` when the database could not be replaced safely, so the+ caller reports a skipped file instead of counting a silent success.+ """+ if not target.exists():+ _extract_member_atomically(zf, member, target, new_file_mode)+ return++ # The database keeps its own mode/ownership: the bytes come from the+ # archive but the file does not, so the archive has no say in either.+ mode = _preserve_file_mode(target)+ owner = _preserve_file_owner(target)++ fd, tmp_name = tempfile.mkstemp(+ dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport"+ )+ try:+ with os.fdopen(fd, "wb") as dst:+ # Stream: a multi-gigabyte state.db member must not be held in+ # memory in one piece.+ with zf.open(member) as src:+ shutil.copyfileobj(src, dst)+ dst.flush()+ os.fsync(dst.fileno())+ if not _safe_restore_db(Path(tmp_name), target):+ raise OSError(+ "live-safe restore refused or failed; the existing database was "+ "left untouched. Stop the gateway/dashboard processes holding it "+ "open and re-run the import."+ )+ _restore_file_owner(target, owner)+ _restore_file_mode(target, mode)+ finally:+ try:+ os.unlink(tmp_name)+ except OSError:+ passdiff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex fe79038d9be..5d6d456e144 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -403,11 +403,8 @@ def get_git_banner_state(repo_dir: Optional[Path] = None) -> Optional[dict]:def _baked_banner_state() -> Optional[dict]:- """Banner state from the baked build SHA (Docker image path), or None."""- def _baked():- from hermes_cli.build_info import get_build_sha- return get_build_sha(short=8)- baked = _quiet(_baked)+ """Banner state from the build-time install stamp (packaged builds), or None."""+ baked = _quiet(_stamped_sha8)return {"upstream": baked, "local": baked, "ahead": 0} if baked else Nonediff --git a/hermes_cli/boot_bootstrap.py b/hermes_cli/boot_bootstrap.pyindex e79f1fe27e5..5a7a1647708 100644--- a/hermes_cli/boot_bootstrap.py+++ b/hermes_cli/boot_bootstrap.py@@ -33,7 +33,7 @@ branch's vocabulary: stamps via ``hermes_cli.steward``, managed tools via"""from __future__ import annotations-import hashlib+from hermes_cli.runtime_paths import install_state_dir, installs_rootimport jsonimport loggingimport os@@ -143,36 +143,6 @@ def current_install_identity(project_root: Path) -> str | None:# the per-install state folder: installs/<SHA16>/ under the DEFAULT home# ----------------------------------------------------------------------------def _install_key(project_root: Path) -> str:- try:- canonical = str(Path(project_root).resolve())- except OSError:- canonical = str(project_root)- return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]---INSTALLS_DIR_NAME = "installs"---def installs_root() -> Path:- """The parent of every per-install state folder.-- Anchored to the DEFAULT home, not the active profile home: profiles- share one folder per install, with per-profile bootstrap records as- files INSIDE it (bootstrap/<profile>.json) rather than per-profile- folders. That keeps profile semantics while collapsing the anchor- count to one.- """- from hermes_cli.profiles import _get_default_hermes_home-- return _get_default_hermes_home() / INSTALLS_DIR_NAME---def install_state_dir(project_root: Path) -> Path:- """``installs/<SHA16>/`` for this install. Derivation only — no I/O."""- return installs_root() / _install_key(project_root)--def ensure_install_dir(project_root: Path) -> Path:"""The state folder, created with its identity record on first touch.@@ -482,9 +452,9 @@ def run_boot_bootstrap(project_root: Path) -> dict:if drift_message:summary["sealed_runtime_drift"] = drift_message- for scope, steps, deferred in (- ("home", post_update.HOME_STEPS, False),- ("machine", post_update.MACHINE_STEPS, True),+ for scope, steps in (+ ("home", post_update.BOOT_HOME_STEPS),+ ("machine", post_update.BOOT_MACHINE_STEPS),):identity = needs_bootstrap(project_root, scope)if not identity:@@ -504,26 +474,9 @@ def run_boot_bootstrap(project_root: Path) -> dict:"post-update bootstrap (%s scope): code changed to %s, running steps",scope, identity[:12],)- if deferred:- # Slow machine steps (network installers) must not block- # boot readiness: record first, then run detached. A crash- # mid-step leaves the record written — intended: the record- # gates "did we trigger for this identity", and the steps- # re-gate themselves (pm.check stamp comparisons) next change.- _write_record(record, identity, {"deferred": True})- import threading-- threading.Thread(- target=post_update.run_steps,- args=(steps,),- name=f"hermes-bootstrap-{scope}",- daemon=True,- ).start()- summary[scope] = "deferred"- else:- results = post_update.run_steps(steps)- _write_record(record, identity, results)- summary[scope] = results+ results = post_update.run_steps(steps)+ _write_record(record, identity, results)+ summary[scope] = resultsfinally:lock.release()return summarydiff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 4601bde0d64..1fdf2bf0660 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -1027,7 +1027,7 @@ class CLICommandsMixin:def _handle_image_command(self, cmd_original: str):"""Handle /image <path> — attach a local image file for the next prompt."""- from cli import _IMAGE_EXTENSIONS, _resolve_attachment_path, _split_path_input+ from cli import _DIM, _IMAGE_EXTENSIONS, _RST, _cprint, _resolve_attachment_path, _split_path_inputraw_args = (cmd_original.split(None, 1)[1].strip() if " " in cmd_original else "")if not raw_args:hint = "/path/to/image.png"diff --git a/hermes_cli/cli_voice_mixin.py b/hermes_cli/cli_voice_mixin.pyindex 8f2b0ebfb9a..9b02fe6685c 100644--- a/hermes_cli/cli_voice_mixin.py+++ b/hermes_cli/cli_voice_mixin.py@@ -224,7 +224,8 @@ class CLIVoiceMixin:f"(first use may download it from Hugging Face)...{_RST}")else:_cprint(f"{_DIM}Transcribing...{_RST}")- from tools.voice_mode import is_voice_stop_phrase, transcribe_recording+ from tools.voice_mode_transcript import is_voice_stop_phrase+ from tools.voice_mode import transcribe_recordingresult = transcribe_recording(wav_path, model=stt_model)if result.get("success") and result.get("transcript", "").strip():transcript = result["transcript"].strip()@@ -446,7 +447,7 @@ class CLIVoiceMixin:result = transcribe_recording(wav_path, model=self._voice_stt_model())transcript = (result.get("transcript") or "").strip() if result.get("success") else ""if transcript:- from tools.voice_mode import is_voice_stop_phrase+ from tools.voice_mode_transcript import is_voice_stop_phraseif is_voice_stop_phrase(transcript):_cprint(f"\n{_DIM}Stop phrase detected — ending voice chat.{_RST}")self._disable_voice_mode()@@ -554,7 +555,7 @@ class CLIVoiceMixin:if not voice_on:return Falsetry:- from tools.voice_mode import is_voice_stop_phrase+ from tools.voice_mode_transcript import is_voice_stop_phraseif not is_voice_stop_phrase(user_input):return Falseexcept Exception:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 9da886901a8..4d1c5cd5d17 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1551,6 +1551,13 @@ DEFAULT_CONFIG = {# 2026-09-14 removal date (see COMPAT_MANIFEST.md, `hermes plugins compat`). Stopgap only: the# old paths raise ImportError once the compat layer is actually removed."allow_deprecated_imports": False,+ # Read-only plugin update-check cadence, hours (gateway tick; 0 disables). Applying stays+ # explicit: `hermes plugins update <name>`, or auto_apply below (git-class plugins only,+ # scan-gated by that same pipeline).+ "auto_update_check_hours": 24,+ # Opt-in unattended apply for the cadence check. Git-row plugins ONLY; every apply runs the+ # same security scan / consent pipeline as the manual update command.+ "auto_apply": False,},# Shell-script hooks: event name (pre_tool_call, post_tool_call, pre_llm_call, subagent_stop,# ...) -> list of {matcher, command, timeout}. First run of a new command prompts for consent;@@ -1863,13 +1870,6 @@ DEFAULT_CONFIG = {# Named-profile allowlist for multiplex mode. None = serve all; [] = default only."multiplex_profile_allowlist": None,- # The MSIX HermesGateway Windows Service posture (windows MSIX- # installs only; see `hermes gateway service on|off|status`).- # False = the service exists but stays demand-start/stopped- # (config-only posture — settled 2026-09-03); True = automatic- # at logon, bots keep running without the desktop app.- "service": False,-# Seconds to let a SIGTERM-interrupted gateway agent unwind before adapter/database# teardown. Keep short so service-manager shutdowns don't exhaust their stop budget."signal_interrupt_grace_timeout": 1,diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex b15690a0d71..f149cdabf30 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -6,7 +6,6 @@ Check bodies live in the ``doctor_*`` siblings.import osimport sys-from pathlib import Pathfrom hermes_cli.config import get_env_path, get_hermes_home, get_project_rootfrom hermes_cli.env_loader import load_hermes_dotenv@@ -65,15 +64,6 @@ _PROVIDER_ENV_HINTS = ("TOKENHUB_API_KEY", "TOKENPLAN_API_KEY",)-def _python_install_cmd() -> str:- return "uv pip install"---def _system_package_install_cmd(pkg: str) -> str:- if sys.platform == "darwin":- return f"brew install {pkg}"- return f"sudo apt install {pkg}"-@doctor_check()def _check_auth_providers(should_fix: bool, f: Finding) -> None:"""Refresh-free OAuth status snapshot (doctor must never trigger a token refresh)."""@@ -193,162 +183,6 @@ def run_doctor(args):_print_summary(should_fix, total)-def _pm_tool_path(name: str) -> Path | None:- """Answer a tool's binary from the pm store (facts.json), not PATH.-- Doctor probes tools (git, rg, ffmpeg, ...) that pinned installs run- out of the store; nothing puts the store on an interactive shell's- PATH, so a PATH-only probe reports a healthy managed install as- "not found". This answers from facts.json + the store: the recorded- entry's binary when it exists on disk, None when unstaged or the- recorded binary is gone (deleted = report missing, never guess).- Contract tests: tests/hermes_cli/test_doctor_pm_store_probe.py.- """- try:- import json-- from pm.paths import store_root- except Exception:- return None- facts_path = store_root() / "facts.json"- if not facts_path.is_file():- return None- try:- facts = json.loads(facts_path.read_text(encoding="utf-8-sig"))- except (OSError, ValueError):- return None- if not isinstance(facts, dict):- return None- entry_name = (facts.get("packages") or {}).get(name) or {}- if not isinstance(entry_name, dict):- return None- entry_dir = entry_name.get("entry")- if not isinstance(entry_dir, str) or not entry_dir:- return None- entry = store_root() / entry_dir- if not entry.is_dir():- return None # recorded but deleted- # resolve the binary: the store entry's package definition knows the- # relative binary path; without importing packages, probe common shapes- binary_names = {- "ripgrep": ("rg.exe", "rg"),- "git": ("cmd/git.exe", "bin/git"),- "node": ("node.exe", "bin/node"),- "gh": ("bin/gh.exe", "bin/gh"),- }.get(name, (f"{name}.exe", name))- for rel in binary_names:- candidate = entry / rel- if candidate.is_file():- return candidate- return None---def _has_provider_env_config(content: str) -> bool:- """Return True when ~/.hermes/.env contains provider auth/base URL settings."""- return any(key in content for key in _PROVIDER_ENV_HINTS)---def _honcho_is_configured_for_doctor() -> bool:- """Return True when Honcho is configured, even if this process has no active session."""- try:- from plugins.memory.honcho.client import HonchoClientConfig-- cfg = HonchoClientConfig.from_global_config()- return bool(cfg.enabled and (cfg.api_key or cfg.base_url))- except Exception:- return False---def _is_kanban_worker_env_gate(item: dict) -> bool:- """Return True when Kanban is unavailable only because this is not a worker process."""- if item.get("name") != "kanban":- return False- if os.environ.get("HERMES_KANBAN_TASK"):- return False-- tools = item.get("tools") or []- return bool(tools) and all(str(tool).startswith("kanban_") for tool in tools)---def _doctor_tool_availability_detail(toolset: str) -> str:- """Optional explanatory suffix for toolsets whose doctor status needs context."""- if toolset == "kanban" and not os.environ.get("HERMES_KANBAN_TASK"):- return "(runtime-gated; loaded only for dispatcher-spawned workers)"- return ""---def _doctor_web_capability_rows() -> list[tuple[str, str, str]]:- """Return doctor rows for web search/extract provider readiness (#78412).-- Each row is ``(status, label, detail)`` where *status* is ``ok`` or ``warn``.- Uses the same active-provider resolvers as the tools, but reports readiness- from ``is_available()`` so an explicitly selected but unconfigured backend- does not look healthy.- """- rows: list[tuple[str, str, str]] = []- try:- from agent.web_search_registry import (- get_active_extract_provider,- get_active_search_provider,- )- from tools.web_tools import _ensure_web_plugins_loaded, _provider_is_ready-- # Doctor runs in a fresh process — bundled web providers register- # during plugin discovery, which nothing has triggered yet here.- # Without this the registry is empty and every row reads- # "no provider selected or registered" (idempotent, cheap on rerun).- _ensure_web_plugins_loaded()- except Exception:- return rows-- for capability, getter in (- ("web search", get_active_search_provider),- ("web extract", get_active_extract_provider),- ):- try:- provider = getter()- except Exception:- provider = None- if provider is None:- rows.append(- (- "warn",- capability,- "(no provider selected or registered)",- )- )- continue- name = getattr(provider, "name", None) or type(provider).__name__- if _provider_is_ready(provider):- rows.append(("ok", capability, f"({name})"))- else:- rows.append(- (- "warn",- capability,- f"({name} selected; provider not configured)",- )- )- return rows--def _apply_doctor_tool_availability_overrides(available: list[str], unavailable: list[dict]) -> tuple[list[str], list[dict]]:- """Adjust runtime-gated tool availability for doctor diagnostics."""- updated_available = list(available)- updated_unavailable = []- for item in unavailable:- name = item.get("name")- if _is_kanban_worker_env_gate(item):- if "kanban" not in updated_available:- updated_available.append("kanban")- continue- if name == "honcho" and _honcho_is_configured_for_doctor():- if "honcho" not in updated_available:- updated_available.append("honcho")- continue- updated_unavailable.append(item)- return updated_available, updated_unavailable--# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----# Names external plugins imported from this module before the Sep 2026 decomposition.# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).@@ -368,14 +202,6 @@ def check_warn(text: str, detail: str = ""):print(f" {color('⚠', Colors.YELLOW)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))-# MERGE-CHECK: HEAD side of this conflict was our legacy monolithic run_doctor body (pre-#102117-# structure + pm-era fixes: inline connectivity probes, memory-provider/profiles checks, state-db-# stats, s6/TCC checks, _pm_venv_active). Upstream decomposed doctor.py into DOCTOR_CHECKS + the-# hermes_cli/doctor_* siblings, so per the merge brief the upstream structure wins and the legacy-# body is dropped. pm-era helpers kept alive above (_pm_tool_path, _doctor_web_capability_rows,-# _apply_doctor_tool_availability_overrides, _is_kanban_worker_env_gate, _honcho_is_configured_for_doctor,-# _has_provider_env_config, _python_install_cmd, _system_package_install_cmd) for the parent to wire-# into the doctor_* siblings. Parent: verify pm wiring / utf-8-sig reads landed in the siblings._PLUGIN_COMPAT_LAZY = {'FTS_STORAGE_VERSION': ('hermes_state_common', 'FTS_STORAGE_VERSION'),'OPENROUTER_MODELS_URL': ('hermes_constants', 'OPENROUTER_MODELS_URL'),diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex e218a81fde5..a6c708d1a13 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -391,6 +391,37 @@ _CONFIG_DRIFT_STEPS = ()+def _check_channel_record_hygiene() -> None:+ """Stale per-install channel records (``update.installs.<sha16>``).++ Same report-don't-delete posture as the state sweep. Three shapes+ (hermes_cli.update_channel.stale_channel_records): a record whose path+ holds a DIFFERENT install now (``replaced``), a record whose path is+ gone (``missing``), and a record no live install-state folder claims+ (``unclaimed``). Keep-on-doubt: doctor names the config key, the user+ removes it.+ """+ try:+ from hermes_cli.config import load_config+ from hermes_cli.update_channel import stale_channel_records++ stale = stale_channel_records(load_config() or {})+ except Exception as exc:+ check_warn("Channel-record hygiene unreadable", f"({exc})")+ return+ if not stale:+ return+ for sha16, record, reason in stale:+ recorded = record.get("path") or "<no path>"+ if reason == "replaced":+ detail = f"(the install at {recorded} is a different install now — stale channel entry)"+ elif reason == "missing":+ detail = f"(nothing at {recorded} — safe to remove update.installs.{sha16})"+ else: # unclaimed+ detail = f"(no live install claims {sha16} — safe to remove update.installs.{sha16})"+ check_warn(f"Stale channel record: {sha16}", detail)++@doctor_check()def _check_config_drift(should_fix: bool, f: Finding) -> None:"""Config version, stale root keys, HERMES_MAX_ITERATIONS ghost, deprecations, structure.@@ -404,6 +435,9 @@ def _check_config_drift(should_fix: bool, f: Finding) -> None:for step in _CONFIG_DRIFT_STEPS if config_path else (_drift_deprecations,):with warn_on_error(""):step(f, should_fix, config_path)+ # Stale per-install update-channel records (update.installs.<sha16>):+ # report-don't-delete, same posture as the state sweep.+ _check_channel_record_hygiene()@doctor_check("xAI retirement check skipped", "({e})")diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex d12fe8f6fd5..1402934f415 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport osimport shutil+import sslimport subprocessimport sysfrom pathlib import Path@@ -176,51 +177,33 @@ def _check_s6_supervision(issues: list[str]) -> None:def check_certificates(should_fix: bool = False, issues: "list | None" = None) -> None:- """Verify the certifi CA bundle is loadable before the first HTTPS call tracebacks.+ """Verify the actual TLS policy is usable before the first HTTPS call tracebacks.- ``--fix`` repairs a broken bundle (e.g. a brew Python upgrade rebuilt the venv) by force-reinstalling- certifi into THIS interpreter's environment and re-verifying.+ The policy is ``agent.ssl_verify``: the platform verifier (truststore) is+ installed process-wide and every stack builds SSL contexts through it. There+ is no certifi bundle to validate anymore; the check is that the platform+ store is in force and a default context constructs."""try:- from agent.ssl_guard import verify_ca_bundle- from agent.errors import SSLConfigurationError+ from agent.ssl_verify import install_truststoreexcept Exception as e:- return check_warn("SSL certificate check skipped", str(e))+ return check_warn("TLS trust check skipped", str(e))if issues is None:issues = []+ platform_store = install_truststore()+ if not platform_store:+ check_warn("TLS platform trust store unavailable",+ "OpenSSL default trust paths are in use; certificates trusted only by the OS store (a corporate root) will not verify")try:- verify_ca_bundle()- return check_ok("SSL CA certificate bundle is valid")- except SSLConfigurationError as e:- first_error = str(e)+ ssl.create_default_context()except Exception as e:- return check_warn("SSL certificate check skipped", str(e))- check_fail("SSL CA certificate bundle is broken", first_error)- pip_cmd = f"{sys.executable} -m pip install --force-reinstall certifi"- if not should_fix:- issues.append(f"Repair the CA bundle: run `hermes doctor --fix`, or `{pip_cmd}`")+ _fail_and_issue("TLS default SSL context cannot be constructed", str(e),+ "Recreate the venv or reinstall Hermes — the TLS stack is broken.", issues)return- print(" → Repairing: force-reinstalling certifi...")- try:- result = subprocess.run([sys.executable, "-m", "pip", "install", "--force-reinstall", "certifi"],- capture_output=True, text=True, timeout=300)- failure = ("certifi reinstall failed", (result.stderr or result.stdout or "")[-500:]) if result.returncode != 0 else None- except Exception as exc:- failure = ("certifi repair could not run pip", str(exc))- if failure:- return _fail_and_issue(*failure, f"Reinstall certifi manually: {pip_cmd}", issues)- # Drop cached certifi modules so where() resolves the fresh install without a restart.- import importlib- for mod_name in [m for m in sys.modules if m == "certifi" or m.startswith("certifi.")]:- sys.modules.pop(mod_name, None)- importlib.invalidate_caches()- try:- verify_ca_bundle()- check_ok("SSL CA certificate bundle repaired (certifi reinstalled)")- except SSLConfigurationError as e:- _fail_and_issue("SSL CA certificate bundle still broken after reinstall", str(e),- "certifi reinstall did not restore the CA bundle — check for a custom CA env var "- "(SSL_CERT_FILE/REQUESTS_CA_BUNDLE) pointing at a missing file, or recreate the venv.", issues)+ if platform_store:+ check_ok("TLS platform trust store configured; default SSL context available")+ else:+ check_ok("TLS default SSL context available (OpenSSL trust paths)")def _check_gateway_service_linger(issues: list[str]) -> None:@@ -367,6 +350,28 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:check_warn(f"{h.package}=={h.installed_version} still installed (advisory {h.advisory.id} acknowledged)")+def _staged_venv_dir() -> "Path | None":+ """pm's provisioned runtime venv, or None when nothing is staged.++ ``pm.packages.Venv().venv_dir()`` is pm's public authority for where+ the runtime venv lives (sealed installs: the mutable venv in the+ writable hermes root, seeded from the payload; dev installs: the repo+ venv). A resolved path without a venv marker is not a provisioned+ venv — pm also returns the intended location before first sync, and+ doctor must not read an empty directory as staged dependencies.+ """+ try:+ import pm # noqa: F401 — imports pm.packages, registering the definitions+ from pm.packages import Venv++ venv_dir = Venv().venv_dir()+ except Exception:+ return None+ if venv_dir is not None and (Path(venv_dir) / "pyvenv.cfg").is_file():+ return Path(venv_dir)+ return None++@doctor_check()def _check_python_environment(should_fix: bool, f: Finding) -> None:"""Interpreter, linked SQLite, venv, macOS TCC anchors/FDA/grants, version-file drift."""@@ -387,7 +392,21 @@ def _check_python_environment(should_fix: bool, f: Finding) -> None:if src:check_info(f"SQLite source id: {(src[:48] + '…') if len(src) > 48 else src}")_report_database_journal_modes()- check_bool(sys.prefix != sys.base_prefix, "Virtual environment active", ("Not in virtual environment", "(recommended)"))+ # Staged dependencies vs the running interpreter, reported as two+ # distinct facts. When pm has provisioned the runtime venv, its+ # resolved location IS the answer ("dependencies staged"); whether+ # THIS process runs inside THAT venv is a separate comparison of+ # resolved prefixes (sys.prefix != base_prefix alone would also be+ # true for an unrelated venv). Only when nothing is staged does the+ # legacy interpreter probe stand alone.+ staged = _staged_venv_dir()+ if staged is not None:+ running_here = Path(sys.prefix).resolve() == staged.resolve()+ check_ok(f"Runtime venv staged ({staged})",+ "(active in this process)" if running_here else "(this process runs outside it)")+ else:+ check_bool(sys.prefix != sys.base_prefix, "Virtual environment active",+ ("Not in virtual environment", "(recommended)"))# macOS TCC interpreter anchor (#95596): dylib-complete re-land of the mechanism reverted in #95563.# Silent on non-macOS.check_macos_tcc_anchor(should_fix=should_fix)diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.pyindex 099936ec239..ada357abdc0 100644--- a/hermes_cli/doctor_state.py+++ b/hermes_cli/doctor_state.py@@ -101,9 +101,84 @@ def _memory_store_flags(hermes_home: Path) -> tuple:return get_builtin_memory_store_flags({"memory": _doctor_memory_config(hermes_home)})+def check_legacy_desktop_checkout() -> None:+ """Report the unused legacy checkout under an embedded desktop install.++ Before the embedded runtime existed, the desktop app installed a git+ checkout at $HERMES_HOME/hermes-agent. An embedded app never uses it,+ so it sits on disk (1-2 GB of tree + venv). Doctor only REPORTS the+ checkout and its size — it never suggests a deletion command, and+ never deletes anything itself: a pristineness probe cannot prove no+ other client uses the tree or that every local commit is published,+ so the review-and-decide step belongs to the user.+ """+ from hermes_cli.steward import STEWARD_DESKTOP, sealed_steward++ try:+ from hermes_cli.main import PROJECT_ROOT+ except Exception:+ return++ if sealed_steward(Path(PROJECT_ROOT)) != STEWARD_DESKTOP:+ return++ from hermes_cli.doctor import HERMES_HOME, _DHH++ checkout = HERMES_HOME / "hermes-agent"+ if not (checkout / ".git").exists():+ return++ _section("Legacy Desktop Checkout")++ def _git(*args: str):+ try:+ return subprocess.run(+ ["git", "-C", str(checkout), *args],+ capture_output=True, text=True, encoding="utf-8", timeout=10,+ )+ except (OSError, subprocess.SubprocessError):+ return None++ status = _git("status", "--porcelain")+ branch = _git("rev-parse", "--abbrev-ref", "HEAD")+ stashes = _git("stash", "list")++ # Conservative pristineness: every probe must succeed AND come back+ # clean. Any probe failure counts as "has local work".+ pristine = (+ status is not None and status.returncode == 0 and status.stdout.strip() == ""+ and branch is not None and branch.returncode == 0 and branch.stdout.strip() == "main"+ and stashes is not None and stashes.returncode == 0 and stashes.stdout.strip() == ""+ )++ size_note = ""+ try:+ total = sum(f.stat().st_size for f in checkout.rglob("*") if f.is_file())+ size_note = f" (~{total / 1_000_000_000:.1f} GB)"+ except OSError:+ pass++ if pristine:+ check_warn(+ f"Unused checkout at {_DHH}/hermes-agent{size_note}",+ "(the desktop app runs embedded and does not use it; the tree is clean)",+ )+ print(" Review it and decide whether to keep or remove it — doctor does not delete anything.")+ else:+ check_info(+ f"A checkout exists at {_DHH}/hermes-agent but holds local work "+ "(changes, a branch, or stashes). The desktop app does not use "+ "it; review it before you remove anything."+ )++@doctor_check()def _check_directory_structure(should_fix: bool, f: Finding) -> None:"""HERMES_HOME, expected subdirs, SOUL.md, and the enabled built-in memory files."""+ try:+ check_legacy_desktop_checkout()+ except Exception:+ pass # best-effort report; must never break the directory checkfrom hermes_cli.doctor import HERMES_HOME, _DHHhermes_home = HERMES_HOMEensure_dir(f, should_fix, hermes_home, f"{_DHH} directory exists", f"Created {_DHH} directory", f"{_DHH} not found")@@ -259,11 +334,21 @@ def _check_state_db(should_fix: bool, f: Finding) -> None:def _gh_authenticated() -> bool:- """Check if gh CLI is authenticated via token file or device flow."""+ """Check if gh CLI is authenticated via token file or device flow.++ Availability is resolved through shutil.which (the same probe every+ other doctor tool check uses); the spawn itself treats any OS-level+ launch failure (a Store/MSIX shim, a deleted binary) as "not+ authenticated" rather than crashing the Skills Hub check.+ """+ from hermes_cli.doctor_tools import _safe_which++ if not _safe_which("gh"):+ return Falsetry:result = subprocess.run(["gh", "auth", "status", "--json", "authenticated"], capture_output=True, timeout=10)return result.returncode == 0- except (FileNotFoundError, subprocess.TimeoutExpired):+ except (OSError, subprocess.TimeoutExpired):return Falsediff --git a/hermes_cli/doctor_tools.py b/hermes_cli/doctor_tools.pyindex 8c66fb9a7b7..e973232f96b 100644--- a/hermes_cli/doctor_tools.py+++ b/hermes_cli/doctor_tools.py@@ -8,6 +8,7 @@ import osimport shutilimport subprocessimport sys+from pathlib import Pathfrom hermes_cli.doctor_platform import _system_package_install_cmdfrom hermes_cli.doctor_report import Finding, _fail_and_issue, check_bool, check_info, check_ok, check_warn, doctor_checkfrom hermes_cli.vercel_auth import describe_vercel_auth@@ -22,6 +23,71 @@ def _safe_which(cmd: str) -> str | None:return None+def _pm_tool_path(name: str) -> Path | None:+ """Answer a tool's binary from the pm store (facts.json), not PATH.++ Doctor probes tools (git, rg, ...) that pinned installs run out of+ the store; nothing puts the store on an interactive shell's PATH, so+ a PATH-only probe reports a healthy managed install as "not found".+ This answers from pm's registry/store/package authority: the recorded+ entry's binary when it exists on disk, None when unstaged or the+ recorded binary is gone (deleted = report missing, never guess).+ Contract tests: tests/hermes_cli/test_doctor_pm_store_probe.py.+ """+ try:+ import pm # noqa: F401 — imports pm.packages, registering the definitions+ from pm import paths, registry, store+ from pm.lock import Facts++ fact = Facts(paths.facts_path()).get(name) or {}+ entry_name = fact.get("entry")+ if not entry_name:+ return None+ package = registry.get_package(name)+ binary = package.binary(store.Store(paths.store_root()).entry(entry_name), store.current_target())+ except Exception:+ return None+ if binary is None or not binary.is_file():+ return None+ return binary+++def _pm_package_for_command(command: str) -> str | None:+ """The pm package that provisions *command*, derived from pm's own+ package definitions (binary_rel → executable basename) — no restated+ name table, so new pm packages are covered without doctor changes."""+ try:+ import pm # noqa: F401 — imports pm.packages, registering the definitions+ from pm import registry, store+ from pm.packages import BinaryPackage++ target = store.current_target()+ for package_name in registry.all_packages():+ package = registry.get_package(package_name)+ if isinstance(package, BinaryPackage):+ rel = package._rel(target)+ if rel and Path(rel).name.removesuffix(".exe").removesuffix(".cmd") == command:+ return package_name+ except Exception:+ return None+ return None+++def _doctor_tool(name: str) -> tuple[str | None, str]:+ """Resolve the tool Hermes would actually run: the pm store first+ (pinned installs run tools out of the store, which nothing puts on+ PATH), then PATH. *name* is the command ("rg"); its pm package+ ("ripgrep") is resolved from pm's own definitions. Returns+ ``(path, ok-row detail)``."""+ for package_name in (name, _pm_package_for_command(name)):+ if not package_name:+ continue+ staged = _pm_tool_path(package_name)+ if staged:+ return str(staged), "(pm store)"+ return _safe_which(name), ""++def _run_ok(cmd: list[str], timeout: int, **kw) -> bool:"""True when *cmd* exits 0 within *timeout*; a timeout counts as failure."""try:@@ -124,8 +190,10 @@ def _missing_api_key_toolsets_for_summary(unavailable: list[dict]) -> list[dict]@doctor_check()def _check_git_and_rg(should_fix: bool, f: Finding) -> None:- check_bool(_safe_which("git"), "git", ("git not found", "(optional)"))- if not check_bool(_safe_which("rg"), ("ripgrep (rg)", "(faster file search)"),+ git, git_detail = _doctor_tool("git")+ rg, rg_detail = _doctor_tool("rg")+ check_bool(git, ("git", git_detail), ("git not found", "(optional)"))+ if not check_bool(rg, ("ripgrep (rg)", f"{rg_detail} (faster file search)".strip()),("ripgrep (rg) not found", "(file search uses grep fallback)")):check_info(f"Install for faster search: {_system_package_install_cmd('ripgrep')}")diff --git a/hermes_cli/dump.py b/hermes_cli/dump.pyindex 48977486680..4c1e4584660 100644--- a/hermes_cli/dump.py+++ b/hermes_cli/dump.py@@ -51,21 +51,45 @@ def _git_output(project_root: Path, *args: str) -> str:def _get_git_commit(project_root: Path) -> str:- """Short git commit hash, or '(unknown)'. Docker images exclude ``.git``, so fall back to the build SHA- the Dockerfile bakes into ``<project_root>/.hermes_build_sha``."""+ """Short git commit hash, or '(unknown)'.++ The requested *project_root* is authoritative: when it has no git,+ the install-stamp fallback is only valid for the RUNNING install+ (``hermes_cli.version_info`` has no per-root API — it reads+ HERMES_INSTALL_ROOT / the running code root, never an arbitrary+ directory). For any other root the provenance is unknown.+ """value = _git_output(project_root, "rev-parse", "--short=8", "HEAD")if value:return value+ if project_root.resolve() != get_project_root():+ return "(unknown)"try:- from hermes_cli.build_info import get_build_sha # deferred: keeps dump cheap on non-dump paths- return get_build_sha(short=8) or "(unknown)"+ from hermes_cli.version_info import get_code_identity # deferred: keeps dump cheap on non-dump paths+ return get_code_identity().get("short_sha") or "(unknown)"except Exception:return "(unknown)"def _get_git_commit_date(project_root: Path) -> str:- """Return the date the HEAD commit was authored (YYYY-MM-DD), or '' (Docker images have no .git)."""- return _git_output(project_root, "log", "-1", "--format=%cd", "--date=short", "HEAD")+ """Return the date the HEAD commit was authored (YYYY-MM-DD), or ''.++ Same authority rule as :func:`_get_git_commit`: the stamp fallback+ describes the running install only.+ """+ value = _git_output(project_root, "log", "-1", "--format=%cd", "--date=short", "HEAD")+ if value:+ return value+ if project_root.resolve() != get_project_root():+ return ""+ try:+ from datetime import datetime, timezone++ from hermes_cli.version_info import get_version_info # deferred: keeps dump cheap on non-dump paths+ commit_date = get_version_info().commit_date+ return datetime.fromtimestamp(commit_date, tz=timezone.utc).strftime("%Y-%m-%d") if commit_date else ""+ except Exception:+ return ""def _redact(value: str) -> str:diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex cafe87c5d70..30fa2e16fb3 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -2569,8 +2569,8 @@ def get_python_path() -> str:from hermes_constants import venv_python_pathexcept ImportError:# Update-boundary: a gateway restarted mid-update can hold a stale hermes_constants- # without this symbol; see _reload_hermes_constants() in hermes_cli/managed_uv.py.- from hermes_cli.managed_uv import _reload_hermes_constants+ # without this symbol; reload through the runtime repair owner.+ from hermes_cli.runtime_repair import _reload_hermes_constantsvenv_python_path = _reload_hermes_constants().venv_python_pathvenv_python = venv_python_path(venv, windows=is_windows())@@ -6153,17 +6153,10 @@ def _cmd_migrate_legacy(args):remove_legacy_hermes_units(interactive=not yes, dry_run=dry_run)-def _cmd_service(args):- """Windows SCM frontend (MSIX HermesGateway service): translate the SCM- protocol onto the payload launcher (sealed-install surface)."""- _windows_scm_service_command(getattr(args, "gateway_service_action", None))--_GATEWAY_SUBCOMMANDS = {None: _cmd_run, "run": _cmd_run, "setup": _cmd_setup, "install": _cmd_install,"uninstall": _cmd_uninstall, "start": _cmd_start, "stop": _cmd_stop, "restart": _cmd_restart,"status": _cmd_status, "list": _cmd_list, "migrate-legacy": _cmd_migrate_legacy,- "service": _cmd_service,}@@ -6208,38 +6201,6 @@ def __getattr__(name): # PEP 562 — lazy so no import cycles# ---- END PLUGIN-COMPAT -----def _try_scm_service_restart() -> bool:- """Restart the HermesGateway Windows Service when it's the running- gateway's manager: sealed MSIX install + service present + running.-- Returns True when the SCM restart was issued (the caller must NOT arm- a detached watcher); False on any other machine shape (source- installs, service absent or stopped — the normal paths apply).- """- if sys.platform != "win32":- return False- try:- import win32serviceutil- except ImportError:- return False- try:- from gateway.windows_service import SERVICE_NAME- from pm.ensure import sealed-- if not sealed():- return False- status = win32serviceutil.QueryServiceStatus(SERVICE_NAME)- running = bool(status and status[1] == 4) # SERVICE_RUNNING- if not running:- return False- win32serviceutil.RestartService(SERVICE_NAME)- print(f" ⏻ Restarting {SERVICE_NAME} service (graceful drain → respawn)")- return True- except Exception:- # Not service-managed (most installs): the ordinary restart paths- # own it. Never fail the update over a service lookup.- return False-def _pm_runtime_venv_dir() -> Path | None:"""The venv pm provisioned for this install, resolved from pm's ownrecords (facts.json + store layout) — never from interpreter state.@@ -6283,103 +6244,3 @@ def _systemd_watchdog_service_fields(return "simple", ""return "notify", f"NotifyAccess=main\nWatchdogSec={seconds}s\n"-def _windows_scm_service_command(action: str | None) -> None:- """`hermes gateway service on|off|status` — the MSIX HermesGateway- Windows Service (SCM-registered at MSIX install, demand-start;- plan: gateway-msix-windows-service, Task 5; config-only posture).-- "on" = automatic-at-logon + start now (persisted via gateway.service).- "off" = demand-start + stop now.- "status" = SCM state + the config key.- """- if sys.platform != "win32":- print_error("`hermes gateway service` manages the MSIX HermesGateway "- "Windows Service — not available on this platform.")- return- try:- import win32service- import win32serviceutil- except ImportError:- print_error("pywin32 is required for service management.")- return-- from gateway.windows_service import SERVICE_NAME-- def _config_get() -> bool:- try:- from hermes_cli.config import get_config_value-- return bool(get_config_value("gateway.service", False))- except Exception:- return False-- def _scm_status() -> tuple[bool, str]:- """(installed, state-name) — service absent = (False, 'not installed')."""- try:- status = win32serviceutil.QueryServiceStatus(SERVICE_NAME)- states = {- 1: "stopped",- 2: "start pending",- 3: "stop pending",- 4: "running",- 5: "continue pending",- 6: "pause pending",- 7: "paused",- }- return True, states.get(status[1], f"unknown ({status[1]})")- except Exception:- return False, "not installed"-- if action in (None, "status"):- installed, state = _scm_status()- enabled = _config_get()- print(f"HermesGateway service: {state}" if installed else- "HermesGateway service: not installed (MSIX bundles only)")- print(f" config gateway.service: {'on' if enabled else 'off'}")- if installed and state == "running" and not enabled:- print_warning("service is running but the config key is off — "- "run `hermes gateway service on` to persist")- return-- if action == "on":- installed, _ = _scm_status()- if not installed:- print_error("HermesGateway service is not installed — it ships "- "with the MSIX bundle (desktop app install).")- return- try:- # Automatic at logon + start now, gracefully.- win32serviceutil.ChangeServiceConfig(- SERVICE_NAME, starttype=win32service.SERVICE_AUTO_START- )- win32serviceutil.StartService(SERVICE_NAME)- from cli import save_config_value-- save_config_value("gateway.service", True)- print(f"✓ {SERVICE_NAME}: automatic at logon + starting now")- print(" Bots keep running without the desktop app.")- except Exception as exc:- print_error(f"Could not enable service: {exc}")- return-- if action == "off":- installed, _ = _scm_status()- if not installed:- print_error("HermesGateway service is not installed.")- return- try:- win32serviceutil.ChangeServiceConfig(- SERVICE_NAME, starttype=win32service.SERVICE_DEMAND_START- )- win32serviceutil.StopService(SERVICE_NAME) # graceful: frontend marker path- from cli import save_config_value-- save_config_value("gateway.service", False)- print(f"✓ {SERVICE_NAME}: demand-start + stopping (graceful drain)")- except Exception as exc:- print_error(f"Could not disable service: {exc}")- return-- print_error(f"Unknown service action: {action!r} (on|off|status)")--diff --git a/hermes_cli/gui_uninstall.py b/hermes_cli/gui_uninstall.pyindex 73342e1aee4..824e74f02b5 100644--- a/hermes_cli/gui_uninstall.py+++ b/hermes_cli/gui_uninstall.py@@ -88,7 +88,7 @@ def gui_install_summary(hermes_home: "Path | None" = None) -> dict:# removed; sealed trees (nix / desktop-app / docker) get data-only.from hermes_cli import steward as steward_mod- steward, code_removal_allowed = steward_mod.classify_install(_agent_root(home))+ steward, code_removal_allowed = steward_mod.classify_install(home / "hermes-agent")return {"hermes_home": str(home),diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex 46da5cc05fa..4cc1d82512e 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -151,7 +151,7 @@ def _boot_in_flight(config: dict | None) -> bool:for manifest in runtimes_root().glob("*/*/manifest.json"):try:- if _json.loads(manifest.read_text(encoding="utf-8-sig")).get("verified_version"):+ if manifest_verified(manifest):return Trueexcept (ValueError, OSError):continuediff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex a5c0f811d7d..338c0e19664 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2015,11 +2015,9 @@ def select_provider_and_model(args=None):# added here — internal import paths are not a stable API._FROZEN_UPDATER_SURFACE: dict[str, tuple[str, ...]] = {"hermes_cli.update_cmd": (- "_abort_dependency_sync_if_self_locked", "_assess_parked_branch_switch",+ "_assess_parked_branch_switch","_capture_active_lazy_features", "_capture_active_tool_dependencies",- "_cold_start_windows_gateway_after_update", "_defer_update_for_self_lock",- "_dependency_sync_would_rewrite", "_detect_self_loaded_native_modules",- "_detect_venv_python_processes", "_discard_stashed_changes",+ "_cold_start_windows_gateway_after_update", "_detect_venv_python_processes", "_discard_stashed_changes","_filter_non_gateway_concurrent_instances", "_fleet_probe_expected_runtimes","_get_origin_url", "_handoff_reapable_backend_pids", "_ledger_manual_serve_holders","_ledger_reapable_backend_pids", "_leftover_pausable_gateway_pids", "_npm_lockfile_changed",@@ -2029,10 +2027,10 @@ _FROZEN_UPDATER_SURFACE: dict[str, tuple[str, ...]] = {"_refresh_active_lazy_features", "_refresh_active_memory_provider_dependencies","_refresh_bootstrap_cache_scripts", "_refresh_windows_gateway_launchers","_relaunch_stopped_serves", "_reload_updated_runtime_modules",- "_restore_active_tool_dependencies", "_restore_stashed_changes",+ "_restore_stashed_changes","_resume_windows_gateways_after_update", "_run_logged_subprocess", "_run_pre_update_backup","_stash_local_changes_if_needed", "_stop_process_trees", "_sync_with_upstream_if_needed",- "_upgrade_pip_before_lazy_refresh", "_venv_launcher_ancestors",+ "_venv_launcher_ancestors","_wait_for_windows_update_gateway_exit", "_warn_orphaned_update_autostashes","_write_update_incomplete_marker",),@@ -2189,6 +2187,17 @@ def _update_preflight_handled(args) -> bool:managed_error("update Hermes Agent")return True+ # Informational flags never enter the updater: --install-id prints the+ # identifier and --set-channel atomically persists a valid channel+ # record; both exit here, before the update lock, git, network,+ # backups, or process pause. Implementation lives in the channel topic+ # module, not this file.+ if getattr(args, "install_id", False) or getattr(args, "set_channel", None):+ from hermes_cli.update_channel import handle_channel_flags++ handle_channel_flags(args)+ return True+# --plan is read-only and deployment-kind aware, so it runs BEFORE the# docker/nix/apt refusal gates: on an image/package-managed install the# plan itself reports "not updatable in place" plus the right mechanism.@@ -3358,6 +3367,10 @@ def main():except Exception:pass+ if _first_positional_argv() != "update":+ from hermes_cli.boot_bootstrap import default_project_root, maybe_run_boot_bootstrap+ maybe_run_boot_bootstrap(default_project_root())+if _try_termux_fast_tui_launch():returnif _try_termux_fast_cli_launch():diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex c23b6a27daa..8b85cfd167e 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -1247,7 +1247,8 @@ def _install_desktop_workspace_deps(npm: str, env: dict) -> None:# (e.g. electron-winstaller's select-7z-arch.js) resolve it even when the# desktop updater chain lost shell PATH customizations. Wrapping the NixOS# env keeps its PYTHON hint while restoring managed Node ahead of PATH.- nixos_env = with_hermes_node_path(_nixos_build_env())+ from pm import env_for+ nixos_env = env_for("npm", base_env=with_hermes_node_path(_nixos_build_env()))install_result = _run_npm_install_deterministic(npm, PROJECT_ROOT, capture_output=False, env=nixos_env)if install_result.returncode == 0:returndiff --git a/hermes_cli/main_install_repair.py b/hermes_cli/main_install_repair.pyindex 32b6349963a..92bf8cf2126 100644--- a/hermes_cli/main_install_repair.py+++ b/hermes_cli/main_install_repair.py@@ -262,10 +262,10 @@ def _recover_core_update_marker_locked() -> None:try:from hermes_cli import _install_repair as _ir- # ensure_uv bootstraps uv itself when missing (the early pass's stdlib-only lookup- # cannot), so a venv whose uv vanished mid-update still heals.- from hermes_cli.managed_uv import ensure_uv- ensure_uv()+ # The early stdlib-only pass cannot restore a missing uv; PM can.+ from pm.ensure import uv as pm_uv++ pm_uv(realize=True)# Shared stdlib executor: late path and pre-import early pass run exactly the same# reinstall. Its own stdout→stderr redirect nests harmlessly inside ours._ir.run_core_install(PROJECT_ROOT)@@ -414,8 +414,9 @@ def _default_venv_install_target() -> tuple[list[str], dict[str, str] | None]:"""Return ``(install_cmd_prefix, env)`` for the project venv when possible."""from hermes_cli.main import PROJECT_ROOTtry:- from hermes_cli.managed_uv import ensure_uv- uv_bin = ensure_uv()+ from pm.ensure import uv as pm_uv++ uv_bin, _ = pm_uv(realize=True)except Exception:uv_bin = Noneif uv_bin:diff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.pyindex e029777e1aa..299450d7e09 100644--- a/hermes_cli/memory_setup.py+++ b/hermes_cli/memory_setup.py@@ -21,34 +21,9 @@ _IMPORT_NAMES = {def _provider_extras(provider_name: str, manifest: dict, plugin_dir=None) -> list[str]:- """The pyproject extras a provider needs on THIS install.-- ``plugin.yaml``'s ``extra:`` names the baseline. Hindsight's- ``local_embedded`` mode needs the daemon+embedder wheel on top- (hindsight-local, #70636) — mode lives in its config file, which the- manifest can't express.-- A provider manifest with legacy ``pip_dependencies`` (no ``extra:``,- no pyproject of its own — the third-party plugin shape, e.g. a- directory-installed external provider) is bridged: pm materializes- the specs into a generated pyproject.toml, and the provider becomes- a workspace member installed by the venv sync. Returns [] either- way — no EXTRA to sync, the union carries the deps."""- extras = []+ """The declared core extra; manifest requirements join the staged union."""declared = manifest.get("extra")- if isinstance(declared, str) and declared:- extras.append(declared)- elif plugin_dir is not None and manifest.get("pip_dependencies"):- try:- from pm.workspace import materialize_legacy_pyproject-- materialize_legacy_pyproject(Path(plugin_dir))- except Exception:- pass- # hindsight local_embedded needs hindsight-all, whose protobuf floor- # conflicts with mem0/modal — it cannot be a venv extra. It stays a- # provider-owned install until plugin side-venvs land (plan step 5).- return extras+ return [declared] if isinstance(declared, str) and declared else []def _curses_select(diff --git a/hermes_cli/nous_subscription.py b/hermes_cli/nous_subscription.pyindex 5f37c580996..a1f4cec87ab 100644--- a/hermes_cli/nous_subscription.py+++ b/hermes_cli/nous_subscription.py@@ -193,11 +193,8 @@ def _has_agent_browser() -> bool:# the setup/status surfaces can't diverge from what browser tools actually# find at runtime; validate=False keeps this a cheap existence check with# no subprocess spawn.- # MERGE-CHECK: upstream moved the cascade to tools.browser_tool_install and added a- # Termux carve-out (_requires_real_termux_browser_install) — termux symbols are- # deliberately removed on this branch, so we keep our tools.browser_tool probe.try:- from tools.browser_tool import _find_agent_browser+ from tools.browser_tool_install import _find_agent_browserexcept Exception:# Runtime probe unavailable: fall back to binary presence rather than crashing. Rungs: PATH;# Hermes-managed Node dirs ($HERMES_HOME/node, prepended to PATH at runtime but usually absentdiff --git a/hermes_cli/plugin_compat.py b/hermes_cli/plugin_compat.pyindex 4cdf04500cd..b299fbb5b10 100644--- a/hermes_cli/plugin_compat.py+++ b/hermes_cli/plugin_compat.py@@ -158,7 +158,7 @@ def scan_plugin(plugin_dir: Optional[Path], manifest: Optional[Dict[str, Dict[stsrc = p.read_text(encoding="utf-8-sig", errors="replace")except OSError:continue- hits += scan_source(src, str(p.relative_to(plugin_dir)), manifest)+ hits += scan_source(src, p.relative_to(plugin_dir).as_posix(), manifest)return hitsdiff --git a/hermes_cli/plugins_admission.py b/hermes_cli/plugins_admission.pynew file mode 100644index 00000000000..93216bc5ac5--- /dev/null+++ b/hermes_cli/plugins_admission.py@@ -0,0 +1,124 @@+"""Validate a proposed plugin set, then publish config and runtime selection."""++from __future__ import annotations++import os+from pathlib import Path+from typing import Iterable, Optional+++class AdmissionRefused(RuntimeError):+ """The candidate set was refused; config and environment untouched."""+++def candidate_member_dirs(+ candidate_enabled: Iterable[str],+ candidate_disabled: Iterable[str] = (),+ *,+ active_plugins_dir: Optional[Path] = None,+ extra_dirs: Iterable[Path] = (),+) -> list[Path]:+ """Member dirs implied by the PROPOSED enabled sets: per plugins dir,+ its enabled names — the active dir's replaced by the candidate set+ (removals excluded), other homes unchanged — filtered to dirs that+ actually declare python deps. ``extra_dirs`` (the install target)+ join when they declare deps."""+ from pm.workspace import enabled_member_dirs, _is_member_candidate++ active = Path(active_plugins_dir) if active_plugins_dir else None+ members = enabled_member_dirs(+ proposed_home=active.parent if active else None,+ enabled=candidate_enabled, disabled=candidate_disabled,+ )+ for directory in extra_dirs:+ directory = Path(directory)+ if directory not in members and _is_member_candidate(directory):+ members.append(directory)+ return members+++def _config_path() -> Path:+ from hermes_cli.config import get_hermes_home++ return get_hermes_home() / "config.yaml"+++def _atomic_write_bytes(path: Path, data: bytes) -> None:+ import tempfile++ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".admission-")+ try:+ with os.fdopen(fd, "wb") as stream:+ stream.write(data)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ finally:+ Path(temporary).unlink(missing_ok=True)+++def _config_commit(candidate_enabled: set, candidate_disabled: set):+ """The before_publish hook: commit the config EXACTLY ONCE while pm+ holds the install lock. Returns an undo callable — invoked by+ sync_venv only when the subsequent facts write fails — that restores+ the previous config bytes atomically (or removes a config this+ commit created)."""+ path = _config_path()+ existed = path.is_file()+ previous = path.read_bytes() if existed else None++ commit_plugin_sets(candidate_enabled, candidate_disabled)++ def undo() -> None:+ if previous is None:+ path.unlink(missing_ok=True)+ else:+ _atomic_write_bytes(path, previous)++ return undo+++def commit_plugin_sets(enabled: set, disabled: set) -> None:+ """Write BOTH plugin keys in ONE atomic config save."""+ from hermes_cli.config import read_raw_config+ from utils import atomic_roundtrip_yaml_save++ path = _config_path()+ config = read_raw_config()+ plugins_cfg = config.setdefault("plugins", {})+ if not isinstance(plugins_cfg, dict):+ raise ValueError(f"plugins must be a mapping in {path}")+ plugins_cfg["enabled"] = sorted(enabled)+ plugins_cfg["disabled"] = sorted(disabled)+ atomic_roundtrip_yaml_save(path, config)+++def admit_plugin_set_change(+ candidate_enabled: set,+ candidate_disabled: set,+ *,+ active_plugins_dir: Optional[Path] = None,+ extra_dirs: Iterable[Path] = (),+) -> None:+ """Validate the proposed sets against the active environment and+ commit — env selection and config move together, inside pm's single+ locked transaction.++ Raises :class:`AdmissionRefused` BEFORE anything is published when+ the candidate union fails to resolve (conflict, frozen feature set,+ …) or when the config write itself fails. The active environment and+ the previous config bytes are kept EXACTLY — no rollback re-resolve.+ """+ from pm.ensure import sync_venv++ members = candidate_member_dirs(+ candidate_enabled, candidate_disabled, active_plugins_dir=active_plugins_dir, extra_dirs=extra_dirs+ )+ try:+ sync_venv(+ explicit=True,+ plugin_dirs=members,+ before_publish=lambda: _config_commit(candidate_enabled, candidate_disabled),+ )+ except Exception as exc:+ raise AdmissionRefused(str(exc)) from excdiff --git a/hermes_cli/plugins_cadence.py b/hermes_cli/plugins_cadence.pyindex 638cedf1322..6d7acb1fa24 100644--- a/hermes_cli/plugins_cadence.py+++ b/hermes_cli/plugins_cadence.py@@ -12,6 +12,7 @@ Pure, injectable clock/check/update seams for hermetic tests.from __future__ import annotations+import threadingimport timefrom pathlib import Pathfrom typing import Callable, Optional@@ -20,11 +21,18 @@ _MARKERS_DIR = "plugin-update-checks"_DEFAULT_INTERVAL_HOURS = 24-def _markers_dir() -> Path:- # resolved per call (tests monkeypatch get_hermes_home)+def _marker_path() -> Path:+ """The last-run marker, resolved per call (tests monkeypatch+ get_hermes_home). Derivation only — NO mkdir: a due-check or any+ read path must not create user state."""from hermes_constants import get_hermes_home- d = get_hermes_home() / _MARKERS_DIR+ return get_hermes_home() / _MARKERS_DIR / "last-run"+++def _markers_dir() -> Path:+ """The markers dir, created on demand — WRITE paths only."""+ d = _marker_path().parentd.mkdir(parents=True, exist_ok=True)return d@@ -72,7 +80,7 @@ def check_due(now: Optional[float] = None, interval_hours: Optional[float] = Nonif interval_hours <= 0:return Falsenow = time.time() if now is None else now- marker = _markers_dir() / "last-run"+ marker = _marker_path()try:last = marker.stat().st_mtimeexcept OSError:@@ -80,6 +88,12 @@ def check_due(now: Optional[float] = None, interval_hours: Optional[float] = Nonreturn (now - last) >= interval_hours * 3600+#: Minimal singleflight for one home: two gateway ticks overlapping in+#: this process (boot pass + periodic tick) must not double-fetch or+#: double-write receipts. A plain non-blocking lock — not a manager.+_tick_lock = threading.Lock()++def run_scheduled_check(*,run_checks_fn: Callable[..., list],@@ -91,8 +105,9 @@ def run_scheduled_check() -> Optional[list]:"""One cadence tick: gate → check → receipt → (opt-in) apply.- Returns the check results, or None when not due / disabled. NEVER- raises — a cadence failure is logged, never fatal.+ Returns the check results, or None when not due / disabled / another+ tick is already in flight. NEVER raises — a cadence failure is+ logged, never fatal."""import logging@@ -100,24 +115,43 @@ def run_scheduled_check(log = logging.getLogger(__name__)if not check_due(now=now, config_get=config_get):return None+ if not _tick_lock.acquire(blocking=False):+ log.debug("plugin update check already in flight — skipping tick")+ return None+ try:+ return _run_check_locked(+ run_checks_fn=run_checks_fn,+ plugins_dir=plugins_dir,+ apply_updates_fn=apply_updates_fn,+ log=log,+ config_get=config_get,+ )+ finally:+ _tick_lock.release()++def _run_check_locked(+ *,+ run_checks_fn: Callable[..., list],+ plugins_dir: Path,+ apply_updates_fn: Optional[Callable[[str], None]],+ log,+ config_get: Callable = None,+) -> list:+ check_ok = Truetry:results = run_checks_fn(plugins_dir)except Exception:log.warning("plugin update check failed", exc_info=True)results = []+ check_ok = False- # the receipt — the surface every medium readstry:from pm import receipt-- receipt.begin("plugin-check")+ token = receipt.begin("plugin-check")receipt.record_plugin_checks(results)- updates = [- r for r in results- if getattr(r, "update_available", None) is True- ]- receipt.finalize("ok" if not updates else "updates-available")+ updates = [r for r in results if getattr(r, "update_available", None) is True]+ receipt.finalize("failed" if not check_ok else "updates-available" if updates else "ok", token=token)except Exception:log.debug("plugin-check receipt write failed", exc_info=True)@@ -147,7 +181,7 @@ def run_scheduled_check(if getattr(r, "klass", "") == "git":try:apply_updates_fn(r.name)- except Exception:+ except (Exception, SystemExit):log.warning("auto-apply of %s failed", r.name, exc_info=True)# stamp the marker AFTER a completed run (even a failed one — a@@ -157,4 +191,55 @@ def run_scheduled_check(marker.write_text(str(int(time.time())), encoding="utf-8")except OSError:pass- return results\ No newline at end of file+ return results+++# ---------------------------------------------------------------------------+# the production caller: real seams for the gateway boot/housekeeping tick+# ---------------------------------------------------------------------------++def maybe_run_gateway_check(+ *,+ run_checks_fn: Optional[Callable[..., list]] = None,+ apply_updates_fn: Optional[Callable[[str], None]] = None,+ plugins_dir: Optional[Path] = None,+ log=None,+ now: Optional[float] = None,+) -> Optional[list]:+ """The tick every gateway boot / housekeeping pass calls.++ Fills in the REAL seams ``run_scheduled_check`` leaves injectable:+ the same read-only ``plugins_updates.run_checks`` the manual+ ``hermes plugins check-updates`` uses (urllib feed fetch, git+ ls-remote, PyPI latest), the real plugins dir, and the manual+ ``hermes plugins update <name>`` flow as the opt-in apply path —+ auto-apply rides the identical security/consent/scan pipeline.++ Returns the check results, or None when not due / disabled. Due-gated+ by ``plugins.auto_update_check_hours`` (0 disables); a network error+ costs one warning and a stamped marker — never an apply.+ """+ if plugins_dir is None:+ from hermes_cli import plugins_cmd++ plugins_dir = plugins_cmd._plugins_dir()+ if run_checks_fn is None:+ # ONE shared network-default implementation — plugins_updates+ # owns default_fetch / default_ls_remote / _default_pypi_latest;+ # the manual `hermes plugins check-updates` passes the same+ # defaults. No boilerplate re-derivation here.+ from hermes_cli.plugins_updates import run_checks++ run_checks_fn = run_checks+ if apply_updates_fn is None:+ from hermes_cli import plugins_cmd++ from functools import partial+ apply_updates_fn = partial(plugins_cmd.cmd_update, interactive=False)+ return run_scheduled_check(+ run_checks_fn=run_checks_fn,+ plugins_dir=plugins_dir,+ apply_updates_fn=apply_updates_fn,+ log=log,+ now=now,+ )diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex a27d16dd13e..98db1b68e8f 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -340,13 +340,17 @@ def _missing_env_specs(manifest: dict) -> list[dict]:def _install_plugin_python_deps(manifest: dict, target: Path, console) -> tuple[bool, Optional[str]]:- """Consent + try-resolve for plugin python deps (settled 2026-09-02).-- y/n prompt (auto-NO when non-interactive) → materialize the legacy- bridge if needed → resolve through the pm workspace union. Returns- (installed, reason): installed=True when the deps resolve; on- conflict the resolver's message is the reason. Never raises — the- caller keeps the plugin installed-but-disabled on failure.+ """Consent gate for plugin python deps (settled 2026-09-02; C13 rework).++ Node sidecar: y/n prompt → ``npm ci`` into the plugin's OWN+ node_modules (separate question, failure never blocks enable).+ Python deps: NO resolution here — the resolve runs inside the ONE+ admission transaction when the enable commits+ (:func:`_admit_and_save_plugin_sets`), so the environment and the+ config always change together or not at all. Returns (consented,+ reason): consented=True when the user accepted (or no prompt was+ needed); a decline/skip returns False and NOTHING is installed.+ Never raises — the caller keeps the plugin installed-but-disabled."""deps = manifest.get("python_dependencies") or []if not isinstance(deps, list):@@ -413,39 +417,9 @@ def _install_plugin_python_deps()return False, "dependency install declined"- # Route through pm.sync_venv — the ONE sync authority: it owns the- # lazy-off gate, the frozen-set refusal, the workspace union (with- # bisect + write-back), and the universal receipt. plugins install- # never drives uv itself (settled: it only drops the folder; the- # sync step does the rest). The plugin is NOT yet in plugins.enabled,- # so the resolve runs the WOULD-BE union: enabled members + this- # plugin, as a dry check via resolve_union (bisect decisions for- # the not-yet-enabled plugin are advisory here — the real sync- # after enable re-runs the union through sync_venv).- try:- from pm.ensure import lazy_installs_allowed- from pm.workspace import enabled_member_dirs, materialize_legacy_pyproject, resolve_union-- # Legacy manifest-only plugins need their generated pyproject- # before the union can see their deps (no-op when lazy-off).- materialize_legacy_pyproject(target)- if not lazy_installs_allowed():- return False, "lazy installs are disabled — install the deps manually"- from pm.packages import Venv-- members = enabled_member_dirs()- survivors, decisions = resolve_union(- members + ([target] if target not in members else []),- venv_dir=Venv().venv_dir(),- )- if target not in survivors:- reason = next(- (d["reason"] for d in decisions if d["plugin"] == target.name),- "did not resolve",- )- return False, reason- except Exception as exc:- return False, str(exc)+ # Consent only — the python-deps resolution itself runs inside the ONE+ # admission transaction at enable-commit time (C13): env + config move+ # together or not at all.return True, None@@ -680,7 +654,7 @@ def _swap_in_plugin(tmp_target: Path, target: Path, backup: Path, old_metadata:_write_install_metadata(new_metadata)except Exception:if target.exists():- shutil.rmtree(target)+ _rmtree_force(target)if replaced_existing and backup.exists():os.replace(backup, target)if old_metadata:@@ -850,58 +824,56 @@ def cmd_install(f"plugin.json, or __init__.py. It may not be a valid Hermes plugin.")_prompt_plugin_env_vars(installed_manifest, console)- deps_ok, deps_reason = _install_plugin_python_deps(- installed_manifest, target, console- )+ should_enable = enable+ if should_enable is None:+ should_enable = _is_tty() and _ask_yes(f" Enable '{installed_name}' now? [y/N]: ")+ deps_ok, deps_reason = (True, None)+ if should_enable:+ deps_ok, deps_reason = _install_plugin_python_deps(installed_manifest, target, console)_display_after_install(target, identifier)- should_enable = enable+ # ONE admission transaction for the enable (C13): resolve the candidate+ # union (enabled members + this target) and commit the config in the+ # same step — env and config change together or not at all. No+ # duplicate sync here: nothing was resolved before this point.if should_enable and not deps_ok:- # Explicitly requested enable, but the deps failed to resolve:- # enabling would break the venv union on the next sync. Refuse- # with the resolver's reason.+ # Consent declined/skipped: nothing was installed or changed, so+ # enabling is refused without touching config or environment.console.print(f"[red]✗[/red] Cannot enable [bold]{installed_name}[/bold]: "- f"its Python dependencies did not resolve: {deps_reason}"+ f"{deps_reason}")console.print("[dim]The plugin stays installed but disabled; re-enable ""after resolving the conflict.[/dim]")should_enable = False- if should_enable is None:- if deps_ok and sys.stdin.isatty() and sys.stdout.isatty():- try:- answer = input(- f" Enable '{installed_name}' now? [y/N]: ",- ).strip().lower()- should_enable = answer in {"y", "yes"}- except (EOFError, KeyboardInterrupt):- should_enable = False- else:- should_enable = False- if not deps_ok:- console.print(- f"[yellow]Plugin [bold]{installed_name}[/bold] installed "- f"but NOT enabled — Python dependencies did not resolve:[/yellow]"- )- console.print(f" [dim]{deps_reason}[/dim]")- console.print(- "[dim]Re-enable after resolving the conflict "- f"(hermes plugins enable {installed_name}).[/dim]\n"- )if should_enable:+ from hermes_cli.plugins_admission import AdmissionRefused+enabled = _get_enabled_set()disabled = _get_disabled_set()enabled.add(installed_name)disabled.discard(installed_name)- _save_enabled_set(enabled)- _save_disabled_set(disabled)- console.print(- f"[green]✓[/green] Plugin [bold]{installed_name}[/bold] enabled.",- )+ try:+ _admit_and_save_plugin_sets(+ enabled,+ disabled,+ extra_dirs=[target],+ console=console,+ action=f"Enable '{installed_name}'",+ )+ except AdmissionRefused:+ console.print(+ "[dim]The plugin stays installed but disabled; re-enable "+ "after resolving the conflict.[/dim]"+ )+ else:+ console.print(+ f"[green]✓[/green] Plugin [bold]{installed_name}[/bold] enabled.",+ )else:console.print(f"[dim]Plugin installed but not enabled. "@@ -940,7 +912,7 @@ def _pull_plugin_update(target: Path, pinned_msg, not_git_msg, before_pull=None)return output-def cmd_update(name: str) -> None:+def cmd_update(name: str, *, interactive: bool = True) -> None:"""Update an installed plugin by pulling latest from its git remote."""from rich.markup import escapeconsole = _console()@@ -959,32 +931,6 @@ def cmd_update(name: str) -> None:_rescan_after_update(target, name, console)_post_pull_housekeeping(target, console)- scan_result = scan_plugin(target, source=name)- allowed, reason = should_allow_plugin_install(scan_result)- if allowed is not True:- console.print()- console.print(- f"[yellow]⚠ Security scan flagged the updated plugin:[/yellow] {reason}",- )- console.print(format_scan_report(scan_result))- if scan_result.verdict == "dangerous":- enabled = _get_enabled_set()- disabled = _get_disabled_set()- if name in enabled or name not in disabled:- enabled.discard(name)- disabled.add(name)- _save_enabled_set(enabled)- _save_disabled_set(disabled)- console.print(- f"[red]Plugin '{name}' has been disabled.[/red] Review the "- f"findings, then re-enable with `hermes plugins enable {name}` "- f"if you trust them.",- )- # Same stale-bytecode class as the main checkout (#6207/#60242): the- # pull just changed .py files under this plugin dir, so drop any- # __pycache__ compiled from the previous revision.- _clear_plugin_bytecode(target)-# Member-manifest plugins: the pull may have changed its pyproject# pins — re-sync the union so new deps land (Task 5, plugin# auto-update plan). The venv stamp now includes member pyproject@@ -1007,9 +953,6 @@ def cmd_update(name: str) -> None:"to retry the dependency sync.[/dim]")- # Copy any new .example files- _copy_example_files(target, console)-# Update-time re-consent (#64228): if the new version declares# capabilities the granted set lacks, surface the diff and require# re-consent for the additions. The stored consent hash detects a@@ -1021,7 +964,10 @@ def cmd_update(name: str) -> None:if declared_caps:from hermes_cli.plugin_capabilities import declared_set_changed, pending_capabilitiesif pending_capabilities(plugin_id, declared_caps) or declared_set_changed(plugin_id, declared_caps):- _run_capability_consent(console, plugin_id, declared_caps, context="update")+ if interactive:+ _run_capability_consent(console, plugin_id, declared_caps, context="update")+ else:+ console.print(f"[yellow]Plugin {plugin_id} has new capabilities; review them with `hermes plugins capabilities {plugin_id}`.[/yellow]")out = output.strip()if "Already up to date" in out:@@ -1114,8 +1060,35 @@ def _save_enabled_set(enabled: set) -> None:def _save_plugin_sets(enabled: set, disabled: set) -> None:- _save_enabled_set(enabled)- _save_disabled_set(disabled)+ from hermes_cli.plugins_admission import admit_plugin_set_change++ admit_plugin_set_change(enabled, disabled, active_plugins_dir=_plugins_dir())+++def _admit_and_save_plugin_sets(+ enabled: set, disabled: set, *, extra_dirs=(), console=None, action: str = "enable"+) -> None:+ """ONE admission authority for proposed enabled/disabled sets (C13):+ the candidate union is resolved against the ACTIVE environment and+ the config commits inside the same locked pm transaction (sync's+ ``before_publish`` hook) — a refusal or a config-write failure+ publishes nothing: previous config bytes AND previous environment+ stay exactly in place. Raises :class:`AdmissionRefused` (UI callers+ catch and surface it — admission never auto-disables to fit)."""+ from hermes_cli.plugins_admission import AdmissionRefused, admit_plugin_set_change++ try:+ admit_plugin_set_change(+ enabled, disabled, active_plugins_dir=_plugins_dir(), extra_dirs=extra_dirs+ )+ except AdmissionRefused as exc:+ if console is not None:+ console.print(f"[red]✗[/red] {action} refused: {exc}")+ console.print(+ "[dim]config.yaml and the active environment are unchanged. "+ "Run `hermes pm install` to resolve dependencies, then retry.[/dim]"+ )+ raise_BASIC_AUTH_PLUGIN_KEYS = frozenset({"basic", "dashboard_auth/basic"})@@ -1144,7 +1117,7 @@ def _discard_key_and_leaf(names: set, key: str) -> None:def _set_plugin_enabled(name: str, *, enable: bool) -> None:- """Move *name* between the enabled allow-list and the disabled deny-list and persist both."""+ """Persist the proposed selection through the same dependency transaction."""enabled = _get_enabled_set()disabled = _get_disabled_set()(enabled.add if enable else enabled.discard)(name)@@ -1221,7 +1194,7 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:manifest_name = next((e[0] for e in _discover_all_plugins() if e[5] == key), None)if manifest_name is not None:disabled.discard(manifest_name)- _save_plugin_sets(enabled, disabled)+ _admit_and_save_plugin_sets(enabled, disabled, console=console, action=f"Enable '{key}'")console.print(f"[green]✓[/green] Plugin [bold]{key}[/bold] enabled. Takes effect on next session.")# Built-in tool override is a privileged grant; bundled plugins are trusted.@@ -1612,40 +1585,15 @@ def cmd_trust_update_url(name: str) -> None:def cmd_check_updates(args: Any | None = None) -> None:"""Read-only: is any installed plugin outdated? NEVER mutates."""- import urllib.error- import urllib.request-from rich.console import Consolefrom rich.table import Table- from hermes_cli.plugins_updates import _default_pypi_latest, run_checks-console = Console()plugins_dir = _plugins_dir()- def _fetch(url: str) -> str:- with urllib.request.urlopen(url, timeout=10.0) as resp:- data = resp.read(1 * 1024 * 1024)- return data.decode("utf-8", errors="replace")-- def _ls_remote(source: str) -> str:- git_exe = _resolve_git_executable()- proc = subprocess.run(- [git_exe or "git", "ls-remote", source, "HEAD"],- capture_output=True,- text=True,- timeout=30,- )- if proc.returncode != 0:- raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200])- # 'sha\trefs/heads/...' or empty- out = (proc.stdout or "").strip()- return out.split("\t")[0] if out else ""-- results = run_checks(- plugins_dir, fetch=_fetch, ls_remote=_ls_remote,- pip_pypi_latest=_default_pypi_latest,- )+ from hermes_cli.plugins_updates import run_checks++ results = run_checks(plugins_dir)if getattr(args, "json", False):print(json.dumps([r.to_json() for r in results], indent=2))@@ -1896,7 +1844,10 @@ def _persist_plugin_selection(plugin_keys, chosen, disabled) -> tuple[bool, set]changed = new_enabled != _get_enabled_set() or new_disabled != disabledif changed:- _save_plugin_sets(new_enabled, new_disabled)+ # C13: the composite UI's candidate goes through the ONE admission+ # authority — refusal raises AdmissionRefused BEFORE any config+ # write; the caller surfaces it and the selection stays unsaved.+ _admit_and_save_plugin_sets(new_enabled, new_disabled, action="Save plugin selection")return changed, new_enabled@@ -2010,7 +1961,17 @@ def _run_composite_ui(curses, plugin_keys, plugin_labels, plugin_selected, disabcurses.wrapper(_draw)flush_stdin()- changed, new_enabled = _persist_plugin_selection(plugin_keys, chosen, disabled)+ from hermes_cli.plugins_admission import AdmissionRefused++ try:+ changed, new_enabled = _persist_plugin_selection(plugin_keys, chosen, disabled)+ except AdmissionRefused as exc:+ console.print(f"[red]✗[/red] Plugin selection refused, not saved: {exc}")+ console.print(+ "[dim]config.yaml and the active environment are unchanged. "+ "Run `hermes pm install` to resolve, then retry.[/dim]"+ )+ returnif changed:console.print(f"\n[green]\u2713[/green] General plugins: {len(new_enabled)} enabled, "@@ -2049,7 +2010,7 @@ def _run_composite_fallback(plugin_keys, plugin_labels, plugin_selected, disableexcept (ValueError, KeyboardInterrupt, EOFError):returnprint()- _persist_plugin_selection(plugin_keys, chosen, disabled)+ _save_plugin_selection_fallback(plugin_keys, chosen, disabled)if categories:print(color("\n Provider Plugins", Colors.YELLOW))@@ -2067,6 +2028,17 @@ def _run_composite_fallback(plugin_keys, plugin_labels, plugin_selected, disableprint()+def _save_plugin_selection_fallback(plugin_keys, chosen, disabled) -> None:+ """The text fallback's save: same admission authority, refusal printed."""+ from hermes_cli.plugins_admission import AdmissionRefused++ try:+ _persist_plugin_selection(plugin_keys, chosen, disabled)+ except AdmissionRefused as exc:+ print(f" Plugin selection refused, not saved: {exc}")+ print(" config.yaml and the active environment are unchanged.")++def dashboard_install_plugin(identifier: str, *, force: bool, enable: bool) -> dict[str, Any]:"""Non-interactive install for the web dashboard. Returns a JSON-serializable dict."""warnings: list[str] = []@@ -2091,7 +2063,15 @@ def dashboard_install_plugin(identifier: str, *, force: bool, enable: bool) -> dreturn {"ok": False, "error": str(exc)}if enable:- _set_plugin_enabled(installed_name, enable=True)+ from hermes_cli.plugins_admission import AdmissionRefused++ try:+ _set_plugin_enabled(installed_name, enable=True)+ except AdmissionRefused as exc:+ return {+ "ok": False, "error": f"enable refused: {exc}",+ "plugin_name": installed_name, "enabled": False,+ }ap = target / "after-install.md"return {"ok": True, "plugin_name": installed_name, "warnings": warnings,@@ -2166,7 +2146,12 @@ def dashboard_set_agent_plugin_enabled(name: str, *, enabled: bool) -> dict[str,dis = _get_disabled_set()if ((name in en and name not in dis) if enabled else (name not in en and name in dis)):return {"ok": True, "name": name, "unchanged": True}- _set_plugin_enabled(name, enable=enabled)+ from hermes_cli.plugins_admission import AdmissionRefused++ try:+ _set_plugin_enabled(name, enable=enabled)+ except AdmissionRefused as exc:+ return {"ok": False, "error": str(exc), "name": name, "unchanged": True}_toggle_plugin_toolset(name, enable=enabled)return {"ok": True, "name": name, "unchanged": False}diff --git a/hermes_cli/plugins_updates.py b/hermes_cli/plugins_updates.pyindex cd3da1deba0..b7234c4f6a7 100644--- a/hermes_cli/plugins_updates.py+++ b/hermes_cli/plugins_updates.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport importlib.metadataimport json+import reimport subprocessfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -30,6 +31,7 @@ from hermes_cli.plugins_provenance import (_FETCH_TIMEOUT = 10.0_MAX_FEED_BYTES = 1 * 1024 * 1024+_FULL_GIT_SHA_RE = re.compile(r"[0-9a-fA-F]{40}")@dataclass@@ -135,9 +137,39 @@ def check_provenanced(return resultresult.latest = feed.get("version")result.min_hermes = feed.get("min_hermes")- result.update_available = (- result.latest is not None and result.latest != result.current- )+ # Like-for-like identity only (audit C17): a feed that ships a full+ # git SHA compares SHA vs recorded revision; otherwise the feed's+ # semantic version compares against the installed manifest's+ # version. A SHA is never compared to a semantic version, and an+ # uncomparable pair reads as unknown — not as an update.+ feed_git = (feed.get("artifacts") or {}).get("git")+ if feed_git and _FULL_GIT_SHA_RE.fullmatch(feed_git):+ if not result.current or not _FULL_GIT_SHA_RE.fullmatch(+ str(result.current)+ ):+ result.update_available = None+ result.reason = (+ "feed declares a git sha but the install records no "+ "full revision sha to compare"+ )+ return result+ # Case-equivalent hex only after format validation.+ result.latest = feed_git.lower()+ result.update_available = feed_git.lower() != result.current.lower()+ return result+ installed_version = _read_manifest_field(prov.path, "version")+ if installed_version is None:+ result.update_available = None+ result.reason = (+ f"feed declares version {result.latest!r} but the installed "+ "plugin.yaml records no version to compare"+ )+ return result+ # Like-for-like fields: the semantic branch compares version vs+ # version, so `current` reports the installed version, not the+ # recorded revision sha.+ result.current = installed_version+ result.update_available = result.latest != installed_versionreturn result# ── 3. no update_url anywhere + git row → ls-remote ────────────@@ -160,7 +192,10 @@ def parse_feed_yml(text: str) -> dict:min_hermes, artifacts{git,bundle,bundle_sha256}, notes_url."""import yaml- data = yaml.safe_load(text)+ try:+ data = yaml.safe_load(text)+ except yaml.YAMLError as exc:+ raise ValueError(f"invalid feed YAML: {exc}") from excif not isinstance(data, dict):raise ValueError("feed must be a YAML mapping")version = data.get("version")@@ -173,12 +208,27 @@ def parse_feed_yml(text: str) -> dict:out[key] = value.strip()artifacts = data.get("artifacts")if isinstance(artifacts, dict):+ git = artifacts.get("git")+ if git is not None and not isinstance(git, str):+ raise ValueError("feed artifacts.git must be a string")out["artifacts"] = {k: v for k, v in artifacts.items() if isinstance(v, str)}return out+def _owning_distribution(ep) -> Optional[str]:+ """The name of the distribution the entry point belongs to — metadata,+ never a guess derived from the import module (audit C17)."""+ dist = getattr(ep, "dist", None)+ if dist is None:+ return None+ try:+ return dist.metadata.get("Name") or None+ except Exception:+ return None++def check_pip_plugins(*,installed_version: Callable[[str], str], # dist name -> version@@ -193,9 +243,19 @@ def check_pip_plugins()results: list[CheckResult] = []for ep in entry_points:- dist_name = getattr(ep, "dist_name", None) or (- ep.value.split(":")[0].split(".")[0] if ep.value else ep.name- )+ dist_name = getattr(ep, "dist_name", None) or _owning_distribution(ep)+ if not dist_name:+ results.append(+ CheckResult(+ name=ep.name,+ klass="pip",+ reason=(+ "entry point has no owning distribution metadata; "+ "cannot determine what to check"+ ),+ )+ )+ continuetry:current = installed_version(dist_name)except importlib.metadata.PackageNotFoundError:@@ -233,17 +293,61 @@ def check_pip_plugins(return results+def default_fetch(url: str) -> str:+ """The real feed fetcher: url -> text (raises on failure).++ ONE implementation shared by the manual ``hermes plugins+ check-updates`` and the cadence tick — callers never re-derive it.+ """+ import urllib.request++ with urllib.request.urlopen(url, timeout=_FETCH_TIMEOUT) as resp:+ data = resp.read(_MAX_FEED_BYTES)+ return data.decode("utf-8", errors="replace")+++def default_ls_remote(source: str) -> str:+ """The real git probe: source -> HEAD sha (raises on failure).++ Uses the same resolved git executable the CLI path resolves. Lazily+ imports plugins_cmd (which lazily imports this module) — no import+ cycle at module load.+ """+ from hermes_cli.plugins_cmd import _resolve_git_executable++ proc = subprocess.run(+ [_resolve_git_executable() or "git", "ls-remote", source, "HEAD"],+ capture_output=True,+ text=True,+ timeout=30,+ )+ if proc.returncode != 0:+ raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200])+ # 'sha\trefs/heads/...' or empty+ out = (proc.stdout or "").strip()+ return out.split("\t")[0] if out else ""++def run_checks(plugins_dir: Path,*,- fetch: Callable[[str], str],- ls_remote: Callable[[str], str],+ fetch: Optional[Callable[[str], str]] = None,+ ls_remote: Optional[Callable[[str], str]] = None,include_pip: bool = True,pip_installed_version: Callable[[str], str] = importlib.metadata.version,pip_pypi_latest: Optional[Callable[[str], Optional[str]]] = None,pip_entry_points: Optional[list] = None,) -> list[CheckResult]:- """All checks for one plugins dir. NEVER mutates anything."""+ """All checks for one plugins dir. NEVER mutates anything.++ ``fetch``/``ls_remote`` default to :func:`default_fetch` /+ :func:`default_ls_remote` — the single shared network implementation+ the manual command and the cadence tick both ride.+ """+ if fetch is None:+ fetch = default_fetch+ if ls_remote is None:+ ls_remote = default_ls_remoteresults = [check_provenanced(p, fetch=fetch, ls_remote=ls_remote)for p in plugins_provenance(plugins_dir)@@ -271,4 +375,4 @@ def _default_pypi_latest(dist: str) -> Optional[str]:data = json.loads(resp.read(_MAX_FEED_BYTES))return (data.get("info") or {}).get("version")except Exception:- return None\ No newline at end of file+ return Nonediff --git a/hermes_cli/post_update.py b/hermes_cli/post_update.pyindex a787e2d8782..73cc947bdc7 100644--- a/hermes_cli/post_update.py+++ b/hermes_cli/post_update.py@@ -297,6 +297,27 @@ def step_provision_runtimes() -> dict:return {"ok": True, "refreshed": refreshed}+def step_report_runtime_drift() -> dict:+ """CHECK-ONLY machine step for automatic boot.++ ``pm.check()`` is O(1) stamp comparisons against the installed-state+ ledger — no network, no installs. Drift is reported loudly (the same+ verdict the CLI startup block prints) so the user knows to run+ ``hermes pm install``; boot itself never installs anything. The+ installing pass is MACHINE_STEPS below, owned by the explicit update+ flow — automatic boot must not run network installers.+ """+ import pm++ problems = pm.check()+ if not problems:+ return {"ok": True, "skipped": "current"}+ logger.warning(+ "install out of sync (%s) — run `hermes pm install`", "; ".join(problems)+ )+ return {"ok": True, "drift": problems}++def step_expose_cli() -> dict:"""Keep the user-facing ``hermes`` launchers alive across updates.@@ -341,6 +362,21 @@ def step_expose_cli() -> dict:return _symlink_sealed_launchers(root.parent / "bin")return {"ok": True, "skipped": "bundle-owns-launchers"}+ # pm-store-managed install: the launchers are owned by+ # hermes_cli._launchers (staged by install.ps1 / _install_repair —+ # boot the STORE python with a repo-first PYTHONPATH, never+ # venv/Scripts|bin python). This step's venv-wrapper shape is NOT+ # that shape; writing it here would rewrite a store launcher into a+ # venv boot. No alternate writer: the existing owner maintains+ # these (per-name, at install and at process-start repair).+ try:+ from hermes_cli._launchers import resolve_store_python++ if resolve_store_python(root) is not None:+ return {"ok": True, "skipped": "store-launchers-owned"}+ except Exception as exc: # noqa: BLE001 — never kill boot over a probe+ logger.debug("store-python probe failed: %s", exc)+# Capability probe for the checkout shape: the wrapper bodies bake# these two paths into text, so both must exist to have anything to# point at. A checkout with a nuked venv lands here — skip; the@@ -473,8 +509,20 @@ HOME_STEPS: tuple = (("expose_cli", step_expose_cli),)-# Machine steps may be slow (network installers); boot bootstrap runs them-# AFTER writing the machine record, detached from boot readiness.+# What AUTOMATIC boot runs for the home scope: HOME_STEPS minus the+# bundled-skills sync — startup skill syncing already has exactly one+# owner per entrypoint (main.py's _sync_bundled_skills_for_startup for+# the CLI, gateway/run.py's configure-logging sync for the gateway), and+# `hermes update`'s explicit pass keeps the full HOME_STEPS. Adding the+# sync here made boot a third writer racing those two.+BOOT_HOME_STEPS: tuple = tuple(+ step for step in HOME_STEPS if step[0] != "sync_skills"+)++# Machine steps may be slow (network installers); they run ONLY in the+# explicit update phase (``python -m hermes_cli.post_update --update-phase``,+# i.e. `hermes update`'s fresh-interpreter step pass) — never on automatic+# boot.## There is no separate cua-driver refresh step: pinned managed tools ride# provision_runtimes' pm sweep — one authority on every tool's version.@@ -482,6 +530,14 @@ MACHINE_STEPS: tuple = (("provision_runtimes", step_provision_runtimes),)+# What AUTOMATIC boot runs for the machine scope: the same pm.check()+# verdict, reported instead of installed (boot must not block on, or+# trigger, network installs — the user runs `hermes pm install` or the+# explicit update pass when they want the repair).+BOOT_MACHINE_STEPS: tuple = (+ ("report_runtime_drift", step_report_runtime_drift),+)+def run_steps(steps: Iterable) -> dict:"""Run steps in order; one failure never stops the rest.diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.pyindex 7c66147f34b..f9aa5bf662a 100644--- a/hermes_cli/profile_distribution.py+++ b/hermes_cli/profile_distribution.py@@ -30,29 +30,11 @@ ENV_EXAMPLE_FILENAME = ".env.EXAMPLE"# ``distribution_owned:``. config.yaml is dist-owned but preserved on update by default.DEFAULT_DIST_OWNED: Tuple[str, ...] = ("SOUL.md", "config.yaml", "mcp.json", "skills", "cron", MANIFEST_FILENAME)-# Paths NEVER part of a distribution: user-owned, protected on update. Keep consistent with-# ``profiles.py`` export exclusions plus the ``local/`` convention for user customizations.-# MERGE-CHECK: upstream made this a self-contained frozenset superseding our-# DEFAULT_EXPORT_EXCLUDE_ROOT import; its entries are a functional superset (includes-# memories/sessions/plans/workspace/home), so we take theirs to avoid coupling to-# profiles.py internals while preserving the same protections.-USER_OWNED_EXCLUDE: frozenset = frozenset({- # Credentials & runtime secrets- "auth.json", ".env",- # Databases & runtime state- "state.db", "state.db-shm", "state.db-wal",- "hermes_state.db", "response_store.db",- "response_store.db-shm", "response_store.db-wal",- "gateway.pid", "gateway_state.json", "processes.json",- "auth.lock", "active_profile", ".update_check",- "errors.log", ".hermes_history",- # User data- "memories", "sessions", "logs", "plans", "workspace", "home",- "image_cache", "audio_cache", "document_cache",- "browser_screenshots", "checkpoints", "sandboxes",- "backups", "cache",- # User customization namespace- "local",+# Distribution-specific user data extends the shared profile/runtime exclusions.+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",})diff --git a/hermes_cli/runtime_paths.py b/hermes_cli/runtime_paths.pynew file mode 100644index 00000000000..8542bc02f2a--- /dev/null+++ b/hermes_cli/runtime_paths.py@@ -0,0 +1,139 @@+"""Dependency-environment paths shared by PM and pre-import launchers.++Only stdlib and hermes_constants: environment selection must work before+any dependency from that environment has been imported.+"""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path++from hermes_constants import get_default_hermes_root, project_venv_dir+++def install_key(project_root: Path) -> str:+ canonical = str(Path(project_root).resolve())+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]+++def installs_root() -> Path:+ return get_default_hermes_root() / "installs"+++def install_state_dir(project_root: Path) -> Path:+ return installs_root() / install_key(project_root)+++def runtime_facts_path(project_root: Path) -> Path:+ return install_state_dir(project_root) / "facts.json"+++def base_venv(project_root: Path) -> Path:+ root = Path(project_root).resolve()+ manifest_path = root.parent / "manifest.json"+ if manifest_path.is_file():+ manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))+ if (root.parent / manifest.get("repo", "")).resolve() == root:+ venv = (root.parent / manifest["venv"]).resolve()+ if not venv.is_relative_to(root.parent):+ raise RuntimeError("payload environment escapes its root")+ return venv+ return project_venv_dir(root) or root / "venv"+++def store_root(project_root: Path) -> Path:+ """Read the stamped byte store before PM dependencies are available."""+ override = os.environ.get("HERMES_RUNTIME_DIR")+ if override:+ return Path(override).resolve()+ root = Path(project_root).resolve()+ for directory in (root, *root.parents):+ stamp = directory / "install-stamp.json"+ if stamp.is_file():+ try:+ data = json.loads(stamp.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ return get_default_hermes_root() / "tools"+ value = data.get("runtimeDir") if isinstance(data, dict) else None+ return Path(value).resolve() if value else get_default_hermes_root() / "tools"+ return get_default_hermes_root() / "tools"+++def selected_venv(project_root: Path) -> Path:+ """Use the committed environment, or the original install before first sync.++ A broken committed selection is an error, not permission to load an older+ dependency set silently. Reading this function never creates user state.+ """+ path = runtime_facts_path(project_root)+ try:+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ except FileNotFoundError:+ return base_venv(project_root)+ except (OSError, ValueError) as exc:+ raise RuntimeError(f"cannot read dependency environment: {path}") from exc+ try:+ fact = data.get("packages", {}).get("venv", {})+ value = fact.get("environment")+ except AttributeError as exc:+ raise RuntimeError(f"invalid dependency environment record: {path}") from exc+ if value is None:+ return base_venv(project_root)+ if not isinstance(value, str):+ raise RuntimeError("invalid dependency environment path")+ environment = Path(value).resolve()+ generations = install_state_dir(project_root) / "environments"+ if not environment.is_relative_to(generations.resolve()) or not (environment / "pyvenv.cfg").is_file():+ raise RuntimeError(f"dependency environment is missing or outside this install: {environment}")+ return environment+++def site_packages(venv: Path) -> Path:+ import sys++ return venv / ("Lib/site-packages" if os.name == "nt" else+ f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")+++def activate_dependencies(project_root: Path) -> None:+ """Select the committed tree at process boot, before third-party imports.++ A process with no extension selection keeps its original launch contract.+ Already-running processes are never switched after a dependency install.+ """+ import sys++ if not runtime_facts_path(project_root).is_file():+ return+ selected = site_packages(selected_venv(project_root))+ if not selected.is_dir():+ raise RuntimeError(f"dependency environment has no site-packages: {selected}")+ import site++ sys.path[:] = [entry for entry in sys.path+ if Path(entry).name not in ("site-packages", "dist-packages")+ and Path(entry).resolve() != project_root.resolve()]+ # uv editable members are activated by .pth files, not by sys.path alone.+ site.addsitedir(str(selected))+ sys.path[:] = [str(project_root.resolve()), str(selected),+ *[entry for entry in sys.path if Path(entry).resolve() != selected.resolve()]]+ os.environ["PYTHONPATH"] = os.pathsep.join([str(project_root.resolve()), str(selected)])+++def activation_environment(project_root: Path) -> dict[str, str]:+ """Read the installed PM environment; do not provision or switch imports."""+ from pm.ensure import env_for+ from pm.registry import all_packages++ env = env_for(*all_packages())+ selected = site_packages(selected_venv(project_root))+ env.pop("PYTHONHOME", None)+ env.pop("VIRTUAL_ENV", None)+ env["PYTHONPATH"] = os.pathsep.join([str(project_root.resolve()), str(selected)])+ return env+++if __name__ == "__main__":+ print(json.dumps(activation_environment(Path(__file__).resolve().parents[1])))diff --git a/hermes_cli/runtime_repair.py b/hermes_cli/runtime_repair.pyindex 5dd4fe88568..09c65353bc9 100644--- a/hermes_cli/runtime_repair.py+++ b/hermes_cli/runtime_repair.py@@ -847,12 +847,9 @@ def _release_repair_lock(lock: _RepairLock) -> None:def _windows_runtime_holders() -> tuple[bool, str]:if platform.system() != "Windows":return False, ""- main_module = sys.modules.get("hermes_cli.main")- detector = getattr(main_module, "_detect_venv_python_processes", None)- if detector is None:- return True, "cannot verify Windows venv holders from this update context"try:- holders = detector()+ from hermes_cli.update_cmd_windows import _detect_venv_python_processes+ holders = _detect_venv_python_processes()except Exception as exc:return True, f"could not verify Windows venv holders: {exc}"if holders:diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 56ded414924..3579869d4d1 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -362,293 +362,6 @@ def _print_banner(*lines: str) -> None:print(color("└─────────────────────────────────────────────────────────┘", Colors.MAGENTA))- # Web tools (Exa, Parallel, Firecrawl, Tavily, or Keenable)- if subscription_features.web.managed_by_nous:- tool_status.append(("Web Search & Extract (Nous subscription)", True, None))- elif subscription_features.web.available:- label = "Web Search & Extract"- if subscription_features.web.current_provider:- label = f"Web Search & Extract ({subscription_features.web.current_provider})"- tool_status.append((label, True, None))- else:- tool_status.append(("Web Search & Extract", False, "EXA_API_KEY, PARALLEL_API_KEY, FIRECRAWL_API_KEY/FIRECRAWL_API_URL, TAVILY_API_KEY, KEENABLE_API_KEY, or SEARXNG_URL"))-- # Browser tools (local Chromium, Camofox, Browserbase, Browser Use, or Firecrawl)- browser_provider = subscription_features.browser.current_provider- if subscription_features.browser.managed_by_nous:- tool_status.append(("Browser Automation (Nous Browser Use)", True, None))- elif subscription_features.browser.available:- label = "Browser Automation"- if browser_provider:- label = f"Browser Automation ({browser_provider})"- tool_status.append((label, True, None))- else:- missing_browser_hint = "npm install -g agent-browser, set CAMOFOX_URL, or configure Browser Use or Browserbase"- if browser_provider == "Browserbase":- missing_browser_hint = (- "npm install -g agent-browser and set "- "BROWSERBASE_API_KEY/BROWSERBASE_PROJECT_ID"- )- elif browser_provider == "Browser Use":- missing_browser_hint = (- "npm install -g agent-browser and set BROWSER_USE_API_KEY"- )- elif browser_provider == "Camofox":- missing_browser_hint = "CAMOFOX_URL"- elif browser_provider == "Local browser":- missing_browser_hint = (- "npm install -g agent-browser && agent-browser install --with-deps"- )- tool_status.append(- ("Browser Automation", False, missing_browser_hint)- )-- # Image generation — FAL (direct or via Nous), or any plugin-registered- # provider (OpenAI, etc.)- if subscription_features.image_gen.managed_by_nous:- tool_status.append(("Image Generation (Nous subscription)", True, None))- elif subscription_features.image_gen.available:- tool_status.append(("Image Generation", True, None))- else:- # Fall back to probing plugin-registered providers so OpenAI-only- # setups don't show as "missing FAL_KEY".- _img_backend = None- try:- from agent.image_gen_registry import list_providers- from hermes_cli.plugins import _ensure_plugins_discovered-- _ensure_plugins_discovered()- for _p in list_providers():- if _p.name == "fal":- continue- try:- if _p.is_available():- _img_backend = _p.display_name- break- except Exception:- continue- except Exception:- pass- if _img_backend:- tool_status.append((f"Image Generation ({_img_backend})", True, None))- else:- tool_status.append(("Image Generation", False, "FAL_KEY or OPENAI_API_KEY"))-- # Video generation — opt-in via `hermes tools` → Video Generation.- # Only show the row when a plugin reports available so we don't badger- # users who don't care about video gen with a "missing" status line.- if subscription_features.video_gen.managed_by_nous:- tool_status.append(("Video Generation (FAL via Nous subscription)", True, None))- else:- try:- from agent.video_gen_registry import list_providers as _list_video_providers- from hermes_cli.plugins import _ensure_plugins_discovered as _ensure_plugins- _ensure_plugins()- _video_backend = None- for _vp in _list_video_providers():- try:- if _vp.is_available():- _video_backend = _vp.display_name- break- except Exception:- continue- except Exception:- _video_backend = None- if _video_backend:- tool_status.append((f"Video Generation ({_video_backend})", True, None))-- # TTS — show configured provider- tts_provider = cfg_get(config, "tts", "provider", default="edge")- if subscription_features.tts.managed_by_nous:- tool_status.append(("Text-to-Speech (OpenAI via Nous subscription)", True, None))- elif tts_provider == "elevenlabs" and get_env_value("ELEVENLABS_API_KEY"):- tool_status.append(("Text-to-Speech (ElevenLabs)", True, None))- elif tts_provider == "openai" and (- get_env_value("VOICE_TOOLS_OPENAI_KEY") or get_env_value("OPENAI_API_KEY")- ):- tool_status.append(("Text-to-Speech (OpenAI)", True, None))- elif tts_provider == "minimax" and get_env_value("MINIMAX_API_KEY"):- tool_status.append(("Text-to-Speech (MiniMax)", True, None))- elif tts_provider == "mistral" and get_env_value("MISTRAL_API_KEY"):- tool_status.append(("Text-to-Speech (Mistral Voxtral)", True, None))- elif tts_provider == "gemini" and (get_env_value("GEMINI_API_KEY") or get_env_value("GOOGLE_API_KEY")):- tool_status.append(("Text-to-Speech (Google Gemini)", True, None))- elif tts_provider == "neutts":- try:- neutts_ok = importlib.util.find_spec("neutts") is not None- except Exception:- neutts_ok = False- if neutts_ok:- tool_status.append(("Text-to-Speech (NeuTTS local)", True, None))- else:- tool_status.append(("Text-to-Speech (NeuTTS — not installed)", False, "run 'hermes setup tts'"))- elif tts_provider == "kittentts":- try:- kittentts_ok = importlib.util.find_spec("kittentts") is not None- except Exception:- kittentts_ok = False- if kittentts_ok:- tool_status.append(("Text-to-Speech (KittenTTS local)", True, None))- else:- tool_status.append(("Text-to-Speech (KittenTTS — not installed)", False, "run 'hermes setup tts'"))- else:- tool_status.append(("Text-to-Speech (Edge TTS)", True, None))-- # STT — show configured provider- stt_provider = cfg_get(config, "stt", "provider", default="local") or "local"- _stt_feature = subscription_features.features.get("stt")- if _stt_feature is not None and _stt_feature.managed_by_nous:- tool_status.append(("Speech-to-Text (OpenAI via Nous subscription)", True, None))- elif stt_provider == "openai" and (- get_env_value("VOICE_TOOLS_OPENAI_KEY") or get_env_value("OPENAI_API_KEY")- ):- tool_status.append(("Speech-to-Text (OpenAI)", True, None))- elif stt_provider == "groq" and get_env_value("GROQ_API_KEY"):- tool_status.append(("Speech-to-Text (Groq Whisper)", True, None))- elif stt_provider == "elevenlabs" and get_env_value("ELEVENLABS_API_KEY"):- tool_status.append(("Speech-to-Text (ElevenLabs Scribe)", True, None))- elif stt_provider == "xai":- tool_status.append(("Speech-to-Text (xAI)", True, None))- elif stt_provider == "deepinfra" and get_env_value("DEEPINFRA_API_KEY"):- tool_status.append(("Speech-to-Text (DeepInfra)", True, None))- else:- try:- fw_ok = importlib.util.find_spec("faster_whisper") is not None- except Exception:- fw_ok = False- if fw_ok:- tool_status.append(("Speech-to-Text (Local Whisper)", True, None))- else:- tool_status.append(- ("Speech-to-Text (Local Whisper — not installed)", False, "run 'hermes tools' → Speech-to-Text")- )-- if subscription_features.modal.managed_by_nous:- tool_status.append(("Modal Execution (Nous subscription)", True, None))- elif cfg_get(config, "terminal", "backend") == "modal":- if subscription_features.modal.direct_override:- tool_status.append(("Modal Execution (direct Modal)", True, None))- else:- tool_status.append(("Modal Execution", False, "run 'hermes setup terminal'"))- elif managed_nous_tools_enabled() and subscription_features.nous_auth_present:- tool_status.append(("Modal Execution (optional via Nous subscription)", True, None))-- # Home Assistant- if get_env_value("HASS_TOKEN"):- tool_status.append(("Smart Home (Home Assistant)", True, None))-- # Spotify (OAuth via hermes auth spotify — check auth.json, not env vars)- try:- from hermes_cli.auth import get_provider_auth_state- _spotify_state = get_provider_auth_state("spotify") or {}- if _spotify_state.get("access_token") or _spotify_state.get("refresh_token"):- tool_status.append(("Spotify (PKCE OAuth)", True, None))- except Exception:- pass-- # Skills Hub- if get_env_value("GITHUB_TOKEN"):- tool_status.append(("Skills Hub (GitHub)", True, None))- else:- tool_status.append(("Skills Hub (GitHub)", False, "GITHUB_TOKEN"))-- # Terminal (always available if system deps met)- tool_status.append(("Terminal/Commands", True, None))-- # Task planning (always available, in-memory)- tool_status.append(("Task Planning (todo)", True, None))-- # Skills (always available -- bundled skills + user-created skills)- tool_status.append(("Skills (view, create, edit)", True, None))-- # Print status- available_count = sum(1 for _, avail, _ in tool_status if avail)- total_count = len(tool_status)-- print_info(f"{available_count}/{total_count} tool categories available:")- print()-- for name, available, missing_var in tool_status:- if available:- print(f" {color('✓', Colors.GREEN)} {name}")- else:- print(- f" {color('✗', Colors.RED)} {name} {color(f'(missing {missing_var})', Colors.DIM)}"- )-- print()-- disabled_tools = [(name, var) for name, avail, var in tool_status if not avail]- if disabled_tools:- print_warning(- "Some tools are disabled. Run 'hermes setup tools' to configure them,"- )- from hermes_constants import display_hermes_home as _dhh- print_warning(f"or edit {_dhh()}/.env directly to add the missing API keys.")- print()-- # Done banner- print()- print(- color(- "┌─────────────────────────────────────────────────────────┐", Colors.GREEN- )- )- print(- color(- "│ ✓ Setup Complete! │", Colors.GREEN- )- )- print(- color(- "└─────────────────────────────────────────────────────────┘", Colors.GREEN- )- )- print()-- # Show file locations prominently- from hermes_constants import display_hermes_home as _dhh- print(color(f"📁 All your files are in {_dhh()}/:", Colors.CYAN, Colors.BOLD))- print()- print(f" {color('Settings:', Colors.YELLOW)} {get_config_path()}")- print(f" {color('API Keys:', Colors.YELLOW)} {get_env_path()}")- print(- f" {color('Data:', Colors.YELLOW)} {hermes_home}/cron/, sessions/, logs/"- )- print()-- print(color("─" * 60, Colors.DIM))- print()- print(color("📝 To edit your configuration:", Colors.CYAN, Colors.BOLD))- print()- print(f" {color('hermes setup', Colors.GREEN)} Re-run the full wizard")- print(f" {color('hermes setup model', Colors.GREEN)} Change model/provider")- print(f" {color('hermes setup terminal', Colors.GREEN)} Change terminal backend")- print(f" {color('hermes setup gateway', Colors.GREEN)} Configure messaging")- print(f" {color('hermes setup tools', Colors.GREEN)} Configure tool providers")- print()- print(f" {color('hermes config', Colors.GREEN)} View current settings")- print(- f" {color('hermes config edit', Colors.GREEN)} Open config in your editor"- )- print(f" {color('hermes config set <key> <value>', Colors.GREEN)}")- print(" Set a specific value")- print()- print(" Or edit the files directly:")- print(f" {color(f'nano {get_config_path()}', Colors.DIM)}")- print(f" {color(f'nano {get_env_path()}', Colors.DIM)}")- print()-- print(color("─" * 60, Colors.DIM))- print()- print(color("🚀 Ready to go!", Colors.CYAN, Colors.BOLD))- print()- print(f" {color('hermes', Colors.GREEN)} Start chatting")- print(f" {color('hermes gateway', Colors.GREEN)} Start messaging gateway")- print(f" {color('hermes doctor', Colors.GREEN)} Check for issues")- print()--def _prompt_container_resources(config: dict):"""Prompt for container resource settings (Docker, Singularity, Modal, Daytona)."""terminal = config.setdefault("terminal", {})@@ -691,102 +404,6 @@ def _prompt_container_resources(config: dict):pass-def _prompt_vercel_sandbox_settings(config: dict):- """Prompt for Vercel Sandbox settings without exposing unsupported disk sizing."""- terminal = config.setdefault("terminal", {})-- print()- print_info("Vercel Sandbox settings:")- print_info(" Filesystem persistence uses Vercel snapshots.")- print_info(" Snapshots restore files only; live processes do not continue after sandbox recreation.")-- from tools.terminal_tool import _SUPPORTED_VERCEL_RUNTIMES-- current_runtime = terminal.get("vercel_runtime") or "node24"- supported_label = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)- runtime = prompt(f" Runtime ({supported_label})", current_runtime).strip() or current_runtime- if runtime not in _SUPPORTED_VERCEL_RUNTIMES:- print_warning(f"Unsupported Vercel runtime '{runtime}', keeping {current_runtime}.")- runtime = current_runtime if current_runtime in _SUPPORTED_VERCEL_RUNTIMES else "node24"- terminal["vercel_runtime"] = runtime- save_env_value("TERMINAL_VERCEL_RUNTIME", runtime)-- current_persist = terminal.get("container_persistent", True)- persist_label = "yes" if current_persist else "no"- terminal["container_persistent"] = prompt(- " Persist filesystem with snapshots? (yes/no)", persist_label- ).lower() in {"yes", "true", "y", "1"}-- current_cpu = terminal.get("container_cpu", 1)- cpu_str = prompt(" CPU cores", str(current_cpu))- try:- terminal["container_cpu"] = float(cpu_str)- except ValueError:- pass-- current_mem = terminal.get("container_memory", 5120)- mem_str = prompt(" Memory in MB (5120 = 5GB)", str(current_mem))- try:- terminal["container_memory"] = int(mem_str)- except ValueError:- pass-- if terminal.get("container_disk", 51200) not in {0, 51200}:- print_warning("Vercel Sandbox does not support custom disk sizing; resetting container_disk to 51200.")- terminal["container_disk"] = 51200-- print()- print_info("Vercel authentication:")- print_info(" Use a long-lived Vercel access token plus project/team IDs.")- linked_project = _read_nearest_vercel_project()- if linked_project:- print_info(" Found defaults in nearest .vercel/project.json.")-- remove_env_value("VERCEL_OIDC_TOKEN")- token = prompt(" Vercel access token", get_env_value("VERCEL_TOKEN") or "", password=True)- project = prompt(- " Vercel project ID",- get_env_value("VERCEL_PROJECT_ID") or linked_project.get("projectId", ""),- )- team = prompt(- " Vercel team ID",- get_env_value("VERCEL_TEAM_ID") or linked_project.get("orgId", ""),- )- if token:- save_env_value("VERCEL_TOKEN", token)- if project:- save_env_value("VERCEL_PROJECT_ID", project)- if team:- save_env_value("VERCEL_TEAM_ID", team)---def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:- """Read project/team defaults from the nearest Vercel link file."""- current = (start or Path.cwd()).resolve()- if current.is_file():- current = current.parent-- for directory in (current, *current.parents):- project_file = directory / ".vercel" / "project.json"- if not project_file.exists():- continue- try:- data = json.loads(project_file.read_text(encoding="utf-8-sig"))- except (OSError, json.JSONDecodeError):- return {}- if not isinstance(data, dict):- return {}- return {- key: value- for key, value in {- "projectId": data.get("projectId"),- "orgId": data.get("orgId"),- }.items()- if isinstance(value, str) and value.strip()- }- return {}--# Tool categories and provider config are now in tools_config.py (shared# between `hermes tools` and `hermes setup tools`).@@ -796,7 +413,6 @@ def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:# =============================================================================-def setup_model_provider(config: dict, *, quick: bool = False):"""Configure the inference provider and default model via the ``hermes model`` flow (one codepath — any provider added there is available here). *quick* is accepted for the first-time@@ -832,759 +448,6 @@ def _check_espeak_ng() -> bool:return shutil.which("espeak-ng") is not None or shutil.which("espeak") is not None-def _install_neutts_deps() -> bool:- """Install NeuTTS dependencies with user approval. Returns True on success."""- import subprocess- import sys-- # Check espeak-ng- if not _check_espeak_ng():- print()- print_warning("NeuTTS requires espeak-ng for phonemization.")- if sys.platform == "darwin":- print_info("Install with: brew install espeak-ng")- elif sys.platform == "win32":- print_info("Install with: choco install espeak-ng")- else:- print_info("Install with: sudo apt install espeak-ng")- print()- if prompt_yes_no("Install espeak-ng now?", True):- try:- if sys.platform == "darwin":- subprocess.run(["brew", "install", "espeak-ng"], check=True)- elif sys.platform == "win32":- subprocess.run(["choco", "install", "espeak-ng", "-y"], check=True)- else:- subprocess.run(["sudo", "apt", "install", "-y", "espeak-ng"], check=True)- print_success("espeak-ng installed")- except (subprocess.CalledProcessError, FileNotFoundError) as e:- print_warning(f"Could not install espeak-ng automatically: {e}")- print_info("Please install it manually and re-run setup.")- return False- else:- print_warning("espeak-ng is required for NeuTTS. Install it manually before using NeuTTS.")-- # Install neutts Python package- print()- print_info("Installing neutts Python package...")- print_info("This will also download the TTS model (~300MB) on first use.")- print()-- # Route through the canonical uv → pip → ensurepip ladder so pip-less- # venvs (Ubuntu 25.10 `python -m venv`, `uv venv`) work out of the box.- from hermes_cli.tools_config import _pip_install-- try:- result = _pip_install(["-U", "neutts[all]", "--quiet"], timeout=300)- except Exception as e:- print_error(f"Failed to install neutts: {e}")- print_info("Try manually: uv pip install -U 'neutts[all]'")- return False- if result.returncode == 0:- print_success("neutts installed successfully")- return True- err = (result.stderr or "").strip()- print_error(f"Failed to install neutts: {err[:300] if err else 'install failed'}")- print_info("Try manually: uv pip install -U 'neutts[all]'")- return False---def _install_kittentts_deps() -> bool:- """Install KittenTTS dependencies with user approval. Returns True on success."""-- wheel_url = (- "https://github.com/KittenML/KittenTTS/releases/download/"- "0.8.1/kittentts-0.8.1-py3-none-any.whl"- )- print()- print_info("Installing kittentts Python package (~25-80MB model downloaded on first use)...")- print()-- from hermes_cli.tools_config import _pip_install-- try:- result = _pip_install(["-U", wheel_url, "soundfile", "--quiet"], timeout=300)- except Exception as e:- print_error(f"Failed to install kittentts: {e}")- print_info(f"Try manually: uv pip install -U '{wheel_url}' soundfile")- return False- if result.returncode == 0:- print_success("kittentts installed successfully")- return True- err = (result.stderr or "").strip()- print_error(f"Failed to install kittentts: {err[:300] if err else 'install failed'}")- print_info(f"Try manually: uv pip install -U '{wheel_url}' soundfile")- return False---def _xai_oauth_logged_in_for_setup() -> bool:- """True iff xAI Grok OAuth credentials are already stored locally.-- Lets TTS / STT setup skip the API-key prompt for users who logged in- through ``hermes model`` -> xAI Grok OAuth (SuperGrok / Premium+).- """- try:- from hermes_cli.auth import get_xai_oauth_auth_status-- return bool(get_xai_oauth_auth_status().get("logged_in"))- except Exception:- return False---def _run_xai_oauth_login_from_setup() -> bool:- """Run the xAI Grok OAuth device-code login from inside the setup wizard.-- Saves OAuth tokens only. Does **not** switch the active inference- provider or rewrite ``model.provider`` — callers (TTS setup, tools- config) only need credentials for side tools.-- Returns True on success, False on any failure (the caller falls back- to whatever the user picked next, e.g. Edge TTS).- """- try:- from hermes_cli.auth import (- _is_remote_session,- _save_xai_oauth_tokens,- _xai_oauth_device_code_login,- unsuppress_credential_source,- )- except Exception as exc:- print_warning(f"xAI Grok OAuth helpers unavailable: {exc}")- return False-- open_browser = not _is_remote_session()- print()- print_info("Signing in to xAI Grok OAuth (SuperGrok / Premium+)...")- try:- creds = _xai_oauth_device_code_login(open_browser=open_browser)- _save_xai_oauth_tokens(- creds["tokens"],- discovery=creds.get("discovery"),- redirect_uri=creds.get("redirect_uri", ""),- last_refresh=creds.get("last_refresh"),- auth_mode="oauth_device_code",- set_active=False,- )- # Mirror model/dashboard re-login: clear device_code suppression so- # the pool can seed from the singleton after a prior `auth remove`.- unsuppress_credential_source("xai-oauth", "device_code")- return True- except Exception as exc:- print_warning(f"xAI Grok OAuth login failed: {exc}")- return False---def _setup_tts_provider(config: dict):- """Interactive TTS provider selection with install flow for NeuTTS."""- tts_config = config.get("tts", {})- current_provider = tts_config.get("provider", "edge")- subscription_features = get_nous_subscription_features(config)-- provider_labels = {- "edge": "Edge TTS",- "elevenlabs": "ElevenLabs",- "openai": "OpenAI TTS",- "xai": "xAI TTS",- "minimax": "MiniMax TTS",- "mistral": "Mistral Voxtral TTS",- "gemini": "Google Gemini TTS",- "neutts": "NeuTTS",- "kittentts": "KittenTTS",- }- current_label = provider_labels.get(current_provider, current_provider)-- print()- print_header("Text-to-Speech Provider (optional)")- print_info(f"Current: {current_label}")- print()-- choices = []- providers = []- if managed_nous_tools_enabled() and subscription_features.nous_auth_present:- choices.append("Nous Subscription (managed OpenAI TTS, billed to your subscription)")- providers.append("nous-openai")- choices.extend(- [- "Edge TTS (free, cloud-based, no setup needed)",- "ElevenLabs (premium quality, needs API key)",- "OpenAI TTS (good quality, needs API key)",- "xAI TTS (Grok voices — OAuth login or API key)",- "MiniMax TTS (high quality with voice cloning, needs API key)",- "Mistral Voxtral TTS (multilingual, native Opus, needs API key)",- "Google Gemini TTS (30 prebuilt voices, prompt-controllable, needs API key)",- "NeuTTS (local on-device, free, ~300MB model download)",- "KittenTTS (local on-device, free, lightweight ~25-80MB ONNX)",- ]- )- providers.extend(["edge", "elevenlabs", "openai", "xai", "minimax", "mistral", "gemini", "neutts", "kittentts"])- choices.append(f"Keep current ({current_label})")- keep_current_idx = len(choices) - 1- idx = prompt_choice("Select TTS provider:", choices, keep_current_idx)-- if idx == keep_current_idx:- return-- selected = providers[idx]- selected_via_nous = selected == "nous-openai"- if selected == "nous-openai":- selected = "openai"- print_info("OpenAI TTS will use the managed Nous gateway and bill to your subscription.")- if get_env_value("VOICE_TOOLS_OPENAI_KEY") or get_env_value("OPENAI_API_KEY"):- print_warning(- "Direct OpenAI credentials are still configured and may take precedence until removed from ~/.hermes/.env."- )-- if selected == "neutts":- # Check if already installed- try:- already_installed = importlib.util.find_spec("neutts") is not None- except Exception:- already_installed = False-- if already_installed:- print_success("NeuTTS is already installed")- else:- print()- print_info("NeuTTS requires:")- print_info(" • Python package: neutts (~50MB install + ~300MB model on first use)")- print_info(" • System package: espeak-ng (phonemizer)")- print()- if prompt_yes_no("Install NeuTTS dependencies now?", True):- if not _install_neutts_deps():- print_warning("NeuTTS installation incomplete. Falling back to Edge TTS.")- selected = "edge"- else:- print_info("Skipping install. Set tts.provider to 'neutts' after installing manually.")- selected = "edge"-- elif selected == "elevenlabs":- existing = get_env_value("ELEVENLABS_API_KEY")- if not existing:- print()- api_key = prompt("ElevenLabs API key", password=True)- if api_key:- save_env_value("ELEVENLABS_API_KEY", api_key)- print_success("ElevenLabs API key saved")- else:- print_warning("No API key provided. Falling back to Edge TTS.")- selected = "edge"-- elif selected == "openai" and not selected_via_nous:- existing = get_env_value("VOICE_TOOLS_OPENAI_KEY") or get_env_value("OPENAI_API_KEY")- if not existing:- print()- api_key = prompt("OpenAI API key for TTS", password=True)- if api_key:- save_env_value("VOICE_TOOLS_OPENAI_KEY", api_key)- print_success("OpenAI TTS API key saved")- else:- print_warning("No API key provided. Falling back to Edge TTS.")- selected = "edge"-- elif selected == "xai":- # Resolution order: existing OAuth tokens (free for SuperGrok subscribers- # via the Hermes auth store) > existing XAI_API_KEY > prompt the user.- # When neither is configured, offer both options instead of forcing the- # API-key path — xAI TTS works fine with OAuth bearer tokens too.- oauth_logged_in = _xai_oauth_logged_in_for_setup()- existing_api_key = get_env_value("XAI_API_KEY")-- if oauth_logged_in:- print_success(- "xAI TTS will use your xAI Grok OAuth (SuperGrok / Premium+) "- "credentials"- )- elif existing_api_key:- print_success("xAI TTS will use your existing XAI_API_KEY")- else:- print()- choice_idx = prompt_choice(- "How do you want xAI TTS to authenticate?",- choices=[- "Sign in with xAI Grok OAuth (SuperGrok / Premium+) — browser login",- "Paste an xAI API key (console.x.ai)",- "Skip → fallback to Edge TTS",- ],- default=0,- )- if choice_idx == 0:- if _run_xai_oauth_login_from_setup():- print_success(- "Logged in — xAI TTS will use these OAuth credentials"- )- else:- print_warning(- "xAI Grok OAuth login did not complete. "- "Falling back to Edge TTS."- )- selected = "edge"- elif choice_idx == 1:- api_key = prompt("xAI API key for TTS", password=True)- if api_key:- save_env_value("XAI_API_KEY", api_key)- print_success("xAI TTS API key saved")- else:- from hermes_constants import display_hermes_home as _dhh- print_warning(- "No xAI API key provided for TTS. Configure XAI_API_KEY "- f"via hermes setup model or {_dhh()}/.env to use xAI TTS. "- "Falling back to Edge TTS."- )- selected = "edge"- else:- print_warning("xAI TTS skipped. Falling back to Edge TTS.")- selected = "edge"-- if selected == "xai":- print()- voice_id = prompt("xAI voice_id (Enter for 'eve', or paste a custom voice ID)")- if voice_id and voice_id.strip():- config.setdefault("tts", {}).setdefault("xai", {})["voice_id"] = voice_id.strip()- print_success(f"xAI voice_id set to: {voice_id.strip()}")--- elif selected == "minimax":- existing = get_env_value("MINIMAX_API_KEY")- if not existing:- print()- api_key = prompt("MiniMax API key for TTS", password=True)- if api_key:- save_env_value("MINIMAX_API_KEY", api_key)- print_success("MiniMax TTS API key saved")- else:- print_warning("No API key provided. Falling back to Edge TTS.")- selected = "edge"-- elif selected == "mistral":- existing = get_env_value("MISTRAL_API_KEY")- if not existing:- print()- api_key = prompt("Mistral API key for TTS", password=True)- if api_key:- save_env_value("MISTRAL_API_KEY", api_key)- print_success("Mistral TTS API key saved")- else:- print_warning("No API key provided. Falling back to Edge TTS.")- selected = "edge"-- elif selected == "gemini":- existing = get_env_value("GEMINI_API_KEY") or get_env_value("GOOGLE_API_KEY")- if not existing:- print()- print_info("Get a free API key at https://aistudio.google.com/app/apikey")- api_key = prompt("Gemini API key for TTS", password=True)- if api_key:- save_env_value("GEMINI_API_KEY", api_key)- print_success("Gemini TTS API key saved")- else:- print_warning("No API key provided. Falling back to Edge TTS.")- selected = "edge"-- elif selected == "kittentts":- # Check if already installed- try:- already_installed = importlib.util.find_spec("kittentts") is not None- except Exception:- already_installed = False-- if already_installed:- print_success("KittenTTS is already installed")- else:- print()- print_info("KittenTTS is lightweight (~25-80MB, CPU-only, no API key required).")- print_info("Voices: Jasper, Bella, Luna, Bruno, Rosie, Hugo, Kiki, Leo")- print()- if prompt_yes_no("Install KittenTTS now?", True):- if not _install_kittentts_deps():- print_warning("KittenTTS installation incomplete. Falling back to Edge TTS.")- selected = "edge"- else:- print_info("Skipping install. Set tts.provider to 'kittentts' after installing manually.")- selected = "edge"-- # Save the selection- if "tts" not in config:- config["tts"] = {}- config["tts"]["provider"] = selected- save_config(config)- print_success(f"TTS provider set to: {provider_labels.get(selected, selected)}")---def setup_tts(config: dict):- """Standalone TTS setup (for 'hermes setup tts')."""- _setup_tts_provider(config)---# =============================================================================-# Section 2: Terminal Backend Configuration-# =============================================================================---def setup_terminal_backend(config: dict):- """Configure the terminal execution backend."""- import platform as _platform- print_header("Terminal Backend")- print_info("Choose where Hermes runs shell commands and code.")- print_info("This affects tool execution, file access, and isolation.")- print_info(f" Guide: {_DOCS_BASE}/user-guide/configuration#terminal-backend-configuration")- print()-- current_backend = cfg_get(config, "terminal", "backend", default="local")- is_linux = _platform.system() == "Linux"-- # Build backend choices with descriptions- terminal_choices = [- "Local - run directly on this machine (default)",- "Docker - isolated container with configurable resources",- "Modal - serverless cloud sandbox",- "SSH - run on a remote machine",- "Daytona - persistent cloud development environment",- "Vercel Sandbox - cloud microVM with snapshot filesystem persistence",- ]- idx_to_backend = {0: "local", 1: "docker", 2: "modal", 3: "ssh", 4: "daytona", 5: "vercel_sandbox"}- backend_to_idx = {"local": 0, "docker": 1, "modal": 2, "ssh": 3, "daytona": 4, "vercel_sandbox": 5}-- next_idx = 6- if is_linux:- terminal_choices.append("Singularity/Apptainer - HPC-friendly container")- idx_to_backend[next_idx] = "singularity"- backend_to_idx["singularity"] = next_idx- next_idx += 1-- # Plugin-registered terminal backends (standalone plugin repos installed- # under ~/.hermes/plugins/). Fail-soft: a broken plugin must not take the- # setup wizard down.- plugin_backend_names = []- try:- from hermes_cli.plugins import discover_plugins-- discover_plugins() # idempotent — plugin state may not be loaded yet- from agent.terminal_env_registry import list_providers-- for _provider in list_providers():- _pname = _provider.name.strip().lower()- terminal_choices.append(f"{_provider.display_name} - {_provider.description}")- idx_to_backend[next_idx] = _pname- backend_to_idx[_pname] = next_idx- plugin_backend_names.append(_pname)- next_idx += 1- except Exception:- pass-- # Add keep current option- keep_current_idx = next_idx- terminal_choices.append(f"Keep current ({current_backend})")- idx_to_backend[keep_current_idx] = current_backend-- terminal_idx = prompt_choice(- "Select terminal backend:", terminal_choices, keep_current_idx- )-- selected_backend = idx_to_backend.get(terminal_idx)-- if terminal_idx == keep_current_idx:- print_info(f"Keeping current backend: {current_backend}")- return-- config.setdefault("terminal", {})["backend"] = selected_backend-- if selected_backend == "local":- print_success("Terminal backend: Local")- print_info("Commands run directly on this machine.")- # Gateway working directory defaults to home; sudo stays off. Both are- # configurable later via `hermes setup terminal` / config.yaml.- config["terminal"].setdefault("cwd", str(Path.home()))-- elif selected_backend == "docker":- print_success("Terminal backend: Docker")-- # Check if Docker is available- docker_bin = shutil.which("docker")- if not docker_bin:- print_warning("Docker not found in PATH!")- print_info("Install Docker: https://docs.docker.com/get-docker/")- else:- print_info(f"Docker found: {docker_bin}")-- # Image and resource limits use defaults; tune via `hermes setup terminal`.- config["terminal"].setdefault(- "docker_image", "nikolaik/python-nodejs:python3.11-nodejs20"- )- print()- print_info("Docker sandboxes can be protected with the egress credential firewall.")- print_info(- "It routes sandbox traffic through iron-proxy so containers receive "- "proxy tokens instead of real API keys."- )- print_info(- " Docker only for now; Modal, SSH, Daytona, and Singularity are not wired yet."- )- if prompt_yes_no(" Enable egress firewall for Docker sandboxes?", False):- proxy_cfg = config.setdefault("proxy", {})- proxy_cfg["enabled"] = True- proxy_cfg.setdefault("enforce_on_docker", True)- print_success("Egress firewall enabled in config")- print_info(- "Run `hermes egress setup` then `hermes egress start` to mint "- "tokens and launch the proxy."- )- else:- print_info(- "Skipping egress firewall. You can enable it later with `hermes egress setup`."- )-- elif selected_backend == "singularity":- print_success("Terminal backend: Singularity/Apptainer")-- # Check if singularity/apptainer is available- sing_bin = shutil.which("apptainer") or shutil.which("singularity")- if not sing_bin:- print_warning("Singularity/Apptainer not found in PATH!")- print_info(- "Install: https://apptainer.org/docs/admin/main/installation.html"- )- else:- print_info(f"Found: {sing_bin}")-- # Image and resource limits use defaults; tune via `hermes setup terminal`.- config["terminal"].setdefault(- "singularity_image",- "docker://nikolaik/python-nodejs:python3.11-nodejs20",- )-- elif selected_backend == "modal":- print_success("Terminal backend: Modal")- print_info("Serverless cloud sandboxes. Each session gets its own container.")- from tools.managed_tool_gateway import is_managed_tool_gateway_ready- from tools.tool_backend_helpers import normalize_modal_mode-- managed_modal_available = bool(- managed_nous_tools_enabled()- and- get_nous_subscription_features(config).nous_auth_present- and is_managed_tool_gateway_ready("modal")- )- modal_mode = normalize_modal_mode(cfg_get(config, "terminal", "modal_mode"))- use_managed_modal = False- if managed_modal_available:- modal_choices = [- "Use my Nous subscription",- "Use my own Modal account",- ]- if modal_mode == "managed":- default_modal_idx = 0- elif modal_mode == "direct":- default_modal_idx = 1- else:- default_modal_idx = 1 if get_env_value("MODAL_TOKEN_ID") else 0- modal_mode_idx = prompt_choice(- "Select how Modal execution should be billed:",- modal_choices,- default_modal_idx,- )- use_managed_modal = modal_mode_idx == 0-- if use_managed_modal:- config["terminal"]["modal_mode"] = "managed"- print_info("Modal execution will use the managed Nous gateway and bill to your subscription.")- if get_env_value("MODAL_TOKEN_ID") or get_env_value("MODAL_TOKEN_SECRET"):- print_info(- "Direct Modal credentials are still configured, but this backend is pinned to managed mode."- )- else:- config["terminal"]["modal_mode"] = "direct"- print_info("Requires a Modal account: https://modal.com")-- # Check if modal SDK is installed- try:- __import__("modal")- except ImportError:- print_info("Installing modal SDK...")- from hermes_cli.tools_config import _pip_install-- result = _pip_install(["modal"])- if result.returncode == 0:- print_success("modal SDK installed")- else:- print_warning("Install failed — run manually: uv pip install modal")-- # Modal token- print()- print_info("Modal authentication:")- print_info(" Get your token at: https://modal.com/settings")- existing_token = get_env_value("MODAL_TOKEN_ID")- if existing_token:- print_info(" Modal token: already configured")- if prompt_yes_no(" Update Modal credentials?", False):- token_id = prompt(" Modal Token ID", password=True)- token_secret = prompt(" Modal Token Secret", password=True)- if token_id:- save_env_value("MODAL_TOKEN_ID", token_id)- if token_secret:- save_env_value("MODAL_TOKEN_SECRET", token_secret)- else:- token_id = prompt(" Modal Token ID", password=True)- token_secret = prompt(" Modal Token Secret", password=True)- if token_id:- save_env_value("MODAL_TOKEN_ID", token_id)- if token_secret:- save_env_value("MODAL_TOKEN_SECRET", token_secret)-- elif selected_backend == "daytona":- print_success("Terminal backend: Daytona")- print_info("Persistent cloud development environments.")- print_info("Each session gets a dedicated sandbox with filesystem persistence.")- print_info("Sign up at: https://daytona.io")-- # Check if daytona SDK is installed- try:- __import__("daytona")- except ImportError:- print_info("Installing daytona SDK...")- from hermes_cli.tools_config import _pip_install-- result = _pip_install(["daytona"])- if result.returncode == 0:- print_success("daytona SDK installed")- else:- print_warning("Install failed — run manually: uv pip install daytona")- if result.stderr:- print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")-- # Daytona API key- print()- existing_key = get_env_value("DAYTONA_API_KEY")- if existing_key:- print_info(" Daytona API key: already configured")- if prompt_yes_no(" Update API key?", False):- api_key = prompt(" Daytona API key", password=True)- if api_key:- save_env_value("DAYTONA_API_KEY", api_key)- print_success(" Updated")- else:- api_key = prompt(" Daytona API key", password=True)- if api_key:- save_env_value("DAYTONA_API_KEY", api_key)- print_success(" Configured")-- # Image and resource limits use defaults; tune via `hermes setup terminal`.- config["terminal"].setdefault(- "daytona_image", "nikolaik/python-nodejs:python3.11-nodejs20"- )-- elif selected_backend == "vercel_sandbox":- print_success("Terminal backend: Vercel Sandbox")- print_info("Cloud microVM sandboxes with snapshot-backed filesystem persistence.")- print_info("Requires the optional SDK: pip install 'hermes-agent[vercel]'")-- try:- __import__("vercel")- except ImportError:- print_info("Installing vercel SDK...")- import subprocess-- # Managed uv first: the store is never on PATH, so a bare- # which() misses the uv Hermes installed. Realizing one is- # welcome here — this is the interactive setup wizard, already- # mid-install, and the alternative tier is a pip that a `uv venv`- # venv may not even have.- import pm-- uv_bin, uv_env = pm.uv()- if uv_bin:- result = subprocess.run(- [uv_bin, "pip", "install", "--python", sys.executable, "vercel"],- capture_output=True,- text=True,- env=uv_env,- )- else:- result = subprocess.run(- [sys.executable, "-m", "pip", "install", "vercel"],- capture_output=True,- text=True,- )- if result.returncode == 0:- print_success("vercel SDK installed")- else:- print_warning("Install failed — run manually: pip install 'hermes-agent[vercel]'")- if result.stderr:- print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")-- _prompt_vercel_sandbox_settings(config)-- elif selected_backend in plugin_backend_names:- try:- from agent.terminal_env_registry import get_provider-- _provider = get_provider(selected_backend)- print_success(f"Terminal backend: {_provider.display_name}")- for _line in _provider.setup_instructions():- print_info(_line)- _provider.post_setup()- except Exception as exc:- print_warning(f"Backend plugin setup hook failed: {exc}")-- elif selected_backend == "ssh":- print_success("Terminal backend: SSH")- print_info("Run commands on a remote machine via SSH.")-- # SSH host- current_host = get_env_value("TERMINAL_SSH_HOST") or ""- host = prompt(" SSH host (hostname or IP)", current_host)- if host:- save_env_value("TERMINAL_SSH_HOST", host)-- # SSH user- current_user = get_env_value("TERMINAL_SSH_USER") or ""- user = prompt(" SSH user", current_user or os.getenv("USER", ""))- if user:- save_env_value("TERMINAL_SSH_USER", user)-- # SSH port- current_port = get_env_value("TERMINAL_SSH_PORT") or "22"- port = prompt(" SSH port", current_port)- if port and port != "22":- save_env_value("TERMINAL_SSH_PORT", port)-- # SSH key- current_key = get_env_value("TERMINAL_SSH_KEY") or ""- default_key = str(Path.home() / ".ssh" / "id_rsa")- ssh_key = prompt(" SSH private key path", current_key or default_key)- if ssh_key:- save_env_value("TERMINAL_SSH_KEY", ssh_key)-- # Test connection- if host and prompt_yes_no(" Test SSH connection?", True):- print_info(" Testing connection...")- import subprocess-- ssh_cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5"]- if ssh_key:- ssh_cmd.extend(["-i", ssh_key])- if port and port != "22":- ssh_cmd.extend(["-p", port])- ssh_cmd.append(f"{user}@{host}" if user else host)- ssh_cmd.append("echo ok")- result = subprocess.run(ssh_cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)- if result.returncode == 0:- print_success(" SSH connection successful!")- else:- print_warning(f" SSH connection failed: {result.stderr.strip()}")- print_info(" Check your SSH key and host settings.")-- # Sync terminal backend to .env so terminal_tool picks it up directly.- # config.yaml is the source of truth, but terminal_tool reads TERMINAL_ENV.- save_env_value("TERMINAL_ENV", selected_backend)- if selected_backend == "modal":- save_env_value("TERMINAL_MODAL_MODE", config["terminal"].get("modal_mode", "auto"))- if selected_backend == "vercel_sandbox":- save_env_value("TERMINAL_VERCEL_RUNTIME", config["terminal"].get("vercel_runtime", "node24"))- save_config(config)- print()- print_success(f"Terminal backend set to: {selected_backend}")--# =============================================================================# Section 3: Agent Settings# =============================================================================diff --git a/hermes_cli/setup_terminal.py b/hermes_cli/setup_terminal.pyindex cc3cede674b..f938667f95b 100644--- a/hermes_cli/setup_terminal.py+++ b/hermes_cli/setup_terminal.py@@ -103,8 +103,11 @@ def _pip_install_vercel(package):"""uv when Hermes has one ($HERMES_HOME/bin is never on PATH, so which() misses it andbootstrapping mid-wizard is fine), else pip — a `uv venv` venv may not even have pip."""import subprocess- from hermes_cli.managed_uv import ensure_uv- uv_bin = ensure_uv()++ from pm.ensure import uv as pm_uv++ # Missing uv can be provisioned by PM during setup.+ uv_bin, _ = pm_uv(realize=True)cmd = ([uv_bin, "pip", "install", "--python", sys.executable, package] if uv_binelse [sys.executable, "-m", "pip", "install", package])return subprocess.run(cmd, **_RUN_KW)diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.pyindex 25637d6c9bc..659651b9213 100644--- a/hermes_cli/subcommands/gateway.py+++ b/hermes_cli/subcommands/gateway.py@@ -61,17 +61,6 @@ def build_gateway_parser("corrupt shared gateway state."),)- gateway_run.add_argument(- "--service",- action="store_true",- help=(- "Windows SCM frontend mode: run as the HermesGateway Windows "- "Service (started by the Service Control Manager; spawns the "- "real gateway as a child and reports STOP via the graceful "- "planned-stop path). Not for interactive use — the SCM invokes "- "this, or `hermes gateway service on` does."- ),- )gateway_run.add_argument("--no-supervise",action="store_true",@@ -116,21 +105,6 @@ def build_gateway_parser(_add_system_flag(gateway_status)_add_compat_platform_flag(gateway_status)- # gateway service (MSIX HermesGateway Windows Service — the SCM one)- gateway_service = gateway_subparsers.add_parser(- "service",- help="Manage the HermesGateway Windows Service (MSIX installs)",- description=(- "The bundled MSIX installs a HermesGateway Windows Service "- "(demand-start, stopped). 'on' = automatic at logon + start "- "now; 'off' = demand + stop; 'status' = SCM state + config."- ),- )- gateway_service_sub = gateway_service.add_subparsers(dest="gateway_service_action")- gateway_service_sub.add_parser("on", help="Enable: automatic at logon + start now")- gateway_service_sub.add_parser("off", help="Disable: demand-start + stop now")- gateway_service_sub.add_parser("status", help="Show SCM state + config key")-# gateway installgateway_install = gateway_subparsers.add_parser("install", help="Install gateway as a systemd/launchd background service")diff --git a/hermes_cli/tools_config_cua.py b/hermes_cli/tools_config_cua.pyindex a6abef75363..5afdd6fb5e8 100644--- a/hermes_cli/tools_config_cua.py+++ b/hermes_cli/tools_config_cua.py@@ -149,14 +149,14 @@ def _pip_install(args: List[str], *, timeout: int = 300, capture_output: bool =venv_root = Path(sys.executable).parent.parentinstall_flags = _post_setup_no_window_flags(streams_to_console=not capture_output)- # Managed uv first: $HERMES_HOME/bin is never on PATH, so a bare which() misses the uv Hermes- # installed; ensure_uv() (not a pure lookup) because installing uv is in scope during setup.- from hermes_cli.managed_uv import ensure_uv- uv_bin = ensure_uv()+ # Resolve uv and its target environment through PM, not ambient PATH.+ from pm.ensure import uv as pm_uv++ uv_bin, uv_env = pm_uv(realize=True, venv=venv_root)try: # a failed uv run falls through to pip — it may have failed for a reason pip can handleresult = uv_bin and _run_text([uv_bin, "pip", "install", *args], timeout=timeout,capture_output=capture_output, creationflags=install_flags,- env={**os.environ, "VIRTUAL_ENV": str(venv_root)})+ env=uv_env)if result and result.returncode == 0:return resultexcept (subprocess.TimeoutExpired, FileNotFoundError):diff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.pyindex b2381536e19..9233491675b 100644--- a/hermes_cli/uninstall.py+++ b/hermes_cli/uninstall.py@@ -119,7 +119,7 @@ def find_shell_configs() -> list:def remove_path_from_shell_configs():"""Remove Hermes PATH entries from shell configuration files."""removed_from = []- for config_path in (c for c in (Path.home() / n for n in _SHELL_RC_NAMES) if c.exists()):+ for config_path in find_shell_configs():try:content = config_path.read_text(encoding="utf-8-sig")original_content = content@@ -222,7 +222,10 @@ def remove_node_symlinks(hermes_home: Path) -> list:# 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()- return _unlink_if(target == node_dir or node_dir in target.parents, link)+ if target != node_dir and node_dir not in target.parents:+ return False+ link.unlink()+ return Truecandidates = (bin_dir / name for name in ("node", "npm", "npx") for bin_dir in _node_symlink_candidate_dirs())return _remove_each(candidates, _unlink_ours)@@ -251,10 +254,13 @@ def uninstall_gateway_service():except Exception as e:log_warn(f"Could not check for gateway processes: {e}")- system = platform.system()+ # Termux/Android has no systemd and no launchd — nothing left to do.+ if os.getenv("TERMUX_VERSION") or "com.termux/files/usr" in os.getenv("PREFIX", ""):+ return stopped_something- # 2. Linux: uninstall systemd services (both user and system scopes)- if system == "Linux":+ # 2. Per-platform service removal (systemd / launchd / Scheduled Task).+ remover, warn_label = _GATEWAY_SERVICE_REMOVERS.get(platform.system(), (None, ""))+ if remover is not None:try:stopped_something = remover() or stopped_somethingexcept Exception as e:@@ -899,7 +905,7 @@ def _perform_uninstall(lambda: remove_portable_tooling_windows(hermes_home), "Removed {}","No Windows installer artifacts to remove")- # 4b. Remove managed-runtime trees a PRE-SPLIT install left in+ # 4c. Remove managed-runtime trees a PRE-SPLIT install left in# HERMES_HOME. Current installs keep these inside the checkout, so# step 4 already removed them — but a checkout outside the home# (~/src/hermes-agent) used to leave its node/uv behind, surviving@@ -914,21 +920,6 @@ def _perform_uninstall(else:log_info("No legacy runtime trees to remove")- # 4c. Remove Windows-only installer artifacts that are NOT user data:- # PortableGit, bundled Node, gateway-service dir. Installer put them- # under HERMES_HOME but they're install tooling, not config — safe to- # remove even in "keep data" mode. If we're doing a full uninstall- # the step-5 rmtree(hermes_home) would sweep them anyway; calling- # this helper there is a no-op since they'll already be gone.- if _is_windows():- log_info("Removing Windows installer artifacts (PortableGit, Node, gateway-service)...")- removed_artifacts = remove_portable_tooling_windows(hermes_home)- if removed_artifacts:- for path in removed_artifacts:- log_success(f"Removed {path}")- else:- log_info("No Windows installer artifacts to remove")-# 5. Optionally remove ~/.hermes/ data directory (and named profiles)if full_uninstall:# 5a. Named profiles' homes live under <default>/profiles/ (swept by the rmtree below),@@ -1022,29 +1013,3 @@ def main(argv=None) -> int:if __name__ == "__main__":sys.exit(main())---# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) -----# Names external plugins imported from this module before the Sep 2026 decomposition.-# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).-# The whole block is removed by reverting the commit that added it.--def find_shell_configs() -> list:- """Find shell configuration files that might have PATH entries."""- home = Path.home()- configs = []-- candidates = [- home / ".bashrc",- home / ".bash_profile",- home / ".profile",- home / ".zshrc",- home / ".zprofile",- ]-- for config in candidates:- if config.exists():- configs.append(config)-- return configs-# ---- END PLUGIN-COMPAT ----diff --git a/hermes_cli/update_channel.py b/hermes_cli/update_channel.pyindex 7167904d65a..0c8e6f3082d 100644--- a/hermes_cli/update_channel.py+++ b/hermes_cli/update_channel.py@@ -32,10 +32,11 @@ installers and boot paths read it before the full config machinery loads.from __future__ import annotations-import hashlib+from hermes_cli.runtime_paths import install_key, installs_rootimport loggingimport osimport re+import sysfrom pathlib import Pathfrom typing import Any, Optional@@ -74,32 +75,6 @@ def canary_tag_for_date(version: str, date_utc: str) -> str:return f"v{major}.{minor}.{patch + 1}-canary.{date_utc}"-def _install_key_sha16(project_root: Path) -> str:- """sha16 of the canonical install-root PATH.-- NOTE: dedupe with ``boot_bootstrap._install_key`` at assembly — this- is a byte-identical inline copy (sha256 of the resolved root, first 16- hex chars). Lane w2a ports boot_bootstrap in parallel; this module must- not import from it until both land.- """- try:- canonical = str(Path(project_root).resolve())- except OSError:- canonical = str(project_root)- return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]---def _installs_root() -> Path:- """The parent of every per-install state folder.-- NOTE: dedupe with ``boot_bootstrap.installs_root`` at assembly —- anchored to the DEFAULT home (profiles share one folder per install).- """- from hermes_cli.profiles import _get_default_hermes_home-- return _get_default_hermes_home() / "installs"--def _default_root() -> Path:"""This process's install root.@@ -118,7 +93,7 @@ def install_id(project_root: Optional[Path] = None) -> str:"""if project_root is None:project_root = _default_root()- return _install_key_sha16(Path(project_root))+ return install_key(Path(project_root))def _read_stamp(root: Path) -> dict:@@ -230,38 +205,119 @@ def set_install_channel(def _write_channel_record(sha16: str, path: str, channel: str) -> None:- """Write ``update.installs.<sha16>`` into config.yaml, preserving the rest."""- import yaml+ """Write ``update.installs.<sha16>`` into config.yaml, preserving the rest.++ Persists through the shared comment-preserving atomic writer+ (:func:`utils.atomic_roundtrip_yaml_update` — the same ruamel round-trip+ path ``hermes config set`` uses), fail-closed via+ :func:`hermes_cli.config.require_readable_config_before_write`. Malformed+ ``update`` / ``update.installs`` values are refused, never replaced —+ the dotted writer would otherwise turn a scalar into a mapping and+ destroy whatever the user had there.+ """+ from utils import atomic_roundtrip_yaml_update- from hermes_cli.config import get_config_path+ from hermes_cli.config import (+ get_config_path,+ require_readable_config_before_write,+ )config_path = get_config_path()- try:- raw = yaml.safe_load(config_path.read_text(encoding="utf-8-sig")) or {}- except FileNotFoundError:- raw = {}- if not isinstance(raw, dict):- raise ValueError(f"config at {config_path} is not a mapping")-- update_cfg = raw.setdefault("update", {})- if not isinstance(update_cfg, dict):+ existing = require_readable_config_before_write(config_path)+ update_cfg = existing.get("update")+ if update_cfg is not None and not isinstance(update_cfg, dict):raise ValueError("config key 'update' is not a mapping")- installs = update_cfg.setdefault("installs", {})- if not isinstance(installs, dict):+ installs = update_cfg.get("installs") if isinstance(update_cfg, dict) else None+ if installs is not None and not isinstance(installs, dict):raise ValueError("config key 'update.installs' is not a mapping")- record = installs.setdefault(sha16, {})- if not isinstance(record, dict):- record = {}- installs[sha16] = record- record["path"] = path # DATA, for humans + doctor GC- record["channel"] = channel-- config_path.parent.mkdir(parents=True, exist_ok=True)- tmp = config_path.with_suffix(config_path.suffix + ".tmp")- tmp.write_text(- yaml.safe_dump(raw, sort_keys=False, allow_unicode=True), encoding="utf-8"- )- tmp.replace(config_path)+ record = installs.get(sha16) if isinstance(installs, dict) else None+ new_record = dict(record) if isinstance(record, dict) else {}+ new_record["path"] = path # DATA, for humans + doctor GC+ new_record["channel"] = channel+ atomic_roundtrip_yaml_update(config_path, f"update.installs.{sha16}", new_record)+++def _stable_wait_target(canary_version: str) -> str:+ """The stable release a canary install waits for: the canary's own base+ version (canary is current-stable patch+1; ``v0.28.0`` from+ ``v0.28.0-canary.20260818171926``)."""+ base = re.sub(r"-canary\.\d+$", "", canary_version.strip())+ return base if base.startswith("v") else f"v{base}"+++def _stamp_channel_hint(stamp: dict) -> Optional[str]:+ """The channel the RUNNING artifact implies, for stamps without a clean+ ``tag`` (desktop About-page stamps carry ``displayVersion`` like+ ``0.28.0-canary.20260818`` — the ``v`` prefix ``is_canary_tag`` requires+ is restored before the shape check, so validation stays with the single+ canary authority). Switch text only; resolution stays with+ :func:`resolve_update_channel`."""+ if stamp.get("updateMechanism") != "electron-updater":+ return None+ version = str(stamp.get("tag") or stamp.get("displayVersion") or "")+ if not version:+ return None+ candidate = version if version.startswith("v") else f"v{version}"+ return CHANNEL_CANARY if is_canary_tag(candidate) else None+++def _set_channel_from_cli(channel: str) -> None:+ """Persist ``--set-channel`` and print the switch text. Never updates.++ Runs before the update lock, git, network, backups, or process pause:+ this is a configuration action, not an update. The reported previous+ channel prefers the stored per-install record over what the running+ artifact implies.+ """+ from hermes_cli.config import read_raw_config++ root = _default_root()+ stamp = _read_stamp(root)+ stored = channel_record(read_raw_config(), root).get("channel")+ if isinstance(stored, str) and stored.strip().lower() in VALID_CHANNELS:+ previous = stored.strip().lower()+ else:+ previous = _stamp_channel_hint(stamp) or resolve_update_channel(None, root)+ try:+ sha16 = set_install_channel(channel, root)+ except ValueError as exc:+ print(f"error: {exc}")+ sys.exit(1)++ print(f"Channel set to '{channel}' (was '{previous}') for install {sha16}.")+ version = str(stamp.get("tag") or stamp.get("displayVersion") or "")+ if previous == CHANNEL_CANARY and channel == CHANNEL_STABLE:+ print(f" You are on canary build {version}.")+ print(+ f" Stable updates begin at { _stable_wait_target(version) } —"+ " canary outversions it until that release ships."+ )+ print(" Not patient? Switch back: hermes update --set-channel canary")+ print(" Docs: https://hermes-agent.nousresearch.com")+ elif channel == CHANNEL_CANARY:+ print(+ " Canary builds are forward-incompatible: a canary install"+ " only updates to artifacts that ship after it. Downgrading"+ " means reinstalling."+ )+ sys.exit(0)+++def handle_channel_flags(args) -> None:+ """Preflight for the informational update flags.++ ``--install-id`` prints this install's id and path; ``--set-channel``+ atomically persists a valid channel record. Both terminate the command+ here — the caller never reaches the update lock, git, network, backup,+ or process-pause paths.+ """+ if getattr(args, "install_id", False):+ root = _default_root()+ print(f"{install_id(root)} {root}")+ sys.exit(0)+ channel = getattr(args, "set_channel", None)+ if channel:+ _set_channel_from_cli(channel)def stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]:@@ -290,7 +346,7 @@ def stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]if not path.exists():stale.append((sha16, record, "missing"))continue- if _install_key_sha16(path) != sha16:+ if install_key(path) != sha16:stale.append((sha16, record, "replaced"))continue@@ -298,7 +354,7 @@ def stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]# record whose sha16 has no installs/<sha16>/install.json was# either hand-written or its install never booted post-record.try:- if not (_installs_root() / sha16 / "install.json").is_file():+ if not (installs_root() / sha16 / "install.json").is_file():stale.append((sha16, record, "unclaimed"))except Exception as exc: # noqa: BLE001 — doctor sweep must not raiselogger.debug("installs root unavailable: %s", exc)diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 567a1d2cbfb..9796df111ef 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1,45 +1,115 @@-"""Hermes update pipeline — extracted from ``hermes_cli/main.py``.--Mechanical move (main.py decomposition): ``_cmd_update_impl``, ``_cmd_update_check``-and every module-level helper used only by the update path, plus the update-only-constants they read. Function bodies are lifted verbatim; the only mechanical-change is that references to helpers/constants that STAY in ``hermes_cli.main``-(and to moved-but-test-patched siblings) are routed through ``_m()`` — a lazy-``hermes_cli.main`` reference — so existing call sites and test monkeypatches-that target ``hermes_cli.main.<name>`` (``PROJECT_ROOT``, ``_is_windows``,-``_run_pre_update_backup``, ...) keep working unchanged. ``main.py`` re-imports-every public-ish name from here (``# noqa: F401``) so the argparse wiring and-the test-patch surface still resolve on ``hermes_cli.main``.--Three self-contained closures nested inside ``_cmd_update_impl``-(``_print_items``, ``_wait_for_service_active``, ``_service_restart_sec``) were-hoisted to module level; they capture no enclosing state (verified via-``symtable``). ``_restart_one_systemd_gateway_unit``, ``_resolve_manage_cmd``-and ``_on_unit_timeout`` DO capture enclosing locals and stay nested,-byte-identical.--Imports are one-way: ``hermes_cli.main`` imports this module, never the reverse-at import time (``_m()`` resolves lazily at call time, when main.py is fully-loaded, so there is no import cycle).+"""Hermes update pipeline: dispatchers (``_cmd_update_impl``/``_cmd_update_check``) + git plumbing.++Each concern lives in ``update_cmd_<concern>.py`` and is re-imported here so+``hermes_cli.update_cmd.<name>`` keeps resolving (and stays monkeypatchable). Imports are one-way:+main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at call time."""-import hashlib-import jsonimport logging+from contextlib import suppressimport osimport reimport shlex-import shutil+import shutil # noqa: F401 (tests patch update_cmd.shutil.*; split modules resolve it here)import subprocessimport sysimport time as _time-from datetime import datetime+from dataclasses import dataclassfrom pathlib import Path-from typing import Optional-from hermes_cli.config import get_hermes_home+from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)+from hermes_cli.update_cmd_common import _best_effortfrom hermes_constants import get_default_hermes_root, venv_python_path+# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.+from hermes_cli.update_abort_recovery import ( # noqa: F401+ _abort_recovery_is_complete, _qualified_serve_skips, _recover_gateway_restart_after_abort,+ _serve_unit_recovery_available, _surviving_pre_update_serve_runtimes,+ _warn_stale_serve_runtimes)+from hermes_cli.update_cmd_windows import ( # noqa: F401+ _HOLDER_VALUE_FLAGS_FALLBACK, _clear_windows_venv_holders_or_exit,+ _cold_start_windows_gateway_after_update, _desktop_owns_gateway_lifecycle,+ _detect_venv_python_processes, _format_venv_python_holders_message,+ _handoff_reapable_backend_pids, _hermes_holder_subcommand, _holder_value_flags,+ _holder_value_flags_cache, _ledger_manual_serve_holders, _ledger_reapable_backend_pids,+ _leftover_pausable_gateway_pids, _looks_like_desktop_control_plane,+ _orphaned_desktop_backend_pids, _pause_windows_gateways_for_update,+ _refresh_bootstrap_cache_scripts, _refresh_windows_gateway_launchers,+ _refuse_gateway_ancestor_tree_kill, _relaunch_stopped_serves,+ _restore_windows_gateway_service, _resume_windows_gateways_after_update,+ _resume_windows_gateways_and_merge_outcome, _self_and_non_gateway_ancestor_pids,+ _serve_relaunch_commands, _start_windows_gateway_service, _stop_process_trees,+ _stop_windows_gateway_service, _venv_launcher_ancestors,+ _wait_for_windows_update_gateway_exit, _write_update_planned_stop_marker)+from hermes_cli.update_cmd_fleet import ( # noqa: F401+ _FLEET_RESTART_PENDING_NAME, _FRESH_RESTART_SUPERVISORS, _GatewayRestartOutcome,+ _apply_pending_fleet_restart_catchup, _clear_fleet_restart_pending_marker,+ _current_checkout_sha, _drain_or_signal_gateway_for_update, _fleet_probe_expected_runtimes,+ _fleet_restart_pending_marker_path, _for_each_systemd_gateway_unit,+ _gateway_recovery_partition, _gateway_service_matches_profile, _pending_fleet_restart_needed,+ _receipt_looks_unfinished, _receipt_reports_stale_runtime, _resolve_manage_cmd,+ _restart_gateway_fleet_after_update, _restart_launchd_gateway_after_update,+ _restart_macos_launchd_gateways, _restart_phase_failure_is_incomplete,+ _restart_systemd_gateway_units, _restart_systemd_gateway_units_best_effort,+ _run_pending_fleet_restart, _service_restart_sec,+ _service_unit_supports_graceful_sigusr1_restart, _surviving_gateway_pids_after_failed_restart,+ _systemctl, _systemctl_reset_and_restart, _verify_fleet_after_update,+ _wait_for_service_active, _warn_gateway_restart_phase_aborted,+ _warn_incomplete_gateway_fleet_restart, _warn_pending_fleet_restart,+ _warn_pending_fleet_restart_on_startup, _write_fleet_restart_pending_marker,+ _write_gateway_update_exit_code)+from hermes_cli.update_cmd_zip import ( # noqa: F401+ _ZIP_PRESERVED_TOP_LEVEL, _ZIP_STAGING_ARTIFACT_SUFFIXES, _abort_zip_update_if_dirty_tree,+ _atomic_replace_dir, _commit_staged_replacements, _discard_staged,+ _is_zip_preserved_entry_status_line, _is_zip_staging_artifact_status_line, _stage_replacement,+ _update_via_zip, _zip_overlay_block_reason)+from hermes_cli.update_cmd_stash import ( # noqa: F401+ _AUTOSTASH_NAME_PREFIX, _AUTOSTASH_WARN_AGE_DAYS, _discard_stashed_changes,+ _git_untracked_paths, _park_stashed_changes, _print_stash_cleanup_guidance,+ _reject_unsafe_stash_restore, _resolve_stash_selector, _restore_stashed_changes,+ _restored_python_paths, _stash_apply_failed_only_on_existing_untracked,+ _stash_local_changes_if_needed, _warn_orphaned_update_autostashes)+from hermes_cli.update_cmd_config import ( # noqa: F401+ _LAST_SIBLING_SNAPSHOTS, _check_and_apply_config_migration, _migrate_sibling_profile_configs,+ _print_items, _reload_config_modules, _run_config_check_fresh, _run_migrate_config_fresh)+from hermes_cli.update_cmd_deps import ( # noqa: F401+ _INSTALL_DEFINING_FILES, _UPDATE_CRITICAL_MODULES,+ _capture_active_lazy_features,+ _capture_active_tool_dependencies, _critical_module_import_failures,+ _desktop_app_present,+ _editable_install_is_current,+ _npm_bin_exists,+ _npm_lockfile_changed, _npm_manifest_paths, _npm_manifests_digest, _path_uid,+ _rebuild_desktop_after_update, _record_npm_lockfile_hash, _refresh_active_lazy_features,+ _refresh_active_memory_provider_dependencies, _refuse_update_if_venv_foreign_owned,+ _repair_node_deps_on_current_checkout,+ _sync_python_dependencies_after_pull, _update_node_dependencies,+ _validate_critical_modules_import,+ _venv_core_imports_healthy, _venv_foreign_owned_paths, _web_build_toolchain_ready,+ _web_toolchain_roots)+from hermes_cli.update_cmd_git import ( # noqa: F401+ OFFICIAL_REPO_URL, OFFICIAL_REPO_URLS, SKIP_UPSTREAM_PROMPT_FILE, _ORPHAN_RESCUE_REFS_TO_KEEP,+ _ORPHAN_RESCUE_REF_MAX_AGE_DAYS, _add_upstream_remote, _assess_parked_branch_switch,+ _branch_head_label, _branch_head_suffix, _classify_fetch_failure, _count_commits_between,+ _discard_lockfile_churn, _ensure_non_trampoline_git, _get_origin_url, _git_is_trampoline,+ _has_upstream_remote, _is_fork, _locate_real_git, _mark_skip_upstream_prompt,+ _normalize_managed_eol, _portable_git_candidates, _print_fetch_failure,+ _print_parked_branch_kept_notice, _print_parked_branch_skip_warning,+ _prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,+ _sync_with_upstream_if_needed)+from hermes_cli.update_cmd_maint import ( # noqa: F401+ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _STALE_PURGE_PREFIXES,+ _STALE_PURGE_PROTECTED, _UPDATE_RUNTIME_RELOAD_MODULES, _clear_stale_sqlite_sidecars,+ _ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,+ _format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,+ _print_curator_first_run_notice, _print_curator_recent_run_notice,+ _print_fts_optimize_available_notice, _print_update_completion, _print_update_summary,+ _print_verified_update_completion, _purge_stale_hermes_modules, _read_project_version,+ _reload_process_scan_modules, _reload_updated_runtime_modules,+ _resolve_pre_update_backup_mode, _restore_state_db_from_snapshot,+ _run_post_update_maintenance, _run_pre_update_backup, _sweep_bytecode_after_update,+ _update_complete_message, _verify_and_restore_one_state_db,+ _verify_and_restore_state_dbs_post_update)logger = logging.getLogger(__name__)@@ -56,6 +126,13 @@ def _m():return main+def _updates_config() -> dict:+ """The ``updates:`` config section (``{}`` when absent/malformed); may raise on config errors."""+ from hermes_cli.config import load_config+ section = (load_config() or {}).get("updates", {})+ return section if isinstance(section, dict) else {}++def _no_prompt_git_kwargs() -> dict:"""``subprocess.run`` kwargs for the updater's network git calls.@@ -72,524 +149,27 @@ def _no_prompt_git_kwargs() -> dict:return {"stdin": subprocess.DEVNULL, "env": env}-_UPDATE_RUNTIME_RELOAD_MODULES = (- "hermes_constants",- "tools.environments.local",- "pm.extras",-)--#: Package prefixes whose cached modules become stale the moment the checkout-#: changes under this process. Purged (not reloaded) by-#: ``_purge_stale_hermes_modules`` so any LATER import chain resolves against-#: fresh on-disk source only.-_STALE_PURGE_PREFIXES = (- "hermes_cli",- "gateway",- "tools",- "tui_gateway",- "agent",-)--#: Modules that must survive the purge: they are (or are referenced by) the-#: code currently EXECUTING the update, so evicting them buys nothing — the-#: running frames keep their module objects alive regardless — and reloading-#: them mid-flight is the one genuinely unsafe move.-_STALE_PURGE_PROTECTED = frozenset(- {- "hermes_cli",- "hermes_cli.main",- "hermes_cli.update_cmd",- "hermes_cli.hermes_logging",- }-)---def _purge_stale_hermes_modules() -> None:- """Evict every cached Hermes module after the checkout changed in-place.-- ``hermes update`` keeps running in the pre-pull Python process. The- gateway auto-restart phase that follows does function-level- ``from hermes_cli.gateway import ...`` — executing NEW source inside an- OLD ``sys.modules`` world. The moment new source references a symbol- that was added to an already-cached module, the import dies (2026-08-20- field failure: freshly-pulled ``hermes_cli.gateway`` does- ``from hermes_cli.cli_output import line_input``, but ``cli_output`` was- cached from before d0132b582 which introduced ``line_input`` → the whole- restart phase aborted and the gateway kept serving pre-update code).-- ``_UPDATE_RUNTIME_RELOAD_MODULES`` handled this per-symptom — three- hardcoded module names, re-fixed every time a new module grew a new- export. This is the class fix: drop EVERY cached module under the Hermes- package prefixes so subsequent lazy imports rebuild a self-consistent,- all-new module graph from the updated checkout. Old module objects- referenced by the running updater frames stay alive and functional (a- purge only removes the ``sys.modules`` cache entry); only genuinely- executing modules are exempted, because reloading-in-place — not purging- — is the operation that can pull code out from under a running frame.-- Best-effort: never raises.- """- try:- import importlib-- importlib.invalidate_caches()- purged = []- for name in list(_m().sys.modules):- if name in _STALE_PURGE_PROTECTED:- continue- if not name.startswith(_STALE_PURGE_PREFIXES):- continue- root = name.split(".", 1)[0]- if root not in _STALE_PURGE_PREFIXES:- # Prefix-string match caught an unrelated package- # (e.g. ``gateway_foo``) — leave it alone.- continue- if _m().sys.modules.pop(name, None) is not None:- purged.append(name)- if purged:- logger.debug(- "Purged %d stale Hermes module(s) after checkout update", len(purged)- )- except Exception as exc:- logger.debug("Could not purge stale Hermes modules: %s", exc)---def _reload_updated_runtime_modules() -> None:- """Reload update-sensitive modules after the checkout changes in-place.-- ``hermes update`` keeps running in the pre-pull Python process. After a- large update, modules already present in ``sys.modules`` can still expose- old symbols even though their source files on disk are new. Refresh the- small module set used by lazy-backend refresh before that step imports- newly-updated code paths.- """- try:- import importlib-- importlib.invalidate_caches()- for module_name in _UPDATE_RUNTIME_RELOAD_MODULES:- module = _m().sys.modules.get(module_name)- if module is None:- continue- try:- importlib.reload(module)- except Exception as exc:- logger.debug("Could not reload updated module %s: %s", module_name, exc)- except Exception as exc:- logger.debug("Could not refresh update runtime modules: %s", exc)---def _reload_config_modules() -> None:- """Force-reload modules from disk after git pull.-- ``hermes update`` runs in the PRE-pull Python process. After ``git pull``- updates the source files on disk, modules already in ``sys.modules``- still hold the OLD code. Function-level imports return the cached module,- so ``DEFAULT_CONFIG["_config_version"]`` is the OLD value and- ``check_config_version()`` reports ``(33, 33)`` — "up to date" — even- though the freshly-pulled code has v34 with a migration to run.-- This function force-reloads ``hermes_cli.config_defaults``,- ``hermes_cli.config``, and ``hermes_cli.config_migrations`` from disk- so subsequent imports read the UPDATED code.-- It also reloads ``hermes_cli._subprocess_compat`` and- ``hermes_cli.dashboard_procs`` so that post-update dashboard cleanup- (``_finish_dashboard_update_cleanup`` → ``_scan_dashboard_processes``)- uses the freshly-pulled code. Without this, a new symbol added to- ``_subprocess_compat`` (e.g. ``bounded_probe_run``) is invisible to the- cached module object, causing ``ImportError`` during the cleanup step- that runs later in the same process.- """- import importlib-- importlib.invalidate_caches()- for mod_name in (- "hermes_cli.config_defaults",- "hermes_cli.config",- "hermes_cli.config_migrations",- "hermes_cli._subprocess_compat",- "hermes_cli.dashboard_procs",- ):- mod = sys.modules.get(mod_name)- if mod is not None:- try:- importlib.reload(mod)- except Exception as exc:- logger.debug("Could not reload %s for fresh post-update code: %s", mod_name, exc)---def _run_config_check_fresh() -> tuple:- """Check config version using freshly-reloaded modules.-- See ``_reload_config_modules`` for why this is necessary.- Returns ``(current_ver, latest_ver)``.- """- _reload_config_modules()- from hermes_cli.config import check_config_version-- return check_config_version(raise_on_parse_error=True)---def _run_migrate_config_fresh(*, interactive: bool = False, quiet: bool = False) -> dict:- """Run config migration using freshly-reloaded modules.-- See ``_reload_config_modules`` for why this is necessary.- Returns the migration results dict.- """- _reload_config_modules()- from hermes_cli.config import migrate_config-- return migrate_config(interactive=interactive, quiet=quiet)---def _migrate_sibling_profile_configs() -> list[tuple[str, int, int]]:- """Migrate every SIBLING profile's config.yaml to the current version.-- #91277 Phase 2 (fleet-wide config migration; #20438/#54926/#79048): the- shared checkout serves every profile, but ``hermes update`` historically- migrated only the active profile's config — siblings drifted versions- until their gateway hit a config the new code couldn't read.-- Per profile home (skipping the active one, already migrated by the- caller): scope config reads/writes via the context-local HERMES_HOME- override (thread-safe — never ``os.environ``), check the version, and- run the NON-INTERACTIVE, quiet migration. Prompt-requiring settings are- left for the profile's own next interactive session, identical to the- gateway-mode contract for the active profile.-- Returns ``[(profile_name, from_version, to_version), ...]`` for profiles- actually migrated. Never raises; a failing profile is skipped (its own- startup migration remains the fallback).- """- migrated: list[tuple[str, int, int]] = []- try:- from hermes_constants import (- get_process_hermes_home,- reset_hermes_home_override,- set_hermes_home_override,- )- from hermes_cli.profiles import _get_profiles_root, _PROFILE_ID_RE-- active_home = get_process_hermes_home()- root = _get_profiles_root()- if not root.is_dir():- return migrated- for entry in sorted(root.iterdir()):- if not entry.is_dir() or not _PROFILE_ID_RE.match(entry.name):- continue- try:- if entry.resolve() == Path(active_home).resolve():- continue- except OSError:- continue- if not (entry / "config.yaml").is_file():- continue # profile never configured — nothing to migrate- token = set_hermes_home_override(entry)- try:- current_ver, latest_ver = _run_config_check_fresh()- if current_ver >= latest_ver:- continue- _run_migrate_config_fresh(interactive=False, quiet=True)- after_ver, _ = _run_config_check_fresh()- if after_ver > current_ver:- migrated.append((entry.name, current_ver, after_ver))- except Exception as exc:- logger.debug(- "Config migration for profile %s failed: %s", entry.name, exc- )- finally:- reset_hermes_home_override(token)- except Exception as exc:- logger.debug("Sibling profile enumeration failed: %s", exc)- return migrated--def _check_and_apply_config_migration(- *,- assume_yes: bool = False,- gateway_mode: bool = False,- pre_update_snapshot_id: str | None = None,-) -> None:- """Check and apply configuration migrations on an update completion path (#91360).-- CRITICAL: ``check_config_version`` and ``migrate_config`` must use- freshly-reloaded modules, not the ``sys.modules`` cache (see- ``_reload_config_modules``). This must run on EVERY update completion- path — the normal post-pull path, the venv-repair retry and the- Node-deps repair on the ``commit_count == 0`` "Already up to date"- branch — so an interrupted update that previously pulled new code does- not strand the user on an older config version.- """- print()- print("→ Checking configuration for new options...")-- # Reload config modules BEFORE any config reads so get_missing_*,- # check_config_version, and migrate_config all use the updated code.- _reload_config_modules()-- from hermes_cli.config import (- get_missing_env_vars,- get_missing_config_fields,- )-- # Defensive (#91360): this helper runs on repair/retry completion paths- # too — a config-check failure must not break an otherwise-successful- # update. Log, point at the manual command, and return.- try:- missing_env = get_missing_env_vars(required_only=True)- missing_config = get_missing_config_fields()- current_ver, latest_ver = _run_config_check_fresh()- except Exception as exc:- logger.debug("Config check during update failed: %s", exc)- print(" ⚠️ Could not check config version.")- print(" Run 'hermes config migrate' to check manually.")- return-- has_new_options = bool(missing_env or missing_config)- version_bump_only = (- not has_new_options and current_ver < latest_ver- )- needs_migration = has_new_options or current_ver < latest_ver-- if version_bump_only:- # Nothing for the user to fill in — only the config format version- # changed (new defaults already merge in transparently). Asking- # "configure new options now?" here is misleading: saying yes just- # bumps the version and looks like a no-op (issue: ScottFive /- # Tt2021). Apply it silently and say what actually happened.- print()- print(- f" ℹ Updating config format (v{current_ver} → v{latest_ver})…"- )- try:- _mig_results = _run_migrate_config_fresh(- interactive=False, quiet=True- )- print(" ✓ Config format updated (no new settings to configure)")- # quiet=True also mutes migration steps that RESET or REMOVE an- # existing setting (e.g. the v33→v34 personality reset from- # #81946, which records its note only in the results dict).- # Re-surface those notes so an unattended update never silently- # changes user configuration (#86656). In this branch- # missing_config is empty, so config_added can only contain- # migration-step mutations, not missing-key listings.- for _note in _mig_results.get("config_added") or []:- print(f" ℹ {_note}")- for _warn in _mig_results.get("warnings") or []:- print(f" ⚠️ {_warn}")- except Exception as _mig_err:- print(f" ⚠️ Config format update failed: {_mig_err}")- print(" Run 'hermes config migrate' to retry.")- elif needs_migration:- print()- # Show WHAT changed, not just a count, so the user can make an- # informed yes/no decision (previously the prompt named nothing).- def _print_items(items, label, key, fallback_key=None):- if not items:- return- print(f" {label}:")- shown = items[:8]- for it in shown:- if isinstance(it, dict):- name = it.get(key) or (fallback_key and it.get(fallback_key)) or "?"- desc = (it.get("description") or "").strip()- else:- # Defensive: some callers/mocks pass bare name strings.- name = str(it)- desc = ""- if desc:- print(f" • {name} — {desc}")- else:- print(f" • {name}")- extra = len(items) - len(shown)- if extra > 0:- print(f" … and {extra} more")-- if missing_env:- print(- f" ⚠️ {len(missing_env)} new required setting(s) need configuration"- )- _print_items(missing_env, "New settings", "name")- if missing_config:- print(f" ℹ️ {len(missing_config)} new config option(s) available")- _print_items(missing_config, "New options", "key")-- print()- if assume_yes:- print(- " ℹ --yes: auto-applying config migration (skipping API-key prompts)."- )- response = "y"- elif gateway_mode:- response = (- _gateway_prompt(- "Would you like to configure new options now? [Y/n]", "n"- )- .strip()- .lower()- )- elif not (sys.stdin.isatty() and sys.stdout.isatty()):- print(" ℹ Non-interactive session — applying safe config migrations.")- response = "auto"- else:- try:- response = (- input("Would you like to configure them now? [Y/n]: ")- .strip()- .lower()- )- except EOFError:- response = "n"- except UnicodeDecodeError:- # input() can raise this when the terminal encoding can't- # decode the byte sequence (e.g. a non-UTF-8 locale, or an- # embedded terminal). Without this, the exception escapes- # here and crashes the update at this prompt.- print(- " ⚠ Could not read input (encoding issue). Skipping. "- "Run 'hermes config migrate' manually to configure."- )- response = "n"-- if response in {"", "y", "yes", "auto"}:- print()- # Gateway mode, --yes, and non-interactive update contexts- # (dashboard / web server actions) cannot prompt for API keys.- # Still run the non-interactive migration pass before restarting- # so new default config fields and version bumps are written- # before the freshly updated gateway validates config at startup.- interactive_migration = not (- gateway_mode or assume_yes or response == "auto"- )- results = _run_migrate_config_fresh(interactive=interactive_migration, quiet=False)-- if results["env_added"] or results["config_added"]:- print()- print("✓ Configuration updated!")- if (gateway_mode or assume_yes or response == "auto") and missing_env:- print(" ℹ API keys require manual entry: hermes config migrate")- else:- print()- print("Skipped. Run 'hermes config migrate' later to configure.")- else:- print(" ✓ Configuration is up to date")-- # Fleet-wide config migration (#91277 Phase 2; #20438 earliest report,- # #54926, #79048): the shared checkout serves EVERY profile, but the- # migration above only touched the active profile's config.yaml.- # Sibling profiles kept their old _config_version and silently- # drifted (field repro: sibling gateway restarted onto new code but- # stayed at config v33 vs v37). Run the same NON-INTERACTIVE safe- # migration for every sibling profile home, scoped via the- # context-local HERMES_HOME override (never os.environ — other- # threads must not see it).- try:- _migrated_siblings = _migrate_sibling_profile_configs()- for _name, _from_ver, _to_ver in _migrated_siblings:- print(- f" ✓ Profile '{_name}': config format updated "- f"(v{_from_ver} → v{_to_ver})"- )- except Exception as exc:- logger.debug("Sibling config migration failed: %s", exc)-- # Safety net: config-version migrations have been observed to leave- # cron/jobs.json valid-but-empty, silently dropping every scheduled- # job (issue #34600). The desktop scheduler can also overwrite with- # its own small set, causing partial loss (issue #52144). If the- # live file now has fewer jobs than the pre-update snapshot, restore- # it and warn loudly.- try:- from hermes_cli.backup import restore_cron_jobs_if_emptied-- cron_restore = restore_cron_jobs_if_emptied(pre_update_snapshot_id)- if cron_restore:- print()- print(- " ⚠️ cron/jobs.json lost jobs during this update — "- f"restored {cron_restore['job_count']} job(s) from "- f"pre-update snapshot {cron_restore['snapshot_id']}."- )- except Exception as exc:- # Never let the cron safety net break an otherwise-good update.- logger.debug("Cron jobs auto-restore check failed: %s", exc)-- # #64160: config.yaml model/provider + MoA safety net. Desktop- # update/repair cycles have rewritten user-set model.provider /- # model.default and dropped the moa: section — settings the gateway- # and cron jobs also consume. Compare the live config against the- # same pre-update snapshot and restore only the protected keys.- try:- from hermes_cli.backup import restore_config_model_settings_if_rewritten-- cfg_restore = restore_config_model_settings_if_rewritten(- pre_update_snapshot_id- )- if cfg_restore:- print()- print(- " ⚠️ config.yaml user model settings were rewritten during "- f"this update — restored {', '.join(cfg_restore['keys'])} "- f"from pre-update snapshot {cfg_restore['snapshot_id']}."- )- except Exception as exc:- # Never let the config safety net break an otherwise-good update.- logger.debug("Config model-settings auto-restore check failed: %s", exc)-- # #66140: run the same cron-jobs safety net for every sibling- # profile against ITS OWN pre-update snapshot (same-generation by- # construction — both taken by this run).- try:- from hermes_cli.backup import restore_cron_jobs_all_profiles+_UPDATE_CRITICAL_FILES = (+ "hermes_cli/main.py", "hermes_cli/config.py", "hermes_cli/__init__.py",+ "hermes_cli/web_server.py", "cli.py", "run_agent.py", "model_tools.py", "toolsets.py",+ "hermes_constants.py")- for _restored in restore_cron_jobs_all_profiles(- _LAST_SIBLING_SNAPSHOTS- ):- print()- print(- f" ⚠️ Profile '{_restored['profile']}': cron/jobs.json "- f"lost jobs during this update — restored "- f"{_restored['job_count']} job(s) from pre-update "- f"snapshot {_restored['snapshot_id']}."- )- except Exception as exc:- logger.debug("Sibling cron auto-restore check failed: %s", exc)- # #64160: same config model-settings safety net for sibling profiles.- try:- from hermes_cli.backup import restore_config_model_settings_all_profiles+def _record_update_step(step: str, ok: bool, detail: str = "") -> None:+ """Best-effort ``update_receipt.record_step``; the receipt must never break an update."""+ with suppress(Exception):+ from hermes_cli.update_receipt import record_step+ record_step(step, ok, detail)- for _cfg_restored in restore_config_model_settings_all_profiles(- _LAST_SIBLING_SNAPSHOTS- ):- print()- print(- f" ⚠️ Profile '{_cfg_restored['profile']}': config.yaml "- f"user model settings were rewritten during this update — "- f"restored {', '.join(_cfg_restored['keys'])} from "- f"pre-update snapshot {_cfg_restored['snapshot_id']}."- )- except Exception as exc:- logger.debug("Sibling config auto-restore check failed: %s", exc)+def _git_run(git_cmd, args, cwd=None, *, check=False, network=False):+ """Run git capturing utf-8 text (default cwd: checkout); ``network=True`` disables the+ terminal prompt so an HTTP 401 fails fast instead of hanging."""+ return subprocess.run(+ git_cmd + args, cwd=_m().PROJECT_ROOT if cwd is None else cwd, capture_output=True,+ text=True, encoding="utf-8", errors="replace", check=check,+ **(_no_prompt_git_kwargs() if network else {}))-# Critical files that Hermes must be able to import immediately after an-# update/install. Most are imported on every CLI startup; ``web_server.py``-# is the desktop/dashboard backend path that a fresh Windows install launches-# right away. If any of these fail to parse after a pull, the user can be-# left with a bricked CLI or desktop backend. The post-pull syntax guard-# validates these and auto-rolls-back on failure.-_UPDATE_CRITICAL_FILES = (- "hermes_cli/main.py",- "hermes_cli/config.py",- "hermes_cli/__init__.py",- "hermes_cli/web_server.py",- "cli.py",- "run_agent.py",- "model_tools.py",- "toolsets.py",- "hermes_constants.py",-)def _capture_head_sha(git_cmd, cwd) -> str | None:"""Return the current HEAD SHA, or None if it can't be resolved."""@@ -605,130 +185,10 @@ def _capture_head_sha(git_cmd, cwd) -> str | None:except (subprocess.CalledProcessError, OSError):return None-_ORPHAN_RESCUE_REFS_TO_KEEP = 10-_ORPHAN_RESCUE_REF_MAX_AGE_DAYS = 30--def _prune_orphan_rescue_refs(- git_cmd,- cwd,- branch,- keep=_ORPHAN_RESCUE_REFS_TO_KEEP,- max_age_days=_ORPHAN_RESCUE_REF_MAX_AGE_DAYS,-) -> None:- """Expire old orphan rescue refs so backups stay bounded.-- Each orphan-history divergence (#87694) parks the pre-reset HEAD under- ``refs/hermes-update-backups/orphan-<branch>-<ts>-<sha>``. A rescue ref- pins every object reachable from that commit against ``git gc`` — and in- the incident shape those objects include a full working-tree snapshot- (the autostash orphan commit), which can be multi-GB when the tree holds- large stray files. Left alone, a repeatedly corrupted install would grow- ``.git`` without bound.-- Two independent limits, both enforced on every orphan incident:-- - **Count cap:** keep only the ``keep`` most-recent refs.- - **Age expiry:** drop any ref older than ``max_age_days``, parsed from- the ``YYYYMMDD-HHMMSS`` timestamp embedded in the ref name (refs with- unparseable names are left alone rather than guessed at).-- Ref names sort chronologically (timestamp prefix), so lexicographic- order from ``for-each-ref`` is also creation order. Deleting a ref makes- its objects eligible for ``git gc``; actual disk reclaim happens on the- next gc (git auto-gc, or the user running ``git gc``). Best-effort: any- failure here must not block the update itself.- """- try:- list_result = subprocess.run(- git_cmd + [- "for-each-ref",- "--format=%(refname)",- "--sort=refname",- f"refs/hermes-update-backups/orphan-{branch}-*",- ],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if list_result.returncode != 0:- return- refs = [line.strip() for line in list_result.stdout.splitlines() if line.strip()]- stale = set(refs[:-keep] if keep > 0 else refs)- # Age expiry: ref names embed a UTC YYYYMMDD-HHMMSS timestamp right- # after the branch segment; anything older than max_age_days goes.- if max_age_days > 0:- from datetime import timedelta, timezone-- cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)- prefix = f"refs/hermes-update-backups/orphan-{branch}-"- for ref in refs:- stamp = ref[len(prefix):][:15] # "YYYYMMDD-HHMMSS"- try:- ref_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(- tzinfo=timezone.utc- )- except ValueError:- continue- if ref_time < cutoff:- stale.add(ref)- for ref in sorted(stale):- subprocess.run(- git_cmd + ["update-ref", "-d", ref],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- except OSError:- pass# Files that define the editable install. A pull that touches none of them# cannot have invalidated it.-_INSTALL_DEFINING_FILES = (- "pyproject.toml",- "setup.py",- "setup.cfg",- "MANIFEST.in",- "uv.lock",-)--def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool:- """True when the pulled commits cannot have invalidated the editable install.-- ``uv pip install -e .`` never audits an editable target — it reinstalls on- every invocation, and every reinstall rewrites the console-script shims.- On Windows that rewrite is the only reason the running ``hermes.exe`` has- to be quarantined, and a quarantine that loses its race is the whole- ``os error 32`` family. Not reinstalling when the reinstall provably- cannot change anything removes that risk outright for the common update,- rather than trying to make the rename win more often.-- Skipping is safe because Hermes pins its editable finder to a *static*- module list (``[tool.setuptools] py-modules`` plus- ``packages.find.include``). The one source-only change that would stale- that finder is a new top-level module or package, and it cannot land- without a ``pyproject.toml`` diff. Dependencies and ``[project.scripts]``- live there too. New submodules inside an already-mapped package resolve- through the real package directory and need no reinstall.-- Fails closed: an unresolvable pre-pull SHA (shallow checkout, ZIP swap)- or a failed ``git diff`` returns False and the install runs as before.- """- if not pre_pull_sha:- return False- try:- result = subprocess.run(- git_cmd- + ["diff", "--name-only", f"{pre_pull_sha}..HEAD", "--"]- + list(_INSTALL_DEFINING_FILES),- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- except OSError:- return False- if result.returncode != 0:- return False- return not result.stdout.strip()+def _validate_python_files_syntax(root, relpaths@@ -751,6 +211,8 @@ def _validate_python_files_syntax(except OSError as exc:return False, str(path), f"could not read: {exc}"return True, None, None++def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]:"""Compile each file in ``_UPDATE_CRITICAL_FILES`` to catch SyntaxErrors.@@ -777,153 +239,7 @@ def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]# is only parsed), these are actually *imported* so that cross-module breakage# is caught — a file can be syntactically perfect and still fail to import# because a name it pulls from a sibling module no longer exists.-_UPDATE_CRITICAL_MODULES = (- "hermes_cli.main",- "run_agent",- "model_tools",- "toolsets",-)---def _critical_module_import_failures(- root, *, report_runtime_errors: bool = False-) -> dict[str, tuple[str, str]]:- """Import each module in ``_UPDATE_CRITICAL_MODULES`` in a subprocess.-- ``_validate_critical_files_syntax`` only *parses* files, so it cannot see- cross-module breakage: a partially-updated tree where ``agent/`` is new but- ``tools/`` is old parses perfectly and still dies at startup with- ``ImportError: cannot import name 'TODO_INJECTION_HEADER' from- 'tools.todo_tool'``. Every file is valid Python; the *combination* is not.-- That skew is reachable on the Windows ZIP-update path, whose copy loop- walks top-level entries in ``os.listdir`` order and replaces each one- independently — ``agent/`` lands long before ``tools/``, so a failure or- interruption between them leaves exactly that mismatch on disk.-- Runs in a subprocess because importing these modules into the running- updater would pollute ``sys.modules`` and execute import-time side effects- against the half-updated tree. Costs ~0.4s.-- Uses the project venv's interpreter when there is one (matching- ``_venv_core_imports_healthy``): ``hermes update`` can be driven by a- different Python than the install's own, and probing the wrong- interpreter would test a tree the user never runs.-- Returns every failing module in probe order. Generic import-time exceptions- remain tolerated by default because they can depend on local config or- environment. ``report_runtime_errors=True`` exposes them so a caller can- compare two states of the same checkout without an earlier failure masking- a later one.- """- from hermes_constants import FIRST_PARTY_MODULE_ROOTS-- import secrets-- marker = f"__HERMES_IMPORT_HEALTH_{secrets.token_hex(16)}__"- probe = (- "import importlib, json, sys\n"- "failures = []\n"- "for name in %r:\n"- " try:\n"- " importlib.import_module(name)\n"- " except ModuleNotFoundError as exc:\n"- # A missing *third-party* module means dependencies aren't installed- # yet, not a skewed checkout. Only our own packages count as breakage.- # The root set is injected from hermes_constants so this can't drift- # from the hint the user is shown (they disagreed once already).- " missing = (getattr(exc, 'name', '') or '').split('.')[0]\n"- " if missing in %r or missing.startswith('hermes_') or %r:\n"- " failures.append((name, type(exc).__name__, str(exc)))\n"- " except ImportError as exc:\n"- " failures.append((name, type(exc).__name__, str(exc)))\n"- " except Exception as exc:\n"- " if %r:\n"- " failures.append((name, type(exc).__name__, str(exc)))\n"- " except BaseException as exc:\n"- " failures.append((name, type(exc).__name__, str(exc)))\n"- "sys.stdout.write('\\n%s' + json.dumps(failures))\n"- % (- _UPDATE_CRITICAL_MODULES,- tuple(sorted(FIRST_PARTY_MODULE_ROOTS)),- report_runtime_errors,- report_runtime_errors,- marker,- )- )- try:- interpreter = sys.executable- try:- venv_python = venv_python_path(- Path(root) / "venv", windows=_m()._is_windows()- )- if venv_python.exists():- interpreter = str(venv_python)- except Exception:- pass # fall back to the running interpreter- result = subprocess.run(- [interpreter, "-c", probe],- cwd=str(root),- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=120,- )- except subprocess.TimeoutExpired:- return {- "critical-module probe": (- "TimeoutExpired",- "timed out before reporting import health",- )- }- except (OSError, subprocess.SubprocessError):- # Can't run the probe — don't block the update on our own tooling.- return {}- output = result.stdout or ""- if marker not in output:- return {- "critical-module probe": (- "ProbeTerminated",- "terminated before reporting import health "- f"(exit code {result.returncode})",- )- }- try:- import json-- failures = json.loads(output.rsplit(marker, 1)[1])- if not isinstance(failures, list) or any(- not isinstance(item, list)- or len(item) != 3- or not all(isinstance(value, str) for value in item)- for item in failures- ):- raise ValueError("invalid import-health payload")- return {- str(module): (str(kind), str(detail))- for module, kind, detail in failures- }- except (TypeError, ValueError):- return {- "critical-module probe": (- "MalformedPayload",- "reported malformed import health data",- )- }--def _validate_critical_modules_import(- root, *, report_runtime_errors: bool = False-) -> tuple[bool, str | None, str | None]:- """Return the first critical-module import failure, if any."""- failures = _critical_module_import_failures(- root, report_runtime_errors=report_runtime_errors- )- if failures:- module = next(iter(failures))- return False, module, failures[module][1]- return True, None, Nonedef _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0) -> str:"""File-based IPC prompt for gateway mode.@@ -974,739 +290,67 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0)print(f" (no response after {int(timeout)}s, using default: {default!r})")return default-def _npm_bin_exists(bin_dir: Path, name: str) -> bool:- """True when an npm bin shim for *name* exists (POSIX or Windows)."""- return any(- (bin_dir / candidate).exists()- for candidate in (name, f"{name}.cmd", f"{name}.ps1", f"{name}.exe")- )-def _web_build_toolchain_ready(*roots: Path) -> bool:- """True when ``tsc`` and ``vite`` shims are reachable from any of *roots*.+def _called_process_error_cmd_parts(exc: subprocess.CalledProcessError) -> list[str]:+ """Normalize ``CalledProcessError.cmd`` into argv-style tokens."""+ cmd = exc.cmd+ if cmd is None:+ return []+ if isinstance(cmd, (str, bytes)):+ text = cmd.decode("utf-8", "replace") if isinstance(cmd, bytes) else cmd+ try:+ return shlex.split(text, posix=os.name != "nt")+ except ValueError:+ return text.split()+ return [str(part) for part in cmd]- Callers must pass every root the build would search; checking only one- reports a healthy tree as broken.- """- bin_dirs = [- bin_dir- for bin_dir in (root / "node_modules" / ".bin" for root in roots)- if bin_dir.is_dir()- ]- return bool(bin_dirs) and all(- any(_npm_bin_exists(bin_dir, tool) for bin_dir in bin_dirs)- for tool in ("tsc", "vite")- )-def _web_toolchain_roots(web_dir: Path) -> tuple[Path, ...]:- """Roots whose ``node_modules/.bin`` can satisfy the web build.+def _called_process_error_is_git(exc: subprocess.CalledProcessError) -> bool:+ """True when the failed subprocess was git itself."""+ parts = _called_process_error_cmd_parts(exc)+ if not parts:+ return False+ # Windows argv may use backslashes; basename() on POSIX would otherwise+ # keep the whole path. Normalize separators before taking the name.+ name = os.path.basename(parts[0].replace("\\", "/")).lower()+ return name in {"git", "git.exe"}- ``npm run build`` prepends ``node_modules/.bin`` for the package and each- of its ancestors, so shims hoisted to the workspace root and shims nested- under a package that owns its lockfile (#42973) are equally valid.- """- return (web_dir, web_dir.parent)-def _print_curator_first_run_notice() -> None:- """Print a short heads-up about the skill curator after `hermes update`.+def _called_process_error_is_python_dep_install(+ exc: subprocess.CalledProcessError,+) -> bool:+ """True when the failed subprocess was a uv/pip (or ensurepip) install."""+ parts = [part.lower() for part in _called_process_error_cmd_parts(exc)]+ if not parts:+ return False+ exe = os.path.basename(parts[0].replace("\\", "/"))+ if "ensurepip" in parts:+ return True+ if "install" in parts and (+ "pip" in parts or exe in {"pip", "pip.exe", "pip3", "pip3.exe", "uv", "uv.exe"}+ ):+ return True+ return False- Only fires when the curator is enabled AND has no recorded run yet, which- is exactly the window where the gateway ticker used to fire Curator- against a fresh skill library immediately after an update. We defer the- first real pass by one ``interval_hours``; this notice tells the user how- to preview or disable before then. Silent on steady state.- """- try:- from agent import curator- except Exception:- return- try:- if not curator.is_enabled():- return- state = curator.load_state()- except Exception:- return- if state.get("last_run_at"):- # Curator has run before (real or already seeded) — no notice needed.- return- try:- hours = curator.get_interval_hours()- except Exception:- hours = 24 * 7- days = max(1, hours // 24)- print()- print("ℹ Skill curator")- print(- f" Background skill maintenance is enabled. First pass is deferred "- f"~{days}d after installation; only agent-created skills are in "- f"scope and nothing is ever auto-deleted (archive is recoverable)."- )- print(" Preview now: hermes curator run --dry-run")- print(" Pause it: hermes curator pause")- print(- " Docs: https://hermes-agent.nousresearch.com/docs/user-guide/features/curator"- )-def _print_fts_optimize_available_notice() -> None:- """Advertise the opt-in v23 search-index optimization after `hermes update`.+def _format_update_failure_stage(exc: subprocess.CalledProcessError) -> str:+ """Name the update stage that actually failed.- Only fires when the current profile's state.db still needs an FTS storage- rebuild. Leads with the reclaimable-space figure and points at the exact- command. Honors ``sessions.fts_optimize_notice``:- ``advise`` (default) prints an advisory notice, ``require`` prints a- firmer required-upgrade notice, ``off`` suppresses it. Silent for- fresh/already-optimized installs.+ The git pull and the Python-dependency install share one ``try`` in+ ``_cmd_update_impl``. Calling every ``CalledProcessError`` a git failure+ (the historical Windows message) sent users hunting in the wrong place+ and, worse, keyed the ZIP overlay on exception *type* rather than on git+ actually having failed (#87304, #85840)."""- mode = "advise"- try:- from hermes_cli.config import load_config-- mode = str(- ((load_config() or {}).get("sessions") or {}).get(- "fts_optimize_notice", "advise"- )- ).strip().lower()- except Exception:- mode = "advise"- if mode == "off":- return+ if _called_process_error_is_python_dep_install(exc):+ return "Python dependency install failed"+ if _called_process_error_is_git(exc):+ return "Git update failed"+ return "Update step failed"- try:- from hermes_constants import get_hermes_home- from hermes_state import SessionDB- except Exception:- return- db_path = get_hermes_home() / "state.db"- if not db_path.exists():- return- try:- size_gb = db_path.stat().st_size / (1024 ** 3)- except OSError:- return- # Skip the notice for trivially small DBs — the win isn't worth the nag.- if size_gb < 0.5:- return- db = None- interrupted = False- needs_upgrade = False- try:- db = SessionDB(db_path=db_path, read_only=True)- # read_only opens skip schema init, so probe the stored layout directly.- row = db._conn.execute(- "SELECT sql FROM sqlite_master "- "WHERE type = 'table' AND name = 'messages_fts'"- ).fetchone()- needs_upgrade = bool(row) and getattr(- db, "_db_needs_fts_storage_upgrade"- )(db._conn)- # An interrupted `optimize-storage` run: the table is already the- # v23 shape, but backfill markers / demoted trash tables remain.- # Offer the command again — re-running resumes and finishes it.- interrupted = bool(- db._conn.execute(- "SELECT 1 FROM state_meta "- "WHERE key = 'fts_rebuild_high_water' LIMIT 1"- ).fetchone()- or db._conn.execute(- "SELECT 1 FROM sqlite_master WHERE type = 'table' "- "AND name LIKE 'fts\\_v22\\_trash\\_%' ESCAPE '\\' LIMIT 1"- ).fetchone()- or db._conn.execute(- "SELECT 1 FROM state_meta WHERE key IN "- "('fts_cjk_rebuild_high_water', 'fts_cjk_stale') LIMIT 1"- ).fetchone()- )- except Exception:- return- finally:- if db is not None:- try:- db.close()- except Exception:- pass- if not needs_upgrade and not interrupted:- # Current layout already present (fresh/optimized) — nothing to offer.- return- if interrupted:- print()- print("◆ Session database optimization incomplete")- print(- " A previous `hermes sessions optimize-storage` run was "- "interrupted. Search still works; re-run the command to resume "- "and finish reclaiming disk:"- )- print(" hermes sessions optimize-storage")- return-- # Concrete size framing — lead with the savings the user cares about.- est_reclaim = size_gb * 0.6- print()- if mode == "require":- print("◆ Session database upgrade required")- print(- f" Your search index uses the OLD storage layout and should be "- f"upgraded. The new layout typically frees ~60% of state.db "- f"(≈{est_reclaim:.1f} GB of your current {size_gb:.1f} GB) and is "- f"required for continued optimal operation."- )- else:- print("◆ Reclaim ~60% of your session database disk")- print(- f" Your search index uses the old storage layout. Upgrading it "- f"typically frees ~60% of state.db — about {est_reclaim:.1f} GB "- f"of your current {size_gb:.1f} GB."- )- print(" Run when convenient: hermes sessions optimize-storage")- print(- " It runs in the foreground with a progress bar, is safe to "- "interrupt/re-run, and never changes your conversations."- )--def _print_curator_recent_run_notice() -> None:- """Print the most recent curator run summary, exactly once.-- The curator runs in the background (gateway tick + CLI session start),- so users learn about skill consolidations only by stumbling into a- rename. ``hermes update`` is a high-attention surface — surface the- most recent run's rename map here, once.-- Show-once: state stamps ``last_run_summary_shown_at`` after printing.- Subsequent ``hermes update`` invocations skip the block until a newer- curator run lands. Silent when the curator has never run, when the- most recent summary has already been shown, or when the summary has- no rename information to display (no archives).- """- try:- from agent import curator- except Exception:- return- try:- state = curator.load_state()- except Exception:- return-- last_run_at = state.get("last_run_at")- if not last_run_at:- return # no curator run yet — first-run notice handles this case-- if state.get("last_run_summary_shown_at") == last_run_at:- return # already shown for this run-- summary = state.get("last_run_summary") or ""- if not summary:- return-- # Only print when there's something interesting to show — i.e. the- # rename map block was appended (multi-line summary). A bare "auto:- # no changes; llm: no change" doesn't warrant interrupting the- # update flow.- if "\n" not in summary:- # Still stamp it shown so we don't reconsider it on every update.- try:- state["last_run_summary_shown_at"] = last_run_at- curator.save_state(state)- except Exception:- pass- return-- # Format the timestamp as "Xh ago" for readability.- when = _format_time_ago(last_run_at)- print()- print(f"ℹ Skill curator — last run {when}")- for line in summary.splitlines():- print(f" {line}")- print(- " (This message shows once per curator run. "- "View anytime: hermes curator status)"- )-- # Stamp shown so we don't repeat on the next update.- try:- state["last_run_summary_shown_at"] = last_run_at- curator.save_state(state)- except Exception:- pass--def _format_time_ago(iso_ts: str) -> str:- """Render an ISO timestamp as `Xh ago` / `Xd ago` / `Xm ago`. Best effort."""- try:- from datetime import datetime, timezone- ts = datetime.fromisoformat(iso_ts.replace("Z", "+00:00"))- if ts.tzinfo is None:- ts = ts.replace(tzinfo=timezone.utc)- delta = datetime.now(timezone.utc) - ts- secs = int(delta.total_seconds())- if secs < 60:- return "just now"- if secs < 3600:- return f"{secs // 60}m ago"- if secs < 86400:- return f"{secs // 3600}h ago"- return f"{secs // 86400}d ago"- except Exception:- return "recently"--def _reload_process_scan_modules() -> None:- """Force-reload the process-scan modules from disk after an update.-- ``_finish_dashboard_update_cleanup`` runs in the PRE-update Python- process, but ``_scan_dashboard_processes`` does a function-level- ``from hermes_cli._subprocess_compat import bounded_probe_run``. If the- update added a new symbol to ``_subprocess_compat`` (as #87134 did with- ``bounded_probe_run``), the cached OLD module object doesn't have it and- the cleanup step crashes with ImportError — after the code update itself- already succeeded. Reload dependency-first so ``dashboard_procs`` binds- against the fresh ``_subprocess_compat``.-- Lives here (called from the cleanup entry point) rather than only in- ``_reload_config_modules`` so EVERY caller — the git-update path, the- Windows ZIP fallback path, and any future one — is covered.- """- import importlib-- importlib.invalidate_caches()- for mod_name in (- "hermes_cli._subprocess_compat",- "hermes_cli.dashboard_procs",- ):- mod = sys.modules.get(mod_name)- if mod is not None:- try:- importlib.reload(mod)- except Exception as exc:- # warning, not debug: a failed reload here surfaces seconds- # later as an ImportError in the same process — leave a trail.- logger.warning(- "Could not reload %s for post-update cleanup: %s",- mod_name,- exc,- )---def _finish_dashboard_update_cleanup(- node_failures: list[str], already_restarted_units: "set[str] | None" = None-) -> None:- """Refresh managed dashboards or stop stale manual ones after an update.-- *already_restarted_units* forwards the systemd unit names (no- ``.service`` suffix) that the fleet-restart loop already restarted- directly, so a Serve-only install's freshly restarted process isn't- found and restarted a second time here (review on #83595).- """- if node_failures:- print()- print(" ℹ Leaving running dashboard process(es) untouched because the")- print(" Node.js dependency refresh did not complete.")- return-- # The scan path lazy-imports symbols from _subprocess_compat; make sure- # both modules reflect the freshly-updated source before touching them.- _reload_process_scan_modules()-- stop_result = _m()._kill_stale_dashboard_processes(- restart_managed=True, already_restarted_units=already_restarted_units- )- if not stop_result.get("unrecovered"):- return-- print()- print(- "⚠ A web dashboard/serve process was stopped during update and could "- "not be auto-restarted."- )- print(" Re-launch it when you want the web UI back:")- print(" hermes dashboard --port <port>")--def _atomic_replace_dir(src: str, dst: str) -> None:- """Replace directory *dst* with *src* without leaving *dst* half-deleted.-- The naive ``rmtree(dst); copytree(src, dst)`` has a destructive window: if- the copy fails partway (common on the Windows ZIP-update path, which only- runs because file I/O is already flaky on that machine), the old directory- is already gone and nothing replaced it — the install is left with a- deleted tree (issue #49145, where ``ui-tui/`` vanished and broke the TUI).-- Now a thin single-entry alias over the two-phase helpers below, which- generalise the same stage-then-swap discipline across every entry the ZIP- update touches (#76104). Retained because it is part of the mechanical- ``hermes_cli.main`` re-export surface and guards the #49145 regression.- """- _commit_staged_replacements([(_stage_replacement(src, dst), dst)])---def _stage_replacement(src: str, dst: str) -> str:- """Copy *src* to a sibling staging path for *dst*; return the staging path.-- Phase 1 of the two-phase replace. Handles both directories and plain- files. Touches nothing live, so a failure here leaves the whole install- untouched.- """- staging = f"{dst}.hermes-update-staging"- backup = f"{dst}.hermes-update-old"- # A previous run may have died between "move dst aside" and "move staging- # in" — leaving dst missing and the backup as the ONLY copy of that entry.- # Restore it before clearing leftovers: deleting the backup first and then- # failing to stage (disk exhaustion is likely right after writing a full- # staging copy) would leave a hole in the install with nothing to roll- # back to. The restore is a same-filesystem rename — instant and safe.- if not os.path.exists(dst) and os.path.exists(backup):- os.rename(backup, dst)- for leftover in (staging, backup):- if os.path.isdir(leftover):- shutil.rmtree(leftover, ignore_errors=True)- elif os.path.exists(leftover):- os.remove(leftover)- if os.path.isdir(src):- shutil.copytree(src, staging)- else:- shutil.copy2(src, staging)- return staging---def _discard_staged(staged) -> None:- """Remove staging paths for entries that were never committed.-- Without this a phase-1 failure (typically disk exhaustion) orphans one- staging copy per entry already processed — up to a full second copy of- the tree. The user then follows the "re-run `hermes update`" advice with- *less* free space than before and the retry fails harder than the- original attempt.- """- for staging, _dst in staged:- try:- if os.path.isdir(staging):- shutil.rmtree(staging, ignore_errors=True)- elif os.path.exists(staging):- os.remove(staging)- except OSError as exc: # best-effort cleanup, never fatal- logger.warning("could not remove staging path %s: %s", staging, exc)---def _commit_staged_replacements(staged) -> None:- """Phase 2: swap every staged entry into place, rolling back all on failure.-- ``_atomic_replace_dir`` makes each *individual* directory swap safe, but- the ZIP update replaces ~90 top-level entries in a loop, and nothing made- the loop atomic *as a whole*. A failure partway left some entries at the- new version and the rest at the old one — every file valid Python, the- combination unbootable (issue #76104; the ``ImportError`` in #76091 and- the field report in #63717 are both this).-- This covers plain files as well as directories: the repo root holds 20- first-party modules (``run_agent.py``, ``cli.py``, ``hermes_constants.py``- …), so a files-only failure reproduces exactly the bug class we are- closing. Every swap is an ``os.rename`` onto a path that was just moved- aside — a same-filesystem rename is atomic on POSIX and NTFS alike, so a- file swap can never leave a half-written module the way ``copy2`` onto a- live path can.-- Splitting stage-all-then-swap-all shrinks the failure window from "the- duration of a full tree copy" to "the duration of N renames", and makes- the remaining window recoverable: if a swap fails we restore every entry- already swapped, so the tree lands wholly new or wholly old.- """- swapped: list[tuple[str, str]] = [] # (dst, backup) in swap order; "" = absent- try:- for staging, dst in staged:- backup = f"{dst}.hermes-update-old"- if os.path.exists(dst):- os.rename(dst, backup)- swapped.append((dst, backup))- else:- swapped.append((dst, ""))- os.rename(staging, dst)- except OSError:- # Undo every swap already made so the install stays self-consistent.- for dst, backup in reversed(swapped):- try:- if os.path.isdir(dst):- shutil.rmtree(dst, ignore_errors=True)- elif os.path.exists(dst):- os.remove(dst)- if backup and os.path.exists(backup):- os.rename(backup, dst)- except OSError as exc:- # Keep restoring the rest — a silent failure here is the one- # thing that turns a recoverable rollback into a mixed tree,- # so say so rather than swallowing it.- logger.warning("rollback failed for %s: %s", dst, exc)- raise- # All swaps succeeded — drop the backups (best-effort, never fatal).- for _dst, backup in swapped:- if backup and os.path.isdir(backup):- shutil.rmtree(backup, ignore_errors=True)- elif backup and os.path.exists(backup):- try:- os.remove(backup)- except OSError:- pass---def _branch_head_label(git_cmd=None, cwd=None) -> str | None:- """``"<branch> @ <short-sha>"`` for the checkout, or None when unknown.-- Appended to the update summary lines so branch drift is visible at a- glance (live incident 2026-08-17: a checkout parked on a stale feature- branch got "✓ Update complete!" with nothing on the line saying WHERE- the checkout actually sat). Never raises — summary decoration must not- break an update.- """- try:- cmd = list(git_cmd) if git_cmd else ["git"]- root = cwd if cwd is not None else _m().PROJECT_ROOT- branch = subprocess.run(- cmd + ["rev-parse", "--abbrev-ref", "HEAD"],- cwd=root, capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- sha = subprocess.run(- cmd + ["rev-parse", "--short", "HEAD"],- cwd=root, capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- branch_name = branch.stdout.strip()- sha_text = sha.stdout.strip()- if branch.returncode != 0 or sha.returncode != 0 or not sha_text:- return None- if not branch_name:- return None- label = "detached" if branch_name == "HEAD" else branch_name- return f"{label} @ {sha_text}"- except Exception:- return None---def _branch_head_suffix(git_cmd=None, cwd=None) -> str:- """`` [<branch> @ <sha>]`` suffix for summary lines ("" when unknown)."""- label = _branch_head_label(git_cmd, cwd)- return f" [{label}]" if label else ""---def _assess_parked_branch_switch(- git_cmd: list[str], cwd: Path, current_branch: str, target_branch: str-) -> tuple[bool, str]:- """Decide whether it is safe to auto-switch a parked feature branch back- to the update target.-- Live incident (2026-08-17, Teknium's box): the source checkout sat on a- stale feature branch left behind by earlier tooling; ``hermes update``- autostashed, ran its post-update steps and printed "✓ Code updated!"- while the running code stayed days behind main. The guard's contract:-- - (True, "") when the working tree + index are clean AND every commit on- the parked branch is already contained in ``origin/<target_branch>``- (``git cherry`` reports no ``+`` lines).- - (True, "unmerged:<count>") when the tree is clean but the branch has- commits not yet in the target. Switching is safe — ``git checkout``- never discards committed work and the branch keeps the commits — but- the caller must print a LOUD notice naming the branch and count so the- work is not forgotten. This is what non-interactive callers (desktop- update button, gateway /update, cron) rely on: they have no way to- resolve a skip, so a clean checkout must always reach the target.- - (False, <reason>) — dirty tree, git errors, or the- ``updates.auto_switch_parked_branch: false`` config opt-out — and the- caller must NOT touch the branch. A dirty tree is the one genuinely- unsafe case: uncommitted work would have to ride an autostash across- branches, which is how the 2026-08-17 incident started.-- Block reasons: "disabled", "dirty", "unverifiable".- """- try:- from hermes_cli.config import load_config-- _update_cfg = (load_config() or {}).get("updates", {})- if isinstance(_update_cfg, dict) and not bool(- _update_cfg.get("auto_switch_parked_branch", True)- ):- return False, "disabled"- except Exception as exc:- # A config read failure must not disable the guard's safety checks —- # fall through to them with the default (auto-switch allowed).- logger.debug("Could not read updates.auto_switch_parked_branch: %s", exc)-- status = subprocess.run(- git_cmd + ["status", "--porcelain"],- cwd=cwd, capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if status.returncode != 0:- return False, "unverifiable"- if status.stdout.strip():- return False, "dirty"-- cherry = subprocess.run(- git_cmd + ["cherry", f"origin/{target_branch}"],- cwd=cwd, capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if cherry.returncode != 0:- return False, "unverifiable"- unmerged = [- line for line in cherry.stdout.splitlines() if line.startswith("+")- ]- if unmerged:- # Clean tree: switching is safe (checkout keeps the commits on the- # branch). The reason string tells the caller to print the loud- # "branch kept with N unmerged commit(s)" notice.- return True, f"unmerged:{len(unmerged)}"- return True, ""---def _print_parked_branch_skip_warning(- git_cmd: list[str],- cwd: Path,- current_branch: str,- target_branch: str,- reason: str,-) -> None:- """LOUD block explaining why the code update was skipped on a parked- branch, with the behind-count and the exact commands to resolve."""- behind = None- try:- behind_result = subprocess.run(- git_cmd + ["rev-list", f"HEAD..origin/{target_branch}", "--count"],- cwd=cwd, capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if behind_result.returncode == 0 and behind_result.stdout.strip():- behind = int(behind_result.stdout.strip())- except Exception:- behind = None-- if reason == "dirty":- why = "the working tree has uncommitted changes"- elif reason == "disabled":- why = "updates.auto_switch_parked_branch is set to false in config.yaml"- else:- why = (- f"the branch state could not be verified against "- f"origin/{target_branch}"- )-- bar = "=" * 68- print()- print(bar)- print(f"⚠ CODE UPDATE SKIPPED — checkout is parked on '{current_branch}'")- print(f" Not auto-switching to {target_branch}: {why}.")- if behind is not None and behind > 0:- print(- f" This checkout is {behind} commit(s) BEHIND "- f"origin/{target_branch} — the code you are running is stale."- )- print()- print(" To resolve, inspect the branch and switch back yourself:")- print(f" git -C {cwd} status")- print(f" git -C {cwd} checkout {target_branch} && hermes update")- print(- " (commit or stash your work on the branch first if you want to "- "keep it)"- )- print(bar)---def _print_parked_branch_kept_notice(- current_branch: str, target_branch: str, unmerged_count: str-) -> None:- """LOUD notice printed when a clean parked branch with unmerged commits- is auto-switched back to the update target.-- Non-interactive callers (desktop update button, gateway /update, cron)- cannot resolve a skip, so a clean checkout always proceeds to the- target — but the unmerged work must be impossible to miss. The commits- are untouched: ``git checkout`` never discards committed work; the- branch keeps them until the user returns.- """- bar = "=" * 68- print()- print(bar)- print(- f"⚠ Checkout was parked on '{current_branch}' with "- f"{unmerged_count} commit(s) not merged into origin/{target_branch}."- )- print(- f" Switching to {target_branch} so the update can proceed — your "- f"commit(s) are safe on '{current_branch}'."- )- print()- print(" To pick the work back up later:")- print(f" git checkout {current_branch}")- print(bar)---def _print_update_completion(message: str) -> None:- """Print an update outcome plus, when the dashboard launched this run- with an action id, a terminal receipt line the Desktop can match after- the dashboard restarts (see #47359 / #58764).-- The outcome line carries the checkout's actual branch + HEAD short-sha- so branch drift is visible at a glance (2026-08-17 parked-branch- incident)."""- print(f"{message}{_branch_head_suffix()}")- action_id = os.environ.get("HERMES_ACTION_ID", "")- if len(action_id) == 32 and all(char in "0123456789abcdef" for char in action_id):- print(f"=== hermes-update completed {action_id} ===")---def _called_process_error_cmd_parts(exc: subprocess.CalledProcessError) -> list[str]:- """Normalize ``CalledProcessError.cmd`` into argv-style tokens."""- cmd = exc.cmd- if cmd is None:- return []- if isinstance(cmd, (str, bytes)):- text = cmd.decode("utf-8", "replace") if isinstance(cmd, bytes) else cmd- try:- return shlex.split(text, posix=os.name != "nt")- except ValueError:- return text.split()- return [str(part) for part in cmd]---def _called_process_error_is_git(exc: subprocess.CalledProcessError) -> bool:- """True when the failed subprocess was git itself."""- parts = _called_process_error_cmd_parts(exc)- if not parts:- return False- # Windows argv may use backslashes; basename() on POSIX would otherwise- # keep the whole path. Normalize separators before taking the name.- name = os.path.basename(parts[0].replace("\\", "/")).lower()- return name in {"git", "git.exe"}---def _called_process_error_is_python_dep_install(- exc: subprocess.CalledProcessError,-) -> bool:- """True when the failed subprocess was a uv/pip (or ensurepip) install."""- parts = [part.lower() for part in _called_process_error_cmd_parts(exc)]- if not parts:- return False- exe = os.path.basename(parts[0].replace("\\", "/"))- if "ensurepip" in parts:- return True- if "install" in parts and (- "pip" in parts or exe in {"pip", "pip.exe", "pip3", "pip3.exe", "uv", "uv.exe"}- ):- return True- return False---def _format_update_failure_stage(exc: subprocess.CalledProcessError) -> str:- """Name the update stage that actually failed.-- The git pull and the Python-dependency install share one ``try`` in- ``_cmd_update_impl``. Calling every ``CalledProcessError`` a git failure- (the historical Windows message) sent users hunting in the wrong place- and, worse, keyed the ZIP overlay on exception *type* rather than on git- actually having failed (#87304, #85840).- """- if _called_process_error_is_python_dep_install(exc):- return "Python dependency install failed"- if _called_process_error_is_git(exc):- return "Git update failed"- return "Update step failed"---def _shim_quarantine_error_type() -> "type[BaseException]":- """The strict-quarantine refusal type, resolved lazily through ``_m()``.+def _shim_quarantine_error_type() -> "type[BaseException]":+ """The strict-quarantine refusal type, resolved lazily through ``_m()``.Falls back to a never-raised private type when main.py lacks it (tornmid-update tree), so the ``except`` clause stays valid.@@ -1778,90 +422,8 @@ def _print_called_process_error_tail(print(f" {line}")-def _zip_overlay_block_reason(- root: Path, *, ignore_staging_artifacts: bool = False-) -> Optional[str]:- """Why overlaying a ZIP onto ``root`` would destroy work, or None if safe.-- The ZIP path swaps every top-level entry (except a tiny preserve set) and- then deletes the backups, so uncommitted edits and untracked files under- a replaced directory are gone. Fail closed when git status cannot run:- unknown dirtiness is not a license to clobber the tree (#87304).-- ``ignore_staging_artifacts`` is for the pre-swap re-check: phase 1 of the- two-phase replace creates ``*.hermes-update-staging`` siblings inside the- checkout, which git reports as untracked. Those are our own artifacts,- not user work — without the filter the re-check would always refuse.- """- if not (root / ".git").exists():- return None- git_cmd = ["git"]- if sys.platform == "win32":- git_cmd = ["git", "-c", "windows.appendAtomically=false"]- result = subprocess.run(- # -uall: a user-level ``status.showUntrackedFiles = no`` git config- # would otherwise hide untracked files and silently blind this guard.- # --ignored=matching: gitignored files are still USER DATA the ZIP- # overlay would permanently delete (logs, scratch files, local data)- # — a .gitignore entry must not blind the guard either (#87392).- # ``matching`` reports an ignored directory as one ``dir/`` line- # instead of enumerating its contents (cheaper, same verdict for the- # top-level filter below). NOTE: ``--ignored=all`` is NOT a valid- # git mode — it exits 128 and would fail-close every ZIP update.- git_cmd + ["status", "--porcelain", "--untracked-files=all", "--ignored=matching"],- cwd=root,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- )- if result.returncode != 0:- detail = (result.stderr or result.stdout or "").strip().splitlines()- suffix = f" ({detail[0]})" if detail else ""- return f"could not check the working tree{suffix}"- lines = [line for line in (result.stdout or "").splitlines() if line.strip()]- # --ignored=all reports the ZIP path's own preserved entries (venv,- # node_modules are gitignored on every normal install). The swap never- # touches those top-level entries, so they must not turn into a false- # dirty-tree refusal. Everything else — including ignored files — blocks.- lines = [line for line in lines if not _is_zip_preserved_entry_status_line(line)]- if ignore_staging_artifacts:- lines = [- line for line in lines if not _is_zip_staging_artifact_status_line(line)- ]- if lines:- return "the working tree has uncommitted changes or untracked files"- return None---_ZIP_STAGING_ARTIFACT_SUFFIXES = (".hermes-update-staging", ".hermes-update-old")# Single source of truth for the top-level entries the ZIP swap preserves —# consumed by both the dirty-tree filter below and _update_via_zip's swap loop.-_ZIP_PRESERVED_TOP_LEVEL = {"venv", "node_modules", ".git", ".env"}---def _is_zip_preserved_entry_status_line(line: str) -> bool:- """True when every path on a porcelain status line sits under a top-level- entry the ZIP swap preserves.-- The ``" -> "`` two-path split applies ONLY to rename/copy status codes- (R/C): porcelain v1 does not quote a plain filename containing spaces,- so an ignored file literally named ``venv -> node_modules`` on an- ``!!``/``??`` line must be treated as ONE path — splitting it would- filter it as two preserved tops and fail-open into the destructive swap.- Requiring EVERY path preserved keeps renames leaving a preserved dir- (``R venv/x -> src/x``) blocking, fail-closed.- """- status, payload = (line[:2], line[3:]) if len(line) >= 3 else ("", line)- is_rename = any(code in "RC" for code in status)- paths = payload.split(" -> ") if is_rename else [payload]- for path in paths:- top_level = (- path.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]- )- if top_level not in _ZIP_PRESERVED_TOP_LEVEL:- return False- return True# Release tags have the form v1.2.3. A tag can have a pre-release suffix.@@ -1870,44 +432,222 @@ def _is_zip_preserved_entry_status_line(line: str) -> bool:# (for example v2026.7.20) use a four-digit year, and a numeric sort would# rank them above every SemVer release. This matches _SEMVER_TAG_RE in# scripts/write_install_stamp.py.-_RELEASE_TAG_RE = re.compile(r"^v(0|[1-9]\d{0,2})\.(\d+)\.(\d+)$")-def _parse_release_tag(tag: str):- """Parse ``vX.Y.Z`` into a sortable (X, Y, Z) tuple, or return None.+def _invalidate_update_cache():+ """Delete the update-check cache for ALL profiles so no banner+ reports a stale "commits behind" count after a successful update.- Tags with a pre-release or build suffix (``v1.2.3-rc1``) return None.- Tags that do not have the shape of a final release also return None.- The stable channel only moves between final releases.+ The git repo is shared across profiles — when one profile runs+ ``hermes update``, every profile is now current."""- m = _RELEASE_TAG_RE.match(tag.strip())- if not m:- return None- return tuple(int(g) for g in m.groups())+ homes = []+ # Default profile home (Docker-aware — uses /opt/data in Docker)+ from hermes_constants import get_default_hermes_root+ default_home = get_default_hermes_root()+ homes.append(default_home)+ # Named profiles under <root>/profiles/+ profiles_root = default_home / "profiles"+ if profiles_root.is_dir():+ for entry in profiles_root.iterdir():+ if entry.is_dir():+ homes.append(entry)+ for home in homes:+ try:+ cache_file = home / ".update_check"+ if cache_file.exists():+ cache_file.unlink()+ except Exception:+ pass-def _latest_release_tag_from_ls_remote(output: str):- """Select the newest final-release tag from ``git ls-remote --tags`` output.- Returns ``(tag, sha)`` or ``(None, None)``. Peeled entries (``^{}``) have- priority over the tag-object SHA. Thus annotated tags and lightweight tags- both give the commit SHA.- """- best = None # (version_tuple, tag)- shas = {} # tag -> commit sha (peeled wins)- for line in output.splitlines():- parts = line.split("\t")- if len(parts) != 2:- continue- sha, ref = parts- if not ref.startswith("refs/tags/"):- continue- name = ref[len("refs/tags/"):]- peeled = name.endswith("^{}")- if peeled:- name = name[:-3]- version = _parse_release_tag(name)- if version is None:+def _write_marker_file(path: Path, *, label: str) -> None:+ """Drop an update-recovery breadcrumb. Never raises."""+ if _m()._pytest_owns_live_checkout(path.parent):+ logger.debug("Skipping %s marker under pytest (live checkout)", label)+ return+ try:+ path.write_text(+ f"started={_time.time()}\npid={os.getpid()}\n", encoding="utf-8"+ )+ except OSError as exc:+ logger.debug("Could not write %s marker: %s", label, exc)+++def _write_update_incomplete_marker() -> None:+ """Drop the interrupted core-install breadcrumb. Never raises."""+ _write_marker_file(_m()._update_marker_path(), label="update-incomplete")+++def _write_lazy_refresh_incomplete_marker() -> None:+ """Drop the interrupted lazy-refresh breadcrumb. Never raises."""+ _write_marker_file(_m()._lazy_refresh_marker_path(), label="lazy-refresh-incomplete")+++def _format_concurrent_instances_message(+ matches: list[tuple[int, str]], scripts_dir: Path+) -> str:+ """Build a human-readable explanation + remediation hint for the user."""+ shim = scripts_dir / "hermes.exe"+ lines = ["✗ Another hermes.exe is running:"]+ for pid, name in matches:+ lines.append(f" PID {pid} {name}")+ lines.append("")+ lines.append(f" Updating now would fail to overwrite {shim} because")+ lines.append(" Windows blocks REPLACE on a running executable.")+ lines.append("")+ lines.append(" Close Hermes Desktop, exit any open `hermes` REPLs, and")+ lines.append(" stop the gateway (`hermes gateway stop`) before retrying.")+ lines.append("")+ if matches:+ pid_args = " ".join(f"/PID {pid}" for pid, _ in matches)+ lines.append(" If you've already closed everything and these PIDs are")+ lines.append(" stale, terminate them directly, then retry the update:")+ lines.append(f" taskkill {pid_args} /F")+ lines.append("")+ lines.append(" Override with `hermes update --force` if you've already")+ lines.append(" confirmed those processes will not write to the venv.")+ return "\n".join(lines)+++def _classify_concurrent_instance(pid: int) -> str:+ """Return ``"gateway"`` when ``pid``'s command line is a gateway runtime.++ Delegates to ``_is_pausable_gateway`` — the same canonical+ ``gateway run`` matcher (``gateway.status.looks_like_gateway_command_line``,+ shlex-tokenized, profile-selector aware) used by the Desktop preflight+ exemption and the venv-holder guard fallback — so a PID classified as+ ``"gateway"`` here is exactly the set the pause/kill+restart machinery+ downstream will stop. That symmetry is what lets the pre-update+ concurrent gate skip the abort for gateway-only matches: the gateway is+ going to be stopped by ``_pause_windows_gateways_for_update()`` moments+ later anyway, so refusing the update just to make the user kill it+ manually is friction without benefit.++ Returns ``"non-gateway"`` when the cmdline doesn't match, and+ ``"unknown"`` when psutil can't read it (process gone, access denied,+ psutil missing). The gate treats ``"unknown"`` as non-gateway — we'd+ rather block an update we could have completed than proceed against a+ process we couldn't positively identify as a gateway.+ """+ try:+ import psutil # noqa: PLC0415+ except Exception:+ return "unknown"++ try:+ proc = psutil.Process(int(pid))+ cmdline_list = proc.cmdline()+ except Exception:+ return "unknown"++ from hermes_cli._scan_venv_blockers import _is_pausable_gateway # noqa: PLC0415++ cmdline = " ".join(cmdline_list or [])+ if _is_pausable_gateway(cmdline):+ return "gateway"+ return "non-gateway"+++def _filter_non_gateway_concurrent_instances(+ matches: list[tuple[int, str]],+) -> list[tuple[int, str]]:+ """Return only the concurrent-instance matches that are NOT the gateway.++ Used by the pre-update concurrent gate to decide whether to abort+ ``hermes update``. If every concurrent instance is a gateway, the pause+ machinery (``_pause_windows_gateways_for_update``) and the post-update+ kill+restart block handle it — the update proceeds. If anything else (a+ TUI shell, a Hermes Desktop backend child, an unrelated ``hermes`` REPL)+ is in the list, the gate still aborts with the existing message, since+ those have no pause machinery downstream.+ """+ non_gateway: list[tuple[int, str]] = []+ for pid, name in matches:+ if _classify_concurrent_instance(pid) != "gateway":+ non_gateway.append((pid, name))+ return non_gateway+++def _log_only_write(text: str) -> None:+ """Write ``text`` to ``~/.hermes/logs/update.log`` only, never the terminal.++ During ``hermes update`` ``sys.stdout`` is an ``_UpdateOutputStream`` that+ mirrors to both the terminal and ``update.log``. Loud, low-signal+ subprocess output (npm installs, the Electron/vite build, the cua-driver+ installer's "Next steps" wall) should be captured and tucked into the log+ so failures stay debuggable, without flooding the user's terminal. This+ reaches past the mirroring stream straight to the underlying log handle.+ """+ if not text:+ return+ stream = _m().sys.stdout+ log_file = getattr(stream, "_log", None)+ if log_file is None:+ return+ try:+ log_file.write(text if text.endswith("\n") else text + "\n")+ log_file.flush()+ except Exception:+ pass+++def _run_logged_subprocess(cmd, *, cwd=None, env=None):+ """Run ``cmd`` capturing combined output into update.log (not the terminal).++ Returns the ``CompletedProcess`` (with ``stdout`` populated) so the caller+ can decide whether to surface the captured output on failure.+ """+ result = subprocess.run(+ cmd,+ cwd=cwd,+ env=env,+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ _log_only_write(result.stdout or "")+ return result+++_RELEASE_TAG_RE = re.compile(r"^v(0|[1-9]\d{0,2})\.(\d+)\.(\d+)$")+def _parse_release_tag(tag: str):+ """Parse ``vX.Y.Z`` into a sortable (X, Y, Z) tuple, or return None.++ Tags with a pre-release or build suffix (``v1.2.3-rc1``) return None.+ Tags that do not have the shape of a final release also return None.+ The stable channel only moves between final releases.+ """+ m = _RELEASE_TAG_RE.match(tag.strip())+ if not m:+ return None+ return tuple(int(g) for g in m.groups())+def _latest_release_tag_from_ls_remote(output: str):+ """Select the newest final-release tag from ``git ls-remote --tags`` output.++ Returns ``(tag, sha)`` or ``(None, None)``. Peeled entries (``^{}``) have+ priority over the tag-object SHA. Thus annotated tags and lightweight tags+ both give the commit SHA.+ """+ best = None # (version_tuple, tag)+ shas = {} # tag -> commit sha (peeled wins)+ for line in output.splitlines():+ parts = line.split("\t")+ if len(parts) != 2:+ continue+ sha, ref = parts+ if not ref.startswith("refs/tags/"):+ continue+ name = ref[len("refs/tags/"):]+ peeled = name.endswith("^{}")+ if peeled:+ name = name[:-3]+ version = _parse_release_tag(name)+ if version is None:continueif peeled or name not in shas:shas[name] = sha.strip()@@ -1917,8 +657,6 @@ def _latest_release_tag_from_ls_remote(output: str):return None, Nonetag = best[1]return tag, shas.get(tag)--def _resolve_latest_release_tag(git_cmd, cwd):"""Ask origin for the newest final release tag. Returns (tag, sha) or (None, None)."""try:@@ -1939,8 +677,6 @@ def _resolve_latest_release_tag(git_cmd, cwd):)return None, Nonereturn _latest_release_tag_from_ls_remote(result.stdout)--def _stable_channel_active(args) -> bool:"""Return True when this update must track tagged releases, not a branch.@@ -1973,8 +709,6 @@ def _stable_channel_active(args) -> bool:except Exception as exc:logger.warning("Channel resolution failed; defaulting to main: %s", exc)return False--def _github_latest_release_tag():"""Resolve the newest final-release tag with the GitHub API (no git necessary).@@ -2017,9144 +751,1059 @@ def _github_latest_release_tag():return None-def _is_zip_staging_artifact_status_line(line: str) -> bool:- """True when a porcelain status line is our own two-phase-swap artifact."""- payload = line[3:] if len(line) >= 3 else line- top_level = (- payload.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]- )- return top_level.endswith(_ZIP_STAGING_ARTIFACT_SUFFIXES)---def _abort_zip_update_if_dirty_tree() -> None:- """Refuse to overlay a ZIP onto a dirty git checkout (#87304)."""- reason = _zip_overlay_block_reason(_m().PROJECT_ROOT)- if reason is None:- return- print(f"✗ ZIP fallback refused: {reason}.")- print(- " Overlaying the ZIP would overwrite uncommitted edits and permanently "- "delete untracked files."- )- print(" Stash or commit your changes, then rerun `hermes update`.")- print(" To inspect: git status --porcelain")- _m().sys.exit(1)---def _read_project_version() -> str | None:- """Read the ``version`` field from the checkout's pyproject.toml.-- Reads the on-disk file (not importlib.metadata) because after a git- pull the installed distribution metadata still describes the OLD- version; the file is the only source that reflects what was just- pulled. Returns None on any failure — version reporting is cosmetic- and must never break an update.- """- try:- import tomllib-- with open(_m().PROJECT_ROOT / "pyproject.toml", "rb") as fh: # windows-footgun: ok — binary mode, tomllib requires bytes- version = tomllib.load(fh).get("project", {}).get("version")- return str(version) if version else None- except Exception:- return None-+def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):+ """Implement ``hermes update --check``: fetch and report without installing.-def _update_complete_message(pre_version: str | None) -> str:- """Completion line with the version transition when it is known.+ ``branch`` selects which branch the check compares against. Default is+ "main"; callers can pass another branch to ask "are there new commits+ on origin/<branch>?" without performing the update.- Ported from PrimeIntellect-ai/prime-agent#630: after a successful- self-update, show both versions (``v0.19.4 → v0.20.0``) so the user- can see what they actually got. Falls back to the plain message when- either side is unknown or the version did not change (e.g. several- commits landed within one release).+ ``branch_explicit`` is True iff the caller passed --branch on the CLI.+ Installs that can't honor non-default branches (e.g. Docker) surface a+ one-line notice instead of silently dropping the flag."""- post_version = _read_project_version()- if pre_version and post_version and pre_version != post_version:- return f"✓ Update complete! (v{pre_version} → v{post_version})"- if post_version:- return f"✓ Update complete! (v{post_version})"- return "✓ Update complete!"---def _post_update_sqlite_runtime_status():- """Return whether the interpreter used after update has safe SQLite."""- from hermes_constants import project_venv_dir- from hermes_cli.sqlite_runtime import probe_sqlite_runtime-- venv_dir = project_venv_dir(_m().PROJECT_ROOT)- python = (- venv_python_path(venv_dir, windows=_m()._is_windows())- if venv_dir is not None- else Path(sys.executable)+ # Shared admission gate (#91277 Phase 3): same marker-first decision as+ # the apply path, so --check can never report git state for an install+ # whose real update mechanism is an image pull.+ from hermes_cli.update_contract import (+ evaluate_update_admission,+ record_refusal_receipt,)- info = probe_sqlite_runtime(python)- return info is not None and not info.wal_reset_vulnerable, info+ refusal = evaluate_update_admission(_m().PROJECT_ROOT)+ if refusal is not None:+ print(refusal.message)+ record_refusal_receipt(refusal)+ sys.exit(2)-def _print_verified_update_completion(message: str) -> bool:- """Print a success completion only after probing the next Hermes runtime."""- if not message.startswith("✓"):- _print_update_completion(message)- return False- sqlite_runtime_ok, sqlite_info = _post_update_sqlite_runtime_status()- if sqlite_info is None:- # Grace path: an unprobeable interpreter (no venv in a dev checkout,- # probe subprocess unavailable) must not fail an otherwise-successful- # update — only a POSITIVE vulnerable probe withholds success- # (same contract as _venv_core_imports_healthy's unknown states).- logger.debug("Post-update SQLite runtime probe unavailable; not blocking")- _print_update_completion(message)- return True- if sqlite_runtime_ok:- _print_update_completion(message)- return True- print()- detail = (- f"SQLite {sqlite_info.sqlite_version_string} still has the "- "WAL-reset corruption bug"- )- print(f"⚠ Update partially complete — {detail}.")- print(- " Rebuild the Hermes venv with a uv-managed Python, restart Hermes, "- "then verify with `hermes doctor`."- )- return False+ git_dir = _m().PROJECT_ROOT / ".git"+ if not git_dir.exists():+ print("✗ Not a git repository — cannot check for updates.")+ sys.exit(1)+ git_cmd = ["git"]+ if sys.platform == "win32":+ git_cmd = ["git", "-c", "windows.appendAtomically=false"]-def _clear_stale_sqlite_sidecars(db_path: Path) -> None:- """Delete the WAL / shared-memory / rollback-journal files next to *db_path*.+ # A crashed/interrupted fetch can leave .git/shallow.lock (or another git+ # lock file) behind; every later fetch then fails with "File exists" and+ # the check reports a hard failure (or, in the banner path, silently+ # compares stale refs). Self-heal abandoned locks before fetching.+ from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs- Call this immediately before overwriting a database file with a snapshot- image. Quick snapshots are produced by ``backup._safe_copy_db`` through- ``sqlite3.backup()``, so the image is already checkpointed and owns no WAL —- which is exactly why ``backup._EXCLUDED_SUFFIXES`` refuses to ship sidecars- inside a snapshot. Copying the image over the destination replaces only the- main database file, so any ``-wal`` / ``-shm`` left behind by the *old*- database (a crashed writer, or a second Hermes process the updater's drain- did not stop) survives and is replayed over the fresh image on the next- open. The result passes ``PRAGMA integrity_check`` while serving the old- database's contents, and the first checkpoint folds it in permanently.+ cleared = clear_stale_git_locks(_m().PROJECT_ROOT)+ for lock_path in cleared:+ print(f" (removed stale git lock: {lock_path})")+ # Aborted fetches on flaky lines also strand tmp_pack_* debris in+ # .git/objects/pack — unchecked it reached 6 GB and corrupted the pack+ # dir outright (#93732). Same age+process safety contract as the locks.+ swept = clear_stale_tmp_packs(_m().PROJECT_ROOT)+ if swept:+ print(f" (removed {len(swept)} aborted-fetch pack temp file(s))")- Removing them is safe here specifically: they belong to a database the- caller has already declared corrupt and is about to discard.- """- for suffix in ("-wal", "-shm", "-journal"):- db_path.with_name(db_path.name + suffix).unlink(missing_ok=True)+ # Stable channel: if the caller did not ask for a branch, the question is+ # "is there a newer tagged release?". The question is not "are there new+ # commits on main?". Compare against the newest release tag and return.+ if not branch_explicit:+ if _stable_channel_active(None):+ print("→ Update channel: stable (tagged releases)")+ tag, tag_sha = _resolve_latest_release_tag(git_cmd, _m().PROJECT_ROOT)+ if tag is None:+ print("✗ No release tags found on origin. A check of the stable channel is not possible.")+ print(" Switch channels with: hermes update --set-channel main")+ sys.exit(1)+ head_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)+ # Newer releases possibly do not exist locally yet. "At the tag"+ # is a SHA comparison. The merge-base check tells us whether HEAD+ # contains the tag (HEAD is ahead of the release or at the release).+ at_or_past_tag = False+ if head_sha and tag_sha:+ if head_sha == tag_sha:+ at_or_past_tag = True+ else:+ contained = subprocess.run(+ git_cmd + ["merge-base", "--is-ancestor", tag_sha, "HEAD"],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ )+ at_or_past_tag = contained.returncode == 0+ if at_or_past_tag:+ print(f"✓ Up to date with the latest release ({tag}).")+ else:+ print(f"→ New release available: {tag}")+ print(" Run `hermes update` to install it.")+ return+ # Fetch only the branch we compare against; prefer upstream as the canonical+ # reference. A bare `git fetch <remote>` pulls every ref, and this repo has+ # thousands of auto-generated branches, so scope the fetch to <branch>.+ # Note: upstream/<branch> may not exist for non-main branches (a fork's+ # bb/gui has no upstream counterpart), so when the caller picks a+ # non-default branch we skip the upstream probe and use origin directly.+ # Installer checkouts are shallow (`git clone --depth 1`). A plain+ # `git fetch` would unshallow the repo (dragging in the whole history —+ # the exact cost the shallow clone avoided) and the rev-list count below+ # would then report a huge bogus "behind" number. Detect shallow up front:+ # fetch with --depth 1 to preserve the boundary and report presence-only.+ is_shallow = (+ subprocess.run(+ git_cmd + ["rev-parse", "--is-shallow-repository"],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ ).stdout.strip()+ == "true"+ )+ depth_args = ["--depth", "1"] if is_shallow else []-def _print_update_summary(- *,- node_failures: list,- desktop_build_ok: bool,- pre_update_version: str | None,-) -> bool:- """Final update banner. A failed Desktop rebuild is non-fatal for the- Python side, but must not print ``✓ Update complete!`` (#88251)."""- sqlite_runtime_ok, sqlite_info = _post_update_sqlite_runtime_status()- if sqlite_info is None:- # Grace path: an unprobeable interpreter must not fail the update —- # only a POSITIVE vulnerable probe demotes success to partial.- sqlite_runtime_ok = True- print()- if node_failures or not desktop_build_ok or not sqlite_runtime_ok:- parts = []- if node_failures:- parts.append(- f"Node.js dependencies for {', '.join(node_failures)} did not refresh"- )- if not desktop_build_ok:- parts.append(- "the desktop app was not rebuilt and is still on the previous build"- )- if not sqlite_runtime_ok and sqlite_info is not None:- parts.append(- f"SQLite {sqlite_info.sqlite_version_string} still has the "- "WAL-reset corruption bug"+ if branch == "main":+ # Probe locally (~6 ms) whether an 'upstream' remote exists at all+ # before spending a network fetch on it. Non-fork installs have no+ # 'upstream' remote, and the old flow burned a failed network attempt+ # (~0.3-1 s) on every --check before falling back to origin.+ has_upstream_remote = (+ subprocess.run(+ git_cmd + ["remote", "get-url", "upstream"],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ ).returncode+ == 0+ )+ fetch_result = None+ if has_upstream_remote:+ print("→ Fetching from upstream...")+ fetch_result = subprocess.run(+ git_cmd + ["fetch"] + depth_args + ["upstream", branch],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ **_no_prompt_git_kwargs(),)- print("⚠ Update partially complete — " + "; ".join(parts) + ".")- if node_failures:- print(" Code and Python deps are updated, but the dashboard/TUI may")- print(" be in a mixed state until the Node deps are rebuilt.")- if not desktop_build_ok:- print(" Run `hermes desktop` to retry the desktop rebuild.")- if not sqlite_runtime_ok:- print(- " The Python runtime remediation did not complete. Run `hermes "- "update` again; if SQLite is unchanged, rebuild the Hermes venv "- "with a uv-managed Python, restart Hermes, then verify with "- "`hermes doctor`."+ if fetch_result is not None and fetch_result.returncode == 0:+ upstream_exists = True+ compare_branch = f"upstream/{branch}"+ else:+ # No upstream remote, or the upstream fetch failed — use origin.+ print("→ Fetching from origin...")+ fetch_result = subprocess.run(+ git_cmd + ["fetch"] + depth_args + ["origin", branch],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ **_no_prompt_git_kwargs(),)+ upstream_exists = False+ compare_branch = f"origin/{branch}"else:- _print_update_completion(_update_complete_message(pre_update_version))- return desktop_build_ok and sqlite_runtime_ok---def _write_gateway_update_exit_code(ok: bool) -> None:- path = get_hermes_home() / ".update_exit_code"- try:- path.write_text("0" if ok else "1", encoding="utf-8")- except OSError:- pass---def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:- """Replace *state_path* with the snapshot image at *snap_state*.-- Shared by both post-update auto-restore paths (the ZIP update and the git- pull). The destination's stale sidecars are cleared before the copy, so the- restored image cannot be silently overwritten by the corrupt database's WAL- replay — see :func:`_clear_stale_sqlite_sidecars`.-- Refuses (returns ``False``) while another process — or a live connection- in THIS process — still holds the database or its sidecars open: copying a- snapshot over a live writer's inode makes the writer's page cache and WAL- index disagree with the file bytes, and its next checkpoint writes pages- at offsets that no longer mean what it thinks — the #90950 page-1 clobber.- ``None`` (scan unavailable) proceeds: the updater has already drained- gateways, and refusing on "unknown" would disable auto-restore on every- non-Linux host.-- Returns ``True`` when the restored file passes an integrity check. Raises- ``OSError`` if the copy itself fails, which callers already report.- """- from hermes_cli.backup import _foreign_db_holder_pids, verify_sqlite_integrity- from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access-- holders = _foreign_db_holder_pids(state_path)- if holders:- print(- f" ✗ Auto-restore refused: process(es) {holders} still hold "- "state.db or its WAL open. Stop them (hermes gateway stop), "- "then restore manually with /snapshot restore."- )- return False- # The foreign-pid scan excludes THIS process on purpose, but an- # in-process SessionDB handle is exactly as much of a live holder:- # unlinking the -wal/-shm and copy2-ing over the main file under it- # leaves this process checkpointing through deleted-inode sidecars —- # the #90950 split brain produced first-party (proven live on main:- # `/proc/self/fd` shows `state.db-wal (deleted)` right after this ran- # under a tracked connection). ``offline_file_access`` fails CLOSED on- # any tracked live connection and holds the connection-lifecycle lock- # across the sidecar clear + copy so none can appear mid-swap.- try:- with offline_file_access(state_path, what="restore a snapshot over"):- _clear_stale_sqlite_sidecars(state_path)- shutil.copy2(snap_state, state_path)- except LiveConnectionError as exc:- print(- f" ✗ Auto-restore refused: {exc} Close the in-process database "- "handles (or restart Hermes) and retry."+ # Non-default branch: compare against origin/<branch> directly.+ print("→ Fetching from origin...")+ fetch_result = subprocess.run(+ git_cmd + ["fetch"] + depth_args + ["origin", branch],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ **_no_prompt_git_kwargs(),)- return False- restored = verify_sqlite_integrity(- state_path, check_header=True, run_pragma=True- )- return bool(restored.get("valid"))---def _verify_and_restore_one_state_db(home: Path, *, label: str) -> None:- """Post-update integrity check + auto-restore for ONE home's state.db.-- Shared by the root-DB and sibling-profile guards (ZIP update path and- git-pull path both route here). A corrupt live DB is restored from the- most recent valid snapshot under that home's own state-snapshots dir.- Never raises: a guard that crashes the update tail would be worse than- the corruption it detects.- """- try:- from hermes_cli.backup import _quick_snapshot_root, verify_sqlite_integrity+ upstream_exists = False+ compare_branch = f"origin/{branch}"- state_path = home / "state.db"- if not state_path.exists():- return- ok = verify_sqlite_integrity(state_path, check_header=True, run_pragma=True)- if ok.get("valid"):- logger.debug(- "Post-update state.db integrity OK (%s): %s",- label,- ok.get("message"),- )- return- print()- print(- f"⚠ state.db is corrupted after update ({label}): "- + ok.get("message", "unknown error")- )- snap_root = _quick_snapshot_root(home)- if not snap_root.exists():- print(" ⚠ No pre-update snapshot for this home")- return- for snap_dir in sorted(- (d for d in snap_root.iterdir() if d.is_dir()), reverse=True- ):- snap_state = snap_dir / "state.db"- if not snap_state.exists():- continue- snap_ok = verify_sqlite_integrity(- snap_state, check_header=True, run_pragma=True- )- if not snap_ok.get("valid"):- continue- try:- if _restore_state_db_from_snapshot(state_path, snap_state):- print(- f" ✓ Auto-restored from snapshot {snap_dir.name} ({label})"- )- else:- print(- " ✗ Auto-restore FAILED — restored copy also failed "- "integrity"- )- except OSError as exc:- print(f" ✗ Auto-restore file copy failed: {exc}")- return- print(" ⚠ No valid pre-update snapshot found for this home")- except Exception as exc:- logger.debug(- "Post-update state.db guard (%s) failed: %s", label, exc- )+ if fetch_result.returncode != 0:+ _print_fetch_failure(fetch_result.stderr)+ sys.exit(1)+ # Verify the compare ref actually exists before asking rev-list about it.+ # Without this, `git rev-list HEAD..origin/<bogus> --count` exits 128 and+ # (with check=True) raises CalledProcessError, surfacing a Python+ # traceback. Friendlier to detect-and-report.+ verify_result = subprocess.run(+ git_cmd + ["rev-parse", "--verify", "--quiet", compare_branch],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ )+ if verify_result.returncode != 0:+ print(f"✗ Branch '{branch}' not found on {compare_branch.split('/', 1)[0]}.")+ sys.exit(1)-def _verify_and_restore_state_dbs_post_update() -> None:- """Post-update integrity guard for the ROOT state.db AND every sibling- profile's state.db (#97994).+ if is_shallow:+ # No history to count across the shallow boundary. Compare tip SHAs+ # (mirrors the banner's _check_via_local_git), then try to recover the+ # exact count via the GitHub compare API — the remote graph is complete+ # even when the local one is truncated.+ head_sha = subprocess.run(+ git_cmd + ["rev-parse", "HEAD"],+ cwd=_m().PROJECT_ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace",+ ).stdout.strip()+ target_sha = subprocess.run(+ git_cmd + ["rev-parse", compare_branch],+ cwd=_m().PROJECT_ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace",+ ).stdout.strip()+ if head_sha and target_sha and head_sha == target_sha:+ print("✓ Already up to date.")+ else:+ from hermes_cli.banner import _github_compare_behind+ from hermes_cli.config import recommended_update_command- The pre-update snapshot already covers every sibling profile- (#66140 create_pre_update_snapshots_all_profiles), but the post-update- guard only ever verified the root DB — a profile database corrupted by- the update was never detected and never auto-restored, leaving that- profile's sessions silently gone while the root DB passed.- """- home = get_hermes_home()- _verify_and_restore_one_state_db(home, label="default home")- try:- from hermes_cli.backup import _sibling_profile_homes+ counted = _github_compare_behind(head_sha, target_sha)+ if counted == 0:+ # Local commits on top of the remote tip — not behind.+ print("✓ Already up to date.")+ return+ if counted is not None:+ commits_word = "commit" if counted == 1 else "commits"+ print(f"⚕ Update available: {counted} {commits_word} behind {compare_branch}.")+ else:+ print(f"⚕ Update available (behind {compare_branch}).")+ print(f" Run '{recommended_update_command()}' to install.")+ return- for name, profile_home in _sibling_profile_homes(home):- _verify_and_restore_one_state_db(profile_home, label=f"profile {name}")- except Exception as exc:- logger.debug("Sibling-profile state.db guard sweep failed: %s", exc)+ rev_result = subprocess.run(+ git_cmd + ["rev-list", f"HEAD..{compare_branch}", "--count"],+ cwd=_m().PROJECT_ROOT,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ check=True,+ )+ behind = int(rev_result.stdout.strip())+ if behind == 0:+ print("✓ Already up to date.")+ else:+ commits_word = "commit" if behind == 1 else "commits"+ print(f"⚕ Update available: {behind} {commits_word} behind {compare_branch}.")+ from hermes_cli.config import recommended_update_command-def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> bool:- """Update Hermes Agent by downloading a ZIP archive.+ print(f" Run '{recommended_update_command()}' to install.")- Used on Windows when git file I/O is broken (antivirus, NTFS filter- drivers causing 'Invalid argument' errors on file creation).- Returns ``False`` when a Desktop rebuild ran and failed; ``True`` otherwise.- """- active_tool_dependencies = _m()._capture_active_tool_dependencies()+def _base_git_cmd() -> list[str]:+ """``git`` argv; Windows adds ``-c windows.appendAtomically=false`` (git can fail "unable to+ write loose object file: Invalid argument" on non-atomic appends)."""+ if sys.platform == "win32":+ return ["git", "-c", "windows.appendAtomically=false"]+ return ["git"]- import tempfile- import zipfile- from urllib.request import urlretrieve- # Snapshot the pre-update version before files are replaced so the- # completion line can report the transition (prime-agent#630 port).- pre_update_version = _read_project_version()+def _is_shallow_checkout(git_cmd) -> bool:+ return _git_run(git_cmd, ["rev-parse", "--is-shallow-repository"]).stdout.strip() == "true"- # The ZIP fallback exists for Windows git-file-I/O breakage. It pulls a- # static archive from GitHub, which is fine for the default "main"- # channel but would silently ignore --branch and update from main even- # if the user asked for something else — exactly the silent-divergence- # bug --branch was added to prevent. Refuse to proceed in that case- # rather than lie.- branch = _m()._resolve_update_branch(args)- if branch != "main":- print(- f"✗ --branch={branch} is not supported on the Windows ZIP-fallback "- "update path."- )- print(- " This path runs when git file I/O is broken on the system. "- "Either resolve the git-side breakage (typically an antivirus "- "or NTFS filter holding files open) and rerun `hermes update "- f"--branch {branch}`, or update against main with `hermes update`."- )- _m().sys.exit(1)- _abort_zip_update_if_dirty_tree()- # Stable channel: pull the archive of the release tag, not main. The ZIP- # path runs when git file I/O is broken. Thus resolve the tag with the- # GitHub API, not with git. No git invocation is necessary.- zip_ref = f"refs/heads/{branch}"- if _stable_channel_active(args):- tag = _github_latest_release_tag()- if tag is None:- print("✗ Hermes cannot resolve the latest release from the GitHub API.")- print(" Switch channels with: hermes update --set-channel main")- _m().sys.exit(1)- print(f"→ Update channel: stable. Hermes downloads release {tag}.")- zip_ref = f"refs/tags/{tag}"- zip_url = (- f"https://github.com/NousResearch/hermes-agent/archive/{zip_ref}.zip"- )- print("→ Downloading latest version...")- tmp_dir = tempfile.mkdtemp(prefix="hermes-update-")- try:- zip_path = os.path.join(tmp_dir, f"hermes-agent-{branch}.zip")- urlretrieve(zip_url, zip_path)-- print("→ Extracting...")- import stat as _stat- with zipfile.ZipFile(zip_path, "r") as zf:- # Validate paths to prevent zip-slip (path traversal) AND reject- # symlink members. A GitHub source ZIP for hermes-agent itself- # should never contain symlinks — they'd point outside the- # extracted tree and let an attacker who can compromise the- # update mirror plant arbitrary files via the update path.- tmp_dir_real = os.path.realpath(tmp_dir)- for member in zf.infolist():- member_path = os.path.realpath(os.path.join(tmp_dir, member.filename))- if (- not member_path.startswith(tmp_dir_real + os.sep)- and member_path != tmp_dir_real- ):- raise ValueError(- f"Zip-slip detected: {member.filename} escapes extraction directory"- )- # Unix mode lives in the upper 16 bits of external_attr;- # mask to the file-type bits.- mode = (member.external_attr >> 16) & 0o170000- if _stat.S_ISLNK(mode):- raise ValueError(- f"ZIP contains unsupported symlink member: {member.filename}"- )- zf.extractall(tmp_dir)-- # GitHub ZIPs extract to hermes-agent-<branch>/- extracted = os.path.join(tmp_dir, f"hermes-agent-{branch}")- if not os.path.isdir(extracted):- # Try to find it- for d in os.listdir(tmp_dir):- candidate = os.path.join(tmp_dir, d)- if os.path.isdir(candidate) and d != "__MACOSX":- extracted = candidate- break-- # Copy updated files over existing installation, preserving venv/node_modules/.git- preserve = _ZIP_PRESERVED_TOP_LEVEL- entries = [i for i in os.listdir(extracted) if i not in preserve]-- # Two-phase replace (#76104). Phase 1 copies every entry — directories- # AND top-level files — to a sibling staging path without touching- # anything live; phase 2 swaps them all in with same-filesystem- # renames and rolls back every swap if any one fails. Replacing- # entries one-at-a-time (the previous shape) meant an interruption- # partway left `agent/` new and `tools/` stale — all files valid, the- # tree unbootable. Files matter as much as directories here: the repo- # root holds 20 first-party modules (run_agent.py, cli.py,- # hermes_constants.py, ...).- #- # Staging costs one extra copy of the tree on disk. Check up front so- # we fail with a clear message instead of running out mid-copy.- need = sum(- os.path.getsize(os.path.join(dirpath, f))- for entry in entries- for dirpath, _dirs, files in os.walk(os.path.join(extracted, entry))- for f in files- ) + sum(- os.path.getsize(os.path.join(extracted, e))- for e in entries- if os.path.isfile(os.path.join(extracted, e))- )- # Only the staging copy is new — the live tree already occupies its- # space and the swaps are renames, not copies. Ask for the staging- # copy plus 20% headroom rather than a full 2x, which would block- # updates that would have succeeded on exactly the space-constrained- # machines most likely to hit this path.- required = int(need * 1.2)- free = shutil.disk_usage(str(_m().PROJECT_ROOT)).free- if free < required:- raise RuntimeError(- f"not enough free disk space to stage the update safely "- f"(need ~{required // (1024 * 1024)} MB, have "- f"{free // (1024 * 1024)} MB)"- )+def _tip_shas(git_cmd, target_ref: str) -> tuple[str, str]:+ """``(HEAD sha, <target_ref> sha)`` as printed by rev-parse ("" when unresolvable)."""+ return tuple(_git_run(git_cmd, ["rev-parse", ref]).stdout.strip() for ref in ("HEAD", target_ref))- staged: list[tuple[str, str]] = []- try:- for item in entries:- src = os.path.join(extracted, item)- dst = os.path.join(str(_m().PROJECT_ROOT), item)- staged.append((_stage_replacement(src, dst), dst))- # #70337/#87331: the GitHub source ZIP contains only source —- # apps/desktop/release/ (the BUILT desktop app, win-unpacked/- # Hermes.exe) exists only in the LIVE tree. Swapping `apps`- # without it deletes the desktop build and breaks the- # shortcut. Graft the live release dir into the staged copy- # BEFORE the swap so the commit preserves it atomically.- if item == "apps":- live_release = os.path.join(dst, "desktop", "release")- staged_release = os.path.join(- staged[-1][0], "desktop", "release"- )- if os.path.isdir(live_release) and not os.path.exists(- staged_release- ):- os.makedirs(os.path.dirname(staged_release), exist_ok=True)- shutil.copytree(live_release, staged_release)- except Exception:- # Nothing is live yet; drop the partial staging copies so a retry- # starts from the same free space this attempt did.- _discard_staged(staged)- raise- try:- # Re-check the tree right before the swap (#87304 TOCTOU): the- # download + extract + staging window above can take minutes, and- # work created in it would be destroyed by the commit below. Our- # own phase-1 staging siblings are filtered out — they are the- # expected artifacts of getting here, not user work.- recheck_reason = _zip_overlay_block_reason(- _m().PROJECT_ROOT, ignore_staging_artifacts=True- )- if recheck_reason is not None:- _discard_staged(staged)- print(f"✗ ZIP fallback aborted before the swap: {recheck_reason}.")- print(- " Files appeared in the checkout while the update was "- "downloading; committing the swap would delete them."- )- print(" Stash or commit your changes, then rerun `hermes update`.")- _m().sys.exit(1)- _commit_staged_replacements(staged)- except Exception:- # The rollback already restored every swapped entry, but staging- # copies for the not-yet-swapped entries (potentially most of a- # full tree) are still on disk. Drop them, or the retry's- # up-front free-space check — which runs BEFORE the lazy- # per-entry leftover cleanup — fails on litter this attempt- # left behind: the exact "retry fails harder" failure mode- # _discard_staged exists to prevent. Safe post-rollback: swapped- # entries' staging paths were renamed away, and _discard_staged- # skips paths that no longer exist.- _discard_staged(staged)- raise- update_count = len(staged)-- print(f"✓ Updated {update_count} items from ZIP")-- except Exception as e:- print(f"✗ ZIP update failed: {e}")- # The two-phase replace either commits every entry or rolls them all- # back, so a failure here does not leave a mixed-version tree — don't- # scare the user toward a reinstall they don't need.- print(" Your existing install was left in place.")- print(- " Re-run `hermes update` to retry; if the agent won't start, "- "reinstall from https://hermes-agent.nousresearch.com"- )- _m().sys.exit(1)- finally:- shutil.rmtree(tmp_dir, ignore_errors=True)+def _print_update_check_result(behind: int | None, compare_branch: str) -> None:+ """Report ``--check``'s verdict: up to date, N commits behind, or behind by an unknown count."""+ if behind == 0:+ print("✓ Already up to date.")+ return+ if behind is not None:+ print(f"⚕ Update available: {behind} {'commit' if behind == 1 else 'commits'} behind {compare_branch}.")+ else:+ print(f"⚕ Update available (behind {compare_branch}).")+ from hermes_cli.config import recommended_update_command+ print(f" Run '{recommended_update_command()}' to install.")- # Clear stale bytecode after ZIP extraction- removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)- if removed:- print(- f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}"- )- _m()._record_bytecode_fingerprint()- _m()._refresh_bootstrap_cache_scripts(branch)-- # Reinstall Python dependencies. Prefer .[all], but if one optional extra- # breaks on this machine, keep base deps and reinstall the remaining extras- # individually so update does not silently strip working capabilities.- #- # Self-lock deferral (relocated preflight — #86735): the ZIP code swap- # above is already committed; defer only the dependency sync when this- # process holds a native extension the sync must rewrite.- _m()._abort_dependency_sync_if_self_locked()- print("→ Updating Python dependencies...")+def _repair_venv_on_current_checkout(+ *, assume_yes, gateway_mode, pre_update_snapshot_id, desktop_dir,+ had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,+ _windows_gateway_resume) -> bool:+ """Stage a replacement dependency environment; keep the marker on failure."""+ _write_update_incomplete_marker()import pmtry:- pm.sync_venv(["all"], explicit=True)- except _shim_quarantine_error_type() as _sqe:- # #87331: this runs inside the ZIP-fallback error handler, so the- # boundary except clause in cmd_update cannot catch it — refuse- # here with the same defer-via-marker contract.- _refuse_update_for_contended_shims(_sqe)+ pm.sync_venv(["all"] + list(active_lazy_features or []), explicit=True)except pm.InstallError as _sync_err:print(f" ✗ {_sync_err}")- print(" Re-run `hermes update` (or `hermes pm install`) once resolved.")-- uv_bin, uv_env = pm.uv(venv=_m().PROJECT_ROOT / "venv")- install_prefix = [uv_bin, "pip"] if uv_bin else [_m().sys.executable, "-m", "pip"]- install_env = uv_env if uv_bin else None- _m()._restore_active_tool_dependencies(- active_tool_dependencies,- install_prefix,- env=install_env,- )+ return False+ healthy_after, detail_after = _venv_core_imports_healthy()+ if not healthy_after:+ print(f"⚠ Venv still unhealthy after repair: {detail_after}")+ print(" Close all Hermes windows/gateways and re-run: hermes update")+ return False+ _m()._clear_update_incomplete_marker()+ print("✓ Dependencies repaired!")+ # Check for config migrations (#91360).+ _check_and_apply_config_migration(+ assume_yes=assume_yes, gateway_mode=gateway_mode,+ pre_update_snapshot_id=pre_update_snapshot_id)+ # The Windows hand-off child lands here after doing the sync its parent could not, and+ # the commits-pulled rebuild is never reached — rebuild the Desktop app here or it+ # silently stays on the old build (#97343).+ if _rebuild_desktop_after_update(+ desktop_dir, had_desktop_app_before_update=had_desktop_app_before_update):+ return _print_verified_update_completion("✓ Update complete!")+ _print_update_completion(+ "⚠ Update partially complete — the desktop app was not rebuilt and is still on the previous build.")+ return False- # ZIP path parity: heal the active memory provider's bridge packages- # after the dependency reinstall, same as the git-pull path (#53272,- # #70636).- _m()._refresh_active_memory_provider_dependencies()-- # Now that dependencies are installed, verify the tree actually imports.- # The copy loop above replaces top-level entries one at a time in- # os.listdir order, so an interruption between (say) `agent/` and `tools/`- # leaves a tree whose files all parse but cannot be imported together —- # the ImportError-on-startup class this guard exists to catch. Deliberately- # placed *after* the dependency reinstall so a genuinely-new third-party- # requirement isn't misreported as a partial copy. There is no SHA to roll- # back to here, so surface it with a concrete recovery step rather than- # reporting a successful update over a bricked install.- import_ok, failing_module, import_error = _validate_critical_modules_import(- _m().PROJECT_ROOT- )- if not import_ok:- print()- print("✗ Update left the install in an unimportable state:")- print(f" {failing_module}: {import_error}")- print()- print(" This usually means the copy was interrupted partway through.")- print(" Re-run `hermes update` to complete it.")- _m().sys.exit(1)-- node_failures = _update_node_dependencies()- _m()._build_web_ui(_m().PROJECT_ROOT / "web")- desktop_build_ok = _rebuild_desktop_after_update(- _m().PROJECT_ROOT / "apps" / "desktop",- had_desktop_app_before_update=had_desktop_app_before_update,- )- # Sync skills- try:- from tools.skills_sync import sync_skills+def _repair_current_checkout(+ *, assume_yes, gateway_mode, pre_update_snapshot_id, desktop_dir,+ had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,+ upstream_checked, _windows_gateway_resume) -> bool:+ """Already-up-to-date path: keep the managed runtime current, repair a broken venv.+ Returns whether the checkout can be reported complete."""+ # "No new commits" does not mean the venv is safe: pm owns the uv pin now — a pin bump+ # realizes a NEW entry on the next ensure. The update command is the one caller that+ # must SEE realization failures, so use the raising API, not the None-swallowing uv().+ import pm- print("→ Syncing bundled skills...")- result = sync_skills(quiet=True)- if result["copied"]:- print(f" + {len(result['copied'])} new: {', '.join(result['copied'])}")- if result.get("updated"):- print(- f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}"- )- if result.get("user_modified"):- print(f" ~ {len(result['user_modified'])} user-modified (kept)")- print(- " → see them: hermes skills list-modified "- "(diff/reset to resume updates)"- )- if result.get("cleaned"):- print(f" − {len(result['cleaned'])} removed from manifest")- if result.get("relocated"):- print(- f" → {len(result['relocated'])} moved to new upstream paths: "- f"{', '.join(result['relocated'])}"- )- if not result["copied"] and not result.get("updated"):- print(" ✓ Skills are up to date")- except Exception:- pass-- # Seed the model-catalog disk cache from the freshly-unpacked checkout- # (same rationale as the git-pull path in _cmd_update_impl). Non-fatal.- try:- from hermes_cli.model_catalog import seed_cache_from_checkout-- if seed_cache_from_checkout(_m().PROJECT_ROOT):- print(" ✓ Model catalog cache refreshed from checkout")- except Exception as e:- logger.debug("Model catalog seed during zip update failed: %s", e)-- # ── Post-update state.db integrity guard (#68474, #97994) ────────────- # Verify state.db survived the ZIP update in the root home AND every- # sibling profile, auto-restoring each from its own most recent valid- # pre-update snapshot when needed.- try:- _verify_and_restore_state_dbs_post_update()- except Exception as exc:- logger.debug(- "Post-update state.db integrity check (zip path) failed: %s", exc- )-- update_complete = _print_update_summary(- node_failures=node_failures,- desktop_build_ok=desktop_build_ok,- pre_update_version=pre_update_version,- )- try:- _print_curator_first_run_notice()- except Exception as e:- logger.debug("Curator first-run notice failed: %s", e)- try:- _print_curator_recent_run_notice()- except Exception as e:- logger.debug("Curator recent-run notice failed: %s", e)- # Don't stop a working dashboard when the Node refresh failed — see the- # git-update path for rationale (#30271).- _finish_dashboard_update_cleanup(node_failures)- try:- from hermes_cli.update_receipt import finalize_update_receipt-- finalize_update_receipt(- "success" if update_complete and not node_failures else "partial"- )- except Exception as _receipt_exc:- logger.debug("Update receipt finalize (zip path) failed: %s", _receipt_exc)- return update_complete--def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[str]:- status = subprocess.run(- git_cmd + ["status", "--porcelain"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=True,- )- if not status.stdout.strip():- return None-- # If the index has unmerged entries (e.g. from an interrupted merge/rebase),- # git stash will fail with "needs merge / could not write index". Clear the- # conflict state with `git reset` so the stash can proceed. Working-tree- # changes are preserved; only the index conflict markers are dropped.- unmerged = subprocess.run(- git_cmd + ["ls-files", "--unmerged"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if unmerged.stdout.strip():- print("→ Clearing unmerged index entries from a previous conflict...")- subprocess.run(git_cmd + ["reset"], cwd=cwd, capture_output=True)-- from datetime import datetime, timezone-- stash_name = datetime.now(timezone.utc).strftime(- f"{_AUTOSTASH_NAME_PREFIX}%Y%m%d-%H%M%S"- )- print("→ Local changes detected — stashing before update...")- prev_stash = subprocess.run(- git_cmd + ["rev-parse", "--verify", "refs/stash"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- push = subprocess.run(- git_cmd + ["stash", "push", "--include-untracked", "-m", stash_name],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if push.stdout.strip():- print(push.stdout.strip())- stash_probe = subprocess.run(- git_cmd + ["rev-parse", "--verify", "refs/stash"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- stash_ref = stash_probe.stdout.strip()- stash_created = (- stash_probe.returncode == 0 and bool(stash_ref) and stash_ref != prev_stash- )-- if push.returncode != 0:- if stash_created:- # git stash push exits non-zero when it saved everything but could- # not delete some swept untracked files from the working tree- # (e.g. a root-owned directory: "warning: failed to remove ...:- # Permission denied"). The stash entry is complete — the changes- # are safe — so this is not a failure. Leave the undeletable- # files in place and continue the update.- if push.stderr.strip():- print(push.stderr.strip())- print(- " ⚠ Some untracked files could not be removed from the "- "working tree (permission denied)."- )- print(- " They were still saved to the stash and were left in "- "place — the update will continue."- )- # A partially-failed stash push also aborts its working-tree- # cleanup for TRACKED modifications — they are saved in the stash- # but still dirty the tree, which would break the checkout/pull- # that follows. Safe to reset: everything is in the stash entry.- subprocess.run(- git_cmd + ["reset", "--hard", "HEAD"],- cwd=cwd,- capture_output=True,- )- else:- # No stash entry was created: the changes were NOT saved. This- # is a real failure — bail out before the update touches HEAD.- print("✗ Could not stash local changes — update aborted.")- if push.stderr.strip():- print(f" {push.stderr.strip().splitlines()[0]}")- print(- " Commit, stash, or clean up your local changes manually, "- "then re-run `hermes update`."- )- raise subprocess.CalledProcessError(- push.returncode, push.args, output=push.stdout, stderr=push.stderr- )-- return stash_ref--def _resolve_stash_selector(- git_cmd: list[str], cwd: Path, stash_ref: str-) -> Optional[str]:- stash_list = subprocess.run(- git_cmd + ["stash", "list", "--format=%gd %H"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=True,- )- for line in stash_list.stdout.splitlines():- selector, _, commit = line.partition(" ")- if commit.strip() == stash_ref:- return selector.strip()- return None--#: Producer/consumer contract for update autostash names: the stash subject is-#: this prefix + a UTC YYYYMMDD-HHMMSS stamp (see _stash_local_changes_if_needed-#: and _warn_orphaned_update_autostashes).-_AUTOSTASH_NAME_PREFIX = "hermes-update-autostash-"--#: Age past which a leftover ``hermes-update-autostash-*`` entry is called out-#: at update time. Entries younger than this are normal (a parked stash from-#: the desktop updater's --keep-stash run minutes ago); older ones are almost-#: always forgotten (#63717 problem 6: an orphan persisted 9+ days unnoticed).-_AUTOSTASH_WARN_AGE_DAYS = 7---def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:- """Surface leftover update autostashes older than the warn threshold.-- Autostash entries legitimately outlive an update run (``--keep-stash``- parks them; a conflicted or failed restore preserves them for safety), but- nothing ever re-surfaces them afterwards — they sit in ``git stash``- invisibly for weeks (#63717 problem 6). This prints a short notice naming- the stale entries with recovery/cleanup guidance. Deliberately NOT a GC:- a stash entry can be the only copy of the user's uncommitted work, so- Hermes never drops one automatically.-- Best-effort — any git failure returns 0 and must not block the update.- Returns the number of stale entries warned about.- """- from datetime import timedelta, timezone-- try:- stash_list = subprocess.run(- git_cmd + ["stash", "list", "--format=%gd %s"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if stash_list.returncode != 0:- return 0- cutoff = datetime.now(timezone.utc) - timedelta(- days=_AUTOSTASH_WARN_AGE_DAYS- )- marker = _AUTOSTASH_NAME_PREFIX- stale: list[tuple[str, str]] = []- for line in stash_list.stdout.splitlines():- selector, _, subject = line.strip().partition(" ")- pos = subject.find(marker)- if pos < 0:- continue- stamp = subject[pos + len(marker):][:15] # "YYYYMMDD-HHMMSS"- try:- stash_time = datetime.strptime(stamp, "%Y%m%d-%H%M%S").replace(- tzinfo=timezone.utc- )- except ValueError:- # Unparseable name — age unknown; leave it alone rather than- # guess (same posture as _prune_orphan_rescue_refs).- continue- if stash_time < cutoff:- stale.append((selector, stamp))- if not stale:- return 0- print()- print(- f"⚠ {len(stale)} leftover update autostash entr"- f"{'y is' if len(stale) == 1 else 'ies are'} more than "- f"{_AUTOSTASH_WARN_AGE_DAYS} days old:"- )- for selector, stamp in stale:- print(f" {selector} ({_AUTOSTASH_NAME_PREFIX}{stamp})")- print(" These hold local changes stashed by earlier updates and never")- print(" restored. Review with: git stash show -p <entry>")- print(" Restore with: git stash apply <entry> Discard with: git stash drop <entry>")- return len(stale)- except Exception as exc:- logger.debug("Autostash age check failed: %s", exc)- return 0---def _print_stash_cleanup_guidance(- stash_ref: str, stash_selector: Optional[str] = None-) -> None:- print(- " Check `git status` first so you don't accidentally reapply the same change twice."- )- print(" Find the saved entry with: git stash list --format='%gd %H %s'")- if stash_selector:- print(f" Remove it with: git stash drop {stash_selector}")- else:- print(- f" Look for commit {stash_ref}, then drop its selector with: git stash drop stash@{{N}}"- )--def _stash_apply_failed_only_on_existing_untracked(stderr: str) -> bool:- """True when a ``git stash apply`` failure is ONLY about untracked files- that already exist in the working tree.-- This is the tail end of the permission-denied autostash class: ``git stash- push --include-untracked`` swept undeletable files (e.g. a root-owned- ``packaging/`` directory) into the stash but could not remove them from- disk. On restore, git applies all tracked changes, then refuses to- overwrite those still-present files (``already exists, no checkout`` /- ``could not restore untracked files from stash``) and exits non-zero even- though nothing was lost. Any other error line (e.g. ``would be- overwritten by merge`` / ``Aborting``) means the tracked apply itself- failed and this returns False.- """- lines = [ln.strip() for ln in (stderr or "").splitlines() if ln.strip()]- if not lines:- return False- saw_untracked_error = False- for ln in lines:- if "already exists, no checkout" in ln:- saw_untracked_error = True- elif "could not restore untracked files from stash" in ln:- saw_untracked_error = True- elif ln.startswith(("warning:", "hint:")):- continue- else:- return False- return saw_untracked_error--def _park_stashed_changes(stash_ref: str) -> None:- """Leave a pre-update autostash parked instead of re-applying it.-- Used by ``hermes update --keep-stash`` (the desktop updater's mode): the- stash made the update possible on a dirty tree, but local source edits- must never be silently re-applied onto the updated code. Nothing is- lost — the entry stays in ``git stash`` with printed recovery guidance.- """- print()- print("ℹ️ Local changes were stashed before updating and were NOT re-applied (--keep-stash).")- print(f" Stash ref: {stash_ref}")- print(f" Restore manually with: git stash apply {stash_ref}")---def _git_untracked_paths(git_cmd: list[str], cwd: Path) -> set[str] | None:- """Return untracked paths, or ``None`` when Git cannot enumerate them."""- try:- result = subprocess.run(- git_cmd + ["ls-files", "--others", "--exclude-standard", "-z"],- cwd=cwd,- capture_output=True,- text=True,- encoding="utf-8",- errors="surrogateescape",- )- except (OSError, subprocess.SubprocessError):- result = None- if result is None or result.returncode != 0:- print(- " ⚠ Could not enumerate untracked files while validating the "- "restored stash."- )- return None- return {path for path in result.stdout.split("\0") if path}---def _restored_python_paths(- git_cmd: list[str], cwd: Path-) -> tuple[str, ...] | None:- """Return restored ``.py`` paths changed from ``HEAD``.-- This deliberately validates Python source only; non-Python entry scripts- remain outside the executable import-health check.- """- try:- changed = subprocess.run(- git_cmd + ["diff", "--name-only", "-z", "HEAD", "--", "*.py"],- cwd=cwd,- capture_output=True,- text=True,- encoding="utf-8",- errors="surrogateescape",- )- except (OSError, subprocess.SubprocessError):- changed = None- if changed is None or changed.returncode != 0:- print(" ⚠ Could not enumerate tracked Python files restored from the stash.")- return None- paths = set(changed.stdout.split("\0"))- untracked = _git_untracked_paths(git_cmd, cwd)- if untracked is None:- return None- paths.update(path for path in untracked if path.endswith(".py"))- paths.discard("")- return tuple(sorted(paths))---def _reject_unsafe_stash_restore(- git_cmd: list[str],- cwd: Path,- stash_ref: str,- preexisting_untracked: set[str],- failing_target: str,- detail: str | None,-) -> None:- """Restore the clean updated tree, preserve the stash, and abort the update."""- print()- print("✗ Restored local changes made the Hermes agent unexecutable.")- print(f" Health check failed: {failing_target}")- if detail:- for line in str(detail).splitlines()[:6]:- print(f" {line}")-- current_untracked = _git_untracked_paths(git_cmd, cwd)- restored_untracked = (- current_untracked - preexisting_untracked- if current_untracked is not None- else set()- )- try:- reset = subprocess.run(- git_cmd + ["reset", "--hard", "HEAD"], cwd=cwd, capture_output=True- )- except (OSError, subprocess.SubprocessError):- reset = None-- clean = None- if restored_untracked:- try:- clean = subprocess.run(- git_cmd + ["clean", "-fd", "--", *sorted(restored_untracked)],- cwd=cwd,- capture_output=True,- )- except (OSError, subprocess.SubprocessError):- clean = None- cleanup_ok = (- current_untracked is not None- and reset is not None- and reset.returncode == 0- and (not restored_untracked or (clean is not None and clean.returncode == 0))- )- if cleanup_ok:- try:- verify = subprocess.run(- git_cmd + ["diff", "--quiet", "HEAD", "--"],- cwd=cwd,- capture_output=True,- )- cleanup_ok = verify.returncode == 0- except (OSError, subprocess.SubprocessError):- cleanup_ok = False-- if cleanup_ok:- print(" The clean updated tree has been restored; the gateway was not restarted.")- else:- print(" ⚠ The clean updated tree could not be fully restored automatically.")- print(" Inspect `git status` and run `git reset --hard HEAD` before retrying.")- print(" Platform connectivity alone does not mean the agent can execute turns.")- print(f" Your local changes remain preserved in stash: {stash_ref}")- print(f" Inspect them with: git stash show --stat {stash_ref}")- print(f" Restore manually after fixing them: git stash apply {stash_ref}")- raise SystemExit(1)---def _restore_stashed_changes(- git_cmd: list[str],- cwd: Path,- stash_ref: str,- prompt_user: bool = False,- input_fn=None,-) -> bool:- if prompt_user:- remote_prompt = input_fn is not None- prompt_suffix = "[y/N]" if remote_prompt else "[Y/n]"- print()- print("⚠ Local changes were stashed before updating.")- print(- " Restoring them may reapply local customizations onto the updated codebase."- )- print(" Review the result afterward if Hermes behaves unexpectedly.")- print(f"Restore local changes now? {prompt_suffix}")- if input_fn is not None:- response = input_fn(f"Restore local changes now? {prompt_suffix}", "n")- else:- try:- response = input().strip().lower()- except (EOFError, UnicodeDecodeError):- # Mirror the config-migration prompt's fix: don't let a- # terminal-encoding issue or a closed stdin crash the- # update mid-restore. Falls through to the existing- # skip-restore path below, which already explains how to- # restore manually from git stash.- response = "n"- accepted = response in {"y", "yes"} or (not remote_prompt and response == "")- if not accepted:- print("Skipped restoring local changes.")- print("Your changes are still preserved in git stash.")- print(f"Restore manually with: git stash apply {stash_ref}")- return False-- preexisting_untracked = _git_untracked_paths(git_cmd, cwd)- if preexisting_untracked is None:- print(" The stash was not restored because its cleanup baseline is unknown.")- print(f" Restore manually with: git stash apply {stash_ref}")- return False- clean_import_failures = _critical_module_import_failures(- cwd, report_runtime_errors=True- )- print("→ Restoring local changes...")- restore = subprocess.run(- git_cmd + ["stash", "apply", stash_ref],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )-- # Check for unmerged (conflicted) files — can happen even when returncode is 0- unmerged = subprocess.run(- git_cmd + ["diff", "--name-only", "--diff-filter=U"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- has_conflicts = bool(unmerged.stdout.strip())-- if restore.returncode != 0 and not has_conflicts and (- _stash_apply_failed_only_on_existing_untracked(restore.stderr)- ):- # Permission-denied autostash tail end: the tracked changes applied- # cleanly; the only "failure" is untracked files that never left the- # working tree (git could not delete them at stash time, so it now- # refuses to overwrite them). Their content was never touched —- # nothing is lost. Treat as restored.- print(- " ⚠ Some stashed untracked files already exist in the working "- "tree and were kept as-is."- )- elif restore.returncode != 0 or has_conflicts:- print("✗ Update pulled new code, but restoring local changes hit conflicts.")- if restore.stdout.strip():- print(restore.stdout.strip())- if restore.stderr.strip():- print(restore.stderr.strip())-- # Show which files conflicted- conflicted_files = unmerged.stdout.strip()- if conflicted_files:- print("\nConflicted files:")- for f in conflicted_files.splitlines():- print(f" • {f}")-- print("\nYour stashed changes are preserved — nothing is lost.")- print(f" Stash ref: {stash_ref}")-- # Always reset to clean state — leaving conflict markers in source- # files makes hermes completely unrunnable (SyntaxError on import).- # The user's changes are safe in the stash for manual recovery.- subprocess.run(- git_cmd + ["reset", "--hard", "HEAD"],- cwd=cwd,- capture_output=True,- )- print("Working tree reset to clean state.")- print(f"Restore your changes later with: git stash apply {stash_ref}")- # Don't sys.exit — the code update itself succeeded, only the stash- # restore had conflicts. Let cmd_update continue with pip install,- # skill sync, and gateway restart.- return False-- restored_python = _restored_python_paths(git_cmd, cwd)- if restored_python is None:- _reject_unsafe_stash_restore(- git_cmd,- cwd,- stash_ref,- preexisting_untracked,- "restored Python source discovery",- "could not determine which restored Python files require validation",- )- syntax_ok, failing_path, syntax_error = _validate_python_files_syntax(- cwd, restored_python- )- if not syntax_ok:- _reject_unsafe_stash_restore(- git_cmd,- cwd,- stash_ref,- preexisting_untracked,- failing_path or "restored Python source",- syntax_error,- )-- restored_import_failures = _critical_module_import_failures(- cwd, report_runtime_errors=True- )- changed_import_failure = next(- (- (module, error)- for module, error in restored_import_failures.items()- if clean_import_failures.get(module) != error- ),- None,- )- if changed_import_failure is not None:- failing_module, import_error = changed_import_failure- _reject_unsafe_stash_restore(- git_cmd,- cwd,- stash_ref,- preexisting_untracked,- f"agent import {failing_module or 'unknown'}",- import_error[1],- )-- stash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref)- if stash_selector is None:- print(- "⚠ Local changes were restored, but Hermes couldn't find the stash entry to drop."- )- print(- " The stash was left in place. You can remove it manually after checking the result."- )- _print_stash_cleanup_guidance(stash_ref)- else:- drop = subprocess.run(- git_cmd + ["stash", "drop", stash_selector],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if drop.returncode != 0:- print(- "⚠ Local changes were restored, but Hermes couldn't drop the saved stash entry."- )- if drop.stdout.strip():- print(drop.stdout.strip())- if drop.stderr.strip():- print(drop.stderr.strip())- print(- " The stash was left in place. You can remove it manually after checking the result."- )- _print_stash_cleanup_guidance(stash_ref, stash_selector)-- print("⚠ Local changes were restored on top of the updated codebase.")- print(" Review `git diff` / `git status` if Hermes behaves unexpectedly.")- return True--def _discard_stashed_changes(- git_cmd: list[str],- cwd: Path,- stash_ref: str,-) -> bool:- """Throw away a stash created before an update, without applying it.-- Used only on a NON-interactive update when the user has set- ``updates.non_interactive_local_changes: discard`` — i.e. they've opted out- of keeping local source edits on this machine. Drops the stash entry- instead of re-applying it, so the working tree stays clean at the freshly- pulled HEAD. Unlike ``git reset --hard`` + ``git clean -fd``, this only- affects what was stashed (tracked changes + the untracked files we- explicitly captured) — ignored paths like node_modules/venv/build outputs- are never touched, since they were never stashed.-- Returns True if the stash was dropped, False on a git failure (in which- case the stash is left in place for safety).- """- stash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref)- if stash_selector is None:- print(- "⚠ Configured to discard local changes on non-interactive update, "- "but Hermes couldn't find the stash entry to drop."- )- _print_stash_cleanup_guidance(stash_ref)- return False-- drop = subprocess.run(- git_cmd + ["stash", "drop", stash_selector],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if drop.returncode != 0:- print(- "⚠ Configured to discard local changes, but Hermes couldn't drop "- "the saved stash entry."- )- if drop.stderr.strip():- print(f" {drop.stderr.strip().splitlines()[0]}")- _print_stash_cleanup_guidance(stash_ref, stash_selector)- return False-- print("→ Discarded local source changes (updates.non_interactive_local_changes=discard).")- return True--OFFICIAL_REPO_URLS = {- "https://github.com/NousResearch/hermes-agent.git",- "[email protected]:NousResearch/hermes-agent.git",- "https://github.com/NousResearch/hermes-agent",- "[email protected]:NousResearch/hermes-agent",-}--OFFICIAL_REPO_URL = "https://github.com/NousResearch/hermes-agent.git"--SKIP_UPSTREAM_PROMPT_FILE = ".skip_upstream_prompt"--def _get_origin_url(git_cmd: list[str], cwd: Path) -> Optional[str]:- """Get the URL of the origin remote, or None if not set."""- try:- result = subprocess.run(- git_cmd + ["remote", "get-url", "origin"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if result.returncode == 0:- return result.stdout.strip()- except Exception:- pass- return None--def _is_fork(origin_url: Optional[str]) -> bool:- """Check if the origin remote points to a fork (not the official repo)."""- if not origin_url:- return False- # Normalize URL for comparison (strip trailing .git if present)- normalized = origin_url.rstrip("/")- if normalized.endswith(".git"):- normalized = normalized[:-4]- for official in OFFICIAL_REPO_URLS:- official_normalized = official.rstrip("/")- if official_normalized.endswith(".git"):- official_normalized = official_normalized[:-4]- if normalized == official_normalized:- return False- return True--def _has_upstream_remote(git_cmd: list[str], cwd: Path) -> bool:- """Check if an 'upstream' remote already exists."""- try:- result = subprocess.run(- git_cmd + ["remote", "get-url", "upstream"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- return result.returncode == 0- except Exception:- return False--def _add_upstream_remote(git_cmd: list[str], cwd: Path) -> bool:- """Add the official repo as the 'upstream' remote. Returns True on success."""- try:- result = subprocess.run(- git_cmd + ["remote", "add", "upstream", OFFICIAL_REPO_URL],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- return result.returncode == 0- except Exception:- return False--def _count_commits_between(git_cmd: list[str], cwd: Path, base: str, head: str) -> int:- """Count commits on `head` that are not on `base`. Returns -1 on error."""- try:- result = subprocess.run(- git_cmd + ["rev-list", "--count", f"{base}..{head}"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if result.returncode == 0:- return int(result.stdout.strip())- except Exception:- pass- return -1--def _should_skip_upstream_prompt() -> bool:- """Check if user previously declined to add upstream."""- from hermes_constants import get_hermes_home-- return (get_hermes_home() / SKIP_UPSTREAM_PROMPT_FILE).exists()--def _mark_skip_upstream_prompt():- """Create marker file to skip future upstream prompts."""- try:- from hermes_constants import get_hermes_home-- (get_hermes_home() / SKIP_UPSTREAM_PROMPT_FILE).touch()- except Exception:- pass--def _sync_fork_with_upstream(git_cmd: list[str], cwd: Path) -> bool:- """Attempt to push updated main to origin (sync fork).-- Returns True if push succeeded, False otherwise.- """- try:- result = subprocess.run(- git_cmd + ["push", "origin", "main", "--force-with-lease"],- cwd=cwd,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- **_no_prompt_git_kwargs(),- )- return result.returncode == 0- except Exception:- return False--def _sync_with_upstream_if_needed(- git_cmd: list[str],- cwd: Path,- *,- assume_yes: bool = False,- input_fn=None,-) -> bool:- """Check if fork is behind upstream and sync if safe.-- This implements the fork upstream sync logic:- - If upstream remote doesn't exist, ask user if they want to add it- - Compare origin/main with upstream/main- - If origin/main is strictly behind upstream/main, pull from upstream- - Try to sync fork back to origin if possible-- Returns True when origin/main was actually verified against the official- upstream/main, False when the check never happened (prompt skipped or- declined, remote add failed, fetch or compare failed) so the caller can- avoid reporting the checkout as up to date on the strength of an origin- comparison alone (#97052 review).- """- has_upstream = _has_upstream_remote(git_cmd, cwd)-- if not has_upstream:- # Check if user previously declined- if _should_skip_upstream_prompt():- return False-- print()- print("ℹ Your fork is not tracking the official Hermes repository.")- print(" This means you may miss updates from NousResearch/hermes-agent.")- print()-- if assume_yes or (- input_fn is None and not (sys.stdin.isatty() and sys.stdout.isatty())- ):- # --yes means "don't block", not "mutate my git remotes". Skip- # without persisting the decline so interactive runs still get asked.- print(" Skipping upstream setup (non-interactive run).")- print(- " Add it later with: git remote add upstream https://github.com/NousResearch/hermes-agent.git"- )- return False-- # Ask user if they want to add upstream- if input_fn is not None:- response = (- input_fn("Add official repo as 'upstream' remote? [y/N]", "n")- .strip()- .lower()- )- else:- try:- response = (- input("Add official repo as 'upstream' remote? [Y/n]: ")- .strip()- .lower()- )- except (EOFError, KeyboardInterrupt, UnicodeDecodeError):- print()- response = "n"-- if response in {"", "y", "yes"}:- print("→ Adding upstream remote...")- if _add_upstream_remote(git_cmd, cwd):- print(- " ✓ Added upstream: https://github.com/NousResearch/hermes-agent.git"- )- has_upstream = True- else:- print(" ✗ Failed to add upstream remote. Skipping upstream sync.")- return False- else:- print(- " Skipped. Run 'git remote add upstream https://github.com/NousResearch/hermes-agent.git' to add later."- )- _mark_skip_upstream_prompt()- return False-- # Fetch upstream main only. This sync compares upstream/main with- # origin/main, so there's no reason to pull every upstream ref — and a bare- # fetch drags in thousands of auto-generated branches.- print()- print("→ Fetching upstream...")- try:- subprocess.run(- git_cmd + ["fetch", "upstream", "main", "--quiet"],- cwd=cwd,- capture_output=True,- check=True,- **_no_prompt_git_kwargs(),- )- except subprocess.CalledProcessError:- print(" ✗ Failed to fetch upstream. Skipping upstream sync.")- return False-- # Compare origin/main with upstream/main- origin_ahead = _count_commits_between(git_cmd, cwd, "upstream/main", "origin/main")- upstream_ahead = _count_commits_between(- git_cmd, cwd, "origin/main", "upstream/main"- )-- if origin_ahead < 0 or upstream_ahead < 0:- print(" ✗ Could not compare branches. Skipping upstream sync.")- return False-- # If origin/main has commits not on upstream, don't trample- if origin_ahead > 0:- print()- print(f"ℹ Your fork has {origin_ahead} commit(s) not on upstream.")- print(" Skipping upstream sync to preserve your changes.")- print(" If you want to merge upstream changes, run:")- print(" git pull upstream main")- return True-- # If upstream is not ahead, fork is up to date- if upstream_ahead == 0:- print(" ✓ Fork is up to date with upstream")- return True-- # origin/main is strictly behind upstream/main (can fast-forward)- print()- print(f"→ Fork is {upstream_ahead} commit(s) behind upstream")- print("→ Pulling from upstream...")-- try:- subprocess.run(- git_cmd + ["pull", "--ff-only", "upstream", "main"],- cwd=cwd,- check=True,- **_no_prompt_git_kwargs(),- )- except subprocess.CalledProcessError:- print(- " ✗ Failed to pull from upstream. You may need to resolve conflicts manually."- )- return False-- print(" ✓ Updated from upstream")-- # Try to sync fork back to origin- print("→ Syncing fork...")- if _sync_fork_with_upstream(git_cmd, cwd):- print(" ✓ Fork synced with upstream")- else:- print(- " ℹ Got updates from upstream but couldn't push to fork (no write access?)"- )- print(" Your local repo is updated, but your fork on GitHub may be behind.")- return True--def _invalidate_update_cache():- """Delete the update-check cache for ALL profiles so no banner- reports a stale "commits behind" count after a successful update.-- The git repo is shared across profiles — when one profile runs- ``hermes update``, every profile is now current.- """- homes = []- # Default profile home (Docker-aware — uses /opt/data in Docker)- from hermes_constants import get_default_hermes_root-- default_home = get_default_hermes_root()- homes.append(default_home)- # Named profiles under <root>/profiles/- profiles_root = default_home / "profiles"- if profiles_root.is_dir():- for entry in profiles_root.iterdir():- if entry.is_dir():- homes.append(entry)- for home in homes:- try:- cache_file = home / ".update_check"- if cache_file.exists():- cache_file.unlink()- except Exception:- pass--def _write_marker_file(path: Path, *, label: str) -> None:- """Drop an update-recovery breadcrumb. Never raises."""- if _m()._pytest_owns_live_checkout(path.parent):- logger.debug("Skipping %s marker under pytest (live checkout)", label)- return- try:- path.write_text(- f"started={_time.time()}\npid={os.getpid()}\n", encoding="utf-8"- )- except OSError as exc:- logger.debug("Could not write %s marker: %s", label, exc)--def _write_update_incomplete_marker() -> None:- """Drop the interrupted core-install breadcrumb. Never raises."""- _write_marker_file(_m()._update_marker_path(), label="update-incomplete")--def _write_lazy_refresh_incomplete_marker() -> None:- """Drop the interrupted lazy-refresh breadcrumb. Never raises."""- _write_marker_file(_m()._lazy_refresh_marker_path(), label="lazy-refresh-incomplete")---# ``fleet_restart_pending`` lives under HERMES_HOME (not next to the venv).-# The existing ``.update-incomplete`` / ``.lazy-refresh-incomplete`` markers-# gate dependency/venv repair; this one is the fleet-restart obligation after-# a git pull that advanced HEAD (#95294). Cleared only when the restart phase-# completes or there were no running services to restart.-_FLEET_RESTART_PENDING_NAME = "fleet_restart_pending"---def _fleet_restart_pending_marker_path() -> Path:- """HERMES_HOME breadcrumb for a pull that has not yet restarted the fleet."""- return get_hermes_home() / _FLEET_RESTART_PENDING_NAME---def _write_fleet_restart_pending_marker(*, expected_sha: str = "") -> None:- """Drop the pull→restart obligation breadcrumb. Never raises."""- path = _fleet_restart_pending_marker_path()- if _m()._pytest_owns_live_checkout(path.parent):- logger.debug("Skipping fleet-restart-pending marker under pytest (live checkout)")- return- try:- lines = [f"started={_time.time()}", f"pid={os.getpid()}"]- if expected_sha:- lines.append(f"expected_sha={expected_sha}")- path.write_text("\n".join(lines) + "\n", encoding="utf-8")- except OSError as exc:- logger.debug("Could not write fleet-restart-pending marker: %s", exc)---def _clear_fleet_restart_pending_marker() -> None:- """Remove the pull→restart obligation breadcrumb. Never raises."""- _m()._clear_marker_file(- _fleet_restart_pending_marker_path(), label="fleet-restart-pending"- )---def _current_checkout_sha() -> str | None:- """Current on-disk checkout HEAD, or None if it cannot be resolved."""- try:- from hermes_cli.version_info import get_code_identity-- sha = (get_code_identity(refresh=True) or {}).get("sha")- return str(sha) if sha else None- except Exception:- # get_code_identity raises only on a mispackaged stamp (missing- # updateMechanism / 'light' payload); a live git checkout is the- # correct fallback for dev trees.- return _capture_head_sha(["git"], _m().PROJECT_ROOT)---def _receipt_looks_unfinished(receipt: dict) -> bool:- """True when *receipt* is from an update that did not finish cleanly."""- if receipt.get("stop_reason"):- return True- exit_code = receipt.get("exit_code")- if exit_code not in (0, None):- return True- outcome = receipt.get("outcome")- if outcome in ("failed", "partial", "running"):- return True- gateway_restart = receipt.get("gateway_restart")- if isinstance(gateway_restart, dict) and gateway_restart.get("incomplete"):- return True- return False---def _receipt_reports_stale_runtime(expected_sha: str | None = None) -> bool:- """True when ``update_receipts/latest.json`` records a runtime SHA skew.-- ``plan.runtimes[].code_sha`` is captured *before* the pull of that run,- so a successful update's receipt always shows pre-update runtime SHAs.- Those must not retrigger a restart on the next invocation. Use the- post-restart ``fleet`` matrix when present; fall back to the plan only- for an unfinished receipt (interrupt / failed / incomplete restart) —- the #95294 smoking-gun shape.- """- try:- from hermes_cli.update_receipt import read_latest_receipt-- receipt = read_latest_receipt()- except Exception:- receipt = None- if not isinstance(receipt, dict):- return False- if not expected_sha:- expected_sha = _current_checkout_sha()- if not expected_sha:- return False-- def _sha_mismatch(code_sha) -> bool:- return bool(code_sha) and str(code_sha) != str(expected_sha)-- fleet = receipt.get("fleet")- if isinstance(fleet, list) and fleet:- for entry in fleet:- if not isinstance(entry, dict):- continue- if entry.get("state") == "stale":- return True- if _sha_mismatch(entry.get("code_sha")):- return True- return False-- if not _receipt_looks_unfinished(receipt):- return False- plan = receipt.get("plan")- if not isinstance(plan, dict):- return False- for runtime in plan.get("runtimes") or []:- if isinstance(runtime, dict) and _sha_mismatch(runtime.get("code_sha")):- return True- return False---def _pending_fleet_restart_needed() -> bool:- """True when a prior pull still owes the fleet a restart (#95294)."""- try:- if _fleet_restart_pending_marker_path().is_file():- return True- except OSError:- pass- return _receipt_reports_stale_runtime()---def _warn_pending_fleet_restart(*, startup: bool = False) -> None:- """Print the specific interrupted-update fleet-restart warning."""- stream = sys.stderr if startup else sys.stdout- print(- "⚠ A previous `hermes update` pulled new code but did not "- "restart running gateways.",- file=stream,- )- print(- " Gateways may still be serving pre-update modules (mixed sys.modules).",- file=stream,- )- if startup:- print(- " Run `hermes update` or `hermes gateway restart`.",- file=stream,- )---def _warn_pending_fleet_restart_on_startup() -> None:- """Cheap CLI-startup hint. Never restarts; never raises."""- try:- if not _pending_fleet_restart_needed():- return- _warn_pending_fleet_restart(startup=True)- except Exception:- pass---def _restart_systemd_gateway_units_best_effort(failed: list) -> None:- """Best-effort ``systemctl restart`` of every hermes-gateway/serve unit."""- for scope, scope_cmd in (- ("user", ["systemctl", "--user"]),- ("system", ["systemctl"]),- ):- try:- result = subprocess.run(- scope_cmd- + [- "list-units",- "hermes-gateway*",- "hermes-serve*",- "--plain",- "--no-legend",- "--no-pager",- ],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=10,- )- except (FileNotFoundError, subprocess.TimeoutExpired):- continue- if result.returncode != 0:- continue-- def process_unit(svc_name: str, _scope=scope, _cmd=scope_cmd) -> None:- restart_cmd = list(_cmd) + ["--no-ask-password", "restart", svc_name]- if (- _scope == "system"- and hasattr(os, "geteuid")- and os.geteuid() != 0 # windows-footgun: ok — systemd path, Linux-only- ):- restart_cmd = ["sudo", "-n"] + restart_cmd- subprocess.run(- restart_cmd,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=30,- )-- def on_timeout(svc_name: str, exc: subprocess.TimeoutExpired) -> None:- failed.append(svc_name)-- _for_each_systemd_gateway_unit(- result.stdout,- process_unit=process_unit,- on_unit_timeout=on_timeout,- )---def _run_pending_fleet_restart() -> bool:- """Catch-up restart for gateways left on pre-update code (#95294).-- Returns True when restart completed or no services were running.- Returns False if restart was incomplete. Never raises.- """- print("→ Restarting gateways left on pre-update code...")- try:- _m()._purge_stale_hermes_modules()- except Exception:- pass- try:- from hermes_cli.gateway import (- find_gateway_pids,- is_macos,- is_windows,- kill_gateway_processes,- supports_systemd_services,- _wait_for_gateway_exit,- )- except Exception as exc:- _warn_gateway_restart_phase_aborted(exc, None)- return False-- try:- pids = list(find_gateway_pids(all_profiles=True))- except Exception as exc:- logger.debug("Pending fleet restart: gateway probe failed: %s", exc)- pids = None-- if pids == []:- print(" ✓ No running gateways — nothing to restart.")- return True-- failed: list = []- try:- if supports_systemd_services():- _restart_systemd_gateway_units_best_effort(failed)- if is_macos():- restarted: list = []- try:- _restart_macos_launchd_gateways(restarted, failed, 45.0)- except Exception as exc:- logger.debug("Pending fleet restart: launchd failed: %s", exc)- failed.append("launchd")- if is_windows():- try:- from hermes_cli import gateway_windows-- if gateway_windows.is_installed():- gateway_windows.restart()- except Exception as exc:- logger.debug("Pending fleet restart: Windows failed: %s", exc)- failed.append("windows-gateway")- leftover: list = []- try:- leftover = list(find_gateway_pids(all_profiles=True))- except Exception:- leftover = list(pids or [])- if leftover:- try:- kill_gateway_processes(all_profiles=True)- _wait_for_gateway_exit(timeout=5.0, force_after=None)- except Exception as exc:- logger.debug("Pending fleet restart: PID stop failed: %s", exc)- if failed:- _warn_incomplete_gateway_fleet_restart(failed)- return False- print(" ✓ Pending fleet restart completed.")- return True- except Exception as exc:- surviving = None- try:- surviving = list(find_gateway_pids(all_profiles=True))- except Exception:- surviving = pids- _warn_gateway_restart_phase_aborted(exc, surviving)- return False---def _apply_pending_fleet_restart_catchup() -> None:- """On an already-up-to-date ``hermes update``, finish a skipped restart.-- No-op when nothing is pending. Exits 1 when the catch-up restart is- incomplete so automation does not treat the fleet as healthy.- """- if not _pending_fleet_restart_needed():- return- print()- _warn_pending_fleet_restart()- print("→ Running the pending fleet restart...")- if _run_pending_fleet_restart():- _clear_fleet_restart_pending_marker()- return- print(" ⚠ Fleet restart incomplete. Recover with: hermes gateway restart")- sys.exit(1)---def _format_concurrent_instances_message(- matches: list[tuple[int, str]], scripts_dir: Path-) -> str:- """Build a human-readable explanation + remediation hint for the user."""- shim = scripts_dir / "hermes.exe"- lines = ["✗ Another hermes.exe is running:"]- for pid, name in matches:- lines.append(f" PID {pid} {name}")- lines.append("")- lines.append(f" Updating now would fail to overwrite {shim} because")- lines.append(" Windows blocks REPLACE on a running executable.")- lines.append("")- lines.append(" Close Hermes Desktop, exit any open `hermes` REPLs, and")- lines.append(" stop the gateway (`hermes gateway stop`) before retrying.")- lines.append("")- if matches:- pid_args = " ".join(f"/PID {pid}" for pid, _ in matches)- lines.append(" If you've already closed everything and these PIDs are")- lines.append(" stale, terminate them directly, then retry the update:")- lines.append(f" taskkill {pid_args} /F")- lines.append("")- lines.append(" Override with `hermes update --force` if you've already")- lines.append(" confirmed those processes will not write to the venv.")- return "\n".join(lines)---def _classify_concurrent_instance(pid: int) -> str:- """Return ``"gateway"`` when ``pid``'s command line is a gateway runtime.-- Delegates to ``_is_pausable_gateway`` — the same canonical- ``gateway run`` matcher (``gateway.status.looks_like_gateway_command_line``,- shlex-tokenized, profile-selector aware) used by the Desktop preflight- exemption and the venv-holder guard fallback — so a PID classified as- ``"gateway"`` here is exactly the set the pause/kill+restart machinery- downstream will stop. That symmetry is what lets the pre-update- concurrent gate skip the abort for gateway-only matches: the gateway is- going to be stopped by ``_pause_windows_gateways_for_update()`` moments- later anyway, so refusing the update just to make the user kill it- manually is friction without benefit.-- Returns ``"non-gateway"`` when the cmdline doesn't match, and- ``"unknown"`` when psutil can't read it (process gone, access denied,- psutil missing). The gate treats ``"unknown"`` as non-gateway — we'd- rather block an update we could have completed than proceed against a- process we couldn't positively identify as a gateway.- """- try:- import psutil # noqa: PLC0415- except Exception:- return "unknown"-- try:- proc = psutil.Process(int(pid))- cmdline_list = proc.cmdline()- except Exception:- return "unknown"-- from hermes_cli._scan_venv_blockers import _is_pausable_gateway # noqa: PLC0415-- cmdline = " ".join(cmdline_list or [])- if _is_pausable_gateway(cmdline):- return "gateway"- return "non-gateway"---def _filter_non_gateway_concurrent_instances(- matches: list[tuple[int, str]],-) -> list[tuple[int, str]]:- """Return only the concurrent-instance matches that are NOT the gateway.-- Used by the pre-update concurrent gate to decide whether to abort- ``hermes update``. If every concurrent instance is a gateway, the pause- machinery (``_pause_windows_gateways_for_update``) and the post-update- kill+restart block handle it — the update proceeds. If anything else (a- TUI shell, a Hermes Desktop backend child, an unrelated ``hermes`` REPL)- is in the list, the gate still aborts with the existing message, since- those have no pause machinery downstream.- """- non_gateway: list[tuple[int, str]] = []- for pid, name in matches:- if _classify_concurrent_instance(pid) != "gateway":- non_gateway.append((pid, name))- return non_gateway---def _capture_active_lazy_features() -> list[str]:- """Snapshot the venv's enabled extras before a managed runtime is replaced."""- try:- import pm-- return pm.enabled_extras()- except Exception as exc:- logger.debug("Could not snapshot enabled extras: %s", exc)- return []---def _capture_active_tool_dependencies() -> list[str]:- """Snapshot Python dependencies installed explicitly through ``hermes tools``."""- try:- from hermes_cli import tools_config-- return tools_config.active_restorable_python_tool_dependencies()- except Exception as exc:- logger.debug("Could not snapshot active Hermes Tools dependencies: %s", exc)- return []---def _restore_active_tool_dependencies(- dependencies: list[str],- install_cmd_prefix: list[str],- *,- env: dict[str, str] | None = None,-) -> None:- """Restore allowlisted ``hermes tools`` dependencies into a rebuilt venv.-- The dependency names came from a pre-rebuild import probe and are resolved- through a static package allowlist. Never raises: a failed optional tool- must not block the core update, but the user must be told what stayed- unavailable.- """- if not dependencies:- return-- try:- from hermes_cli import tools_config- except Exception as exc:- logger.debug("Hermes Tools dependency restore skipped (import failed): %s", exc)- return-- target_python = _m()._resolve_install_target_python(install_cmd_prefix, env)- missing: list[tuple[str, tuple[str, ...]]] = []- for name in dependencies:- spec = tools_config.restorable_python_tool_dependency(name)- if spec is None:- continue- module_name, install_args = spec- if target_python is not None:- try:- probe = subprocess.run(- [- str(target_python),- "-c",- "import importlib.util,sys; "- "raise SystemExit(0 if importlib.util.find_spec(sys.argv[1]) else 1)",- module_name,- ],- capture_output=True,- env=env,- check=False,- )- if probe.returncode == 0:- continue- except (subprocess.SubprocessError, OSError):- # An indeterminate probe is safer to repair than to treat as- # proof that a pre-rebuild dependency survived.- pass- missing.append((name, install_args))-- if not missing:- return-- print()- print(f"→ Restoring {len(missing)} Hermes Tools dependency set(s)...")- restored: list[str] = []- failed: list[tuple[str, str]] = []- for name, install_args in missing:- try:- _m()._run_install_with_heartbeat(- install_cmd_prefix + ["install", *install_args, "--quiet"],- env=env,- )- restored.append(name)- except Exception as exc:- # This is best-effort recovery for optional tooling. Unexpected- # installer failures must be surfaced without aborting the core- # runtime update.- failed.append((name, str(exc)))-- if restored:- print(f" ✓ {len(restored)} restored: {', '.join(restored)}")- for name, reason in failed:- if len(reason) > 200:- reason = reason[:200] + "..."- print(f" ⚠ {name} failed to restore: {reason}")---def _refresh_active_lazy_features(features: list[str] | None = None) -> bool:- """Re-sync the venv's enabled extras against the (possibly new) uv.lock.-- Extras live in the installed-state file and uv.lock owns every pin, so- a post-update refresh is one sync_venv() call: it re-installs exactly- the locked versions of everything enabled. Never raises.- """- try:- from pm.ensure import sync_venv-- sync_venv(features, explicit=True)- return True- except Exception as exc:- print(f" ⚠ Extra re-sync failed: {exc}")- print(" Rerun `hermes update` (or `hermes pm install`) once resolved.")- return False---def _refresh_active_memory_provider_dependencies() -> None:- """Refresh pip dependencies for the configured external memory provider.-- Memory-provider bridge packages are declared in each provider's- ``plugin.yaml`` (plus mode-dependent extras like Hindsight's- ``hindsight-all``), NOT in Hermes' editable-install extras or- ``LAZY_DEPS`` alone — so the core dependency reinstall above can strip- or downgrade them (#53272 mem0ai, #70636 hindsight-embed). Re-run the- provider's declared install for the ACTIVE provider only, after the- core install and lazy refresh, so the last write to any shared package- is the one the active provider needs.-- Never raises. A failure here must not block the rest of the update.- """- try:- from hermes_cli.config import load_config-- cfg = load_config()- except Exception as exc:- logger.debug("Memory provider refresh skipped (config load failed): %s", exc)- return-- provider = ""- if isinstance(cfg, dict):- memory_cfg = cfg.get("memory")- if isinstance(memory_cfg, dict):- if memory_cfg.get("enabled") is False:- return- provider = str(memory_cfg.get("provider") or "").strip()-- # "default" / empty is the built-in file-backed store — no pip deps.- if not provider or provider in {"default", "builtin", "none"}:- return-- try:- from hermes_cli.memory_setup import _install_dependencies- except Exception as exc:- logger.debug("Memory provider refresh skipped (import failed): %s", exc)- return-- print()- print(f"→ Refreshing active memory provider dependencies ({provider})...")-- try:- _install_dependencies(provider, force=True)- except Exception as exc:- print(f" ⚠ {provider} dependencies failed to refresh: {exc}")--def _npm_manifest_paths() -> tuple[Path, ...]:- """Manifests whose changes must defeat the update-skip.-- The lockfile alone is NOT a sufficient key: on a local checkout a dev- can edit package.json (root or a workspace) without running npm — the- lockfile is then unchanged but `hermes update` is exactly the step- expected to sync node_modules (via the `npm install` fallback in- _run_npm_install_deterministic).-- The workspace list is pulled from the root package.json's `workspaces`- globs (npm's own source of truth) rather than hardcoded, so adding a- workspace can never silently escape the skip key. Every workspace- manifest belongs in the key — desktop included, even though the- install only names ui-tui and web — because the single lockfile spans- the whole workspace graph, so any manifest edit can put the lockfile- out of sync and change what the install must do. Falls back to hashing- just root manifests if package.json is unreadable (never skips more- than main would have installed).- """- root_pkg = _m().PROJECT_ROOT / "package.json"- paths = [_m().PROJECT_ROOT / "package-lock.json", root_pkg]- try:- workspaces = json.loads(root_pkg.read_text(encoding="utf-8-sig")).get(- "workspaces", []- )- if isinstance(workspaces, dict): # legacy {"packages": [...]} form- workspaces = workspaces.get("packages", [])- for pattern in workspaces:- for match in sorted(_m().PROJECT_ROOT.glob(str(pattern))):- manifest = match / "package.json"- if manifest.is_file():- paths.append(manifest)- except (OSError, json.JSONDecodeError, TypeError):- pass- return tuple(paths)--def _npm_manifests_digest() -> str | None:- """Combined sha256 over the lockfile + all workspace package.json files.-- Returns None when the lockfile is missing (never skip then).- """- if not (_m().PROJECT_ROOT / "package-lock.json").exists():- return None- h = hashlib.sha256()- for p in _npm_manifest_paths():- h.update(str(p.relative_to(_m().PROJECT_ROOT)).encode())- try:- h.update(p.read_bytes())- except OSError:- h.update(b"<missing>")- return h.hexdigest()--def _npm_lockfile_changed(hermes_root: Path) -> bool:- current = _npm_manifests_digest()- if current is None:- return True- # Also check that node_modules exists; a matching hash with missing- # node_modules means the cache was recorded by another checkout.- if not (_m().PROJECT_ROOT / "node_modules").is_dir():- return True- # A matching lockfile hash over a tree whose web build toolchain never- # landed must NOT skip the reinstall — otherwise every later `hermes- # update` keeps rebuilding against a half-installed tree and serving a- # stale dist.- web_dir = _m().PROJECT_ROOT / "web"- if (web_dir / "package.json").is_file() and not _web_build_toolchain_ready(- *_web_toolchain_roots(web_dir)- ):- return True- try:- # Key the cache by PROJECT_ROOT so parallel worktrees don't collide.- cache_key = hashlib.sha256(str(_m().PROJECT_ROOT).encode()).hexdigest()[:12]- cache_file = hermes_root / f".npm_lock_hash_{cache_key}"- if not cache_file.exists():- return True- return cache_file.read_text(encoding="utf-8-sig").strip() != current- except OSError:- return True--def _record_npm_lockfile_hash(hermes_root: Path) -> None:- digest = _npm_manifests_digest()- if digest is None:- return- try:- cache_key = hashlib.sha256(str(_m().PROJECT_ROOT).encode()).hexdigest()[:12]- cache_file = hermes_root / f".npm_lock_hash_{cache_key}"- cache_file.write_text(digest, encoding="utf-8")- except OSError:- logger.debug("Could not write npm lockfile hash cache")--def _repair_node_deps_on_current_checkout(- print_completion,- *,- assume_yes: bool = False,- gateway_mode: bool = False,- pre_update_snapshot_id: str | None = None,- completion_message: str = "✓ Already up to date!",- had_desktop_app_before_update: bool = False,-) -> bool:- """Repair Node deps on the ``commit_count == 0`` path (#77211).-- A current checkout does not imply healthy Node deps: a previous npm- install may have failed (EBADENGINE from a node/npm mismatch, network- timeout, interrupted install) and its error message says to "re-run- hermes update" — but the early return never reached the Node refresh,- so that repair advice could never work. ``_update_node_dependencies``- self-gates on the lockfile hash, which is only recorded after a- SUCCESSFUL npm install (and re-trips when node_modules is missing or- the web toolchain never landed), so this is a cheap no-op on healthy- installs and a real repair after a failed one.- """- node_failures = _update_node_dependencies()- if node_failures:- print(f" ⚠ Node.js refresh failed for: {', '.join(node_failures)}")- print(" Fix npm and re-run `hermes update`.")- print_completion(- "⚠ Checkout is current, but Node.js dependencies could not be repaired."- )- return False- # Pair the refresh with the web build like every other- # _update_node_dependencies call site; it staleness-checks internally,- # so this is a no-op when nothing changed.- _m()._build_web_ui(_m().PROJECT_ROOT / "web")- _check_and_apply_config_migration(- assume_yes=assume_yes,- gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- )- # A current checkout can still owe a Desktop rebuild (#97343): the- # packaged app is built from source the pull already landed — or, on the- # Windows hand-off, by a child that never reaches the commits-pulled- # rebuild. Skipping it leaves a stale desktop app behind a- # successful-looking update. Self-gates on the build stamp, so this is a- # no-op when nothing changed.- if not _rebuild_desktop_after_update(- _m().PROJECT_ROOT / "apps" / "desktop",- had_desktop_app_before_update=had_desktop_app_before_update,- ):- # _rebuild_desktop_after_update already printed the retry hint; withhold- # success rather than claiming the update finished (#88251).- print_completion(- "⚠ Update partially complete — the desktop app was not rebuilt "- "and is still on the previous build."- )- return False- return bool(print_completion(completion_message))---def _update_node_dependencies() -> list[str]:- """Refresh Node deps for the ui-tui and web workspaces.-- Returns the list of labels whose npm install failed (empty on success),- so the caller can treat a Node refresh failure as a partial update rather- than silently reporting ``Update complete!`` (#30271).- """- if not (_m().PROJECT_ROOT / "package.json").exists():- return []-- npm = _m()._resolve_node_runtime_npm()- if not npm:- # If the only npm reachable inside this WSL shell is the Windows one,- # flag it loudly: silently skipping leaves ui-tui deps stale while the- # rest of the update proceeds, and running it would corrupt the tree.- from hermes_constants import is_wsl-- path_npm = shutil.which("npm")- if is_wsl() and path_npm and _m()._is_windows_npm_path(path_npm):- print("→ Updating Node.js dependencies...")- print(" ⚠ Skipped: only a Windows npm is reachable from this WSL shell.")- print(" Install Node.js inside the WSL distro (nvm, or your distro's")- print(" package manager), then re-run `hermes update`.")- failed = []- if any(- (_m().PROJECT_ROOT / workspace / "package.json").exists()- for workspace in ("ui-tui", "web")- ):- failed.append("ui-tui, web workspaces")- return failed- return []-- from hermes_constants import get_default_hermes_root-- # This cache describes PROJECT_ROOT/node_modules, which is shared by every- # Hermes profile using this checkout. Keep one per-checkout cache under the- # shared Hermes root rather than rerunning npm once per named profile.- shared_hermes_root = get_default_hermes_root()-- # Best-effort: warm npx's cache for agent-browser (#43564). Runs before- # the lockfile-unchanged early return below since that's the common- # `hermes update` case. Synchronous and can block ~11s on a true cold- # cache (~0.4s once warm) — print first so that doesn't look like a hang.- print("→ Warming npx cache for agent-browser...")- try:- from tools.browser_tool_install import warm_agent_browser_npx_cache- warm_agent_browser_npx_cache()- except Exception:- pass-- if not _m()._npm_lockfile_changed(shared_hermes_root):- logger.info("npm lockfile unchanged, skipping npm install")- return []-- # Root package.json has no dependencies of its own (agent-browser and- # @streamdown/math were moved out — see #43564): agent-browser resolves- # at runtime via `npx agent-browser` (tools/browser_tool.py), and- # @streamdown/math is a desktop-only import now declared in- # apps/desktop/package.json. That means a plain workspace-scoped install- # can never prune anything root-only, so we only need to name the- # workspaces the CLI/TUI/web build actually requires. apps/desktop pulls- # in Electron as a devDependency with a ~200MB postinstall download, so- # it's deliberately never named here — desktop deps install on demand- # (see _desktop_build_needed).- print("→ Updating Node.js dependencies...")-- def _partial_update_failure(*labels: str) -> list[str]:- print()- print(" ⚠ Node.js dependency refresh did not complete cleanly; the")- print(" installation may be in a mixed state (updated code, stale Node")- print(" deps). Fix npm and re-run `hermes update`.")- return list(labels)-- install_args = [- "--no-fund", "--no-audit", "--prefer-offline", "--progress=false",- "--workspace", "ui-tui", "--workspace", "web",- # Root package.json's own devDependencies (the shared ESLint flat- # config every workspace's eslint.config.mjs imports) are otherwise- # pruned by this scoped install, same as agent-browser/@streamdown- # math used to be before they moved out of root entirely (#43564).- # Unlike those, root's devDependencies have nowhere else to live —- # this flag still excludes apps/desktop, which is never named above.- "--include-workspace-root",- ]-- from hermes_constants import with_hermes_node_path-- nixos_env = with_hermes_node_path(_m()._nixos_build_env())-- # NOTE: capture_output=False here is deliberate (#18840) — optional- # postinstall scripts print download progress, and capturing it makes a- # long download look hung. The chatty npm-deprecation noise during- # `hermes update` comes from the *desktop* build, not this step; that- # one is captured to update.log.- result = _m()._run_npm_install_deterministic(- npm,- _m().PROJECT_ROOT,- extra_args=tuple(install_args),- capture_output=False,- env=nixos_env,- )- if result.returncode == 0:- _record_npm_lockfile_hash(shared_hermes_root)- print(" ✓ ui-tui, web workspaces installed (desktop skipped)")- failures: list[str] = []- else:- print(" ⚠ npm install failed")- stderr = (result.stderr or "").strip() if result.stderr else ""- if stderr:- print(f" {stderr.splitlines()[-1]}")- failures = _partial_update_failure("ui-tui, web workspaces")-- return failures--def _log_only_write(text: str) -> None:- """Write ``text`` to ``~/.hermes/logs/update.log`` only, never the terminal.-- During ``hermes update`` ``sys.stdout`` is an ``_UpdateOutputStream`` that- mirrors to both the terminal and ``update.log``. Loud, low-signal- subprocess output (npm installs, the Electron/vite build, the cua-driver- installer's "Next steps" wall) should be captured and tucked into the log- so failures stay debuggable, without flooding the user's terminal. This- reaches past the mirroring stream straight to the underlying log handle.- """- if not text:- return- stream = _m().sys.stdout- log_file = getattr(stream, "_log", None)- if log_file is None:- return- try:- log_file.write(text if text.endswith("\n") else text + "\n")- log_file.flush()- except Exception:- pass--def _run_logged_subprocess(cmd, *, cwd=None, env=None):- """Run ``cmd`` capturing combined output into update.log (not the terminal).-- Returns the ``CompletedProcess`` (with ``stdout`` populated) so the caller- can decide whether to surface the captured output on failure.- """- result = subprocess.run(- cmd,- cwd=cwd,- env=env,- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- encoding="utf-8",- errors="replace",- )- _log_only_write(result.stdout or "")- return result--def _classify_fetch_failure(stderr: str) -> str:- """Map git-fetch stderr to a one-line, user-facing diagnosis.-- Order matters: curl surfaces HTTP failures as- ``fatal: unable to access '<url>': The requested URL returned error: 429``,- so the rate-limit/outage checks must run BEFORE the generic- "unable to access" network check or a GitHub 429/5xx gets misreported as a- local network problem. The caller always prints the first raw stderr line- alongside this diagnosis — the friendly message adds guidance, it never- replaces the wire error.- """-- def _has_http_code(*codes: str) -> bool:- return any(- f"HTTP {code}" in stderr or f"returned error: {code}" in stderr- for code in codes- )-- if _has_http_code("429") or "rate limit" in stderr.lower():- return (- "✗ GitHub is rate limiting requests or having an outage (HTTP 429)"- " — try again in 5 minutes."- )- if _has_http_code("500", "502", "503", "504"):- return (- "✗ GitHub appears to be having an outage — try again in a few"- " minutes (https://www.githubstatus.com)."- )- if "Could not resolve host" in stderr or "unable to access" in stderr:- return "✗ Network error — cannot reach the remote repository."- if "could not read Username" in stderr or "terminal prompts disabled" in stderr:- # Anonymous fetch of a public repo got HTTP 401. GitHub does this- # during outages (and for renamed/private repos) — it is not a- # credentials problem on the user's side.- return (- "✗ GitHub rejected the anonymous fetch (asked for a login) — this"- " usually means a GitHub outage; try again in a few minutes"- " (https://www.githubstatus.com). If it persists, check"- " `git remote -v` points at a public repo."- )- if "Authentication failed" in stderr:- return "✗ Authentication failed — check your git credentials or SSH key."- return "✗ Failed to fetch updates from origin."---def _print_fetch_failure(stderr: str) -> None:- """Print the classified diagnosis plus the first raw stderr line."""- stderr = (stderr or "").strip()- print(_classify_fetch_failure(stderr))- if stderr:- print(f" {stderr.splitlines()[0]}")---def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):- """Implement ``hermes update --check``: fetch and report without installing.-- ``branch`` selects which branch the check compares against. Default is- "main"; callers can pass another branch to ask "are there new commits- on origin/<branch>?" without performing the update.-- ``branch_explicit`` is True iff the caller passed --branch on the CLI.- Installs that can't honor non-default branches (e.g. Docker) surface a- one-line notice instead of silently dropping the flag.- """- # Shared admission gate (#91277 Phase 3): same marker-first decision as- # the apply path, so --check can never report git state for an install- # whose real update mechanism is an image pull.- from hermes_cli.update_contract import (- evaluate_update_admission,- record_refusal_receipt,- )-- refusal = evaluate_update_admission(_m().PROJECT_ROOT)- if refusal is not None:- print(refusal.message)- record_refusal_receipt(refusal)- sys.exit(2)-- git_dir = _m().PROJECT_ROOT / ".git"- if not git_dir.exists():- print("✗ Not a git repository — cannot check for updates.")- sys.exit(1)-- git_cmd = ["git"]- if sys.platform == "win32":- git_cmd = ["git", "-c", "windows.appendAtomically=false"]-- # A crashed/interrupted fetch can leave .git/shallow.lock (or another git- # lock file) behind; every later fetch then fails with "File exists" and- # the check reports a hard failure (or, in the banner path, silently- # compares stale refs). Self-heal abandoned locks before fetching.- from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs-- cleared = clear_stale_git_locks(_m().PROJECT_ROOT)- for lock_path in cleared:- print(f" (removed stale git lock: {lock_path})")- # Aborted fetches on flaky lines also strand tmp_pack_* debris in- # .git/objects/pack — unchecked it reached 6 GB and corrupted the pack- # dir outright (#93732). Same age+process safety contract as the locks.- swept = clear_stale_tmp_packs(_m().PROJECT_ROOT)- if swept:- print(f" (removed {len(swept)} aborted-fetch pack temp file(s))")-- # Stable channel: if the caller did not ask for a branch, the question is- # "is there a newer tagged release?". The question is not "are there new- # commits on main?". Compare against the newest release tag and return.- if not branch_explicit:- if _stable_channel_active(None):- print("→ Update channel: stable (tagged releases)")- tag, tag_sha = _resolve_latest_release_tag(git_cmd, _m().PROJECT_ROOT)- if tag is None:- print("✗ No release tags found on origin. A check of the stable channel is not possible.")- print(" Switch channels with: hermes update --set-channel main")- sys.exit(1)- head_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)- # Newer releases possibly do not exist locally yet. "At the tag"- # is a SHA comparison. The merge-base check tells us whether HEAD- # contains the tag (HEAD is ahead of the release or at the release).- at_or_past_tag = False- if head_sha and tag_sha:- if head_sha == tag_sha:- at_or_past_tag = True- else:- contained = subprocess.run(- git_cmd + ["merge-base", "--is-ancestor", tag_sha, "HEAD"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- at_or_past_tag = contained.returncode == 0- if at_or_past_tag:- print(f"✓ Up to date with the latest release ({tag}).")- else:- print(f"→ New release available: {tag}")- print(" Run `hermes update` to install it.")- return-- # Fetch only the branch we compare against; prefer upstream as the canonical- # reference. A bare `git fetch <remote>` pulls every ref, and this repo has- # thousands of auto-generated branches, so scope the fetch to <branch>.- # Note: upstream/<branch> may not exist for non-main branches (a fork's- # bb/gui has no upstream counterpart), so when the caller picks a- # non-default branch we skip the upstream probe and use origin directly.- # Installer checkouts are shallow (`git clone --depth 1`). A plain- # `git fetch` would unshallow the repo (dragging in the whole history —- # the exact cost the shallow clone avoided) and the rev-list count below- # would then report a huge bogus "behind" number. Detect shallow up front:- # fetch with --depth 1 to preserve the boundary and report presence-only.- is_shallow = (- subprocess.run(- git_cmd + ["rev-parse", "--is-shallow-repository"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- == "true"- )- depth_args = ["--depth", "1"] if is_shallow else []-- if branch == "main":- # Probe locally (~6 ms) whether an 'upstream' remote exists at all- # before spending a network fetch on it. Non-fork installs have no- # 'upstream' remote, and the old flow burned a failed network attempt- # (~0.3-1 s) on every --check before falling back to origin.- has_upstream_remote = (- subprocess.run(- git_cmd + ["remote", "get-url", "upstream"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).returncode- == 0- )- fetch_result = None- if has_upstream_remote:- print("→ Fetching from upstream...")- fetch_result = subprocess.run(- git_cmd + ["fetch"] + depth_args + ["upstream", branch],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- **_no_prompt_git_kwargs(),- )- if fetch_result is not None and fetch_result.returncode == 0:- upstream_exists = True- compare_branch = f"upstream/{branch}"- else:- # No upstream remote, or the upstream fetch failed — use origin.- print("→ Fetching from origin...")- fetch_result = subprocess.run(- git_cmd + ["fetch"] + depth_args + ["origin", branch],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- **_no_prompt_git_kwargs(),- )- upstream_exists = False- compare_branch = f"origin/{branch}"- else:- # Non-default branch: compare against origin/<branch> directly.- print("→ Fetching from origin...")- fetch_result = subprocess.run(- git_cmd + ["fetch"] + depth_args + ["origin", branch],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- **_no_prompt_git_kwargs(),- )- upstream_exists = False- compare_branch = f"origin/{branch}"-- if fetch_result.returncode != 0:- _print_fetch_failure(fetch_result.stderr)- sys.exit(1)-- # Verify the compare ref actually exists before asking rev-list about it.- # Without this, `git rev-list HEAD..origin/<bogus> --count` exits 128 and- # (with check=True) raises CalledProcessError, surfacing a Python- # traceback. Friendlier to detect-and-report.- verify_result = subprocess.run(- git_cmd + ["rev-parse", "--verify", "--quiet", compare_branch],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if verify_result.returncode != 0:- print(f"✗ Branch '{branch}' not found on {compare_branch.split('/', 1)[0]}.")- sys.exit(1)-- if is_shallow:- # No history to count across the shallow boundary. Compare tip SHAs- # (mirrors the banner's _check_via_local_git), then try to recover the- # exact count via the GitHub compare API — the remote graph is complete- # even when the local one is truncated.- head_sha = subprocess.run(- git_cmd + ["rev-parse", "HEAD"],- cwd=_m().PROJECT_ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- target_sha = subprocess.run(- git_cmd + ["rev-parse", compare_branch],- cwd=_m().PROJECT_ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- if head_sha and target_sha and head_sha == target_sha:- print("✓ Already up to date.")- else:- from hermes_cli.banner import _github_compare_behind- from hermes_cli.config import recommended_update_command-- counted = _github_compare_behind(head_sha, target_sha)- if counted == 0:- # Local commits on top of the remote tip — not behind.- print("✓ Already up to date.")- return- if counted is not None:- commits_word = "commit" if counted == 1 else "commits"- print(f"⚕ Update available: {counted} {commits_word} behind {compare_branch}.")- else:- print(f"⚕ Update available (behind {compare_branch}).")- print(f" Run '{recommended_update_command()}' to install.")- return-- rev_result = subprocess.run(- git_cmd + ["rev-list", f"HEAD..{compare_branch}", "--count"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=True,- )- behind = int(rev_result.stdout.strip())-- if behind == 0:- print("✓ Already up to date.")- else:- commits_word = "commit" if behind == 1 else "commits"- print(f"⚕ Update available: {behind} {commits_word} behind {compare_branch}.")- from hermes_cli.config import recommended_update_command-- print(f" Run '{recommended_update_command()}' to install.")--def _ensure_fhs_path_guard() -> None:- """Ensure /usr/local/bin is on PATH for RHEL-family root non-login shells.-- Mirrors the post-symlink probe added to ``scripts/install.sh`` so that- existing FHS-layout root installs on RHEL/CentOS/Rocky/Alma 8+ get- repaired on ``hermes update`` without requiring a reinstall. The- installer's assumption that ``/usr/local/bin`` is on PATH for every- standard shell breaks on those distros in non-login interactive shells- (su, sudo -s, tmux panes, some web terminals): /etc/bashrc doesn't- add /usr/local/bin and /root/.bash_profile doesn't either. Symptom:- ``hermes`` prints ``command not found`` even though the symlink lives- at /usr/local/bin/hermes.-- Silent no-op on: non-Linux, non-root, non-FHS installs, and any system- where ``bash -i -c 'command -v hermes'`` already resolves. Idempotent.- """- if _m().sys.platform != "linux":- return- try:- if os.geteuid() != 0: # windows-footgun: ok — Linux FHS helper, guarded by sys.platform == "linux" above + AttributeError catch- return- except AttributeError:- return- # Only act when this is actually an FHS-layout install (command link at- # /usr/local/bin/hermes, code at /usr/local/lib/hermes-agent).- fhs_link = Path("/usr/local/bin/hermes")- if not fhs_link.is_symlink() and not fhs_link.exists():- return-- # Probe a fresh non-login interactive bash the way the user will use it.- # ``bash -i -c`` sources ~/.bashrc but NOT ~/.bash_profile or /etc/profile,- # which is the exact scenario where RHEL root loses /usr/local/bin.- home = os.environ.get("HOME") or "/root"- try:- probe = subprocess.run(- [- "env",- "-i",- f"HOME={home}",- f"TERM={os.environ.get('TERM', 'dumb')}",- "bash",- "-i",- "-c",- "command -v hermes",- ],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=10,- )- except (FileNotFoundError, subprocess.TimeoutExpired):- return # no bash or probe hung — don't block update on this- if probe.returncode == 0:- return # already on PATH, nothing to do-- path_line = 'export PATH="/usr/local/bin:$PATH"'- path_comment = (- "# Hermes Agent — ensure /usr/local/bin is on PATH " "(RHEL non-login shells)"- )- wrote_any = False- for candidate in (".bashrc", ".bash_profile"):- cfg = Path(home) / candidate- if not cfg.is_file():- continue- try:- existing = cfg.read_text(errors="replace", encoding="utf-8-sig")- except OSError:- continue- # Idempotency: skip if any uncommented PATH= line already references- # /usr/local/bin. Mirrors the grep pattern used by install.sh.- already_guarded = any(- "/usr/local/bin" in line- and "PATH" in line- and not line.lstrip().startswith("#")- for line in existing.splitlines()- )- if already_guarded:- continue- try:- with cfg.open("a", encoding="utf-8") as f:- f.write("\n" + path_comment + "\n" + path_line + "\n")- except OSError as e:- print(f" ⚠ Could not update {cfg}: {e}")- continue- print(f" ✓ Added /usr/local/bin to PATH in {cfg}")- wrote_any = True- if wrote_any:- print(" (reload your shell or run 'source ~/.bashrc' to pick it up)")--def _ensure_acp_launcher() -> None:- r"""Self-heal: install a ``hermes-acp`` launcher next to the ``hermes`` one.-- Mirrors the launcher block in ``scripts/install.sh`` so existing installs- gain the ACP command on ``hermes update`` without a reinstall. ACP hosts- (Zed, JetBrains, Buzz Desktop) spawn the agent by resolving the- ``hermes-acp`` command name against the login-shell PATH; the console- script of that name lives inside the install's venv, which is not on that- PATH, so those hosts report Hermes as not installed even when it is.-- The shim simply delegates to the sibling ``hermes`` launcher with the- ``acp`` subcommand, which makes it correct for every install layout- (venv wrapper, FHS symlink, pipx/pip console script) without having to- reconstruct interpreter/entrypoint paths.-- No-op on Windows (install.ps1 stages the ``hermes`` / ``hermes-acp``- launchers into the managed binary dir ``$HermesHome\bin`` and puts THAT- on the user PATH — never the whole ``venv\Scripts`` dir, which would- shadow the user's ``python`` (#83797); when those launchers go missing,- ``hermes_cli._install_repair.ensure_windows_bin_launchers`` re-stages- them) and wherever a ``hermes-acp`` is already present next to the- ``hermes`` command. Unwritable directories (e.g. ``/usr/local/bin`` as- non-root) are skipped silently. Idempotent.- """- if _m().sys.platform == "win32":- # Windows launcher staging/repair lives in _install_repair- # (ensure_windows_bin_launchers at process start,- # migrate_windows_bin_path in this command's tail) — not here.- return- for bin_dir in (Path.home() / ".local" / "bin", Path("/usr/local/bin")):- hermes_cmd = bin_dir / "hermes"- acp_cmd = bin_dir / "hermes-acp"- try:- if not (hermes_cmd.is_file() or hermes_cmd.is_symlink()):- continue- # Already present — a console script (pip/pipx install), an- # earlier shim, or a symlink. is_symlink() catches broken- # symlinks that exists() would miss; never follow-and-overwrite- # (the #21454 failure mode).- if acp_cmd.exists() or acp_cmd.is_symlink():- continue- shim = (- "#!/usr/bin/env bash\n"- "# Hermes Agent — ACP launcher (written by `hermes update`).\n"- "# ACP hosts (Zed, JetBrains, Buzz) resolve the agent by this\n"- "# command name on the login-shell PATH.\n"- f'exec "{hermes_cmd}" acp "$@"\n'- )- acp_cmd.write_text(shim, encoding="utf-8")- acp_cmd.chmod(acp_cmd.stat().st_mode | 0o755)- except OSError:- continue- print(f" ✓ Installed hermes-acp launcher → {acp_cmd}")--_PRE_UPDATE_SNAPSHOT_KEEP = 1-# Sibling-profile snapshot ids from the current run's pre-update backup-# ({profile: snapshot_id}) — consumed by the post-update per-profile-# cron-jobs safety net (#66140). Module-level because the snapshot and the-# restore run in the same process but far apart in _cmd_update_impl.-_LAST_SIBLING_SNAPSHOTS: dict = {}--# Per-file size cap for the pre-update quick snapshot. Anything larger is-# skipped with a warning: the snapshot exists to protect small, hard-to--# regenerate state (pairing JSONs, cron jobs, config, auth) — not to copy a-# multi-GB state.db on every update (observed: a 24 GB state.db added ~60s-# of wall time and silently ate 24 GB of disk per update).-_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE = 1 << 30 # 1 GiB--def _resolve_pre_update_backup_mode(args) -> str:- """Resolve the pre-update backup mode: ``"off"``, ``"quick"``, or ``"full"``.-- CLI flags win over config; ``--no-backup`` beats ``--backup`` when both- are set. Config accepts the mode strings plus legacy booleans:- ``true`` → ``full`` (the old zip behavior), ``false`` → ``off``- (an explicit opt-out now disables the quick snapshot too — previously- it ran unconditionally, ignoring the user's setting). A missing key- defaults to ``quick``.- """- if getattr(args, "no_backup", False):- return "off"- if getattr(args, "backup", False):- return "full"-- try:- from hermes_cli.config import load_config-- cfg = load_config()- except Exception as exc:- logging.getLogger(__name__).debug(- "Could not load config for pre-update backup: %s", exc- )- cfg = {}-- updates_cfg = cfg.get("updates", {}) if isinstance(cfg, dict) else {}- raw = updates_cfg.get("pre_update_backup", "quick")-- if raw is True:- return "full"- if raw is False:- return "off"- mode = str(raw).strip().lower()- if mode in ("off", "false", "none", "disabled"):- return "off"- if mode in ("full", "zip", "true"):- return "full"- if mode == "quick":- return "quick"- logging.getLogger(__name__).warning(- "Unknown updates.pre_update_backup value %r — using 'quick'", raw- )- return "quick"--def _run_pre_update_backup(args) -> Optional[str]:- """Run the pre-update safety backup and return the quick-snapshot id.-- Single consolidated mechanism gated on ``updates.pre_update_backup``:-- - ``off`` — nothing runs. Explicit user opt-out is honored fully.- - ``quick`` (default) — a state snapshot of critical small files- (pairing JSONs, cron jobs, config, auth; see ``_QUICK_STATE_FILES``)- under ``state-snapshots/``. Files over 1 GiB are skipped with a- warning so a bloated state.db can never stall the update- (issues #15733, #34600 are the reason this safety net exists).- - ``full`` — the quick snapshot PLUS a full zip of HERMES_HOME under- ``backups/`` (restorable via ``hermes import``; the #48200 wrong-path- wipe is the reason this level exists).-- ``--backup`` forces ``full`` for one run; ``--no-backup`` forces ``off``.- Never raises — a backup failure should not block the update itself.-- Returns the quick-snapshot id (used by the post-update cron-jobs- restore safety net), or ``None`` when mode is ``off`` or the snapshot- failed.- """- mode = _resolve_pre_update_backup_mode(args)-- if mode == "off":- if getattr(args, "no_backup", False):- print("◆ Pre-update backup: skipped (--no-backup)")- print()- # Config-level off is silent — the user opted out; don't spam them- # on every update.- return None-- snapshot_id = None- try:- from hermes_cli.backup import (- _quick_snapshot_root,- create_quick_snapshot,- verify_sqlite_integrity,- )-- # NOTE: this function later does `from hermes_constants import- # get_hermes_home`, which makes the name function-local — the- # module-level import is shadowed and unbound here. Alias explicitly.- from hermes_cli.config import get_hermes_home as _get_home-- snapshot_id = create_quick_snapshot(- label="pre-update",- keep=_PRE_UPDATE_SNAPSHOT_KEEP,- max_file_size=_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- )-- # After the snapshot, verify the source state.db is still intact.- # The snapshot was taken via _safe_copy_db (read-only SQLite backup- # API), but a concurrent process (antivirus, force-killed gateway- # releasing file handles, Windows filter driver) can corrupt the live- # file at any point. A silent zeroing at this point would proceed with- # the update and exit code 0 — exactly the #68474 symptom.- if snapshot_id:- _src_path = _get_home() / "state.db"- if _src_path.exists():- _integrity = verify_sqlite_integrity(- _src_path,- check_header=True,- run_pragma=True,- max_bytes=_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- )- if not _integrity.get("valid"):- _msg = _integrity.get("message", "unknown error")- print(- f" ⚠ state.db integrity check FAILED after snapshot: {_msg}"- )- # Check if the snapshot itself is valid.- _snap_root = _quick_snapshot_root(_get_home())- _snap_state = _snap_root / snapshot_id / "state.db"- if _snap_state.exists():- _snap_ok = verify_sqlite_integrity(- _snap_state, check_header=True, run_pragma=True- )- if _snap_ok.get("valid"):- print(- " ✓ Snapshot copy is valid — continuing update."- )- print(- " If state.db is lost after update it will be auto-restored."- )- else:- print(- " ✗ Snapshot copy ALSO failed integrity — "- "the source was already corrupted before the backup."- )- else:- print(- " ⚠ Snapshot does not contain state.db (was skipped or too large)."- )- print()- if snapshot_id:- print(f"◆ Pre-update snapshot: {snapshot_id}")-- # #66140: the code swap + fleet restart touch EVERY profile, so- # every profile gets the same snapshot (same set, same 1GiB cap,- # keep=1) under its own state-snapshots/. Best-effort per profile.- try:- from hermes_cli.backup import create_pre_update_snapshots_all_profiles-- _sibling_snaps = create_pre_update_snapshots_all_profiles(- keep=_PRE_UPDATE_SNAPSHOT_KEEP,- max_file_size=_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- )- if _sibling_snaps:- print(- f"◆ Sibling profile snapshot(s): "- + ", ".join(sorted(_sibling_snaps))- )- try:- from hermes_cli.update_receipt import record_step-- record_step(- "sibling_profile_snapshots",- True,- ", ".join(- f"{k}={v}" for k, v in sorted(_sibling_snaps.items())- ),- )- except Exception:- pass- global _LAST_SIBLING_SNAPSHOTS- _LAST_SIBLING_SNAPSHOTS = _sibling_snaps- except Exception as _sib_exc:- logging.getLogger(__name__).debug(- "Sibling profile snapshots failed: %s", _sib_exc- )- except Exception as exc:- # Never let a snapshot failure block an update.- logging.getLogger(__name__).debug("Pre-update snapshot failed: %s", exc)-- if mode != "full":- if snapshot_id:- print()- return snapshot_id-- try:- from hermes_cli.backup import create_pre_update_backup- except Exception as exc:- print(- f"⚠ Pre-update backup: could not load backup module ({exc}); continuing update."- )- print()- return snapshot_id-- try:- from hermes_cli.config import load_config-- _keep = (load_config() or {}).get("updates", {}).get("backup_keep", 5)- except Exception:- _keep = 5-- print("◆ Creating pre-update backup...")- t0 = _time.monotonic()- try:- out_path = create_pre_update_backup(keep=int(_keep))- except Exception as exc: # defensive — helper already swallows, but just in case- print(f" ⚠ Backup failed: {exc}")- print(" Continuing with update.")- print()- return snapshot_id-- elapsed = _time.monotonic() - t0-- if out_path is None:- print(" ⚠ Backup skipped (no files found or write failed); continuing update.")- print()- return snapshot_id-- try:- size_bytes = out_path.stat().st_size- except OSError:- size_bytes = 0-- # Human-readable size- from hermes_cli.sizefmt import format_bytes-- size_str = format_bytes(size_bytes)-- # Render path using display_hermes_home so the user sees ~/.hermes/...- try:- from hermes_constants import get_hermes_home, display_hermes_home-- home = get_hermes_home()- try:- display_path = f"{display_hermes_home()}/{out_path.relative_to(home)}"- except ValueError:- display_path = str(out_path)- except Exception:- display_path = str(out_path)-- print(f" Saved: {display_path} ({size_str}, {elapsed:.1f}s)")- print(f" Restore: hermes import {out_path}")- print(" Disable: set updates.pre_update_backup: quick (or off) in config.yaml")- print()- return snapshot_id--def _write_update_planned_stop_marker(profile_path: Path, pid: int) -> bool:- """Write a planned-stop marker into a specific profile home."""- try:- from datetime import timezone-- from gateway.status import _get_process_start_time- from utils import atomic_json_write-- record = {- "target_pid": pid,- "target_start_time": _get_process_start_time(pid),- "stopper_pid": os.getpid(),- "written_at": datetime.now(timezone.utc).isoformat(),- }- atomic_json_write(- Path(profile_path) / ".gateway-planned-stop.json",- record,- indent=None,- separators=(",", ":"),- )- return True- except (OSError, PermissionError):- return False--def _wait_for_windows_update_gateway_exit(- pids: list[int], *, timeout: float-) -> set[int]:- """Wait for the given gateway PIDs to exit, returning survivors."""- if not pids:- return set()-- from gateway.status import _pid_exists-- remaining = set(pids)- deadline = _time.monotonic() + max(timeout, 0.0)- while remaining and _time.monotonic() < deadline:- for pid in list(remaining):- try:- if not _pid_exists(pid):- remaining.discard(pid)- except Exception:- remaining.discard(pid)- if remaining:- _time.sleep(0.25)-- survivors: set[int] = set()- for pid in remaining:- try:- if _pid_exists(pid):- survivors.add(pid)- except Exception:- pass- return survivors--def _venv_core_imports_healthy() -> tuple[bool, str]:- """Probe the project venv for the core imports the backend needs to boot.-- Runs a tiny import check inside the venv interpreter (NOT this process —- ``hermes update`` may be driven by a different Python). Catches the- half-updated-venv state: git checkout current but a dependency sync that- failed or was killed partway (e.g. Windows access-denied on a loaded- .pyd), leaving imports like ``fastapi``'s new transitive deps missing.- Without this probe, ``hermes update`` on a current checkout prints- "Already up to date!" and returns without ever re-syncing dependencies —- the user's install stays broken no matter how many times they update- (ryanc's incident, July 2026).-- Returns ``(healthy, detail)``. Never raises; unknown states report- healthy so a probe failure can't force needless reinstalls.- """- venv_dir = _m().PROJECT_ROOT / "venv"- venv_python = venv_python_path(venv_dir, windows=_m()._is_windows())- if not venv_python.exists():- # No venv interpreter at all. In a dev checkout that's normal (the- # dev may run hermes from any interpreter), so report healthy to- # avoid forcing reinstalls. But on a MANAGED install (the Windows- # installer / desktop bootstrap stamps `.hermes-bootstrap-complete`,- # and an interrupted update leaves `.update-incomplete`), the venv- # IS the install — its absence means a repair got interrupted after- # the old venv was moved aside, and "Already up to date!" would- # gaslight the user while nothing can run.- managed_markers = (- _m().PROJECT_ROOT / ".hermes-bootstrap-complete",- _m()._update_marker_path(),- )- if any(m.exists() for m in managed_markers):- return False, f"venv python missing ({venv_python})"- return True, ""-- # Core web/serve imports plus their newest transitive deps. Import (not- # just metadata) — a package can have intact dist-info but a missing- # module after an interrupted uninstall/install cycle.- check = (- "import importlib\n"- "mods = ['fastapi', 'uvicorn', 'pydantic', 'openai', 'yaml']\n"- "missing = []\n"- "for m in mods:\n"- " try: importlib.import_module(m)\n"- " except Exception as e: missing.append(f'{m}: {e}')\n"- "print('\\n'.join(missing))\n"- )- try:- result = subprocess.run(- [str(venv_python), "-c", check],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=60,- cwd=_m().PROJECT_ROOT,- )- except Exception as exc:- logger.debug("venv health probe failed to run: %s", exc)- return True, ""-- missing = [line.strip() for line in (result.stdout or "").splitlines() if line.strip()]- if result.returncode != 0 and not missing:- # Interpreter itself is broken (e.g. deleted stdlib) — that IS unhealthy.- detail = (result.stderr or "").strip().splitlines()- return False, detail[0] if detail else "venv python failed to run"- if missing:- return False, "; ".join(missing[:4])- return True, ""--def _detect_venv_python_processes(- *, exclude_pids: set[int] | None = None-) -> list[tuple[int, str, str]]:- """Find live processes running from the project venv's interpreter.-- The hermes.exe shim guard misses the biggest lock-holder class on- Windows: the Desktop app's backend (``python.exe -m hermes_cli.main- serve``) and anything else running straight off ``venv\\Scripts\\python- (w).exe``. Those processes keep native ``.pyd`` extensions mapped, so a- dependency sync mid-update dies with access-denied and strands the venv- half-updated (ryanc's brotlicffi/_sodium.pyd incidents, July 2026).-- Killing them from here is pointless — the Desktop app supervises its- backend and respawns it within seconds — so the caller should refuse and- tell the user to close the app instead. Returns ``(pid, name, cmdline)``- tuples; empty off-Windows / without psutil / when nothing matches. The- calling process and its ancestors are always excluded (a CLI ``hermes- update`` itself runs from the venv python). Never raises.- """- if not _m()._is_windows():- return []- try:- import psutil- except Exception:- return []-- venv_dir = _m().PROJECT_ROOT / "venv"- try:- venv_prefix = str(venv_dir.resolve()).lower().rstrip(os.sep) + os.sep- except OSError:- venv_prefix = str(venv_dir).lower().rstrip(os.sep) + os.sep- try:- root_prefix = str(_m().PROJECT_ROOT.resolve()).lower().rstrip(os.sep) + os.sep- except OSError:- root_prefix = str(_m().PROJECT_ROOT).lower().rstrip(os.sep) + os.sep-- skip: set[int] = set(exclude_pids or set())- skip.add(os.getpid())- try:- from gateway.status import looks_like_gateway_command_line as _is_gw- except Exception:- _is_gw = None- try:- for anc in psutil.Process().parents():- # #87594: do NOT blanket-exclude ancestors. When `/update` runs- # from a messaging platform the updater is a CHILD of the gateway- # — excluding all ancestors hides the gateway from the scan, so- # the pause machinery downstream never sees the one process it- # exists to stop, and the update dead-ends on `venv-blocked`.- # A GATEWAY ancestor stays visible (the pause path stops it- # gracefully; a detached child updater survives its parent's- # stop on Windows). Every other ancestor (shells, terminals,- # this CLI's own venv python chain) stays excluded — an updater- # must never nominate its own interactive ancestry as blockers.- try:- anc_cmdline = " ".join(anc.cmdline() or [])- except Exception:- anc_cmdline = ""- if _is_gw is not None and anc_cmdline and _is_gw(anc_cmdline):- continue- skip.add(int(anc.pid))- except Exception:- pass-- matches: list[tuple[int, str, str]] = []- try:- # On Windows, prefetching cmdline and cwd performs two expensive- # per-process queries. A busy workstation can have 500+ processes, so- # querying those fields for every unrelated process can exceed the- # Desktop preflight watchdog. First collect only cheap identity fields;- # fetch cmdline/cwd lazily for plausible Python/uv/Hermes candidates.- proc_iter = psutil.process_iter(["pid", "exe", "name"])- except Exception:- return []- for proc in proc_iter:- try:- info = proc.info- except Exception:- continue- pid = info.get("pid")- exe = info.get("exe")- if not exe or pid is None or int(pid) in skip:- continue- try:- exe_norm = str(Path(exe).resolve()).lower()- except (OSError, ValueError):- exe_norm = str(exe).lower()- # Primary match: the executable itself lives under this venv- # (venv\Scripts\python(w).exe — the desktop backend / gateway case).- is_holder = exe_norm.startswith(venv_prefix)- name = str(info.get("name") or Path(exe).name)- name_low = name.lower()-- if not is_holder and not (- name_low.startswith(("python", "pypy"))- or name_low in {"uv.exe", "uvx.exe", "hermes.exe"}- ):- continue-- try:- cmdline_raw = " ".join(proc.cmdline() or [])- except Exception:- cmdline_raw = ""- cmdline_low = cmdline_raw.lower()- # Fallback: uv/base-interpreter trampolines run a python whose exe is- # OUTSIDE the venv but which still imports from it and holds its .pyd- # files. Catch those by what they're running: a cmdline that references- # this venv's path, or a `-m hermes_cli.main ...` invocation tied to- # this install (install root in the cmdline or as the working dir).- if not is_holder and venv_prefix in cmdline_low:- is_holder = True- if not is_holder and "hermes_cli.main" in cmdline_low:- try:- cwd_low = str(proc.cwd() or "").lower().rstrip(os.sep) + os.sep- except Exception:- cwd_low = os.sep- if root_prefix in cmdline_low or cwd_low.startswith(root_prefix):- is_holder = True- if not is_holder:- continue- name = info.get("name") or Path(exe).name- # Return the FULL cmdline: callers match against it (the Desktop- # preflight's pausable-gateway exemption parses for `gateway run`).- # Truncating here cut long managed-runtime interpreter paths before- # the `-m hermes_cli.main gateway run` argv, so autostarted gateways- # were misreported as blockers and the update dead-ended. Truncate- # only at display time.- matches.append((int(pid), str(name), cmdline_raw))- return matches--# Native-extension modules that pin files inside the venv once imported. If-# the updater process itself has any of these loaded, the dependency sync-# below cannot rewrite the backing ``.pyd``/``.dll`` — Windows blocks REPLACE-# on a mapped image — and the update dies with ``os error 5`` between-# uninstall and reinstall, stranding the venv half-updated (#83569).-# ``cryptography`` is the canonical case: ``hermes_cli.main`` used to import-# it at startup while resolving external secret sources; ``PyYAML``'s-# ``_yaml`` C extension is loaded by every CLI process (config parsing).-# Keep this guard as defence-in-depth against future eager imports (new-# secret sources, plugins absorbed into core, refactors of the startup-# order) — but the guard must be HONEST (#86735/#86780/#86781: a preflight-# that fired on every run, before the fetch, re-bricked the exact flow it-# was meant to protect). Two honesty gates:-#-# 1. It only fires when the dependency sync would actually REWRITE the-# loaded distribution (``_dependency_sync_would_rewrite``): if the-# installed version already satisfies the on-disk pyproject pins, uv/pip-# will not touch the mapped ``.pyd``, so there is no lock to trip.-# 2. It runs AFTER the code swap (git pull / ZIP commit), immediately-# before the venv rewrite — so the on-disk pyproject is the NEW one-# (gate 1 compares against the right target) and a deferral no longer-# strands the user on the old checkout: the next launch's marker-# recovery completes the dependency install against the already-updated-# pyproject.-#-# Keys are module prefixes in ``sys.modules``; values are-# ``(display name, PyPI distribution name)``.-_SELF_LOCKING_NATIVE_MODULES: dict[str, tuple[str, str]] = {- "cryptography.hazmat.bindings._rust": ("cryptography (_rust.pyd)", "cryptography"),- "yaml._yaml": ("PyYAML (_yaml.pyd)", "pyyaml"),-}---def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:- """Whether ``uv pip install -e .[all]`` would replace *dist_name*'s files.-- Compares the installed distribution version against every applicable- requirement for it in the on-disk ``pyproject.toml`` (base dependencies- plus all optional extras). Returns:-- - ``False`` — installed version satisfies every pin: the resolver will- leave the wheel alone, so a mapped extension is NOT at risk.- - ``True`` — some pin is not satisfied (or the distribution is- missing): the sync will rewrite it.- - ``None`` — could not determine (parse failure, unparseable pins).-- Never raises. Callers treat ``None`` as fail-OPEN (no deferral): a- module in the registry can be loaded by every process (PyYAML), so- deferring on uncertainty would recreate the #86735 always-firing loop.- """- try:- from importlib import metadata as _ilmd-- installed = _ilmd.version(dist_name)- except Exception:- return True # not installed → the sync will definitely install it- try:- import tomllib-- from packaging.requirements import Requirement- from packaging.utils import canonicalize_name- from packaging.version import Version-- pyproject = _m().PROJECT_ROOT / "pyproject.toml"- data = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))- project = data.get("project") or {}- req_strings: list[str] = list(project.get("dependencies") or [])- for extra_reqs in (project.get("optional-dependencies") or {}).values():- req_strings.extend(extra_reqs or [])-- target = canonicalize_name(dist_name)- installed_v = Version(installed)- saw_pin = False- for req_str in req_strings:- try:- req = Requirement(req_str)- except Exception:- continue- if canonicalize_name(req.name) != target:- continue- if req.marker is not None and not req.marker.evaluate():- continue- saw_pin = True- if installed_v not in req.specifier:- return True- if saw_pin:- return False- # Not pinned anywhere in pyproject: the resolver may still move it- # as a transitive — we cannot cheaply predict that, so stay honest- # about the uncertainty.- return None- except Exception:- return None---def _detect_self_loaded_native_modules() -> list[str]:- """Native venv extensions loaded into THIS process that the sync would rewrite.-- Returns display names (empty off Windows — POSIX lets a running process- keep using an unlinked inode, so self-locking is a Windows-only hazard).- A loaded module whose installed version already satisfies the on-disk- pyproject pins is NOT reported: the dependency sync will not touch its- files, so there is no swap at risk (#86735 — the always-firing variant- of this preflight bricked every Windows update). Never raises.- """- if not _m()._is_windows():- return []- found = []- for prefix, (display, dist) in _SELF_LOCKING_NATIVE_MODULES.items():- if prefix not in sys.modules:- continue- # Defer ONLY on a CONFIRMED pending rewrite. An "unknown" result- # (unreadable/unparseable pyproject, no pin found) must fail OPEN:- # PyYAML is loaded in every CLI process, so treating unknown as- # at-risk would re-create the exact always-firing loop this guard's- # first version caused (#86735). The downside of a missed deferral- # is the pre-existing failure mode — a mid-sync os error 5 that the- # marker recovery already handles — which is strictly less harmful- # than an update that can never run.- if _m()._dependency_sync_would_rewrite(dist) is not True:- continue- found.append(display)- return sorted(set(found))---def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:- """Defer the venv rewrite when THIS process holds something it must replace.-- Runs at the last moment before the venv rewrite — after the code swap —- so the on-disk pyproject reflects the update target and a deferral- leaves the user on NEW code with only the dependency install pending.- No-op when nothing at-risk is held.-- Two hazards, both "this process holds a file the sync must replace", and- they end differently because their recoveries differ:-- - A mapped native extension (``.pyd``). Exit 2 and let the next launch's- marker recovery finish the install: that launch runs the install before- importing anything heavy, so it maps nothing and the swap succeeds.-- - The ``hermes.exe`` console shim we were launched from (#88838, #89599).- The marker cannot help here — every future ``hermes`` launch is also the- shim, so deferring to the next launch defers forever. Hand the install- to a child under the venv interpreter and exit, releasing the shim.- """- locked = _m()._detect_self_loaded_native_modules()- if locked:- _m()._defer_update_for_self_lock(locked)- if gateway_resume is not None:- _m()._resume_windows_gateways_after_update(gateway_resume)- sys.exit(2)-- if _m()._reexec_dependency_sync_off_windows_shim():- if gateway_resume is not None:- _m()._resume_windows_gateways_after_update(gateway_resume)- sys.exit(0)---def _defer_update_for_self_lock(loaded: list[str]) -> None:- """Bail out before the dependency sync when the updater holds a lock.-- The install cannot win this race from inside the locked process — even- killing threads would not unmap the image — so defer it: drop the- update-incomplete marker (next launch's fresh process completes the- install before importing anything heavy), explain, and exit 2 like the- other preflight refusals.- """- print("✗ This updater process has already loaded native venv modules that")- print(" the dependency sync must replace:")- for name in loaded:- print(f" {name}")- print()- print(" On Windows a mapped extension cannot be replaced by the process")- print(" holding it. The code update has been applied; only the dependency")- print(" sync has been deferred: the next `hermes` launch will complete it")- print(" in a fresh process before anything imports these modules.")- _m()._write_update_incomplete_marker()---_HOLDER_VALUE_FLAGS_FALLBACK = frozenset(- {- "--profile", "-p", "--config",- "--model", "-m", "--provider", "--reasoning",- "--toolsets", "-t", "--skills", "-s",- "--continue", "-c", "--resume", "-r",- "--oneshot", "-z", "--in", "--usage-file",- }-)-_holder_value_flags_cache: frozenset | None = None---def _holder_value_flags() -> frozenset:- """Top-level CLI flags that consume a value — derived from the REAL parser.-- Introspects ``build_top_level_parser()`` (every option with nargs != 0)- so the holder classifier can never drift from the argparse surface- (#91869 review: a handwritten subset misparsed ``--reasoning high- serve`` as subcommand ``high`` and ``-m dashboard serve`` as- ``dashboard`` — recreating the wrong-hint class). The pre-argparse- profile selectors (``--profile``/``-p``, ``--config``) are added- explicitly since they are stripped before argparse sees argv. Falls- back to a static snapshot when the parser cannot be imported (the- updater must classify holders even mid-upgrade on a broken tree).- Cached per process.- """- global _holder_value_flags_cache- if _holder_value_flags_cache is not None:- return _holder_value_flags_cache- flags: set[str] = {"--profile", "-p", "--config"}- try:- from hermes_cli._parser import build_top_level_parser-- parser = build_top_level_parser()[0]- for action in parser._actions:- if action.option_strings and action.nargs != 0:- flags.update(action.option_strings)- _holder_value_flags_cache = frozenset(flags)- except Exception:- _holder_value_flags_cache = _HOLDER_VALUE_FLAGS_FALLBACK- return _holder_value_flags_cache---def _hermes_holder_subcommand(cmdline: str) -> str | None:- """The actual Hermes SUBCOMMAND a venv-holder argv runs, or None.-- Token-based, never substring (#90778: ``kanban --preserve-cache``- contained \"serve\" and got labeled as the Desktop backend). Finds the- ``hermes_cli.main`` / ``hermes(.exe)`` entry token, then returns the- first following token that is not a flag or a flag's value. Profile- selectors (``--profile X``, ``-p X``) are skipped like the canonical- gateway matcher does. Returns None when no subcommand can be- determined — callers must NOT guess a label in that case.- """- try:- import shlex-- tokens = shlex.split(cmdline, posix=False)- except Exception:- tokens = cmdline.split()-- entry_idx: int | None = None- for i, token in enumerate(tokens):- low = token.lower().strip('"')- if low.endswith("hermes_cli.main") and i > 0 and tokens[i - 1] == "-m":- entry_idx = i- break- base = low.rsplit("\\", 1)[-1].rsplit("/", 1)[-1]- if base in ("hermes", "hermes.exe"):- entry_idx = i- break- if entry_idx is None:- return None-- value_flags = _holder_value_flags()- i = entry_idx + 1- while i < len(tokens):- token = tokens[i]- if token in value_flags or token.split("=", 1)[0] in value_flags:- # --flag value consumes two tokens; --flag=value consumes one.- i += 1 if "=" in token else 2- continue- if token.startswith("-"):- i += 1- continue- return token.lower()- return None---def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) -> str:- """Explain which venv processes block the update and how to clear them.-- Holder labels come from the parsed SUBCOMMAND, never substring matching- (#90778): a standalone ``hermes dashboard`` must not be labeled as the- Desktop backend (advice to close an app that isn't running), and flags- like ``--preserve-cache`` must not match \"serve\". Unknown argv gets no- hint rather than a wrong one.- """- lines = [- "✗ Other Hermes processes are running from this install's venv:",- ]- hint_by_subcommand = {- "serve": " ← Hermes backend (if the Desktop app is open, close it)",- "dashboard": " ← hermes dashboard (stop it: hermes dashboard stop, or close that terminal)",- "gateway": " ← gateway",- }- for pid, name, cmdline in matches[:6]:- sub = _hermes_holder_subcommand(cmdline)- hint = hint_by_subcommand.get(sub or "", "")- lines.append(f" PID {pid} {name} {cmdline[:120]}{hint}")- if len(matches) > 6:- lines.append(f" ... and {len(matches) - 6} more")- lines.append("")- lines.append(- " On Windows these keep native extension files (.pyd) locked, so the"- )- lines.append(- " dependency update would fail partway and leave a broken install."- )- lines.append(- " Close the Hermes desktop app / other Hermes terminals, then re-run:"- )- lines.append(" hermes update")- lines.append(" (or use `hermes update --force-venv` to proceed anyway at your own risk)")- return "\n".join(lines)--def _venv_launcher_ancestors(pids: list[int]) -> list[int]:- """Return venv-interpreter ancestors of *pids* that hold the install open.-- On Windows a gateway started through the venv shim is a **two-process- chain**: ``venv\\Scripts\\python.exe`` (the launcher, which keeps native- ``.pyd`` files from the venv mapped) spawns the actual interpreter from- uv's managed CPython directory (``AppData\\Roaming\\uv\\python\\...``).- The gateway writes its PID file from the *child*, so- ``find_gateway_pids()`` — and therefore this module's pause set — only- ever sees the uv-side worker.-- ``_detect_venv_python_processes()`` matches on the venv path prefix, so- the guard downstream of the pause sees the *launcher* instead. The two- sets are disjoint, which meant a paused gateway still tripped the- venv-holder guard and aborted the update every time (the Desktop- "venv-blocked: N process(es) hold the install" dead-end, where the- reported holder is a gateway the updater believes it already stopped).-- Walking one hop up from each mapped gateway PID and keeping ancestors- that live under the project venv closes the gap. Only the venv-side- parent is returned — unrelated ancestors (the Scheduled Task's- ``cmd.exe``, an operator's shell) are ignored so we never widen the- blast radius beyond the gateway's own launcher. Never raises.- """- if not _m()._is_windows() or not pids:- return []- try:- import psutil- except Exception:- return []-- venv_dir = _m().PROJECT_ROOT / "venv"- try:- venv_prefix = str(venv_dir.resolve()).lower().rstrip(os.sep) + os.sep- except OSError:- venv_prefix = str(venv_dir).lower().rstrip(os.sep) + os.sep-- # Never return ourselves or our own ancestry: a CLI ``hermes update``- # runs from the venv python and would otherwise nominate itself.- # Same #87594 carve-out as _detect_venv_python_processes: a GATEWAY- # ancestor is not "our own ancestry" in the interactive sense — it is- # the process the pause machinery must see (the /update-from-gateway- # topology makes the updater the gateway's child).- try:- from gateway.status import looks_like_gateway_command_line as _is_gw- except Exception:- _is_gw = None- skip: set[int] = {os.getpid()}- try:- for anc in psutil.Process().parents():- try:- anc_cmdline = " ".join(anc.cmdline() or [])- except Exception:- anc_cmdline = ""- if _is_gw is not None and anc_cmdline and _is_gw(anc_cmdline):- continue- skip.add(int(anc.pid))- except Exception:- pass-- found: list[int] = []- for pid in pids:- try:- parent = psutil.Process(int(pid)).parent()- except Exception:- continue- if parent is None:- continue- ppid = int(parent.pid)- if ppid in skip or ppid in found or ppid in set(pids):- continue- try:- exe = (parent.exe() or "").lower()- except Exception:- continue- if exe.startswith(venv_prefix):- found.append(ppid)- return found---def _leftover_pausable_gateway_pids(- matches: list[tuple[int, str, str]],-) -> list[int] | None:- """PIDs from *matches* when every remaining venv holder is a pausable gateway.-- ``_pause_windows_gateways_for_update()`` stops every gateway its discovery- finds, but the venv-holder guard downstream sees the process table as it- is *now*: a gateway respawned by its supervisor (Scheduled Task, login- watchdog) inside the pause→guard window, or one started through a spawn- path the discovery does not map, still holds venv ``.pyd`` files and- would dead-end the update — an abort pointed at exactly the kind of- process the pause machinery exists to stop.-- Holders are classified with the same matcher the Desktop preflight uses- to exempt them (``_is_pausable_gateway``), so the preflight's exemption- and this guard's tolerance cannot drift apart — matcher drift between- two views of the same process table is what produced the launcher/worker- dead-end fixed above. The scan captures only a 120-char cmdline prefix,- so the live argv is re-read where psutil allows; an unreadable argv- falls back to the captured prefix.-- Returns ``None`` when any holder is not a pausable gateway — an operator- REPL, a stray script, or the Desktop backend has no pause machinery- downstream, and the guard must keep refusing exactly as before.- """- from hermes_cli._scan_venv_blockers import _is_pausable_gateway-- try:- import psutil # type: ignore- except Exception:- psutil = None-- pids: list[int] = []- for pid, _name, cmdline in matches:- argv = cmdline- if psutil is not None:- try:- argv = " ".join(psutil.Process(int(pid)).cmdline()) or cmdline- except Exception:- pass- if not _is_pausable_gateway(argv):- return None- pids.append(int(pid))- return pids---def _refuse_gateway_ancestor_tree_kill(- pids: list[int], *, gateway_mode: bool-) -> bool:- """Refuse a plain Windows update that would kill its own process tree.-- A chat agent can launch plain ``hermes update`` through its terminal tool.- In that topology the updater is a child of the gateway. The leftover- holder recovery below uses ``taskkill /T /F`` on Windows, so force-stopping- that gateway also kills the updater before it can mutate the checkout- (#98814).-- ``/update`` uses the supported ``--gateway`` hand-off and is deliberately- exempt: it detaches the updater and provides file-based progress/result- delivery. For every other invocation, refuse only when a nominated- gateway is positively identified as this process's ancestor. If ancestry- cannot be established, preserve the existing holder recovery behavior.- """- if gateway_mode or not pids:- return False-- try:- from hermes_cli.gateway import _is_pid_ancestor_of_current_process-- ancestors = [- int(pid)- for pid in pids- if _is_pid_ancestor_of_current_process(int(pid))- ]- except Exception as exc:- logger.debug("Could not inspect gateway ancestry before tree-kill: %s", exc)- return False-- if not ancestors:- return False-- rendered = ", ".join(str(pid) for pid in ancestors)- print(- "✗ Refusing to stop the gateway process tree because this updater "- f"is running inside it (gateway PID(s): {rendered})."- )- print(- " On Windows, taskkill /T would terminate the updater before the "- "update can run."- )- print(" From a chat platform, use `/update` instead.")- print(" Otherwise, run `hermes update` from a separate terminal.")- return True---def _ledger_manual_serve_holders(- matches: list[tuple[int, str, str]],-) -> list[dict]:- """Ledger entries for venv holders that are MANUAL serve/dashboard backends.-- Positive identity only (#63206): the process self-registered in the spawn- ledger with purpose serve/dashboard, its (pid, create_time) still matches- a live process, and its recorded spawner is NOT alive (a Desktop-owned- backend keeps its live Electron spawner and must keep the refusal — the- app would respawn what we kill; a PowerShell-launched serve has no live- Hermes spawner). Returns the full ledger entries so the relauncher can- rebuild the launch command from structured host/port/profile instead of- parsing argv.- """- try:- from hermes_cli.process_identity import ledger_entries, spawner_is_dead- except Exception:- return []- holder_pids = {int(pid) for pid, _name, _cmd in matches}- out: list[dict] = []- for entry in ledger_entries():- if entry.get("purpose") not in ("serve", "dashboard"):- continue- pid = entry.get("pid")- if not isinstance(pid, int) or pid not in holder_pids:- continue- if spawner_is_dead(entry) is False:- continue # live Desktop supervisor owns it — keep refusing- out.append(entry)- return out---def _serve_relaunch_commands(entries: list[dict]) -> list[list[str]]:- """Rebuild launch commands for stopped serves from structured identity.-- Uses the ledger's host/port/profile fields — never argv parsing (a- joined argv string cannot round-trip Windows paths with spaces). Entries- without a recorded port are skipped; the caller prints the manual hint- for those.- """- commands: list[list[str]] = []- hermes = None- try:- scripts_dir = _m()._venv_scripts_dir()- if scripts_dir is not None:- for name in ("hermes.exe", "hermes"):- candidate = scripts_dir / name- if candidate.is_file():- hermes = str(candidate)- break- except Exception:- hermes = None- if hermes is None:- hermes = "hermes"- for entry in entries:- port = entry.get("port")- if not isinstance(port, int) or port <= 0:- continue- cmd = [hermes]- profile = str(entry.get("profile") or "")- if profile and profile != "default":- cmd += ["--profile", profile]- cmd.append(str(entry.get("purpose")))- host = str(entry.get("host") or "")- if host:- cmd += ["--host", host]- cmd += ["--port", str(port)]- commands.append(cmd)- return commands---def _relaunch_stopped_serves(token: dict) -> None:- """Idempotent atexit relaunch of manual serves stopped by the venv guard.-- Mirrors the gateway resume token contract: `pending` flips False on the- first invocation so the explicit call and the atexit registration cannot- double-spawn (#63206).- """- if not token.get("pending"):- return- token["pending"] = False- entries = token.get("entries") or []- if not entries:- return- commands = _serve_relaunch_commands(entries)- skipped = len(entries) - len(commands)- failed: list = []- if commands:- print(" ⟲ Relaunching stopped serve/dashboard backend(s)")- failed = _m()._respawn_dashboard_processes(commands)- if skipped or failed:- print(- " ⚠ Some stopped backends could not be relaunched automatically; "- "restart them manually (hermes serve --host <ip> --port <port>)."- )- try:- from hermes_cli.update_receipt import record_step-- record_step(- "serve_relaunch",- not failed and not skipped,- f"relaunched={len(commands) - len(failed)} failed={len(failed)} skipped={skipped}",- )- except Exception:- pass---def _orphaned_desktop_backend_pids(- matches: list[tuple[int, str, str]],-) -> list[tuple[int, int]] | None:- """PIDs from *matches* when every remaining holder is an ORPHANED backend.-- The venv-holder guard refuses on the Desktop app's ``serve`` backend by- design: while the Desktop is open, killing its backend is futile (the app- supervises and respawns it within seconds), so the user must close the- app. But in the GUI-updater handoff path the Desktop has *already- exited* — by contract it tree-kills its backends and waits for the venv- shim before spawning hermes-setup, and the update-in-progress marker- parks any relaunched Desktop from spawning a fresh backend (#50238). A- ``serve`` backend still holding the venv at that point is a straggler- whose supervisor is gone: SIGTERM raced its spawn, or it belongs to a- crashed window. Nothing will respawn it, and refusing on it dead-ends- the update with "Hermes is still running" while the user stares at zero- open windows (ryanc's 2026-08-09 01:59/02:17 failures).-- A holder qualifies only when BOTH hold:-- - its cmdline is a Hermes backend (``hermes_cli.main`` + ``serve`` /- ``dashboard``), and- - its supervising parent is demonstrably gone: the parent PID no longer- exists, or the PID was reused (parent created *after* the child).-- Tree-aware: the scanner can return an orphaned backend AND one of its- managed-runtime descendants (the ``.hermes-runtime`` interpreter child)- in the same holder set. That descendant has a live parent — the orphaned- backend itself — and isn't a ``serve`` cmdline, so per-process rules- would refuse a set that is entirely safe to reap. Holders that sit- inside an accepted orphan root's tree are therefore folded into that- root (only roots are returned; ``taskkill /T`` reaps the descendants).-- Any other live-parent backend (the Desktop is still open), non-backend- holder outside an orphan tree, or unprovable case disqualifies the whole- set — the guard must keep refusing exactly as before. Returns ``None``- in that case, or when psutil is unavailable (can't prove orphanhood →- refuse). Never raises.- """- try:- import psutil # type: ignore- except Exception:- return None-- def _is_backend(argv_low: str) -> bool:- return "hermes_cli.main" in argv_low and (- " serve" in argv_low or " dashboard" in argv_low- )-- # Pass 1: find orphaned backend ROOTS among the holders.- roots: list[tuple[int, int]] = []- remaining: list[tuple[int, str]] = [] # (pid, argv_low) still to justify- for pid, _name, cmdline in matches:- argv = cmdline- try:- argv = " ".join(psutil.Process(int(pid)).cmdline()) or cmdline- except psutil.NoSuchProcess:- # Holder exited between scan and classification — nothing to- # reap, nothing blocking. Skip it.- continue- except Exception:- pass- low = argv.lower()- if not _is_backend(low):- remaining.append((int(pid), low))- continue- try:- proc = psutil.Process(int(pid))- # Fingerprint from the SAME psutil handle used for classification- # below, quantized to centiseconds — the exact scheme- # gateway.status.get_process_start_time uses on Windows, so the- # value round-trips through pid_is_hermes at kill time. (Reading- # /proc/<pid>/stat here instead would consult the HOST process- # table and use different units.)- process_start_time = int(round(proc.create_time() * 100))- except psutil.NoSuchProcess:- # The candidate itself exited during classification; there is- # nothing left to reap and no identity to pass to taskkill.- continue- except Exception:- return None-- try:- ppid = proc.ppid()- parent = psutil.Process(ppid) if ppid else None- if parent is not None and parent.is_running():- # PID-reuse check: a "parent" created after its child is a- # recycled PID, not the real (dead) supervisor.- if parent.create_time() <= proc.create_time():- # Live parent — NOT a root. But it may still be a- # descendant of an orphan root: the venv python.exe is- # a trampoline that re-execs the uv-managed interpreter- # with the SAME backend argv, so the worker half of the- # two-process chain lands here. Defer to pass 2 instead- # of refusing outright.- remaining.append((int(pid), low))- continue- except psutil.NoSuchProcess:- pass # parent gone → orphan- except Exception:- return None- roots.append((int(pid), process_start_time))-- # Pass 2: every non-backend holder must be a descendant of an accepted- # orphan root — then it dies with the root's tree reap. Anything else- # (operator REPL, stray script) keeps the refusal.- root_set = {pid for pid, _start_time in roots}- for pid, _low in remaining:- if not root_set:- return None- try:- ancestors = {int(a.pid) for a in psutil.Process(pid).parents()}- except psutil.NoSuchProcess:- continue # exited already- except Exception:- return None- if not (ancestors & root_set):- return None- return roots---def _ledger_reapable_backend_pids(- matches: list[tuple[int, str, str]],-) -> list[int]:- """PIDs positively identified by the spawn ledger as orphaned backends.-- The strongest rung: instead of inferring lineage from PPIDs or cmdline- shape, look each venv holder up in the machine spawn ledger- (``hermes_cli.process_identity``). A holder qualifies when ALL of:-- - its ``(pid, create_time)`` matches a live ledger entry (PID reuse- cannot forge this pair);- - the entry's purpose is a reapable backend kind (serve/dashboard/- gateway — never interactive processes);- - the entry's recorded SPAWNER is provably dead (``spawner_is_dead``).-- Unlike the heuristic rungs, this is safe in ANY update context — no- hand-off contract needed — because the ownership claim is explicit: the- process itself declared who supervises it, and that supervisor is gone.- Holders not in the ledger are simply not returned (they fall through to- the later rungs); they never disqualify the identified ones. Never raises.- """- try:- from hermes_cli.process_identity import (- REAPABLE_PURPOSES,- ledger_entries,- spawner_is_dead,- )-- entries = ledger_entries()- except Exception:- return []- by_pid = {e.get("pid"): e for e in entries if isinstance(e.get("pid"), int)}- roots: list[int] = []- for pid, _name, _cmdline in matches:- entry = by_pid.get(int(pid))- if not entry:- continue- if entry.get("purpose") not in REAPABLE_PURPOSES:- continue- if spawner_is_dead(entry) is True:- roots.append(int(pid))- return roots---def _handoff_reapable_backend_pids(- matches: list[tuple[int, str, str]],-) -> list[int] | None:- """PIDs of Hermes ``serve``/``dashboard`` backends safe to reap during a- GUI-updater hand-off, INCLUDING ones with a still-live parent.-- Complements ``_orphaned_desktop_backend_pids``, which only reaps backends- whose supervisor is provably dead. That check returns ``None`` (keep- refusing) the moment ANY holder still has a live parent — which is exactly- the case that produced the field incident this fixes: a Windows Desktop- update hand-off (``update --yes --gateway --force``) left a *swarm* of- per-profile ``serve`` backends (mr-tester, probe-inherit, turqoise, …)- holding ``cryptography\\_rust.pyd``. Several still had a lingering- parent (the tearing-down Electron process, or the two-hop venv- launcher→worker chain mid-exit), so the orphan check disqualified the- WHOLE set and the update dead-ended — the user saw a 12-minute hang, then- force-closed, and the half-done state stranded bot sessions.-- The hand-off is the safe signal: when the update-incomplete marker is- present (the GUI updater claimed it) AND this is a ``--gateway`` hand-off- run AND no live Desktop shim (``hermes.exe``) is open, NOTHING legitimate- is supervising or respawning a ``serve`` backend from this venv — by the- hand-off contract the Desktop tree-kills its backends and parks any- relaunch behind the marker (#50238). Any ``serve`` backend still holding- the venv here is therefore a leak, live parent or not, and reaping its- tree is correct rather than a race.-- Guarded conservatively:-- - Only Hermes backends (``hermes_cli.main`` + ``serve``/``dashboard``)- from THIS install's venv qualify; a non-backend holder (operator REPL,- stray script) disqualifies the whole set → ``None`` (keep refusing), so- we never widen the blast radius during a hand-off.- - Only runs when the CALLER has confirmed the hand-off context- (``args.gateway`` AND a claimed update-incomplete marker AND no live- ``hermes.exe`` shim) — outside that gate this function is never called- and the stricter orphan-only path stands.- - psutil unavailable → ``None`` (can't re-read argv to classify → refuse).-- Returns the backend root PIDs to tree-reap, or ``None`` to leave the- decision to the caller's existing rungs. Never raises.- """- try:- import psutil # type: ignore- except Exception:- return None-- def _is_backend(argv_low: str) -> bool:- return "hermes_cli.main" in argv_low and (- " serve" in argv_low or " dashboard" in argv_low- )-- roots: list[int] = []- for pid, _name, cmdline in matches:- argv = cmdline- try:- argv = " ".join(psutil.Process(int(pid)).cmdline()) or cmdline- except psutil.NoSuchProcess:- # Exited between scan and classification — nothing to reap.- continue- except Exception:- pass- if not _is_backend(argv.lower()):- # A non-backend holder during a hand-off is unexpected; refuse the- # whole set rather than reap something we cannot justify.- return None- roots.append(int(pid))-- return roots or None---def _stop_process_trees(- pids: list[int] | list[tuple[int, int]],-) -> None:- """Force-stop each PID with its full child tree (Windows).-- ``taskkill /T /F`` mirrors the Desktop's ``forceKillProcessTree`` and- install.ps1's venv sweep: stopping only the parent can leave a managed- ``.hermes-runtime`` interpreter child alive and holding the install open- (#70026). Best effort; never raises.- """- from gateway.status import get_process_start_time- from hermes_cli._subprocess_compat import pid_is_hermes, windows_hide_flags-- for entry in pids:- if isinstance(entry, tuple):- pid, expected_start_time = entry- else:- pid = int(entry)- expected_start_time = get_process_start_time(pid)- try:- if expected_start_time is None:- logger.debug(- "Skipping taskkill of PID %s: process identity unavailable",- pid,- )- continue- if not pid_is_hermes(- pid,- expected_start_time=expected_start_time,- ):- logger.debug(- "Skipping taskkill of non-Hermes or changed PID %s",- pid,- )- continue- subprocess.run(- ["taskkill", "/PID", str(pid), "/T", "/F"],- check=False,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- stdin=subprocess.DEVNULL,- creationflags=windows_hide_flags(),- )- except Exception as exc:- logger.debug("Could not stop process tree %s: %s", pid, exc)---def _looks_like_desktop_control_plane(cmdline: str) -> bool:- """True for this-install ``hermes serve`` / ``hermes dashboard`` argv.-- That is the Desktop control plane, not the messaging gateway. Serve and- dashboard do not host platform adapters (#92091); do not feed this into- ``looks_like_gateway_command_line``.-- Token-based via the parser-derived subcommand classifier — never- substring (#90778/#91869: ``kanban --preserve-cache`` contains "serve",- ``-m dashboard chat`` contains " dashboard"; both are NOT control- planes). A cmdline whose subcommand cannot be determined is NOT a- control plane — callers must not guess ownership.- """- if "hermes_cli.main" not in (cmdline or "").lower():- return False- return _hermes_holder_subcommand(cmdline) in ("serve", "dashboard")---def _desktop_owns_gateway_lifecycle() -> bool:- """True when Desktop currently supervises this install's control plane.-- The updater must not steal gateway start in that case: Desktop owns- start/stop via ``/api/gateway/*``. This is *not* proof messaging is- already served — a live serve process is the control plane, and the- gateway is a detached sibling (#76129 / #92091).-- Prefer the spawn ledger (owned identity). Fall back to the install-scoped- venv-holder scan already used by the lock guard; an orphaned control-plane- process (supervisor gone) does not count.- """- try:- from hermes_cli.process_identity import ledger_entries, spawner_is_dead-- for entry in ledger_entries():- if entry.get("purpose") not in ("serve", "dashboard"):- continue- if spawner_is_dead(entry) is False:- return True- except Exception as exc:- logger.debug("Desktop-lifecycle ledger probe failed: %s", exc)-- try:- import psutil- except Exception:- psutil = None-- try:- holders = _m()._detect_venv_python_processes()- except Exception as exc:- logger.debug("Desktop-lifecycle holder scan failed: %s", exc)- return False-- for pid, _name, cmdline in holders:- if not _looks_like_desktop_control_plane(cmdline):- continue- if psutil is None:- # Cannot prove orphanhood; a live this-install control plane is- # enough to refuse stealing gateway start.- return True- try:- proc = psutil.Process(int(pid))- parent = proc.parent()- if parent is None or not parent.is_running():- continue- if parent.create_time() > proc.create_time():- continue- return True- except Exception:- continue- return False---def _stop_windows_gateway_service(- name: str,- *,- expected_processes: tuple[tuple[int, float], ...] = (),- expected_service_identity: tuple[int, float] | None = None,- expected_gateway_identity: tuple[int, float] | None = None,- timeout: float = 30.0,-) -> None:- """Stop one verified Windows service and wait until SCM reports it down."""- import psutil # noqa: PLC0415-- service = psutil.win_service_get(name)- if expected_service_identity is not None:- try:- current_status = str(service.status())- current_service_pid = int(service.pid() or 0)- except Exception as exc:- raise RuntimeError(- f"Windows service {name} SCM identity is unavailable before stop"- ) from exc- if current_status != "running":- raise RuntimeError(- f"Windows service {name} is not stably running before stop: {current_status}"- )- if current_service_pid != int(expected_service_identity[0]):- raise RuntimeError(- f"Windows service {name} SCM process identity changed before stop"- )- for label, identity in (- ("service", expected_service_identity),- ("gateway", expected_gateway_identity),- ):- if identity is None:- continue- pid, create_time = identity- try:- current = float(psutil.Process(int(pid)).create_time())- except Exception as exc:- raise RuntimeError(- f"Windows {label} process identity is unavailable before stop"- ) from exc- if abs(current - float(create_time)) > 0.001:- raise RuntimeError(- f"Windows {label} process identity changed before stop"- )- if expected_service_identity is not None and expected_gateway_identity is not None:- service_pid = int(expected_service_identity[0])- gateway_pid = int(expected_gateway_identity[0])- try:- ancestor_pids = {- int(parent.pid) for parent in psutil.Process(gateway_pid).parents()- }- except Exception as exc:- raise RuntimeError(- "Windows gateway ancestry is unavailable before service stop"- ) from exc- if service_pid not in ancestor_pids:- raise RuntimeError(- f"Windows gateway is no longer owned by service {name}"- )- result = subprocess.run(- ["sc.exe", "stop", name],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=10,- check=False,- )- if result.returncode != 0 and service.status() != "stopped":- detail = (result.stderr or result.stdout).strip()- raise RuntimeError(detail or f"sc.exe stop failed with {result.returncode}")-- def _original_process_is_alive(pid: int, create_time: float) -> bool:- try:- current = float(psutil.Process(pid).create_time())- except (psutil.NoSuchProcess, psutil.ZombieProcess):- # A vanished process is clear.- return False- except Exception:- # AccessDenied or any unknown probe failure stays fail-closed- # because the venv may still be locked.- return True- return abs(current - create_time) <= 0.001-- alive = [- pid- for pid, create_time in expected_processes- if _original_process_is_alive(pid, create_time)- ]- deadline = _time.monotonic() + timeout- while _time.monotonic() < deadline:- service_stopped = service.status() == "stopped"- alive = [- pid- for pid, create_time in expected_processes- if _original_process_is_alive(pid, create_time)- ]- if service_stopped and not alive:- return- _time.sleep(0.2)- if service.status() == "stopped":- # We only return if the original processes have also exited their identity.- # A lingering process with a matching creation time means the venv mutation- # must not proceed — fail closed.- alive_after_stop = [- pid- for pid, create_time in expected_processes- if _original_process_is_alive(pid, create_time)- ]- if alive_after_stop:- raise RuntimeError(- f"Windows service {name} stopped but its process tree is still alive: "- f"{alive_after_stop}"- )- return- # If we reach here, the timeout elapsed without the service reaching a stable stopped state- # while its original descendants are still alive. Fail closed — venv mutation is unsafe.- raise RuntimeError(- f"Windows service {name} did not stop within {timeout:.0f}s; venv mutation unsafe."- )---def _start_windows_gateway_service(name: str, *, timeout: float = 30.0) -> None:- """Start one previously paused Windows service and verify it is running."""- import psutil # noqa: PLC0415-- service = psutil.win_service_get(name)- result = subprocess.run(- ["sc.exe", "start", name],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=10,- check=False,- )- if result.returncode != 0 and service.status() != "running":- detail = (result.stderr or result.stdout).strip()- raise RuntimeError(detail or f"sc.exe start failed with {result.returncode}")- deadline = _time.monotonic() + timeout- while _time.monotonic() < deadline:- if service.status() == "running":- return- _time.sleep(0.2)- raise RuntimeError(f"Windows service {name} did not start within {timeout:.0f}s")---def _restore_windows_gateway_service(name: str, *, timeout: float = 60.0) -> None:- """Restore a service after an uncertain stop, including STOP_PENDING."""- import psutil # noqa: PLC0415-- service = psutil.win_service_get(name)- deadline = _time.monotonic() + timeout- while _time.monotonic() < deadline:- status = service.status()- if status == "running":- return- if status == "stopped":- _start_windows_gateway_service(name)- return- _time.sleep(0.2)- raise RuntimeError(- f"Windows service {name} did not reach a restorable state within {timeout:.0f}s"- )---def _pause_windows_gateways_for_update() -> dict | None:- """Stop running Windows gateways before mutating the checkout or venv.-- Windows scheduled/startup gateways run through pythonw.exe, so the generic- hermes.exe concurrent-instance guard does not see them. They still import- from the checkout and can keep files locked while ``git`` or ``uv`` updates- the install. Stop only PIDs that the gateway discovery code identifies.- """- if not _m()._is_windows():- return None-- try:- from gateway.status import get_process_start_time, terminate_pid- from hermes_cli.gateway import (- _capture_gateway_argv,- _get_restart_drain_timeout,- find_gateway_pids,- find_profile_gateway_processes,- find_windows_gateway_services,- )- except Exception as exc:- raise RuntimeError(- f"Could not prepare Windows gateway pause for update: {exc}"- ) from exc-- try:- profile_process_list = find_profile_gateway_processes(strict=True)- profile_processes = {proc.pid: proc for proc in profile_process_list}- except Exception as exc:- raise RuntimeError(- f"Could not map Windows gateway PIDs to profiles: {exc}"- ) from exc-- try:- service_gateways = find_windows_gateway_services(- profile_processes=profile_process_list- )- except Exception as exc:- raise RuntimeError(- f"Could not determine Windows gateway service ownership: {exc}"- ) from exc-- service_gateway_pids = {int(service.gateway_pid) for service in service_gateways}- try:- running_pids = list(- dict.fromkeys(- [- *find_gateway_pids(all_profiles=True),- *sorted(profile_processes),- *sorted(service_gateway_pids),- ]- )- )- except Exception as exc:- raise RuntimeError(- f"Could not discover Windows gateway PIDs before update: {exc}"- ) from exc- if not running_pids:- # No gateway is running right now, but the user may have installed an- # autostart entry (Scheduled Task or Startup-folder login item) — that- # is an explicit "I want a gateway" signal. A gateway that died between- # updates (e.g. the spawning terminal/TUI closed, taking its child with- # it) would otherwise never come back: the autostart entry only fires on- # the next login, and the update flow's resume path only relaunched- # gateways that were running when the update began. Cold-start one after- # the update so an installed gateway is actually up post-update. Users- # who run gateway-less (no autostart entry) get nothing forced on them.- #- # Exception: Desktop currently owns this install's gateway lifecycle- # (live supervised serve/dashboard). A vestigial Startup/Scheduled- # Task is not the owner — spawning ``gateway run`` beside Desktop- # races ports/state (#76129). Serve is the control plane, not proof- # messaging is served; the skip is ownership, not liveness (#92091).- try:- if _desktop_owns_gateway_lifecycle():- logger.debug(- "Skipping Windows gateway cold-start plan: "- "Desktop owns gateway lifecycle"- )- return None- except Exception as exc:- logger.debug(- "Could not check Desktop gateway-lifecycle ownership before update: %s",- exc,- )- try:- from hermes_cli import gateway_windows-- if gateway_windows.is_installed():- return {- "resume_needed": True,- "profiles": {},- "unmapped_pids": [],- "unmapped": [],- "cold_start_if_installed": True,- }- except Exception as exc:- logger.debug(- "Could not check Windows gateway autostart state before update: %s",- exc,- )- return None-- profiles: dict[str, int] = {}- mapped_pids = []- socket_acks: list[dict] = []- for pid in running_pids:- if pid in service_gateway_pids:- continue- proc = profile_processes.get(pid)- if proc is None:- continue- profiles[str(proc.profile)] = int(pid)- mapped_pids.append(int(pid))- _write_update_planned_stop_marker(Path(proc.path), int(pid))- # Socket-first pause (#92091 step 2): ask the gateway to drain and- # exit itself instead of relying on the marker poll + force-kill- # ladder. A positive ACK means the gateway is running its own- # graceful restart path (same drain as SIGUSR1/service restarts) and- # will release its venv handles on the way out. No answer (older- # gateway, no socket) → the marker watcher / force-kill fallback- # below behaves exactly as before this verb existed.- try:- from gateway.control_socket import pause_gateway_for_update-- ack = pause_gateway_for_update(Path(proc.path))- if ack and (ack.get("pausing") or ack.get("already_stopping")):- socket_acks.append(ack)- except Exception as exc:- logger.debug(- "Socket pause unavailable for gateway %s: %s", pid, exc- )-- # Resolve each mapped worker's venv-side launcher BEFORE draining: the- # drain stops tracking a PID exactly when it dies, so a gracefully- # drained worker is gone by the time the wait returns — and a dead pid's- # parent cannot be recovered (psutil raises NoSuchProcess). The snapshot- # is stopped after the drain alongside the survivors.- #- # Why launchers matter: the drain targets the PID that wrote the PID- # file (the uv-side worker). On Windows that worker's parent is usually- # the venv-side ``python.exe`` launcher, which keeps venv ``.pyd`` files- # mapped and is what ``_detect_venv_python_processes()`` reports- # downstream. Left alive, it trips the venv-holder guard and aborts the- # update even though the gateway itself is stopped.- launcher_pids = _m()._venv_launcher_ancestors(mapped_pids)-- print("→ Stopping Windows gateway process(es) before updating Hermes...")- try:- drain_timeout = max(float(_get_restart_drain_timeout()), 1.0)- except Exception:- drain_timeout = 10.0- if socket_acks:- # A socket-paused gateway drains its ACTIVE TURN before exiting; give- # it the budget it declared (plus teardown grace) rather than only- # the local default, so a mid-turn gateway isn't force-killed at the- # end of a too-short wait — the exact outcome the verb exists to- # prevent.- try:- declared = max(- float(a.get("drain_timeout") or 0.0) for a in socket_acks- )- drain_timeout = max(drain_timeout, declared + 10.0)- except Exception:- pass- print(- f" → {len(socket_acks)} gateway(s) ACKed socket pause; "- f"waiting up to {int(drain_timeout)}s for graceful exit"- )- survivors = _m()._wait_for_windows_update_gateway_exit(- mapped_pids,- timeout=drain_timeout,- )- unmapped_pids = [- pid- for pid in running_pids- if pid not in profile_processes and pid not in service_gateway_pids- ]-- # Snapshot each unmapped gateway's command line *before* we force-kill it,- # so ``_resume_windows_gateways_after_update`` can respawn it by replaying- # its own argv. Unmapped gateways are ones with no profile→PID-file mapping- # — e.g. a Windows Scheduled Task running ``pythonw.exe -m hermes_cli.main- # gateway run``. Without this snapshot they were force-killed and never- # restarted (the "Restart manually after update" dead-end from #50090).- unmapped: list[dict] = []- for pid in unmapped_pids:- argv = None- try:- argv = _capture_gateway_argv(int(pid))- except Exception as exc:- logger.debug("Could not capture argv for unmapped gateway %s: %s", pid, exc)- unmapped.append({"pid": int(pid), "argv": argv})-- # Stop drain survivors, unmapped gateways, and the pre-drain launcher- # snapshot. ``terminate_pid(force=True)`` is a tree kill, so a launcher- # that outlived its worker takes any stragglers with it; a launcher that- # already exited with its drained worker raises ProcessLookupError below- # and is skipped.- force_killed = []- for pid in sorted(set(survivors).union(unmapped_pids).union(launcher_pids)):- try:- pid_int = int(pid)- terminate_pid(- pid_int,- force=True,- expected_start_time=get_process_start_time(pid_int),- )- force_killed.append(pid_int)- except (ProcessLookupError, PermissionError, OSError):- pass-- if profiles:- print(f" ✓ Paused gateway profile(s): {', '.join(sorted(profiles))}")- if force_killed:- print(f" → Force-stopped {len(force_killed)} gateway process(es)")-- if unmapped_pids:- respawnable = sum(1 for u in unmapped if u.get("argv"))- print(- f" → Stopped {len(unmapped_pids)} gateway process(es) without profile mapping"- )- if respawnable < len(unmapped_pids):- # Some had no recoverable command line (psutil missing, access- # denied, already gone): those still need a manual restart.- print(" Restart manually after update: hermes gateway run")-- token = {- "resume_needed": True,- "profiles": profiles,- "unmapped_pids": unmapped_pids,- "unmapped": unmapped,- }-- # Stop SCM-supervised gateways only after every fallible preparation step- # for ordinary gateways is complete. From this point to return, any error- # restores both the attempted services and the already-paused ordinary- # gateways before aborting the update.- paused_services = []- current_service_name = None- try:- for service in service_gateways:- current_service_name = str(service.name)- _stop_windows_gateway_service(- current_service_name,- expected_processes=tuple(- getattr(service, "descendant_identities", ())- ),- expected_service_identity=(- int(service.service_pid),- float(service.service_create_time),- ),- expected_gateway_identity=(- int(service.gateway_pid),- float(service.gateway_create_time),- ),- )- paused_services.append(current_service_name)- current_service_name = None- if paused_services:- token["services"] = paused_services- token["expected_services"] = list(paused_services)- token["restarted_services"] = []- token["service_profiles"] = {- str(service.name): str(service.profile)- for service in service_gateways- if str(service.name) in paused_services- }- print(- " ✓ Paused Windows gateway service(s): "- + ", ".join(paused_services)- )- return token- except Exception as exc:- restore_names = []- if current_service_name:- restore_names.append(current_service_name)- restore_names.extend(reversed(paused_services))- rollback_failures = []- for service_name in dict.fromkeys(restore_names):- try:- _restore_windows_gateway_service(service_name)- except Exception as restore_exc:- rollback_failures.append(f"{service_name}: {restore_exc}")- if profiles or unmapped:- try:- _resume_windows_gateways_after_update(token)- except Exception as restore_exc:- rollback_failures.append(f"ordinary gateways: {restore_exc}")- failed_service = current_service_name or "unknown"- detail = f"Could not stop Windows gateway service {failed_service}: {exc}"- if rollback_failures:- detail += "; rollback failures: " + "; ".join(rollback_failures)- raise RuntimeError(detail) from exc---def _cold_start_windows_gateway_after_update() -> bool:- """Start a fresh detached gateway after update when one is installed but down.-- Invoked from ``_resume_windows_gateways_after_update`` for the- ``cold_start_if_installed`` case: no gateway was running when the update- began, but an autostart entry (Scheduled Task / Startup-folder login item)- is installed, signalling the user wants a gateway. Unlike the relaunch- paths — which watch an old PID and respawn once it exits — this is a direct- fresh spawn via the same hidden-console + breakaway path that- ``hermes gateway start`` uses (``gateway_windows._spawn_detached``).-- Best-effort and idempotent: re-checks that nothing is running first so a- concurrent start (e.g. the autostart entry firing) can't produce a- duplicate gateway.-- A successful ``Popen`` only proves the process was created, not that it- survived (e.g. a Windows job object denying breakaway kills it before it- logs anything — #84185). So the success line is gated on the same- post-spawn liveness poll every other ``_spawn_detached`` caller uses- (``gateway_windows._report_gateway_start``), instead of being printed- unconditionally from the returned PID.- """- if not _m()._is_windows():- return True- try:- from hermes_cli import gateway_windows- from hermes_cli.gateway import find_gateway_pids- except Exception as exc:- raise RuntimeError(- f"Could not load Windows gateway cold-start helpers: {exc}"- ) from exc-- # Re-check liveness right before spawning — between pause and resume the- # autostart entry may have already brought a gateway up, or a leftover- # process may have re-registered. Don't double-start.- try:- if list(find_gateway_pids(all_profiles=True)):- return True- except Exception as exc:- raise RuntimeError(- f"Could not re-check gateway liveness before cold-start: {exc}"- ) from exc-- try:- if _desktop_owns_gateway_lifecycle():- logger.debug(- "Skipping Windows gateway cold-start: Desktop owns gateway lifecycle"- )- return True- except Exception as exc:- raise RuntimeError(- "Could not re-check Desktop gateway-lifecycle ownership before cold-start: "- f"{exc}"- ) from exc-- try:- pid = gateway_windows._spawn_detached()- except Exception as exc:- raise RuntimeError(f"Could not cold-start Windows gateway after update: {exc}") from exc-- if not pid:- raise RuntimeError("Windows gateway cold-start did not return a process ID")- ready_pids = gateway_windows._wait_for_gateway_ready()- if not ready_pids:- raise RuntimeError(- f"Windows gateway cold-start PID {pid} did not become ready"- )- print()- print(- "✓ Gateway started via cold-start after update "- f"(PID: {', '.join(map(str, ready_pids))})"- )- # Persist the PIDs this ✓ vouched for so a death AFTER the updater exits- # (parent Job Object teardown, #91675) is reported by the next CLI- # invocation instead of staying silent. Best-effort.- try:- gateway_windows._write_start_attestation(- ready_pids, "cold-start after update"- )- except Exception:- pass- return True---def _for_each_systemd_gateway_unit(- list_units_stdout: str,- *,- process_unit,- on_unit_timeout,-) -> None:- """Process each ``hermes-gateway*.service``/``hermes-serve*.service`` unit- from ``systemctl list-units``.-- ``subprocess.TimeoutExpired`` raised by ``process_unit`` is isolated to- that unit via ``on_unit_timeout`` so one wedged systemctl call cannot- abort the rest of the fleet (#68523).- """- for line in (list_units_stdout or "").strip().splitlines():- parts = line.split()- if not parts:- continue- unit = parts[0]- if not unit.endswith(".service"):- continue- # list-units is already pattern-filtered, but keep the name gate so a- # stray non-gateway/serve line cannot enter the restart path.- # ``unit.startswith("hermes-serve")`` alone would also accept the- # unrelated ``hermes-server.service`` — require the exact base unit- # or the hyphenated profile family instead (review on #83595).- if not (- unit == "hermes-gateway.service"- or unit.startswith("hermes-gateway-")- or unit == "hermes-serve.service"- or unit.startswith("hermes-serve-")- ):- continue- svc_name = unit.removesuffix(".service")- try:- process_unit(svc_name)- except subprocess.TimeoutExpired as exc:- on_unit_timeout(svc_name, exc)--def _service_unit_supports_graceful_sigusr1_restart(svc_name: str) -> bool:- """Whether *svc_name* wires SIGUSR1 to a graceful drain-then-restart.-- Only ``hermes-gateway*`` units run ``gateway/run.py``, which installs the- SIGUSR1 handler. ``hermes-serve*`` units (#83438) don't, so sending them- SIGUSR1 would just invoke the default terminate action and burn the full- drain budget waiting for an exit that was never graceful — go straight to- the blunt ``systemctl restart`` path for those instead.-- Uses the same strict exact/hyphenated shape as the unit-name gate in- ``_for_each_systemd_gateway_unit`` so a hypothetical near-prefix unit- (``hermes-gateway-helper`` is fine — profile units are- ``hermes-gateway-<profile>`` — but ``hermes-gatewayd``-style names are- not) can't be sent a SIGUSR1 it doesn't handle.- """- return svc_name == "hermes-gateway" or svc_name.startswith("hermes-gateway-")---def _warn_incomplete_gateway_fleet_restart(failed_units: list) -> None:- """Print an explicit incomplete-update warning for unrestarted units."""- from hermes_cli.gateway import is_macos-- if not failed_units:- return- # Preserve discovery order while de-duplicating.- seen = set()- ordered = []- for name in failed_units:- if name in seen:- continue- seen.add(name)- ordered.append(name)- print()- print("⚠ Update incomplete — some units were not restarted:")- for name in ordered:- print(f" - {name}")- if is_macos():- # A launchd label reaches this list when launchd was not supervising a- # live process after the restart (#88848), so the unit is not merely- # stale — it is very likely deregistered, and `launchctl kickstart`- # cannot revive a job launchd no longer knows about.- print(" Listed services may be deregistered from launchd, or still")- print(" running pre-update code (mixed sys.modules). Recover with:")- print(" hermes gateway status")- print(" launchctl list | grep <label>")- print(" launchctl bootstrap gui/$(id -u) "- "~/Library/LaunchAgents/<label>.plist")- return- print(" Skipped units may still be running pre-update code (mixed")- print(" sys.modules). Restart them manually, then verify:")- print(" hermes gateway status")- if any(not name.startswith("ai.hermes.") for name in ordered):- print(" systemctl --user restart <unit> # user-scope")- print(" sudo systemctl restart <unit> # system-scope")- if any(name.startswith("ai.hermes.") for name in ordered):- print(" launchctl kickstart -k gui/$UID/<label> # macOS (or user/$UID)")---def _restart_launchd_gateway_after_update(- *, supervision_verify: bool = True-) -> tuple[list, list]:- """Restart the invoking profile's launchd gateway after an update.-- #74973 (salvage #75021 by @jeff-mettel): the restart used to be gated on- ``launchctl list <label>`` exiting 0. A *booted-out* job — plist present,- definition deregistered from launchd (crashed helper, manual bootout,- failed prior update) — fails that check, so the whole branch silently- skipped: no restart, no message, ``KeepAlive`` unable to revive a- definition launchd no longer knows, and the update still printed- "Update complete!". ``launchctl list`` is also session-scoped and can- exit non-zero while the job is alive in its gui/user domain, so it is- not a reliable classifier at all.-- The fix performs NO list-based classification: when the plist exists,- ``launchd_restart()`` always runs — it drains a live PID, kickstarts- with ``-k``, and owns the bootout/bootstrap/kickstart ladder for the- genuinely unloaded state. Every failure path is loud and names the- manual recovery command.-- Returns ``(restarted_labels, failed_labels)``. With- ``supervision_verify`` (the update path), success additionally requires- launchd reporting a fresh supervised PID (#88848 — "the call returned"- is not "the gateway is supervised").- """- from hermes_cli.gateway import (- get_launchd_label,- get_launchd_plist_path,- launchd_restart,- wait_for_launchd_gateway_supervision,- )-- current_label = get_launchd_label()- try:- if not get_launchd_plist_path().exists():- return [], [] # not a launchd install — nothing to do or warn- try:- launchd_restart()- except subprocess.CalledProcessError as e:- stderr = (getattr(e, "stderr", "") or "").strip()- print(- f" ⚠ Gateway restart failed: {stderr}\n"- " The gateway may be DOWN on pre-update code. "- "Recover manually: hermes gateway restart"- )- return [], [current_label]- except (FileNotFoundError, subprocess.TimeoutExpired) as e:- # A plist exists, so a gateway is SUPPOSED to be supervised here —- # a broken/missing/wedged launchctl is not proof nothing needs- # restarting. The old code `pass`ed here (#74973's second silent- # variant); count it and tell the operator.- print(- " ⚠ Could not restart the gateway "- f"({e.__class__.__name__}: {e}).\n"- " Recover manually: hermes gateway restart"- )- return [], [current_label]-- if not supervision_verify:- return [current_label], []-- # launchd_restart() returning is only "restart REQUESTED" — the- # self-restart branch hands work to the running gateway, a plist reload- # to a detached helper; both asynchronous. A helper that dies before its- # first bootstrap (#88848), or a bootstrap that exits 0 without- # registering (measured on macOS 26.6.1), otherwise reaches "Update- # complete!" with nothing supervising the gateway. Verified- # domain-agnostically (a domain locate fails on macOS-26 hosts whose- # per-user domains reject service management).- if wait_for_launchd_gateway_supervision(label=current_label):- return [current_label], []- print(- f" ✗ {current_label} restarted but launchd is not supervising it.\n"- " Check logs, then: hermes gateway restart"- )- return [], [current_label]---def _restart_macos_launchd_gateways(- restarted_services: list,- failed_or_stale_units: list,- drain_budget: float,-) -> None:- """Restart every launchd-managed gateway after an update (macOS).-- The code update (git pull) is shared across all profiles, so every- ``ai.hermes.gateway*`` LaunchAgent must reload it — restarting only the- invoking profile's service leaves siblings on pre-update ``sys.modules``- until their next agent turn imports a symbol the old module generation- doesn't have (#41403). Parity with the systemd fleet path.-- The invoking profile keeps the existing ``launchd_restart()`` treatment- (self-restart request → graceful drain → kickstart). Siblings get the- same drain-first sequence, with their launchd domain resolved per label:- a sibling bootstrapped in the other supported domain (``gui/<uid>`` vs- ``user/<uid>``) must not be kickstarted in the current profile's domain.- ``subprocess.TimeoutExpired`` is isolated per label so one wedged- launchctl call cannot leave the rest of the fleet on old code (#68523).- """- from hermes_cli.gateway import (- get_launchd_label,- get_launchd_plist_path,- launchd_restart,- launchd_gateway_labels_for_install,- _graceful_restart_via_sigusr1,- _launchd_kickstart,- _launchd_service_registered,- _locate_launchd_gateway_service,- _wait_for_launchd_service_pid,- wait_for_launchd_gateway_supervision,- )-- # --- Current profile: unchanged single-service path ---------------------- _restarted, _failed = _restart_launchd_gateway_after_update(- supervision_verify=True- )- restarted_services.extend(_restarted)- failed_or_stale_units.extend(_failed)- current_label = get_launchd_label()-- # --- Sibling profiles ---------------------------------------------------- for label in launchd_gateway_labels_for_install():- if label == current_label:- continue- try:- # Locate = liveness + domain in one domain-explicit probe; the- # kickstart and fresh-PID verification below reuse the located- # domain, so a sibling in the other gui/user domain can never be- # probed in one domain and restarted in another.- domain, old_pid = _locate_launchd_gateway_service(label)- if domain is None:- # Installed but not bootstrapped (stopped/uninstalled- # mid-way) — nothing is running old code here.- continue- graceful_ok = False- if old_pid is not None and old_pid > 0:- print(f" → {label}: draining (up to {int(drain_budget)}s)...")- graceful_ok = _graceful_restart_via_sigusr1(- old_pid, drain_timeout=drain_budget- )- if graceful_ok and _wait_for_launchd_service_pid(- label, old_pid=old_pid, timeout=10.0, domain=domain- ):- # Unconditional KeepAlive already respawned it on the new- # code — a hard kickstart now would kill the fresh process.- restarted_services.append(label)- continue- try:- _launchd_kickstart(label, domain)- except subprocess.CalledProcessError as e:- stderr = (getattr(e, "stderr", "") or "").strip()- failed_or_stale_units.append(label)- print(- f" ⚠ Failed to restart {label}: {stderr}\n"- f" Recover manually: launchctl kickstart -k {domain}/{label}"- )- continue- if _wait_for_launchd_service_pid(- label, old_pid=old_pid, timeout=15.0, domain=domain- ):- restarted_services.append(label)- else:- failed_or_stale_units.append(label)- print(- f" ✗ {label} failed to come back after restart.\n"- f" Check logs, then: launchctl kickstart -k {domain}/{label}"- )- except subprocess.TimeoutExpired:- failed_or_stale_units.append(label)- print(- f" ⚠ launchctl timed out restarting {label}; "- "continuing with remaining gateways"- )---def _surviving_gateway_pids_after_failed_restart():- """Best-effort PIDs of gateways still running after the restart phase died.-- Returns ``None`` when the answer cannot be determined — most importantly- when ``hermes_cli.gateway`` itself no longer imports, which is one of the- ways the restart phase aborts in the first place (the update replaced the- checkout under a process that already loaded the old modules). ``None`` and- a non-empty list are both treated as "assume stale" by the caller; only a- positive empty result is proof that nothing needs restarting.- """- try:- from hermes_cli.gateway import find_gateway_pids-- return list(find_gateway_pids(all_profiles=True))- except Exception as exc: # pragma: no cover - defensive- logger.debug("Could not probe for surviving gateways after update: %s", exc)- return None---_FRESH_RESTART_SUPERVISORS = frozenset({"systemd", "launchd", "service", "s6"})---def _gateway_service_matches_profile(profile: str, service: object) -> bool:- """Match an exact gateway service/label to a profile.-- Profile names must not be matched as substrings: ``foo`` must not claim- that ``hermes-gateway-foobar.service`` was already restarted. These are- the service/label shapes produced by the existing systemd, launchd, and- s6 lifecycle implementations.- """- name = str(service).removesuffix(".service")- if profile == "default":- return name in {- "hermes-gateway",- "ai.hermes.gateway",- "gateway",- "gateway-default",- }- return name in {- f"hermes-gateway-{profile}",- f"ai.hermes.gateway-{profile}",- f"gateway-{profile}",- }---# Abort recovery lives in its own bounded module (review on #96235). Re-exported-# here because `hermes_cli.main` and the update flow below address these names-# through `update_cmd`.-from hermes_cli.update_abort_recovery import ( # noqa: E402- _abort_recovery_is_complete,- _qualified_serve_skips,- _recover_gateway_restart_after_abort,- _serve_unit_recovery_available,- _surviving_pre_update_serve_runtimes,- _warn_stale_serve_runtimes,-)---def _gateway_recovery_partition(- plan, *, skip_profiles: set[str] | None = None-) -> tuple[dict[str, str], list[dict]]:- """Partition pre-update runtimes into fresh-restart candidates and skips.-- The update inventory is captured before the checkout changes. It is the- only safe source here: re-importing ``hermes_cli.gateway`` in the failing- interpreter is exactly what can raise the original ``ImportError``.-- Returns ``(candidates, skipped)`` where ``candidates`` maps profile →- supervisor for supervised gateway runtimes the fresh process may restart,- and ``skipped`` lists every other inventoried runtime the recovery pass- deliberately does NOT touch *through a profile command*, each with an- explicit reason. Nothing from the spawn ledger may vanish silently:- manual gateways have no relaunch authority, and serve/dashboard runtimes- (the ``update_inventory`` serve collector) have no per-profile relaunch- command at all.-- A ``skipped`` serve/dashboard entry is NOT a statement that the runtime is- unrecoverable. The fresh child runs a separate ``hermes-serve*`` systemd- pass that enumerates units from systemd rather than from this inventory,- precisely because the ledger collector cannot classify a systemd-launched- ``hermes serve``: it records no spawner, so it reads as ``manual-serve``.- Whatever that unit pass does not reconcile is caught afterwards by- :func:`_surviving_pre_update_serve_runtimes` (#92145).- """- skip_profiles = skip_profiles or set()- candidates: dict[str, str] = {}- skipped: list[dict] = []- try:- for runtime in getattr(plan, "runtimes", ()) or ():- kind = getattr(runtime, "kind", None)- profile = getattr(runtime, "profile", None)- supervisor = getattr(runtime, "supervisor", None)- if not isinstance(profile, str) or not profile:- continue- if kind == "gateway":- if profile in skip_profiles:- continue- if supervisor in _FRESH_RESTART_SUPERVISORS:- candidates.setdefault(profile, str(supervisor))- else:- skipped.append(- {- "profile": profile,- "kind": "gateway",- "supervisor": str(supervisor),- "reason": (- "manual gateway has no supervisor relaunch"- " authority; left running for explicit operator"- " restart"- ),- }- )- elif kind in ("serve", "dashboard"):- if supervisor == "desktop":- reason = (- "desktop app owns and respawns this serve backend;"- " the recovery pass must not restart it out from under"- " its supervisor"- )- else:- # NOT a claim that no supervisor exists. The ledger- # collector derives serve/dashboard supervisors from- # spawner liveness alone, and a systemd-launched- # `hermes serve` sets neither HERMES_SPAWN nor- # HERMES_PARENT_PID, so it lands here as "manual-serve".- # Unit-backed serve runtimes are recovered by the- # fresh child's systemd pass, which enumerates- # `hermes-serve*` from systemd instead of trusting this- # classification; survivors are reported afterwards by- # _surviving_pre_update_serve_runtimes (#92145).- reason = (- "no per-profile relaunch command reaches a serve/"- "dashboard runtime; recovered by the fresh systemd"- " unit pass when it owns a hermes-serve* unit, else"- " left running for explicit operator restart"- )- skipped.append(- {- "profile": profile,- "kind": str(kind),- "supervisor": str(supervisor),- "reason": reason,- }- )- except Exception as exc:- logger.debug("Could not prepare fresh gateway restart profiles: %s", exc)- return candidates, skipped---def _gateway_restart_recovery_profiles(- plan, *, skip_profiles: set[str] | None = None-) -> list[str]:- """Return supervised gateway profiles that a fresh process may restart."""- candidates, _ = _gateway_recovery_partition(plan, skip_profiles=skip_profiles)- return sorted(candidates)---def _warn_gateway_restart_phase_aborted(exc: BaseException, pids) -> None:- """Print a recovery warning when the whole restart phase raised.-- Issue #78574: the gateway auto-restart phase was wrapped in a blanket- ``except Exception`` that only logged at debug level, so an early failure- (e.g. importing ``hermes_cli.gateway`` from the freshly pulled checkout)- erased every drain/restart line from the update output. The update still- printed "Update complete!" and exited 0 while the running gateway kept- serving pre-update modules against replaced source files — the next turn- died with an ImportError.- """- print()- print(f"⚠ Update incomplete — gateway auto-restart failed: {exc}")- if pids:- listed = ", ".join(str(pid) for pid in pids)- print(f" Gateway process(es) still running pre-update code: {listed}")- else:- print(" Any gateway still running is serving pre-update code")- print(" (mixed sys.modules) against the updated checkout.")- print(" Restart it manually, then verify:")- print(" hermes gateway restart")- print(" hermes gateway status")--def _refresh_windows_gateway_launchers() -> None:- """Regenerate installed Windows gateway launcher scripts after update.-- The Scheduled Task / Startup-folder launchers (``gateway.cmd`` +- ``gateway.vbs``) are persistence artifacts written once at install time —- ``hermes update`` never touched them, so installs created before the- hidden-console rework (aa2ae36c3f) kept launching the gateway through- ``pythonw.exe`` forever: every descendant spawn flashed a conhost- (#54220/#56747) and, since #70344, the console-less gateway died at- startup with ``RuntimeError: sys.stderr is None`` (#71671).-- The task's /TR points at a stable script path, so rewriting the files in- place retargets the task without any schtasks call (no UAC needed).- ``_write_task_script`` is idempotent and renders from current code, so- this is a no-op for modern installs. Best-effort: a failed refresh must- never fail the update.- """- if not _m()._is_windows():- return- try:- from hermes_cli import gateway_windows-- if not gateway_windows.is_installed():- return- gateway_windows._write_task_script()- print(" ✓ Refreshed Windows gateway launcher scripts")- except Exception as exc:- logger.debug("Could not refresh Windows gateway launchers after update: %s", exc)--def _refresh_bootstrap_cache_scripts(branch: str = "main") -> None:- """Sync the installer's bootstrap-cache scripts from the fresh checkout.-- The Desktop GUI updater (``hermes-setup.exe``) executes- ``$HERMES_HOME/bootstrap-cache/install-<ref>.ps1`` (or ``.sh``) for its- repair/bootstrap stages. Installer binaries built before the #67193- cache-refresh fix (June 2026 and earlier) NEVER re-download a cached- branch-ref script — ``install-main.ps1`` cached at install time is- reused forever, executing months-stale code with long-fixed bugs (the- 2026-08-09 incident: a June 4 cached script's venv stage lacked the- #81327 process-tree sweep and died on ``Access denied``). The binary- has no self-update path, so the poisoned cache outlives every- ``hermes update``.-- Overwriting the cached script for *branch* with the freshly pulled- ``scripts/install.ps1`` / ``scripts/install.sh`` on every update turns- the stale binary's unconditional reuse into a feature: it "reuses" a- file this function keeps permanently current. Post-#67193 installers- re-download on each run anyway, so for them this is a harmless- pre-seed of the same bytes.-- Scope guards, mirroring ``install_script.rs``:-- - Only the cache key for the update-target *branch* is rewritten- (``sanitize_ref``: non ``[A-Za-z0-9._-]`` chars become ``_``, so- ``bb/gui`` → ``install-bb_gui.ps1``). Sibling mutable refs cache- DIFFERENT branches' scripts — updating main must not clobber- ``install-bb_gui.ps1`` with main's script.- - Commit-SHA pins are immutable by design and never touched. The- installer's ``is_valid_commit()`` accepts **7–40** hex chars, so an- abbreviated pin like ``install-4ce1994.ps1`` is just as immutable as- a full 40-hex one; the sanitized *branch* is additionally required- to not itself look like a commit pin (defense in depth against a- caller passing a SHA as the branch).-- The .ps1 copy gets a UTF-8 BOM to match the installer's cache format- (#67193 encoding fix). Best-effort: a failed refresh must never fail- the update.- """- try:- import re as _re-- cache_dir = Path(_m().get_hermes_home()) / "bootstrap-cache"- if not cache_dir.is_dir():- return- # Mirror install_script.rs::sanitize_ref().- safe_ref = _re.sub(r"[^A-Za-z0-9._-]", "_", str(branch or "main"))- # Mirror install_script.rs::is_valid_commit(): 7-40 hex chars is an- # immutable commit pin — abbreviated SHAs included. Never rewrite.- if _re.fullmatch(r"[0-9a-fA-F]{7,40}", safe_ref):- return- refreshed = []- for kind, src_name in (("ps1", "install.ps1"), ("sh", "install.sh")):- src = _m().PROJECT_ROOT / "scripts" / src_name- if not src.is_file():- continue- cached = cache_dir / f"install-{safe_ref}.{kind}"- if not cached.is_file():- continue # this ref was never bootstrap-cached — nothing to heal- data = src.read_bytes()- if kind == "ps1" and not data.startswith(b"\xef\xbb\xbf"):- # Match the installer's cache format: PowerShell needs the- # UTF-8 BOM or localized/em-dash text mis-decodes (#67193).- data = b"\xef\xbb\xbf" + data- if cached.read_bytes() == data:- continue # already current- tmp = cached.with_suffix(cached.suffix + ".tmp")- tmp.write_bytes(data)- os.replace(tmp, cached)- refreshed.append(cached.name)- if refreshed:- print(- " ✓ Refreshed installer bootstrap-cache script(s): "- + ", ".join(sorted(refreshed))- )- except Exception as exc:- logger.debug("Could not refresh bootstrap-cache scripts after update: %s", exc)--def _resume_windows_gateways_after_update(token: dict | None) -> None:- """Restart Windows profile gateways previously paused for update."""- if not token or not token.get("resume_needed"):- return- if not _m()._is_windows():- token["resume_needed"] = False- return-- # Regenerate the persisted launcher scripts before respawning anything,- # so a legacy pythonw-era Scheduled Task / Startup entry comes back on- # current hidden-console design at the next login too.- _m()._refresh_windows_gateway_launchers()-- services = list(token.get("services") or [])- token.setdefault("expected_services", list(services))- verified_restarts = list(token.get("restarted_services") or [])- restarted_services = []- failed_services = []- for service_name in services:- try:- _start_windows_gateway_service(str(service_name))- restarted_services.append(str(service_name))- if str(service_name) not in verified_restarts:- verified_restarts.append(str(service_name))- except Exception as exc:- logger.warning(- "Could not restart Windows gateway service %s after update: %s",- service_name,- exc,- )- print(f" ⚠ Could not restart Windows gateway service: {service_name}")- failed_services.append(str(service_name))-- if failed_services:- token["services"] = failed_services- token["restarted_services"] = verified_restarts- raise RuntimeError(- "Could not restart Windows gateway service(s): "- + ", ".join(failed_services)- )- token["services"] = []- token["restarted_services"] = verified_restarts- if restarted_services:- print()- print(- " ✓ Restarted Windows gateway service(s): "- + ", ".join(restarted_services)- )-- profiles = token.get("profiles") or {}- unmapped = token.get("unmapped") or []- cold_start = bool(token.get("cold_start_if_installed"))- if not profiles and not any(u.get("argv") for u in unmapped):- if cold_start:- if not _m()._cold_start_windows_gateway_after_update():- raise RuntimeError("Windows gateway cold-start was not verified")- token["cold_start_if_installed"] = False- token["resume_needed"] = False- return-- try:- from hermes_cli.gateway import (- launch_detached_gateway_restart_by_cmdline,- launch_detached_profile_gateway_restart,- )- except Exception as exc:- raise RuntimeError(- f"Could not load Windows gateway restart helper: {exc}"- ) from exc-- relaunched = []- failed_profiles = {}- for profile, old_pid in sorted(profiles.items()):- try:- if launch_detached_profile_gateway_restart(str(profile), int(old_pid)):- relaunched.append(str(profile))- else:- failed_profiles[str(profile)] = int(old_pid)- except Exception as exc:- logger.debug(- "Could not restart Windows gateway profile %s after update: %s",- profile,- exc,- )- failed_profiles[str(profile)] = int(old_pid)-- # Surface the outcome on the token (#91277 Phase 2 plan-vs-execution- # reconciliation): the git-based update path's fleet reconciliation- # cross-checks every planned runtime against restarted_services /- # relaunched_profiles / externally_supervised_profiles / killed_pids —- # bookkeeping this Windows-specific pause/resume never fed, so a- # correctly-paused-and-relaunched Windows gateway was reported- # "unaccounted" (loud warning + exit 1) even though the restart- # succeeded. The caller merges this into the shared- # relaunched_profiles list before reconciliation runs. A profile whose- # relaunch genuinely failed is deliberately left off this list — it- # must still surface as unaccounted so the user is told to restart it- # manually (Windows has no watcher to recover a failed relaunch).- token["relaunched_profiles"] = relaunched-- # Respawn unmapped gateways (no profile→PID-file mapping, e.g. a Scheduled- # Task) by replaying the argv we snapshotted before force-killing them.- unmapped_relaunched = 0- failed_unmapped = []- for entry in unmapped:- argv = entry.get("argv")- old_pid = entry.get("pid")- if not argv or not old_pid:- failed_unmapped.append(entry)- continue- try:- if launch_detached_gateway_restart_by_cmdline(int(old_pid), list(argv)):- unmapped_relaunched += 1- else:- failed_unmapped.append(entry)- except Exception as exc:- logger.debug(- "Could not restart unmapped Windows gateway (pid %s) after update: %s",- old_pid,- exc,- )- failed_unmapped.append(entry)-- token["profiles"] = failed_profiles- token["unmapped"] = failed_unmapped- if failed_profiles or failed_unmapped:- raise RuntimeError("Could not restart every paused Windows gateway")-- # A truthy return from the launch helpers only proves the detached- # watcher process was created — not that the gateway it respawns- # survived. A parent Job Object that denies CREATE_BREAKAWAY_FROM_JOB- # kills the freshly respawned gateway on updater teardown before it- # writes a single log line, yet "✓ Restarting" was printed anyway- # (#48820, 3rd/4th repro). Verify a stable gateway process actually- # exists before vouching for the resume, using the same- # provisional-hit + confirmation-window poll every other spawn path- # uses (#91675). all_profiles=True because the resume covers the fleet.- if relaunched or unmapped_relaunched:- try:- from hermes_cli import gateway_windows- except Exception as exc:- raise RuntimeError(- f"Could not load Windows gateway liveness helpers: {exc}"- ) from exc- ready_pids = gateway_windows._wait_for_gateway_ready(- timeout_s=30.0, all_profiles=True- )- if not ready_pids:- token["profiles"] = dict(profiles)- token["unmapped"] = list(unmapped)- print()- print(- " ⚠ Windows gateway restart could not be verified — no stable "- "gateway process appeared after relaunch."- )- print(- " (The respawned gateway may have been killed by a parent "- "Job Object during updater teardown, #48820.)"- )- print(" Recover with: hermes gateway restart")- raise RuntimeError(- "Windows gateway relaunch after update was not verified alive"- )- # Persist the PIDs this ✓ vouches for so a death AFTER the updater- # exits (parent Job Object teardown, #91675) is reported by the next- # CLI invocation instead of staying silent. Best-effort.- try:- gateway_windows._write_start_attestation(- ready_pids, "post-update relaunch"- )- except Exception:- pass-- token["resume_needed"] = False-- if relaunched:- print()- print(f" ✓ Restarting Windows gateway profile(s): {', '.join(relaunched)}")- if unmapped_relaunched:- if not relaunched:- print()- print(- f" ✓ Restarting {unmapped_relaunched} unmapped Windows gateway process(es)"- )--def _git_is_trampoline(git_cmd: list) -> bool:- """Whether *git_cmd* resolves to a Git-for-Windows trampoline launcher.-- Git for Windows ships two ~46KB shims (``bin\\git.exe``, ``cmd\\git.exe``)- that re-exec the real ``mingw64\\libexec\\git-core\\git.exe``. When the- shim's re-exec target is missing or PATH resolves to the shim in a- context where it cannot find git-core, every git call dies with the- launcher's own guard message instead of running — a broken PATH entry,- not a network or filesystem problem (#87876). Never raises; unknown- states report False so a probe failure can't block an update.- """- try:- result = subprocess.run(- git_cmd + ["--version"],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=15,- )- except Exception:- return False- output = ((result.stdout or "") + (result.stderr or "")).lower()- return "fork bomb" in output---def _portable_git_candidates() -> list:- """PortableGit candidate paths: shared root first, then profile home.-- The Hermes-managed PortableGit tree lives under the SHARED root- (``<root>/git/...``), not the profile-scoped HERMES_HOME- (``<root>/profiles/<name>``), so a profile-scoped ``hermes update`` must- look there (monerostar review, #87876). The profile-home candidate is- kept as a fallback for custom layouts that place it there.- """- candidates = []- try:- for root in (get_default_hermes_root(), Path(get_hermes_home())):- candidates.append(- root / "git" / "mingw64" / "libexec" / "git-core" / "git.exe"- )- except Exception:- pass- return candidates---def _locate_real_git() -> Optional[Path]:- """Find a real Git-for-Windows binary that is not a broken trampoline.-- The trampoline symptom is PATH-level: ``bin\\git.exe`` / ``cmd\\git.exe``- (both ~46KB shims) fail to re-exec git-core, while the real binary at- ``mingw64\\libexec\\git-core\\git.exe`` (≈4.4MB) works when invoked- directly (#87876). Check the standard Git for Windows locations plus the- Hermes-managed PortableGit copy; accept the first candidate that runs and- does NOT print the trampoline guard. Returns None when nothing suitable- is found — callers then keep the broken command and let the existing- fetch-failure ZIP fallback handle it.- """- candidates = [- Path(r"C:\Program Files\Git\mingw64\libexec\git-core\git.exe"),- Path(r"C:\Program Files (x86)\Git\mingw64\libexec\git-core\git.exe"),- ] + _portable_git_candidates()- for candidate in candidates:- if not candidate.exists():- continue- try:- result = subprocess.run(- [str(candidate), "--version"],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=15,- )- except Exception:- continue- output = ((result.stdout or "") + (result.stderr or "")).lower()- if "fork bomb" in output:- continue- return candidate- return None---def _ensure_non_trampoline_git(git_cmd: list) -> list:- """Swap a broken Git-for-Windows trampoline for a real git binary.-- Runs up front, right after the git command is built. When the resolved- ``git`` is a broken trampoline, locate the real binary and rebuild the- command with it so fetch/pull/checkout keep working with a real git- instead of degrading to the ZIP fallback. When no real binary can be- found, leave the command untouched — the existing fetch-failure handler- already falls back to the ZIP path on Windows. No-op off Windows (the- trampoline is a Git-for-Windows artifact) and when git is healthy.- """- if sys.platform != "win32":- return git_cmd- if not _git_is_trampoline(git_cmd):- return git_cmd- real_git = _locate_real_git()- if real_git is None:- print(- "⚠ Detected a broken git trampoline and could not locate a real "- "git binary — the update will fall back to the ZIP path."- )- return git_cmd- print(- f"⚠ Detected a broken git trampoline; switching to real git at "- f"{real_git}"- )- return [str(real_git)] + list(git_cmd[1:])---def _discard_lockfile_churn(git_cmd, repo_root):- """Restore tracked ``package-lock.json`` files that npm dirtied locally.-- npm rewrites lockfiles non-deterministically at install/build time. On a- managed install those diffs are never intentional, so we discard them so- ``hermes update`` sees a clean tree instead of autostashing every run.- Best-effort; only ever touches files named ``package-lock.json``.- """- try:- diff = subprocess.run(- git_cmd + ["diff", "--name-only"],- cwd=repo_root,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if diff.returncode != 0:- return- dirty_package_dirs = {- Path(line.strip()).parent- for line in diff.stdout.splitlines()- if line.strip().endswith("package.json")- }- dirty = [- line.strip()- for line in diff.stdout.splitlines()- if line.strip().endswith("package-lock.json")- and Path(line.strip()).parent not in dirty_package_dirs- ]- if not dirty:- return- subprocess.run(- git_cmd + ["checkout", "--", *dirty],- cwd=repo_root,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=False,- )- print(f"→ Discarded npm lockfile churn ({len(dirty)} file(s))")- except Exception:- # Never let lockfile cleanup block an update.- pass--def _normalize_managed_eol(git_cmd, repo_root):- """Take a managed checkout off ``core.autocrlf=true`` without leaving it dirty.-- Git for Windows ships ``core.autocrlf=true`` in its system config, which- renormalizes this repo's LF text files to CRLF in the working tree. That- breaks ``git checkout`` on update with "Your local changes would be- overwritten", so ``install.ps1`` pins ``core.autocrlf=false`` on the managed- clone (#67730). Checkouts created before that landed never got the pin and- cannot receive it — the bootstrap installer reuses its build-pinned- ``install.ps1`` forever — so ``hermes update``, which ships with the checkout- itself, is the only path left that can fix them.-- The pin and the cleanup are one operation. Under ``autocrlf=true`` git- compares normalized content, so a CRLF working tree reads clean; pinning- alone would expose every text file as modified and hand the update an- autostash of the whole tree. So the pin is written only after the tree is- verified clean under it, and a checkout we cannot fully normalize is left- exactly as it was. Best-effort: never blocks an update.- """- # -c, not config: evaluate the tree as it WOULD look pinned, without- # persisting anything we might not be able to follow through on.- probe = git_cmd + ["-c", "core.autocrlf=false"]-- def _dirty(*extra):- out = subprocess.run(- probe + ["diff", "-z", "--name-only", *extra],- cwd=repo_root,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if out.returncode != 0:- return None- return {p for p in out.stdout.split("\0") if p}-- def _real_dirty():- # Files with a *content* change once CRLF differences are ignored.- # NOTE: ``diff --name-only --ignore-cr-at-eol`` still LISTS CR-only- # files (the name list is computed from blob/stat differences before- # the CR filter is applied), so it cannot be used to isolate real- # edits. ``--numstat`` does honor the filter: a CR-only file produces- # no numstat record, while a genuinely-edited file does. Parse the- # paths out of numstat instead.- out = subprocess.run(- probe + ["-c", "core.quotepath=false",- "diff", "--numstat", "--ignore-cr-at-eol"],- cwd=repo_root,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if out.returncode != 0:- return None- paths = set()- for line in out.stdout.splitlines():- if not line.strip():- continue- # Format: "<added>\t<deleted>\t<path>". Rename detection is off in- # plain diff, so there is exactly one path field per record.- parts = line.split("\t", 2)- if len(parts) == 3 and parts[2]:- paths.add(parts[2])- return paths-- def _eol_only():- all_dirty, real_dirty = _dirty(), _real_dirty()- if all_dirty is None or real_dirty is None:- return None- return all_dirty - real_dirty-- try:- effective = subprocess.run(- git_cmd + ["config", "--get", "core.autocrlf"],- cwd=repo_root,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- # Only "true" rewrites LF to CRLF on checkout. Unset, false, and input- # all leave the working tree alone, so there is nothing to repair.- if effective.stdout.strip().lower() != "true":- return-- eol_only = _eol_only()- if eol_only is None:- return- if eol_only:- # Pathspec over stdin, not argv: a fully renormalized checkout is- # thousands of paths, well past the Windows command-line limit.- subprocess.run(- probe- + ["checkout", "--pathspec-from-file=-", "--pathspec-file-nul", "--"],- cwd=repo_root,- input="\0".join(sorted(eol_only)),- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=False,- )- if _eol_only():- # Still dirty — persisting the pin here would only surface churn- # we failed to clear. Leave the checkout as we found it.- return- print(f"→ Normalized line-ending churn ({len(eol_only)} file(s))")-- subprocess.run(- git_cmd + ["config", "core.autocrlf", "false"],- cwd=repo_root,- capture_output=True,- check=False,- )- except Exception:- # Never let line-ending cleanup block an update.- pass---def _desktop_app_present(desktop_dir: Path) -> bool:- """Return whether a packaged or source Desktop build exists."""- return (- _m()._desktop_packaged_executable(desktop_dir) is not None- or _m()._desktop_dist_exists(desktop_dir)- )---def _rebuild_desktop_after_update(- desktop_dir: Path, *, had_desktop_app_before_update: bool-) -> bool:- """Rebuild an installed Desktop app when its source or artifact changed.-- Returns ``False`` only when a rebuild was attempted and failed, so the- caller can withhold ``✓ Update complete!`` and (in gateway mode) write- a failing ``.update_exit_code`` (#88251). Every other outcome — nothing- to rebuild, up to date, build succeeded, Desktop never installed —- returns ``True``.- """- # The release tree is ignored by git and can disappear during an update.- # Its pre-update presence is enough to restore it; do not make people who- # have never used Desktop pay for an Electron build.- has_desktop_app = had_desktop_app_before_update or _desktop_app_present(desktop_dir)- if not (- (desktop_dir / "package.json").exists()- and _m()._resolve_node_runtime_npm()- and has_desktop_app- ):- return True-- print("→ Checking if desktop app needs rebuilding...")- # Consult the content-hash stamp IN-PROCESS first. The spawned- # `hermes desktop --build-only` subprocess re-imports the whole CLI stack- # (~1-3 s) just to reach the same _m()._desktop_build_needed check; when- # the stamp already says "up to date" we can skip the spawn entirely. The- # update path never passes --source, so the subprocess would run with- # source_mode=False — mirror that here. Any error in the pre-check falls- # through to the subprocess.- skip_desktop_build = False- try:- skip_desktop_build = not _m()._desktop_build_needed(- desktop_dir, _m().PROJECT_ROOT, source_mode=False- )- except Exception:- skip_desktop_build = False- if skip_desktop_build:- print(" ✓ Desktop app up to date")- return True-- desktop_build_cmd = [sys.executable, "-m", "hermes_cli.main", "desktop", "--build-only"]- # Capture the (very loud) Electron/vite build output into update.log- # instead of streaming it to the terminal. On the rare nonzero exit,- # retry once after waiting again for the venv — this covers a- # still-settling rebuild window the first wait didn't fully catch — then- # surface the captured tail so the failure is debuggable.- #- # Start the build subprocess with the Hermes-managed Node on PATH: when- # `hermes update` runs inside the desktop updater chain (Desktop →- # hermes-setup → hermes update), the shell PATH customizations are lost,- # so a bare-PATH child would fail with `node: not found` before cmd_gui can- # self-heal.- from hermes_constants import with_hermes_node_path-- build_env = with_hermes_node_path()- build_result = _m()._run_logged_subprocess(- desktop_build_cmd, cwd=_m().PROJECT_ROOT, env=build_env- )- if build_result.returncode != 0:- build_result = _m()._run_logged_subprocess(- desktop_build_cmd, cwd=_m().PROJECT_ROOT, env=build_env- )- if build_result.returncode != 0:- print(" ⚠ Desktop build failed (run `hermes desktop` to retry)")- tail = "\n".join((build_result.stdout or "").strip().splitlines()[-15:])- if tail:- print(tail)- from hermes_constants import display_hermes_home as _dhh-- print(f" Full build log: {_dhh()}/logs/update.log")- return False- print(" ✓ Desktop app up to date")- return True---def _path_uid(path) -> Optional[int]:- """Owner uid of ``path`` via ``os.stat`` — ``None`` when unreadable.-- Separate seam so tests can simulate root-owned files without chown- (which needs root). Never raises.- """- try:- return os.stat(path, follow_symlinks=False).st_uid- except OSError:- return None---def _venv_foreign_owned_paths(venv_root, limit: int = 5) -> list:- """Bounded scan for venv entries not owned by the current user (#83529).-- A venv that was ever touched by ``sudo pip`` / ``sudo hermes`` contains- root-owned files (classically ``*.dist-info/INSTALLER``). A later normal- ``hermes update`` then dies mid-mutation inside ``uv pip install -e .``- ("Permission denied (os error 13)") with ``venv/bin/hermes`` already- deleted — the CLI is bricked. Same philosophy as the contended-venv gate- (#87331): a venv we cannot safely mutate is never mutated at all.-- Checks a deliberately BOUNDED set (no full recursion — must never be- slow): the venv root, each direct entry of ``venv/bin``, the top-level- entries of the first ``lib/python*/site-packages`` found, and the direct- children of each ``*.dist-info`` there. Caps stat calls at ~2000 and- returned paths at ``limit``. POSIX-only: returns ``[]`` on Windows- (no ``os.geteuid``) and when running as root. Swallows every per-entry- ``OSError`` and returns ``[]`` on any structural surprise — this helper- must NEVER raise and must never add noticeable latency to update.-- Returns a list of ``(path_str, uid)`` tuples, at most ``limit`` long.- """- try:- if not hasattr(os, "geteuid"):- return [] # windows-footgun: ok — POSIX ownership concept only- euid = os.geteuid() # windows-footgun: ok — guarded by hasattr above- if euid == 0:- return [] # root can rewrite anything; nothing to refuse-- venv_root = Path(venv_root)- budget = 2000 # max stat() calls — hard bound on preflight cost- foreign: list = []-- def _check(p) -> bool:- """stat one path; True while scan should continue."""- nonlocal budget- if budget <= 0 or len(foreign) >= limit:- return False- budget -= 1- uid = _path_uid(p)- if uid is not None and uid != euid:- foreign.append((str(p), uid))- return budget > 0 and len(foreign) < limit-- def _scan_dir(d, recurse_dist_info: bool = False) -> None:- try:- entries = list(os.scandir(d))- except OSError:- return- for entry in entries:- if not _check(entry.path):- return- if recurse_dist_info and entry.name.endswith(".dist-info"):- try:- children = list(os.scandir(entry.path))- except OSError:- continue- for child in children:- if not _check(child.path):- return-- if not _check(venv_root):- return foreign[:limit]- _scan_dir(venv_root / "bin")-- # First lib/python*/site-packages (POSIX venv layout).- site_packages = next(- iter(sorted(venv_root.glob("lib/python*/site-packages"))), None- )- if site_packages is not None:- _scan_dir(site_packages, recurse_dist_info=True)-- return foreign[:limit]- except Exception:- # Preflight is advisory: any structural surprise means "no verdict",- # never a crashed or blocked update.- return []---def _refuse_update_if_venv_foreign_owned(project_root) -> None:- """Refuse-before-mutate ownership gate for the dependency install (#83529).-- Runs after the code pull (pulling code is safe) and immediately before- the first venv mutation. If the venv contains files owned by another- uid, the ``uv pip install -e .`` below would die mid-mutation and brick- the install — so refuse up front, with the exact recovery command,- while the venv is still fully intact. No subprocess calls here: update- tests mock ``subprocess.run`` with sequenced side effects.- """- foreign = _venv_foreign_owned_paths(Path(project_root) / "venv")- if not foreign:- return- print("\n✗ Update stopped: this install's venv contains files owned by another user.")- print(" Updating now would fail midway (Permission denied) and leave Hermes broken.")- print(" This usually happens after running hermes or pip with sudo. Offending paths:")- for p, uid in foreign:- print(f" - {p} (owner uid {uid})")- print("\n Fix ownership, then re-run the update:")- print(f" sudo chown -R $(id -un): {project_root}")- print(" hermes update")- print("\n Nothing in the venv was modified.")- sys.exit(1)---def _drain_or_signal_gateway_for_update(- pid: int,- drain_budget: float,- label: str,-) -> bool:- """Decide how ``hermes update`` hands a running gateway over to new code.-- Three-way triage shared by the systemd and bare-process restart paths:-- 1. **Gateway is an ancestor of this process** — THREE-WAY DEADLOCK BREAK- (#100179). When ``hermes update`` runs INSIDE the gateway's own- process tree (the hermes-auto-update cron job is the canonical case),- waiting for that gateway to exit is a circular wait::-- gateway waits on all in-flight work units (#77184)- └─ cron agent session waits on the `hermes update` process- └─ `hermes update` waits on the gateway to exit ← back to A-- The wedged-loop probe cannot break it: the cron session posts- activity every ~180s (process-tool poll return), so it is "actively- waiting forever" and never marked wedged — the gateway burns the full- force-drain cap (1800s) before killing its own updater's session.- Fire-and-forget instead: signal the restart and return immediately;- the gateway's own restart flow completes once THIS process (and- therefore the cron work unit holding it) exits.- 2. **Event loop provably wedged** (#81642) — SIGUSR1 can never drain it;- bounded escalation (SIGTERM grace → SIGKILL) instead of burning the- full drain budget.- 3. **Live, out-of-tree gateway** — the normal graceful SIGUSR1 drain,- waiting up to ``drain_budget`` for the process to exit (unchanged,- including the #86684 cron floor).-- Returns True when the gateway was signalled/stopped successfully.- """- from hermes_cli.gateway import (- GATEWAY_LOOP_WEDGED,- _escalate_wedged_gateway,- _graceful_restart_via_sigusr1,- _is_pid_ancestor_of_current_process,- _request_gateway_self_restart,- probe_gateway_loop_liveness,- )-- if _is_pid_ancestor_of_current_process(pid):- print(- f" → {label}: update is running inside this gateway's "- "process tree — signalling restart and letting the gateway "- "drain itself (avoids the cron-update deadlock, #100179)"- )- return _request_gateway_self_restart(pid)- if probe_gateway_loop_liveness(pid) == GATEWAY_LOOP_WEDGED:- print(- f" ⚠ {label}: gateway event loop is unresponsive — "- "skipping drain, forcing a bounded stop..."- )- _escalate_wedged_gateway(pid)- return True- print(f" → {label}: draining (up to {int(drain_budget)}s)...")- return _graceful_restart_via_sigusr1(pid, drain_timeout=drain_budget)---def _cmd_update_impl(args, gateway_mode: bool):- """Body of ``cmd_update`` — kept separate so the wrapper can always- restore stdio even on ``sys.exit``."""- # A managed-runtime refresh can replace site-packages before the normal- # ``.[all]`` install runs. Snapshot while the old environment can still- # prove which optional backends the user had activated.- active_lazy_features = _m()._capture_active_lazy_features()- active_tool_dependencies = _m()._capture_active_tool_dependencies()-- # Snapshot the pre-update version before any code is pulled so the- # completion line can report the transition (prime-agent#630 port).- pre_update_version = _read_project_version()- # In gateway mode, use file-based IPC for prompts instead of stdin- gw_input_fn = (- (lambda prompt, default="": _gateway_prompt(prompt, default))- if gateway_mode- else None- )- assume_yes = bool(getattr(args, "yes", False))- # --keep-stash (desktop updater): stash local changes so the update can- # proceed, but never re-apply them afterward — they stay parked in git- # stash. Only applies when an update actually landed; abort/no-op paths- # still restore, since the tree they restore onto is unchanged.- keep_stash = bool(getattr(args, "keep_stash", False))- # --switch-branch: on a branch carrying unmerged commits, prefer switching- # to the update target over an in-place merge, so the branch's history is- # never written to by an update (#89507 review feedback). Only meaningful- # when updates.parked_branch_strategy is "update_in_place".- switch_branch = bool(getattr(args, "switch_branch", False))-- # Whether this update is running without a human at the keyboard.- # Interactive terminal updates always stash-and-ask (unchanged behavior);- # only non-interactive updates (desktop/chat app, gateway, `--yes`) consult- # the `updates.non_interactive_local_changes` config setting to decide- # whether to auto-restore stashed local source changes or throw them away.- _non_interactive_update = (- gateway_mode- or assume_yes- or not (sys.stdin.isatty() and sys.stdout.isatty())- )- discard_local_changes = False- if _non_interactive_update:- try:- from hermes_cli.config import load_config-- _update_cfg = (load_config() or {}).get("updates", {})- if isinstance(_update_cfg, dict):- _mode = str(_update_cfg.get("non_interactive_local_changes", "stash")).lower()- discard_local_changes = _mode == "discard"- except Exception as exc:- # Never let a config read failure change the safe default.- logger.debug("Could not read updates.non_interactive_local_changes: %s", exc)- discard_local_changes = False-- print("⚕ Updating Hermes Agent...")- print()-- # Phase 1 (#91277): structured update receipt — record what this run- # discovers, does, and skips, so silent-failure classes (#88848,- # #74973, #85753, #81193) become diagnosable from disk.- try:- from hermes_cli.update_receipt import begin_update_receipt-- begin_update_receipt()- except Exception as _receipt_exc:- logger.debug("Update receipt unavailable: %s", _receipt_exc)-- # Plan phase (#91277 Phase 2): snapshot the pre-update fleet — every- # running Hermes runtime, its supervisor, and its running code version —- # into the receipt, so a post-mortem can compare what the update SAW- # against what it did. Read-only; a probe failure records nothing.- # ``_pre_update_plan`` is read again AFTER the restart phase to reconcile- # every planned runtime against the phase's bookkeeping (restart via- # declared mechanism — the plan is the worklist, not just a printout).- _pre_update_plan = None- try:- from hermes_cli.update_inventory import (- collect_runtime_inventory,- record_plan_in_receipt,- )-- _pre_update_plan = collect_runtime_inventory()- record_plan_in_receipt(_pre_update_plan)- if _pre_update_plan.runtimes:- _n = len(_pre_update_plan.runtimes)- _profiles = ", ".join(- sorted({r.profile for r in _pre_update_plan.runtimes})- )- print(f"→ Fleet: {_n} running service(s) across profiles: {_profiles}")- except Exception as _plan_exc:- logger.debug("Update plan phase failed: %s", _plan_exc)-- # On Windows, abort early if another hermes.exe is holding the venv shim- # open. Continuing would result in a string of WinError 32 warnings and- # then either a deferred-rename leftover or a failed git-pull fast path- # that silently falls back to the slower ZIP route. See issue #26670.- #- # Exception (#37039): when every concurrent instance is a gateway- # runtime, the pause machinery a few lines below- # (``_pause_windows_gateways_for_update``) stops it before any file- # mutation, and the post-update restart phase brings it back. Aborting- # just to make the user run the same kill manually is friction without- # benefit. Anything not positively identified as a gateway (TUI shell,- # Desktop backend child, unreadable cmdline) still aborts exactly as- # before.- if _m()._is_windows() and not getattr(args, "force", False):- scripts_dir = _m()._venv_scripts_dir()- if scripts_dir is not None:- concurrent = _m()._detect_concurrent_hermes_instances(scripts_dir)- if concurrent:- non_gateway = _m()._filter_non_gateway_concurrent_instances(- concurrent- )- if non_gateway:- print(- _format_concurrent_instances_message(- non_gateway, scripts_dir- )- )- sys.exit(2)-- # Pre-update backup — runs before any git/file mutation so users can- # always roll back to the exact state they had before this update.- # Returns the quick-snapshot id (or None when disabled/failed); the- # post-update cron-jobs safety net uses it to detect job loss.- pre_update_snapshot_id = _m()._run_pre_update_backup(args)try:- from hermes_cli.update_receipt import record_step-- record_step(- "pre_update_backup",- pre_update_snapshot_id is not None,- f"snapshot={pre_update_snapshot_id}" if pre_update_snapshot_id else "disabled or failed",- )- except Exception:- pass-- _windows_gateway_resume = _m()._pause_windows_gateways_for_update()- if _windows_gateway_resume:- import atexit as _atexit-- _atexit.register(- _m()._resume_windows_gateways_after_update,- _windows_gateway_resume,- )-- # With gateways paused, anything still running from the venv interpreter- # (most commonly the Desktop app's `hermes serve` backend) will keep .pyd- # files locked and corrupt the dependency sync below. Refuse rather than- # race: killing the desktop backend is futile (the app supervises and- # respawns it), so the user must close the app. Deliberately NOT bypassed- # by plain --force: the desktop bootstrap updater passes --force to skip- # the hermes.exe shim guard above, but its lock probe only checks the shim- # and app.asar — a non-desktop venv python holding a .pyd would sail- # through and corrupt the sync (the exact failure this guard exists for).- # --force-venv is the explicit escape hatch.- if _m()._is_windows() and not getattr(args, "force_venv", False):- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- _gateway_holders = _m()._leftover_pausable_gateway_pids(_venv_holders)- if _gateway_holders is not None:- if _refuse_gateway_ancestor_tree_kill(- _gateway_holders, gateway_mode=gateway_mode- ):- _m()._resume_windows_gateways_after_update(- _windows_gateway_resume- )- sys.exit(2)- # Every remaining holder is a gateway the pause machinery- # already owns — respawned by its supervisor inside the- # pause→guard window, or up through a spawn path discovery- # does not map. Stop them and re-check instead of- # dead-ending; the post-update resume (and the supervisor- # that respawned them) brings gateways back afterwards.- from gateway.status import get_process_start_time, terminate_pid-- print(- f" ⚠ {len(_gateway_holders)} gateway process(es) still "- "hold the venv after the pause; stopping them"- )- for _pid in _gateway_holders:- try:- pid_int = int(_pid)- terminate_pid(- pid_int,- force=True,- expected_start_time=get_process_start_time(pid_int),- )- except Exception as exc:- logger.debug(- "Could not stop leftover gateway %s: %s", _pid, exc- )- _time.sleep(1.0)- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- # Positive-identity rung (runs FIRST, any update context): holders- # the spawn ledger proves are orphaned Hermes backends — the- # process self-registered (pid, create_time, purpose, spawner) at- # startup and its recorded spawner is provably dead. No PPID- # archaeology, no hand-off contract required.- _ledger_backends = _m()._ledger_reapable_backend_pids(_venv_holders)- if _ledger_backends:- print(- f" ⚠ {len(_ledger_backends)} ledger-identified orphaned "- "Hermes backend process(es) hold the venv; stopping their trees"- )- _m()._stop_process_trees(_ledger_backends)- _time.sleep(1.0)- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- _orphan_backends = _m()._orphaned_desktop_backend_pids(_venv_holders)- if _orphan_backends:- # Every remaining holder is a Desktop `serve` backend whose- # supervising app is GONE — the GUI-updater handoff race:- # Electron's teardown lost the SIGTERM race, exited, and left- # its backend (and any .hermes-runtime child) holding the- # venv. Nothing will respawn an orphan, so reap the tree and- # re-check instead of dead-ending with "Hermes is still- # running" while no window is open. Backends whose Desktop- # is still alive never reach here (_orphaned_desktop_- # backend_pids returns None for them) — that path keeps the- # refusal, because the app would just respawn what we kill.- print(- f" ⚠ {len(_orphan_backends)} orphaned Desktop backend "- "process(es) still hold the venv; stopping their trees"- )- _m()._stop_process_trees(_orphan_backends)- _time.sleep(1.0)- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- # Manual serve/dashboard rung (#63206): a network-bound- # `hermes serve --host <ip>` powering a REMOTE Desktop holds the- # venv and used to dead-end the update with exit 2 — the user's- # only option was killing the backend by hand, and nothing ever- # brought it back (the remote client's endpoint stayed dead).- # Positive ledger identity only: self-registered serve/dashboard- # whose recorded spawner is not alive (Desktop-owned backends- # keep the refusal — the app respawns what we kill). Stop them,- # and register an idempotent atexit relaunch built from the- # ledger's structured host/port/profile so the endpoint comes- # back on the SAME bind after the update — success or failure.- _serve_entries = _m()._ledger_manual_serve_holders(_venv_holders)- if _serve_entries:- print(- f" ⚠ {len(_serve_entries)} manual serve/dashboard "- "backend(s) hold the venv; stopping them for the update "- "(they will be relaunched on their recorded endpoints)"- )- _m()._stop_process_trees(- [int(e["pid"]) for e in _serve_entries]- )- _serve_resume_token = {- "pending": True,- "entries": _serve_entries,- }- try:- from hermes_cli.update_receipt import record_step-- record_step(- "serve_pause",- True,- f"stopped={len(_serve_entries)}",- )- except Exception:- pass- import atexit as _serve_atexit-- _serve_atexit.register(- _m()._relaunch_stopped_serves, _serve_resume_token- )- _time.sleep(1.0)- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- # Final rung before the dead-end: a GUI-updater hand-off- # (`update --gateway --force` with the update-incomplete marker- # claimed) means the Desktop is contractually gone and nothing- # legitimate will respawn a `serve` backend from this venv. The- # orphan-only reap above bails the instant ANY holder still has a- # live parent — which stranded a whole swarm of per-profile- # backends (the tearing-down Electron parent / the venv- # launcher→worker chain still mid-exit) and hung the update. In- # the hand-off context those surviving Hermes backends are leaks,- # live parent or not — reap them by cmdline instead of dead-ending.- _handoff = False- try:- _handoff = bool(getattr(args, "gateway", False)) and _m()._update_marker_path().exists()- except Exception:- _handoff = False- # Fail closed: if we cannot positively verify the shim state- # (scripts dir unresolvable, detection raised), assume a live- # shim exists and keep refusing rather than reap.- _no_live_shim = False- try:- _scripts_dir = _m()._venv_scripts_dir()- if _scripts_dir is not None:- _no_live_shim = not _m()._detect_concurrent_hermes_instances(_scripts_dir)- except Exception:- _no_live_shim = False- if _handoff and _no_live_shim:- _handoff_backends = _m()._handoff_reapable_backend_pids(_venv_holders)- if _handoff_backends:- print(- f" ⚠ {len(_handoff_backends)} Hermes backend process(es) "- "still hold the venv after the Desktop hand-off; "- "stopping their trees"- )- _m()._stop_process_trees(_handoff_backends)- _time.sleep(1.0)- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- print(_format_venv_python_holders_message(_venv_holders))- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(2)-- # Self-lock deferral moved: the venv-holder sweep above excludes this- # process by design (a CLI `hermes update` IS the venv python), and an- # updater that has imported a native venv extension cannot rewrite its- # own mapped .pyd (#83569). That check used to run HERE — before the- # fetch — but firing pre-fetch meant a deferral stranded the user on the- # OLD checkout, and any startup path that eagerly loaded cryptography- # turned every Windows update into an exit-2 loop (#86735/#86780/#86781).- # It now runs via _abort_dependency_sync_if_self_locked() after the code- # swap, immediately before the dependency sync — the only phase the lock- # can actually break — and only when the sync would truly rewrite the- # loaded distribution.-- # Capture this after every fail-closed venv guard, but before either- # update path can remove the ignored release tree.- desktop_dir = _m().PROJECT_ROOT / "apps" / "desktop"- had_desktop_app_before_update = _desktop_app_present(desktop_dir)-- # Try git-based update first, fall back to ZIP download on Windows- # when git file I/O is broken (antivirus, NTFS filter drivers, etc.)- use_zip_update = False- git_dir = _m().PROJECT_ROOT / ".git"-- if not git_dir.exists():- if sys.platform == "win32":- use_zip_update = True- else:- print("✗ Not a git repository. Please reinstall:")- print(- " curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"- )+ pm.ensure("uv")+ except pm.InstallError as e:+ print(f"⚠ Managed uv unavailable: {e}")++ # A current checkout does NOT imply a healthy install: a previous dependency sync may+ # have failed partway (classic on Windows: a running gateway/desktop backend keeps .pyd+ # locked and the installer dies with access-denied, stranding the venv between+ # versions). Probe the venv's core imports and repair if broken — otherwise "Already up+ # to date!" gaslights the user while their install stays bricked.+ healthy, detail = _venv_core_imports_healthy()+ # The Windows shim hand-off spawns this child precisely to run a sync its parent could+ # not. The parent already pulled, so the checkout is current BY DESIGN and venv health+ # is not the question — the pending sync is.+ handed_off_sync = os.environ.get(_m()._UPDATE_REEXEC_ENV) == "1"+ if handed_off_sync:+ print("→ Finishing the dependency install handed off by hermes.exe...")+ elif not healthy:+ print("⚠ Checkout is current, but the venv is unhealthy:")+ print(f" {detail}")+ print("→ Repairing Python dependencies...")+ if handed_off_sync or not healthy:+ return _repair_venv_on_current_checkout(+ assume_yes=assume_yes, gateway_mode=gateway_mode,+ pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,+ had_desktop_app_before_update=had_desktop_app_before_update,+ active_lazy_features=active_lazy_features,+ active_tool_dependencies=active_tool_dependencies,+ _windows_gateway_resume=_windows_gateway_resume)+ return _repair_node_deps_on_current_checkout(+ _print_verified_update_completion, assume_yes=assume_yes, gateway_mode=gateway_mode,+ pre_update_snapshot_id=pre_update_snapshot_id,+ completion_message=(+ "✓ Already up to date!" if upstream_checked+ else "✓ Up to date with your fork (official repo not checked)."),+ had_desktop_app_before_update=had_desktop_app_before_update)+++def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_ref=None) -> None:+ """Fast-forward failed: merge on a custom branch (local commits survive) or reset --hard on the+ same branch (rescue ref first when histories share no ancestor). ``sys.exit(1)`` on failure."""+ # A custom branch (local commits atop origin/<branch>) also can't ff, and reset --hard+ # would discard that work: merge instead, stop on conflict.+ merge_ref = target_ref if target_ref is not None else f"origin/{branch}"+ _cur_branch = (_git_run(git_cmd, ["branch", "--show-current"]).stdout or "").strip()+ if _cur_branch and _cur_branch != branch:+ print(+ f" ⚠ Checkout is on custom branch '{_cur_branch}' — "+ f"merging origin/{branch} instead of resetting so local commits survive...")+ # Best-effort safety tag as a recovery anchor.+ _git_run(git_cmd, ["tag", f"pre-update-{_time.strftime('%Y%m%d-%H%M%S')}"])+ if _git_run(git_cmd, ["merge", "--no-edit", merge_ref]).returncode != 0:+ _git_run(git_cmd, ["merge", "--abort"])+ print("✗ Merge conflict between local commits and upstream — update stopped, nothing was changed.")+ print(f" Resolve manually: cd {_m().PROJECT_ROOT} && git merge origin/{branch}")+ print(" Then re-run the update. Local work is untouched.")sys.exit(1)-- # On Windows, git can fail with "unable to write loose object file: Invalid argument"- # due to filesystem atomicity issues. Set the recommended workaround.- if sys.platform == "win32" and git_dir.exists():- subprocess.run(- [- "git",- "-c",- "windows.appendAtomically=false",- "config",- "windows.appendAtomically",- "false",- ],- cwd=_m().PROJECT_ROOT,- check=False,- capture_output=True,- )-- # Build git command once — reused for fork detection and the update itself.- git_cmd = ["git"]- if sys.platform == "win32":- git_cmd = ["git", "-c", "windows.appendAtomically=false"]- # A broken Git-for-Windows trampoline refuses every git call with a- # "BUG (fork bomb)" guard instead of running; swap in a real binary up- # front so the normal git path survives instead of degrading to ZIP- # (#87876).- git_cmd = _ensure_non_trampoline_git(git_cmd)-- # Discard npm lockfile churn before any stash/branch logic. npm rewrites- # tracked package-lock.json files non-deterministically at install/build- # time (platform-specific optional deps, ideallyInert annotations, etc.),- # which is never an intentional edit on a managed install but leaves the- # tree dirty — forcing an autostash on every update and making branch- # switches fragile. Restoring them first lets the common case (only- # lockfile churn) update with a clean tree.- _discard_lockfile_churn(git_cmd, _m().PROJECT_ROOT)- # Same rationale, different generator: line-ending churn is machine-made- # dirt on a managed checkout, so clear it (and stop generating it) before- # the stash/branch logic rather than autostashing the entire tree.- _normalize_managed_eol(git_cmd, _m().PROJECT_ROOT)-- # Detect if we're updating from a fork (before any branch logic)- origin_url = _m()._get_origin_url(git_cmd, _m().PROJECT_ROOT)- is_fork = _is_fork(origin_url)-- if is_fork:- print("⚠ Updating from fork:")- print(f" {origin_url}")- print()-- if use_zip_update:- # ZIP-based update for Windows when git is broken- try:- desktop_build_ok = _update_via_zip(- args,- had_desktop_app_before_update=had_desktop_app_before_update,- )- finally:- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- if gateway_mode:- _write_gateway_update_exit_code(desktop_build_ok)return-- # Fetch and pull- try:-- # Resolve the target branch up front so the fetch can be scoped to it.- # A bare `git fetch origin` pulls every ref, and this repo carries- # thousands of auto-generated branches — an unscoped fetch can stall for- # minutes on a non-single-branch checkout. Fetch only what we update- # against.- branch = _m()._resolve_update_branch(args)-- # Self-heal abandoned git lock files (e.g. .git/shallow.lock left by a- # crashed fetch) before the fetch — otherwise the update fails with- # "Unable to create .../shallow.lock: File exists" and never reaches- # the network.- from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs-- cleared = clear_stale_git_locks(_m().PROJECT_ROOT)- if cleared:- print(" (removed stale git lock(s): %s)" % ", ".join(cleared))- swept = clear_stale_tmp_packs(_m().PROJECT_ROOT)- if swept:- print(" (removed %d aborted-fetch pack temp file(s))" % len(swept))-- # target_ref is the reference that we count against, fast-forward to,- # and reset to. On the main channel it is origin/<branch>. That is the- # historical behavior. On the stable channel it is the commit of the- # newest release tag. The current branch pointer fast-forwards to the- # release. Thus the checkout keeps its branch shape (no detached HEAD).- # The next stable update then fast-forward merges to the next tag.- target_ref = f"origin/{branch}"- stable_tag = None- if _stable_channel_active(args):- print("→ Update channel: stable (tagged releases)")- stable_tag, _stable_tag_sha = _resolve_latest_release_tag(- git_cmd, _m().PROJECT_ROOT- )- if stable_tag is None:- print("✗ No release tags found on origin. An update on the stable channel is not possible.")- print(" Switch channels with: hermes update --set-channel main")- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(1)- print(f"→ Latest release: {stable_tag}")- target_ref = stable_tag-- # Surface autostash entries left behind by earlier updates (#63717- # problem 6) — parked --keep-stash runs and failed restores preserve- # the stash but nothing ever mentioned it again.- _m()._warn_orphaned_update_autostashes(git_cmd, _m().PROJECT_ROOT)-- print("→ Fetching updates...")- fetch_target = ["tag", stable_tag] if stable_tag else [branch]- fetch_result = subprocess.run(- git_cmd + ["fetch", "origin", *fetch_target],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- **_no_prompt_git_kwargs(),- )- if fetch_result.returncode != 0:- _print_fetch_failure(fetch_result.stderr)- sys.exit(1)-- # Get current branch (returns literal "HEAD" when detached)- result = subprocess.run(- git_cmd + ["rev-parse", "--abbrev-ref", "HEAD"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=True,- )- current_branch = result.stdout.strip()-- # Parked-branch guard (2026-08-17 live incident): the checkout can be- # left parked on a stale feature branch by earlier tooling. Blindly- # stash-switch-pull-switch-back "updates" main while the running code- # stays days behind, then prints "✓ Code updated!".- #- # What happens next is routed by what the branch carries (which is- # exactly what the guard measures) plus updates.parked_branch_strategy:- #- # fully merged -> a stale leftover with nothing to lose: switch- # back to the target.- # unmerged: N -> strategy "switch" (default): switch to the- # target anyway — committed work is safe on the- # branch (git checkout never discards commits) and- # a loud "kept" notice names the branch + count.- # Deterministic, so non-interactive callers- # (desktop update button, gateway /update, cron)- # always reach the target.- # strategy "update_in_place": a maintained custom- # branch (local patches on top of main) is updated- # IN PLACE from origin/<target> — the checkout- # never moves, local commits survive, the running- # code advances. --switch-branch overrides back to- # the switch path for one run.- # anything else -> dirty / unverifiable / opted out: touch nothing,- # warn loudly, mark the code update SKIPPED, and- # stop before the post-update steps reinforce the- # stale tree.- parked_branch_switched = False- in_place_update = False- # Stable channel: the checkout does NOT switch branches. The current- # branch pointer fast-forwards (or merges) to the release tag's- # commit, so the parked-branch machinery below is main-channel only.- if stable_tag is None and current_branch != branch and current_branch != "HEAD":- switch_safe, switch_block_reason = _m()._assess_parked_branch_switch(- git_cmd, _m().PROJECT_ROOT, current_branch, branch- )- if not switch_safe:- _m()._print_parked_branch_skip_warning(- git_cmd,- _m().PROJECT_ROOT,- current_branch,- branch,- switch_block_reason,- )- print()- print(- "⚠ Update finished — code update SKIPPED"- f"{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}"- )- _m()._resume_windows_gateways_after_update(- _windows_gateway_resume- )- sys.exit(1)- if switch_block_reason.startswith("unmerged:"):- _in_place_configured = False- try:- from hermes_cli.config import load_config as _load_cfg-- _upd_cfg = (_load_cfg() or {}).get("updates", {})- _in_place_configured = (- isinstance(_upd_cfg, dict)- and _upd_cfg.get("parked_branch_strategy", "switch")- == "update_in_place"- )- except Exception as exc:- logger.debug(- "Could not read updates.parked_branch_strategy: %s", exc- )- if _in_place_configured and not switch_branch:- # The merge source must exist upstream; --branch typos- # previously surfaced through the checkout failing, which- # does not run on this path.- verify_ref = subprocess.run(- git_cmd + ["rev-parse", "--verify", "--quiet", f"origin/{branch}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if verify_ref.returncode != 0:- print(f"✗ Branch '{branch}' does not exist locally or on origin.")- sys.exit(1)- in_place_update = True- print(- f" ℹ On branch '{current_branch}' — updating it in place from "- f"origin/{branch} (no branch switch; local commits preserved)."- )- else:- parked_branch_switched = True- _m()._print_parked_branch_kept_notice(- current_branch,- branch,- switch_block_reason.split(":", 1)[1],- )- else:- parked_branch_switched = True- print(- f" ⚠ Checkout was parked on '{current_branch}' "- f"(fully merged) — switching back to {branch}..."- )-- if stable_tag is None and not in_place_update and current_branch != branch:- if current_branch == "HEAD":- print(- f" ⚠ Currently on detached HEAD — switching to {branch} "- "for update..."- )- # Stash before checkout so uncommitted work isn't lost- auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)- checkout_result = subprocess.run(- git_cmd + ["checkout", branch],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if checkout_result.returncode != 0:- # Local checkout doesn't have this branch yet. Try to set- # it up as a tracking branch of origin/<branch>. This is- # the common case when the requested branch exists upstream- # but was never checked out locally.- track_result = subprocess.run(- git_cmd + ["checkout", "-B", branch, f"origin/{branch}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if track_result.returncode != 0:- # Restore the user's prior stash before bailing- # so we don't leave them stranded in a weird state.- if auto_stash_ref is not None:- _m()._restore_stashed_changes(- git_cmd,- _m().PROJECT_ROOT,- auto_stash_ref,- prompt_user=False,- input_fn=gw_input_fn,- )- print(f"✗ Branch '{branch}' does not exist locally or on origin.")- if track_result.stderr.strip():- print(f" {track_result.stderr.strip().splitlines()[0]}")- sys.exit(1)- else:- auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)-- prompt_for_restore = (- auto_stash_ref is not None- and not assume_yes- and (gateway_mode or (sys.stdin.isatty() and sys.stdout.isatty()))- )-- # Check if there are updates. On shallow checkouts `rev-list --count`- # walks the truncated graph and can report the entire remote ancestry- # (e.g. "Found 9980 new commit(s)" on a depth-1 install — #53479).- # The zero/nonzero gate is still sound (HEAD == origin/<branch> counts- # 0), so keep it, but treat the shallow NUMBER as unknown and recover- # the real one via the GitHub compare API when possible.- result = subprocess.run(- git_cmd + ["rev-list", f"HEAD..{target_ref}", "--count"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=True,- )- commit_count = int(result.stdout.strip())-- apply_is_shallow = (- subprocess.run(- git_cmd + ["rev-parse", "--is-shallow-repository"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- == "true"- )- if commit_count > 0 and apply_is_shallow:- from hermes_cli.banner import _github_compare_behind-- head_sha = subprocess.run(- git_cmd + ["rev-parse", "HEAD"],- cwd=_m().PROJECT_ROOT, capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- target_sha = subprocess.run(- git_cmd + ["rev-parse", target_ref],- cwd=_m().PROJECT_ROOT, capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- counted = _github_compare_behind(head_sha, target_sha)- # counted == 0 means local-ahead (remote tip reachable from HEAD):- # not behind, fall through to the up-to-date path.- commit_count = counted if counted is not None else -1-- # A fork can match origin while still trailing upstream. The sync can- # therefore advance HEAD even though the origin comparison found no- # commits. Detect that BEFORE taking the no-update return so dependency- # refreshes, gateway restarts, AND the fleet version matrix still run- # for the pulled code (#73108 — previously the sync lived inside the- # commit_count == 0 branch, which returns immediately after: an update- # that pulled hundreds of upstream commits printed "Already up to- # date!" and verified nothing).- # Non-fork checkouts have no upstream question: origin IS the official- # repo, so "Already up to date!" is fully verified there.- upstream_checked = True- if commit_count == 0 and is_fork and branch == "main":- pre_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)- upstream_checked = _m()._sync_with_upstream_if_needed(- git_cmd,- _m().PROJECT_ROOT,- assume_yes=assume_yes,- input_fn=gw_input_fn,- )- post_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)- if pre_sync_sha and post_sync_sha and pre_sync_sha != post_sync_sha:- synced_count = _count_commits_between(- git_cmd,- _m().PROJECT_ROOT,- pre_sync_sha,- post_sync_sha,- )- # HEAD moving is itself proof of an update. Keep the update- # path active even if the informational count cannot be read.- commit_count = max(1, synced_count)-- if commit_count == 0:- _invalidate_update_cache()-- # Restore stash and switch back to original branch if we moved.- # EXCEPTION: a parked feature branch we verified clean + fully- # merged stays on the target — re-parking the checkout on the- # stale branch is the 2026-08-17 incident all over again.- if auto_stash_ref is not None:- _m()._restore_stashed_changes(- git_cmd,- _m().PROJECT_ROOT,- auto_stash_ref,- prompt_user=prompt_for_restore,- input_fn=gw_input_fn,- )- if parked_branch_switched:- if switch_block_reason.startswith("unmerged:"):- _count = switch_block_reason.split(":", 1)[1]- print(- f" ✓ Checkout was parked on '{current_branch}' — "- f"switched back to {branch}; {_count} unmerged "- f"commit(s) kept on '{current_branch}'."- )- else:- print(- f" ✓ Checkout was parked on '{current_branch}' (fully "- f"merged) — switched back to {branch}."- )- elif current_branch not in {branch, "HEAD"}:- subprocess.run(- git_cmd + ["checkout", current_branch],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- check=False,- )-- # "No new commits" does not mean the venv is safe: pm owns the uv- # pin now — a pin bump realizes a NEW entry on the next ensure.- # The update command is the one caller that must SEE realization- # failures, so use the raising API, not the None-swallowing uv().- import pm-- try:- pm.ensure("uv")- except pm.InstallError as e:- print(f"⚠ Managed uv unavailable: {e}")-- # A current checkout does NOT imply a healthy install: a previous- # dependency sync may have failed partway (classic on Windows,- # where a running gateway/desktop backend keeps .pyd files locked- # and uv/pip dies with access-denied, stranding the venv between- # versions). Probe the venv's core imports and repair if broken —- # otherwise "Already up to date!" gaslights the user while their- # install stays bricked.- healthy, detail = _venv_core_imports_healthy()- # The Windows shim hand-off spawns this child precisely to run a- # sync its parent could not. The parent already pulled, so the- # checkout is current BY DESIGN and venv health is not the- # question — the pending sync is. Without this the child prints- # "Already up to date!" and exits without doing the one job it- # was spawned for.- handed_off_sync = os.environ.get(_m()._UPDATE_REEXEC_ENV) == "1"- current_checkout_complete = True- if handed_off_sync:- print("→ Finishing the dependency install handed off by hermes.exe...")- elif not healthy:- print("⚠ Checkout is current, but the venv is unhealthy:")- print(f" {detail}")- print("→ Repairing Python dependencies...")- if handed_off_sync or not healthy:- # Self-lock deferral (#86735): the repair rewrites the venv- # too — same mapped-extension hazard as the update sync.- _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)- _write_update_incomplete_marker()- import pm-- repair_uv, repair_env = pm.uv(venv=_m().PROJECT_ROOT / "venv")- # A managed install whose venv is gone entirely (interrupted- # repair after the old venv was moved aside) needs the venv- # recreated before dependencies can be installed into it.- venv_python_missing = not (- venv_python_path(- _m().PROJECT_ROOT / "venv", windows=_m()._is_windows()- )- ).exists()- if venv_python_missing and repair_uv:- print("→ Recreating virtual environment...")- subprocess.run(- [repair_uv, "venv", "venv"],- cwd=_m().PROJECT_ROOT,- check=False,- )- try:- pm.sync_venv(["all"] + list(active_lazy_features or []), explicit=True)- except pm.InstallError as _sync_err:- print(f" ✗ {_sync_err}")- if repair_uv:- _m()._restore_active_tool_dependencies(- active_tool_dependencies,- [repair_uv, "pip"],- env=repair_env,- )- else:- _m()._restore_active_tool_dependencies(- active_tool_dependencies,- [sys.executable, "-m", "pip"],- )- _m()._clear_update_incomplete_marker()- healthy_after, detail_after = _venv_core_imports_healthy()- if healthy_after:- print("✓ Dependencies repaired!")- _check_and_apply_config_migration(- assume_yes=assume_yes,- gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- )- # The Windows hand-off child lands here after doing the- # sync its parent could not, and the commits-pulled- # rebuild below is never reached — rebuild the Desktop- # app here or it silently stays on the old build- # (#97343).- if _rebuild_desktop_after_update(- desktop_dir,- had_desktop_app_before_update=had_desktop_app_before_update,- ):- current_checkout_complete = _print_verified_update_completion(- "✓ Update complete!"- )- else:- current_checkout_complete = False- _print_update_completion(- "⚠ Update partially complete — the desktop app was "- "not rebuilt and is still on the previous build."- )- else:- current_checkout_complete = False- print(f"⚠ Venv still unhealthy after repair: {detail_after}")- print(" Close all Hermes windows/gateways and re-run: hermes update")- else:- current_checkout_complete = _repair_node_deps_on_current_checkout(- _print_verified_update_completion,- assume_yes=assume_yes,- gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- completion_message=(- "✓ Already up to date!"- if upstream_checked- else "✓ Up to date with your fork (official repo not checked)."- ),- had_desktop_app_before_update=had_desktop_app_before_update,- )- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- # Git is current, but a prior pull may still owe the fleet a- # restart (#95294). Catch up even on the "Already up to date"- # path — that early return is what left the gateway on stale- # code for two days. Runs BEFORE the runtime-verification exit- # gate below: a vulnerable SQLite runtime demotes the outcome to- # partial, but must not strand the fleet on stale code (#91277- # fleet contract — the pending-restart check always executes).- _apply_pending_fleet_restart_catchup()- if not current_checkout_complete:- if gateway_mode:- _write_gateway_update_exit_code(False)- try:- from hermes_cli.update_receipt import finalize_update_receipt-- finalize_update_receipt("partial")- except Exception as _receipt_exc:- logger.debug(- "Update receipt finalize (current checkout) failed: %s",- _receipt_exc,- )- sys.exit(1)- return-- if commit_count > 0:- print(f"→ Found {commit_count} new commit(s)")- else:- # Shallow checkout, exact count unrecoverable (offline/rate-limited- # compare API) — the tips differ, so there IS an update.- print("→ Updates available (commit count unknown on this shallow checkout)")-- print("→ Pulling updates...")- update_succeeded = False- # Capture the pre-pull SHA so we can auto-roll-back if the new code- # has a syntax error in a critical-path file (PR #28452 incident:- # orphan merge-conflict markers in hermes_cli/config.py bricked- # every user who ran ``hermes update`` for the 7 minutes between- # the bad commit and the fix landing).- pre_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)- try:- # Merge the ref we already fetched above (→ Fetching updates...)- # instead of `git pull`, which performs a SECOND network fetch of- # the same branch (~0.5-1.5 s of redundant round-trip per update).- # `merge --ff-only origin/<branch>` is byte-identical in effect to- # `pull --ff-only origin <branch>` given the fresh tracking ref;- # the divergence fallback below is unchanged.- pull_result = subprocess.run(- git_cmd + ["merge", "--ff-only", target_ref],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if pull_result.returncode != 0:- # ff-only failed — local and remote have diverged. Before- # assuming an upstream force-push, check WHY: a checkout on a- # custom branch (local commits on top of origin/<branch>) also- # cannot fast-forward, and `reset --hard` here would silently- # discard that work. Merge instead and stop cleanly on- # conflict — an update must never destroy local commits.- _cur_branch = (- subprocess.run(- git_cmd + ["branch", "--show-current"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout- or ""- ).strip()- if _cur_branch and _cur_branch != branch:- print(- f" ⚠ Checkout is on custom branch '{_cur_branch}' — "- f"merging origin/{branch} instead of resetting so local commits survive..."- )- # Best-effort safety tag; recovery anchor if anything goes wrong.- subprocess.run(- git_cmd- + ["tag", f"pre-update-{_time.strftime('%Y%m%d-%H%M%S')}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- check=False,- )- merge_result = subprocess.run(- git_cmd + ["merge", "--no-edit", f"origin/{branch}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if merge_result.returncode != 0:- subprocess.run(- git_cmd + ["merge", "--abort"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- check=False,- )- print(- "✗ Merge conflict between local commits and upstream — "- "update stopped, nothing was changed."- )- print(- f" Resolve manually: cd {_m().PROJECT_ROOT} && "- f"git merge origin/{branch}"- )- print(- " Then re-run the update. Local work is untouched."- )- sys.exit(1)- else:- # Same branch as the update target — a true upstream- # force-push/rebase. Local changes are already stashed;- # reset to match the remote exactly (original behaviour).- #- # Divergence here comes in two shapes: ordinary (a common- # ancestor still exists — the reset below is a normal,- # safe re-sync onto the remote) and orphan (no common- # ancestor at all, e.g. a corrupted local HEAD or a repo- # re-init — see #87694). In the orphan case `reset --hard`- # would silently discard the entire local commit graph- # with no way back, so park pre_pull_sha behind a rescue- # ref first.- merge_base_result = subprocess.run(- git_cmd + ["merge-base", "HEAD", f"origin/{branch}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- has_common_ancestor = bool(- merge_base_result.returncode == 0- and merge_base_result.stdout.strip()- )- if not has_common_ancestor and pre_pull_sha:- from datetime import datetime as _dt, timezone-- # Suffix with the pre-pull SHA (not just a second-- # resolution timestamp) so two updates racing within- # the same second (e.g. a retried update) get distinct- # refs instead of the second `update-ref` silently- # overwriting the first backup.- rescue_ref = (- f"refs/hermes-update-backups/orphan-{branch}-"- f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}"- f"-{pre_pull_sha[:12]}"- )- update_ref_result = subprocess.run(- git_cmd + ["update-ref", rescue_ref, pre_pull_sha],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if update_ref_result.returncode == 0:- print(- " ⚠ Local history shares no common ancestor with "- f"origin/{branch} (orphan divergence) — backed up "- f"current HEAD to {rescue_ref} before resetting. "- f"This backup expires after "- f"{_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days."- )- else:- # update-ref's return code is intentionally not- # fatal (disk full, permissions) — but don't tell- # the user a backup exists when the write failed.- print(- " ⚠ Local history shares no common ancestor with "- f"origin/{branch} (orphan divergence) — attempted "- f"to back up current HEAD to {rescue_ref} before "- "resetting, but the backup write failed "- f"(pre-reset SHA was {pre_pull_sha})."- )- _prune_orphan_rescue_refs(git_cmd, _m().PROJECT_ROOT, branch)- print(- " ⚠ Fast-forward not possible (history diverged), resetting to match remote..."- )- reset_result = subprocess.run(- git_cmd + ["reset", "--hard", f"origin/{branch}"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if reset_result.returncode != 0:- print(f"✗ Failed to reset to origin/{branch}.")- if reset_result.stderr.strip():- print(f" {reset_result.stderr.strip()}")- print(- f" Try manually: git fetch origin && git reset --hard origin/{branch}"- )- sys.exit(1)-- # Post-pull syntax guard: validate critical-path files actually- # parse before declaring the update successful. If a bad commit- # made it through CI (e.g. admin-merge bypass of a failing- # ruff check), this catches it on the user side and rolls back- # so the CLI stays bootable. The user can then retry ``hermes- # update`` later once a fix lands upstream.- syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(- _m().PROJECT_ROOT- )- if not syntax_ok:- print()- print("✗ Pulled code has a syntax error in a critical file:")- print(f" {failing_path}")- if syntax_error:- # py_compile errors can be multi-line; show the first- # ~6 lines so the user sees the actual SyntaxError text.- for line in str(syntax_error).splitlines()[:6]:- print(f" {line}")- if pre_pull_sha:- print()- print(f"→ Rolling back to {pre_pull_sha[:10]}...")- rollback_result = subprocess.run(- git_cmd + ["reset", "--hard", pre_pull_sha],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- )- if rollback_result.returncode == 0:- print(" ✓ Rollback complete — your install is unchanged.")- print(" Try ``hermes update`` again later once a fix lands.")- else:- print(" ✗ Rollback failed. Recover manually with:")- print(f" cd {_m().PROJECT_ROOT} && git reset --hard {pre_pull_sha}")- if rollback_result.stderr.strip():- print(f" ({rollback_result.stderr.strip().splitlines()[0]})")- else:- print()- print(" Could not capture pre-pull SHA — recover manually with:")- print(f" cd {_m().PROJECT_ROOT} && git reflog && git reset --hard <prev-sha>")- sys.exit(1)-- update_succeeded = True- finally:- if auto_stash_ref is not None:- # Don't attempt stash restore if the code update itself failed —- # working tree is in an unknown state.- if not update_succeeded:- print(- f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})"- )- print(" Restore manually with: git stash apply")- elif discard_local_changes:- # Non-interactive update + user opted into discarding local- # source edits (updates.non_interactive_local_changes:- # discard). Throw the stash away instead of re-applying it.- _m()._discard_stashed_changes(- git_cmd,- _m().PROJECT_ROOT,- auto_stash_ref,- )- elif keep_stash:- # --keep-stash (desktop updater): the update landed; leave- # local edits parked in the stash instead of silently- # re-applying them onto the updated code.- _m()._park_stashed_changes(auto_stash_ref)- else:- _m()._restore_stashed_changes(- git_cmd,- _m().PROJECT_ROOT,- auto_stash_ref,- prompt_user=prompt_for_restore,- input_fn=gw_input_fn,- )-- _invalidate_update_cache()-- # Verify HEAD actually moved (issue #79678). ``merge --ff-only``- # succeeding only means the merge completed, not that the update- # applied: a checkout that is pinned to a raw SHA (detached HEAD) can- # report "N new commit(s)" against origin yet still sit on the old- # commit afterward (the branch-switch step re-detaches to the SHA).- # Before this guard, ``hermes update`` printed "✓ Code updated!" and- # reinstalled deps + rebuilt the desktop app against the stale tree —- # no error, no warning, ``hermes doctor`` healthy. Compare pre-pull- # and post-pull HEAD; if they match, surface the no-op instead of- # claiming success.- post_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)- if pre_pull_sha and post_pull_sha == pre_pull_sha:- print()- print("✗ Code did not move — update was a no-op.")- print(- f" HEAD is pinned to {pre_pull_sha[:10]} (detached checkout); "- f"origin/{branch} advanced but the working tree stayed put."- )- print(- " Reattach to the branch and retry: "- f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update"- )- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(1)-- # And verify HEAD actually sits on the target branch. The parked-- # branch guard above should make this unreachable, but if any path- # leaves the checkout attached elsewhere, "✓ Code updated!" would be- # a lie — refuse to claim success (2026-08-17 incident class).- #- # An IN-PLACE branch update is the one legitimate way to end on a- # non-target branch: origin/<target> was merged INTO the checked-out- # branch, so the running code *is* up to date and HEAD staying put is- # the whole point. Claiming failure there would make every update on a- # real working branch exit 1 after doing exactly the right thing.- post_pull_branch = subprocess.run(- git_cmd + ["rev-parse", "--abbrev-ref", "HEAD"],- cwd=_m().PROJECT_ROOT,- capture_output=True,- text=True, encoding="utf-8", errors="replace",- ).stdout.strip()- if (- not in_place_update- and post_pull_branch- and post_pull_branch not in {branch, "HEAD"}- ):- print()- print(- f"✗ Update pulled origin/{branch}, but the checkout is on "- f"'{post_pull_branch}' — not claiming success."- )- print(- " Switch to the target branch and retry: "- f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update"- )- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(1)-- # #95294: HEAD advanced; running gateways still serve pre-pull- # modules until the restart phase below. Any interrupt between here- # and a completed (or no-op) restart leaves this marker so the next- # ``hermes update`` can catch up even when git is already up to date.- # Distinct from ``.update-incomplete`` (venv/install repair).- _write_fleet_restart_pending_marker(expected_sha=post_pull_sha or "")-- # Clear stale .pyc bytecode cache — prevents ImportError on gateway- # restart when updated source references names that didn't exist in- # the old bytecode (e.g. get_hermes_home added to hermes_constants).- removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)- if removed:- print(- f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}"- )- _m()._record_bytecode_fingerprint()- _m()._refresh_bootstrap_cache_scripts(branch)-- # Fork upstream sync logic (only for main branch on forks)- if is_fork and branch == "main":- _m()._sync_with_upstream_if_needed(- git_cmd,- _m().PROJECT_ROOT,- assume_yes=assume_yes,- input_fn=gw_input_fn,- )-- # Reinstall Python dependencies. Prefer .[all], but if one optional extra- # breaks on this machine, keep base deps and reinstall the remaining extras- # individually so update does not silently strip working capabilities.- #- # Ownership preflight (#83529): refuse before the first venv mutation- # if the venv contains foreign-owned files (sudo-pip residue) — the- # install below would die mid-mutation and brick the CLI.- _refuse_update_if_venv_foreign_owned(_m().PROJECT_ROOT)- #- # Self-lock deferral (relocated preflight — #86735): if THIS process- # holds a native extension the sync must rewrite, defer NOW — after- # the code swap, so only the dependency install is pending and the- # next fresh launch completes it via the marker.- _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)- #- # Drop the core-install breadcrumb BEFORE touching the venv. If the- # install is killed mid-flight (Ctrl-C, terminal close, WSL OOM), the- # marker survives and the next ``hermes`` launch finishes the install- # via ``_recover_from_interrupted_install``. Cleared after the core- # ``.[all]`` install completes — lazy refresh uses a separate marker.- _write_update_incomplete_marker()- print("→ Syncing Python dependencies...")- import pm-- try:- pm.sync_venv(["all"], explicit=True)- deps_synced = True- except pm.InstallError as _sync_err:- deps_synced = False- print(f" ✗ {_sync_err}")- print(" Re-run `hermes update` (or `hermes pm install`) once resolved.")-- uv_bin, uv_env = pm.uv(venv=_m().PROJECT_ROOT / "venv")- pip_cmd = [sys.executable, "-m", "pip"]- install_prefix = [uv_bin, "pip"] if uv_bin else pip_cmd- lazy_env = uv_env if uv_bin else None-- if deps_synced:- # Console-script shims aren't covered by the sync stamp — verify- # them so a venv whose Scripts/ was clobbered self-heals.- _m()._verify_console_scripts_installed(install_prefix, env=lazy_env)-- # Core ``.[all]`` install finished. Clear the generic core breadcrumb- # before the lazy-refresh phase — that phase uses its own marker so a- # later lazy failure cannot be "healed" by clearing the core marker- # based on a narrow 7-package import probe (#58004 review).- _m()._clear_update_incomplete_marker()-- # The update process is still the old Python interpreter process. Run- # one final cache/module refresh immediately before lazy backend- # refresh, which imports newly-pulled modules that may depend on fresh- # symbols in hermes_constants or pm. The dependency install- # above may also have regenerated bytecode from build-cache copies —- # this second sweep catches those stragglers (#60242, #65240).- removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)- if removed:+ # Same branch: a true upstream force-push/rebase; local changes are stashed, so reset.+ # Orphan divergence (no common ancestor: corrupted HEAD, re-init) would lose the whole+ # local graph, so park pre_pull_sha behind a rescue ref first.+ merge_base_result = _git_run(git_cmd, ["merge-base", "HEAD", merge_ref])+ has_common_ancestor = merge_base_result.returncode == 0 and merge_base_result.stdout.strip()+ if not has_common_ancestor and pre_pull_sha:+ from datetime import datetime as _dt, timezone+ # SHA suffix so two updates in the same second get distinct refs.+ rescue_ref = (+ f"refs/hermes-update-backups/orphan-{branch}-"+ f"{_dt.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{pre_pull_sha[:12]}")+ head = f" ⚠ Local history shares no common ancestor with origin/{branch} (orphan divergence) — "+ if _git_run(git_cmd, ["update-ref", rescue_ref, pre_pull_sha]).returncode == 0:print(- f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}"- )- _m()._record_bytecode_fingerprint()- _m()._refresh_bootstrap_cache_scripts(branch)- _m()._reload_updated_runtime_modules()-- _write_lazy_refresh_incomplete_marker()- lazy_ok = _m()._refresh_active_lazy_features(active_lazy_features)- if lazy_ok:- _m()._clear_lazy_refresh_incomplete_marker()+ f"{head}backed up current HEAD to {rescue_ref} before resetting. "+ f"This backup expires after {_ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days.")else:+ # update-ref failure is intentionally non-fatal, but never claim a backup exists.print(- " ⚠ Lazy-refresh recovery incomplete — run `hermes` again "- "to finish import-based venv repair."- )+ f"{head}attempted to back up current HEAD to {rescue_ref} before resetting, "+ f"but the backup write failed (pre-reset SHA was {pre_pull_sha}).")+ _prune_orphan_rescue_refs(git_cmd, _m().PROJECT_ROOT, branch)+ print(" ⚠ Fast-forward not possible (history diverged), resetting to match remote...")+ reset_result = _git_run(git_cmd, ["reset", "--hard", merge_ref])+ if reset_result.returncode != 0:+ print(f"✗ Failed to reset to origin/{branch}.")+ if reset_result.stderr.strip():+ print(f" {reset_result.stderr.strip()}")+ print(f" Try manually: git fetch origin && git reset --hard origin/{branch}")+ sys.exit(1)- _m()._restore_active_tool_dependencies(- active_tool_dependencies,- install_prefix,- env=lazy_env,- )- # Heal the active memory provider's bridge packages last — the core- # reinstall + lazy refresh above may have stripped or downgraded- # plugin.yaml-declared deps that aren't in extras (#53272, #70636).- _m()._refresh_active_memory_provider_dependencies()-- # Everything that can legitimately produce a transient ImportError has- # now run (bytecode sweep, dependency reinstall, lazy refresh), so a- # module that still won't import is real breakage. Warn only — never- # roll back here: `cannot import name X` is also the signature of the- # stale-bytecode class (#6207, #60242), and the launch-time sweep in- # _sweep_stale_bytecode_if_checkout_changed() self-heals that on the- # next run. A destructive reset would undo a good update over a state- # that fixes itself.- import_ok, failing_module, import_error = _validate_critical_modules_import(- _m().PROJECT_ROOT- )- if not import_ok:- print()- print(f" ⚠ {failing_module} still fails to import after updating:")- print(f" {import_error}")- print(" Run `hermes update` again — if it persists, reinstall:")- print(" https://hermes-agent.nousresearch.com")-- node_failures = _update_node_dependencies()- _m()._build_web_ui(_m().PROJECT_ROOT / "web")-- desktop_build_ok = _rebuild_desktop_after_update(- desktop_dir,- had_desktop_app_before_update=had_desktop_app_before_update,- )+def _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha) -> None:+ """Post-pull syntax guard: roll back to *pre_pull_sha* and ``sys.exit(1)`` when a critical+ file no longer compiles (a bad admin-merge past CI must not brick the CLI)."""+ syntax_ok, failing_path, syntax_error = _validate_critical_files_syntax(_m().PROJECT_ROOT)+ if syntax_ok:+ return+ print()+ print("✗ Pulled code has a syntax error in a critical file:")+ print(f" {failing_path}")+ # py_compile errors can be multi-line; show enough for the SyntaxError text.+ for line in str(syntax_error).splitlines()[:6] if syntax_error else ():+ print(f" {line}")+ print()+ if pre_pull_sha:+ print(f"→ Rolling back to {pre_pull_sha[:10]}...")+ rollback_result = _git_run(git_cmd, ["reset", "--hard", pre_pull_sha])+ if rollback_result.returncode == 0:+ print(" ✓ Rollback complete — your install is unchanged.")+ print(" Try ``hermes update`` again later once a fix lands.")+ else:+ print(" ✗ Rollback failed. Recover manually with:")+ print(f" cd {_m().PROJECT_ROOT} && git reset --hard {pre_pull_sha}")+ if rollback_result.stderr.strip():+ print(f" ({rollback_result.stderr.strip().splitlines()[0]})")+ else:+ print(" Could not capture pre-pull SHA — recover manually with:")+ print(f" cd {_m().PROJECT_ROOT} && git reflog && git reset --hard <prev-sha>")+ sys.exit(1)++def _pull_updates(+ git_cmd, branch, auto_stash_ref, *, prompt_for_restore, gw_input_fn, discard_local_changes,+ keep_stash, target_ref=None):+ """Fast-forward onto ``origin/<branch>`` and settle the autostash. Divergence by shape:+ custom branch -> merge, same branch -> reset, orphan history -> rescue ref first; a+ post-pull syntax error in a critical file rolls back. Exits on failure; returns pre-pull SHA."""+ update_succeeded = False+ # Pre-pull SHA for auto-rollback (stray conflict markers once bricked every updater).+ # Capture the pre-pull SHA so we can auto-roll-back if the new code has a syntax error in a+ # critical-path file (PR #28452 incident: orphan merge-conflict markers in hermes_cli/config.py bricked+ # every user who ran ``hermes update`` for the 7 minutes between the bad commit and the fix landing).+ pre_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)+ try:+ # merge --ff-only the already-fetched ref instead of `git pull`, which would do a+ # SECOND network fetch; identical in effect given the fresh tracking ref.+ merge_ref = target_ref if target_ref is not None else f"origin/{branch}"+ if _git_run(git_cmd, ["merge", "--ff-only", merge_ref]).returncode != 0:+ _reconcile_diverged_checkout(git_cmd, branch, pre_pull_sha, target_ref=merge_ref)+ _rollback_if_pulled_syntax_error(git_cmd, pre_pull_sha)+ update_succeeded = True+ finally:+ if auto_stash_ref is not None:+ # No stash restore if the update failed — tree state is unknown.+ if not update_succeeded:+ print(f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})")+ print(" Restore manually with: git stash apply")+ elif discard_local_changes:+ # Non-interactive + updates.non_interactive_local_changes: discard.+ _m()._discard_stashed_changes(git_cmd, _m().PROJECT_ROOT, auto_stash_ref)+ elif keep_stash:+ # --keep-stash (desktop updater): leave edits parked rather than re-apply silently.+ _m()._park_stashed_changes(auto_stash_ref)+ else:+ _m()._restore_stashed_changes(+ git_cmd, _m().PROJECT_ROOT, auto_stash_ref, prompt_user=prompt_for_restore,+ input_fn=gw_input_fn)+ return pre_pull_sha+++@dataclass+class _CheckoutPlan:+ """What the pre-pull checkout phase decided (see ``_prepare_checkout_for_update``)."""++ auto_stash_ref: "str | None"+ commit_count: int+ in_place_update: bool+ parked_branch_switched: bool+ prompt_for_restore: bool+ switch_block_reason: "str | None"+ upstream_checked: bool+++def _apply_parked_branch_guard(+ git_cmd, branch, current_branch, *, switch_branch, _windows_gateway_resume+) -> tuple[bool, bool, "str | None"]:+ """Decide how a checkout parked on another branch is brought to *branch* (stash-switch-pull-+ switch-back used to "update" main while the running code stayed behind).++ By branch contents + updates.parked_branch_strategy: fully merged -> switch back;+ unmerged -> "switch" (default; loud "kept" notice) or "update_in_place" (merge origin/<target>+ INTO the branch, checkout never moves; --switch-branch overrides once); dirty/unverifiable ->+ touch nothing, warn, ``sys.exit(1)`` with the code update SKIPPED (also when the target is+ missing). Returns ``(parked_branch_switched, in_place_update, switch_block_reason)``.+ """+ if current_branch == branch or current_branch == "HEAD":+ return False, False, None+ switch_safe, switch_block_reason = _m()._assess_parked_branch_switch(+ git_cmd, _m().PROJECT_ROOT, current_branch, branch)+ if not switch_safe:+ _m()._print_parked_branch_skip_warning(+ git_cmd, _m().PROJECT_ROOT, current_branch, branch, switch_block_reason)print()- print(f"✓ Code updated!{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")-- # ── macOS TCC stale-grant notice (#86385) ──────────────────────- # Locally-built desktop bundles are re-signed on every update. With the- # post-#73681 identifier-pinned DR, new grants survive rebuilds — but a- # grant made to a pre-fix binary stays stale: the System Settings toggle- # shows ON while macOS re-prompts on every capture, and the modern prompt- # has no Allow button, so users loop. One line of guidance after update- # tells affected users how to complete the one-time re-grant.- if sys.platform == "darwin" and had_desktop_app_before_update:- print()- print(- " ℹ macOS: if Hermes re-prompts for permissions you already "- "granted (toggle shows ON), the stored grant is stale — run "- "`tccutil reset ScreenCapture com.nousresearch.hermes` (repeat "- "per affected service), toggle it ON in System Settings, then "- "fully quit & relaunch once."- )+ print(f"⚠ Update finished — code update SKIPPED{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ sys.exit(1)+ if not switch_block_reason.startswith("unmerged:"):+ print(f" ⚠ Checkout was parked on '{current_branch}' (fully merged) — switching back to {branch}...")+ return True, False, switch_block_reason+ _in_place_configured = False+ with _best_effort('Could not read updates.parked_branch_strategy: %s'):+ _in_place_configured = (+ _updates_config().get("parked_branch_strategy", "switch") == "update_in_place")+ if not _in_place_configured or switch_branch:+ _m()._print_parked_branch_kept_notice(+ current_branch, branch, switch_block_reason.split(":", 1)[1])+ return True, False, switch_block_reason+ # --branch typos used to surface via the checkout failing, which this path skips.+ if _git_run(git_cmd, ["rev-parse", "--verify", "--quiet", f"origin/{branch}"]).returncode != 0:+ print(f"✗ Branch '{branch}' does not exist locally or on origin.")+ sys.exit(1)+ print(+ f" ℹ On branch '{current_branch}' — updating it in place from "+ f"origin/{branch} (no branch switch; local commits preserved).")+ return False, True, switch_block_reason+++def _prepare_checkout_for_update(+ git_cmd, branch, current_branch, *, is_fork, assume_yes, gateway_mode, gw_input_fn,+ switch_branch, target_ref=None, _windows_gateway_resume):+ """Parked-branch guard, land on the target, stash, count new commits. Exits when the+ checkout is unsafe to move or the target is missing. ``commit_count`` is 0 when up to+ date, -1 when tips differ but the shallow count is unrecoverable."""+ if target_ref is None:+ target_ref = f"origin/{branch}"+ stable_tag = target_ref != f"origin/{branch}"+ if stable_tag:+ # Stable channel: the checkout does NOT switch branches — the current branch+ # pointer fast-forwards (or merges) to the release tag, so the parked-branch+ # machinery is main-channel only.+ parked_branch_switched, in_place_update, switch_block_reason = False, False, None+ else:+ parked_branch_switched, in_place_update, switch_block_reason = _apply_parked_branch_guard(+ git_cmd, branch, current_branch, switch_branch=switch_branch,+ _windows_gateway_resume=_windows_gateway_resume)++ if not stable_tag and not in_place_update and current_branch == "HEAD" != branch:+ print(f" ⚠ Currently on detached HEAD — switching to {branch} for update...")+ auto_stash_ref = _m()._stash_local_changes_if_needed(git_cmd, _m().PROJECT_ROOT)+ if (+ not stable_tag and not in_place_update and current_branch != branch+ and _git_run(git_cmd, ["checkout", branch]).returncode != 0):+ track_result = _git_run(git_cmd, ["checkout", "-B", branch, f"origin/{branch}"])+ if track_result.returncode != 0:+ # Restore the stash before bailing so the user isn't stranded.+ if auto_stash_ref is not None:+ _m()._restore_stashed_changes(+ git_cmd, _m().PROJECT_ROOT, auto_stash_ref, prompt_user=False, input_fn=gw_input_fn)+ print(f"✗ Branch '{branch}' does not exist locally or on origin.")+ if track_result.stderr.strip():+ print(f" {track_result.stderr.strip().splitlines()[0]}")+ sys.exit(1)- # macOS TCC interpreter anchor (#95596): dylib-complete re-land.- # Boot-gated — a failed probe leaves the venv untouched.- try:- from hermes_cli.macos_tcc_anchor import ensure_tcc_anchor+ prompt_for_restore = (+ auto_stash_ref is not None+ and not assume_yes+ and (gateway_mode or (sys.stdin.isatty() and sys.stdout.isatty())))++ # On shallow checkouts `rev-list --count` can report the entire remote ancestry. The+ # zero/nonzero gate is still sound; treat the shallow NUMBER as unknown and recover it+ # via the GitHub compare API when possible.+ result = _git_run(git_cmd, ["rev-list", f"HEAD..{target_ref}", "--count"], check=True)+ commit_count = int(result.stdout.strip())++ apply_is_shallow = _is_shallow_checkout(git_cmd)+ if commit_count > 0 and apply_is_shallow:+ from hermes_cli.banner import _github_compare_behind+ counted = _github_compare_behind(*_tip_shas(git_cmd, target_ref))+ # counted == 0 means local-ahead: falls through to the up-to-date path.+ commit_count = counted if counted is not None else -1++ # A fork can match origin yet trail upstream, so the sync can move HEAD with+ # commit_count == 0; detect that BEFORE the no-update return so deps, restarts AND the+ # fleet matrix still run (it used to live in the early-return branch and verified nothing).+ # The sync can therefore advance HEAD even though the origin comparison found no commits. Detect that+ # BEFORE taking the no-update return so dependency refreshes, gateway restarts, AND the fleet version+ # matrix still run for the pulled code (#73108 — previously the sync lived inside the commit_count == 0+ # branch, which returns immediately after: an update that pulled hundreds of upstream commits printed+ # "Already up to date!" and verified nothing). Non-fork checkouts have no upstream question: origin IS+ # the official repo, so "Already up to date!" is fully verified there.+ upstream_checked = True+ if commit_count == 0 and is_fork and branch == "main":+ pre_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)+ upstream_checked = _m()._sync_with_upstream_if_needed(+ git_cmd, _m().PROJECT_ROOT, assume_yes=assume_yes, input_fn=gw_input_fn)+ post_sync_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)+ if pre_sync_sha and post_sync_sha and pre_sync_sha != post_sync_sha:+ synced_count = _count_commits_between(+ git_cmd, _m().PROJECT_ROOT, pre_sync_sha, post_sync_sha)+ # HEAD moving is proof of an update even if the count can't be read.+ commit_count = max(1, synced_count)++ return _CheckoutPlan(+ auto_stash_ref=auto_stash_ref, commit_count=commit_count, in_place_update=in_place_update,+ parked_branch_switched=parked_branch_switched, prompt_for_restore=prompt_for_restore,+ switch_block_reason=switch_block_reason, upstream_checked=upstream_checked)+++@dataclass+class _UpdateOptions:+ """Resolved ``hermes update`` inputs (flags, config, pre-update snapshots)."""++ active_lazy_features: object+ active_tool_dependencies: object+ pre_update_version: object+ gw_input_fn: object+ assume_yes: bool+ keep_stash: bool+ switch_branch: bool+ discard_local_changes: bool+++def _resolve_update_options(args, gateway_mode: bool) -> _UpdateOptions:+ """Snapshot pre-update state and resolve the flags/config ``_cmd_update_impl`` runs on."""+ # Snapshot before a managed-runtime refresh can replace site-packages, while the old+ # environment can still prove which optional backends were active.+ active_lazy_features = _m()._capture_active_lazy_features()+ active_tool_dependencies = _m()._capture_active_tool_dependencies()- ensure_tcc_anchor()- except Exception:- logger.debug("macOS TCC anchor refresh skipped", exc_info=True)-- # ── Post-update state.db integrity guard (#68474, #97994) ─────────- # Verify that state.db survived the update intact in the root home- # AND every sibling profile. If a live file is now corrupted (zeroed,- # missing header, integrity failure), automatically restore from that- # home's own pre-update snapshot rather than letting the user discover- # silently that their sessions are gone.- try:- _verify_and_restore_state_dbs_post_update()- except Exception as exc:- logger.debug("Post-update state.db integrity check failed: %s", exc)-- # Seed the model-catalog disk cache from the freshly-pulled checkout.- # The repo ships the canonical catalog at- # website/static/api/model-catalog.json, and `git pull` just made it- # current — so copy it straight over ~/.hermes/cache/model_catalog.json- # instead of waiting on a network fetch (which can be bot-gated or hit a- # Portal hiccup). Keeps the model picker's curated/free lists in sync- # with the version the user just installed. Non-fatal on failure: the- # normal network refresh still applies on the next picker open.- try:- from hermes_cli.model_catalog import seed_cache_from_checkout+ # Captured before any pull so the completion line can report the transition.+ # Snapshot the pre-update version before files are replaced so the completion line can report the+ # transition (prime-agent#630 port).+ # Snapshot the pre-update version before any code is pulled so the completion line can report the+ # transition (prime-agent#630 port).+ pre_update_version = _read_project_version()+ gw_input_fn = (+ (lambda prompt, default="": _gateway_prompt(prompt, default)) if gateway_mode else None)+ assume_yes = bool(getattr(args, "yes", False))+ # --keep-stash (desktop updater): never re-apply the autostash; only when an update+ # landed — abort/no-op paths still restore since the tree is unchanged.+ keep_stash = bool(getattr(args, "keep_stash", False))+ # --switch-branch: prefer switching over an in-place merge so an update never writes the+ # branch's history; only meaningful with parked_branch_strategy "update_in_place".+ # See #89507.+ switch_branch = bool(getattr(args, "switch_branch", False))- if seed_cache_from_checkout(_m().PROJECT_ROOT):- print(" ✓ Model catalog cache refreshed from checkout")- except Exception as e:- logger.debug("Model catalog seed during update failed: %s", e)+ # Interactive terminals always stash-and-ask; only non-interactive updates consult+ # updates.non_interactive_local_changes (auto-restore vs discard).+ discard_local_changes = False+ if gateway_mode or assume_yes or not (sys.stdin.isatty() and sys.stdout.isatty()):+ # A config read failure must never change the safe default.+ with _best_effort("Could not read updates.non_interactive_local_changes: %s"):+ _mode = str(_updates_config().get("non_interactive_local_changes", "stash")).lower()+ discard_local_changes = _mode == "discard"+ return _UpdateOptions(+ active_lazy_features=active_lazy_features,+ active_tool_dependencies=active_tool_dependencies, pre_update_version=pre_update_version,+ gw_input_fn=gw_input_fn, assume_yes=assume_yes, keep_stash=keep_stash,+ switch_branch=switch_branch, discard_local_changes=discard_local_changes)+++def _begin_update_receipt_and_plan(args):+ """Open the receipt, snapshot the fleet, refuse on Windows shim holders. Returns the+ pre-update plan (None if the probe failed); ``sys.exit(2)`` when a non-gateway hermes.exe+ holds the venv shim."""+ # Structured receipt: record what this run discovers/does/skips so silent failures are diagnosable.+ with _best_effort('Update receipt unavailable: %s'):+ # See #74973, #81193, #85753, #88848, #91277.+ from hermes_cli.update_receipt import begin_update_receipt+ begin_update_receipt()- # Sync bundled skills (copies new, updates changed, respects user deletions)- try:- from tools.skills_sync import sync_skills-- print()- print("→ Syncing bundled skills...")- result = sync_skills(quiet=True)- if result["copied"]:- print(f" + {len(result['copied'])} new: {', '.join(result['copied'])}")- if result.get("updated"):- print(- f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}"- )- if result.get("user_modified"):- print(f" ~ {len(result['user_modified'])} user-modified (kept)")- print(- " → see them: hermes skills list-modified "- "(diff/reset to resume updates)"- )- if result.get("cleaned"):- print(f" − {len(result['cleaned'])} removed from manifest")- if result.get("relocated"):- print(- f" → {len(result['relocated'])} moved to new upstream paths: "- f"{', '.join(result['relocated'])}"- )- if not result["copied"] and not result.get("updated"):- print(" ✓ Skills are up to date")- except Exception as e:- logger.debug("Skills sync during update failed: %s", e)-- # Sync bundled skills to all profiles (including the active one).- # seed_profile_skills() uses subprocess with an explicit HERMES_HOME so- # it is not affected by sync_skills()'s module-level HERMES_HOME cache,- # which means the active profile is reliably synced regardless of whether- # the caller's HERMES_HOME env var points at the default or a named profile.- try:- from hermes_cli.profiles import (- list_profiles,- seed_profile_skills,- )+ # Plan phase: snapshot runtimes/supervisors/version (read-only; probe failure records+ # nothing). Re-read AFTER the restart phase to reconcile — the plan is the worklist.+ # Plan phase (#91277 Phase 2): snapshot the pre-update fleet — every running Hermes runtime, its+ # supervisor, and its running code version — into the receipt, so a post-mortem can compare what the+ # update SAW against what it did. ``_pre_update_plan`` is read again AFTER the restart phase to+ # reconcile every planned runtime against the phase's bookkeeping (restart via declared mechanism — the+ # plan is the worklist, not just a printout).+ _pre_update_plan = None+ with _best_effort('Update plan phase failed: %s'):+ from hermes_cli.update_inventory import collect_runtime_inventory, record_plan_in_receipt+ _pre_update_plan = collect_runtime_inventory()+ record_plan_in_receipt(_pre_update_plan)+ if _pre_update_plan.runtimes:+ _n = len(_pre_update_plan.runtimes)+ _profiles = ", ".join(sorted({r.profile for r in _pre_update_plan.runtimes}))+ print(f"→ Fleet: {_n} running service(s) across profiles: {_profiles}")- all_profiles = list_profiles()- if all_profiles:- print()- print("→ Syncing bundled skills to all profiles...")- for p in all_profiles:- try:- r = seed_profile_skills(p.path, quiet=True)- if r and r.get("skipped_opt_out"):- status = "opted out (--no-skills)"- elif r:- copied = len(r.get("copied", []))- updated = len(r.get("updated", []))- modified = len(r.get("user_modified", []))- parts = []- if copied:- parts.append(f"+{copied} new")- if updated:- parts.append(f"↑{updated} updated")- if modified:- parts.append(f"~{modified} user-modified")- status = ", ".join(parts) if parts else "up to date"- else:- status = "sync failed"- print(f" {p.name}: {status}")- except Exception as pe:- print(f" {p.name}: error ({pe})")- except Exception:- pass # profiles module not available or no profiles+ # Windows: another hermes.exe holding the venv shim means WinError 32 spam and a+ # deferred-rename leftover or silent ZIP fallback. Positively identified gateways are+ # paused/restarted by the update instead; anything else still aborts.+ # Continuing would result in a string of WinError 32 warnings and then either a deferred-rename leftover+ # or a failed git-pull fast path that silently falls back to the slower ZIP route. See issue #26670.+ # Exception (#37039): when every concurrent instance is a gateway runtime, the pause machinery a few+ # lines below (``_pause_windows_gateways_for_update``) stops it before any file mutation, and the+ # post-update restart phase brings it back. Aborting just to make the user run the same kill manually is+ # friction without benefit. Anything not positively identified as a gateway (TUI shell, Desktop backend+ # child, unreadable cmdline) still aborts exactly as before.+ if _m()._is_windows() and not getattr(args, "force", False):+ scripts_dir = _m()._venv_scripts_dir()+ concurrent = _m()._detect_concurrent_hermes_instances(scripts_dir) if scripts_dir is not None else []+ non_gateway = _m()._filter_non_gateway_concurrent_instances(concurrent) if concurrent else []+ if non_gateway:+ print(_format_concurrent_instances_message(non_gateway, scripts_dir))+ sys.exit(2)+ return _pre_update_plan- # Backfill per-profile .env files for profiles created before the- # .env-seeding fix (#44792). Copies the default install's .env so- # those profiles keep the credentials they were effectively using.- try:- from hermes_cli.profiles import backfill_profile_envs- backfilled = backfill_profile_envs(quiet=True)- if backfilled:- print()- print(- f"→ Seeded .env for {len(backfilled)} profile(s) "- f"(copied from default): {', '.join(backfilled)}"- )- except Exception:- pass # profiles module not available or no profiles+def _prepare_git_command() -> tuple[bool, list, bool]:+ """Return ``(use_zip_update, git_cmd, is_fork)``; ``sys.exit(1)`` when not a git repo+ on a non-Windows host (Windows falls back to ZIP: broken git file I/O, AV, NTFS filters)."""+ git_dir = _m().PROJECT_ROOT / ".git"+ use_zip_update = not git_dir.exists()+ if use_zip_update and sys.platform != "win32":+ print("✗ Not a git repository. Please reinstall:")+ print(" curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash")+ sys.exit(1)- # Sync Honcho host blocks to all profiles- try:- from plugins.memory.honcho.cli import sync_honcho_profiles_quiet+ git_cmd = _base_git_cmd()+ if sys.platform == "win32" and git_dir.exists():+ _git_run(git_cmd, ["config", "windows.appendAtomically", "false"])+ # A broken Git-for-Windows trampoline refuses every call with a "BUG (fork bomb)" guard;+ # swap in a real binary up front so git survives instead of degrading to ZIP.+ # See #87876.+ git_cmd = _ensure_non_trampoline_git(git_cmd)- synced = sync_honcho_profiles_quiet()- if synced:- print(f"\n-> Honcho: synced {synced} profile(s)")- except Exception:- pass # honcho plugin not installed or not configured+ # Before stash/branch logic: npm rewrites package-lock.json non-deterministically and+ # line-ending churn is machine-made dirt; both would otherwise force an autostash every update.+ _discard_lockfile_churn(git_cmd, _m().PROJECT_ROOT)+ _normalize_managed_eol(git_cmd, _m().PROJECT_ROOT)- # Check for config migrations (#91360).- _check_and_apply_config_migration(- assume_yes=assume_yes,- gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- )+ origin_url = _m()._get_origin_url(git_cmd, _m().PROJECT_ROOT)+ is_fork = _is_fork(origin_url)- update_complete = _print_update_summary(- node_failures=node_failures,- desktop_build_ok=desktop_build_ok,- pre_update_version=pre_update_version,- )+ if is_fork:+ print("⚠ Updating from fork:")+ print(f" {origin_url}")+ print()+ return use_zip_update, git_cmd, is_fork+++def _verify_head_after_pull(+ git_cmd, branch: str, pre_pull_sha, *, in_place_update: bool, _windows_gateway_resume+) -> str | None:+ """Return the post-pull HEAD SHA; ``sys.exit(1)`` if the pull was a no-op or landed off-branch."""+ # A detached checkout pinned to a SHA can report "N new commit(s)" and a successful+ # merge --ff-only yet stay put; surface the no-op instead of claiming "Code updated!".+ # Verify HEAD actually moved (issue #79678). ``merge --ff-only`` succeeding only means the merge+ # completed, not that the update applied: a checkout that is pinned to a raw SHA (detached HEAD) can+ # report "N new commit(s)" against origin yet still sit on the old commit afterward (the branch-switch+ # step re-detaches to the SHA). Before this guard, ``hermes update`` printed "✓ Code updated!" and+ # reinstalled deps + rebuilt the desktop app against the stale tree — no error, no warning, ``hermes+ # doctor`` healthy. Compare pre-pull and post-pull HEAD; if they match, surface the no-op instead of+ # claiming success.+ post_pull_sha = _capture_head_sha(git_cmd, _m().PROJECT_ROOT)+ if pre_pull_sha and post_pull_sha == pre_pull_sha:+ print()+ print("✗ Code did not move — update was a no-op.")+ print(+ f" HEAD is pinned to {pre_pull_sha[:10]} (detached checkout); "+ f"origin/{branch} advanced but the working tree stayed put.")+ print(+ " Reattach to the branch and retry: "+ f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update")+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ sys.exit(1)- # Search-index optimization notice (v23). Existing installs keep their- # working search index untouched on update; the compact v23 layout —- # which reclaims a large fraction of state.db on heavy users — is- # opt-in. Surface it here (the moment the user is already thinking- # about their install) with the exact command and the concrete size- # win. Show-once-ish: only when a legacy index is actually present.- try:- _print_fts_optimize_available_notice()- except Exception as e:- logger.debug("FTS optimize notice failed: %s", e)-- # Curator first-run heads-up. Only prints when curator is enabled AND- # has never run — i.e. the window where the ticker would otherwise- # have fired against a fresh skill library. Kept silent on steady- # state so we don't nag.- try:- _print_curator_first_run_notice()- except Exception as e:- logger.debug("Curator first-run notice failed: %s", e)-- # Most-recent curator run notice — show-once per run. Surfaces the- # rename map (`old-name → umbrella`) on the high-attention update- # surface so users learn about consolidations without having to- # check `hermes curator status`. Self-stamps after printing so it- # never repeats for the same run.- try:- _print_curator_recent_run_notice()- except Exception as e:- logger.debug("Curator recent-run notice failed: %s", e)+ # HEAD must be on the target or "Code updated!" is a lie; an IN-PLACE update is the one+ # legitimate exception (origin/<target> merged INTO the checked-out branch).+ post_pull_branch = _current_branch_name(git_cmd)+ if not in_place_update and post_pull_branch and post_pull_branch not in {branch, "HEAD"}:+ print()+ print(+ f"✗ Update pulled origin/{branch}, but the checkout is on "+ f"'{post_pull_branch}' — not claiming success.")+ print(+ " Switch to the target branch and retry: "+ f"git -C {_m().PROJECT_ROOT} checkout {branch} && hermes update")+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ sys.exit(1)+ return post_pull_sha- # Repair RHEL-family root installs where /usr/local/bin isn't on PATH- # for non-login interactive shells. No-op on every other platform.- try:- _ensure_fhs_path_guard()- except Exception as e:- logger.debug("FHS PATH guard check failed: %s", e)-- # Self-heal the hermes-acp launcher for installs that predate it, so- # ACP hosts (Zed, JetBrains, Buzz) can resolve Hermes on PATH without- # a reinstall. No-op on Windows (the launcher migration below owns- # that) and when already present.- try:- _ensure_acp_launcher()- except Exception as e:- logger.debug("hermes-acp launcher self-heal failed: %s", e)-- # Migrate the Windows hermes launchers to the managed binary dir- # (the default Hermes root's bin, next to the managed uv) and repair- # them if they are missing. Earlier layouts put them inside the git- # checkout (hermes-agent\bin) or put venv\Scripts itself on PATH; the- # in-checkout copies were swept by this command's own pre-update- # autostash (git stash push --include-untracked) and, with- # --keep-stash (the desktop updater), never restored — `hermes`- # stopped resolving in every new terminal. Updates never run- # install.ps1, so this tail call is how existing installs reach the- # new layout. No-op on POSIX and on source checkouts (root is not- # the managed clone under the default Hermes root).- try:- from hermes_cli._install_repair import migrate_windows_bin_path-- migrate_windows_bin_path(_m().PROJECT_ROOT)- except Exception as e:- logger.debug("Windows bin launcher migration failed: %s", e)-- # Refresh the cua-driver binary used by the Computer Use toolset.- # The upstream installer is gated on supported platforms and on the- # binary already being on PATH, so this is a no-op for users who- # don't have it. Tying the refresh to ``hermes update`` gives users a- # predictable cadence (matches when they pull new agent code) without- # adding startup latency or a per-launch GitHub API call.- try:- refresh_cua_driver = True- try:- from hermes_cli.config import load_config- _update_cfg = (load_config() or {}).get("updates", {})- if isinstance(_update_cfg, dict):- refresh_cua_driver = bool(- _update_cfg.get("refresh_cua_driver", True)- )- except Exception as cfg_exc:- logger.debug("Could not read updates.refresh_cua_driver: %s", cfg_exc)-- if (- refresh_cua_driver- and sys.platform in ("darwin", "win32", "linux")- and shutil.which("cua-driver")- ):- from hermes_cli.tools_config import install_cua_driver-- print()- print("→ Refreshing cua-driver (Computer Use)...")- # require_confirmed_update: only run the (multi-minute,- # silent) upstream installer when the driver's native- # check-update verb positively reports a newer release.- # An indeterminate check (offline, rate-limited, old- # driver) keeps the installed version — `hermes update`- # must stay fast; `hermes computer-use install --upgrade`- # remains the force path. Windows also defers confirmed- # updates and contract repairs to that explicit command- # because the upstream installer may prompt for console/UAC- # consent that this hidden updater cannot provide.- install_cua_driver(- upgrade=True,- require_confirmed_update=True,- show_installer_progress=False,- )- except Exception as e:- logger.debug("cua-driver refresh failed: %s", e)-- # Write exit code *before* the gateway restart attempt.- # When running as ``hermes update --gateway`` (spawned by the gateway's- # /update command), this process lives inside the gateway's systemd- # cgroup. A graceful SIGUSR1 restart keeps the drain loop alive long- # enough for the exit-code marker to be written below, but the- # fallback ``systemctl restart`` path (see below) kills everything in- # the cgroup (KillMode=mixed → SIGKILL to remaining processes),- # including us and the wrapping bash shell. The shell never reaches- # its ``printf $status > .update_exit_code`` epilogue, so the- # exit-code marker file would never be created. The new gateway's- # update watcher would then poll for 30 minutes and send a spurious- # timeout message.- #- # Writing the marker here — after git pull + pip install succeed but- # before we attempt the restart — ensures the new gateway sees it- # regardless of how we die. The verified summary includes Desktop and- # SQLite-runtime health, so neither failure is reported as "0" to the- # gateway watcher (gateway/run.py).- if gateway_mode:- _write_gateway_update_exit_code(update_complete)-- gateway_fleet_restart_incomplete = False- gateway_restart_phase_errors: list[str] = []- # Snapshot of gateways running before we touch anything. Stays empty- # until we successfully import the probe and are about to stop/drain —- # so an exception raised before we touch any gateway keeps this empty- # (nothing to fail closed on), while a failure after we have stopped a- # discovered gateway lets the handler fail closed on an empty survivor- # probe rather than reporting a clean update (#78574).- _pre_restart_gateway_pids: list | None = []- # Declared outside the restart try/except below (and never reset- # to None) so it's always safe to read afterwards even if that- # block raises before reaching its own restart bookkeeping —- # needed to forward already-restarted units to- # ``_finish_dashboard_update_cleanup`` (review on #83595).- restarted_services: list = []- # Scope-qualified twin of ``restarted_services`` for systemd units:- # ``user/hermes-serve`` and ``system/hermes-serve`` are two different- # processes, and the abort-recovery child needs to know WHICH one was- # already settled. ``restarted_services`` itself keeps its bare-name- # vocabulary — the fleet probe, the receipt and the operator summary- # all read it (#92145 review).- restarted_scoped_units: set = set()- # Keep these restart bookkeeping collections defined even when the- # phase raises before its platform-specific imports initialize them.- # The abort recovery and the fleet reconciliation both consume the- # pre-update plan in that early-failure shape.- failed_or_stale_units: list = []- relaunched_profiles: list = []- externally_supervised_profiles: list = []- # Same outside-the-try treatment: the post-restart fleet version- # check consults killed_pids to decide whether to wait for- # freshly-restarted gateways to settle, and the phase's except- # path forwards it to the update receipt.- killed_pids: set = set()-- # Auto-restart ALL gateways after update.- # The code update (git pull) is shared across all profiles, so every- # running gateway needs restarting to pick up the new code.- #- # Purge stale cached Hermes modules FIRST: the import below pulls- # freshly-updated gateway source into this pre-update interpreter,- # and any already-cached sibling module (cli_output, status, ...)- # that the new source expects a new symbol from would otherwise- # ImportError and abort this whole phase (2026-08-20 field failure:- # new gateway.py ← stale cli_output missing line_input).- _m()._purge_stale_hermes_modules()- try:- from hermes_cli.gateway import (- is_macos,- supports_systemd_services,- _ensure_user_systemd_env,- find_gateway_pids,- find_profile_gateway_processes,- _prepare_profile_gateway_update_restart,- _get_service_pids,- _graceful_restart_via_sigusr1,- _wait_for_gateway_exit,- )- import signal as _signal-- def _wait_for_service_active(- scope_cmd_: list,- svc_name_: str,- timeout: float = 10.0,- ) -> bool:- """Poll ``systemctl is-active`` until the unit reports active.-- systemd's Stopped -> Started transition after a graceful exit- (or a hard restart) is not instantaneous; a one-shot check- races that window and falsely reports the unit as down.- Poll every 0.5s up to ``timeout`` seconds before giving up.- """- deadline = _time.monotonic() + max(timeout, 0.5)- while True:- try:- _verify = subprocess.run(- scope_cmd_ + ["is-active", svc_name_],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=5,- )- if _verify.stdout.strip() == "active":- return True- except (FileNotFoundError, subprocess.TimeoutExpired):- pass- if _time.monotonic() >= deadline:- return False- _time.sleep(0.5)-- def _service_restart_sec(- scope_cmd_: list,- svc_name_: str,- default: float = 0.0,- ) -> float:- """Read the unit's ``RestartUSec`` (RestartSec) in seconds.-- After a graceful exit-75, systemd waits ``RestartSec`` before- respawning the unit. Callers that poll for ``is-active``- must use a timeout >= ``RestartSec`` + transition slack, or- they'll give up *during* the cooldown window and wrongly- conclude the unit didn't relaunch.- """- try:- _show = subprocess.run(- scope_cmd_- + [- "show",- svc_name_,- "--property=RestartUSec",- "--value",- ],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=5,- )- except (FileNotFoundError, subprocess.TimeoutExpired):- return default- raw = (_show.stdout or "").strip()- # systemd emits values like "30s", "100ms", "1min 30s", or- # "infinity". Parse conservatively; on any miss return default.- if not raw or raw == "infinity":- return default- total = 0.0- matched = False- for part in raw.split():- for _suf, _mult in (- ("ms", 0.001),- ("us", 0.000001),- ("min", 60.0),- ("s", 1.0),- ):- if part.endswith(_suf):- try:- total += float(part[: -len(_suf)]) * _mult- matched = True- except ValueError:- pass- break- return total if matched else default-- _manage_cmd_cache: dict = {}-- def _resolve_manage_cmd(scope_: str, scope_cmd_: list, svc_name_: str):- """Resolve the command prefix for manage-units operations.-- Read-only systemctl calls (``is-active``, ``show``,- ``list-units``) work unprivileged, but manage-units verbs- (``reset-failed``, ``start``, ``restart``) on a *system*- service trigger a polkit ``org.freedesktop.systemd1.manage-units``- authentication prompt when run as a non-root user. That- interactive prompt runs inside our captured subprocess with a- 10-15s timeout — the user sees the prompt flash and "exit- directly" before they can answer, and the resulting- TimeoutExpired used to be swallowed silently.-- Strategy: if root, plain systemctl. If not root, try- non-interactive sudo (``sudo -n``) — first a blanket probe,- then a targeted ``systemctl reset-failed`` probe so a- least-privilege sudoers entry scoped to- ``systemctl ... hermes-gateway*`` also qualifies- (``reset-failed`` is an idempotent no-op we run before every- privileged restart anyway). If neither works, return None —- the caller must SKIP the restart (without draining the- gateway first!) and tell the user how to restart manually.- ``--no-ask-password`` guarantees polkit can never hang a- captured subprocess on this path.- """- if scope_ in _manage_cmd_cache:- return _manage_cmd_cache[scope_]- cmd = scope_cmd_ + ["--no-ask-password"]- if (- scope_ == "system"- and hasattr(os, "geteuid")- and os.geteuid() != 0 # windows-footgun: ok — systemd path, Linux-only- ):- sudo_cmd = ["sudo", "-n"] + scope_cmd_ + ["--no-ask-password"]- sudo_ok = False- try:- _probe = subprocess.run(- ["sudo", "-n", "true"],- capture_output=True,- timeout=5,- )- sudo_ok = _probe.returncode == 0- if not sudo_ok:- # Blanket sudo refused — a targeted sudoers entry- # (NOPASSWD for systemctl ... hermes-gateway*)- # may still allow the exact commands we need.- _probe = subprocess.run(- sudo_cmd + ["reset-failed", svc_name_],- capture_output=True,- timeout=5,- )- sudo_ok = _probe.returncode == 0- except (FileNotFoundError, subprocess.TimeoutExpired):- sudo_ok = False- cmd = sudo_cmd if sudo_ok else None- _manage_cmd_cache[scope_] = cmd- return cmd-- # Wait budget for graceful SIGUSR1 restarts. In-band restart- # may defer stop() until active turns finish- # (``restart_after_turn_timeout``, #77184) and then spend up to- # ``restart_drain_timeout`` inside stop(). Cover both phases so- # we don't fall back to a hard kill while the gateway is still- # patiently waiting for the requesting turn. On older systemd- # units without SIGUSR1 wiring this wait just times out and we- # fall back to ``systemctl restart`` (the old behaviour).- try:- from hermes_cli.gateway import _get_restart_exit_wait_budget-- _drain_budget = max(float(_get_restart_exit_wait_budget()), 45.0)- except Exception:- _drain_budget = 45.0-- failed_or_stale_units = []- killed_pids = set()- relaunched_profiles = []- externally_supervised_profiles = []-- # Record which gateways are running before any stop/drain, so a- # later failure that leaves the survivor probe empty can still be- # recognised as "a running gateway was stopped and did not come- # back" rather than "nothing was running" (#78574). Best-effort:- # if the probe itself raises, leave the snapshot as-is (the- # survivor probe's own None result already fails closed).- try:- _pre_restart_gateway_pids = list(find_gateway_pids(all_profiles=True))- except Exception:- _pre_restart_gateway_pids = None-- # --- Systemd services (Linux) ---- # Discover all hermes-gateway* units (default + profiles) plus- # hermes-serve* units (the Desktop app's backend, #83438).- if supports_systemd_services():- try:- _ensure_user_systemd_env()- except Exception:- pass-- for scope, scope_cmd in [- ("user", ["systemctl", "--user"]),- ("system", ["systemctl"]),- ]:- try:- result = subprocess.run(- scope_cmd- + [- "list-units",- "hermes-gateway*",- "hermes-serve*",- "--plain",- "--no-legend",- "--no-pager",- ],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=10,- )- except FileNotFoundError:- continue- except subprocess.TimeoutExpired as exc:- # Discovery timeout — skip this scope, keep the other.- print(- f" ⚠ systemctl timed out listing {scope}-scope "- f"gateway units ({exc.cmd if exc.cmd else 'unknown command'}). "- f"Check the gateway with: hermes gateway status"- )- continue-- def _restart_one_systemd_gateway_unit(svc_name: str) -> None:- # Check if active- check = subprocess.run(- scope_cmd + ["is-active", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=5,- )- if check.stdout.strip() != "active":- return-- # Resolve how we may run manage-units verbs- # (reset-failed/start/restart) for this scope.- # None ⇒ no non-interactive privilege path; we- # must avoid those verbs entirely or polkit will- # throw an interactive auth prompt inside our- # captured 10-15s subprocess (the user sees it- # flash and "exit directly" — reported June 2026).- _manage_cmd = _resolve_manage_cmd(- scope, scope_cmd, svc_name- )-- # Prefer a graceful SIGUSR1 restart so in-flight- # agent runs drain instead of being SIGKILLed.- # The gateway's SIGUSR1 handler calls- # request_restart(via_service=True) → drain →- # exit; systemd's Restart=always respawns the unit.- # hermes-serve has no such handler (it isn't- # gateway/run.py), so skip straight to the blunt- # restart below rather than sending it an unhandled- # signal and waiting out the drain budget for- # nothing.- _main_pid = 0- if _service_unit_supports_graceful_sigusr1_restart(svc_name):- try:- _show = subprocess.run(- scope_cmd- + [- "show",- svc_name,- "--property=MainPID",- "--value",- ],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=5,- )- _main_pid = int((_show.stdout or "").strip() or 0)- except (- ValueError,- subprocess.TimeoutExpired,- FileNotFoundError,- ):- _main_pid = 0-- _graceful_ok = False- if _main_pid > 0:- # Three-way triage (ancestor fire-and-forget- # #100179 / wedged escalation #81642 / normal- # graceful drain) — shared with the bare-process- # path below.- _graceful_ok = _drain_or_signal_gateway_for_update(- _main_pid, _drain_budget, svc_name- )-- if _graceful_ok:- # Gateway exited after a planned restart.- # ``Restart=always`` means systemd WILL respawn- # the unit — but only after- # ``RestartSec`` (default 60s on our unit- # file). That 60s wait is a crash-loop guard,- # and is the right default when the gateway- # dies unexpectedly. For a voluntary restart- # on update, it's dead time the user watches.- #- # Shortcut it: ``reset-failed`` + ``start``- # skips RestartSec entirely (we're manually- # initiating the unit, not waiting for- # systemd's auto-restart logic). Takes about- # as long as the process takes to come up- # (~1-3s on a warm box).- #- # If the unit is already active because- # RestartSec elapsed while we were draining,- # ``start`` is a no-op and we fall through to- # the poll below. Either way we collapse the- # 60s+ delay to a ~5s one.- #- # The shortcut needs manage-units privileges.- # Without them (system service, non-root, no- # passwordless sudo) skip it — systemd's own- # auto-restart still relaunches the unit after- # RestartSec, no privileges required.- if _manage_cmd is not None:- subprocess.run(- _manage_cmd + ["reset-failed", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=10,- )- subprocess.run(- _manage_cmd + ["start", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=15,- )- # Short poll: the gateway should be up- # within a few seconds now that we- # bypassed RestartSec.- if _wait_for_service_active(- scope_cmd,- svc_name,- timeout=10.0,- ):- restarted_services.append(svc_name)- return- # Passive poll: systemd's auto-restart fires- # after RestartSec regardless of privileges.- # This is the primary path when _manage_cmd is- # None, and the fallback when the explicit- # start didn't take.- _restart_sec = _service_restart_sec(- scope_cmd,- svc_name,- default=0.0,- )- _post_drain_timeout = max(- 10.0,- _restart_sec + 10.0,- )- if _manage_cmd is None and _restart_sec > 5.0:- print(- f" → {svc_name}: waiting for systemd "- f"auto-restart (~{int(_restart_sec)}s; "- "no root for an immediate restart)..."- )- if _wait_for_service_active(- scope_cmd,- svc_name,- timeout=_post_drain_timeout,- ):- restarted_services.append(svc_name)- return- # Process exited but wasn't respawned (older- # unit without Restart=on-failure or- # RestartForceExitStatus=75). Fall through- # to systemctl start/restart.- print(- f" ⚠ {svc_name} drained but didn't relaunch — forcing restart"- )-- # Forcing a restart requires manage-units- # privileges. Without a non-interactive path,- # running systemctl here would spawn a polkit- # auth prompt inside a captured 10-15s subprocess- # — it flashes and dies before the user can- # answer. Skip with clear instructions instead.- if _manage_cmd is None:- failed_or_stale_units.append(svc_name)- print(- f" ⚠ {svc_name} is a system service and restarting it needs root.\n"- f" Restart it manually to load the new version:\n"- f" sudo systemctl restart {svc_name}\n"- f" To let `hermes update` restart it automatically, allow\n"- f" passwordless sudo for systemctl, or run updates with sudo."- )- return-- # Fallback: blunt systemctl restart. This is- # what the old code always did; we get here only- # when the graceful path failed (unit missing- # SIGUSR1 wiring, drain exceeded the budget,- # restart-policy mismatch).- #- # Always `reset-failed` first. If systemd's own- # auto-restart attempts already parked the unit- # in a failed state (transient CHDIR / OOM /- # filesystem race after our drain + exit-75),- # a plain `systemctl restart` can wedge against- # the RestartSec backoff and leave the unit- # dead. Clearing the failed state first makes- # the restart idempotent. Mirrors the recovery- # path in `hermes gateway restart`- # (`systemd_restart()`) as of PR #20949.- subprocess.run(- _manage_cmd + ["reset-failed", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=10,- )- restart = subprocess.run(- _manage_cmd + ["restart", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=15,- )- if restart.returncode == 0:- # Verify the service actually survived the- # restart. systemctl restart returns 0 even- # if the new process crashes immediately.- if _wait_for_service_active(- scope_cmd,- svc_name,- timeout=10.0,- ):- restarted_services.append(svc_name)- else:- # Retry once — transient startup failures- # (stale module cache, import race) often- # resolve on the second attempt. Again- # clear any failed state first so the- # retry isn't blocked by the previous- # crash.- print(- f" ⚠ {svc_name} died after restart, retrying..."- )- subprocess.run(- _manage_cmd + ["reset-failed", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=10,- )- subprocess.run(- _manage_cmd + ["restart", svc_name],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=15,- )- if _wait_for_service_active(- scope_cmd,- svc_name,- timeout=10.0,- ):- restarted_services.append(svc_name)- print(f" ✓ {svc_name} recovered on retry")- else:- failed_or_stale_units.append(svc_name)- _scope_flag = "--user " if scope == "user" else ""- _sudo_hint = "sudo " if scope == "system" else ""- print(- f" ✗ {svc_name} failed to stay running after restart.\n"- f" Check logs: {_sudo_hint}journalctl {_scope_flag}-u {svc_name} --since '2 min ago'\n"- f" Recover manually:\n"- f" {_sudo_hint}systemctl {_scope_flag}reset-failed {svc_name}\n"- f" {_sudo_hint}systemctl {_scope_flag}restart {svc_name}"- )- else:- failed_or_stale_units.append(svc_name)- print(- f" ⚠ Failed to restart {svc_name}: {restart.stderr.strip()}"- )-- def _on_unit_timeout(svc_name: str, exc: subprocess.TimeoutExpired) -> None:- # Isolate the timeout to this unit and keep going- # (#68523). A scope-wide handler used to abort every- # later gateway and leave the fleet on mixed code.- failed_or_stale_units.append(svc_name)- print(- f" ⚠ systemctl timed out restarting {svc_name} "- f"({exc.cmd if exc.cmd else 'unknown command'}); "- f"continuing with remaining gateways"- )-- # Everything this scope appends to ``restarted_services``- # belongs to THIS systemd manager; qualify it before the- # next scope can append a same-named unit. ``finally`` so a- # phase abort mid-scope still carries the units it settled.- _scope_mark = len(restarted_services)- try:- _for_each_systemd_gateway_unit(- result.stdout,- process_unit=_restart_one_systemd_gateway_unit,- on_unit_timeout=_on_unit_timeout,- )- finally:- restarted_scoped_units.update(- f"{scope}/{name}"- for name in restarted_services[_scope_mark:]- )-- # --- Launchd services (macOS) ---- # Restart EVERY ai.hermes.gateway* LaunchAgent, not only the- # invoking profile's — parity with the systemd branch above- # (#41403). Per-label TimeoutExpired isolation happens inside.- if is_macos():- try:- _restart_macos_launchd_gateways(- restarted_services,- failed_or_stale_units,- _drain_budget,- )- except (FileNotFoundError, ImportError):- pass-- # --- Manual (non-service) gateways ---- # Kill any remaining gateway processes not managed by a service.- # Exclude PIDs that belong to just-restarted services so we don't- # immediately kill the process that systemd/launchd just spawned.- service_pids = _get_service_pids(all_profiles=True)- manual_pids = find_gateway_pids(- exclude_pids=service_pids, all_profiles=True- )- profile_processes = {- proc.pid: proc- for proc in find_profile_gateway_processes(exclude_pids=service_pids)- if proc.pid in manual_pids- }- # Profile gateways we could not arm a relaunch for. These must- # NOT be left running: their modules are the pre-update ones and- # every lazy import from here on mixes versions against the new- # code on disk (#88654). Handing them to the unmapped sweep- # below stops them and surfaces them in the "Stopped N manual- # gateway process(es) / Restart manually" summary, which is the- # contract already used for gateways with no profile mapping.- unrestartable_pids = set()- for pid, proc in profile_processes.items():- restart_mode = _prepare_profile_gateway_update_restart(- proc.profile, pid- )- if restart_mode is None:- # Previously a bare ``continue``: the gateway was neither- # relaunched nor stopped nor mentioned, so it kept serving- # from stale modules with no operator signal at all.- print(- f" ⚠ {proc.profile}: could not arm an automatic "- f"gateway restart for PID {pid} — stopping it instead "- "so it cannot keep running pre-update code"- )- unrestartable_pids.add(pid)- continue- # Prefer a graceful SIGUSR1 drain so in-flight agent runs- # finish before the watcher respawns the gateway. If the- # gateway doesn't support SIGUSR1 or doesn't exit within- # the drain budget, fall back to SIGTERM — the watcher- # still sees the exit and relaunches either way.- # Three-way triage (ancestor fire-and-forget #100179 /- # wedged escalation #81642 / normal graceful drain) — shared- # with the systemd path above. The helper announces the- # chosen path first: a drain wait can hold for the full- # budget per gateway with no other output, and on surfaces- # that stream update progress the silence reads as a hung- # update (#44515).- drained = _drain_or_signal_gateway_for_update(- pid, _drain_budget, proc.profile- )- if not drained:- try:- os.kill(pid, _signal.SIGTERM)- except (ProcessLookupError, PermissionError):- pass- # Wait for the old process to fully exit before the watcher- # spawns the new gateway. Telegram holds the previous- # getUpdates long-poll session open on its servers for up to- # ~30s after the client disconnects. If the new gateway- # connects before that window expires it receives a 409- # Conflict, which _handle_polling_conflict() recovers from- # via back-off retries — but a brief wait here reduces the- # chance of hitting that path at all, especially on fast- # machines where the watcher loop restarts in < 1s.- # We wait up to 5s for the process to exit (the OS-level- # close, not the Telegram server-side expiry), then let the- # watcher take over. The Telegram adapter's retry logic- # handles any remaining 409s if the server session is still- # live when the new gateway polls.- _wait_for_gateway_exit(timeout=5.0, force_after=None)- killed_pids.add(pid)- if restart_mode == "external-supervisor":- externally_supervised_profiles.append(proc.profile)- else:- relaunched_profiles.append(proc.profile)-- for pid in manual_pids:- if pid in profile_processes and pid not in unrestartable_pids:- continue- try:- os.kill(pid, _signal.SIGTERM)- killed_pids.add(pid)- except (ProcessLookupError, PermissionError):- pass-- if restarted_services or killed_pids:- print()- for svc in restarted_services:- print(f" ✓ Restarted {svc}")- if relaunched_profiles:- names = ", ".join(relaunched_profiles)- print(f" ✓ Restarting manual gateway profile(s): {names}")- if externally_supervised_profiles:- names = ", ".join(externally_supervised_profiles)- print(- " ✓ Handed gateway profile(s) back to their external "- f"supervisor: {names}"- )- unmapped_count = (- len(killed_pids)- - len(relaunched_profiles)- - len(externally_supervised_profiles)- )- if unmapped_count:- print(f" → Stopped {unmapped_count} manual gateway process(es)")- print(" Restart manually: hermes gateway run")- if unmapped_count > 1:- print(- " (or: hermes -p <profile> gateway run for each profile)"- )-- if failed_or_stale_units:- gateway_fleet_restart_incomplete = True- if gateway_mode:- _exit_code_path = get_hermes_home() / ".update_exit_code"- try:- _exit_code_path.write_text("1", encoding="utf-8")- except OSError:- pass- _warn_incomplete_gateway_fleet_restart(failed_or_stale_units)+def _current_branch_name(git_cmd, *, check: bool = False) -> str:+ """``rev-parse --abbrev-ref HEAD`` (literal "HEAD" when detached)."""+ return _git_run(git_cmd, ["rev-parse", "--abbrev-ref", "HEAD"], check=check).stdout.strip()- try:- from hermes_cli.update_receipt import record_gateway_restart-- record_gateway_restart(- restarted_services=restarted_services,- relaunched_profiles=relaunched_profiles,- externally_supervised_profiles=externally_supervised_profiles,- killed_pids=sorted(killed_pids),- failed_units=failed_or_stale_units,- incomplete=bool(failed_or_stale_units),- )- except Exception:- pass- if not restarted_services and not killed_pids:- # No gateways were running — nothing to do- pass+def _handle_update_called_process_error(+ e, args, gateway_mode: bool, had_desktop_app_before_update: bool) -> None:+ """Git/installer failure: ZIP-fallback when safe, else report and ``sys.exit(1)``."""+ stage = _format_update_failure_stage(e)+ if _should_zip_fallback_on_update_error(e):+ print(f"⚠ {stage}: {e}")+ print("→ Falling back to ZIP download...")+ print()+ desktop_build_ok = _update_via_zip(+ args, had_desktop_app_before_update=had_desktop_app_before_update)+ if gateway_mode:+ _write_gateway_update_exit_code(desktop_build_ok)+ else:+ print(f"✗ {stage}: {e}")+ _print_called_process_error_tail(e)+ if _called_process_error_is_python_dep_install(e):+ print(+ " The git update already finished. Re-downloading the source "+ "ZIP cannot fix a dependency install error and would overwrite local files.")+ if _m()._is_windows():+ print(" Retry through the venv interpreter:")+ print(+ ' venv\\Scripts\\python.exe -c '+ '"from hermes_cli.main import main; main()" update --yes')+ _finalize_receipt("failed", 'Update receipt finalize failed: %s')+ sys.exit(1)- # --- Post-restart survivor sweep ------------------------------ # Issue #17648: some gateways ignore SIGTERM (stuck drain,- # blocked I/O, PID dead but zombie). The detached profile- # watchers wait 120s for the old PID to exit — if it never- # does, no respawn happens and the user keeps hitting- # ImportError against a stale sys.modules. Give the- # graceful paths a brief window to complete, then SIGKILL- # any remaining pre-update PIDs so the watcher / service- # manager can relaunch with fresh code.- try:- _time.sleep(3.0)- _service_pids_after = _get_service_pids(all_profiles=True)- _surviving = find_gateway_pids(- exclude_pids=_service_pids_after,- all_profiles=True,- )- # Scope to PIDs we already tried to kill during this- # update (killed_pids). Anything new is a gateway that- # started AFTER our restart attempt — respecting user- # intent, we don't kill those.- _stuck = [pid for pid in _surviving if pid in killed_pids]- if _stuck:- print()- print(- f" ⚠ {len(_stuck)} gateway process(es) ignored SIGTERM — force-killing"- )- from gateway.status import (- get_process_start_time as _get_process_start_time,- terminate_pid as _terminate_pid,- )- for pid in _stuck:- try:- # Routes through taskkill /T /F on Windows,- # SIGKILL on POSIX — _signal.SIGKILL doesn't- # exist on Windows so the old raw os.kill call- # used to crash the entire update path.- _terminate_pid(- pid,- force=True,- expected_start_time=_get_process_start_time(pid),- )- except (ProcessLookupError, PermissionError, OSError):- pass- # Give the OS a beat to reap the processes so the- # watchers see them exit and respawn.- _time.sleep(1.5)- except Exception as _sweep_exc:- logger.debug("Post-restart survivor sweep failed: %s", _sweep_exc)-- except Exception as e:- logger.debug("Gateway restart during update failed: %s", e)- gateway_restart_phase_errors.append(str(e))- # An exception escaping the whole phase means the drain/restart- # output the user relies on never printed. Don't let that pass for- # a clean update: surface it and treat the fleet as stale unless we- # can positively prove no gateway is running (#78574).- #- # A positive-empty ``_surviving`` is only proof-of-safety when- # nothing was running before we touched anything. If a gateway was- # discovered pre-restart and none survive now, it was stopped and- # its replacement was never verified — the same fail-open contract- # this fix closes — so we must still fail closed on ``[]``.- _surviving = _surviving_gateway_pids_after_failed_restart()- _already_restarted_profiles = set(relaunched_profiles)- _already_restarted_profiles.update(externally_supervised_profiles)- for runtime in getattr(_pre_update_plan, "runtimes", ()) or ():- if getattr(runtime, "kind", None) != "gateway":- continue- profile = getattr(runtime, "profile", None)- if not isinstance(profile, str):- continue- if any(- _gateway_service_matches_profile(profile, service)- for service in restarted_services- ):- _already_restarted_profiles.add(profile)- _recovery_result = _recover_gateway_restart_after_abort(- _pre_update_plan,- gateway_mode=gateway_mode,- skip_profiles=_already_restarted_profiles,- skip_units=set(restarted_scoped_units),- )- _recovery_serve_units = _recovery_result.get("serve_units") or {}- _serve_units_failed = list(_recovery_serve_units.get("failed") or [])- # Deliberately NOT merged into ``restarted_services``: that list is- # the gateway phase's own vocabulary and feeds the fleet-probe- # expectation. Serve coverage lives in the recovery result and the- # receipt, where it can be read without changing gateway semantics.- # A serve/dashboard runtime that is still the SAME process the- # pre-update inventory saw is a live runtime on the pre-update- # code generation — the exact unsafe state of #92145, and the one- # the reporter hit through tui_gateway (hosted by `hermes serve`,- # which is not a gateway profile and which no `gateway restart`- # command can reach). Recovery may not report success while one- # is still there, and it must never kill one: a manual or- # Desktop-owned serve has no relaunch authority.- _stale_runtime_rows = _surviving_pre_update_serve_runtimes(- _pre_update_plan- )- _recovery_result["stale_runtimes"] = _stale_runtime_rows- # Only systemd-VERIFIED outcomes may claim supervisor coverage.- # A relaunch that merely exited 0 ("relaunch_attempted") was never- # observed by the code and must not clear the incomplete flag.- _recovery_verified = set(_recovery_result.get("verified") or [])- if _recovery_verified:- relaunched_profiles.extend(- profile- for profile in sorted(_recovery_verified)- if profile not in relaunched_profiles- )- _planned_gateway_runtimes = [- runtime- for runtime in getattr(_pre_update_plan, "runtimes", ()) or ()- if getattr(runtime, "kind", None) == "gateway"- and isinstance(getattr(runtime, "profile", None), str)- ]- _planned_gateway_profiles = {- runtime.profile for runtime in _planned_gateway_runtimes- }- _covered_gateway_profiles = (- _already_restarted_profiles | _recovery_verified- )- _recovery_complete = _abort_recovery_is_complete(- planned_gateway_profiles=_planned_gateway_profiles,- covered_gateway_profiles=_covered_gateway_profiles,- recovery_result=_recovery_result,- stale_runtime_rows=_stale_runtime_rows,- )- if _recovery_complete:- # The fresh child is the recovery terminal result. Leave the- # final fleet-version matrix below as the authoritative- # read-back before the update is declared successful.- gateway_fleet_restart_incomplete = False- elif (- _restart_phase_failure_is_incomplete(- _surviving, _pre_restart_gateway_pids- )- or _stale_runtime_rows- or _serve_units_failed- ):- gateway_fleet_restart_incomplete = True- _warn_gateway_restart_phase_aborted(e, _surviving)- _warn_stale_serve_runtimes(_stale_runtime_rows)- if gateway_mode:- _exit_code_path = get_hermes_home() / ".update_exit_code"- try:- _exit_code_path.write_text("1", encoding="utf-8")- except OSError:- pass- try:- from hermes_cli.update_receipt import record_gateway_restart-- record_gateway_restart(- restarted_services=restarted_services,- relaunched_profiles=relaunched_profiles,- externally_supervised_profiles=externally_supervised_profiles,- killed_pids=sorted(killed_pids),- failed_units=failed_or_stale_units,- incomplete=gateway_fleet_restart_incomplete,- phase_error=str(e),- fresh_recovery=_recovery_result,- )- except Exception:- pass- try:- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- except Exception as _windows_resume_exc:- gateway_fleet_restart_incomplete = True- gateway_restart_phase_errors.append(str(_windows_resume_exc))+def _finalize_receipt(status: str, debug_message: str) -> None:+ """Best-effort ``finalize_update_receipt(status)``; the receipt must never break an update."""+ with _best_effort(debug_message):+ from hermes_cli.update_receipt import finalize_update_receipt+ finalize_update_receipt(status)+++def _finish_already_up_to_date(+ git_cmd, branch: str, current_branch: str, _plan, *, assume_yes: bool, gateway_mode: bool,+ gw_input_fn, pre_update_snapshot_id, desktop_dir, had_desktop_app_before_update: bool,+ active_lazy_features, active_tool_dependencies, _windows_gateway_resume) -> None:+ """"Already up to date" path: restore stash/branch, repair the checkout, catch up the fleet.+ ``sys.exit(1)`` when the repair is incomplete (after gateway exit code + partial receipt)."""+ _invalidate_update_cache()++ # Restore stash and switch back if we moved. EXCEPTION: a parked branch verified clean ++ # fully merged stays on the target — re-parking on the stale branch recreates the incident.+ if _plan.auto_stash_ref is not None:+ _m()._restore_stashed_changes(+ git_cmd, _m().PROJECT_ROOT, _plan.auto_stash_ref, prompt_user=_plan.prompt_for_restore,+ input_fn=gw_input_fn)+ if _plan.parked_branch_switched:+ if _plan.switch_block_reason.startswith("unmerged:"):+ _count = _plan.switch_block_reason.split(":", 1)[1]print(- " ⚠ Windows gateway service restart incomplete: "- f"{_windows_resume_exc}"- )- if gateway_mode:- _exit_code_path = get_hermes_home() / ".update_exit_code"- try:- _exit_code_path.write_text("1", encoding="utf-8")- except OSError:- pass-- if isinstance(_windows_gateway_resume, dict):- # Feed Windows's own pause/resume outcome into the same- # relaunched_profiles bookkeeping the systemd/launchd restart- # phase populates, so the #91277 Phase 2 reconciliation below- # does not report a correctly-relaunched Windows gateway as- # "unaccounted" (a runtime the plan saw but no bookkeeping- # mentions — the reconciliation's blind-spot tripwire). A- # profile whose relaunch genuinely failed is intentionally- # left out of the token's list, so it still surfaces there.- # Best-effort: the restart-phase try/except above may have- # raised before relaunched_profiles was initialized, so this- # must never itself abort the update.- try:- for _win_profile in _windows_gateway_resume.get("relaunched_profiles") or []:- if _win_profile not in relaunched_profiles:- relaunched_profiles.append(_win_profile)- except Exception as _win_reconcile_exc:- logger.debug(- "Could not merge Windows relaunch outcome into fleet "- "reconciliation bookkeeping: %s",- _win_reconcile_exc,- )- windows_restarted = list(- _windows_gateway_resume.get("restarted_services") or []- )- for service_name in windows_restarted:- if service_name not in restarted_services:- restarted_services.append(service_name)- service_profiles = _windows_gateway_resume.get("service_profiles") or {}- for service_name in windows_restarted:- profile_name = service_profiles.get(service_name)- if profile_name and profile_name not in relaunched_profiles:- relaunched_profiles.append(profile_name)- pending_services = list(_windows_gateway_resume.get("services") or [])- for service_name in pending_services:- label = str(service_profiles.get(service_name) or service_name)- if label not in failed_or_stale_units:- failed_or_stale_units.append(label)-- try:- from hermes_cli.update_receipt import record_gateway_restart-- record_gateway_restart(- restarted_services=restarted_services,- relaunched_profiles=relaunched_profiles,- externally_supervised_profiles=externally_supervised_profiles,- killed_pids=sorted(killed_pids),- failed_units=failed_or_stale_units,- incomplete=(- gateway_fleet_restart_incomplete- or bool(failed_or_stale_units)- ),- phase_error="; ".join(gateway_restart_phase_errors) or None,- )- except Exception:- pass+ f" ✓ Checkout was parked on '{current_branch}' — switched back to {branch}; "+ f"{_count} unmerged commit(s) kept on '{current_branch}'.")+ else:+ print(f" ✓ Checkout was parked on '{current_branch}' (fully merged) — switched back to {branch}.")+ elif current_branch not in {branch, "HEAD"}:+ _git_run(git_cmd, ["checkout", current_branch])- # Warn if legacy Hermes gateway unit files are still installed.- # When both hermes.service (from a pre-rename install) and the- # current hermes-gateway.service are enabled, they SIGTERM-fight- # for the same bot token (see PR #11909). Flagging here means- # every `hermes update` surfaces the issue until the user migrates.- try:- from hermes_cli.gateway import (- has_legacy_hermes_units,- _find_legacy_hermes_units,- supports_systemd_services,- )+ current_checkout_complete = _repair_current_checkout(+ assume_yes=assume_yes, gateway_mode=gateway_mode,+ pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,+ had_desktop_app_before_update=had_desktop_app_before_update,+ active_lazy_features=active_lazy_features,+ active_tool_dependencies=active_tool_dependencies, upstream_checked=_plan.upstream_checked,+ _windows_gateway_resume=_windows_gateway_resume)+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ # A prior pull may still owe the fleet a restart; catch up here too, BEFORE the exit+ # gate so a partial outcome can't strand the fleet on stale code.+ # Catch up even on the "Already up to date" path — that early return is what left the gateway on stale+ # code for two days. Runs BEFORE the runtime-verification exit gate below: a vulnerable SQLite runtime+ # demotes the outcome to partial, but must not strand the fleet on stale code (#91277 fleet contract —+ # the pending-restart check always executes).+ _apply_pending_fleet_restart_catchup()+ if not current_checkout_complete:+ if gateway_mode:+ _write_gateway_update_exit_code(False)+ _finalize_receipt("partial", 'Update receipt finalize (current checkout) failed: %s')+ sys.exit(1)- if supports_systemd_services() and has_legacy_hermes_units():- print()- print("⚠ Legacy Hermes gateway unit(s) detected:")- for name, path, is_sys in _find_legacy_hermes_units():- scope = "system" if is_sys else "user"- print(f" {path} ({scope} scope)")- print()- print(" These pre-rename units (hermes.service) fight the current")- print(" hermes-gateway.service for the bot token and cause SIGTERM")- print(" flap loops. Remove them with:")- print()- print(" hermes gateway migrate-legacy")- print()- print(" (add `sudo` if any are in system scope)")- except Exception as e:- logger.debug("Legacy unit check during update failed: %s", e)-- # Restart a managed dashboard through systemd, or stop stale manual- # dashboard processes. Raw-killing a systemd-owned dashboard PID makes- # systemd treat it as a clean stop, leaving the Cloudflare origin dead.- # Preserve the safety rule above: a failed Node refresh leaves the- # currently running dashboard untouched.- #- # Forward the systemd units restarted above (includes hermes-serve*,- # #83438) so a Serve-only install's freshly restarted process isn't- # found and restarted again below (review on #83595).- _finish_dashboard_update_cleanup(- node_failures, already_restarted_units=set(restarted_services)- )- # Check if any pre-update serve/dashboard runtimes survived on- # pre-update code generations (#100479). This is the SUCCESS-path- # twin of the abort-recovery probe above: the restart phase only- # restarts units, so an sshd-spawned `serve --isolated` or a manual- # `hermes serve` (no unit) is left running its pre-update- # sys.modules graph — and its cron ticker keeps firing agent jobs- # that ImportError on every symbol added in the pulled range. Runs- # AFTER the dashboard cleanup so a manual dashboard that cleanup- # killed and respawned is (correctly) not a survivor. The rows also- # feed the plan-vs-execution reconciliation below, so a survivor is- # escalated (exit 1) instead of merely printed. ``None`` means the- # probe itself failed; the reconciliation then stays fail-closed.- _stale_serve_rows: "list | None" = None- try:- _stale_serve_rows = _surviving_pre_update_serve_runtimes(_pre_update_plan)- if _stale_serve_rows:- _warn_stale_serve_runtimes(_stale_serve_rows)- except Exception as _serve_warn_exc:- logger.debug("Failed to check for surviving serve runtimes: %s", _serve_warn_exc)+def _apply_pulled_update(+ git_cmd, branch, pre_pull_sha, _plan, opts, *, gateway_mode, is_fork, desktop_dir,+ had_desktop_app_before_update, pre_update_snapshot_id, _pre_update_plan,+ _windows_gateway_resume) -> None:+ """Post-pull phase: verify HEAD, sync Python/Node/web/Desktop, maintenance, fleet restart."""+ _invalidate_update_cache()+ post_pull_sha = _verify_head_after_pull(+ git_cmd, branch, pre_pull_sha, in_place_update=_plan.in_place_update,+ _windows_gateway_resume=_windows_gateway_resume)++ # Gateways still serve pre-pull modules until the restart phase; an interrupt before a+ # completed restart leaves this marker so the next update catches up even when git is+ # current. Distinct from ``.update-incomplete`` (venv/install repair).+ # See #95294.+ _write_fleet_restart_pending_marker(expected_sha=post_pull_sha or "")+ # Stale .pyc would ImportError on gateway restart when new source references new names.+ _sweep_bytecode_after_update(branch)++ if is_fork and branch == "main":+ _m()._sync_with_upstream_if_needed(+ git_cmd, _m().PROJECT_ROOT, assume_yes=opts.assume_yes, input_fn=opts.gw_input_fn)++ # .[all], falling back to base + extras individually so one broken extra doesn't strip+ # the rest; the ownership preflight refuses first on foreign-owned (sudo-pip) venv files.+ # PM dep phase (update_cmd_deps owner): ``pm.sync_venv(["all"], explicit=True)`` — no+ # pip/lazy_deps fallback — plus the node/web/desktop surfaces it owns, so the orchestrator+ # consumes its outcome instead of recomputing it.+ node_failures, desktop_build_ok = _sync_python_dependencies_after_pull(+ git_cmd, branch, pre_pull_sha, active_lazy_features=opts.active_lazy_features,+ active_tool_dependencies=opts.active_tool_dependencies,+ _windows_gateway_resume=_windows_gateway_resume, desktop_dir=desktop_dir,+ had_desktop_app_before_update=had_desktop_app_before_update)- print()- print("Tip: You can now select a provider and model:")- print(" hermes model # Select provider and model")-- # Phase 1 (#91277): post-update fleet version verification. Compare- # every live gateway's stamped code_sha against the freshly-updated- # checkout and surface any gateway still serving pre-update code —- # instead of assuming the restart phase worked (#88654, #69754).- _fleet_snapshot: list = []- try:- from hermes_cli.update_receipt import (- collect_fleet_versions,- print_fleet_version_matrix,- )+ print()+ print(f"✓ Code updated!{_branch_head_suffix(git_cmd, _m().PROJECT_ROOT)}")- # Cross-platform "we expected fleet rows" signal (#93406). The- # old (restarted_services or killed_pids) condition never fires- # on Windows: the pause/resume phase populates neither list, so- # a healthy resumed gateway yielded zero rows and exit 0.- _fleet_rows_expected = _m()._fleet_probe_expected_runtimes(- _pre_update_plan,- _pre_restart_gateway_pids,- _windows_gateway_resume,- restarted_services,- killed_pids,- )- # A brief settle window: freshly restarted/resumed gateways need- # a moment to rewrite gateway_state.json with their new identity.- # Skipped when the restart phase touched nothing (no gateways- # were running) — nothing to settle.- #- # On Windows the resume path relaunches the gateway DETACHED, and- # that process must boot before it stamps gateway_state.json or- # answers the control socket (a Telegram gateway reconnects its- # polling loop — ~10s). A single 2s sleep therefore races the- # gateway's own startup and reports "no rows" (exit 1) for a- # healthy resume, which then triggers a full retry that re-kills- # the gateway the first attempt just started. Poll a bounded- # window for the resumed gateway to publish its identity instead.- _fleet_snapshot = []- if _fleet_rows_expected:- _fleet_deadline = _time.monotonic() + 30.0- while True:- _time.sleep(2.0)- # Pass the pre-restart PID snapshot so a gateway the- # restart phase stopped WITHOUT a verified replacement- # shows as a DOWN row (exit 1) instead of silently- # producing no row at all.- _fleet_snapshot = collect_fleet_versions(- pre_restart_pids=_pre_restart_gateway_pids- )- # A "down" row here is the stale pre-restart record of a- # gateway whose detached replacement is still booting —- # not a confirmed failure. Keep polling until every- # resumed gateway has published (no "down" rows remain)- # or the deadline passes, so a slow second gateway can't- # be misread as down and re-trigger the retry loop.- if _fleet_snapshot and not any(- row.get("state") == "down" for row in _fleet_snapshot- ):- break- if _time.monotonic() >= _fleet_deadline:- break- else:- _fleet_snapshot = collect_fleet_versions(- pre_restart_pids=_pre_restart_gateway_pids- )- if print_fleet_version_matrix(_fleet_snapshot):- gateway_fleet_restart_incomplete = True- elif not _fleet_snapshot and _fleet_rows_expected:- # Fleet probe returned zero rows even though at least one- # gateway runtime was (or may have been) live pre-update —- # POSIX restart bookkeeping, the pre-restart PID snapshot,- # the pre-update plan inventory, or the Windows pause/resume- # token all count as that signal. Every failure path inside- # collect_fleet_versions() is swallowed via logger.debug(),- # so an empty list is indistinguishable from a healthy fleet- # in the current output. Treat it as verification failure- # so the receipt records "partial" and the exit code is 1- # (#93406).- print(- "\n⚠ Fleet version check returned no rows even though"- " gateway runtimes were expected — verification incomplete."- )- gateway_fleet_restart_incomplete = True- except Exception as _fleet_exc:- logger.debug("Fleet version verification failed: %s", _fleet_exc)-- # Plan-vs-execution reconciliation (#91277 Phase 2, restart via- # declared mechanism): every runtime the PLAN saw must be accounted- # for by the restart phase's bookkeeping. An unaccounted runtime is- # the silent-miss class (a platform branch re-discovered its own- # targets and skipped one the inventory knew about) — escalate it- # exactly like a STALE/DOWN fleet row.- _runtime_outcomes: list = []- try:- if _pre_update_plan is not None and _pre_update_plan.runtimes:- from hermes_cli.update_inventory import (- match_runtime_outcomes,- report_unaccounted_runtimes,- )-- _runtime_outcomes = match_runtime_outcomes(- _pre_update_plan,- restarted_services=restarted_services,- relaunched_profiles=relaunched_profiles,- externally_supervised_profiles=externally_supervised_profiles,- killed_pids=killed_pids,- failed_units=failed_or_stale_units,- # Serve/dashboard runtimes reconcile by incarnation- # liveness, not by the gateway's unit names (#100479).- stale_serve_pids=(- {row.get("pid") for row in _stale_serve_rows}- if _stale_serve_rows is not None- else None- ),- )- if report_unaccounted_runtimes(_runtime_outcomes):- gateway_fleet_restart_incomplete = True- try:- import hermes_cli.update_receipt as _ur-- if _ur._current is not None:- _ur._current.data["runtime_outcomes"] = _runtime_outcomes- except Exception:- pass- except Exception as _outcome_exc:- logger.debug("Runtime-outcome reconciliation failed: %s", _outcome_exc)+ update_complete = _run_post_update_maintenance(+ assume_yes=opts.assume_yes, gateway_mode=gateway_mode,+ pre_update_snapshot_id=pre_update_snapshot_id,+ had_desktop_app_before_update=had_desktop_app_before_update,+ node_failures=node_failures, desktop_build_ok=desktop_build_ok,+ pre_update_version=opts.pre_update_version)- try:- from hermes_cli.update_receipt import finalize_update_receipt-- _receipt_path = finalize_update_receipt(- (- "partial"- if gateway_fleet_restart_incomplete or not update_complete- else "success"- ),- fleet=_fleet_snapshot,- )- if _receipt_path is not None:- logger.info("Update receipt written: %s", _receipt_path)- except Exception as _receipt_exc:- logger.debug("Update receipt finalize failed: %s", _receipt_exc)-- if gateway_fleet_restart_incomplete:- # Code update itself succeeded, but at least one gateway still- # runs pre-update modules — surface that as a failed update so- # automation / operators do not treat the fleet as healthy.- # Leave ``fleet_restart_pending`` in place so the next- # ``hermes update`` still runs the catch-up restart.- sys.exit(1)- _clear_fleet_restart_pending_marker()+ # Exit code *before* the restart: under --gateway this process lives in the gateway's+ # systemd cgroup and the systemctl-restart fallback SIGKILLs it (KillMode=mixed), so+ # the marker would never land and the new gateway's watcher would time out spuriously.+ if gateway_mode:+ _write_gateway_update_exit_code(update_complete)- except _shim_quarantine_error_type() as e:- # Fail-closed shim contention (#87331): strict quarantine refused- # BEFORE any installer ran — defer via marker, exit 2, no ZIP.- _refuse_update_for_contended_shims(e)- except subprocess.CalledProcessError as e:- stage = _format_update_failure_stage(e)- if _should_zip_fallback_on_update_error(e):- print(f"⚠ {stage}: {e}")- print("→ Falling back to ZIP download...")- print()- desktop_build_ok = _update_via_zip(- args,- had_desktop_app_before_update=had_desktop_app_before_update,- )- if gateway_mode:- _write_gateway_update_exit_code(desktop_build_ok)- else:- print(f"✗ {stage}: {e}")- _print_called_process_error_tail(e)- if _called_process_error_is_python_dep_install(e):- print(- " The git update already finished. Re-downloading the source "- "ZIP cannot fix a dependency install error and would overwrite "- "local files."- )- if _m()._is_windows():- print(" Retry through the venv interpreter:")- print(- ' venv\\Scripts\\python.exe -c '- '"from hermes_cli.main import main; main()" update --yes'- )- try:- from hermes_cli.update_receipt import finalize_update_receipt+ _restart = _restart_gateway_fleet_after_update(_pre_update_plan, gateway_mode)+ _resume_windows_gateways_and_merge_outcome(_restart, _windows_gateway_resume, gateway_mode)+ _verify_fleet_after_update(+ _restart, _pre_update_plan=_pre_update_plan, _windows_gateway_resume=_windows_gateway_resume,+ node_failures=node_failures, update_complete=update_complete)- finalize_update_receipt("failed")- except Exception:- pass- sys.exit(1)-# --- Hoisted from the body of _cmd_update_impl (self-contained, no closure state) ---+def _cmd_update_impl(args, gateway_mode: bool):+ """Body of ``cmd_update`` — kept separate so the wrapper can always restore stdio even on+ ``sys.exit``. Self-lock deferral deliberately does NOT run here (pre-fetch it stranded users+ on the OLD checkout in an exit-2 loop); it runs right before the dependency sync."""+ opts = _resolve_update_options(args, gateway_mode)+ gw_input_fn, assume_yes = opts.gw_input_fn, opts.assume_yes-def _restart_phase_failure_is_incomplete(surviving, pre_restart_pids) -> bool:- """Whether an escaped gateway-restart-phase exception must fail the update.+ print("⚕ Updating Hermes Agent...")+ print()- Fail closed unless we can positively prove the fleet is safe:+ _pre_update_plan = _begin_update_receipt_and_plan(args)- * ``surviving is None`` — the survivor probe could not determine state- (typically the freshly-pulled ``hermes_cli.gateway`` no longer imports,- one of the ways the phase aborts). Assume stale.- * ``surviving`` non-empty — a gateway is still running pre-update code.- * ``surviving == []`` — nothing is running now. That is proof-of-safety- ONLY when nothing was running before we touched anything. If a gateway- was discovered pre-restart (``pre_restart_pids`` non-empty, or ``None``- meaning the pre-state could not be read), it was stopped without a- verified replacement, so we still fail closed (#78574).- """- if surviving is None or surviving:- return True- # surviving == []: safe only if we know nothing was running beforehand.- return pre_restart_pids is None or bool(pre_restart_pids)+ # Backup before any git/file mutation; the snapshot id (None if disabled/failed) feeds+ # the post-update cron-jobs safety net.+ pre_update_snapshot_id = _m()._run_pre_update_backup(args)+ _record_update_step(+ "pre_update_backup", pre_update_snapshot_id is not None,+ f"snapshot={pre_update_snapshot_id}" if pre_update_snapshot_id else "disabled or failed")+ _windows_gateway_resume = _m()._pause_windows_gateways_for_update()+ if _windows_gateway_resume:+ import atexit as _atexit+ _atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume)-def _fleet_probe_expected_runtimes(- pre_update_plan,- pre_restart_pids,- windows_resume_token,- restarted_services,- killed_pids,-) -> bool:- """Whether the post-update fleet probe should have produced rows.-- The zero-rows fail-open (#93406): ``collect_fleet_versions()`` swallows- every probe failure via ``logger.debug()`` and ``print_fleet_version_matrix([])``- early-returns ``False``, so an empty snapshot reads as \"healthy fleet\" and- the update exits 0. An empty snapshot is only proof-of-safety when NOTHING- says a gateway existed before the update. Any of these signals means at- least one runtime was (or may have been) live pre-update, so zero rows is- verification failure, not health:-- * ``restarted_services`` / ``killed_pids`` — the POSIX restart phase- touched live gateways.- * ``pre_restart_pids`` non-empty, or ``None`` (pre-state unreadable —- cannot prove nothing was running; same contract as- ``_restart_phase_failure_is_incomplete``, #78574).- * the pre-update plan inventoried ≥1 runtime.-- ``windows_resume_token`` is deliberately EXCLUDED (#93406 residual). The- pause/resume token is bookkeeping for ``_pause_windows_gateways_for_update``- / ``_resume_windows_gateways_after_update`` — it is not a runtime- inventory, and its entries do not correspond to rows- ``collect_fleet_versions()`` is capable of returning:-- * ``unmapped`` entries (Scheduled-Task gateways) never publish- ``gateway_state.json`` rows at all, and- * a paused profile gateway is resumed as a DETACHED relaunch that may not- republish its identity within the probe window.-- Counting the token therefore made ``_fleet_rows_expected`` True on every- Windows update that had paused a gateway, the probe's polling window ran- out with zero rows on a perfectly healthy update, and verification- reported "no rows … verification incomplete" and exited 1 after a long- silent wait. Expected-runtimes must key only on signals that map to rows- the probe can actually see; a genuinely live pre-update Windows gateway- is already covered by ``pre_restart_pids`` and the plan inventory. The- parameter stays in the signature so the call site keeps passing the token- (cheap, explicit, and the docstring is where the exclusion is explained).-- The same condition gates the 2.0s settle sleep: a freshly restarted- gateway needs the settle window to rewrite ``gateway_state.json``.-- Note this keys ONLY on zero-rows-despite-expected-runtimes. A non-empty- snapshot — including rows in ``unknown`` state — is still judged solely by- ``print_fleet_version_matrix``.- """- del windows_resume_token # excluded on purpose — see docstring (#93406)- if restarted_services or killed_pids:- return True- if pre_restart_pids is None or pre_restart_pids:- return True- try:- if pre_update_plan is not None and pre_update_plan.runtimes:- return True- except Exception:- pass- return False+ # Any venv python still running (typically the Desktop `hermes serve` backend) keeps .pyd+ # locked and would corrupt the sync; refuse rather than race (the app respawns a killed+ # backend). NOT bypassed by --force (desktop updater, shim guard only); --force-venv is.+ if _m()._is_windows() and not getattr(args, "force_venv", False):+ _clear_windows_venv_holders_or_exit(args, gateway_mode, _windows_gateway_resume)+ desktop_dir = _m().PROJECT_ROOT / "apps" / "desktop"+ had_desktop_app_before_update = _desktop_app_present(desktop_dir)-def _print_items(items, label, key, fallback_key=None):- if not items:- return- print(f" {label}:")- shown = items[:8]- for it in shown:- if isinstance(it, dict):- name = it.get(key) or (fallback_key and it.get(fallback_key)) or "?"- desc = (it.get("description") or "").strip()- else:- # Defensive: some callers/mocks pass bare name strings.- name = str(it)- desc = ""- if desc:- print(f" • {name} — {desc}")- else:- print(f" • {name}")- extra = len(items) - len(shown)- if extra > 0:- print(f" … and {extra} more")--def _wait_for_service_active(- scope_cmd_: list,- svc_name_: str,- timeout: float = 10.0,-) -> bool:- """Poll ``systemctl is-active`` until the unit reports active.+ use_zip_update, git_cmd, is_fork = _prepare_git_command()- systemd's Stopped -> Started transition after a graceful exit- (or a hard restart) is not instantaneous; a one-shot check- races that window and falsely reports the unit as down.- Poll every 0.5s up to ``timeout`` seconds before giving up.- """- deadline = _time.monotonic() + max(timeout, 0.5)- while True:+ if use_zip_update:try:- _verify = subprocess.run(- scope_cmd_ + ["is-active", svc_name_],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=5,- )- if _verify.stdout.strip() == "active":- return True- except (FileNotFoundError, subprocess.TimeoutExpired):- pass- if _time.monotonic() >= deadline:- return False- _time.sleep(0.5)+ desktop_build_ok = _update_via_zip(+ args, had_desktop_app_before_update=had_desktop_app_before_update)+ finally:+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ if gateway_mode:+ _write_gateway_update_exit_code(desktop_build_ok)+ return-def _service_restart_sec(- scope_cmd_: list,- svc_name_: str,- default: float = 0.0,-) -> float:- """Read the unit's ``RestartUSec`` (RestartSec) in seconds.-- After a graceful exit-75, systemd waits ``RestartSec`` before- respawning the unit. Callers that poll for ``is-active``- must use a timeout >= ``RestartSec`` + transition slack, or- they'll give up *during* the cooldown window and wrongly- conclude the unit didn't relaunch.- """try:- _show = subprocess.run(- scope_cmd_- + [- "show",- svc_name_,- "--property=RestartUSec",- "--value",- ],- capture_output=True,- text=True, encoding="utf-8", errors="replace",- timeout=5,- )- except (FileNotFoundError, subprocess.TimeoutExpired):- return default- raw = (_show.stdout or "").strip()- # systemd emits values like "30s", "100ms", "1min 30s", or- # "infinity". Parse conservatively; on any miss return default.- if not raw or raw == "infinity":- return default- total = 0.0- matched = False- for part in raw.split():- for _suf, _mult in (- ("ms", 0.001),- ("us", 0.000001),- ("min", 60.0),- ("s", 1.0),- ):- if part.endswith(_suf):- try:- total += float(part[: -len(_suf)]) * _mult- matched = True- except ValueError:- pass- break- return total if matched else default+ # Scoped fetch: a bare `git fetch origin` pulls thousands of branches and can stall.+ branch = _m()._resolve_update_branch(args)++ # Self-heal abandoned .git/*.lock files (crashed fetch) or the fetch fails "File exists".+ from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs+ cleared = clear_stale_git_locks(_m().PROJECT_ROOT)+ if cleared:+ print(" (removed stale git lock(s): %s)" % ", ".join(cleared))+ swept = clear_stale_tmp_packs(_m().PROJECT_ROOT)+ if swept:+ print(" (removed %d aborted-fetch pack temp file(s))" % len(swept))++ # Stable channel targets the newest release tag instead of origin/<branch>: the+ # current branch fast-forwards to the tag's commit, so the checkout keeps its+ # branch shape (no detached HEAD) and the next stable update ff-merges to the tag.+ target_ref = f"origin/{branch}"+ stable_tag = None+ if _stable_channel_active(args):+ print("→ Update channel: stable (tagged releases)")+ stable_tag, _stable_tag_sha = _resolve_latest_release_tag(git_cmd, _m().PROJECT_ROOT)+ if stable_tag is None:+ print("✗ No release tags found on origin. An update on the stable channel is not possible.")+ print(" Switch channels with: hermes update --set-channel main")+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ sys.exit(1)+ print(f"→ Latest release: {stable_tag}")+ target_ref = stable_tag++ # Surface autostashes left by earlier updates (--keep-stash, failed restores).+ # Surface autostash entries left behind by earlier updates (#63717 problem 6) — parked --keep-stash+ # runs and failed restores preserve the stash but nothing ever mentioned it again.+ _m()._warn_orphaned_update_autostashes(git_cmd, _m().PROJECT_ROOT)++ print("→ Fetching updates...")+ fetch_target = ["tag", stable_tag] if stable_tag else [branch]+ fetch_result = _git_run(git_cmd, ["fetch", "origin", *fetch_target], network=True)+ if fetch_result.returncode != 0:+ _print_fetch_failure(fetch_result.stderr)+ sys.exit(1)++ current_branch = _current_branch_name(git_cmd, check=True)+ _plan = _prepare_checkout_for_update(+ git_cmd, branch, current_branch, is_fork=is_fork, assume_yes=assume_yes,+ gateway_mode=gateway_mode, gw_input_fn=gw_input_fn, switch_branch=opts.switch_branch,+ target_ref=target_ref, _windows_gateway_resume=_windows_gateway_resume)+ commit_count = _plan.commit_count++ if commit_count == 0:+ _finish_already_up_to_date(+ git_cmd, branch, current_branch, _plan, assume_yes=assume_yes,+ gateway_mode=gateway_mode, gw_input_fn=gw_input_fn,+ pre_update_snapshot_id=pre_update_snapshot_id, desktop_dir=desktop_dir,+ had_desktop_app_before_update=had_desktop_app_before_update,+ active_lazy_features=opts.active_lazy_features,+ active_tool_dependencies=opts.active_tool_dependencies,+ _windows_gateway_resume=_windows_gateway_resume)+ return++ if commit_count > 0:+ print(f"→ Found {commit_count} new commit(s)")+ else:+ # Shallow, exact count unrecoverable — but the tips differ, so there IS an update.+ print("→ Updates available (commit count unknown on this shallow checkout)")++ print("→ Pulling updates...")+ pre_pull_sha = _pull_updates(+ git_cmd, branch, _plan.auto_stash_ref, prompt_for_restore=_plan.prompt_for_restore,+ gw_input_fn=gw_input_fn, discard_local_changes=opts.discard_local_changes,+ keep_stash=opts.keep_stash, target_ref=target_ref)+ _apply_pulled_update(+ git_cmd, branch, pre_pull_sha, _plan, opts, gateway_mode=gateway_mode,+ is_fork=is_fork, desktop_dir=desktop_dir,+ had_desktop_app_before_update=had_desktop_app_before_update,+ pre_update_snapshot_id=pre_update_snapshot_id, _pre_update_plan=_pre_update_plan,+ _windows_gateway_resume=_windows_gateway_resume)+ except _shim_quarantine_error_type() as e:+ # Strict quarantine refused BEFORE any installer ran — defer via marker, exit 2, no ZIP.+ # See #87331.+ _refuse_update_for_contended_shims(e)+ except subprocess.CalledProcessError as e:+ _handle_update_called_process_error(e, args, gateway_mode, had_desktop_app_before_update)+++# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----+# Names external plugins imported from this module before the Sep 2026 decomposition.+# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).+# The whole block is removed by reverting the commit that added it.+from typing import Optional # noqa: F401,E402+from datetime import datetime # noqa: F401,E402+import hashlib # noqa: F401,E402+import json # noqa: F401,E402+# ---- END PLUGIN-COMPAT ----diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex ff2bbb49212..42089fb1f2e 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -146,36 +146,11 @@ def _web_toolchain_roots(web_dir: Path) -> tuple[Path, ...]:return (web_dir, web_dir.parent)-def _ensure_venv_pip(pip_cmd: list, python_exe: str) -> None:- """Bootstrap pip back into the venv via ensurepip when ``pip --version`` fails- (some environments lose it); call before the editable install."""- from hermes_cli.update_cmd import _m- try:- subprocess.run(pip_cmd + ["--version"], cwd=_m().PROJECT_ROOT, check=True, capture_output=True)- except subprocess.CalledProcessError:- subprocess.run(- [python_exe, "-m", "ensurepip", "--upgrade", "--default-pip"], cwd=_m().PROJECT_ROOT, check=True)---def _upgrade_pip_before_lazy_refresh(- install_cmd_prefix: list[str], *, env: dict[str, str] | None = None) -> None:- """Upgrade pip before lazy refreshes: older pip can fail setuptools source builds and- leave a partially-written venv. Never raises.-- See #57828.- """- from hermes_cli.update_cmd import _m- try:- _m()._run_package_only_install(install_cmd_prefix + ["install", "--upgrade", "pip"], env=env)- except subprocess.CalledProcessError as exc:- logger.debug("pip upgrade before lazy refresh failed: %s", exc)--def _capture_active_lazy_features() -> list[str]:"""Snapshot active lazy backends before a managed runtime is replaced."""try:- from tools import lazy_deps- return lazy_deps.active_features()+ from pm.ensure import enabled_extras+ return enabled_extras()except Exception as exc:logger.debug("Could not snapshot active lazy features: %s", exc)return []@@ -191,152 +166,25 @@ def _capture_active_tool_dependencies() -> list[str]:return []-def _module_importable_in(target_python, module_name: str, env) -> bool:- """Probe ``find_spec(module_name)`` under *target_python*; an indeterminate probe reads as- missing (safer to repair than to assume it survived)."""- try:- probe = subprocess.run(- [str(target_python), "-c",- "import importlib.util,sys; raise SystemExit(0 if importlib.util.find_spec(sys.argv[1]) else 1)",- module_name],- capture_output=True, env=env, check=False)- return probe.returncode == 0- except (subprocess.SubprocessError, OSError):- return False-def _restore_active_tool_dependencies(- dependencies: list[str], install_cmd_prefix: list[str], *, env: dict[str, str] | None = None-) -> None:- """Restore allowlisted ``hermes tools`` dependencies (from a pre-rebuild probe) into a rebuilt- venv. Never raises: a failed optional tool must not block the update, but must be reported."""- from hermes_cli.update_cmd import _m- if not dependencies:- return- try:- from hermes_cli import tools_config- except Exception as exc:- logger.debug("Hermes Tools dependency restore skipped (import failed): %s", exc)- return-- target_python = _m()._resolve_install_target_python(install_cmd_prefix, env)- missing: list[tuple[str, tuple[str, ...]]] = []- for name in dependencies:- spec = tools_config.restorable_python_tool_dependency(name)- if spec is None:- continue- module_name, install_args = spec- if target_python is not None and _module_importable_in(target_python, module_name, env):- continue- missing.append((name, install_args))- if not missing:- return-- print()- print(f"→ Restoring {len(missing)} Hermes Tools dependency set(s)...")- restored: list[str] = []- failed: list[tuple[str, str]] = []- for name, install_args in missing:- try:- _m()._run_package_only_install(- install_cmd_prefix + ["install", *install_args, "--quiet"], env=env)- restored.append(name)- except Exception as exc:- # Best-effort: surface failures without aborting the update.- failed.append((name, str(exc)))+def _refresh_active_lazy_features(features: list[str] | None = None) -> bool:+ """Re-sync the venv's enabled extras against the (possibly new) uv.lock.- if restored:- print(f" ✓ {len(restored)} restored: {', '.join(restored)}")- for name, reason in failed:- print(f" ⚠ {name} failed to restore: {_clip(reason)}")---def _clip(reason: str, limit: int = 200) -> str:- """Bound a failure reason for the one-line report."""- return reason if len(reason) <= limit else reason[:limit] + "..."---def _refresh_active_lazy_features(- install_cmd_prefix: list[str] | None = None, *, env: dict[str, str] | None = None,- features: list[str] | None = None) -> bool:- """Refresh previously-activated lazy backends (cold ones untouched): the core install never- touches them, so a bumped :data:`LAZY_DEPS` pin would leave them stale forever. Returns True- when the venv is safe (refreshed / nothing active / import repair succeeded), False when a- failed lazy install left broken core imports repair couldn't fix. Never raises.-- See #57828.+ Extras live in the installed-state file and uv.lock owns every pin, so+ a post-update refresh is one sync_venv() call: it re-installs exactly+ the locked versions of everything enabled. Never raises."""- from hermes_cli.update_cmd import _mtry:- from tools import lazy_deps- except Exception as exc:- logger.debug("Lazy refresh skipped (import failed): %s", exc)- return True+ from pm.ensure import sync_venv- active = features- if active is None:- try:- active = lazy_deps.active_features()- except Exception as exc:- logger.debug("Lazy refresh skipped (active_features failed): %s", exc)- return True- if not active:+ sync_venv(features, explicit=True)return True-- print()- print(f"→ Refreshing {len(active)} active lazy backend(s)...")-- unexpected_failure = False- try:- results = (- lazy_deps.refresh_active_features(prompt=False) if features is None- else lazy_deps.restore_features(active))except Exception as exc:- # refresh_active_features is never-raise by contract; defend anyway.- print(f" ⚠ Lazy refresh failed unexpectedly: {exc}")- results = {}- unexpected_failure = True-- refreshed = [f for f, s in results.items() if s in {"refreshed", "restored"}]- current = [f for f, s in results.items() if s == "current"]- failed = [(f, s) for f, s in results.items() if s.startswith("failed:")]- skipped = [(f, s) for f, s in results.items() if s.startswith("skipped:")]-- if refreshed:- print(f" ↑ {len(refreshed)} refreshed: {', '.join(refreshed)}")- if current:- print(f" ✓ {len(current)} already current")- if skipped:- # Usually security.allow_lazy_installs=false; informational, not an error.- names = ", ".join(f for f, _ in skipped)- reason = skipped[0][1].split(": ", 1)[-1]- print(f" · {len(skipped)} skipped ({reason}): {names}")-- if not failed and not unexpected_failure:- return True-- for feature, status in failed:- print(f" ⚠ {feature} failed to refresh: {_clip(status.split(': ', 1)[-1])}")-- if install_cmd_prefix is None:- print(" ⚠ Lazy refresh failed; rerun `hermes update` once resolved.")+ print(f" ⚠ Extra re-sync failed: {exc}")+ print(" Rerun `hermes update` (or `hermes pm install`) once resolved.")return False- # Import-based recovery: metadata-only verifiers miss dist-info intact but import files- # wiped. Unavailable probes are indeterminate, not healthy — keep the lazy marker.- # See #57828.- status = _m()._repair_venv_via_import_probes(install_cmd_prefix, env=env)- if status == "repaired":- print(" Lazy backend(s) keep their previous version until refresh succeeds.")- return True- if status == "healthy":- print(" Lazy backend(s) keep their previous version; probed packages look intact.")- print(" Rerun `hermes update` once the upstream issue is resolved.")- return True- if status == "indeterminate":- print(" ⚠ Leaving `.lazy-refresh-incomplete` until import probes can confirm health.")- return False-def _refresh_active_memory_provider_dependencies() -> None:"""Refresh pip deps for the configured external memory provider: its bridge packages live in@@ -380,52 +228,6 @@ def _refresh_active_memory_provider_dependencies() -> None:print(f" ⚠ {provider} dependencies failed to refresh: {exc}")-def _is_android_python() -> bool:- from hermes_cli.update_cmd import _m- return _m().sys.platform == "android"---def _install_psutil_android_compat(- install_cmd_prefix: list[str], *, env: dict[str, str] | None = None) -> None:- """Install psutil on Android by patching its platform detection: setup gates Linux sources on- ``sys.platform.startswith('linux')`` but Termux reports ``'android'`` though the Linux path- compiles fine. Only this attempt's build tree is patched (stopgap until psutil ships a fix)."""- from hermes_cli.update_cmd import _m- import tempfile- import urllib.request- from hermes_cli.psutil_android import PSUTIL_URL, prepare_patched_psutil_sdist- with tempfile.TemporaryDirectory() as tmp:- archive = Path(tmp) / "psutil.tar.gz"- urllib.request.urlretrieve(PSUTIL_URL, archive)- src_root = prepare_patched_psutil_sdist(archive, Path(tmp))- _m()._run_install_with_heartbeat(- install_cmd_prefix + ["install", "--no-build-isolation", str(src_root)], env=env)---def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None:- """Best-effort uv bootstrap on Termux (official installer may fail: glibc vs bionic). Prefer a- PATH uv; else wheel-only ``pip install uv`` so the Rust crate is never source-built."""- from hermes_cli.update_cmd import _m- from hermes_cli.managed_uv import resolve_uv- existing = resolve_uv()- if existing:- return existing- if not _m()._is_termux_env():- return None- # Termux-packaged uv is on PATH but not the managed bin dir, so resolve_uv() misses it;- # prefer it over pip, which has no Android wheel and would source-build on a small device.- system_uv = shutil.which("uv")- if system_uv:- return system_uv- with suppress(Exception):- print(" → Termux detected: trying to install uv for faster dependency updates...")- result = subprocess.run(- pip_cmd + ["install", "uv", "--only-binary", ":all:"], cwd=_m().PROJECT_ROOT, check=False)- if result.returncode != 0:- return None- return resolve_uv() or shutil.which("uv")--def _npm_manifest_paths() -> tuple[Path, ...]:"""Manifests whose changes must defeat the update-skip. The lockfile alone isn't enough (apackage.json can be edited without running npm); workspaces come from the root ``workspaces``@@ -627,11 +429,29 @@ def _update_node_dependencies() -> list[str]:def _venv_core_imports_healthy() -> tuple[bool, str]:- """Probe the venv (in ITS interpreter — the updater may run under another Python) for core- imports, catching a half-updated venv that "Already up to date!" would otherwise never re-sync.+ """Probe the SELECTED dependency environment (in ITS interpreter — the updater may run under+ another Python) for core imports, catching a half-updated environment that "Already up to+ date!" would otherwise never re-sync.++ Selection goes through ``hermes_cli.runtime_paths`` — the stdlib-only selection module — not+ through the pm manager: the probe must run before any dependency of that environment has been+ imported. The legacy ``<repo>/venv`` target is superseded: the PM model stages a fresh+ generation under ``installs/<key>/environments/<gen>`` and commits the selection in+ ``facts.json`` (``pm.packages.VenvPackage.apply``), so the environment the update must judge+ (and the one the repair below rebuilds) is the SELECTED one, never a hardcoded repo-relative+ ``venv`` directory.+Returns ``(healthy, detail)``; never raises, unknown states report healthy."""from hermes_cli.update_cmd import _m- venv_dir = _m().PROJECT_ROOT / "venv"+ from hermes_cli import runtime_paths+ try:+ venv_dir = runtime_paths.selected_venv(_m().PROJECT_ROOT)+ except FileNotFoundError:+ venv_dir = runtime_paths.base_venv(_m().PROJECT_ROOT)+ except RuntimeError as exc:+ # An unreadable/invalid committed selection is a KNOWN-unhealthy state (the repair+ # flow below re-syncs and re-commits); never raise.+ return False, str(exc)venv_python = venv_python_path(venv_dir, windows=_m()._is_windows())if not venv_python.exists():# No venv: normal for a dev checkout (healthy), but on a MANAGED install (bootstrap@@ -669,138 +489,6 @@ def _venv_core_imports_healthy() -> tuple[bool, str]:return True, ""-# Native extensions that pin venv files once imported: if the updater holds one, Windows blocks-# REPLACE on the mapped ``.pyd`` and the sync dies with ``os error 5``. PyYAML's ``_yaml`` is in-# every CLI process, so the guard must be HONEST: fire only when the sync would actually REWRITE-# the dist, and only AFTER the code swap so a deferral leaves new code with just the install-# pending. Keys are ``sys.modules`` prefixes; values are ``(display name, PyPI dist)``.-# If the updater process itself has any of these loaded, the dependency sync below cannot rewrite the-# backing ``.pyd``/``.dll`` — Windows blocks REPLACE on a mapped image — and the update dies with ``os error-# 5`` between uninstall and reinstall, stranding the venv half-updated (#83569). ``cryptography`` is the-# canonical case: ``hermes_cli.main`` used to import it at startup while resolving external secret sources;-# ``PyYAML``'s ``_yaml`` C extension is loaded by every CLI process (config parsing). Keep this guard as-# defence-in-depth against future eager imports (new secret sources, plugins absorbed into core, refactors-# of the startup order) — but the guard must be HONEST (#86735/#86780/#86781: a preflight that fired on-# every run, before the fetch, re-bricked the exact flow it was meant to protect). Two honesty gates: 1. It-# only fires when the dependency sync would actually REWRITE the loaded distribution-# (``_dependency_sync_would_rewrite``): if the installed version already satisfies the on-disk pyproject-# pins, uv/pip will not touch the mapped ``.pyd``, so there is no lock to trip. 2. It runs AFTER the code-# swap (git pull / ZIP commit), immediately before the venv rewrite — so the on-disk pyproject is the NEW-# one (gate 1 compares against the right target) and a deferral no longer strands the user on the old-# checkout: the next launch's marker recovery completes the dependency install against the already-updated-# pyproject.-_SELF_LOCKING_NATIVE_MODULES: dict[str, tuple[str, str]] = {- "cryptography.hazmat.bindings._rust": ("cryptography (_rust.pyd)", "cryptography"),- "yaml._yaml": ("PyYAML (_yaml.pyd)", "pyyaml")}---def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:- """Whether the ``.[all]`` install would replace *dist_name*'s files, judged against every- applicable pin in on-disk ``pyproject.toml`` (base + extras). False: all pins satisfied;- True: pin unsatisfied or dist missing; None: undeterminable. Never raises. Callers treat- None as fail-OPEN — PyYAML is in every process, so deferring on uncertainty always fires.-- See #86735.- """- from hermes_cli.update_cmd import _m- try:- from importlib import metadata as _ilmd- installed = _ilmd.version(dist_name)- except Exception:- return True # not installed → the sync will definitely install it- try:- import tomllib- from packaging.requirements import Requirement- from packaging.utils import canonicalize_name- from packaging.version import Version- pyproject = _m().PROJECT_ROOT / "pyproject.toml"- data = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))- project = data.get("project") or {}- req_strings: list[str] = list(project.get("dependencies") or [])- for extra_reqs in (project.get("optional-dependencies") or {}).values():- req_strings.extend(extra_reqs or [])-- target = canonicalize_name(dist_name)- installed_v = Version(installed)- saw_pin = False- for req_str in req_strings:- try:- req = Requirement(req_str)- except Exception:- continue- if canonicalize_name(req.name) != target:- continue- if req.marker is not None and not req.marker.evaluate():- continue- saw_pin = True- if installed_v not in req.specifier:- return True- # Not pinned in pyproject: the resolver may still move it as a transitive — unknown.- return False if saw_pin else None- except Exception:- return None---def _detect_self_loaded_native_modules() -> list[str]:- """Display names of native venv extensions loaded into THIS process that the sync would rewrite.- Empty off Windows (POSIX keeps an unlinked inode usable). Modules whose installed version- already satisfies the pins are NOT reported — no swap at risk. Never raises.-- Returns display names (empty off Windows — POSIX lets a running process keep using an unlinked inode, so- self-locking is a Windows-only hazard). A loaded module whose installed version already satisfies the- on-disk pyproject pins is NOT reported: the dependency sync will not touch its files, so there is no- swap at risk (#86735 — the always-firing variant of this preflight bricked every Windows update).- """- from hermes_cli.update_cmd import _m- if not _m()._is_windows():- return []- # Defer ONLY on a CONFIRMED rewrite; unknown fails OPEN (PyYAML is in every process, so- # unknown-as-at-risk always fires). A missed deferral only yields the mid-sync os error 5- # that marker recovery already handles — far less harmful than an update that never runs.- return sorted({- display for prefix, (display, dist) in _SELF_LOCKING_NATIVE_MODULES.items()- if prefix in sys.modules and _m()._dependency_sync_would_rewrite(dist) is True})---def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:- """Defer the venv rewrite when THIS process holds something it must replace (runs after the- code swap, so a deferral leaves NEW code with only the install pending). Two hazards:- a mapped ``.pyd`` -> exit 2, next launch's marker recovery finishes; the ``hermes.exe`` shim- we run from -> every launch is the shim so the marker would defer forever: hand the- install to a child under the venv interpreter and exit 0.-- See #88838, #89599.- """- from hermes_cli.update_cmd import _m- locked = _m()._detect_self_loaded_native_modules()- if locked:- _m()._defer_update_for_self_lock(locked)- exit_code = 2- elif _m()._reexec_dependency_sync_off_windows_shim():- exit_code = 0- else:- return- if gateway_resume is not None:- _m()._resume_windows_gateways_after_update(gateway_resume)- sys.exit(exit_code)---def _defer_update_for_self_lock(loaded: list[str]) -> None:- """Explain + drop the update-incomplete marker (next fresh launch completes the install) when- the updater holds a lock the sync must replace; the caller exits 2."""- from hermes_cli.update_cmd import _m- print("✗ This updater process has already loaded native venv modules that")- print(" the dependency sync must replace:")- for name in loaded:- print(f" {name}")- print()- print(" On Windows a mapped extension cannot be replaced by the process")- print(" holding it. The code update has been applied; only the dependency")- print(" sync has been deferred: the next `hermes` launch will complete it")- print(" in a fresh process before anything imports these modules.")- _m()._write_update_incomplete_marker()--def _desktop_app_present(desktop_dir: Path) -> bool:"""Return whether a packaged or source Desktop build exists."""from hermes_cli.update_cmd import _m@@ -960,93 +648,97 @@ def _refuse_update_if_venv_foreign_owned(project_root) -> None:def _sync_python_dependencies_after_pull(git_cmd, branch, pre_pull_sha, *, active_lazy_features, active_tool_dependencies,- _windows_gateway_resume):- """Reinstall Python deps for the pulled checkout. Order matters: ownership preflight ->- self-lock deferral -> core marker -> ``.[all]`` -> bytecode sweep -> lazy/tool refresh (own- marker) -> memory-provider deps -> critical-import probe (warn only; stale bytecode self-heals)."""+ _windows_gateway_resume, desktop_dir, had_desktop_app_before_update):+ """Reinstall Python deps for the pulled checkout (PM flow). Order matters: ownership preflight ->+ core marker -> ``pm.sync_venv(["all"], explicit=True)`` (stages + commits a fresh generation+ environment; the live env of any running process is never mutated) -> module reload -> lazy/tool+ refresh (own marker) -> memory-provider deps -> critical-import probe (warn only) -> node deps ++ web + desktop rebuild. Returns ``(node_failures, desktop_build_ok)``."""from hermes_cli.update_cmd import (- _m, _pip_install_prefix, _sweep_bytecode_after_update, _validate_critical_modules_import,- _write_lazy_refresh_incomplete_marker, _write_update_incomplete_marker)- # Reinstall Python dependencies. Prefer .[all], but if one optional extra breaks on this machine, keep- # base deps and reinstall the remaining extras individually so update does not silently strip working- # capabilities. Ownership preflight (#83529): refuse before the first venv mutation if the venv contains- # foreign-owned files (sudo-pip residue) — the install below would die mid-mutation and brick the CLI.+ _m, _write_lazy_refresh_incomplete_marker, _write_update_incomplete_marker)+ # Reinstall Python dependencies. Prefer .[all], but if one optional extra+ # breaks on this machine, keep base deps and reinstall the remaining extras+ # individually so update does not silently strip working capabilities.+ #+ # Ownership preflight (#83529): refuse before the first venv mutation+ # if the venv contains foreign-owned files (sudo-pip residue) — the+ # install below would die mid-mutation and brick the CLI._refuse_update_if_venv_foreign_owned(_m().PROJECT_ROOT)- # Self-lock deferral: if THIS process holds a native extension the sync must rewrite, defer- # NOW (after the code swap) so only the install is pending for the next launch's marker.- _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)- # Drop the core-install breadcrumb BEFORE touching the venv so a killed install is finished- # by the next launch (``_recover_from_interrupted_install``). Lazy refresh uses its own marker._write_update_incomplete_marker()- deps_current = _editable_install_is_current(git_cmd, _m().PROJECT_ROOT, pre_pull_sha)- print(- "→ Python dependencies unchanged — skipping reinstall" if deps_current- else "→ Updating Python dependencies...")- from hermes_cli.managed_uv import ensure_uv, update_managed_uv- # `uv self update` if we already have a managed uv.- update_managed_uv()- uv_bin = ensure_uv()- pip_cmd = [sys.executable, "-m", "pip"]- if not uv_bin:- uv_bin = _ensure_uv_for_termux(pip_cmd)- if not uv_bin:- _ensure_venv_pip(pip_cmd, sys.executable)- install_prefix, lazy_env = _pip_install_prefix(uv_bin)- install_group = "all"- is_termux = _m()._is_termux_env(lazy_env)- if is_termux:- if lazy_env is not None:- lazy_env.pop("PYTHONPATH", None)- lazy_env.pop("PYTHONHOME", None)- install_group = "termux-all"- uv_note = "uv + " if uv_bin else ""- print(f" → Termux detected: using {uv_note}curated termux-all optional profile...")- if deps_current:- # Verification normally runs inside the skipped install; run it here so a wrong skip- # self-heals (both verifiers reinstall what they find missing).- _m()._verify_core_dependencies_installed(install_prefix, env=lazy_env, group=install_group)- _m()._verify_console_scripts_installed(install_prefix, env=lazy_env)- else:- if is_termux and _is_android_python():- print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")- _install_psutil_android_compat(install_prefix, env=lazy_env)- _m()._install_python_dependencies_with_optional_fallback(- install_prefix, env=lazy_env, group=install_group)-- # Clear the core breadcrumb before lazy refresh, which uses its own marker so a lazy- # failure can't be "healed" by a narrow core import probe.+ print("→ Syncing Python dependencies...")+ import pm++ try:+ pm.sync_venv(["all"], explicit=True)+ deps_synced = True+ except pm.InstallError as _sync_err:+ print(f" ✗ {_sync_err}")+ print(" Re-run `hermes update` (or `hermes pm install`) once resolved.")+ raise+++ # Core ``.[all]`` install finished. Clear the generic core breadcrumb+ # before the lazy-refresh phase — that phase uses its own marker so a+ # later lazy failure cannot be "healed" by clearing the core marker+ # based on a narrow 7-package import probe (#58004 review)._m()._clear_update_incomplete_marker()- # Still the old interpreter process: refresh caches/modules before lazy refresh imports- # newly-pulled modules. The install may have regenerated bytecode from build-cache- # copies — this second sweep catches those stragglers.- _sweep_bytecode_after_update(branch)+ # The update process is still the old Python interpreter process. Run+ # one final cache/module refresh immediately before lazy backend+ # refresh, which imports newly-pulled modules that may depend on fresh+ # symbols in hermes_constants or pm. The dependency install+ # above may also have regenerated bytecode from build-cache copies —+ # this second sweep catches those stragglers (#60242, #65240).+ removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)+ if removed:+ print(+ f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}"+ )+ _m()._record_bytecode_fingerprint()+ _m()._refresh_bootstrap_cache_scripts(branch)_m()._reload_updated_runtime_modules()- # Stale pip can fail source builds and leave partially-written packages.- # See #57828._write_lazy_refresh_incomplete_marker()- _m()._upgrade_pip_before_lazy_refresh(install_prefix, env=lazy_env)-- # Clear the lazy marker only when refresh/repair is confirmed healthy.- if _m()._refresh_active_lazy_features(install_prefix, env=lazy_env, features=active_lazy_features):+ lazy_ok = _m()._refresh_active_lazy_features(active_lazy_features)+ if lazy_ok:_m()._clear_lazy_refresh_incomplete_marker()else:print(" ⚠ Lazy-refresh recovery incomplete — run `hermes` again "- "to finish import-based venv repair.")+ "to finish import-based venv repair."+ )- _m()._restore_active_tool_dependencies(active_tool_dependencies, install_prefix, env=lazy_env)- # Heal memory-provider bridge packages last — the steps above may have stripped them.+ # Heal the active memory provider's bridge packages last — the core+ # reinstall + lazy refresh above may have stripped or downgraded+ # plugin.yaml-declared deps that aren't in extras (#53272, #70636)._m()._refresh_active_memory_provider_dependencies()- # Remaining import failures are real breakage. Warn only — never roll back: `cannot import- # name X` is also the stale-bytecode signature, which self-heals next launch.- import_ok, failing_module, import_error = _validate_critical_modules_import(_m().PROJECT_ROOT)+ # Everything that can legitimately produce a transient ImportError has+ # now run (bytecode sweep, dependency reinstall, lazy refresh), so a+ # module that still won't import is real breakage. Warn only — never+ # roll back here: `cannot import name X` is also the signature of the+ # stale-bytecode class (#6207, #60242), and the launch-time sweep in+ # _sweep_stale_bytecode_if_checkout_changed() self-heals that on the+ # next run. A destructive reset would undo a good update over a state+ # that fixes itself.+ import_ok, failing_module, import_error = _validate_critical_modules_import(+ _m().PROJECT_ROOT+ )if not import_ok:print()print(f" ⚠ {failing_module} still fails to import after updating:")print(f" {import_error}")print(" Run `hermes update` again — if it persists, reinstall:")print(" https://hermes-agent.nousresearch.com")++ node_failures = _update_node_dependencies()+ _m()._build_web_ui(_m().PROJECT_ROOT / "web")++ desktop_build_ok = _rebuild_desktop_after_update(+ desktop_dir,+ had_desktop_app_before_update=had_desktop_app_before_update,+ )++ print()+ return node_failures, desktop_build_okdiff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex f81bf0b4d8c..e42e3c71cbe 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -70,7 +70,7 @@ def _current_checkout_sha() -> str | None:"""Current on-disk checkout HEAD, or None if it cannot be resolved."""from hermes_cli.update_cmd import _capture_head_sha, _mtry:- from hermes_cli.build_info import get_code_identity+ from hermes_cli.version_info import get_code_identitysha = (get_code_identity(refresh=True) or {}).get("sha")return str(sha) if sha else Noneexcept Exception:diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.pyindex b479cb8373f..a29abb46a11 100644--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@ -28,9 +28,24 @@ def _git_ok(git_cmd, args, cwd, **kw) -> bool:return _git_stdout(git_cmd, args, cwd, **kw) is not None+def _git_run(git_cmd, args, cwd=None, *, check=False):+ """Run ``git_cmd + args`` and return the CompletedProcess.++ The updater's git runner: capture all output and decode as UTF-8 regardless of the+ Windows ANSI code page (#52649). ``check=True`` raises on non-zero exit.+ """+ return subprocess.run(+ git_cmd + list(args),+ cwd=cwd,+ capture_output=True,+ text=True, encoding="utf-8", errors="replace",+ check=check,+ )++def _git_stdout(git_cmd, args, cwd, **kw) -> Optional[str]:"""Stripped stdout of a successful ``_git_run``; ``None`` on non-zero exit or any exception."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runwith suppress(Exception):result = _git_run(git_cmd, args, cwd, **kw)if result.returncode == 0:@@ -52,7 +67,7 @@ def _prune_orphan_rescue_refs(those objects include a full working-tree snapshot (the autostash orphan commit), which can be multi-GBwhen the tree holds large stray files. See #87694."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runwith suppress(OSError):prefix = f"refs/hermes-update-backups/orphan-{branch}-"list_result = _git_run(git_cmd, ["for-each-ref", "--format=%(refname)", "--sort=refname", f"{prefix}*"], cwd)@@ -107,7 +122,7 @@ def _assess_parked_branch_switch(git_cmd: list[str], cwd: Path, current_branch:- (False, "disabled"|"dirty"|"unverifiable") — caller must NOT touch the branch. Dirty is thegenuinely unsafe case: uncommitted work riding an autostash across branches.A config read failure must not disable the safety checks: fall through with the default."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runtry:from hermes_cli.config import load_config_update_cfg = (load_config() or {}).get("updates", {})@@ -400,8 +415,9 @@ def _locate_real_git() -> Optional[Path]:invoked directly (#87876)."""candidates = [- Path(r"C:\Program Files\Git\mingw64\libexec\git-core\git.exe"),- Path(r"C:\Program Files (x86)\Git\mingw64\libexec\git-core\git.exe"),+ Path(base) / "Git" / arch / "libexec" / "git-core" / "git.exe"+ for base in (r"C:\Program Files", r"C:\Program Files (x86)")+ for arch in ("clangarm64", "mingw64", "mingw32")] + _portable_git_candidates()return next((c for c in candidates if c.exists() and _probe_fork_bomb([str(c)]) is False), None)@@ -424,7 +440,7 @@ def _ensure_non_trampoline_git(git_cmd: list) -> list:def _discard_lockfile_churn(git_cmd, repo_root):"""Restore ``package-lock.json`` files npm rewrote non-deterministically, so the update sees a clean treeinstead of autostashing every run. Only touches lockfiles whose package.json is NOT also dirty. Best-effort."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runwith suppress(Exception):diff = _git_run(git_cmd, ["diff", "--name-only"], repo_root)if diff.returncode != 0:@@ -452,7 +468,7 @@ def _normalize_managed_eol(git_cmd, repo_root):reuses its build-pinned ``install.ps1`` forever — so ``hermes update``, which ships with the checkoutitself, is the only path left that can fix them. See #67730."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_run# -c, not config: evaluate the tree as it WOULD look pinned, persisting nothing.probe = git_cmd + ["-c", "core.autocrlf=false"]diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex 85588ba3682..26fae54f83a 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -23,7 +23,7 @@ from hermes_cli.update_cmd_common import _best_effortlogger = logging.getLogger("hermes_cli.update_cmd")-_UPDATE_RUNTIME_RELOAD_MODULES = "hermes_constants", "tools.environments.local", "tools.lazy_deps"+_UPDATE_RUNTIME_RELOAD_MODULES = "hermes_constants", "tools.environments.local", "pm.extras"#: Package prefixes whose cached modules go stale when the checkout changes under this#: process; purged (not reloaded) so any LATER import chain resolves against fresh source.@@ -472,7 +472,8 @@ def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:clobbers pages. Holder scan ``None`` proceeds (gateways drained; refusing on unknown woulddisable auto-restore on non-Linux). Raises OSError if the copy fails."""- from hermes_cli.backup import _foreign_db_holder_pids, verify_sqlite_integrity+ from hermes_cli.backup import verify_sqlite_integrity+ from hermes_cli.backup_restore import _foreign_db_holder_pidsfrom hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_accessholders = _foreign_db_holder_pids(state_path)if holders:diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.pyindex 70be0cb7a00..26328a31b3c 100644--- a/hermes_cli/update_cmd_stash.py+++ b/hermes_cli/update_cmd_stash.py@@ -57,7 +57,7 @@ def _print_first_line(text: str) -> None:def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[str]:- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runstatus = _git_run(git_cmd, ["status", "--porcelain"], cwd, check=True)if not status.stdout.strip():return None@@ -94,7 +94,7 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[stdef _resolve_stash_selector(git_cmd: list[str], cwd: Path, stash_ref: str) -> Optional[str]:- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runstash_list = _git_run(git_cmd, ["stash", "list", "--format=%gd %H"], cwd, check=True)for line in stash_list.stdout.splitlines():selector, _, commit = line.partition(" ")@@ -114,7 +114,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:``git stash`` invisibly for weeks (#63717 problem 6). This prints a short notice naming the staleentries with recovery/cleanup guidance."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runtry:stash_list = _git_run(git_cmd, ["stash", "list", "--format=%gd %s"], cwd)if stash_list.returncode != 0:@@ -270,7 +270,7 @@ def _confirm_restore(stash_ref: str, input_fn) -> bool:def _apply_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> bool:"""``git stash apply``; False (tree reset, stash kept) on conflicts or any failure other than theundeletable-untracked class."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runprint("→ Restoring local changes...")restore = _git_run(git_cmd, ["stash", "apply", stash_ref], cwd)unmerged = _git_run(git_cmd, ["diff", "--name-only", "--diff-filter=U"], cwd) # conflicts can exist even on rc 0@@ -298,7 +298,7 @@ def _apply_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> bool:def _drop_restored_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> None:- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runstash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref)if stash_selector is None:print("⚠ Local changes were restored, but Hermes couldn't find the stash entry to drop.")@@ -317,9 +317,7 @@ def _drop_restored_stash(git_cmd: list[str], cwd: Path, stash_ref: str) -> None:def _restore_stashed_changes(git_cmd: list[str], cwd: Path, stash_ref: str, prompt_user: bool = False, input_fn=None,) -> bool:- from hermes_cli.update_cmd import (- _critical_module_import_failures, _git_untracked_paths, _restored_python_paths, _validate_python_files_syntax,- )+ from hermes_cli.update_cmd import _critical_module_import_failures, _git_untracked_paths, _restored_python_paths, _validate_python_files_syntaxif prompt_user and not _confirm_restore(stash_ref, input_fn):return Falsepreexisting_untracked = _git_untracked_paths(git_cmd, cwd)@@ -356,7 +354,7 @@ def _discard_stashed_changes(git_cmd: list[str], cwd: Path, stash_ref: str) -> bUnlike reset --hard + clean -fd this touches only what was stashed; ignored paths are never affected.Returns True if dropped, False on git failure (stash left in place)."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runstash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref)if stash_selector is None:print(diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 97deeed3c93..2c7832efba1 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -402,7 +402,8 @@ def _relaunch_stopped_serves(token: dict) -> None:"""Idempotent atexit relaunch of manual serves stopped by the venv guard.`pending` flips False on first invocation so explicit call + atexit registration cannot double-spawn."""- from hermes_cli.update_cmd import _m, _record_update_step+ from hermes_cli.update_cmd import _m+ from hermes_cli.update_receipt import record_step as _record_update_stepif not token.get("pending"):returntoken["pending"] = False@@ -1206,7 +1207,8 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatewRungs in order: leftover pausable gateways -> ledger orphaned backends -> orphaned Desktop backends ->ledger manual serve (relaunched at exit on the same bind) -> GUI hand-off leaks. Remaining holders arerefused (the sync would corrupt against a locked .pyd)."""- from hermes_cli.update_cmd import _m, _record_update_step, _refuse_gateway_ancestor_tree_kill+ from hermes_cli.update_cmd import _m, _refuse_gateway_ancestor_tree_kill+ from hermes_cli.update_receipt import record_step as _record_update_stepdef _resume_and_exit():_m()._resume_windows_gateways_after_update(_windows_gateway_resume)diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 01a98c62336..8c6e44f78e2 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -317,41 +317,30 @@ def _download_and_swap_zip(branch: str, zip_url: str) -> None:def _reinstall_python_deps_after_zip(active_tool_dependencies) -> None:- """Reinstall Python deps (uv preferred, pip fallback) and re-arm active tool deps."""- from hermes_cli.update_cmd import (- _ensure_uv_for_termux, _ensure_venv_pip, _m, _refuse_update_for_contended_shims, _shim_quarantine_error_type,- )+ """Reinstall Python deps via the PM sync authority (pm.sync_venv, no pip fallback).++ The PM sync stages a fresh generation environment and commits the selection — the live+ environment of the running process is never mutated, so no self-lock deferral guards this+ and no pip/uv restore re-arms tool deps into the superseded pre-swap environment+ (pm-clean-audit-49945b1402 final-gates item 9)."""+ from hermes_cli.update_cmd import _m++ import pm++ # Same raising-uv realize the current-checkout repair path uses: the update command+ # must SEE realization failures rather than silently fall back.+ try:+ pm.ensure("uv")+ except pm.InstallError as e:+ print(f"⚠ Managed uv unavailable: {e}")++ try:+ pm.sync_venv(["all"], explicit=True)+ except pm.InstallError as _sync_err:+ print(f" ✗ {_sync_err}")+ print(" Re-run `hermes update` (or `hermes pm install`) once resolved.")+ raise- from hermes_cli.managed_uv import ensure_uv, update_managed_uv- update_managed_uv() # keep managed uv current — runs `uv self update` if we already have one- uv_bin = ensure_uv()- pip_cmd = [_m().sys.executable, "-m", "pip"]- if not uv_bin:- uv_bin = _ensure_uv_for_termux(pip_cmd)- if uv_bin:- # Same UV-env isolation as the main update path: a user-level UV_PYTHON_INSTALL_DIR / UV_PYTHON- # from unrelated software must not steer which interpreter uv resolves here.- from hermes_cli.managed_uv import managed_python_env- uv_env = managed_python_env()- uv_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")- if _m()._is_termux_env(uv_env):- uv_env.pop("PYTHONPATH", None)- uv_env.pop("PYTHONHOME", None)- try:- _m()._install_python_dependencies_with_optional_fallback([uv_bin, "pip"], env=uv_env)- except _shim_quarantine_error_type() as _sqe:- # Runs inside the ZIP-fallback error handler, so cmd_update's boundary except cannot catch- # it — refuse here with the same defer-via-marker contract.- # See #87331.- _refuse_update_for_contended_shims(_sqe)- install_prefix, install_env = [uv_bin, "pip"], uv_env- else:- # sys.executable -m pip avoids PEP 668 'externally-managed-environment' errors.- _ensure_venv_pip(pip_cmd, _m().sys.executable)- _m()._install_python_dependencies_with_optional_fallback(pip_cmd)- install_prefix, install_env = pip_cmd, None- _m()._restore_active_tool_dependencies(active_tool_dependencies, install_prefix, env=install_env)- # Parity with git-pull path: heal the active memory provider's bridge packages after the reinstall._m()._refresh_active_memory_provider_dependencies()@@ -359,11 +348,19 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo"""Update via ZIP archive; used on Windows when git file I/O is broken (antivirus / NTFS filterdrivers causing 'Invalid argument'). Returns ``False`` when a Desktop rebuild ran and failed."""from hermes_cli.update_cmd import (- _finish_dashboard_update_cleanup, _m, _print_bundled_skills_sync_report, _print_curator_first_run_notice,- _print_curator_recent_run_notice, _print_update_summary, _read_project_version, _rebuild_desktop_after_update,- _sweep_bytecode_after_update, _update_node_dependencies, _validate_critical_modules_import,+ _finish_dashboard_update_cleanup,+ _m,+ _print_curator_first_run_notice,+ _print_curator_recent_run_notice,+ _print_update_summary,+ _read_project_version,+ _rebuild_desktop_after_update,+ _update_node_dependencies,+ _validate_critical_modules_import,_verify_and_restore_state_dbs_post_update,)+ from hermes_cli.update_cmd_maint import _print_bundled_skills_sync_report+ from hermes_cli.update_cmd_maint import _sweep_bytecode_after_updateactive_tool_dependencies = _m()._capture_active_tool_dependencies()pre_update_version = _read_project_version() # snapshot before files are replaced, for the completion line# The static archive would silently ignore --branch — the exact silent-divergence bug it exists to@@ -381,12 +378,6 @@ def _update_via_zip(args, *, had_desktop_app_before_update: bool = False) -> boo_abort_zip_update_if_dirty_tree()_download_and_swap_zip(branch, f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip")_sweep_bytecode_after_update(branch)- # Self-lock deferral: the code swap is committed; defer only the dependency sync when this process- # holds a native extension the sync must rewrite.- # Reinstall Python dependencies. Prefer .[all], but if one optional extra breaks on this machine, keep- # base deps and reinstall the remaining extras individually so update does not silently strip working- # capabilities. See #86735.- _m()._abort_dependency_sync_if_self_locked()print("→ Updating Python dependencies...")_reinstall_python_deps_after_zip(active_tool_dependencies)# Verify the tree imports (catches the parse-OK-but-skewed tree an interrupted copy leaves). Runsdiff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.pyindex 912d66dcc3c..d20eaaa6c84 100644--- a/hermes_cli/update_inventory.py+++ b/hermes_cli/update_inventory.py@@ -237,7 +237,7 @@ def collect_runtime_inventory() -> UpdatePlan:plan = UpdatePlan()_collect_install_shape(plan)with _probe("Code-identity probe"):- from hermes_cli.build_info import get_code_identity+ from hermes_cli.version_info import get_code_identityidentity = get_code_identity(refresh=True)plan.expected_sha = identity.get("sha")diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex da1ad20afa5..c4a93a6fd23 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -54,7 +54,7 @@ def _utc_now_iso() -> str:def _code_identity(refresh: bool = False) -> dict[str, Any]:"""Running-code identity, or ``{}`` when the probe fails."""with suppress(Exception):- from hermes_cli.build_info import get_code_identity+ from hermes_cli.version_info import get_code_identityreturn get_code_identity(refresh=refresh) or {}return {}diff --git a/hermes_cli/voice.py b/hermes_cli/voice.pyindex cd2cb232035..7f7a7d6fe10 100644--- a/hermes_cli/voice.py+++ b/hermes_cli/voice.py@@ -109,13 +109,8 @@ def format_voice_record_key_for_status(raw: Any) -> str:return prefix + key[0].upper() + key[1:]-from tools.voice_mode import (- create_audio_recorder,- is_voice_stop_phrase,- is_whisper_hallucination,- play_audio_file,- transcribe_recording,-)+from tools.voice_mode_transcript import is_voice_stop_phrase, is_whisper_hallucination+from tools.voice_mode import create_audio_recorder, play_audio_file, transcribe_recordinglogger = logging.getLogger(__name__)diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 5c490a32e06..94345b1baf2 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -150,31 +150,62 @@ def _step(job: Dict[str, Any], phase: str, detail: str) -> None:def _finish(job: Dict[str, Any], detail: str) -> None:+ # The worker publishes terminal status after releasing its resources._step(job, "done", detail)- job["status"] = "done"def _spawn_job(job: Dict[str, Any], name: str, body: Callable[[], None], *, fail_msg: str | None = None,- on_exit: Callable[[], None] | None = None, download_label: str | None = None) -> None:- """Run ``body`` on a daemon thread; an exception marks the job errored (warning ``fail_msg`` when- given); ``on_exit`` always runs last. ``download_label`` = download job: finishes as "<label> ready"- and bounces the router to pick the file up."""+ on_exit: Callable[[], None] | None = None, download_label: str | None = None,+ resumable: bool = False) -> None:+ """One worker per job. Pauses retain ownership; terminal outcomes release it."""+ guard = threading.Lock()+def _run():+ status = "done"try:body()if download_label is not None:_finish(job, f"{download_label} ready")_refresh_runtime("post-download runtime refresh skipped")+ except DownloadPaused:+ status = "paused"except Exception as exc: # noqa: BLE001if fail_msg:logger.warning(fail_msg, exc)- job["status"] = "error"+ status = "error"job["error"] = str(exc)finally:+ try:+ if status != "paused":+ _RUNNING.pop(job["job_id"], None)+ if on_exit is not None:+ on_exit()+ finally:+ job["status"] = status+ guard.release()++ def start(*, initial: bool = False) -> bool:+ if not guard.acquire(blocking=False):+ return False+ if not initial and job["status"] != "paused":+ guard.release()+ return False+ job["status"] = "running"+ job["error"] = None+ try:+ threading.Thread(target=_run, daemon=True, name=name).start()+ except Exception:+ _RUNNING.pop(job["job_id"], None)if on_exit is not None:on_exit()+ job["status"] = "error"+ guard.release()+ raise+ return True- threading.Thread(target=_run, daemon=True, name=name).start()+ if resumable:+ _RUNNING[job["job_id"]] = {"resume": start}+ start(initial=True)# ── runtime / router plumbing ────────────────────────────────@@ -399,8 +430,10 @@ def _download_plan(entry, variant) -> list:def _run_download_plan(job: Dict[str, Any], plan: list, label: str) -> None:"""Download every missing file in ``plan`` via pm.downloader (one resumableDownload per job); already-present files count toward progress without a- transfer. The live handle is kept OFF the job dict (which stays- JSON-serializable for the poll route) under _RUNNING."""+ transfer. Raises DownloadPaused straight through: the caller's worker+ parks the job — the sequence must never advance past a pause. Handle+ lifecycle (dl registration, resume handle, _RUNNING cleanup) belongs to+ _spawn_job, not here."""_step(job, "downloading", f"{label} — {_human_gb(sum(p[2] for p in plan))}")done_before = 0for url, dest, size in plan:@@ -409,7 +442,6 @@ def _run_download_plan(job: Dict[str, Any], plan: list, label: str) -> None:job["phase"] = "downloading"done_before += sizejob["done_bytes"] = done_before- _RUNNING.pop(job["job_id"], None)def _download_job(job: Dict[str, Any], plan) -> None:"""Run a plan of (url, dest, size) downloads as ONE resumable Download.@@ -420,8 +452,10 @@ def _download_job(job: Dict[str, Any], plan) -> None:hash by design: catalog sizes may lag an upstream re-upload, socompleteness is judged by the downloader against the server's declaredtotal, never the catalog. On pause the downloader raises- DownloadPaused; the job is marked 'paused' with its partials intact- for a later resume.+ DownloadPaused and this propagates to the caller: the worker parks the+ job 'paused' with its partials intact for a later resume. The live+ handle is kept OFF the job dict (which stays JSON-serializable for the+ poll route) under _RUNNING."""dl = Download([Source(url, dest) for url, dest, _ in plan])_RUNNING.setdefault(job["job_id"], {})["dl"] = dl@@ -433,15 +467,10 @@ def _download_job(job: Dict[str, Any], plan) -> None:try:dl.run(progress=tick)- except DownloadPaused:- job["status"] = "paused"- # Do NOT re-raise: _spawn_job's except would mark the job 'error'.- # Paused is a terminal state the poll route reports as-is.finally:_RUNNING.get(job["job_id"], {}).pop("dl", None)-def _loaded_models(running: Dict[str, Any]) -> "tuple[Dict[str, str], Dict[str, Any]]":"""Resident models right now, plus how each is placed (granted window from the child, spill facts fromthe preset decision) — the difference between 'fast' and 'why is my CPU busy', so it must be inspectable.@@ -732,30 +761,13 @@ async def local_models_download(body: ModelDownloadBody):job["total_bytes"] = sum(p[2] for p in plan)def _run():- try:- job["phase"] = "downloading"- job["detail"] = f"{entry.display_name} — {_human_gb(job['total_bytes'])}"- _download_job(job, plan)- job["phase"] = "done"- job["status"] = "done"- job["detail"] = f"{entry.display_name} ready"- try:- from hermes_cli.local_runtime.bootstrap import refresh_local_runtime- refresh_local_runtime()- except Exception: # noqa: BLE001- logger.debug("post-download runtime refresh skipped", exc_info=True)- except DownloadPaused:- pass # status already "paused"; partials kept for resume- except Exception as exc: # noqa: BLE001- logger.warning("model download failed: %s", exc)- job["status"] = "error"- job["error"] = str(exc)- finally:- if job["status"] != "paused":- _RUNNING.pop(job["job_id"], None)+ job["phase"] = "downloading"+ job["detail"] = f"{entry.display_name} — {_human_gb(job['total_bytes'])}"+ _download_job(job, plan)+ _finish(job, f"{entry.display_name} ready")+ _refresh_runtime("post-download runtime refresh skipped")- _RUNNING[job["job_id"]] = {"resume": _run, "dl": None}- threading.Thread(target=_run, daemon=True, name="lr-model-download").start()+ _spawn_job(job, "lr-model-download", _run, fail_msg="model download failed: %s", resumable=True)return {"job_id": job["job_id"], "model_id": variant.model_id}@@ -783,8 +795,7 @@ async def local_models_download_resume(body: JobIdBody):resume = running.get("resume")if resume is None:return {"ok": True, "resumed": False}- threading.Thread(target=resume, daemon=True, name="lr-model-download-resume").start()- return {"ok": True, "resumed": True}+ return {"ok": True, "resumed": resume()}@router.delete("/api/local-models/models/{model_id}")@@ -856,7 +867,8 @@ async def local_models_quickstart(body: QuickstartBody):_assign_default(job, variant.model_id)_finish(job, f"{entry.display_name} is ready — new chats use it")- _spawn_job(job, "lr-quickstart", _run, fail_msg="quickstart failed: %s", on_exit=_QUICKSTART_LOCK.release)+ _spawn_job(job, "lr-quickstart", _run, fail_msg="quickstart failed: %s",+ on_exit=_QUICKSTART_LOCK.release, resumable=True)return {"job_id": job["job_id"], "model_id": entry.id, "display_name": entry.display_name,"needs_runtime": need_runtime, "needs_download": need_download, "download_bytes": download_bytes}diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.pyindex c1da206ac21..6538ae9b779 100644--- a/hermes_cli/web_routers/memory_providers.py+++ b/hermes_cli/web_routers/memory_providers.py@@ -329,30 +329,58 @@ def _command_result(}-def _install_memory_provider_pip_dependencies(dependencies: List[str]) -> List[Dict[str, Any]]:+def _install_memory_provider_pip_dependencies(name: str, dependencies: List[str]) -> List[Dict[str, Any]]:if not dependencies:return []missing = [dep for dep in dependencies if not _dependency_importable(dep)]if not missing:return [_command_result(kind="pip", name=", ".join(dependencies), status="already_installed")]- # Route through the lazy-install pipeline rather than pip against- # sys.executable: on hosted/immutable images the agent venv is sealed- # read-only and installs must go to HERMES_LAZY_INSTALL_TARGET, which- # install_specs also activates on sys.path so the recheck sees the packages.- name = ", ".join(missing)+ # Route through pm's venv sync — the ONE install authority (uv.lock owns the+ # pins; no pip against sys.executable, and tools.lazy_deps is deleted).+ # Extras come from the existing ``_provider_extras`` owner: the declared+ # plugin.yaml ``extra:`` — or, for legacy third-party declared python+ # dependencies, it materializes the specs into a generated pyproject and+ # admits the provider dir into the workspace union BEFORE the post-config+ # selection; one sync then carries the deps.+ target = ", ".join(missing)+ manifest = _memory_provider_manifest(name)+ command = "hermes pm install"try:- from tools.lazy_deps import install_specs- outcome = install_specs(missing, timeout=240)+ import pm++ from hermes_cli.memory_setup import _provider_extras+ from plugins.memory import find_provider_dir++ plugin_dir = find_provider_dir(name)+ extras = _provider_extras(name, manifest, plugin_dir=plugin_dir)+ if extras:+ pm.sync_venv(extras, explicit=True)+ elif plugin_dir is not None and any(+ manifest.get(k) for k in ("pip_dependencies", "python_dependencies")+ ):+ # Legacy declared deps with no own extra: admit the provider dir+ # into the workspace union (materialize is idempotent; it also+ # covers the python_dependencies key _provider_extras doesn't+ # read), then one sync carries the deps.+ from pm.workspace import enabled_member_dirs++ members = enabled_member_dirs()+ candidate = Path(plugin_dir)+ pm.sync_venv(explicit=True, plugin_dirs=members + ([candidate] if candidate not in members else []))+ else:+ return [_command_result(+ kind="pip", name=target, status="failed", command=command,+ error="no declared extra and no plugin directory to materialize declared dependencies from",+ )]except Exception as exc:- return [_command_result(kind="pip", name=name, status="failed", error=str(exc))]- if outcome.blocked:- return [_command_result(kind="pip", name=name, status="failed", command=outcome.command, error=outcome.reason)]- return [_command_result(- kind="pip", name=name, status="installed" if outcome.ok else "failed", command=outcome.command,- completed=subprocess.CompletedProcess(- args=outcome.command, returncode=0 if outcome.ok else 1, stdout=outcome.stdout, stderr=outcome.stderr,- ),- )]+ return [_command_result(kind="pip", name=target, status="failed", command=command, error=str(exc))]+ still_missing = [dep for dep in missing if not _dependency_importable(dep)]+ if still_missing:+ # The environment is selected at boot: a sync that succeeded outside+ # this interpreter's sight is NOT immediate import success — report+ # the truth instead of stamping installed without the deps visible.+ return [_command_result(kind="pip", name=target, status="restart_required", command=command)]+ return [_command_result(kind="pip", name=target, status="installed", command=command)]def _run_setup_step(results: list, kind: str, name: str, command: str, status_of, **kwargs) -> Optional[int]:@@ -396,7 +424,7 @@ def _install_memory_provider_setup(name: str) -> Dict[str, Any]:if provider is None and not manifest:raise _unknown_provider(name)setup = _memory_provider_setup_manifest(name)- results = _install_memory_provider_pip_dependencies(setup["pip_dependencies"])+ results = _install_memory_provider_pip_dependencies(name, setup["pip_dependencies"])results.extend(_install_memory_provider_external_dependencies(setup["external_dependencies"]))if not results:results.append(_command_result(kind="setup", name=name, status="no_declared_steps"))diff --git a/hermes_cli/worktree_gc.py b/hermes_cli/worktree_gc.pyindex 5969c7e4c4a..5306c39a382 100644--- a/hermes_cli/worktree_gc.py+++ b/hermes_cli/worktree_gc.py@@ -91,7 +91,8 @@ def _dirty_split(path: str) -> tuple[bool, List[str]]:def _archive_untracked(tree: Path, untracked: List[str]) -> Optional[Path]:"""Copy untracked files out of a doomed tree; None on any failure (caller must then keep)."""stamp = time.strftime("%Y%m%d-%H%M%S")- dest = Path.home() / ".hermes" / "archive" / "worktree-prune" / f"{tree.name}-{stamp}"+ from hermes_constants import get_hermes_home+ dest = get_hermes_home() / "archive" / "worktree-prune" / f"{tree.name}-{stamp}"try:for rel in untracked:src = tree / reldiff --git a/plugins/google_meet/process_manager.py b/plugins/google_meet/process_manager.pyindex 96a86c65724..eca48e8ce42 100644--- a/plugins/google_meet/process_manager.py+++ b/plugins/google_meet/process_manager.py@@ -28,6 +28,10 @@ def _root() -> Path:return Path(get_hermes_home()) / "workspace" / "meetings"+def _active_file() -> Path:+ return _root() / ".active.json"++def _read_active() -> Optional[Dict[str, Any]]:p = _active_file()if not p.is_file():@@ -39,7 +43,7 @@ def _read_active() -> Optional[Dict[str, Any]]:def _write_active(data: Dict[str, Any]) -> None:- write_json_atomic(_root() / ".active.json", data)+ write_json_atomic(_active_file(), data)def _pid_alive(pid: int) -> bool:@@ -191,6 +195,6 @@ def stop(*, reason: str = "requested") -> Dict[str, Any]:time.sleep(0.5)else:_kill(pid, signal.SIGKILL) # windows-footgun: ok — POSIX-only plugin (google_meet registers no-op on Windows; see __init__.py)- (_root() / ".active.json").unlink(missing_ok=True)+ _active_file().unlink(missing_ok=True)return {"ok": True, "reason": reason, "meetingId": active.get("meeting_id"),"transcriptPath": str(Path(out_dir) / "transcript.txt") if out_dir else None}diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.pyindex 5c2d5074b9f..4b61ed9cf63 100644--- a/plugins/memory/hindsight/__init__.py+++ b/plugins/memory/hindsight/__init__.py@@ -34,9 +34,10 @@ from tools.registry import tool_errorfrom .embedded import (_RETRIABLE_CONNECTION_MARKERS, _build_embedded_profile_env,- _check_local_runtime, _embedded_llm_api_key, _embedded_profile_env_path,- _export_port_health_grace_timeout, _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,+ _check_local_runtime, _embedded_profile_env_path,+ _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,)+from .embedded_runtime import ensure_daemon_and_url as _start_sideenv_daemonfrom .settings import (_DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_RETAIN_SOURCE,_DEFAULT_TIMEOUT, _HINDSIGHT_GLYPH, _MIN_CLIENT_VERSION, _MIN_VERSION_FOR_UPDATE_MODE_APPEND,@@ -462,25 +463,31 @@ class HindsightMemoryProvider(MemoryProvider):return _parse_int_setting(os.environ.get(env_var, env_default) if value is None else value, default)def _new_embedded_client(self):- available, reason = _check_local_runtime()- if not available:- raise RuntimeError("Hindsight local runtime is unavailable" + (f": {reason}" if reason else ""))- _ensure_client_dependency()- from hindsight import HindsightEmbedded- HindsightEmbedded.__del__ = lambda self: None+ """HTTP client against the side-env daemon. The daemon manager runs in the+ isolated side env (its own interpreter → its own hindsight-api binary and+ ProfileManager port allocation); Hermes talks to it over HTTP with the+ pinned main-env hindsight-client — no in-process HindsightEmbedded."""cfg = self._config+ profile = cfg.get("profile", "hermes")llm_provider = _daemon_llm_provider(cfg.get("llm_provider", ""))- logger.debug("Creating HindsightEmbedded client (profile=%s, provider=%s)",- cfg.get("profile", "hermes"), llm_provider)+ logger.debug("Creating Hindsight embedded client (profile=%s, provider=%s)", profile, llm_provider)self._idle_timeout = self._int_setting("idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,)- kwargs = dict(profile=cfg.get("profile", "hermes"), llm_provider=llm_provider,- llm_api_key=_embedded_llm_api_key(cfg), llm_model=cfg.get("llm_model", ""),- idle_timeout=self._idle_timeout)- if self._llm_base_url:- kwargs["llm_base_url"] = self._llm_base_url- return HindsightEmbedded(**kwargs)+ # Starts (or reuses) the side-env daemon; the URL comes from the side env's+ # own ProfileManager/get_url, never a hardcoded port.+ changed = _load_simple_env(_embedded_profile_env_path(cfg)) != _build_embedded_profile_env(cfg)+ if changed:+ _materialize_embedded_profile_env(cfg)+ url = _start_sideenv_daemon(cfg, restart=changed)+ self._api_url = url+ _ensure_client_dependency()+ from hindsight_client import Hindsight+ kwargs = {"base_url": url, "timeout": float(self._timeout or _DEFAULT_TIMEOUT)}+ if self._api_key:+ kwargs["api_key"] = self._api_key+ logger.info("Hindsight embedded: HTTP client ready (profile=%s, url=%s)", profile, url)+ return Hindsight(**kwargs)def _new_cloud_client(self):_ensure_client_dependency()@@ -649,7 +656,8 @@ class HindsightMemoryProvider(MemoryProvider):stable session-scoped id with ``update_mode='append'``; older APIs get*fallback_document_id* (per-process unique) and no update_mode — the onlyway the resume-overwrite fix works there. The /version probe targets the- embedded client's dynamic per-profile port when running, else api_url.+ embedded daemon URL resolved by the side env (stored in ``_api_url``), else+ the configured api_url.On Hindsight ≥ 0.5.0 the API supports ``update_mode='append'``, which lets us reuse a stablesession-scoped ``document_id`` across process lifecycles without overwriting prior turns. On older@@ -657,8 +665,7 @@ class HindsightMemoryProvider(MemoryProvider):minted at initialize / switch time) and don't pass ``update_mode`` at all — that's the only way theresume-overwrite fix (#6654) keeps working on legacy servers."""- url = getattr(self._client, "url", None) if self._mode == "local_embedded" else None- probe_url = str(url) if url else (self._api_url or "")+ probe_url = self._api_url or ""if self._session_id and _check_api_supports_update_mode_append(probe_url, self._api_key):return self._session_id, "append"return fallback_document_id, None@@ -686,14 +693,14 @@ class HindsightMemoryProvider(MemoryProvider):if self._mode == "local": # legacy aliasself._mode = "local_embedded"if self._mode == "local_embedded":- # Must precede the daemon_embed_manager import, which reads it at import time.- _export_port_health_grace_timeout(cfg)available, reason = _check_local_runtime()if not available:- logger.warning("Hindsight local mode disabled because its runtime could not be imported: %s.%s",+ logger.warning("Hindsight local_embedded disabled: the isolated runtime is unavailable: %s.%s",reason, _local_runtime_hint(reason))self._mode = "disabled"return+ logger.info("Hindsight local_embedded: isolated runtime available (profile=%s); "+ "daemon start queued", cfg.get("profile", "hermes"))self._apply_connection_settings(cfg)self._apply_retain_settings(cfg)self._apply_recall_settings(cfg)@@ -813,32 +820,15 @@ class HindsightMemoryProvider(MemoryProvider):_context_thread(self._daemon_start_worker, "hindsight-daemon-start").start()def _daemon_start_worker(self) -> None:- import traceback- log_path = get_hermes_home() / "logs" / "hindsight-embed.log"- log_path.parent.mkdir(parents=True, exist_ok=True)-- def _log(text: str) -> None:- with open(log_path, "a", encoding="utf-8") as f:- f.write(text)-+ """Background daemon bring-up: keep the materialized profile .env in sync,+ then start/reuse the side-env daemon and connect the HTTP client."""try:- # Rich console -> our log file (redirecting global fds would capture other threads).- import hindsight_embed.daemon_embed_manager as dem- from rich.console import Console- dem.console = Console(file=open(log_path, "a", encoding="utf-8"), force_terminal=False)-- client = self._get_client()- profile = self._config.get("profile", "hermes")- # Profile .env out of sync with config -> rewrite and restart a running daemon.- if _load_simple_env(_embedded_profile_env_path(self._config)) != _build_embedded_profile_env(self._config):- _materialize_embedded_profile_env(self._config)- if client._manager.is_running(profile):- _log("\n=== Config changed, restarting daemon ===\n")- client._manager.stop(profile)- client._ensure_started()- _log("\n=== Daemon started successfully ===\n")+ cfg = self._config+ profile = cfg.get("profile", "hermes")+ self._get_client()+ logger.info("Hindsight embedded: daemon start worker finished (profile=%s)", profile)except Exception as e:- _log(f"\n=== Daemon startup failed: {e} ===\n" + traceback.format_exc())+ logger.warning("Hindsight embedded daemon startup failed: %s", e, exc_info=True)def system_prompt_block(self) -> str:mode = self._memory_mode if self._memory_mode in _SYSTEM_PROMPT_TAILS else "hybrid"@@ -1170,22 +1160,12 @@ class HindsightMemoryProvider(MemoryProvider):self._session_id, self._parent_session_id, reset, self._document_id)def _close_client(self) -> None:- if self._mode != "local_embedded":- self._run_sync(self._client.aclose())- return- # HindsightEmbedded.close() closes its sync client from this thread ("attached- # to a different loop" before aiohttp releases the session): aclose the inner- # client on the shared loop first, then let the wrapper clean up bookkeeping.- inner_client = getattr(self._client, "_client", None)- if inner_client is not None and hasattr(inner_client, "aclose"):- _run_sync(inner_client.aclose())- with contextlib.suppress(Exception):- self._client._client = None- with contextlib.suppress(RuntimeError):- self._client.close()+ # Both client kinds are hindsight_client.Hindsight now (the embedded mode+ # is an HTTP client against the side-env daemon): close on the shared loop.+ self._run_sync(self._client.aclose())def shutdown(self) -> None:- logger.debug("Hindsight shutdown: stopping writer + waiting for background threads")+ logger.debug("Hindsight shutdown: mode=%s, stopping writer + waiting for background threads", self._mode)# Stop accepting retain jobs first so late sync_turn() calls are dropped.self._shutting_down.set()# The writer finishes in-flight work then exits on the sentinel; thediff --git a/plugins/memory/hindsight/embedded.py b/plugins/memory/hindsight/embedded.pyindex a155c67fc18..5abdfe733a4 100644--- a/plugins/memory/hindsight/embedded.py+++ b/plugins/memory/hindsight/embedded.py@@ -1,13 +1,12 @@-"""Local-embedded Hindsight runtime: import probe, install hint, the per-profile env-file the standalone ``hindsight-embed`` daemon consumes, and the health-grace export."""+"""Local-embedded Hindsight runtime seam: side-env runtime probe, install hint, and+the per-profile env file the standalone ``hindsight-embed`` daemon consumes. The+heavy stack itself lives in the isolated side env owned by ``embedded_runtime`` —+nothing here imports it in-process."""from __future__ import annotationsimport contextlib-import importlib-import loggingimport os-import sysfrom pathlib import Pathfrom typing import Any@@ -15,17 +14,6 @@ from agent.secret_scope import get_secretfrom .settings import _DEFAULT_IDLE_TIMEOUT, _daemon_llm_provider, _parse_int_setting-logger = logging.getLogger(__name__.rpartition(".")[0])--# Read by hindsight_embed.daemon_embed_manager AT IMPORT TIME: how long to wait-# for a slow /health before killing the daemon as stale. Busy hosts exceed the-# upstream 2s check and get needlessly restarted, so it's plugin config.-# Env var the embedded daemon manager reads (at import time, as a module-level constant) to size the grace-# window it waits for a slow /health before declaring a daemon stale and killing it. We surface it as plugin-# config so users can raise it without hand-setting an env var, consistent with "config.json, not raw env-# vars". See #13125.-_PORT_HEALTH_GRACE_ENV = "HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"-# Stale embedded-daemon connection markers (client recreated, operation retried once)._RETRIABLE_CONNECTION_MARKERS = ("cannot connect to host",@@ -46,53 +34,23 @@ _RETRIABLE_CONNECTION_MARKERS = ()-def _export_port_health_grace_timeout(config: dict[str, Any]) -> None:- """Export the daemon health grace timeout BEFORE ``daemon_embed_manager`` is- imported. Only when configured; ``setdefault`` so an explicit env override wins."""- raw = config.get("port_health_grace_timeout")- if raw is None or raw == "":- return- try:- seconds = float(raw)- except (TypeError, ValueError):- return logger.warning("Invalid Hindsight port_health_grace_timeout %r; ignoring.", raw)- if seconds < 0:- return logger.warning("Negative Hindsight port_health_grace_timeout %r; ignoring.", raw)- os.environ.setdefault(_PORT_HEALTH_GRACE_ENV, repr(seconds))--def _check_local_runtime() -> tuple[bool, str | None]:- """Whether the local embedded stack imports cleanly (older CPUs: NumPy can raise- at import, so Hermes degrades instead of retrying a broken backend).- ``sentence_transformers`` is probed too: ``hindsight`` imports fine with a broken- embedding stack, and the daemon would then abort on every retain/recall."""- try:- for module in ("hindsight", "hindsight_embed.daemon_embed_manager", "sentence_transformers"):- importlib.import_module(module)- return True, None- except Exception as exc:- return False, str(exc)+ """Whether the isolated side-env runtime imports cleanly (probed in the side+ interpreter — older CPUs: NumPy can raise at import, so Hermes degrades+ instead of retrying a broken backend; ``sentence_transformers`` is probed+ too: ``hindsight`` imports fine with a broken embedding stack, and the+ daemon would then abort on every retain/recall)."""+ from .embedded_runtime import check_local_runtime++ return check_local_runtime()def _local_runtime_hint(reason: str | None) -> str:- """Install guidance when the local_embedded runtime is missing: ``plugin.yaml``- declares only ``hindsight-client``, so a hand-written config, the legacy- ``"mode": "local"`` alias or a restored backup hits ``No module named 'hindsight'``.-- ``local_embedded`` imports ``from hindsight import HindsightEmbedded``, which is provided only by the- ``hindsight-all`` package (its wheel ships the top-level ``hindsight`` module).- NousResearch/hermes-agent#7718.- """- text = (reason or "").lower()- if "no module named" in text and any(m in text for m in ("hindsight'", 'hindsight"', "hindsight_embed")):- return (- f" Install the embedded runtime with: uv pip install --python "- f"{sys.executable} hindsight-all — or run 'hermes memory setup'. "- "(local_embedded needs the 'hindsight-all' package, which provides the "- "top-level 'hindsight' module; 'hindsight-client' alone only covers "- "cloud / local_external.)"- )- return ""+ """Install/reinstall guidance when the local_embedded side runtime is missing+ or broken (probe reason appended when present)."""+ from .embedded_runtime import _local_runtime_hint as _hint++ return _hint(reason)def _load_simple_env(path) -> dict[str, str]:diff --git a/plugins/memory/hindsight/embedded_runtime.py b/plugins/memory/hindsight/embedded_runtime.pynew file mode 100644index 00000000000..928aba5d9c2--- /dev/null+++ b/plugins/memory/hindsight/embedded_runtime.py@@ -0,0 +1,321 @@+"""Build an isolated Hindsight API runtime and start its daemon in that interpreter."""++from __future__ import annotations++import json+import logging+import os+import shutil+import subprocess+import sys+import uuid+from pathlib import Path+from typing import Any++from hermes_constants import get_hermes_home++logger = logging.getLogger(__name__)++_EMBED_VERSION = "0.9.2"+_API_SLIM_VERSION = "0.9.2"+# Marker file written inside each generation recording what it was built from;+# a generation whose marker no longer matches is replaced (new generation) on+# the next ensure — never mutated in place.+_EXPECTED = {"hindsight-embed": _EMBED_VERSION, "hindsight-api-slim": _API_SLIM_VERSION}+_STATE_FILE = ".hermes-sideenv.json"+_ACTIVE_RECORD = "active.json"++# First successful daemon start downloads/loads ML models — minutes, not seconds.+_DEFAULT_DAEMON_START_TIMEOUT = 900.0+_UV_LOCK_TIMEOUT = 900.0+_UV_SYNC_TIMEOUT = 3600.0+_PROBE_TIMEOUT = 300.0++_PORT_HEALTH_GRACE_ENV = "HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"+_API_VERSION_ENV = "HINDSIGHT_EMBED_API_VERSION"++# Printed by the bridge as its LAST stdout line; the manager's Rich output and+# the daemon's own logs share the stream, so the marker makes parsing exact.+_BRIDGE_MARKER = "__HERMES_HINDSIGHT_BRIDGE__"++_PROBE_CODE = "import hindsight_embed.daemon_embed_manager, hindsight_api, sentence_transformers"++_DAEMON_BRIDGE_CODE = """\+import json, sys+from hindsight_embed import daemon_client++profile = sys.argv[1]+if len(sys.argv) > 2 and sys.argv[2] == "restart":+ daemon_client.stop_daemon(profile)+result = {"ok": False, "url": None, "error": None}+try:+ # {} config: the manager merges the profile's own .env (materialized by the+ # plugin) over it, so the LLM keys live only in the 0600 profile file.+ result["ok"] = bool(daemon_client.ensure_daemon_running({}, profile))+ if result["ok"]:+ result["url"] = daemon_client.get_daemon_url(profile)+ else:+ result["error"] = "daemon did not start (see the hindsight profile log)"+except Exception as exc: # bridge must always report, never crash the parse+ result["error"] = f"{type(exc).__name__}: {exc}"+print("@MARKER@" + json.dumps(result))+""".replace("@MARKER@", _BRIDGE_MARKER)+++def sideenv_root() -> Path:+ """Private side env for the embedded runtime (never the boot-selected venv)."""+ return get_hermes_home() / "profiles" / "Hindsight" / "env"+++def _active_generation(root: Path) -> Path | None:+ """The published generation directory, or None when nothing is active."""+ try:+ record = json.loads((root / _ACTIVE_RECORD).read_text(encoding="utf-8-sig"))+ gen = root / str(record.get("generation", ""))+ except Exception:+ return None+ return gen if gen.resolve().is_relative_to(root.resolve()) and gen != root and gen.is_dir() else None+++def _publish_generation(root: Path, generation: Path) -> None:+ """Point the selection record at *generation* atomically (file replace —+ never a directory rename: venv launchers embed absolute paths)."""+ from utils import atomic_json_write++ atomic_json_write(root / _ACTIVE_RECORD, {"generation": generation.name, "pins": _EXPECTED})+++def sideenv_python(root: Path | None = None) -> Path | None:+ """The active generation's interpreter, or None when the side env is not+ installed. Resolved through the selection record — the generation dir is+ created at its final path and never renamed."""+ root = Path(root) if root is not None else sideenv_root()+ gen = _active_generation(root)+ if gen is None:+ return None+ exe = "python.exe" if os.name == "nt" else "python"+ for scripts in ("Scripts", "bin"):+ candidate = gen / ".venv" / scripts / exe+ if candidate.is_file():+ return candidate+ return None+++def sideenv_pyproject() -> str:+ """Exact pinned requirements of the isolated runtime (public PyPI versions,+ frozen into uv.lock at install time; never resolved against the main env)."""+ return (+ '[project]\n'+ 'name = "hermes-hindsight-embedded"\n'+ 'version = "0.9.2"\n'+ 'requires-python = ">=3.11"\n'+ 'dependencies = [\n'+ f' "hindsight-embed=={_EMBED_VERSION}",\n'+ f' "hindsight-api-slim[all]=={_API_SLIM_VERSION}",\n'+ ']\n'+ )+++def _generation_current(generation: Path) -> bool:+ """Installed and matching the pinned versions (marker written at build)."""+ if generation is None:+ return False+ try:+ state = json.loads((generation / _STATE_FILE).read_text(encoding="utf-8-sig"))+ except Exception:+ return False+ return state.get("pins") == _EXPECTED+++def _uv_bridge(venv: Path) -> tuple[str, dict[str, str]]:+ """The sanctioned pm bridge: pinned uv binary + sanitized env for *venv*."""+ from pm.ensure import uv as pm_uv++ uv_bin, env = pm_uv(venv=venv)+ if not uv_bin:+ raise RuntimeError(+ "pm could not realize the pinned uv binary; run 'hermes pm install' "+ "before installing the isolated Hindsight runtime"+ )+ return str(uv_bin), env+++def _run_uv(uv_bin: str, env: dict[str, str], args: list[str], timeout: float) -> None:+ # Pin the interpreter explicitly: pm's sanitized env strips UV_PYTHON, and+ # without a pin uv's chooser can pick a different (e.g. PBS 3.14) runtime.+ # sys.executable is the Hermes venv python — the side venv is fully+ # isolated (own site-packages); this only fixes the BASE interpreter.+ env = {**env, "UV_PYTHON": sys.executable}+ result = subprocess.run( # noqa: S603 — fixed argv, no shell+ [uv_bin, *args], env=env, capture_output=True, text=True,+ encoding="utf-8", errors="replace", timeout=timeout,+ )+ if result.returncode != 0:+ detail = (result.stderr or result.stdout or "").strip()[-2000:]+ raise RuntimeError(f"uv {' '.join(args)} failed (exit {result.returncode}): {detail}")+++def ensure_sideenv() -> Path:+ """Install/update the isolated runtime; returns the active generation dir.++ Each install is an immutable generation built at its final path and+ published via the ``active.json`` selection record. A failed build removes+ only its own unpublished generation; the previous generation (and any+ daemon running from it) stays untouched."""+ root = sideenv_root()+ active = _active_generation(root)+ if _generation_current(active) and sideenv_python(root) is not None:+ return active++ generation = root / f"gen-{uuid.uuid4().hex}"+ generation.parent.mkdir(parents=True, exist_ok=True)+ logger.info("Hindsight embedded runtime: building generation %s (pins=%s)",+ generation, _EXPECTED)+ try:+ generation.mkdir(parents=True)+ (generation / "pyproject.toml").write_text(sideenv_pyproject(), encoding="utf-8")+ uv_bin, env = _uv_bridge(generation / ".venv")+ _run_uv(uv_bin, env, ["lock", "--project", str(generation)], _UV_LOCK_TIMEOUT)+ _run_uv(uv_bin, env, ["sync", "--project", str(generation), "--frozen"], _UV_SYNC_TIMEOUT)+ (generation / _STATE_FILE).write_text(+ json.dumps({"pins": _EXPECTED}, sort_keys=True) + "\n", encoding="utf-8")+ except BaseException:+ # The failed generation was never published; nothing can be running+ # from it, so removing it leaks nothing. Previous generations stay.+ shutil.rmtree(generation, ignore_errors=True)+ raise+ _publish_generation(root, generation)+ logger.info("Hindsight embedded runtime: generation %s published (side env %s)",+ generation.name, root)+ return generation+++def _probe_interpreter(python: Path, timeout: float = _PROBE_TIMEOUT) -> tuple[bool, str | None]:+ """Import the embedded stack IN THE SIDE ENV (its own interpreter). Covers the+ old-CPU NumPy failure class and a broken embedding stack the same way the+ legacy in-process probe did — but inside the isolated environment."""+ try:+ result = subprocess.run( # noqa: S603 — fixed argv, no shell+ [str(python), "-c", _PROBE_CODE], capture_output=True, text=True,+ encoding="utf-8", errors="replace", timeout=timeout,+ env=_daemon_subprocess_env({}),+ )+ except (OSError, subprocess.TimeoutExpired) as exc:+ return False, f"side runtime probe failed: {exc}"+ if result.returncode == 0:+ return True, None+ reason = (result.stderr or result.stdout or "").strip()+ return False, reason[-500:] if reason else f"probe exited {result.returncode}"+++def check_local_runtime() -> tuple[bool, str | None]:+ """(available, reason) for local_embedded — probes the side env, never the+ boot-selected main environment."""+ root = sideenv_root()+ python = sideenv_python(root)+ if python is None:+ reason = (f"the isolated Hindsight runtime is not installed at {root}; "+ "run 'hermes memory setup' and choose Local Embedded")+ logger.debug("Hindsight local runtime unavailable: %s", reason)+ return False, reason+ available, reason = _probe_interpreter(python)+ if available:+ logger.debug("Hindsight side runtime probe OK (%s)", python)+ else:+ logger.debug("Hindsight side runtime probe failed: %s", reason)+ return available, reason+++def _local_runtime_hint(reason: str | None) -> str:+ """Install/reinstall guidance for an unavailable side runtime. The main+ Hermes environment is never touched, so the fix is always the same one."""+ text = f"{reason or ''}".strip()+ return (+ " The local_embedded runtime lives in an isolated environment"+ f" ({sideenv_root()}; hindsight-embed=={_EMBED_VERSION} +"+ f" hindsight-api-slim[all]=={_API_SLIM_VERSION}), separate from Hermes"+ " itself. Reinstall it with 'hermes memory setup' (Local Embedded), or"+ " switch to cloud / local_external mode."+ + (f" Last probe failure: {text}" if text else "")+ )+++def _daemon_subprocess_env(config: dict[str, Any]) -> dict[str, str]:+ """Env for the side-env bridge/manager process. daemon_embed_manager reads+ the health-grace window AT IMPORT TIME of that process, so it rides here —+ not in Hermes' own environment. Main-env interpreter markers are stripped so+ the side python resolves only its own environment."""+ env = dict(os.environ)+ env["PYTHONUTF8"] = "1"+ for key in ("VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE"):+ env.pop(key, None)+ raw = config.get("port_health_grace_timeout")+ if raw not in (None, ""):+ try:+ seconds = float(raw)+ except (TypeError, ValueError):+ logger.warning("Invalid Hindsight port_health_grace_timeout %r; ignoring.", raw)+ else:+ if seconds >= 0:+ env.setdefault(_PORT_HEALTH_GRACE_ENV, repr(seconds))+ else:+ logger.warning("Negative Hindsight port_health_grace_timeout %r; ignoring.", raw)+ # Freeze the daemon/API component version to the pinned pair (the manager+ # reads this as the profile .env override's fallback).+ env[_API_VERSION_ENV] = _API_SLIM_VERSION+ return env+++def _parse_bridge_output(stdout: str) -> dict[str, Any]:+ """The bridge's marked JSON line; Rich/log noise is ignored."""+ for line in reversed(stdout.splitlines()):+ if line.startswith(_BRIDGE_MARKER):+ try:+ return json.loads(line[len(_BRIDGE_MARKER):])+ except ValueError:+ continue+ return {}+++def ensure_daemon_and_url(config: dict[str, Any], *, restart: bool = False) -> str:+ """Start (or reuse) the side-env daemon and return its URL.++ The URL is resolved by the side env's own ProfileManager/get_url — profile+ ``HINDSIGHT_API_PORT`` override, then the manager's metadata allocation —+ and never hardcoded here. The daemon child runs the side env's hindsight-api+ because DaemonEmbedManager resolves the API command from the interpreter it+ runs under (the side python)."""+ python = sideenv_python()+ if python is None:+ raise RuntimeError(_local_runtime_hint("the isolated runtime is not installed"))+ profile = str(config.get("profile", "hermes") or "hermes")+ env = _daemon_subprocess_env(config)+ logger.info("Hindsight embedded: starting side-env daemon manager (profile=%s, side_python=%s)",+ profile, python)+ timeout = float(config.get("daemon_start_timeout") or _DEFAULT_DAEMON_START_TIMEOUT)+ try:+ result = subprocess.run( # noqa: S603 — fixed argv (python -c bridge), no shell+ [str(python), "-c", _DAEMON_BRIDGE_CODE, profile, "restart" if restart else "start"],+ env=env, capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=timeout,+ )+ except subprocess.TimeoutExpired as exc:+ logger.warning("Hindsight embedded daemon start timed out after %.0fs (profile=%s)", timeout, profile)+ raise RuntimeError(+ f"Hindsight daemon start timed out after {timeout:.0f}s; the first start "+ "can take several minutes — check the hindsight profile log and retry."+ ) from exc+ except OSError as exc:+ raise RuntimeError(f"could not run the side-env runtime {python}: {exc}") from exc+ if result.returncode != 0:+ detail = (result.stderr or result.stdout or "").strip()[-2000:]+ logger.warning("Hindsight embedded daemon bridge failed (exit %s): %s", result.returncode, detail)+ raise RuntimeError(f"Hindsight daemon startup failed (exit {result.returncode}): {detail}")+ payload = _parse_bridge_output(result.stdout)+ url = payload.get("url")+ if payload.get("ok") and url:+ logger.info("Hindsight embedded: daemon ready at %s (profile=%s)", url, profile)+ return str(url)+ error = payload.get("error") or f"no bridge result in side-env output: {(result.stdout or '')[-500:]}"+ logger.warning("Hindsight embedded daemon did not start: %s", error)+ raise RuntimeError(f"Hindsight daemon startup failed: {error}")diff --git a/plugins/memory/hindsight/setup.py b/plugins/memory/hindsight/setup.pyindex e6fdbac3515..cbeaeb8b91e 100644--- a/plugins/memory/hindsight/setup.py+++ b/plugins/memory/hindsight/setup.py@@ -14,7 +14,7 @@ from hermes_cli.secret_prompt import masked_secret_promptfrom . import templates as _hs_templatesfrom .embedded import _embedded_profile_env_path, _load_simple_env, _materialize_embedded_profile_envfrom .settings import (- _DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_TIMEOUT, _MIN_CLIENT_VERSION,+ _DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_TIMEOUT,_PROVIDER_DEFAULT_MODELS,)@@ -76,6 +76,41 @@ def _prompt_embedded_llm(llm_provider: str, provider_config: dict, env_writes: denv_writes["HINDSIGHT_LLM_API_KEY"] = llm_key or _load_simple_env(hermes_env).get("HINDSIGHT_LLM_API_KEY", "")+def _sync_client_dependency() -> bool:+ """hindsight-client via the declared ``extra: hindsight`` (plugin.yaml).++ pm's venv sync is the ONE install authority (uv.lock owns the pin) — no+ pip against sys.executable, and no ``tools.lazy_deps`` (deleted)."""+ try:+ import pm++ pm.sync_venv(["hindsight"], explicit=True)+ return True+ except Exception as e:+ print(f" ⚠ Install failed: {e}")+ print(" Run manually: hermes pm install")+ return False+++def _install_embedded_runtime() -> bool:+ """local_embedded: install the isolated side env (hindsight-embed + the heavy+ hindsight-api-slim[all], pinned 0.9.2) via the pm.ensure.uv bridge — never the+ shared main venv (the protobuf floors conflict). The daemon later runs from the+ side env's own interpreter/binary; Hermes talks HTTP with hindsight-client."""+ from .embedded_runtime import _local_runtime_hint, ensure_sideenv, sideenv_root++ try:+ root = ensure_sideenv()+ except Exception as e:+ print(f" ⚠ Isolated runtime install failed: {e}")+ print(f" {_local_runtime_hint(str(e)).strip()}")+ return False+ print(f" ✓ Isolated Hindsight runtime installed at {sideenv_root()}")+ print(" (separate environment — the Hermes venv is not modified; the daemon")+ print(" runs from it and Hermes connects over HTTP)")+ return True++def run_setup(provider, hermes_home: str, config: dict) -> None:"""Interactive wizard — installs only the deps the selected mode needs."""from hermes_cli.config import save_config@@ -105,18 +140,13 @@ def run_setup(provider, hermes_home: str, config: dict) -> None:provider_config["llm_provider"] = llm_providerprint("\n Checking dependencies...")- # Environment-aware install: sealed hosted venvs redirect to the durable data volume.- from tools.lazy_deps import install_specs-- deps = ["hindsight-all"] if mode == "local_embedded" else [f"hindsight-client>={_MIN_CLIENT_VERSION}"]- outcome = install_specs(deps, timeout=120)- if outcome.ok:- print(" ✓ Dependencies up to date")- elif outcome.blocked:- print(f" ⚠ Cannot install dependencies: {outcome.reason}")- else:- print(f" ⚠ Install failed:\n{(outcome.stderr or '').strip()}")- print(f" Run manually: uv pip install --python {sys.executable} {' '.join(deps)}")+ # Environment-aware install: pm's venv sync is the ONE authority for the+ # client (declared extra, uv.lock pin); tools.lazy_deps is deleted. The+ # local_embedded heavy stack installs into its own isolated side env.+ if not _sync_client_dependency():+ return+ if mode == "local_embedded" and not _install_embedded_runtime():+ returnif mode == "cloud":print("\n Get your API key at https://ui.hindsight.vectorize.io\n")diff --git a/plugins/memory/honcho/cli.py b/plugins/memory/honcho/cli.pyindex d18a51d4139..6b5cb6517ff 100644--- a/plugins/memory/honcho/cli.py+++ b/plugins/memory/honcho/cli.py@@ -518,519 +518,6 @@ def _ensure_sdk_installed() -> bool:return False-def cmd_setup(args) -> None:- """Interactive Honcho setup wizard."""- cfg = _read_config()-- write_path = _local_config_path()- read_path = _config_path()- print("\nHoncho memory setup\n" + "─" * 40)- print(" Honcho gives Hermes persistent cross-session memory.")- print(f" Config: {write_path}")- if read_path != write_path and read_path.exists():- print(f" (seeding from existing config at {read_path})")- print()-- if not _ensure_sdk_installed():- return-- hosts = cfg.setdefault("hosts", {})- hermes_host = hosts.setdefault(_host_key(), {})-- # Canonicalize any legacy pinPeerName before detection/writes.- _migrate_pin_key(cfg)- _migrate_pin_key(hermes_host)-- # --- 1. Cloud or local? ---- print(" Deployment:")- print(" cloud -- Honcho cloud (api.honcho.dev)")- print(" local -- self-hosted Honcho server")- current_deploy = "local" if any(- h in (cfg.get("baseUrl") or cfg.get("base_url") or "")- for h in ("localhost", "127.0.0.1", "::1")- ) else "cloud"- deploy = _prompt("Cloud or local?", default=current_deploy)- is_local = deploy.lower() in {"local", "l"}-- # Clean up legacy snake_case key- cfg.pop("base_url", None)-- if is_local:- # --- Local: ask for base URL, optionally accept a JWT for auth ---- current_url = cfg.get("baseUrl") or ""- new_url = _prompt("Base URL", default=current_url or "http://localhost:8000")- if new_url:- cfg["baseUrl"] = new_url-- # Self-hosted Honcho can run with AUTH_USE_AUTH=true and an- # AUTH_JWT_SECRET on the server side. In that case clients must- # send a JWT signed with that secret as the bearer token (the- # Honcho SDK takes it via ``api_key=``). Cloud users got prompted- # for a key already; the local path historically skipped this and- # forced users to disable auth on the server. Offer the prompt- # here too. We store it under the host block (not the top-level- # apiKey) so ``get_honcho_client`` recognises it as an explicit- # local auth opt-in (see ``_host_has_key`` in client.py) and- # cloud/hybrid switching is unaffected.- current_host_key = hermes_host.get("apiKey", "")- masked = (- f"...{current_host_key[-8:]}"- if len(current_host_key) > 8- else ("set" if current_host_key else "not set")- )- print(- "\n Local Honcho auth (JWT signed with the server's "- "AUTH_JWT_SECRET)."- )- print(- " Leave blank if your server runs with AUTH_USE_AUTH=false. "- f"Current: {masked}"- )- new_local_key = _prompt(- "Local JWT / bearer token (blank to skip / keep current)",- secret=True,- )- if new_local_key:- hermes_host["apiKey"] = new_local_key- elif current_host_key:- print(" Keeping existing local JWT.")- else:- # Surface the top-level key situation for transparency.- top_key = cfg.get("apiKey", "")- if top_key:- print(- "\n Top-level API key present in config (kept for "- "cloud/hybrid use)."- )- print(- " Local connections will skip auth automatically "- "until a local JWT is set above."- )- else:- print("\n No local JWT set. Local no-auth ready.")- use_oauth = False- if not is_local:- # --- Cloud: OAuth (browser), device code, or API key ---- cfg.pop("baseUrl", None) # cloud uses SDK default-- # Detect an existing OAuth grant so re-running setup reflects it instead- # of looking like a fresh connect.- from plugins.memory.honcho.oauth import OAuthCredential- existing_oauth = OAuthCredential.from_host_block(hermes_host)-- device_available = _device_login_available()- is_remote, can_browse = _headless()-- print("\n Auth method:")- if existing_oauth is not None:- print(f" (currently connected via OAuth — client {existing_oauth.client_id})")- print(" oauth -- sign in via browser on this machine (recommended)")- if device_available:- print(" device -- device code: approve from a browser on another machine (SSH / headless)")- print(" apikey -- paste an API key from https://app.honcho.dev")-- default_method = "oauth"- if is_remote or not can_browse:- if device_available:- print(" (no usable local browser detected — device code recommended)")- default_method = "device"- else:- print(" (no usable local browser detected — browser sign-in may need an SSH tunnel to 127.0.0.1:8765)")- prompt_label = "oauth, device, or apikey?" if device_available else "OAuth or API key?"- method = _prompt(prompt_label, default=default_method).strip().lower()- use_oauth = method in {"oauth", "o"}- use_device = device_available and method in {"device", "d"}-- if use_device:- from plugins.memory.honcho.oauth_flow import (- AccessDenied,- AuthorizationTimeout,- DeviceCode,- DeviceCodeExpired,- DeviceFlowError,- authorize_via_device_code,- )-- def _show(device: DeviceCode) -> None:- print("\n To connect, on any device with a browser:")- print(f"\n 1. Open {device.verification_uri}")- print(f" 2. Enter {device.user_code}")- print(f"\n Or open directly:\n\n {device.verification_uri_complete}\n")- mins = max(1, device.expires_in // 60)- print(f" Waiting for approval (expires in {mins} min, Ctrl-C to cancel) ", end="", flush=True)-- def _open_local(url: str) -> None:- import webbrowser-- webbrowser.open(url)-- print("\n Requesting device code…")- try:- cred = authorize_via_device_code(- config_path=write_path,- source="hermes-cli",- apply_config=False,- display=_show,- open_url=_open_local if can_browse and not is_remote else None,- on_poll=lambda: print(".", end="", flush=True),- )- except KeyboardInterrupt:- print("\n Cancelled. Re-run 'hermes honcho setup' to try again.\n")- return- except (AuthorizationTimeout, DeviceCodeExpired):- print("\n Device code expired before approval.")- print(" Re-run 'hermes honcho setup' to get a new code.\n")- return- except AccessDenied:- print("\n Sign-in was denied on the approval page.")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- except DeviceFlowError as e:- if e.error == "http_429":- print("\n Too many device-code requests — wait a minute and re-run setup.\n")- else:- print(f"\n Device sign-in failed: {e}")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- except Exception as e:- print(f"\n Device sign-in failed: {e}")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- print(" approved")- _apply_grant_to_host(hermes_host, cred)- print(" Authorized — token saved. Let's finish configuring.\n")- elif use_oauth:- # Sign in now, up front — the browser link is the whole point, so- # don't bury it behind the identity prompts. The grant's tokens are- # merged into the in-memory cfg so the wizard's final save preserves- # them; settings stay wizard-owned (apply_config=False).- from plugins.memory.honcho.oauth_flow import authorize_via_loopback-- def _open(url: str) -> None:- print(f"\n Open this link to authorize (waiting up to 5 minutes):\n\n {url}\n")- import webbrowser-- webbrowser.open(url)-- print("\n Starting browser sign-in…")- try:- cred = authorize_via_loopback(- config_path=write_path,- source="hermes-cli",- apply_config=False,- open_url=_open,- )- except Exception as e:- print(f" OAuth sign-in failed: {e}")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- _apply_grant_to_host(hermes_host, cred)- print(" Authorized — token saved. Let's finish configuring.\n")- else:- current_key = cfg.get("apiKey", "")- masked = f"...{current_key[-8:]}" if len(current_key) > 8 else ("set" if current_key else "not set")- print(f"\n Current API key: {masked}")- new_key = _prompt("Honcho API key (leave blank to keep current)", secret=True)- if new_key:- cfg["apiKey"] = new_key-- if not cfg.get("apiKey"):- print("\n No API key configured. Get yours at https://app.honcho.dev")- print(" Run 'hermes honcho setup' again once you have a key.\n")- return-- # --- 3. Identity ---- current_peer = hermes_host.get("peerName") or cfg.get("peerName", "")- new_peer = _prompt("Your name (user peer)", default=current_peer or os.getenv("USER", "user"))- if new_peer:- hermes_host["peerName"] = new_peer-- current_ai = hermes_host.get("aiPeer") or cfg.get("aiPeer", "hermes")- new_ai = _prompt("AI peer name", default=current_ai)- if new_ai:- hermes_host["aiPeer"] = new_ai-- current_workspace = hermes_host.get("workspace") or cfg.get("workspace", "hermes")- new_workspace = _prompt("Workspace ID", default=current_workspace)- if new_workspace:- hermes_host["workspace"] = new_workspace-- # --- 3b. Gateway identity mapping ---- # These keys only affect the Hermes GATEWAY (Telegram/Discord/Slack/...),- # the one entrypoint that supplies a runtime user ID. CLI/TUI/desktop/ACP- # sessions have no runtime ID and fall through to peerName, so the step is- # moot off-gateway — gate it behind detection.- #- # Detection mirrors the gateway resolver: root-level config and the- # canonical ``pinUserPeer`` both affect routing, so host-only reads would- # mis-classify a profile that inherits its mapping from root.- (- current_pin,- current_aliases,- current_prefix,- aliases_from_root,- prefix_from_root,- ) = _resolve_effective_identity_mapping(cfg, hermes_host)-- if current_pin:- current_shape = "single"- elif current_aliases:- current_shape = "hybrid"- else:- current_shape = "multi"-- gw_platforms = _gateway_platforms()- if gw_platforms is None:- print("\n Gateway identity mapping routes platform users to memory peers.")- run_mapping = _prompt(- "Running the Hermes gateway (Telegram/Discord/etc.)? (y/N)",- default="n",- ).strip().lower() in {"y", "yes"}- elif not gw_platforms:- print("\n No gateway platforms connected — identity mapping only affects")- print(" gateway users, so this step doesn't apply here.")- run_mapping = _prompt(- "Configure gateway mapping anyway? (y/N)", default="n",- ).strip().lower() in {"y", "yes"}- else:- print(f"\n Gateway platforms detected: {', '.join(gw_platforms)}")- run_mapping = True-- if run_mapping:- peer_target = hermes_host.get("peerName") or current_peer or "user"- default_choice = {"single": "1", "hybrid": "2", "multi": "3"}.get(current_shape, "3")- print("\n How should gateway users map to memory peers?")- print(" [1] just me — every non-agent user collapses to your peer")- print(" [2] me + other people — keep mine pooled, others separate")- print(" [3] only other people — everyone gets their own peer")- print(" [s] skip (leave untouched) [e] edit raw keys")- choice = _prompt("Choice", default=default_choice).strip().lower()-- if choice in {"2", "me+others", "both"}:- pooled = _prompt(- " Keep my own memory pooled across platforms? (Y/n)", default="y",- ).strip().lower()- shape = "hybrid" if pooled in {"y", "yes", ""} else "multi"- elif choice in {"1", "me", "just-me"}:- shape = "single"- elif choice in {"3", "others"}:- shape = "multi"- elif choice in {"e", "edit", "raw"}:- shape = "raw"- else:- shape = "skip"-- # Un-pinning a currently-pinned profile without aliasing strands the- # pooled peerName history; steer the operator toward pooling instead.- if current_pin and shape == "multi":- print(- f"\n ⚠ Un-pinning will orphan memory accumulated under peer\n"- f" '{peer_target}'. Existing gateway users resolve to fresh,\n"- f" empty peers."- )- confirm = _prompt(- " Pool my own memory instead (alias my IDs to peerName)? (Y/n)",- default="y",- ).strip().lower()- if confirm in {"y", "yes", ""}:- shape = "hybrid"-- # Each branch scrubs every peer-mapping key first so a stale alias,- # prefix, or pin from an earlier run starts clean.- if shape == "single":- _scrub_identity_mapping(hermes_host)- hermes_host["pinUserPeer"] = True- print(f" All non-agent gateway users route to '{peer_target}' (pin overrides aliases).")- _echo_identity_mapping(hermes_host)- elif shape == "multi":- # Preserve operator-curated host-level aliases across multi → multi- # re-runs. Root-sourced aliases cascade naturally and are NOT- # copied down — an empty host map would mask a root baseline.- prior_aliases = (- dict(current_aliases)- if isinstance(current_aliases, dict) and not aliases_from_root- else {}- )- _scrub_identity_mapping(hermes_host)- hermes_host["pinUserPeer"] = False- if prior_aliases:- hermes_host["userPeerAliases"] = prior_aliases- _apply_runtime_prefix(- hermes_host, current_prefix, prefix_from_root,- "Runtime peer prefix (e.g. 'telegram_', blank for none)",- )- print(" Each gateway user → own peer.")- _echo_identity_mapping(hermes_host)- elif shape == "hybrid":- existing_aliases = dict(current_aliases) if isinstance(current_aliases, dict) else {}- _scrub_identity_mapping(hermes_host)- hermes_host["pinUserPeer"] = False- merged = _collect_operator_aliases(existing_aliases, peer_target)- if merged:- hermes_host["userPeerAliases"] = merged- _apply_runtime_prefix(- hermes_host, current_prefix, prefix_from_root,- "Runtime peer prefix for unknown users (e.g. 'telegram_', blank for none)",- )- print(f" Your runtime IDs → '{peer_target}', others → own peer.")- _echo_identity_mapping(hermes_host)- elif shape == "raw":- _configure_raw_identity_mapping(- hermes_host, current_pin, current_aliases, current_prefix,- aliases_from_root, prefix_from_root,- )- _echo_identity_mapping(hermes_host)- else: # skip- print(" Identity mapping left untouched.")-- # --- 4. Observation mode ---- current_obs = hermes_host.get("observationMode") or cfg.get("observationMode", "directional")- print("\n Observation mode:")- print(" directional -- all observations on, each AI peer builds its own view (default)")- print(" unified -- user observes self, AI observes others only")- new_obs = _prompt("Observation mode", default=current_obs)- if new_obs in {"unified", "directional"}:- hermes_host["observationMode"] = new_obs- else:- hermes_host["observationMode"] = "directional"-- # --- 5. Write frequency ---- current_wf = str(hermes_host.get("writeFrequency") or cfg.get("writeFrequency", "async"))- print("\n Write frequency:")- print(" async -- background thread, no token cost (recommended)")- print(" turn -- sync write after every turn")- print(" session -- batch write at session end only")- print(" N -- write every N turns (e.g. 5)")- new_wf = _prompt("Write frequency", default=current_wf)- try:- hermes_host["writeFrequency"] = int(new_wf)- except (ValueError, TypeError):- hermes_host["writeFrequency"] = new_wf if new_wf in {"async", "turn", "session"} else "async"-- # --- 6. Recall mode ---- _raw_recall = hermes_host.get("recallMode") or cfg.get("recallMode", "hybrid")- current_recall = "hybrid" if _raw_recall not in {"hybrid", "context", "tools"} else _raw_recall- print("\n Recall mode:")- print(" hybrid -- auto-injected context + Honcho tools available (default)")- print(" context -- auto-injected context only, Honcho tools hidden")- print(" tools -- Honcho tools only, no auto-injected context")- new_recall = _prompt("Recall mode", default=current_recall)- if new_recall in {"hybrid", "context", "tools"}:- hermes_host["recallMode"] = new_recall-- # --- 7. Context token budget ---- current_ctx_tokens = hermes_host.get("contextTokens") or cfg.get("contextTokens")- current_display = str(current_ctx_tokens) if current_ctx_tokens else "uncapped"- print("\n Context injection per turn (hybrid/context recall modes only):")- print(" uncapped -- no limit (default)")- print(" N -- token limit per turn (e.g. 1200)")- new_ctx_tokens = _prompt("Context tokens", default=current_display)- if new_ctx_tokens.strip().lower() in {"none", "uncapped", "no limit"}:- hermes_host.pop("contextTokens", None)- elif new_ctx_tokens.strip() == "":- pass # keep current- else:- try:- val = int(new_ctx_tokens)- if val >= 0:- hermes_host["contextTokens"] = val- except (ValueError, TypeError):- pass # keep current-- # --- 7b. Dialectic cadence ---- current_dialectic = str(hermes_host.get("dialecticCadence") or cfg.get("dialecticCadence") or "2")- print("\n Dialectic cadence:")- print(" How often Honcho rebuilds its user model (LLM call on Honcho backend).")- print(" 1 = every turn, 2 = every other turn, 3+ = sparser.")- print(" Recommended: 1-5.")- new_dialectic = _prompt("Dialectic cadence", default=current_dialectic)- try:- val = int(new_dialectic)- if val >= 1:- hermes_host["dialecticCadence"] = val- except (ValueError, TypeError):- hermes_host["dialecticCadence"] = 2-- # --- 7c. Dialectic reasoning level ---- current_reasoning = (- hermes_host.get("dialecticReasoningLevel")- or cfg.get("dialecticReasoningLevel")- or "low"- )- print("\n Dialectic reasoning level:")- print(" Depth Honcho uses when synthesizing user context on auto-injected calls.")- print(" minimal -- quick factual lookups")- print(" low -- straightforward questions (default)")- print(" medium -- multi-aspect synthesis")- print(" high -- complex behavioral patterns")- print(" max -- thorough audit-level analysis")- new_reasoning = _prompt("Reasoning level", default=current_reasoning)- if new_reasoning in {"minimal", "low", "medium", "high", "max"}:- hermes_host["dialecticReasoningLevel"] = new_reasoning- else:- hermes_host["dialecticReasoningLevel"] = "low"-- # --- 8. Session strategy ---- current_strat = hermes_host.get("sessionStrategy") or cfg.get("sessionStrategy", "per-session")- print("\n Session strategy:")- print(" per-session -- each run starts clean, Honcho injects context automatically")- print(" per-directory -- reuses session per dir, prior context auto-injected each run")- print(" per-repo -- one session per git repository")- print(" global -- single session across all directories")- new_strat = _prompt("Session strategy", default=current_strat)- if new_strat in {"per-session", "per-repo", "per-directory", "global"}:- hermes_host["sessionStrategy"] = new_strat-- hermes_host["enabled"] = True- hermes_host.setdefault("saveMessages", True)-- _write_config(cfg)- print(f"\n Config written to {write_path}")-- # --- Auto-enable Honcho as memory provider in config.yaml ---- try:- from hermes_cli.config import load_config, save_config- hermes_config = load_config()- hermes_config.setdefault("memory", {})["provider"] = "honcho"- save_config(hermes_config)- print(" Memory provider set to 'honcho' in config.yaml")- except Exception as e:- print(f" Could not auto-enable in config.yaml: {e}")- print(" Run: hermes config set memory.provider honcho")-- # --- Test connection ---- print(" Testing connection... ", end="", flush=True)- try:- from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client, reset_honcho_client- reset_honcho_client()- hcfg = HonchoClientConfig.from_global_config(host=_host_key())- get_honcho_client(hcfg)- print("OK")- except Exception as e:- print(f"FAILED\n Error: {e}")- return-- print("\n Honcho is ready.")- print(f" Session: {hcfg.resolve_session_name()}")- print(f" Workspace: {hcfg.workspace_id}")- print(f" User: {hcfg.peer_name}")- print(f" AI peer: {hcfg.ai_peer}")- print(f" Observe: {hcfg.observation_mode}")- print(f" Frequency: {hcfg.write_frequency}")- print(f" Recall: {hcfg.recall_mode}")- print(f" Sessions: {hcfg.session_strategy}")- print("\n Honcho tools available in chat:")- print(" honcho_context -- session context: summary, representation, card, messages")- print(" honcho_search -- semantic search over history")- print(" honcho_profile -- peer card, key facts")- print(" honcho_reasoning -- ask Honcho a question, synthesized answer")- print(" honcho_conclude -- persist a user fact to memory")- print("\n Other commands:")- print(" hermes honcho status -- show full config")- print(" hermes honcho mode -- change recall/observation mode")- print(" hermes honcho tokens -- tune context and dialectic budgets")- print(" hermes honcho peer -- update peer names")- print(" hermes honcho map <name> -- map this directory to a session name\n")def _device_login_available() -> bool:@@ -1793,12 +1280,7 @@ Step 4 Seed AI identity files → Honcho AI peermgr = HonchoSessionManager(honcho=client, config=hcfg)session_key = hcfg.resolve_session_name()mgr.get_or_create(session_key)- for f in agent_files:- content = f.read_text(encoding="utf-8-sig").strip()- if content:- ok = mgr.seed_ai_identity(session_key, content, source=f.name)- status = "seeded" if ok else "failed"- print(f" {f.name}: {status}")+ _migrate_seed(mgr, session_key, agent_files)except Exception as e:print(f" Failed: {e}")else:diff --git a/plugins/memory/mem0/__init__.py b/plugins/memory/mem0/__init__.pyindex 76d14e320f7..cba45a5bda6 100644--- a/plugins/memory/mem0/__init__.py+++ b/plugins/memory/mem0/__init__.py@@ -80,295 +80,6 @@ def _load_config() -> dict:return config-def _schema(name: str, description: str, properties: dict[str, tuple[str, str]], required: list[str]) -> dict:- props = {k: {"type": t, "description": d} for k, (t, d) in properties.items()}- return {"name": name, "description": description, "parameters": {"type": "object", "properties": props, "required": required}}---TOOL_SCHEMAS = [- _schema("mem0_search", "Search the user's memories by meaning; returns facts ranked by relevance. Use this before answering any question that may depend on what you know about the user (preferences, facts, history, people, projects, past decisions). For multi-part or multi-hop questions, call it several times — vary the wording and run follow-up searches on what earlier results reveal; one search is rarely enough.",- {"query": ("string", "What to search for."), "top_k": ("integer", "Max results (default: 10, max: 50)."), "rerank": ("boolean", "Rerank results for relevance (default: false, platform mode only).")}, ["query"]),- _schema("mem0_add", "Store a durable fact about the user, verbatim (no LLM extraction). Call this the moment the user states a lasting preference, correction, decision, or personal detail worth recalling on future turns — don't wait to be asked to remember. Skip transient chit-chat and facts you've already stored.",- {"content": ("string", "The fact to store.")}, ["content"]),- _schema("mem0_update", "Replace the text of an existing memory by its ID (take the ID from a mem0_search result). Use when a stored fact has changed or was wrong — correct it in place instead of adding a duplicate.",- {"memory_id": ("string", "Memory UUID to update."), "text": ("string", "New text content.")}, ["memory_id", "text"]),- _schema("mem0_delete", "Delete a memory by its ID (take the ID from a mem0_search result). Use when a stored fact is obsolete or the user asks you to forget it; prefer mem0_update if the fact merely changed.",- {"memory_id": ("string", "Memory UUID to delete.")}, ["memory_id"]),-]--_PROMPT_BODY = (- "You have persistent memory of this user from past conversations. You should call mem0_search before answering anything that could depend on prior context (the user's preferences, facts, history, people, projects, or earlier decisions) — do not rely on the chat window alone, and do not assume you have no memory.\n"- "For multi-part or multi-hop questions, run several searches with different wording/angles and follow-up searches on what the first results surface; one search is rarely enough. Keep searching until you have every fact the question needs before you answer.\n"- "Tools: mem0_search to find memories, mem0_add to store facts, mem0_update and mem0_delete to manage by ID."-)---class Mem0MemoryProvider(MemoryProvider):- """Mem0 memory with server-side extraction and semantic search (platform, self-hosted or OSS)."""-- def __init__(self):- self._config = self._backend = self._sync_thread = self._prefetch_thread = None- self._mode, self._api_key, self._host, self._user_id, self._agent_id = "platform", "", "", _DEFAULT_USER_ID, "hermes"- self._rerank_default, self._channel = False, "cli" # channel = gateway name (cli/telegram/discord/...)- self._prefetch_query = self._prefetch_result = ""- self._prefetch_done = self._atexit_registered = False- self._consecutive_failures, self._breaker_open_until = 0, 0.0 # circuit breaker state- self._breaker_lock, self._sync_lock, self._prefetch_lock = threading.Lock(), threading.Lock(), threading.Lock()-- @property- def name(self) -> str:- return "mem0"-- def is_available(self) -> bool:- cfg = _load_config()- if cfg.get("mode", "platform") == "oss":- return bool(cfg.get("oss", {}).get("vector_store"))- return bool(cfg.get("api_key") or cfg.get("host")) # platform needs a key; self-hosted a host (key optional with AUTH_DISABLED)-- def save_config(self, values, hermes_home):- """Merge-write config to $HERMES_HOME/mem0.json."""- from utils import atomic_json_write- config_path = Path(hermes_home) / "mem0.json"- atomic_json_write(config_path, {**_read_mem0_json(config_path), **values}, mode=0o600)-- def get_config_schema(self):- api_key_required = _load_config().get("mode", "platform") != "oss"- return [- {"key": "api_key", "description": "Mem0 Platform API key", "secret": True, "required": api_key_required, "env_var": "MEM0_API_KEY", "url": "https://app.mem0.ai"},- {"key": "host", "description": "Self-hosted Mem0 server URL (leave blank for cloud)", "required": False, "env_var": "MEM0_HOST"},- {"key": "user_id", "description": "User identifier", "default": "hermes-user"},- {"key": "agent_id", "description": "Agent identifier", "default": "hermes"},- {"key": "rerank", "description": "Enable reranking for recall", "default": "false", "choices": ["true", "false"]},- ]-- def post_setup(self, hermes_home: str, config: dict) -> None:- from ._setup import post_setup- post_setup(hermes_home, config)-- def _oss_hint(self, template: str, default: str = "vector store") -> str:- """OSS-only hint; ``{vs}`` is the configured vector-store provider. "" in other modes."""- return template.format(vs=self._config.get("oss", {}).get("vector_store", {}).get("provider", default)) if self._mode == "oss" else ""-- def _create_backend(self):- # Lazy-install the mem0 SDK before the backend imports it (honors security.allow_lazy_installs);- # on failure the backend import raises the canonical error, captured below.- with suppress(Exception):- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("memory.mem0", prompt=False)- try:- from . import _backend- if self._mode == "oss":- return _backend.OSSBackend(self._config.get("oss", {}))- return _backend.SelfHostedBackend(self._api_key, self._host) if self._host else _backend.PlatformBackend(self._api_key)- except Exception as e:- logger.error("Mem0 backend failed to initialize (%s mode): %s", self._mode, e)- self._init_error = str(e)- return None-- def _is_breaker_open(self) -> bool:- """True while the breaker is tripped; an expired cooldown resets the failure count."""- with self._breaker_lock:- if self._consecutive_failures >= _BREAKER_THRESHOLD and time.monotonic() < self._breaker_open_until:- return True- if self._consecutive_failures >= _BREAKER_THRESHOLD:- self._consecutive_failures = 0- return False-- def _format_error(self, prefix: str, exc: Exception) -> str:- msg = f"{prefix}: {exc}"- if any(s in str(exc).lower() for s in ("connection", "refused", "timeout")):- msg += self._oss_hint(" (check that {vs} is running)")- return msg-- def _record_success(self):- with self._breaker_lock:- self._consecutive_failures = 0-- def _record_failure(self):- with self._breaker_lock:- self._consecutive_failures = count = self._consecutive_failures + 1- if count >= _BREAKER_THRESHOLD:- self._breaker_open_until = time.monotonic() + _BREAKER_COOLDOWN_SECS- if count >= _BREAKER_THRESHOLD:- hint = self._oss_hint(" Check that your {vs} vector store is running and reachable.", "unknown")- logger.warning("Mem0 circuit breaker tripped after %d consecutive failures. Pausing API calls for %ds.%s", count, _BREAKER_COOLDOWN_SECS, hint)-- def _try(self, call, log, msg: str):- """Background-path wrapper: run ``call`` under the breaker; on error log ``msg`` and return None."""- try:- result = call()- except Exception as e:- self._record_failure()- log(msg, e)- return None- self._record_success()- return result-- def initialize(self, session_id: str, **kwargs) -> None:- self._config = cfg = _load_config()- self._mode, self._api_key, self._host, self._agent_id = cfg.get("mode", "platform"), cfg.get("api_key", ""), cfg.get("host", ""), cfg.get("agent_id", "hermes")- # user_id precedence: operator-configured (env/mem0.json) > gateway-native id (kwargs) > _DEFAULT_USER_ID.- # The literal placeholder counts as unset so wizard users still get gateway-native ids.- configured = cfg.get("user_id")- self._user_id = (None if configured == _DEFAULT_USER_ID else configured) or kwargs.get("user_id") or _DEFAULT_USER_ID- # Persisted rerank preference: default for mem0_search when the model omits ``rerank``. Platform-only.- _rr = cfg.get("rerank", False)- self._rerank_default = _rr.lower() in ("true", "1", "yes") if isinstance(_rr, str) else bool(_rr)- self._channel = kwargs.get("platform") or "cli"- self._backend = self._create_backend()- if self._backend and not self._atexit_registered:- atexit.register(self._shutdown_backend)- self._atexit_registered = True-- def _search(self, query: str, top_k: int = 10, rerank: bool = False, backend=None) -> list:- # Scoped to user_id only — by design — so recall surfaces memories from any gateway/agent under this- # principal; writes attach agent_id and metadata.channel so narrower views remain possible at query time.- return (backend or self._backend).search(query, filters={"user_id": self._user_id}, top_k=top_k, rerank=rerank)-- def _add(self, messages: list, infer: bool):- metadata = {"channel": self._channel} if self._channel else {}- return self._backend.add(messages, user_id=self._user_id, agent_id=self._agent_id, infer=infer, metadata=metadata)-- def system_prompt_block(self) -> str:- # Mirror _create_backend precedence (oss > host > platform). Rerank is a Mem0 Platform feature only.- mode_label = "OSS (self-hosted)" if self._mode == "oss" else "self-hosted (HTTP API)" if self._host else "platform (cloud API)"- rerank_note = " Rerank is available on search." if (self._mode == "platform" and not self._host) else ""- return f"# Mem0 Memory\nActive. Mode: {mode_label}. User: {self._user_id}.\n{_PROMPT_BODY}{rerank_note}"-- def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:- self._start_prefetch(message)-- def _consume_prefetch_result(self, query: str) -> str | None:- """Pop the finished prefetch body for ``query`` (None if absent or still running)."""- with self._prefetch_lock:- if self._prefetch_query != query or not self._prefetch_done:- return None- result, self._prefetch_result, self._prefetch_done = self._prefetch_result, "", False- return result-- def _start_prefetch(self, query: str) -> None:- backend = self._backend- if not query or backend is None or self._is_breaker_open():- return-- def _run():- results = self._try(lambda: self._search(query, backend=backend), logger.debug, "Mem0 prefetch failed: %s")- lines = [r.get("memory", "") for r in (results or []) if r.get("memory")]- body = "## Mem0 Memory\n" + "\n".join(f"- {l}" for l in lines) if lines else ""- with self._prefetch_lock:- if self._prefetch_query == query:- self._prefetch_result, self._prefetch_done = body, True-- with self._prefetch_lock:- # Same query already answered or still in flight: don't restart it.- if self._prefetch_query == query and (self._prefetch_done or (self._prefetch_thread and self._prefetch_thread.is_alive())):- return- self._prefetch_query, self._prefetch_result, self._prefetch_done = query, "", False- self._prefetch_thread = t = threading.Thread(target=_run, daemon=True, name="mem0-prefetch")- t.start()-- def prefetch(self, query: str, *, session_id: str = "") -> str:- """Recall memories for the CURRENT question with a short hot-path wait."""- if (cached := self._consume_prefetch_result(query)) is not None:- return cached- self._start_prefetch(query)- with self._prefetch_lock:- thread = self._prefetch_thread if self._prefetch_query == query else None- if thread:- thread.join(timeout=_PREFETCH_WAIT_SECS)- return self._consume_prefetch_result(query) or "" # slow backend: skip injection; mem0_search remains the backstop-- def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:- """Send the turn to Mem0 for server-side fact extraction (non-blocking)."""- if self._backend is None or self._is_breaker_open():- return-- def _sync():- if self._backend is not None:- messages = [{"role": "user", "content": user_content}, {"role": "assistant", "content": assistant_content}]- self._try(lambda: self._add(messages, infer=True), logger.warning, "Mem0 sync failed: %s")-- with self._sync_lock:- prev = self._sync_thread- if prev and prev.is_alive():- prev.join(timeout=5.0)- if prev.is_alive(): # still busy after the wait: skip to avoid duplicate ingestion- return- self._sync_thread = threading.Thread(target=_sync, daemon=True, name="mem0-sync")- self._sync_thread.start()-- def get_tool_schemas(self) -> List[Dict[str, Any]]:- return list(TOOL_SCHEMAS)-- # -- tool handlers: (required params, error label, body, client-error policy) ---- # Client errors (bad ID / not found) never trip the breaker, except for mem0_add- # where they count as failures; update/delete answer them with "Memory not found".-- def _tool_search(self, args: dict) -> str:- top_k = max(1, min(int(args.get("top_k", 10)), 50))- rerank_raw = args.get("rerank", self._rerank_default)- rerank = rerank_raw.lower() not in ("false", "0", "no") if isinstance(rerank_raw, str) else bool(rerank_raw)- results = self._search(args["query"], top_k, rerank)- if not results:- return json.dumps({"result": "No relevant memories found."})- items = [{"id": r.get("id"), "memory": r.get("memory", ""), "score": r.get("score", 0)} for r in results]- return json.dumps({"results": items, "count": len(items)})-- def _tool_add(self, args: dict) -> str:- result = self._add([{"role": "user", "content": args["content"]}], infer=False)- event_id = result.get("event_id") if isinstance(result, dict) else None- # Cloud add is async (server-side extraction); OSS and self-hosted store synchronously.- msg = "Fact stored." if (self._mode == "oss" or self._host) else "Fact queued for storage."- return json.dumps({"result": msg, "event_id": event_id})-- _TOOL_HANDLERS = {- "mem0_search": (("query",), "Search failed", _tool_search, "skip"),- "mem0_add": (("content",), "Failed to store", _tool_add, "count"),- "mem0_update": (("memory_id", "text"), "Update failed", lambda self, a: json.dumps(self._backend.update(a["memory_id"], a["text"])), "not_found"),- "mem0_delete": (("memory_id",), "Delete failed", lambda self, a: json.dumps(self._backend.delete(a["memory_id"])), "not_found"),- }-- def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:- if self._backend is None:- err = getattr(self, "_init_error", "unknown error")- return json.dumps({"error": f"Mem0 backend not initialized: {err}.{self._oss_hint(' Check that {vs} is running and reachable.')}"})- if self._is_breaker_open():- return json.dumps({"error": f"Mem0 temporarily unavailable (multiple consecutive failures). Will retry automatically.{self._oss_hint(' Check that your {vs} is running.')}"})- if tool_name not in self._TOOL_HANDLERS:- return tool_error(f"Unknown tool: {tool_name}")- required, label, body, on_client_error = self._TOOL_HANDLERS[tool_name]- if missing := next((k for k in required if not args.get(k, "")), None):- return tool_error(f"Missing required parameter: {missing}")- try:- result = body(self, args)- except Exception as e:- client = _is_client_error(e)- if client and on_client_error == "not_found":- return tool_error(f"Memory not found: {args['memory_id']}")- if not client or on_client_error == "count":- self._record_failure()- return tool_error(self._format_error(label, e))- self._record_success()- return result-- def _shutdown_backend(self):- with suppress(Exception):- if self._backend:- self._backend.close()- self._backend = None-- def shutdown(self) -> None:- for t in (self._prefetch_thread, self._sync_thread):- if t and t.is_alive():- t.join(timeout=5.0)- self._shutdown_backend()---def register(ctx) -> None:- """Register Mem0 as a memory provider plugin."""- ctx.register_memory_provider(Mem0MemoryProvider())--# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----# Names external plugins imported from this module before the Sep 2026 decomposition.# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).@@ -392,22 +103,6 @@ ADD_SCHEMA = {},}-DELETE_SCHEMA = {- "name": "mem0_delete",- "description": (- "Delete a memory by its ID (take the ID from a mem0_search "- "result). Use when a stored fact is obsolete or the user asks you to "- "forget it; prefer mem0_update if the fact merely changed."- ),- "parameters": {- "type": "object",- "properties": {- "memory_id": {"type": "string", "description": "Memory UUID to delete."},- },- "required": ["memory_id"],- },-}-SEARCH_SCHEMA = {"name": "mem0_search","description": (diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.pyindex 6fc3cda0e51..e5f2a049313 100644--- a/plugins/platforms/dingtalk/adapter.py+++ b/plugins/platforms/dingtalk/adapter.py@@ -48,9 +48,9 @@ except Exception:from gateway.config import Platform, PlatformConfigfrom gateway.platforms.helpers import MessageDeduplicator, compile_mention_patterns-from gateway.platforms.base import BasePlatformAdapter, MessageEvent, SendResult+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResultfrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secret-from plugins.platforms.dingtalk.inbound import collect_download_codes, extract_media, extract_text+from plugins.platforms.dingtalk.inbound import DINGTALK_TYPE_MAPPINGlogger = logging.getLogger(__name__)@@ -59,684 +59,8 @@ MAX_MESSAGE_LENGTH = 20000RECONNECT_BACKOFF = [2, 5, 10, 30, 60]_SESSION_WEBHOOKS_MAX = 500_DINGTALK_WEBHOOK_RE = re.compile(r'^https://(?:api|oapi)\.dingtalk\.com/')-_TRUTHY = {"true", "1", "yes", "on"}-_EMOTION_ID = "2659900"-_EMOTION_BG = "im_bg_1"-# recall? -> (TextEmotion model, Request model, Headers model, robot SDK method), resolved on ``dingtalk_robot_models`` at call time.-_EMOTION_SDK = {recall: (f"Robot{v}EmotionRequestTextEmotion", f"Robot{v}EmotionRequest", f"Robot{v}EmotionHeaders", f"robot_{v.lower()}_emotion_with_options_async")- for recall, v in ((True, "Recall"), (False, "Reply"))}-_NUMBERED_RE = re.compile(r"^\d+\.\s")-_NO_LOCAL_UPLOAD = "DingTalk session webhook replies do not support local %s. Only markdown/text replies are supported without OpenAPI %s."-def _csv_set(raw: Any) -> Set[str]:- """Split a list or comma-separated string into a set of stripped, non-empty items."""- parts = raw if isinstance(raw, list) else str(raw).split(",")- return {str(part).strip() for part in parts if str(part).strip()}---def dingtalk_deps_present() -> bool:- """PASSIVE registry ``check_fn`` — must never install; credentials are gated separately.-- Registry ``check_fn`` — called from status displays and config loading, so it must never install- anything. The ACTIVE lazy-installer (``check_dingtalk_requirements``) is registered as- ``ensure_deps_fn`` and runs from ``create_adapter()`` when this returns False (#79812).- """- return DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE---def ensure_dingtalk_deps() -> bool:- """ACTIVE deps-only installer (registry ``ensure_deps_fn``); rebinds module globals. Deliberately does NOT- check credentials: an ``extra``-configured platform would otherwise be vetoed before ever installing (deadlock).-- Lazy-installs dingtalk-stream/httpx and rebinds module globals. Deliberately does NOT check credentials- — ``ensure_deps_fn``'s contract is deps-only ("Returns True once deps are importable"); credentials are- gated by ``is_connected``/``validate_config``. Otherwise a platform configured via- ``PlatformConfig.extra`` (which ``_is_connected`` accepts) would pass enablement, reach- ``create_adapter()``, and have the installer veto on env-var grounds before ever installing —- re-creating the #79812 deadlock for extra-configured setups.- """- global DINGTALK_STREAM_AVAILABLE, dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, HTTPX_AVAILABLE, httpx- if DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE:- return True- try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("platform.dingtalk", prompt=False)- import dingtalk_stream as _ds, httpx as _httpx # noqa: E401- from dingtalk_stream import ChatbotMessage as _CM- from dingtalk_stream.frames import CallbackMessage as _CBM, AckMessage as _AM- except Exception:- return False- dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, httpx = _ds, _CM, _CBM, _AM, _httpx- DINGTALK_STREAM_AVAILABLE = HTTPX_AVAILABLE = True- return True---def _credentials(extra: Optional[dict]) -> tuple:- """(client_id, client_secret) from PlatformConfig.extra first, then env / scoped secret."""- extra = extra or {}- return (extra.get("client_id") or os.getenv("DINGTALK_CLIENT_ID", ""), extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))---def check_dingtalk_requirements() -> bool:- """Combined deps (lazy-installed) + credentials check for setup/status callers."""- return ensure_dingtalk_deps() and all(_credentials(None))---class DingTalkAdapter(BasePlatformAdapter):- """Stream Mode adapter: the SDK keeps a long-lived WebSocket and messages arrive via a ChatbotHandler- callback; replies go through the message's session_webhook (httpx) or, with ``card_template_id``, AI Cards."""-- MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH-- @property- def SUPPORTS_MESSAGE_EDITING(self) -> bool: # noqa: N802- """Edits only exist with AI Cards; the gateway gates streaming cursor/edit on this."""- return bool(self._card_template_id and self._card_sdk)-- REQUIRES_EDIT_FINALIZE = SUPPORTS_MESSAGE_EDITING # AI Cards need an explicit ``finalize=True`` edit to close the streaming indicator-- def __init__(self, config: PlatformConfig):- super().__init__(config, Platform.DINGTALK)- extra = config.extra or {}- self._client_id, self._client_secret = _credentials(extra)- # Group-chat gating; mention state is the SDK's structured ``is_in_at_list``, not text parsing.- self._mention_patterns: List[re.Pattern] = self._compile_mention_patterns()- self._allowed_users: Set[str] = {item.lower() for item in self._csv_setting("allowed_users", "DINGTALK_ALLOWED_USERS")}- self._stream_client = self._stream_task = self._http_client = self._card_sdk = self._robot_sdk = None- self._robot_code: str = extra.get("robot_code") or self._client_id- self._dedup = MessageDeduplicator(max_size=1000)- self._session_webhooks: Dict[str, tuple[str, int]] = {} # chat_id -> (webhook, expired_time_ms)- self._message_contexts: Dict[str, Any] = {} # chat_id -> last inbound ChatbotMessage (per-chat: no clobber)- self._card_template_id: Optional[str] = extra.get("card_template_id")- self._done_emoji_fired: Set[str] = set() # chats whose Done reaction fired this turn; reset per inbound- # Open streaming cards: chat_id -> {out_track_id: last_content}. ``edit_message(finalize=False)``- # re-opens a finalized card, so we track them and auto-close as siblings on the next ``send()``.- self._streaming_cards: Dict[str, Dict[str, str]] = {}- self._bg_tasks: Set[asyncio.Task] = set() # fire-and-forget emoji tasks, kept referenced (GC) + cancellable-- async def connect(self, *, is_reconnect: bool = False) -> bool:- """Connect to DingTalk via Stream Mode."""- for ok, problem in ((DINGTALK_STREAM_AVAILABLE, "dingtalk-stream not installed. Run: pip install 'dingtalk-stream>=0.20'"),- (HTTPX_AVAILABLE, "httpx not installed. Run: pip install httpx"),- (self._client_id and self._client_secret, "DINGTALK_CLIENT_ID and DINGTALK_CLIENT_SECRET required")):- if not ok:- logger.warning("[%s] " + problem, self.name)- return False- try:- from gateway.platforms._http_client_limits import platform_httpx_limits # tighter keepalive: idle CLOSE_WAIT drains promptly- self._http_client = httpx.AsyncClient(timeout=30.0, limits=platform_httpx_limits())- self._stream_client = dingtalk_stream.DingTalkStreamClient(dingtalk_stream.Credential(self._client_id, self._client_secret))- if CARD_SDK_AVAILABLE:- sdk_config = open_api_models.Config()- sdk_config.protocol, sdk_config.region_id = "https", "central"- if self._card_template_id:- self._card_sdk = dingtalk_card_client.Client(sdk_config)- self._robot_sdk = dingtalk_robot_client.Client(sdk_config) # needed for media download even without cards- if self._card_template_id:- logger.info("[%s] Card SDK initialized with template: %s", self.name, self._card_template_id)- else:- logger.info("[%s] Robot SDK initialized (media download)", self.name)- self._stream_client.register_callback_handler(dingtalk_stream.ChatbotMessage.TOPIC, _IncomingHandler(self, asyncio.get_running_loop()))- self._stream_task = asyncio.create_task(self._run_stream())- self._mark_connected()- logger.info("[%s] Connected via Stream Mode", self.name)- self._wire_plugin_handlers(self._stream_client) # plugin-registered native handlers- return True- except Exception as e:- logger.error("[%s] Failed to connect: %s", self.name, e)- return False-- async def _run_stream(self) -> None:- """Run the async stream client with auto-reconnection."""- backoff_idx = 0- while self._running:- try:- logger.debug("[%s] Starting stream client...", self.name)- await self._stream_client.start()- except asyncio.CancelledError:- return- except Exception as e:- if self._running:- logger.warning("[%s] Stream client error: %s", self.name, e)- if not self._running:- return- delay = RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)]- logger.info("[%s] Reconnecting in %ds...", self.name, delay)- await asyncio.sleep(delay)- backoff_idx += 1-- async def _quiet(self, coro, debug_fmt: str = "", *args) -> None:- """Await *coro*, swallowing any exception (logged at debug as ``debug_fmt % (name, *args, exc)`` when given)."""- try:- await coro- except Exception as e:- if debug_fmt:- logger.debug(debug_fmt, self.name, *args, e)-- async def disconnect(self) -> None:- """Disconnect from DingTalk."""- self._running = False- self._mark_disconnected()- # Close the websocket first so the stream task sees the disconnect instead of awaiting frames that never arrive.- websocket = getattr(self._stream_client, "websocket", None) if self._stream_client else None- if websocket is not None:- await self._quiet(websocket.close(), "[%s] websocket close during disconnect failed: %s")- if self._stream_task:- if hasattr(self._stream_client, "close"):- await self._quiet(asyncio.to_thread(self._stream_client.close)) # sync close() may block on I/O- self._stream_task.cancel()- try:- await asyncio.wait_for(self._stream_task, timeout=5.0)- except (asyncio.CancelledError, asyncio.TimeoutError):- logger.debug("[%s] stream task did not exit cleanly during disconnect", self.name)- self._stream_task = None- for task in list(self._bg_tasks):- task.cancel()- if self._bg_tasks:- await asyncio.gather(*self._bg_tasks, return_exceptions=True)- # Finalize open streaming cards BEFORE the HTTP client closes so they don't stay stuck- # in streaming state after a gateway restart. Outer try guards the token fetch.- for _chat_id in list(self._streaming_cards):- await self._quiet(self._close_streaming_siblings(_chat_id), "[%s] Failed to finalize streaming card on disconnect for %s: %s", _chat_id)- if self._http_client:- await self._http_client.aclose()- self._http_client = self._stream_client = None- for store in (self._session_webhooks, self._message_contexts, self._streaming_cards, self._done_emoji_fired, self._dedup, self._bg_tasks):- store.clear()- logger.info("[%s] Disconnected", self.name)-- def _extra_get(self, key: str, env_name: str = "", env_default: str = ""):- """config.extra[key]; when *env_name* is given, absent keys fall back to the env var."""- value = self.config.extra.get(key) if self.config.extra else None- return os.getenv(env_name, env_default) if value is None and env_name else value-- def _csv_setting(self, key: str, env_name: str) -> Set[str]:- """List/CSV setting from config.extra[key], falling back to the env var."""- return _csv_set(self._extra_get(key, env_name))-- def _dingtalk_require_mention(self) -> bool:- """Whether group chats require an explicit bot trigger."""- configured = self._extra_get("require_mention", "DINGTALK_REQUIRE_MENTION", "false")- return configured.lower() in _TRUTHY if isinstance(configured, str) else bool(configured)-- def _dingtalk_allowed_chats(self) -> Set[str]:- """Group chat whitelist; non-empty = hard gate even when @mentioned. DMs never filtered."""- return self._csv_setting("allowed_chats", "DINGTALK_ALLOWED_CHATS")-- def _compile_mention_patterns(self) -> List[re.Pattern]:- """Compile optional regex wake-word patterns (config list, or env as JSON / lines / CSV)."""- patterns = self._extra_get("mention_patterns")- if patterns is None and (raw := os.getenv("DINGTALK_MENTION_PATTERNS", "").strip()):- try:- patterns = json.loads(raw)- except Exception:- patterns = [part.strip() for part in raw.splitlines() if part.strip()]- if not patterns:- patterns = [part.strip() for part in raw.split(",") if part.strip()]- if patterns is None: # return before touching ``self.name`` on the no-patterns path (historical parity)- return []- return compile_mention_patterns(patterns, log_prefix=self.name, platform_label="dingtalk", display_label="DingTalk", logger_=logger)-- def _is_user_allowed(self, sender_id: str, sender_staff_id: str) -> bool:- if not self._allowed_users or "*" in self._allowed_users:- return True- return bool(({(sender_id or "").lower(), (sender_staff_id or "").lower()} - {""}) & self._allowed_users)-- def _message_matches_mention_patterns(self, text: str) -> bool:- return bool(text and self._mention_patterns) and any(p.search(text) for p in self._mention_patterns)-- def _should_process_message(self, message: "ChatbotMessage", text: str, is_group: bool, chat_id: str) -> bool:- """Group trigger rules (DMs always pass; ``allowed_users`` is enforced earlier): ``allowed_chats`` is a hard- gate, then any of free_response_chats / require_mention off / @mentioned (SDK ``is_in_at_list``) / wake-word."""- if not is_group:- return True- allowed = self._dingtalk_allowed_chats()- if allowed and chat_id and chat_id not in allowed:- return False- return (- bool(chat_id and chat_id in self._csv_setting("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS"))- or not self._dingtalk_require_mention()- or bool(getattr(message, "is_in_at_list", False))- or self._message_matches_mention_patterns(text)- )-- def _spawn_bg(self, coro) -> None:- """Start a fire-and-forget coroutine and track it for cleanup."""- self._bg_tasks.add(task := asyncio.create_task(coro))- task.add_done_callback(self._bg_tasks.discard)-- async def _close_streaming_siblings(self, chat_id: str) -> None:- """Finalize open streaming cards for this chat at the start of every ``send()`` — the gateway has no "turn end" signal, so this is what closes lingering tool-progress cards."""- cards = self._streaming_cards.pop(chat_id, None)- token = await self._get_access_token() if cards else None- for out_track_id, last_content in list(cards.items()) if token else ():- try:- await self._stream_card_content(out_track_id, token, last_content, finalize=True)- logger.debug("[%s] AI Card sibling closed: %s", self.name, out_track_id)- except Exception as e:- logger.debug("[%s] Sibling close failed for %s: %s", self.name, out_track_id, e)-- def _fire_done_reaction(self, chat_id: str) -> None:- """Swap 🤔Thinking → 🥳Done on the original user message; idempotent per chat_id."""- if chat_id in self._done_emoji_fired:- return- self._done_emoji_fired.add(chat_id)- msg = self._message_contexts.get(chat_id)- msg_id, conversation_id = (getattr(msg, "message_id", None) or "", getattr(msg, "conversation_id", None) or "") if msg else ("", "")- if not (msg_id and conversation_id):- return- async def _swap() -> None:- await self._send_emotion(msg_id, conversation_id, "🤔Thinking", recall=True)- await self._send_emotion(msg_id, conversation_id, "🥳Done", recall=False)- self._spawn_bg(_swap())-- async def _on_message(self, message: "ChatbotMessage") -> None:- """Process an incoming DingTalk chatbot message."""- msg_id = getattr(message, "message_id", None) or uuid.uuid4().hex- if self._dedup.is_duplicate(msg_id):- return logger.debug("[%s] Duplicate message %s, skipping", self.name, msg_id)- conversation_id, sender_id, sender_nick, sender_staff_id = (getattr(message, k, "") or "" for k in ("conversation_id", "sender_id", "sender_nick", "sender_staff_id"))- is_group = str(getattr(message, "conversation_type", "1")) == "2"- sender_nick = sender_nick or sender_id- chat_id = conversation_id or sender_id- if not self._is_user_allowed(sender_id, sender_staff_id):- return logger.debug("[%s] Dropping message from non-allowlisted user staff_id=%s sender_id=%s", self.name, sender_staff_id, sender_id)- if not self._should_process_message(message, self._extract_text(message) or "", is_group, chat_id): # wake-word gate needs text early- return logger.debug("[%s] Dropping group message that failed mention gate message_id=%s chat_id=%s", self.name, msg_id, chat_id)- # Per-chat context; reset the Done marker so this message gets its own Thinking→Done cycle.- if chat_id:- self._message_contexts[chat_id] = message- self._done_emoji_fired.discard(chat_id)- session_webhook = getattr(message, "session_webhook", None) or ""- if session_webhook and chat_id and _DINGTALK_WEBHOOK_RE.match(session_webhook):- if len(self._session_webhooks) >= _SESSION_WEBHOOKS_MAX:- self._session_webhooks.pop(next(iter(self._session_webhooks))) # evict oldest (dict is non-empty here)- self._session_webhooks[chat_id] = (session_webhook, getattr(message, "session_webhook_expired_time", 0) or 0)- await self._resolve_media_codes(message) # download codes -> URLs so vision tools can use them- text = self._extract_text(message)- msg_type, media_urls, media_types = self._extract_media(message)- if not text and not media_urls:- return logger.debug("[%s] Empty message, skipping", self.name)- source = self.build_source(chat_id=chat_id, chat_name=getattr(message, "conversation_title", None), chat_type="group" if is_group else "dm",- user_id=sender_id, user_name=sender_nick, user_id_alt=sender_staff_id if sender_staff_id else None)- create_at = getattr(message, "create_at", None)- try:- timestamp = datetime.fromtimestamp(int(create_at) / 1000, tz=timezone.utc) if create_at else datetime.now(tz=timezone.utc)- except (ValueError, OSError, TypeError):- timestamp = datetime.now(tz=timezone.utc)- logger.debug("[%s] Message from %s in %s: %s", self.name, sender_nick, chat_id[:20] if chat_id else "?", text[:80] if text else "(media)")- await self.handle_message(MessageEvent(text=text, message_type=msg_type, source=source, message_id=msg_id, raw_message=message,- media_urls=media_urls, media_types=media_types, timestamp=timestamp))-- _extract_text = staticmethod(extract_text)-- def _extract_media(self, message: "ChatbotMessage"):- return extract_media(message)-- async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:- """Send a reply via AI Card (when configured) or DingTalk session webhook markdown."""- metadata = metadata or {}- logger.debug("[%s] send() chat_id=%s card_enabled=%s", self.name, chat_id, bool(self._card_template_id and self._card_sdk))- session_webhook = metadata.get("session_webhook") or (self._get_valid_webhook(chat_id) or ("",))[0]- if not session_webhook:- logger.warning("[%s] No valid session_webhook for chat_id=%s", self.name, chat_id)- return SendResult(success=False, error="No valid session_webhook available. Reply must follow an incoming message.")- if not self._http_client:- return SendResult(success=False, error="HTTP client not initialized")- current_message = self._message_contexts.get(chat_id)- # ``reply_to`` is only set by base.py:_send_with_retry for the FINAL reply to an inbound message;- # tool-progress, commentary and stream first-sends leave it None. It decides (1) finalize-on-create- # (intermediate cards stay open so edits don't flicker) and (2) whether to fire the Done reaction.- is_final_reply = reply_to is not None- if self._card_template_id and current_message and self._card_sdk:- await self._close_streaming_siblings(chat_id) # close lingering tool-progress cards before creating a new one- result = await self._create_and_stream_card(chat_id, current_message, content, finalize=is_final_reply)- if result and result.success:- if is_final_reply:- self._fire_done_reaction(chat_id)- else: # keep open + track so the next send() auto-closes it, or edit_message(finalize=True) does- self._streaming_cards.setdefault(chat_id, {})[result.message_id] = content- return result- logger.warning("[%s] AI Card send failed, falling back to webhook", self.name)- logger.debug("[%s] Sending via webhook", self.name)- payload = {"msgtype": "markdown", "markdown": {"title": "Hermes", "text": self._normalize_markdown(content[: self.MAX_MESSAGE_LENGTH])}}- try:- resp = await self._http_client.post(session_webhook, json=payload, timeout=15.0)- if resp.status_code < 300:- if is_final_reply:- self._fire_done_reaction(chat_id)- return SendResult(success=True, message_id=uuid.uuid4().hex[:12])- logger.warning("[%s] Send failed HTTP %d: %s", self.name, resp.status_code, resp.text[:200])- return SendResult(success=False, error=f"HTTP {resp.status_code}: {resp.text[:200]}")- except httpx.TimeoutException:- return SendResult(success=False, error="Timeout sending message to DingTalk")- except Exception as e:- logger.error("[%s] Send error: %s", self.name, e)- return SendResult(success=False, error=str(e))-- async def send_typing(self, chat_id: str, metadata=None) -> None:- """DingTalk does not support typing indicators."""-- async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata=None) -> SendResult:- """Render a remote image inline via markdown (session webhook has no native attachments)."""- image_block = f""- return await self.send(chat_id=chat_id, content=f"{caption}\n\n{image_block}" if caption else image_block, reply_to=reply_to, metadata=metadata)-- async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata=None, **kwargs) -> SendResult:- """Webhook replies cannot upload local images."""- return SendResult(success=False, error=_NO_LOCAL_UPLOAD % ("image uploads", "media upload"))-- async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None, reply_to=None, metadata=None, **kwargs) -> SendResult:- """Webhook replies cannot upload local files."""- return SendResult(success=False, error=_NO_LOCAL_UPLOAD % ("file attachments", "message send"))-- async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:- """Return basic info about a DingTalk conversation."""- return {"name": chat_id, "type": "group" if "group" in chat_id.lower() else "dm"}-- def _get_valid_webhook(self, chat_id: str) -> Optional[tuple[str, int]]:- """Get a non-expired session webhook for chat_id (5-minute safety margin)."""- info = self._session_webhooks.get(chat_id)- expired_time_ms = info[1] if info else 0- if expired_time_ms and expired_time_ms > 0 and int(datetime.now(tz=timezone.utc).timestamp() * 1000) + 5 * 60 * 1000 >= expired_time_ms:- self._session_webhooks.pop(chat_id, None)- return None- return info or None-- async def _create_and_stream_card(self, chat_id: str, message: Any, content: str, *, finalize: bool = True) -> Optional[SendResult]:- """Create, deliver and stream an AI Card; ``finalize=False`` leaves it open for ``edit_message`` by out_track_id."""- try:- token = await self._get_access_token()- if not token:- return None- out_track_id, models = f"hermes_{uuid.uuid4().hex[:12]}", dingtalk_card_models- is_group = str(getattr(message, "conversation_type", "1")) == "2"- sender_staff_id = getattr(message, "sender_staff_id", "") or ""- create_request = models.CreateCardRequest(- card_template_id=self._card_template_id, out_track_id=out_track_id, callback_type="STREAM",- card_data=models.CreateCardRequestCardData(card_param_map={"content": ""}),- im_group_open_space_model=models.CreateCardRequestImGroupOpenSpaceModel(support_forward=True),- im_robot_open_space_model=models.CreateCardRequestImRobotOpenSpaceModel(support_forward=True))- await self._sdk_call(self._card_sdk.create_card_with_options_async, create_request, models.CreateCardHeaders, token)- if is_group:- open_space_id = f"dtv1.card//IM_GROUP.{getattr(message, 'conversation_id', '') or ''}"- deliver_model = {"im_group_open_deliver_model": models.DeliverCardRequestImGroupOpenDeliverModel(robot_code=self._robot_code)}- elif sender_staff_id:- open_space_id = f"dtv1.card//IM_ROBOT.{sender_staff_id}"- deliver_model = {"im_robot_open_deliver_model": models.DeliverCardRequestImRobotOpenDeliverModel(space_type="IM_ROBOT")}- else:- return logger.warning("[%s] AI Card skipped: missing sender_staff_id for DM", self.name)- deliver_request = models.DeliverCardRequest(out_track_id=out_track_id, user_id_type=1, open_space_id=open_space_id, **deliver_model)- await self._sdk_call(self._card_sdk.deliver_card_with_options_async, deliver_request, models.DeliverCardHeaders, token)- await self._stream_card_content(out_track_id, token, content, finalize=finalize)- logger.info("[%s] AI Card %s: %s", self.name, "created+finalized" if finalize else "created (streaming)", out_track_id)- return SendResult(success=True, message_id=out_track_id)- except Exception as e:- logger.warning("[%s] AI Card create failed: %s\n%s", self.name, e, traceback.format_exc())- return None-- async def edit_message(self, chat_id: str, message_id: str, content: str, *, finalize: bool = False) -> SendResult:- """Stream updated content to an AI Card; ``message_id`` is the creating ``send()``'s out_track_id (callers track their own ids so parallel flows on one chat don't interfere)."""- token = await self._get_access_token() if message_id else None- if not token:- return SendResult(success=False, error="message_id required" if not message_id else "No access token")- try:- await self._stream_card_content(message_id, token, content, finalize=finalize)- if finalize: # canonical "response ended" signal from the stream consumer's final edit- self._streaming_cards.get(chat_id, {}).pop(message_id, None)- if not self._streaming_cards.get(chat_id):- self._streaming_cards.pop(chat_id, None)- logger.debug("[%s] AI Card finalized (edit): %s", self.name, message_id)- self._fire_done_reaction(chat_id)- else: # non-final edit reopens the card into streaming state — track for sibling close- self._streaming_cards.setdefault(chat_id, {})[message_id] = content- return SendResult(success=True, message_id=message_id)- except Exception as e:- logger.warning("[%s] Card edit failed: %s", self.name, e)- return SendResult(success=False, error=str(e))-- @staticmethod- async def _sdk_call(method, request, headers_cls, token: str):- """``await method(request, headers_cls(token), RuntimeOptions())`` — the alibabacloud SDK call shape."""- return await method(request, headers_cls(x_acs_dingtalk_access_token=token), tea_util_models.RuntimeOptions())-- async def _stream_card_content(self, out_track_id: str, token: str, content: str, finalize: bool = False) -> None:- """Stream content to an existing AI Card."""- stream_request = dingtalk_card_models.StreamingUpdateRequest(- out_track_id=out_track_id, guid=str(uuid.uuid4()), key="content", content=content[: self.MAX_MESSAGE_LENGTH],- is_full=True, is_finalize=finalize, is_error=False,- )- await self._sdk_call(self._card_sdk.streaming_update_with_options_async, stream_request, dingtalk_card_models.StreamingUpdateHeaders, token)-- async def _get_access_token(self) -> Optional[str]:- """Get access token via the SDK's cached (sync, requests-based) getter."""- if not self._stream_client:- return None- try:- return await asyncio.to_thread(self._stream_client.get_access_token)- except Exception as e:- logger.error("[%s] Failed to get access token: %s", self.name, e)- return None-- async def _send_emotion(self, open_msg_id: str, open_conversation_id: str, emoji_name: str, *, recall: bool = False) -> None:- """Add (or recall) an emoji reaction on a message."""- if not self._robot_sdk or not open_msg_id or not open_conversation_id:- return- action = "recall" if recall else "reply"- try:- token = await self._get_access_token()- if not token:- return- text_emotion_cls, request_cls, headers_cls, sdk_method = _EMOTION_SDK[recall]- text_emotion = getattr(dingtalk_robot_models, text_emotion_cls)(emotion_id=_EMOTION_ID, emotion_name=emoji_name, text=emoji_name, background_id=_EMOTION_BG)- request = getattr(dingtalk_robot_models, request_cls)(robot_code=self._robot_code, open_msg_id=open_msg_id, open_conversation_id=open_conversation_id,- emotion_type=2, emotion_name=emoji_name, text_emotion=text_emotion)- await self._sdk_call(getattr(self._robot_sdk, sdk_method), request, getattr(dingtalk_robot_models, headers_cls), token)- logger.info("[%s] _send_emotion: %s %s on msg=%s", self.name, action, emoji_name, open_msg_id[:24])- except Exception:- logger.debug("[%s] _send_emotion %s failed", self.name, action, exc_info=True)-- async def _resolve_media_codes(self, message: "ChatbotMessage") -> None:- """Resolve download codes in the message to real URLs (in place, in parallel)."""- token = await self._get_access_token()- if not token:- return- robot_code = getattr(message, "robot_code", None) or self._client_id- pairs = [(getattr(obj, key, None) if hasattr(obj, key) else obj.get(key), obj, key) for obj, key in collect_download_codes(message)]- tasks = [self._fetch_download_url(code, robot_code, token, obj, key) for code, obj, key in pairs if code]- if tasks:- await asyncio.gather(*tasks, return_exceptions=True)-- async def _fetch_download_url(self, code: str, robot_code: str, token: str, obj, key: str) -> None:- """Fetch the download URL for one code via the robot SDK and write it back to ``obj[key]``."""- if not self._robot_sdk:- return logger.warning("[%s] Robot SDK not initialized, cannot resolve media code", self.name)- try:- response = await self._sdk_call(self._robot_sdk.robot_message_file_download_with_options_async,- dingtalk_robot_models.RobotMessageFileDownloadRequest(download_code=code, robot_code=robot_code),- dingtalk_robot_models.RobotMessageFileDownloadHeaders, token)- body = response.body if response else None- url = getattr(body, "download_url", None) if body else None- if not body:- logger.warning("[%s] Failed to download media: empty response for code %s", self.name, code)- elif url and hasattr(obj, key):- setattr(obj, key, url)- elif url and isinstance(obj, dict):- obj[key] = url- except Exception as e:- logger.error("[%s] Error resolving media code %s: %s", self.name, code, e)-- @staticmethod- def _normalize_markdown(text: str) -> str:- """Work around DingTalk renderer quirks: blank line before numbered lists, dedent ``` fences."""- lines = text.split("\n")- out = []- for i, line in enumerate(lines):- prev = lines[i - 1].strip() if i > 0 else ""- if prev and _NUMBERED_RE.match(line.strip()) and not _NUMBERED_RE.match(prev):- out.append("")- out.append(line.lstrip() if line.strip().startswith("```") else line)- return "\n".join(out)---class _IncomingHandler(dingtalk_stream.ChatbotHandler if DINGTALK_STREAM_AVAILABLE else object):- """ChatbotHandler forwarding to the adapter (SDK >= 0.20: async ``process()`` gets a CallbackMessage ``.data`` dict)."""-- def __init__(self, adapter: DingTalkAdapter, loop: Optional[asyncio.AbstractEventLoop] = None):- if DINGTALK_STREAM_AVAILABLE:- super().__init__()- self._adapter, self._loop = adapter, loop-- def pre_start(self) -> None:- """No-op hook the SDK calls on every handler before opening the WebSocket (missing → AttributeError)."""- return-- async def process(self, message: "CallbackMessage"):- """Convert to ChatbotMessage, dispatch as a background task, ACK immediately (blocking would stall SDK heartbeats)."""- try:- data = json.loads(message.data) if isinstance(message.data, str) else message.data- chatbot_msg = ChatbotMessage.from_dict(data)- data = data if isinstance(data, dict) else {} # backfill fields from_dict() may not map (names vary across SDK versions)- webhook = data.get("sessionWebhook") or data.get("session_webhook") or ""- if webhook and not getattr(chatbot_msg, "session_webhook", None):- chatbot_msg.session_webhook = webhook- if not getattr(chatbot_msg, "is_in_at_list", False) and data.get("isInAtList"):- chatbot_msg.is_in_at_list = True- msg_id, conversation_id = getattr(chatbot_msg, "message_id", None) or "", getattr(chatbot_msg, "conversation_id", None) or ""- if msg_id and conversation_id:- self._adapter._spawn_bg(self._adapter._send_emotion(msg_id, conversation_id, "🤔Thinking", recall=False))- asyncio.create_task(self._safe_on_message(chatbot_msg)) # surfaces exceptions in logs instead of losing them- except Exception:- logger.exception("[%s] Error preparing incoming message", self._adapter.name)- return AckMessage.STATUS_SYSTEM_EXCEPTION, "error"- return AckMessage.STATUS_OK, "OK"-- async def _safe_on_message(self, chatbot_msg: "ChatbotMessage") -> None:- try:- await self._adapter._on_message(chatbot_msg)- except Exception:- logger.exception("[%s] Error processing incoming message", self._adapter.name)---async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):- """Out-of-process delivery (standalone_sender_fn) via the static robot webhook (DINGTALK_WEBHOOK_URL / extra- ``webhook_url``) — per-session webhooks aren't available to cron jobs."""- try:- import httpx- except ImportError:- return {"error": "httpx not installed"}- webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or os.getenv("DINGTALK_WEBHOOK_URL", "")- if not webhook_url:- return {"error": "DingTalk not configured. Set DINGTALK_WEBHOOK_URL env var or webhook_url in dingtalk platform extra config."}- try:- async with httpx.AsyncClient(timeout=30.0) as client:- resp = await client.post(webhook_url, json={"msgtype": "text", "text": {"content": message}})- resp.raise_for_status()- data = resp.json()- if data.get("errcode", 0) != 0:- return {"error": f"DingTalk API error: {data.get('errmsg', 'unknown')}"}- return {"success": True, "platform": "dingtalk", "chat_id": chat_id}- except Exception as e:- try: # send_message_tool._error redacts access_token from webhook URLs (lazy import avoids a circular)- from tools.send_message_tool import _error as _redact_error- return _redact_error(f"DingTalk send failed: {e}")- except Exception:- return {"error": f"DingTalk send failed: {e}"}---def interactive_setup() -> None:- """Configure DingTalk — QR scan (recommended) or manual credential entry."""- from hermes_cli.config import get_env_value, save_env_value- from hermes_cli.setup import prompt_choice- from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_success, print_warning- print_header("DingTalk")- if existing := get_env_value("DINGTALK_CLIENT_ID"):- print_success(f"DingTalk is already configured (Client ID: {existing}).")- if not prompt_yes_no("Reconfigure DingTalk?", False):- return- choices = ["QR Code Scan (Recommended, auto-obtain Client ID and Client Secret)", "Manual Input (Client ID and Client Secret)"]- result = None- if prompt_choice("Choose setup method", choices, default=0) == 0:- try:- from hermes_cli.dingtalk_auth import dingtalk_qr_auth- result = dingtalk_qr_auth()- if result is None:- print_warning("QR auth incomplete, falling back to manual input.")- except ImportError as exc:- print_warning(f"QR auth module failed to load ({exc}), falling back to manual input.")- if result is not None:- for key, value in zip(("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"), result):- save_env_value(key, value)- return print_success("DingTalk configured via QR scan!")- _manual_credential_entry(prompt, save_env_value, print_success)---def _manual_credential_entry(prompt, save_env_value, print_success) -> None:- client_id = prompt("DingTalk Client ID (app key)")- if not client_id:- return- save_env_value("DINGTALK_CLIENT_ID", client_id)- if client_secret := prompt("DingTalk Client Secret", password=True):- save_env_value("DINGTALK_CLIENT_SECRET", client_secret)- print_success("DingTalk credentials saved")---def _bridge_list_env(env_name: str, value) -> None:- """Export a YAML list/scalar as a comma-joined env var unless the env var is already set."""- if value is not None and not os.getenv(env_name):- os.environ[env_name] = ",".join(str(v) for v in value) if isinstance(value, list) else str(value)---def _nested_allowed_users(yaml_cfg: dict, dingtalk_cfg: dict):- """Allowlist from ``extra.allowed_users``: this block's own extra first, then ``gateway.platforms.dingtalk.extra`` and ``platforms.dingtalk.extra``."""- _gw = yaml_cfg.get("gateway")- containers = (_gw.get("platforms") if isinstance(_gw, dict) else None, yaml_cfg.get("platforms"))- for holder in (dingtalk_cfg, *(c.get("dingtalk") if isinstance(c, dict) else None for c in containers)):- _extra = holder.get("extra") if isinstance(holder, dict) else None- if isinstance(_extra, dict) and _extra.get("allowed_users") is not None:- return _extra.get("allowed_users")- return None---def _apply_yaml_config(yaml_cfg: dict, dingtalk_cfg: dict) -> dict | None:- """Translate config.yaml dingtalk: keys into DINGTALK_* env vars (apply_yaml_config_fn); env wins, returns None. The docs put the allowlist at- ``gateway.platforms.dingtalk.extra.allowed_users`` but gateway authz only consults DINGTALK_ALLOWED_USERS, so nested-only allowlists are bridged too.-- Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy dingtalk_cfg block from- gateway/config.py::load_gateway_config(). Env vars take precedence over YAML (each assignment guarded by- not os.getenv(...)). Returns None — everything flows through env.- """- for key, env, encode in (("require_mention", "DINGTALK_REQUIRE_MENTION", lambda v: str(v).lower()), ("mention_patterns", "DINGTALK_MENTION_PATTERNS", json.dumps)):- if key in dingtalk_cfg and not os.getenv(env):- os.environ[env] = encode(dingtalk_cfg[key])- allowed = dingtalk_cfg.get("allowed_users")- for env, value in (("DINGTALK_FREE_RESPONSE_CHATS", dingtalk_cfg.get("free_response_chats")), ("DINGTALK_ALLOWED_CHATS", dingtalk_cfg.get("allowed_chats")),- ("DINGTALK_ALLOWED_USERS", _nested_allowed_users(yaml_cfg, dingtalk_cfg) if allowed is None else allowed)):- _bridge_list_env(env, value)- return None---def _is_connected(config) -> bool:- """Connected when client_id + client_secret are present (PlatformConfig.extra first, then env)."""- return all(_credentials(getattr(config, "extra", {})))---def _build_adapter(config):- return DingTalkAdapter(config)---def register(ctx) -> None:- """Plugin entry point — called by the Hermes plugin system."""- ctx.register_platform(- name="dingtalk", label="DingTalk", adapter_factory=_build_adapter, check_fn=dingtalk_deps_present,- ensure_deps_fn=ensure_dingtalk_deps, is_connected=_is_connected, validate_config=_is_connected,- required_env=["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"], install_hint="pip install 'dingtalk-stream>=0.20' httpx",- setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="DINGTALK_ALLOWED_USERS",- allow_all_env="DINGTALK_ALLOW_ALL_USERS", cron_deliver_env_var="DINGTALK_HOME_CHANNEL",- standalone_sender_fn=_standalone_send, emoji="🐳", allow_update_command=True,- )-# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----# Names external plugins imported from this module before the Sep 2026 decomposition.diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 36eeb483ffc..dd14cb50e1b 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -3857,7 +3857,7 @@ class DiscordAdapter(BasePlatformAdapter):async def _process_voice_input(self, guild_id: int, user_id: int, pcm_data: bytes):"""Convert PCM -> WAV -> STT -> callback."""- from tools.voice_mode import is_whisper_hallucination+ from tools.voice_mode_transcript import is_whisper_hallucinationtmp_f = tempfile.NamedTemporaryFile(suffix=".wav", prefix="vc_listen_", delete=False)wav_path = tmp_f.nametmp_f.close()diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 50c9a33b8b8..b9d9ae777ec 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -681,12 +681,10 @@ def ensure_matrix_deps() -> bool:"ContentURI": ContentURI,"EventID": EventID,"EventType": EventType,- "PaginationDirection": PaginationDirection,- "PresenceState": PresenceState,+ "PresenceState": PresenceState,"RoomCreatePreset": RoomCreatePreset,"RoomID": RoomID,- "SyncToken": SyncToken,- "TrustState": TrustState,+ "TrustState": TrustState,"UserID": UserID,}diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex 874d0840a69..c7028aa10c5 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -35,7 +35,7 @@ else:HTTPX_AVAILABLE = Falsehttpx = None-from gateway.config import Platform, PlatformConfig+from gateway.config import Platform, PlatformConfig, _coerce_float, _coerce_intfrom gateway.platforms._shared import coerce_port as _coerce_portfrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secretfrom gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult@@ -206,6 +206,11 @@ def _is_timeout_error(exc: BaseException) -> bool:return "timeout" in type(exc).__name__.lower()+def _first_set(*vals: Any) -> Any:+ """First non-None value, else None (same semantic as the honcho helper)."""+ return next((val for val in vals if val is not None), None)++def _node_command(command: str) -> Optional[str]:"""Resolve a Node toolchain binary (node/npm), pm store first.diff --git a/plugins/video_gen/fal/__init__.py b/plugins/video_gen/fal/__init__.pyindex e8fb2b19228..4d92f59707d 100644--- a/plugins/video_gen/fal/__init__.py+++ b/plugins/video_gen/fal/__init__.py@@ -159,27 +159,6 @@ def _video_url_from_result(result: Any) -> Tuple[Any, Optional[str]]:_fal_client: Any = None_fal_client_lock = threading.Lock()--def _load_fal_client() -> Any:- """Lazy-load the ``fal_client`` SDK and cache it on this module.-- Delegates the actual import to :func:`tools.fal_common.import_fal_client`- so the ``pm.ensure_import`` handling stays in one place.-- Thread-safe via double-checked locking: concurrent first calls import- the SDK exactly once instead of each racing thread re-running the import.- """- global _fal_client- if _fal_client is not None:- return _fal_client- with _fal_client_lock:- if _fal_client is not None: # re-check inside the lock- return _fal_client- from tools.fal_common import import_fal_client- _fal_client = import_fal_client()- return _fal_client--# ---------------------------------------------------------------------------# Managed FAL gateway (Nous Subscription)# ---------------------------------------------------------------------------diff --git a/plugins/web/_common.py b/plugins/web/_common.pyindex 3576c399bcd..7b397cf3250 100644--- a/plugins/web/_common.py+++ b/plugins/web/_common.py@@ -167,14 +167,13 @@ def titled_rows(raw_results: List[Dict[str, Any]], description_key: str) -> List]-def lazy_ensure(feature: str) -> None:- """Best-effort ``tools.lazy_deps.ensure``: its own ImportError is benign and swallowed;- an install hint (any other error) is re-raised as ImportError."""+def lazy_ensure(extra: str) -> None:+ """Best-effort ``pm.ensure_import``: a missing-but-unavailable extra raises+ ``pm.InstallError``, re-raised as ImportError for the caller's own handling."""+ import pm+try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure(feature, prompt=False)- except ImportError:- pass+ pm.ensure_import(extra)except Exception as exc: # noqa: BLE001raise ImportError(str(exc))diff --git a/plugins/web/exa/provider.py b/plugins/web/exa/provider.pyindex f6d4dc753ba..fad5bea3b54 100644--- a/plugins/web/exa/provider.py+++ b/plugins/web/exa/provider.py@@ -26,7 +26,7 @@ def _get_exa_client() -> Any:client.headers["x-exa-integration"] = "hermes-agent"return client- return cached_sdk_client("_exa_client", "EXA_API_KEY", _MISSING_KEY, "search.exa", _factory)+ return cached_sdk_client("_exa_client", "EXA_API_KEY", _MISSING_KEY, "exa", _factory)class ExaWebSearchProvider(BaseWebSearchProvider):diff --git a/plugins/web/parallel/provider.py b/plugins/web/parallel/provider.pyindex b69647da57b..c35b7009a78 100644--- a/plugins/web/parallel/provider.py+++ b/plugins/web/parallel/provider.py@@ -38,7 +38,7 @@ def _client(slot: str, cls_name: str) -> Any:passexcept Exception as exc: # noqa: BLE001 — surface install hint as ImportErrorraise ImportError(str(exc))- return cached_sdk_client(slot, "PARALLEL_API_KEY", _MISSING_KEY, "search.parallel", _factory)+ return cached_sdk_client(slot, "PARALLEL_API_KEY", _MISSING_KEY, "parallel-web", _factory)def _get_sync_client() -> Any:diff --git a/pm/cli.py b/pm/cli.pyindex b786613943a..cea1e929ba2 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -109,8 +109,10 @@ def _bundle_package_names() -> list[str]:def cmd_install(args) -> int:+ # Source-install launchers require the store interpreter, even though+ # Python remains optional when provisioning individual tools.names = args.names or [- n for n in _lockfile().names() if not get_package(n).optional+ n for n in _lockfile().names() if not get_package(n).optional or n == "python"]failed = _install_names(names)if not args.names:@@ -139,7 +141,7 @@ def cmd_env(args) -> int:def cmd_doctor(args) -> int:- from pm.ensure import _identity+ from pm.ensure import _identity, _installed_locationfrom pm.store import tree_digestlockfile = _lockfile()@@ -153,6 +155,7 @@ def cmd_doctor(args) -> int:if reason is not None:print(f"- {name}: n/a on {target} ({reason})")continue+ facts, store = _installed_location(package, lockfile, target) or (_facts(), _store())fact = facts.get(name)soft = package.optional or package.internalidentity = _identity(lockfile, name, target)@@ -564,7 +567,6 @@ def cmd_bundle(args) -> int:print(f"✓ repo ({ref})")os.environ["HERMES_RUNTIME_DIR"] = str(store_dir)- paths._stamp.cache_clear()names = _bundle_package_names()failed = _install_names(diff --git a/pm/ensure.py b/pm/ensure.pyindex 18bb85d7807..d8d1152af7f 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -40,6 +40,19 @@ def _store() -> Store:return Store(paths.store_root())+def _installed_location(package: Package, lockfile: Lockfile, target: str, *, verify: bool = False):+ """Select matching shipped bytes first, then an added pinned store entry."""+ roots = dict.fromkeys([paths.store_root(), paths.writable_store_root()])+ for root in roots:+ store = Store(root)+ facts = _facts() if root == paths.store_root() else Facts(root / "facts.json")+ if facts.installed(package.name, lockfile.version(package.name), root,+ _identity(lockfile, package.name, target)):+ if not verify or _entry_verified(package, facts.get(package.name), store, target):+ return facts, store+ return None++def _identity(lockfile: Lockfile, name: str, target: str):"""The identity the lock currently pins for `name` on `target`:(target, tuple(artifact sha256s)) — or None when the lock pins no@@ -79,18 +92,12 @@ def lazy_installs_allowed() -> bool:def enabled_extras() -> list[str]:"""The venv extras recorded in the installed state."""- return list((_facts().get("venv") or {}).get("extras", []))+ fact = Facts(paths.runtime_facts_path()).get("venv") or _facts().get("venv") or {}+ return list(fact.get("extras", []))def is_installed(name: str) -> bool:- lockfile = _lockfile()- facts = _facts()- return facts.installed(- name,- lockfile.version(name),- _store().root,- _identity(lockfile, name, current_target()),- )+ return _installed_location(get_package(name), _lockfile(), current_target()) is not Nonedef sealed() -> bool:@@ -101,12 +108,6 @@ def sealed() -> bool:def _refuse_lazy(name: str, what: str) -> InstallError:- if sealed():- return InstallError(- name,- f"this install is sealed and does not ship: {what}",- "the bundle bakes its entire tree at build time; rebuild the bundle",- )return InstallError(name,f"not installed and lazy installs are disabled: {what}",@@ -115,18 +116,20 @@ def _refuse_lazy(name: str, what: str) -> InstallError:def _remove_entry(store: Store, entry_name: str) -> None:- """Remove a published store entry before re-realizing it. NOT- fire-and-forget: a silent failure here would leave the stale entry in- place and publish() would then keep it (a concurrent-winner guard),- re-recording facts over bytes the new lock never produced. Defender /- indexer handles on Windows make removal transiently fail, so retry —- then fail loudly."""+ """Remove a replaced or failed entry, retrying transient Windows holds.++ Corruption may leave a file where the directory belonged. Failure+ must propagate so recovery never claims to have removed surviving bytes.+ """import timeentry = store.entry(entry_name)for attempt in range(5):try:- shutil.rmtree(entry)+ if entry.is_symlink() or not entry.is_dir():+ entry.unlink(missing_ok=True)+ else:+ shutil.rmtree(entry)returnexcept FileNotFoundError:return@@ -136,6 +139,33 @@ def _remove_entry(store: Store, entry_name: str) -> None:time.sleep(0.2 * (attempt + 1))+def _entry_verified(package: Package, fact: dict, store: Store, target: str) -> bool:+ """Explicit installs re-check realized bytes; startup keeps its cheap facts check."""+ entry = store.entry(fact["entry"])+ try:+ return not package.verify(entry, target) and fact.get("digest") == tree_digest(entry)+ except OSError:+ return False+++def _restore_previous_entry(store: Store, entry, previous) -> None:+ """Keep both versions recoverable until the restore rename succeeds."""+ import uuid++ displaced = store.entry(f".displaced-{uuid.uuid4().hex}")+ had_entry = entry.exists() or entry.is_symlink()+ if had_entry:+ entry.rename(displaced)+ try:+ previous.rename(entry)+ except BaseException:+ if had_entry:+ displaced.rename(entry)+ raise+ if had_entry:+ _remove_entry(store, displaced.name)++def _install(package: Package,lockfile: Lockfile,@@ -159,55 +189,73 @@ def _install(with store.install_lock():facts.reload()+ entry = store.entry(entry_name)+ previous_entry = store.entry(f".previous-{entry_name}")+ if previous_entry.exists():+ # An interrupted replacement keeps its old bytes outside scratch.+ # Facts commit last; only a verified committed replacement wins.+ fact = facts.get(package.name)+ if fact and fact.get("entry") == entry_name and _entry_verified(package, fact, store, target):+ _remove_entry(store, previous_entry.name)+ else:+ _restore_previous_entry(store, entry, previous_entry)if facts.installed(package.name, version, store.root, _identity(lockfile, package.name, target)- ):+ ) and _entry_verified(package, facts.get(package.name), store, target):return- entry = store.entry(entry_name)- _cond = store.published(entry_name) and package.verify(entry, target) == ""- if _cond:- _remove_entry(store, entry_name)- if not store.published(entry_name):- if not artifacts:- raise InstallError(- package.name,- f"no artifact for {target} in the lockfile",- "run `hermes pm lock --bump` for this package",- )- with store.scratch() as scratch:- staged = scratch / "tree"+ if not artifacts:+ raise InstallError(+ package.name,+ f"no artifact for {target} in the lockfile",+ "run `hermes pm lock --bump` for this package",+ )+ with store.scratch() as scratch:+ staged = scratch / "tree"+ previous = facts.get(package.name)+ try:+ for index, artifact in enumerate(artifacts):+ label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""+ archive = store.fetch(+ artifact["url"], artifact["sha256"], scratch,+ progress=_artifact_progress(progress, index, len(artifacts)),+ )+ if progress is not None:+ progress("unpack", 0, 0, label)+ if index == 0:+ package.unpack(archive, staged, target)+ continue+ # unpack() empties its destination; merge additional+ # archives only after extracting them separately.+ extra = scratch / f"extra-{index}"+ package.unpack(archive, extra, target)+ merge_tree(extra, staged)+ package.stage(store, staged, version, target)+ reason = package.verify(staged, target)+ if reason:+ raise InstallError(package.name, f"staged entry failed verification: {reason}")+ if entry.exists():+ entry.rename(previous_entry)try:- for index, artifact in enumerate(artifacts):- label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""- archive = store.fetch(- artifact["url"], artifact["sha256"], scratch,- progress=_artifact_progress(- progress, index, len(artifacts)),- )- if progress is not None:- progress("unpack", 0, 0, label)- if index == 0:- package.unpack(archive, staged, target)- continue- # unpack() empties its destination by contract, so- # a second archive must be unpacked apart and moved- # in — extracting over `staged` would delete the- # first archive's files.- extra = scratch / f"extra-{index}"- package.unpack(archive, extra, target)- merge_tree(extra, staged)- package.stage(store, staged, version, target)store.publish(staged, entry_name)- except InstallError:+ reason = package.verify(entry, target)+ if reason:+ raise InstallError(package.name, f"published entry failed verification: {reason}")+ facts.record(+ package.name, version, entry_name, package.env(entry, target), store.root,+ target=target, artifacts=[a["sha256"] for a in artifacts],+ digest=tree_digest(entry),+ )+ except BaseException:+ if previous_entry.exists():+ _restore_previous_entry(store, entry, previous_entry)raise- except Exception as e:- raise InstallError(package.name, f"install failed: {e}") from e-- reason = package.verify(entry, target)- if reason:- raise InstallError(package.name, f"published entry failed verification: {reason}")+ if previous_entry.exists():+ _remove_entry(store, previous_entry.name)+ except InstallError:+ raise+ except Exception as e:+ raise InstallError(package.name, f"install failed: {e}") from e- previous = facts.get(package.name)if previous and "entry" in previous:# Work item 6: replacing an ESTABLISHED fact is a repair —# log it, no transaction system, no receipt file.@@ -219,17 +267,6 @@ def _install(else version)LOG.info("repair: %s re-realized %s -> %s", package.name, old, new)- env = package.env(entry, target)- facts.record(- package.name,- version,- entry_name,- env,- store.root,- target=target,- artifacts=[a["sha256"] for a in artifacts],- digest=tree_digest(entry),- )if previous and previous.get("version") != version:package.migrate(previous["version"], version)@@ -253,36 +290,22 @@ def ensure(return Runner(name, compose_env([], base=base_env))lockfile = _lockfile()- facts = _facts()- store = _store()target = current_target()-chain = walk([name])- missing = [- p- for p in chain- if not facts.installed(- p.name, lockfile.version(p.name), store.root, _identity(lockfile, p.name, target)- )- ]-- if missing and (sealed() or (not explicit and not lazy_installs_allowed())):+ missing = [p for p in chain if _installed_location(p, lockfile, target, verify=explicit) is None]+ if missing and not explicit and not lazy_installs_allowed():raise _refuse_lazy(name, ", ".join(p.name for p in missing))-- for package in missing:- _install(package, lockfile, facts, store, target, progress=progress)if missing:- facts.reload()-- diffs = [facts.env_for(p.name, store.root) for p in chain]- return Runner(name, compose_env(diffs, base=base_env))+ store = Store(paths.writable_store_root())+ facts = _facts() if store.root == paths.store_root() else Facts(store.root / "facts.json")+ for package in missing:+ _install(package, lockfile, facts, store, target, progress=progress)+ return Runner(name, env_for(name, base_env=base_env))def env_for(*names: str, base_env: Optional[dict] = None) -> dict[str, str]:"""Composed env of already-installed packages only. Never installs,never raises on missing packages — they contribute nothing."""- facts = _facts()- store = _store()lockfile = _lockfile()target = current_target()diffs: list[dict] = []@@ -292,17 +315,24 @@ def env_for(*names: str, base_env: Optional[dict] = None) -> dict[str, str]:except KeyError:continuefor package in chain:- if facts.installed(- package.name,- lockfile.version(package.name),- store.root,- _identity(lockfile, package.name, target),- ):+ location = _installed_location(package, lockfile, target)+ if location:+ facts, store = locationdiffs.append(facts.env_for(package.name, store.root))return compose_env(diffs, base=base_env)-def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False) -> None:+def _runtime_state_matches(fact: dict, stamp: str) -> bool:+ if fact.get("stamp") != stamp:+ return False+ environment = fact.get("environment")+ if environment is None:+ return True # shipped/pre-generation state+ from pathlib import Path+ return isinstance(environment, str) and (Path(environment) / "pyvenv.cfg").is_file()+++def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plugin_dirs=None, before_publish=None) -> None:"""Make the venv match uv.lock + the enabled extras. Extras union intothe installed state (one ledger); no-op when the stamp already matches.``explicit`` marks a deliberate install command (`hermes pm install`,@@ -313,36 +343,76 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False) ->security.allow_lazy_installs is false AND the bundle'senabled-features.json exists, the feature list is FROZEN to that file— requested extras outside it are refused, and plugin members are- never installed (the bundle IS the install)."""+ never installed (the bundle IS the install).++ Receipt contract: EVERY outcome writes a receipt. ``begin`` fires+ BEFORE the frozen/lazy refusals (a refusal is a recorded ``failed``+ outcome, not a silent raise); finalize runs in FINALLY — no-op syncs+ ("ok" with ``venv_rebuild`` false) and refusals ("failed") both get+ a receipt. ``before_publish`` is the concrete selection hook: called+ while the install lock is held, AFTER the environment staged and+ BEFORE the facts write — it returns an undo callable that runs if+ the facts write then fails, so a selection committed here is rolled+ back atomically instead of drifting from the surviving environment.+ No module globals, no callback framework — one hook, one consumer."""+ from pm import receiptfrom pm.features import read_features- frozen = read_features() if not lazy_installs_allowed() else None- if frozen is not None and extras:- outside = sorted(set(extras) - set(frozen))- if outside:- raise _refuse_lazy(- "venv",- f"extras {outside} are outside this bundle's frozen feature "- "set (security.allow_lazy_installs is false)",- )- package = get_package("venv")- facts = _facts()- fact = facts.get("venv") or {}- enabled = sorted(set(fact.get("extras", [])) | set(extras or []))- stamp = package.expected_stamp(enabled)- if fact.get("stamp") == stamp:- return- if sealed() or (not explicit and not lazy_installs_allowed()):- raise _refuse_lazy("venv", str(extras) if extras else "venv out of sync")- with _store().install_lock():- facts.reload()- fact = facts.get("venv") or {}+ token = receipt.begin("sync")+ outcome = "failed"+ try:+ frozen = read_features() if not lazy_installs_allowed() else None+ if frozen is not None and extras:+ outside = sorted(set(extras) - set(frozen))+ if outside:+ raise _refuse_lazy(+ "venv",+ f"extras {outside} are outside this bundle's frozen feature "+ "set (security.allow_lazy_installs is false)",+ )++ package = get_package("venv")+ inputs = {} if plugin_dirs is None else {"plugin_dirs": plugin_dirs}+ facts = Facts(paths.runtime_facts_path())+ baseline = _facts().get("venv") or {}+ fact = facts.get("venv") or baselineenabled = sorted(set(fact.get("extras", [])) | set(extras or []))- stamp = package.expected_stamp(enabled)- if fact.get("stamp") == stamp:+ stamp = package.expected_stamp(enabled, **inputs)+ if before_publish is None and _runtime_state_matches(fact, stamp):+ receipt.record_venv_rebuild(False, "already in sync")+ outcome = "ok"return- package.apply(enabled)- facts.record_state("venv", stamp, enabled)+ if not explicit and not lazy_installs_allowed() and not _runtime_state_matches(fact, stamp):+ raise _refuse_lazy("venv", str(extras) if extras else "venv out of sync")+ with Store(facts.path.parent).install_lock():+ facts.reload()+ fact = facts.get("venv") or baseline+ enabled = sorted(set(fact.get("extras", [])) | set(extras or []))+ stamp = package.expected_stamp(enabled, **inputs)+ if _runtime_state_matches(fact, stamp):+ if before_publish is not None:+ before_publish()+ receipt.record_venv_rebuild(False, "already in sync")+ outcome = "ok"+ return+ receipt.record_feature_list(enabled)+ undo = None+ try:+ result = package.apply(enabled, **inputs) or {}+ if before_publish is not None:+ undo = before_publish()+ facts.record_state("venv", stamp, enabled, **result)+ receipt.record_venv_rebuild(True)+ except BaseException:+ if undo is not None:+ try:+ undo()+ except Exception:+ LOG.exception("pm sync: publish undo failed; config may drift")+ raise+ outcome = "ok"+ finally:+ receipt.finalize(outcome, 0 if outcome == "ok" else 1, token=token)def adopt() -> bool:@@ -362,7 +432,8 @@ def adopt() -> bool:if not paths.facts_path().is_file():return False- marker = store.root.parent / ".adopted"+ from hermes_cli.runtime_paths import install_state_dir+ marker = install_state_dir(paths.repo_root()) / ".adopted"if marker.is_file():return False@@ -404,23 +475,11 @@ def adopt() -> bool:return Falsetry:+ marker.parent.mkdir(parents=True, exist_ok=True)marker.write_text("", encoding="utf-8")except OSError:- pass-- # Bootstrap the mutable venv (sealed installs): lazy-off copies the- # shipped venv out as the seed; lazy-on builds fresh from the shipped- # uv cache on first sync. Failure is reported, never fatal — a cold- # sync still converges.- try:- venv_package = get_package("venv")- except KeyError:- venv_package = None- seed = getattr(venv_package, "seed_mutable_venv", None) if venv_package else None- if seed is not None:- reason = seed()- if reason:- LOG.info("pm adopt: mutable venv seed skipped: %s", reason)+ LOG.warning("could not record payload verification", exc_info=True)+ return Falsereturn True@@ -432,7 +491,7 @@ def check() -> list[str]:(no installed-state file) reports nothing — pm only vouches for whatit installed. Lockfile packages this build doesn't know (version skewduring a partial update) are skipped, not fatal."""- if not paths.facts_path().is_file():+ if not paths.facts_path().is_file() and not paths.runtime_facts_path().is_file():return []problems: list[str] = []@@ -449,18 +508,16 @@ def check() -> list[str]:continueif package.missing_reason(target) is not None:continue- if not facts.installed(- name, lockfile.version(name), store.root, _identity(lockfile, name, target)- ):+ if _installed_location(package, lockfile, target) is None:problems.append(f"{name}: not installed or outdated")try:venv = get_package("venv")except KeyError:venv = None- fact = facts.get("venv")+ fact = Facts(paths.runtime_facts_path()).get("venv") or facts.get("venv")if venv is not None and fact is not None:expected = venv.expected_stamp(fact.get("extras", []))- if fact.get("stamp") != expected:+ if not _runtime_state_matches(fact, expected):problems.append("venv: out of sync with uv.lock")return problems@@ -472,10 +529,6 @@ def _store_path_dirs() -> list[str]:though it's not in the root closure. Never installs."""import os- if not paths.facts_path().is_file():- return []- facts = _facts()- store = _store()lockfile = _lockfile()target = current_target()dirs: list[str] = []@@ -490,10 +543,10 @@ def _store_path_dirs() -> list[str]:continueif package.missing_reason(target) is not None:continue- if not facts.installed(- name, lockfile.version(name), store.root, _identity(lockfile, name, target)- ):+ location = _installed_location(package, lockfile, target)+ if location is None:continue+ facts, store = locationenv = facts.env_for(name, store.root)path_dirs = env.get("PATH") or []if isinstance(path_dirs, str):@@ -545,22 +598,21 @@ def uv(*, venv=None, realize: bool = True):env.pop("UV_NO_CONFIG", None)lockfile = _lockfile()- facts = _facts()- store = _store()package = get_package("uv")- if not facts.installed(- "uv", lockfile.version("uv"), store.root, _identity(lockfile, "uv", current_target())- ):+ location = _installed_location(package, lockfile, current_target())+ if location is None:if not realize or not lazy_installs_allowed():return None, env+ store = Store(paths.writable_store_root())+ facts = _facts() if store.root == paths.store_root() else Facts(store.root / "facts.json")try:_install(package, lockfile, facts, store, current_target())facts.reload()except Exception:- import logging-- logging.getLogger(__name__).debug("pm.uv: install failed", exc_info=True)+ LOG.debug("pm.uv: install failed", exc_info=True)return None, env+ else:+ facts, store = locationfact = facts.get("uv")if fact is None:return None, envdiff --git a/pm/extras.py b/pm/extras.pyindex 9a4b654ef0f..d34c70aa3d4 100644--- a/pm/extras.py+++ b/pm/extras.py@@ -168,6 +168,18 @@ def ensure_import(extra: str) -> None:from pm.ensure import sync_venvsync_venv([extra])+ # Activation is a process-boot operation. Never mix a newly resolved+ # dependency tree with libraries already imported by this process.+ from hermes_cli.runtime_paths import selected_venv, site_packages+ from pm.paths import repo_root, runtime_facts_path+ import sys+ from pathlib import Path++ if runtime_facts_path().is_file():+ selected = site_packages(selected_venv(repo_root())).resolve()+ if selected not in {Path(entry).resolve() for entry in sys.path}:+ from pm.package import InstallError+ raise InstallError("venv", f"{extra} installed; restart Hermes to activate the new dependency environment")def ensure_and_bind(extra, importer, target_globals) -> bool:diff --git a/pm/lock.py b/pm/lock.pyindex 94ee6b08a52..a5b28efc069 100644--- a/pm/lock.py+++ b/pm/lock.py@@ -35,7 +35,7 @@ def _read(path: Path) -> dict:return {"schema": SCHEMA, "packages": {}}try:data = json.loads(text)- if data.get("schema") == SCHEMA and isinstance(data.get("packages"), dict):+ if isinstance(data, dict) and data.get("schema") == SCHEMA and isinstance(data.get("packages"), dict):return dataexcept ValueError:pass@@ -44,7 +44,12 @@ def _read(path: Path) -> dict:# the next _write would silently discard every installed-state# record. Keep the bytes for post-mortem.try:- path.with_suffix(".corrupt").write_text(text, encoding="utf-8")+ from pm.paths import store_root+ if path.parent == store_root() and (store_root().parent / "manifest.json").is_file():+ import logging+ logging.getLogger(__name__).warning("invalid shipped state file: %s", path)+ else:+ path.with_suffix(".corrupt").write_text(text, encoding="utf-8")except OSError:passreturn {"schema": SCHEMA, "packages": {}}@@ -171,9 +176,17 @@ class Facts:fact["digest"] = digestself._merge_and_write(name, fact)- def record_state(self, name: str, stamp: str, extras: list[str]) -> None:- """State packages (the venv) have a stamp and extras, no entry."""- self._merge_and_write(name, {"stamp": stamp, "extras": extras})+ def record_state(+ self, name: str, stamp: str, extras: list[str], *,+ environment: Path | None = None, resolved_lock: Path | None = None,+ ) -> None:+ """Commit a verified state package and its selected environment atomically."""+ fact = {"stamp": stamp, "extras": extras}+ if environment is not None:+ fact["environment"] = str(environment.resolve())+ if resolved_lock is not None:+ fact["resolved_lock"] = str(resolved_lock.resolve())+ self._merge_and_write(name, fact)def entries_in_use(self) -> set[str]:return {f["entry"] for f in self._packages.values() if "entry" in f}diff --git a/pm/packages.py b/pm/packages.pyindex c27efe0577e..0c101fa12e7 100644--- a/pm/packages.py+++ b/pm/packages.py@@ -21,10 +21,12 @@ from pm.package import (from pm.registry import registerfrom pm.store import ALL_TARGETS, Store, flatten_single_dir, merge_treefrom pm.update import (+ btbn_index,btbn_versions,github_release_tags,llama_app_bucket_versions,llama_app_latest,+ martin_riedl_index,martin_riedl_versions,node_latest_versions,npm_dist_tags,@@ -345,49 +347,11 @@ class Venv(StatePackage):return repo_root()def venv_dir(self) -> Path:- # Sealed installs are read-only: the MUTABLE venv lives in the- # writable machine hermes root (get_default_hermes_root()/venv —- # per-install, beside the uv cache), seeded on first adopt by- # copying the payload's shipped venv out. Dev/source installs- # keep the repo-local venv (project_venv_dir) unchanged.- from pm.ensure import sealed-- if sealed():- from hermes_constants import get_default_hermes_root-- return get_default_hermes_root() / "venv"- from hermes_constants import project_venv_dir-- found = project_venv_dir(self.project_root())- return found if found else self.project_root() / "venv"-- def seed_mutable_venv(self) -> Optional[str]:- """Bootstrap the mutable venv from the shipped payload venv- (lazy-off installs). Returns None on success, else why not."""- import shutil-- from pm.ensure import lazy_installs_allowed, sealed- from pm.paths import store_root-- if not sealed():- return None # dev installs use the repo venv directly- dest = self.venv_dir()- if dest.exists():- return None # already bootstrapped- if lazy_installs_allowed():- # Lazy installs ON: build fresh from the shipped uv cache —- # no seed copy needed (the sync is near-free from the cache).- return None- payload_venv = store_root().parent / "venv"- if not payload_venv.is_dir():- return "payload ships no venv to seed from"- try:- shutil.copytree(payload_venv, dest)- except OSError as exc:- return f"seed copy failed: {exc}"- return None+ from hermes_cli.runtime_paths import selected_venv++ return selected_venv(self.project_root())- def expected_stamp(self, extras: list[str]) -> str:+ def expected_stamp(self, extras: list[str], *, plugin_dirs=None) -> str:import hashlibimport sys@@ -399,93 +363,52 @@ class Venv(StatePackage):# re-sync even when extras and core lock are unchanged.from pm.workspace import enabled_member_dirs, members_stamp- h.update(members_stamp(enabled_member_dirs()).encode())+ h.update(members_stamp(enabled_member_dirs() if plugin_dirs is None else plugin_dirs).encode())return h.hexdigest()- def apply(self, extras: list[str]) -> None:+ def apply(self, extras: list[str], *, plugin_dirs=None) -> dict:+ """Prepare one complete environment; the caller commits its selection."""+ import sys+ import uuid+ from hermes_cli.runtime_paths import install_state_dir, runtime_facts_pathfrom pm.ensure import uv as pm_uv+ from pm.lock import Factsfrom pm.workspace import enabled_member_dirs, lock_and_sync- member_dirs = enabled_member_dirs()- if member_dirs:- # Lazy installs OFF = the frozen bundle feature set: plugin- # members are never installed (the bundle IS the install).- from pm.ensure import lazy_installs_allowed-- if not lazy_installs_allowed():- from pm.features import read_features-- if read_features() is not None:- raise InstallError(- self.name,- "plugin members present but lazy installs are "- "disabled — this bundle's feature set is frozen "- "(remove the plugin or enable lazy installs)",- )- # Plugin deps union into the venv through the generated- # workspace root (one lock, conflict = loud refusal). On- # conflict, resolve_union bisects: fail-alone plugins and- # mutual-conflict losers (incumbent wins) are dropped with- # their resolver reasons, and the union retries.- from pm.workspace import record_disabled_plugins, resolve_union-- import logging-- survivors, decisions = resolve_union(- member_dirs, extras, venv_dir=self.venv_dir()- )- for decision in decisions:- logging.getLogger(__name__).warning(- "plugin %s disabled by the venv union: %s",- decision["plugin"],- decision["reason"],- )- # Write bisect disables back to the plugins enabled config —- # `hermes plugins list` must reflect reality and re-enable- # must retry. Best-effort: a config write failure never- # breaks the sync.- try:- record_disabled_plugins(decisions)- except Exception:- logging.getLogger(__name__).warning(- "could not persist bisect disable decisions", exc_info=True- )- # Receipt: the machine-readable surface for this rebuild- # (same schema/dir as update receipts; the updater embeds- # these sections via pm.receipt.snapshot()).- try:- from pm import receipt-- receipt.begin("sync")- receipt.record_feature_list(sorted(extras))- receipt.record_venv_rebuild(True)- if decisions:- receipt.record_bisect(decisions)- receipt.finalize("bisected")- else:- receipt.finalize("ok")- except Exception:- pass- return-- uv_bin, env = pm_uv(venv=self.venv_dir())+ project = self.project_root()+ generation = install_state_dir(project) / "environments" / uuid.uuid4().hex+ candidate = generation / "venv"+ uv_bin, env = pm_uv()if uv_bin is None:raise InstallError(self.name, "uv is not installed")- cmd = [uv_bin, "sync", "--frozen"]- for extra in sorted(extras):- cmd += ["--extra", extra]- proc = subprocess.run(- cmd,- cwd=str(self.project_root()),- capture_output=True,- text=True,- timeout=1800,- env=env,- )- if proc.returncode != 0:- raise InstallError(- self.name, f"uv sync exited {proc.returncode}: {proc.stderr[-400:]}"+ env["UV_PROJECT_ENVIRONMENT"] = str(candidate)+ env.pop("UV_NO_CONFIG", None) # project indexes/sources belong to the project+ members = enabled_member_dirs() if plugin_dirs is None else plugin_dirs+ try:+ generation.mkdir(parents=True)+ create = subprocess.run(+ [uv_bin, "venv", "--relocatable", "--python", sys.executable, str(candidate)],+ env=env, capture_output=True, text=True, timeout=120,+ )+ if create.returncode:+ raise InstallError(self.name, f"uv venv failed: {create.stderr[-600:]}")+ prior = Facts(runtime_facts_path(project)).get("venv") or {}+ seed = (Path(prior["resolved_lock"]) if members and prior.get("resolved_lock")+ else project / "uv.lock")+ lock_and_sync(members, extras, venv_dir=candidate, root=generation / "workspace",+ seed_lock=seed, frozen=not members, env=env)+ resolved_lock = generation / "workspace" / "uv.lock"+ python = candidate / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ checked = subprocess.run(+ [uv_bin, "pip", "check", "--python", str(python)],+ env=env, capture_output=True, text=True, timeout=60,)+ if checked.returncode:+ raise InstallError(self.name, f"dependency validation failed: {checked.stderr[-600:]}")+ except BaseException:+ shutil.rmtree(generation, ignore_errors=True)+ raise+ return {"environment": candidate, "resolved_lock": resolved_lock}@register@@ -517,12 +440,14 @@ class Npm(BinaryPackage):bundled npm instead. --offline pins the bytes to the verifiedtarball; --ignore-scripts + a sanitized env keep user npm/nodeconfig out of the staging."""- from pm.ensure import _facts, _store+ from pm.ensure import _installed_location, _lockfilefrom pm.registry import get_package- facts = _facts()- store = _store()node = get_package("node")+ location = _installed_location(node, _lockfile(), target)+ if location is None:+ raise InstallError(self.name, "npm extends node, which is not installed")+ facts, store = locationnode_fact = facts.get("node")if node_fact is None:raise InstallError(self.name, "npm extends node, which is not installed")@@ -670,46 +595,26 @@ class Ffmpeg(BinaryPackage):def fetch_url(self, version: str, target: str) -> str:osname, arch = target.split("-")if osname == "win32":- # BtbN: the newest autobuild tag whose assets carry this version.- for tag, asset in btbn_index().get(version, [])[:1]:- return (- "https://github.com/BtbN/FFmpeg-Builds/releases/download/"- f"{tag}/{asset}"- )- # Fall back to the pinned build (index unreachable) — this must- # match what the lockfile's own urls carry for the same version.- return self._btbn_fallback(version, target)- # martin-riedl: /download/<os>/<arch>/<epoch>_<version>/ffmpeg.zip- martin = {- ("linux", "x64"): "linux/amd64/1787074600_9.0.1",- ("linux", "arm64"): "linux/arm64/1787072884_9.0.1",- ("darwin", "x64"): "macos/amd64/1787081194_9.0.1",- ("darwin", "arm64"): "macos/arm64/1787073674_9.0.1",- }- epoch = None- for t, by_version in martin_riedl_index().items():- if t == target and version in by_version:- epoch = by_version[version]- break- if epoch is not None:- osdir = "macos" if osname == "darwin" else "linux"- return f"https://ffmpeg.martin-riedl.de/download/{osdir}/{arch}/{epoch}_{version}/ffmpeg.zip"- # Fall back to the hardcoded pinned path (index unreachable).- return f"https://ffmpeg.martin-riedl.de/download/{martin[(osname, arch)]}/ffmpeg.zip"+ artifact = btbn_index().get(target, {}).get(version)+ if artifact is not None:+ tag, asset = artifact+ return f"https://github.com/BtbN/FFmpeg-Builds/releases/download/{tag}/{asset}"+ else:+ epoch = martin_riedl_index().get(target, {}).get(version)+ if epoch is not None:+ osdir = "macos" if osname == "darwin" else "linux"+ source_arch = "amd64" if arch == "x64" else arch+ return f"https://ffmpeg.martin-riedl.de/download/{osdir}/{source_arch}/{epoch}_{version}/ffmpeg.zip"+ # Existing installs read exact URLs from the lockfile. Re-pinning+ # must never silently substitute a different version or target.+ raise InstallError(self.name, f"no advertised {version} artifact for {target}",+ "retry when the upstream index is available, or keep the existing pin")def latest_versions(self, target: str, locked=None) -> list[str]:if target.startswith("win32"):- return btbn_versions()+ return btbn_versions(target)return martin_riedl_versions(target)- def _btbn_fallback(self, version: str, target: str) -> str:- arch = "arm64" if target.endswith("arm64") else "64"- return (- "https://github.com/BtbN/FFmpeg-Builds/releases/download/"- f"autobuild-2026-08-28-17-08/ffmpeg-n{version}-11-ge47273f4d9-"- f"win{arch}-gpl-9.0.zip"- )-@registerdiff --git a/pm/paths.py b/pm/paths.pyindex 6343baa3ad9..72b4ad89678 100644--- a/pm/paths.py+++ b/pm/paths.py@@ -2,9 +2,6 @@from __future__ import annotations-import json-import os-from functools import lru_cachefrom pathlib import Path@@ -16,36 +13,10 @@ def lockfile_path() -> Path:return Path(__file__).resolve().parent / "lock.json"-@lru_cache(maxsize=1)-def _stamp() -> dict:- for parent in (repo_root(), *repo_root().parents):- stamp = parent / "install-stamp.json"- if stamp.is_file():- try:- return json.loads(stamp.read_text(encoding="utf-8-sig"))- except (OSError, ValueError):- return {}- return {}--def store_root() -> Path:- """The byte store. Entries are keyed (package, version, target) and- hold nothing profile-specific, so the store is MACHINE-scoped: a- second profile reuses the engine and browser this machine already- downloaded instead of fetching its own copy.+ from hermes_cli.runtime_paths import store_root as resolve- A payload overrides it — a sealed bundle carries its own store beside- its manifest, and that IS per-install by construction.- """- env = os.environ.get("HERMES_RUNTIME_DIR")- if env:- return Path(env).resolve()- stamped = _stamp().get("runtimeDir")- if stamped:- return Path(stamped).resolve()- from hermes_constants import get_default_hermes_root-- return get_default_hermes_root() / "tools"+ return resolve(repo_root())def partials_root() -> Path:@@ -65,3 +36,17 @@ def partials_root() -> Path:def facts_path() -> Path:return store_root() / "facts.json"+++def writable_store_root() -> Path:+ if not (store_root().parent / "manifest.json").is_file():+ return store_root()+ from hermes_constants import get_default_hermes_root++ return get_default_hermes_root() / "tools"+++def runtime_facts_path() -> Path:+ from hermes_cli.runtime_paths import runtime_facts_path as resolve++ return resolve(repo_root())diff --git a/pm/plugins_state.py b/pm/plugins_state.pyindex b75e926241b..d57d8d59b40 100644--- a/pm/plugins_state.py+++ b/pm/plugins_state.py@@ -11,7 +11,7 @@ second authority for enabled state.from __future__ import annotationsfrom pathlib import Path-from typing import Optional+from typing import Any, Optionaldef _profiles_root() -> Path:@@ -28,29 +28,41 @@ def _profiles_root() -> Path:return get_default_hermes_root() / "profiles"-def _enabled_list_for_home(home: Path) -> list[str]:- """plugins.enabled for ONE hermes home, ORDER-PRESERVING."""+def _read_home_config(home: Path) -> Optional[dict[str, Any]]:+ """Parse ONE home's config.yaml, or None when absent/unparseable.++ 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.+ """try:- import yaml+ import utilsconfig_path = home / "config.yaml"if not config_path.is_file():- return []- with config_path.open(encoding="utf-8-sig") as f:- config = yaml.safe_load(f) or {}- plugins_cfg = config.get("plugins") or {}- if not isinstance(plugins_cfg, dict):- return []- enabled = plugins_cfg.get("enabled")- if not isinstance(enabled, list):- return []- out: list[str] = []- for name in enabled:- if isinstance(name, str) and name and name not in out:- out.append(name)- return out+ return None+ config = utils.fast_safe_load(config_path.read_text(encoding="utf-8-sig"))+ return config if isinstance(config, dict) else Noneexcept Exception:+ return None+++def _enabled_from_config(config: dict[str, Any]) -> list[str]:+ """plugins.enabled from an already-parsed config, ORDER-PRESERVING."""+ plugins_cfg = config.get("plugins")+ if not isinstance(plugins_cfg, dict):return []+ enabled = plugins_cfg.get("enabled")+ if not isinstance(enabled, list):+ return []+ disabled = plugins_cfg.get("disabled", [])+ disabled = set(disabled) if isinstance(disabled, list) else set()+ out: list[str] = []+ for name in enabled:+ if (isinstance(name, str) and name and name not in out+ and name not in disabled and name.rsplit("/", 1)[-1] not in disabled):+ out.append(name)+ return outdef _all_homes() -> list[Path]:@@ -73,7 +85,7 @@ def _all_homes() -> list[Path]:return homes-def enabled_plugins_ordered() -> dict[Path, list[str]]:+def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None) -> dict[Path, list[str]]:"""plugins_dir → ordered enabled list, per home. Keyed by thePLUGINS DIR (where the member dirs live), not the home itself.@@ -84,26 +96,24 @@ def enabled_plugins_ordered() -> dict[Path, list[str]]:incumbent-wins tiebreak disables it before older plugins)."""out: dict[Path, list[str]] = {}for home in _all_homes():- enabled = _enabled_list_for_home(home)- provider = _active_memory_provider(home)- if provider and provider not in enabled:- enabled = enabled + [provider]- if enabled:- out[home / "plugins"] = enabled+ # ONE parse per home feeds both queries (enabled + provider).+ config = _read_home_config(home)+ config = config or {}+ if proposed_home is not None and home.resolve() == Path(proposed_home).resolve():+ config = {**config, "plugins": {"enabled": list(enabled or ()), "disabled": list(disabled or ())}}+ names = _enabled_from_config(config)+ provider = _provider_from_config(home, config)+ if provider and provider not in names:+ names.append(provider)+ if names:+ out[home / "plugins"] = namesreturn out-def _active_memory_provider(home: Path) -> Optional[str]:- """The home's ``memory.provider`` config key, when set and its plugin- dir exists (a provider name with no installed dir is not a member)."""+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:- import yaml-- config_path = home / "config.yaml"- if not config_path.is_file():- return None- with config_path.open(encoding="utf-8-sig") as f:- config = yaml.safe_load(f) or {}provider = (config.get("memory") or {}).get("provider")if not isinstance(provider, str) or not provider.strip():return None@@ -118,35 +128,43 @@ def _active_memory_provider(home: Path) -> Optional[str]:def disable_plugins(names: list[str]) -> dict[str, list[str]]:"""Remove names from EVERY home's enabled list (a bisect decisionnames the plugin, not the profile — disable where it's enabled).- Returns per-home what was removed. Writes via yaml round-trip of- the same config.yaml the plugins CLI owns."""+ Returns per-home what was removed.++ Writes go through utils.atomic_roundtrip_yaml_update — the same+ atomic, comment-preserving round-trip writer the plugins CLI's+ config path uses — pointed at that home's config.yaml (explicit+ home scope; pm never derives the target from ambient state). A+ write failure RAISES: a disable that didn't land must never be+ reported as removed. An EXISTING home config that can't be parsed+ also raises — silently skipping it would report success while the+ plugin stays enabled in that home.+ """removed: dict[str, list[str]] = {}if not names:return removedname_set = set(names)- import yamlfor home in _all_homes():config_path = home / "config.yaml"if not config_path.is_file():continue- try:- with config_path.open(encoding="utf-8-sig") as f:- config = yaml.safe_load(f) or {}- plugins_cfg = config.get("plugins")- if not isinstance(plugins_cfg, dict):- continue- enabled = plugins_cfg.get("enabled")- if not isinstance(enabled, list):- continue- kept = [n for n in enabled if not (isinstance(n, str) and n in name_set)]- hit = [n for n in enabled if isinstance(n, str) and n in name_set]- if not hit:- continue- plugins_cfg["enabled"] = kept- with config_path.open("w", encoding="utf-8") as f:- yaml.safe_dump(config, f, default_flow_style=False)- removed[str(home)] = hit- except Exception:+ config = _read_home_config(config_path.parent)+ if config is None:+ raise ValueError(+ f"could not parse existing config: {config_path}"+ )+ plugins_cfg = config.get("plugins")+ if not isinstance(plugins_cfg, dict):+ continue+ enabled = plugins_cfg.get("enabled")+ if not isinstance(enabled, list):continue+ hit = [n for n in enabled if isinstance(n, str) and n in name_set]+ if not hit:+ continue+ kept = [n for n in enabled if not (isinstance(n, str) and n in name_set)]+ import utils++ utils.atomic_roundtrip_yaml_update(config_path, "plugins.enabled", kept)+ removed[str(home)] = hitreturn removeddiff --git a/pm/receipt.py b/pm/receipt.pyindex 4d1ea88165c..5f5ab3fed52 100644--- a/pm/receipt.py+++ b/pm/receipt.py@@ -7,20 +7,43 @@ receipt with the SAME schema the updater's receipts useseparating kinds. One reader (``hermes pm status``, desktop IPC) servesevery surface: a failed venv rebuild is as reportable as a failedupdate.++The in-flight receipt lives in a ContextVar, not a module global: the+sync cadence and an ensure bisect can overlap across threads, and a+shared global lets one run's begin/finalize clobber another's record.++Two hazards of ContextVar state are handled explicitly:+- Copied contexts (``contextvars.copy_context()``, asyncio.to_thread)+ share the SAME dict object — so every record_* COPY-ON-WRITES: it+ deep-copies, mutates the copy, and re-sets it in the current context.+ A child task records into its own copy; the parent's receipt is+ untouched.+- A nested ``begin`` in the same context would silently drop the outer+ receipt. ``begin`` therefore returns the ContextVar token; passing it+ to ``finalize(..., token=...)`` restores the OUTER receipt instead of+ discarding it. The ambient no-token begin→finalize stays as-is (the+ existing linear consumers — pm sync, the plugin-check cadence)."""from __future__ import annotations+import contextvars+import copyimport json+import osimport time+import uuidfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Optional_RECEIPT_KEEP = 20-# Module current receipt — pm sync is a single-threaded CLI path.-_current: Optional[dict[str, Any]] = None+# Scoped current receipt — per-context (threads get their own via+# context isolation), same pattern as agent/context_compressor's pin.+_current: contextvars.ContextVar[Optional[dict[str, Any]]] = contextvars.ContextVar(+ "pm_receipt_current", default=None+)def _utc_now_iso() -> str:@@ -28,102 +51,116 @@ def _utc_now_iso() -> str:def _receipt_dir() -> Path:+ """The receipts dir — a pure path computation, NO mkdir side+ effect: readers (latest()) must not create state."""from hermes_constants import get_hermes_home- d = get_hermes_home() / "logs" / "update_receipts"- d.mkdir(parents=True, exist_ok=True)- return d---def begin(kind: str) -> None:- """Start recording a sync. ``kind``: 'sync' | 'update' (update embeds- the sync sections into its own receipt via `snapshot`)."""- global _current- _current = {- "schema": 1,- "kind": kind,- "started_at": _utc_now_iso(),- "steps": [],- "venv_rebuild": None,- "plugin_bisect": [],- "feature_list": None,- "platform": None,- "outcome": None,- }+ return get_hermes_home() / "logs" / "update_receipts"+++def begin(kind: str) -> contextvars.Token:+ """Start recording a sync. ``kind``: 'sync' | 'update' | 'plugin-check'.+ Returns the ContextVar token — pass it to ``finalize(token=...)`` when+ this begin nests inside an outer begin in the same context, so the+ outer receipt survives the inner finalize."""+ return _current.set(+ {+ "schema": 1,+ "kind": kind,+ "started_at": _utc_now_iso(),+ "steps": [],+ "venv_rebuild": None,+ "plugin_bisect": [],+ "feature_list": None,+ "platform": None,+ "outcome": None,+ }+ )-def record_step(name: str, ok: bool, detail: str = "") -> None:- if _current is None:+def _record(mutate) -> None:+ """Copy-on-write record: the ContextVar may be shared with copied+ contexts, so mutate a deep copy and re-set it in THIS context only."""+ current = _current.get()+ if current is None:return- _current["steps"].append(- {"name": name, "ok": ok, "detail": detail, "at": _utc_now_iso()}- )+ updated = dict(current)+ mutate(updated)+ _current.set(copy.deepcopy(updated))+++def record_step(name: str, ok: bool, detail: str = "") -> None:+ _record(lambda r: r.update(steps=[*r["steps"],+ {"name": name, "ok": ok, "detail": detail, "at": _utc_now_iso()}]))def record_venv_rebuild(ok: bool, reason: str = "") -> None:- if _current is None:- return- _current["venv_rebuild"] = {"ok": ok, "reason": reason}+ _record(lambda r: r.__setitem__("venv_rebuild", {"ok": ok, "reason": reason}))def record_bisect(decisions: list[dict]) -> None:- if _current is None:- return- _current["plugin_bisect"] = decisions+ _record(lambda r: r.__setitem__("plugin_bisect", decisions))def record_feature_list(extras: Optional[list[str]]) -> None:- if _current is None:- return- _current["feature_list"] = extras+ _record(lambda r: r.__setitem__("feature_list", extras))def record_platform(platform_id: str) -> None:- if _current is None:- return- _current["platform"] = platform_id+ _record(lambda r: r.__setitem__("platform", platform_id))def record_plugin_checks(results: list) -> None:"""Plugin update-check results (the cadence's receipt section).Each item is a plugins_updates.CheckResult.to_json() dict."""- if _current is None:- return- _current["plugin_checks"] = [- r.to_json() if hasattr(r, "to_json") else r for r in results- ]+ _record(+ lambda r: r.__setitem__(+ "plugin_checks", [r.to_json() if hasattr(r, "to_json") else r for r in results]+ )+ )def snapshot() -> Optional[dict[str, Any]]:"""The in-flight receipt data — for the updater to EMBED its sync- sections into its own receipt (one schema, one directory)."""- return _current+ sections into its own receipt (one schema, one directory). A deep+ COPY: the authoritative in-flight dict is never exposed for the+ caller to mutate."""+ current = _current.get()+ return copy.deepcopy(current) if current is not None else None-def finalize(outcome: str, exit_code: int = 0) -> Optional[Path]:+def finalize(+ outcome: str, exit_code: int = 0, token: Optional[contextvars.Token] = None+) -> Optional[Path]:"""Write the receipt (``outcome``: ok | refused | failed | bisected)- and rotate. Returns its path; None when nothing was begun."""- global _current- if _current is None:+ and rotate. Returns its path; None when nothing was begun.++ With ``token`` (from the matching ``begin``): pops only this begin's+ receipt and restores the outer one. Without: pops whatever is+ current (the ambient linear-consumer form)."""+ current = snapshot()+ if current is None:return None- _current["outcome"] = outcome- _current["exit_code"] = exit_code- _current["finished_at"] = _utc_now_iso()+ if token is not None:+ _current.reset(token)+ else:+ _current.set(None)+ current["outcome"] = outcome+ current["exit_code"] = exit_code+ current["finished_at"] = _utc_now_iso()try:- path = _write_rotated(_current)+ path = _write_rotated(current)except OSError:return None- finally:- _current = Nonereturn pathdef latest() -> Optional[dict[str, Any]]:"""The newest receipt (any kind) — the reader surface for- ``hermes pm status`` + the desktop."""+ ``hermes pm status`` + the desktop. Pure read: never creates the+ receipts dir."""try:- d = _receipt_dir()- point = d / "latest.json"+ point = _receipt_dir() / "latest.json"if point.is_file():return json.loads(point.read_text(encoding="utf-8-sig"))except (OSError, ValueError):@@ -131,29 +168,34 @@ def latest() -> Optional[dict[str, Any]]:return None+def _receipt_name(data: dict[str, Any]) -> str:+ """Unique name for concurrent writers: stamp + pid + full random+ uuid4 (same pid+random convention as the updater's receipts)."""+ stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())+ kind = data.get("kind") or "sync"+ return f"pm_{stamp}-{kind}-{os.getpid()}-{uuid.uuid4().hex}.json"++def _write_rotated(data: dict[str, Any]) -> Path:+ """Atomic + durable publication: temp file + fsync + rename for both+ the stamped receipt and latest.json (utils.atomic_json_write)."""+ import utils+d = _receipt_dir()- # _write_rotated must not depend on _receipt_dir()'s mkdir side- # effect (a patched/injected dir lambda breaks it) — self-sufficient.d.mkdir(parents=True, exist_ok=True)- stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())- kind = data.get("kind") or "sync"- path = d / f"{stamp}-{kind}.json"- counter = 0- while path.exists():- counter += 1- path = d / f"{stamp}-{kind}-{counter}.json"- path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")- (d / "latest.json").write_text(- json.dumps(data, indent=2) + "\n", encoding="utf-8"- )+ path = d / _receipt_name(data)+ utils.atomic_json_write(path, data)+ utils.atomic_json_write(d / "latest.json", data)_rotate(d)return pathdef _rotate(d: Path) -> None:+ """Keep the newest _RECEIPT_KEEP PM receipts. The dir also holds the+ updater's ``update_*.json`` receipts — this rotates ONLY pm's own+ (``pm_*.json``); the updater rotates its own."""receipts = sorted(- (p for p in d.glob("*.json") if p.name != "latest.json"),+ (p for p in d.glob("pm_*.json") if p.is_file()),key=lambda p: p.name,)for stale in receipts[:-_RECEIPT_KEEP]:diff --git a/pm/update.py b/pm/update.pyindex 5c7f34ac2f2..787d99a89a1 100644--- a/pm/update.py+++ b/pm/update.py@@ -301,7 +301,8 @@ def node_latest_versions() -> list[str]:v = entry.get("version", "")if v.startswith("v"):v = v[1:]- out.append(v)+ if re.fullmatch(r"\d+\.\d+\.\d+", v):+ out.append(v)return out@@ -329,8 +330,11 @@ def martin_riedl_index() -> dict[str, dict[str, str]]:page,):osname, arch, epoch, version = m.groups()- target = f"{'darwin' if osname == 'macos' else 'linux'}-{arch}"- out.setdefault(target, {})[version] = epoch+ target_arch = "x64" if arch == "amd64" else arch+ target = f"{'darwin' if osname == 'macos' else 'linux'}-{target_arch}"+ versions = out.setdefault(target, {})+ if version not in versions or int(epoch) > int(versions[version]):+ versions[version] = epoch_martin_cache.set(out)return out@@ -340,17 +344,16 @@ def martin_riedl_versions(target: str) -> list[str]:return list((martin_riedl_index().get(target) or {}).keys())-def btbn_index() -> dict[str, list[tuple[str, str]]]:- """BtbN/FFmpeg-Builds autobuild index, cached: version -> [(tag, asset)].+def btbn_index() -> dict[str, dict[str, tuple[str, str]]]:+ """Newest static GPL Windows asset per target/version, as (tag, name).- The release tag is a dated autobuild (autobuild-2026-08-28-17-08); the- ffmpeg version lives in the asset names (ffmpeg-n9.0.1-11-g<hash>-- win64-gpl-9.0.zip). Building the download URL at pin time needs BOTH- the tag and the full asset name, so the index keeps them per version."""+ Releases also contain Linux, shared and LGPL builds. Retain target+ identity here so discovery and pinning select the same artifact.+ """cached = _btbn_cache.get()if cached is not None:return cached- out: dict[str, list[tuple[str, str]]] = {}+ out: dict[str, dict[str, tuple[str, str]]] = {}for page in range(1, 4):data = _get_json(f"https://api.github.com/repos/BtbN/FFmpeg-Builds/releases?per_page=30&page={page}")if not data:@@ -363,18 +366,22 @@ def btbn_index() -> dict[str, list[tuple[str, str]]]:continuefor asset in release.get("assets", []):name = asset.get("name", "")- m = re.search(r"(?:^|-)n(\d+\.\d+\.\d+)(?:-|$)", name)- if m and m.group(1) not in out:- out[m.group(1)] = [(tag, name)]+ m = re.fullmatch(+ r"ffmpeg-n(\d+\.\d+\.\d+)-.+-win(64|arm64)-gpl-\d+\.\d+\.zip", name+ )+ if m:+ version, arch = m.groups()+ target = "win32-x64" if arch == "64" else "win32-arm64"+ out.setdefault(target, {}).setdefault(version, (tag, name))if len(data) < 30:break_btbn_cache.set(out)return out-def btbn_versions() -> list[str]:- """Newest-first ffmpeg versions BtbN autobuilds currently ship."""- return list(btbn_index().keys())+def btbn_versions(target: str) -> list[str]:+ """Release versions with a supported Windows asset for this target."""+ return list(btbn_index().get(target, {}))def pbs_build_tags(minor: str, target: str) -> list[str]:diff --git a/pm/workspace.py b/pm/workspace.pyindex ff414d5a8f6..500f333aa99 100644--- a/pm/workspace.py+++ b/pm/workspace.py@@ -1,23 +1,7 @@-"""The generated uv-workspace root that unions plugin deps into the venv.--Design (settled 2026-09-02, .hermes/plans/2026-09-02_164500-plugin-deps--workspace-union.md):--- The workspace root is pm-GENERATED, never the committed pyproject.toml.- Sealed installs are read-only, and the member list is machine-specific- (which plugins the user enabled). Generated root lives beside the byte- store: ``<store_root()>/.pm-workspace`` — per-install, writable on every- install kind.-- Its pyproject = core's pyproject verbatim + a ``[tool.uv.workspace]``- members block of relative ``../``-escaping paths to each enabled plugin- dir. Relative members can escape the workspace root (probed live).-- ``uv lock`` resolves core + plugin deps as ONE graph: existing core pins- are preserved (a plugin's range spec does not move them) and a conflict- fails loudly, so the plugin simply does not install.-- ``uv sync --frozen --extra ...`` at the root installs the union into the- project venv; ``UV_PROJECT_ENVIRONMENT`` pins WHICH venv that is.-- Plugin-member extras are banned/ignored for now (settled): uv selects- only ROOT extras, and the root mirrors core's extras.+"""Resolve core plus plugin requirements in a writable build snapshot.++Shipped source and locks are inputs, never mutation targets. Candidate+failure propagates without changing plugin configuration or the live venv."""from __future__ import annotations@@ -29,13 +13,45 @@ from pathlib import Pathfrom typing import Optionalfrom pm import paths+from pm.package import InstallErrorWORKSPACE_DIRNAME = ".pm-workspace"+class ResolutionConflict(InstallError):+ """uv's resolver proved the union has no valid solution."""+++# Markers uv prints ONLY when the resolver itself proves no solution+# exists (its conflict report: "Because ...", "no solution found").+# Deliberately narrow: a fetch timeout or index outage must not be+# misread as a conflict — and regardless of classification, nothing+# here ever disables a plugin; the caller decides.+_RESOLVER_MARKERS = (+ "no solution found",+ "conflicting requirements",+ "because only the following versions",+ "and your pyproject depends on",+)+++def classify_uv_failure(stage: str, returncode: int, output: str) -> InstallError:+ """Turn a failed `uv <stage>` into the right classified error.++ Resolver-conflict output → ResolutionConflict; anything else (fetch,+ build, tooling) → plain InstallError with the tail of the output.+ """+ cause = f"uv {stage} exited {returncode}: {output.strip()[-600:]}"+ lowered = output.lower()+ if any(marker in lowered for marker in _RESOLVER_MARKERS):+ return ResolutionConflict("venv", cause)+ return InstallError("venv", cause)++def workspace_root() -> Path:- """The generated workspace root — per-install, beside the byte store."""- return paths.store_root() / WORKSPACE_DIRNAME+ """Default preparation root; callers can supply a fresh transaction root."""+ from hermes_cli.runtime_paths import install_state_dir+ return install_state_dir(paths.repo_root()) / WORKSPACE_DIRNAMEdef _member_rel(root: Path, plugin_dir: Path) -> str:@@ -57,27 +73,78 @@ def members_stamp(plugin_dirs: list[Path]) -> str:for entry in resolved:h.update(str(entry).encode("utf-8"))h.update(b"\0")- pyproject = entry / "pyproject.toml"- if pyproject.is_file():- try:- h.update(pyproject.read_bytes())- except OSError:- pass- h.update(b"\0")+ for name in ("pyproject.toml", "plugin.yaml"):+ source = entry / name+ if source.is_file():+ h.update(source.read_bytes())+ h.update(b"\0")return h.hexdigest()-def build_root(plugin_dirs: list[Path]) -> Path:+def _copy_core_inputs(source: Path, destination: Path) -> None:+ """Build from a writable snapshot, never from signed/read-only source."""+ import shutil++ import fnmatch+ import tomllib++ metadata = tomllib.loads((source / "pyproject.toml").read_text(encoding="utf-8-sig"))+ project = metadata.get("project", {})+ setuptools = metadata.get("tool", {}).get("setuptools", {})+ patterns = setuptools.get("packages", {}).get("find", {}).get("include", ["*"])+ package_roots = {pattern.split(".", 1)[0] for pattern in patterns}+ files = {"pyproject.toml", "setup.py", "setup.cfg"}+ readme = project.get("readme")+ if isinstance(readme, str):+ files.add(readme)+ elif isinstance(readme, dict) and "file" in readme:+ files.add(readme["file"])+ for pattern in project.get("license-files", []):+ files.update(str(p.relative_to(source)) for p in source.glob(pattern))+ files.update(p.name for p in source.glob("*.py"))++ excluded = {".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist", "release", "uv.lock"}+ def ignore(directory, names):+ return [name for name in names if name in excluded or name.startswith(".")+ or name.endswith(".egg-info") or (Path(directory) / name).is_symlink()]++ for entry in source.iterdir():+ if (entry.is_dir() and not entry.is_symlink() and entry.name not in excluded+ and not entry.name.startswith(".") and entry.resolve() != destination.resolve()+ and any(fnmatch.fnmatchcase(entry.name, pattern) for pattern in package_roots)):+ target = destination / entry.name+ if target.exists():+ shutil.rmtree(target)+ shutil.copytree(entry, target, ignore=ignore)+ for name in files:+ entry = source / name+ if not entry.is_file() or entry.is_symlink():+ continue+ if not entry.resolve().is_relative_to(source.resolve()):+ raise InstallError("venv", f"build input escapes the core project: {name}")+ target = destination / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(entry, target)+++def _generate_pyproject(plugin_dirs: list[Path], root: Optional[Path] = None) -> tuple[Path, bool]:"""(Re)generate the workspace root's pyproject.toml from core'spyproject + the enabled plugin members. Idempotent — same inputs,- same bytes."""- root = workspace_root()+ same bytes. Returns (root, changed): changed is True when the member+ surface moved (member set or a member's pyproject content), which is+ the signal to re-seed the resolution from the committed lock."""+ if root is None:+ root = workspace_root()+ source = paths.repo_root().resolve()+ if root.resolve() == source or source.is_relative_to(root.resolve()):+ raise InstallError("venv", "workspace must not replace the core source")root.mkdir(parents=True, exist_ok=True)core_pyproject = paths.repo_root() / "pyproject.toml"core_text = core_pyproject.read_text(encoding="utf-8-sig")- members = [_member_rel(root, Path(p)) for p in {str(Path(p).resolve()) for p in plugin_dirs}]+ members = [_member_rel(root, _workspace_member(Path(p), root))+ for p in {str(Path(p).resolve()) for p in plugin_dirs}]lines = [core_text.rstrip("\n")]if members:@@ -85,8 +152,50 @@ def build_root(plugin_dirs: list[Path]) -> Path:lines.append("[tool.uv.workspace]")lines.append("members = [" + ", ".join(f'"{m}"' for m in sorted(members)) + "]")- (root / "pyproject.toml").write_text("\n".join(lines) + "\n", encoding="utf-8")- return root+ text = "\n".join(lines) + "\n"+ target = root / "pyproject.toml"+ try:+ changed = target.read_text(encoding="utf-8") != text+ except OSError:+ changed = True+ _copy_core_inputs(paths.repo_root(), root)+ target.write_text(text, encoding="utf-8")+ return root, changed+++def build_root(plugin_dirs: list[Path], root: Optional[Path] = None) -> Path:+ """(Re)generate the workspace root's pyproject.toml. ``root`` pins a+ parent-supplied STAGING workspace (tests, staged syncs); default is+ the per-install generated root beside the byte store."""+ generated, _changed = _generate_pyproject(plugin_dirs, root)+ return generated+++def _seed_lock(root: Path, seed_lock: Optional[Path] = None) -> None:+ """Seed the generated root's uv.lock with the CURRENT resolution.++ Seed precedence: the parent-supplied ``seed_lock`` path first, then+ the root's own existing uv.lock (the current EXTENDED resolution from+ the previous sync), then the committed core lock — so a plugin-driven+ extension keeps every compatible selection it already made, and a+ fresh root extends the committed resolution. uv preserves compatible+ selections from the seed (a plugin's range spec does not move core+ pins); explicit exact requirements stay binding as declared+ constraints. The lock is COPIED — shipped/extended source bytes are+ never rewritten; only the staging root receives the copy.++ Called only when the member surface changed; an unchanged root keeps+ its lock untouched, so repeated syncs are stable. Seed failures+ SURFACE (they would silently degrade the resolution otherwise)."""+ if seed_lock is None:+ existing = root / "uv.lock"+ if existing.is_file():+ seed_lock = existing+ else:+ seed_lock = paths.repo_root() / "uv.lock"+ if not seed_lock.is_file():+ return # nothing committed to seed from; uv resolves from scratch+ (root / "uv.lock").write_bytes(seed_lock.read_bytes())def _plugin_dir_roots() -> set[Path]:@@ -131,139 +240,63 @@ def _is_member_candidate(plugin_dir: Path) -> bool:return False-def enabled_member_dirs() -> list[Path]:- """Plugin dirs that carry python deps AND are enabled, machine-wide- across profiles. Per-install union: profiles share the venv, so their- enabled plugins share the resolution graph (settled).-- ENABLED-STATE FILTER: only plugins in some profile's- ``plugins.enabled`` config list are members — a disabled plugin- never joins the sync. The result is ordered by ENABLE RECENCY- (newest-enabled LAST): profiles' enabled lists preserve config- order, and enabling appends — so the bisect's incumbent-wins- tiebreak (pop the last) disables the most-recently-enabled."""+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- enabled_by_root: dict[Path, set[str]] = enabled_plugins_ordered()-- member_dirs: list[Path] = []- for plugins_dir in sorted(_plugin_dir_roots(), key=str):- try:- if not plugins_dir.is_dir():- continue- entries = sorted(plugins_dir.iterdir(), key=str)- except OSError:- continue- # The profile's enabled list preserves config order (recency).- # Iterate the ENABLED names in order so members land recency-- # ordered; a name not present on disk is skipped.- enabled_names = enabled_by_root.get(plugins_dir, [])- by_name = {}- for plugin_dir in entries:- try:- if plugin_dir.is_dir():- by_name[plugin_dir.name] = plugin_dir- except OSError:- continue- for name in enabled_names:- plugin_dir = by_name.get(name)- if plugin_dir is None:- continue- try:- if _is_member_candidate(plugin_dir):- member_dirs.append(plugin_dir)- except OSError:- continue- return member_dirs---def record_disabled_plugins(decisions: list[dict]) -> list[str]:- """Write bisect disable decisions back to the enabled-plugins- config so `hermes plugins list` reflects reality and re-enable- retries. Returns the plugin names actually disabled."""- if not decisions:- return []- from pm.plugins_state import disable_plugins-- names = [d["plugin"] for d in decisions if d.get("action") == "disabled"]- if not names:- return []- disable_plugins(names)- return names-+ selection = enabled_plugins_ordered() if proposed_home is None else enabled_plugins_ordered(+ proposed_home=proposed_home, enabled=enabled, disabled=disabled,+ )+ members = []+ for plugins_dir, names in selection.items():+ for name in names:+ relative = Path(name)+ 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():+ plugin_dir = paths.repo_root() / "plugins" / relative+ if plugin_dir.is_dir() and _is_member_candidate(plugin_dir):+ members.append(plugin_dir)+ return list(dict.fromkeys(members))+++def _legacy_requirements(plugin_dir: Path) -> list[str]:+ from utils import fast_safe_load-def materialize_legacy_pyproject(plugin_dir: Path) -> Optional[Path]:- """Bridge: a plugin declaring legacy ``pip_dependencies`` /- ``python_dependencies`` in plugin.yaml, with no pyproject.toml of its- own, gets one MATERIALIZED — the same specs, same workspace-union- install path. Never when lazy installs are off (the sync refuses- separately); idempotent (regenerating is a no-op when specs match)."""manifest = plugin_dir / "plugin.yaml"if not manifest.is_file():- return None- # Never when lazy installs are disabled (settled): materializing the- # generated pyproject would make the dir a workspace-member candidate- # and then hard-fail every sealed/lazy-off sync. The frozen-bundle- # posture keeps the dir untouched.- from pm.ensure import lazy_installs_allowed-- if not lazy_installs_allowed():- return None- generated = plugin_dir / "pyproject.toml"- if generated.is_file():- # A USER-owned pyproject is the modern plugin shape — nothing to- # bridge. One WE generated earlier is still bridgeable (spec- # changes must rewrite it); the GENERATED header marks ours.- try:- existing = generated.read_text(encoding="utf-8-sig")- except OSError:- return None- if "GENERATED by pm" not in existing:- return None-- try:- import re-- text = manifest.read_text(encoding="utf-8-sig")- except OSError:- return None-- specs: list[str] = []+ return []+ data = fast_safe_load(manifest.read_text(encoding="utf-8-sig"))+ if not isinstance(data, dict):+ raise InstallError("venv", f"invalid plugin manifest: {manifest}")+ specs = []for key in ("pip_dependencies", "python_dependencies"):- block = re.search(- rf"^\s*{key}:\s*\n((?:[ \t]+- [^\n]+\n?)*)", text, re.MULTILINE- )- if not block:- continue- for line in block.group(1).splitlines():- item = line.strip()- if item.startswith("- "):- spec = item[2:].strip().strip("'\"")- if spec:- specs.append(spec)-- if not specs:- return None-- name = plugin_dir.name- body = (- "# GENERATED by pm from plugin.yaml pip_dependencies — the legacy\n"- "# bridge (settled 2026-09-02). Migrate to a real pyproject.toml +\n"- "# uv.lock; this file is rewritten when the manifest changes.\n"- "[project]\n"- f'name = "{name}"\n'- 'version = "0.0.0"\n'+ values = data.get(key, [])+ if not isinstance(values, list) or any(not isinstance(v, str) for v in values):+ raise InstallError("venv", f"invalid {key}: {manifest}")+ specs.extend(values)+ return list(dict.fromkeys(specs))+++def _workspace_member(plugin_dir: Path, root: Path) -> Path:+ """Legacy dependency declarations become virtual members in staging only."""+ import json++ pyproject = plugin_dir / "pyproject.toml"+ if pyproject.is_file() and "GENERATED by pm" not in pyproject.read_text(encoding="utf-8-sig"):+ return plugin_dir+ specs = _legacy_requirements(plugin_dir)+ identity = hashlib.sha256(str(plugin_dir.resolve()).encode()).hexdigest()[:16]+ member = root / "plugin-deps" / identity+ member.mkdir(parents=True, exist_ok=True)+ (member / "pyproject.toml").write_text(+ f'[project]\nname = "hermes-plugin-{identity}"\nversion = "0.0.0"\n''requires-python = ">=3.11"\n'- f'dependencies = [{", ".join(repr(s) for s in specs)}]\n'+ f'dependencies = {json.dumps(specs)}\n[tool.uv]\npackage = false\n',+ encoding="utf-8",)- if generated.is_file():- try:- if generated.read_text(encoding="utf-8-sig") == body:- return generated # already current- except OSError:- pass- generated.write_text(body, encoding="utf-8")- return generated+ return memberdef scan_plugin(plugin_dir: Path) -> dict:@@ -353,36 +386,55 @@ def lock_and_sync(plugin_dirs: list[Path],extras: Optional[list[str]] = None,*,- venv_dir: Optional[Path] = None,+ venv_dir: Path,+ root: Optional[Path] = None,+ env: Optional[dict] = None,+ seed_lock: Optional[Path] = None,+ frozen: bool = False,) -> None:"""Build the root, then `uv lock` + `uv sync --frozen --extra ...`.- Raises InstallError on any failure (the caller surfaces the resolver's- message — that IS the plugin-conflict UX). ``venv_dir`` pins- UV_PROJECT_ENVIRONMENT; default is the core project venv.+ Everything resolves into a parent-supplied STAGING surface: ``root``+ pins the generated workspace dir, ``venv_dir`` pins+ UV_PROJECT_ENVIRONMENT and ``seed_lock`` (optional) pins which+ existing lock seeds the extension (default: the root's current+ extended lock, else the committed core lock). ``env`` replaces the+ ambient base environment when supplied; either way the subprocess+ gets a COPY — the live process environment is never mutated.++ Raises a CLASSIFIED InstallError on failure: ResolutionConflict only+ for a confirmed resolver conflict; network, build and tool failures+ stay generic InstallError — they are not evidence of a dependency+ conflict and must not disable plugins."""- from pm.package import InstallErrorfrom pm.packages import uv_env- root = build_root(plugin_dirs)-- if venv_dir is None:- venv_dir = _default_venv_dir()+ generated, changed = _generate_pyproject(plugin_dirs, root)+ if changed:+ _seed_lock(generated, seed_lock)uv_bin = _uv_binary()if uv_bin is None:raise InstallError("venv", "uv is not installed (pm ensure uv)")- env = uv_env()- env["UV_PROJECT_ENVIRONMENT"] = str(venv_dir)+ # uv_env SANITIZES the base: when the parent staged an env it is the+ # base (ambient VIRTUAL_ENV/UV_* leakage stripped); otherwise the live+ # environment is sanitized. Either way this is a fresh COPY — the live+ # process environment is never mutated.+ run_env = uv_env(env)+ run_env.pop("UV_NO_CONFIG", None)+ run_env["UV_PROJECT_ENVIRONMENT"] = str(venv_dir)+ import sys+ run_env["UV_PYTHON"] = sys.executableimport subprocess- lock = subprocess.run(- [uv_bin, "lock"], cwd=str(root), env=env, capture_output=True, text=True- )- if lock.returncode != 0:- raise InstallError("venv", f"uv lock exited {lock.returncode}: {lock.stderr[-600:]}")+ if not frozen:+ lock = subprocess.run(+ [uv_bin, "lock"], cwd=str(generated), env=run_env, capture_output=True, text=True, timeout=1800+ )+ if lock.returncode != 0:+ raise classify_uv_failure("lock", lock.returncode, lock.stderr or lock.stdout)# --all-packages is REQUIRED: plain `uv sync --frozen` installs only the# ROOT project's deps — workspace-member deps are locked by `uv lock`@@ -394,77 +446,15 @@ def lock_and_sync(cmd = [uv_bin, "sync", "--frozen", "--all-packages"]for extra in sorted(set(extras or [])):cmd += ["--extra", extra]- sync = subprocess.run(cmd, cwd=str(root), env=env, capture_output=True, text=True)+ sync = subprocess.run(cmd, cwd=str(generated), env=run_env, capture_output=True, text=True, timeout=1800)if sync.returncode != 0:- raise InstallError(- "venv", f"uv sync exited {sync.returncode}: {sync.stderr[-600:]}"+ # --frozen means the lock already resolved; a sync failure here is+ # install/download/tooling, never a NEW resolution conflict.+ raise classify_uv_failure(+ "sync", sync.returncode, sync.stderr or sync.stdout)-def resolve_union(- plugin_dirs: list[Path],- extras: Optional[list[str]] = None,- *,- venv_dir: Optional[Path] = None,-) -> tuple[list[Path], list[dict]]:- """Try the full union; on failure, bisect the member set.-- Returns (surviving_members, decisions). Every decision is- {plugin, action: kept|disabled, reason}. Fail-alone plugins are- disabled with the resolver's message; mutually-conflicting plugins- are resolved incumbent-wins (the most-recently-enabled member of a- conflicting pair is the one disabled — order = plugin_dirs list,- LAST wins the tiebreak because the caller passes- newest-last). Retries the union until it resolves or every member- is disabled; never raises for a resolution failure (a uv binary- absence still raises InstallError)."""- from pm.package import InstallError-- survivors = list(plugin_dirs)- decisions: list[dict] = []-- def _try(members: list[Path]) -> Optional[str]:- """None on success, else the failure reason."""- try:- lock_and_sync(members, extras, venv_dir=venv_dir)- return None- except InstallError as exc:- return str(exc)-- reason = _try(survivors)- if reason is None:- return survivors, decisions-- # Phase 1: each member alone against core. Fail-alone = disabled.- alone_ok: dict[Path, Optional[str]] = {}- for member in list(survivors):- fail = _try([member])- alone_ok[member] = fail- if fail is not None:- decisions.append(- {"plugin": member.name, "action": "disabled", "reason": fail}- )- survivors.remove(member)-- # Phase 2: retry the reduced union; if it still fails, the remaining- # set conflicts mutually — incumbent wins, newest (last) disabled.- while survivors:- reason = _try(survivors)- if reason is None:- return survivors, decisions- loser = survivors.pop() # newest-enabled = last in the list- decisions.append(- {"plugin": loser.name, "action": "disabled", "reason": reason}- )- return survivors, decisions---def _default_venv_dir() -> Path:- from pm.packages import Venv-- return Venv().venv_dir()--def _uv_binary() -> Optional[str]:"""Store uv first (pinned), PATH uv second (dev machines, test envs).A dev machine with uv on PATH but no provisioned store is the normaldiff --git a/scripts/audit-old-updater-imports.py b/scripts/audit-old-updater-imports.pyindex 05cd6f18bf6..0c93f13b473 100644--- a/scripts/audit-old-updater-imports.py+++ b/scripts/audit-old-updater-imports.py@@ -458,7 +458,11 @@ def analyse(source: str, source_file: str, *, entrypoints: bool) -> Analysis | Ndef _all_audited_paths() -> tuple[str, ...]:- return UPDATE_MODULE_CANDIDATES + POST_SWAP_HELPER_MODULES+ siblings = tuple(sorted(+ str(p.relative_to(REPO_ROOT)).replace("\\", "/")+ for p in (REPO_ROOT / "hermes_cli").glob("update_cmd_*.py")+ ))+ return tuple(dict.fromkeys((*UPDATE_MODULE_CANDIDATES, *POST_SWAP_HELPER_MODULES, *siblings)))def shipped_commits() -> list[str]:diff --git a/scripts/check_compat_pointers.py b/scripts/check_compat_pointers.pyindex 6ac79d4c3dc..2e99dada330 100644--- a/scripts/check_compat_pointers.py+++ b/scripts/check_compat_pointers.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport astimport json+import osimport reimport sysfrom pathlib import Path@@ -27,14 +28,15 @@ SKIP_DIRS = {".git", "node_modules", "website", "skills", "optional-skills", "apdef _py_files():- for p in ROOT.rglob("*.py"):- parts = p.relative_to(ROOT).parts- if parts[0] in SKIP_DIRS or p.name == "check_compat_pointers.py":- continue- # The compat layer's own contract test uses the pointers on purpose; it is deleted with them.- if p.name == "test_compat_manifest_targets.py":- continue- yield p+ def fail(error):+ raise error++ for directory, dirs, files in os.walk(ROOT, onerror=fail):+ dirs[:] = [name for name in dirs if name not in SKIP_DIRS and not name.startswith(".")]+ for name in files:+ if not name.endswith(".py") or name in {"check_compat_pointers.py", "test_compat_manifest_targets.py"}:+ continue+ yield Path(directory) / namedef main() -> int:diff --git a/scripts/ci/check_lazy_deps_imports.py b/scripts/ci/check_lazy_deps_imports.pynew file mode 100644index 00000000000..117e6e84410--- /dev/null+++ b/scripts/ci/check_lazy_deps_imports.py@@ -0,0 +1,179 @@+#!/usr/bin/env python3+"""Fail when tracked production code imports the deleted tools.lazy_deps module.++``tools/lazy_deps.py`` was deleted by the pm migration; pm.extras+(available / ensure_import / ensure_and_bind) is the only lazy-install+surface. Any remaining import of it is an ImportError at call time, so+this guard blocks the migration from silently re-opening.++- **Tracked inventory.** The file list comes from ``git ls-files``, so+ ignored worktree/build debris is never walked. The check never passes+ by scanning nothing: an inventory that cannot be built (not a repo,+ git failure) or that contains no ``*.py`` files at all FAILS (exit 2).+- **AST import analysis.** Matches real import statements only:+ ``import tools.lazy_deps`` and dotted variants, ``from tools import+ lazy_deps``, ``from tools.lazy_deps...`` and the relative forms+ (``from . import lazy_deps``, ``from .lazy_deps import ...``) resolved+ inside the tracked ``tools/`` package. Comments, docstrings, and other+ prose mentions are ignored by construction.+- **Errors are failures.** A tracked file that cannot be read, decoded,+ or parsed is reported and fails the run (exit 2), not skipped.++tests/ files are out of scope: tests may reference the deleted module to+assert it is gone.++Exit codes: 0 = clean, 1 = offenders found (exact ``path:line`` sites on+stdout), 2 = inventory/analysis error.++Usage:+ python scripts/ci/check_lazy_deps_imports.py [repo_root]++Wired unconditionally into .github/workflows/lazy-deps-guard.yml+(blocking job); the contract tests driving this CLI against fixture+repos live in tests/pm/test_no_lazy_deps.py.+"""++from __future__ import annotations++import ast+import subprocess+import sys+from pathlib import Path, PurePosixPath++_DELETED_MODULE = "tools.lazy_deps"+_DELETED_PARENT = "tools"+++def _tracked_python_files(root: Path) -> list[str]:+ """Tracked ``*.py`` paths (repo-relative, POSIX separators) minus tests/."""+ proc = subprocess.run(+ ["git", "-C", str(root), "ls-files", "-z", "--", "*.py"],+ capture_output=True,+ )+ if proc.returncode != 0:+ sys.stderr.write(+ f"inventory failed: git ls-files exited {proc.returncode}: "+ f"{proc.stderr.decode(errors='replace').strip()}\n"+ )+ raise SystemExit(2)+ names = proc.stdout.decode(errors="replace").split("\0")+ deleted = subprocess.run(+ ["git", "-C", str(root), "ls-files", "--deleted", "-z", "--", "*.py"],+ capture_output=True, check=True,+ )+ removed = set(deleted.stdout.decode(errors="replace").split("\0"))+ files = sorted(+ n.replace("\\", "/")+ for n in names+ if n.endswith(".py") and n not in removed+ and not n.replace("\\", "/").startswith("tests/")+ )+ if not files:+ sys.stderr.write(+ "inventory failed: no tracked *.py files under "+ f"{root} — refusing to pass an empty inventory\n"+ )+ raise SystemExit(2)+ return files+++def _relative_target(relpath: str, node: ast.ImportFrom) -> str | None:+ """Absolute module a relative from-import resolves to for *relpath*.++ ``level`` 1 is the file's own package; each further level climbs one+ package. Returns None when the import escapes the repo root (never a+ real module, so never the deleted one).+ """+ parts = PurePosixPath(relpath).with_suffix("").parts[:-1]+ up = node.level - 1+ if up > len(parts):+ return None+ base = parts[: len(parts) - up] if up else parts+ mod = node.module.split(".") if node.module else []+ return ".".join([*base, *mod])+++def _import_sites(tree: ast.AST, relpath: str) -> list[str]:+ """``relpath:line: <description>`` for every tools.lazy_deps import."""+ sites: list[str] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name == _DELETED_MODULE or alias.name.startswith(+ _DELETED_MODULE + "."+ ):+ sites.append(+ f"{relpath}:{node.lineno}: import of deleted module "+ f"'{alias.name}'"+ )+ elif isinstance(node, ast.ImportFrom):+ names = ", ".join(a.name for a in node.names)+ kind: str | None = None+ if node.level == 0:+ if node.module == _DELETED_MODULE or (+ node.module and node.module.startswith(_DELETED_MODULE + ".")+ ):+ kind = f"'{node.module} ({names})'"+ elif node.module == _DELETED_PARENT and any(+ a.name == "lazy_deps" for a in node.names+ ):+ kind = f"'{node.module} ({names})'"+ else:+ resolved = _relative_target(relpath, node)+ if resolved == _DELETED_PARENT and any(+ a.name == "lazy_deps" for a in node.names+ ):+ kind = f"'{resolved} ({names})' (relative)"+ elif resolved == _DELETED_MODULE or (+ resolved and resolved.startswith(_DELETED_MODULE + ".")+ ):+ kind = f"'{resolved} ({names})' (relative)"+ if kind is not None:+ sites.append(+ f"{relpath}:{node.lineno}: from-import of deleted module {kind}"+ )+ return sites+++def main(argv: list[str]) -> int:+ root = Path(argv[1]) if len(argv) > 1 else Path.cwd()+ if not root.is_dir():+ print(f"no such directory: {root}", file=sys.stderr)+ return 2++ offenders: list[str] = []+ errors: list[str] = []+ for relpath in _tracked_python_files(root):+ path = root / relpath+ try:+ source = path.read_bytes()+ tree = ast.parse(source, filename=str(path))+ except (OSError, SyntaxError, ValueError) as exc:+ errors.append(f"{relpath}: inventory/read/parse failed: {exc}")+ continue+ offenders.extend(_import_sites(tree, relpath))++ if errors:+ for err in errors:+ print(f"inventory error: {err}", file=sys.stderr)+ print(+ f"{len(errors)} tracked file(s) could not be analyzed — "+ "failing the check rather than scanning a partial inventory",+ file=sys.stderr,+ )+ return 2+ if offenders:+ for site in sorted(offenders):+ print(site)+ print(+ f"{len(offenders)} import(s) of '{_DELETED_MODULE}' (deleted module — "+ "ImportError at call time). Migrate to pm.extras "+ "(available / ensure_import / ensure_and_bind).",+ file=sys.stderr,+ )+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv))diff --git a/scripts/ci/list_os_marked_tests.py b/scripts/ci/list_os_marked_tests.pyindex 4177a4e10f6..70d48ed31b0 100644--- a/scripts/ci/list_os_marked_tests.py+++ b/scripts/ci/list_os_marked_tests.py@@ -1,57 +1,128 @@#!/usr/bin/env python3"""List the test files that carry a platforms() gate for a given platform.-Used by the marked-OS lane of ``.github/workflows/tests.yml`` to scope what-the macOS lane imports.--Why scope at all, when ``pytest -m platforms`` already selects correctly?-Because ``-m`` filters AFTER collection, and collection IMPORTS every test-module under ``tests/``. On the Linux lane that is fine (it runs them all-anyway), but on the macOS lane it would drag ~900 unrelated modules through-import on a host they were never expected to import on — one unrelated-ImportError would fail a job whose actual subject passed. Narrowing the-paths keeps each lane's failure signal about its own tests.--``-m platforms`` (plus the conftest's per-test host skips) remains the-authoritative selector: this script only decides which files get imported,-never which tests run. Over-selecting here is harmless (the skips drop the-extras); the failure mode to care about is UNDER-selecting, which is why-the workflow fails the job when zero tests end up selected.--A file matches when a quoted ``platforms("...")`` spec names the platform —-including negated (``"not macos"``) and any-of lists. The match is anchored-inside the string literal so bare identifiers (a variable named ``windows``)-don't produce false positives.+Used by the marked-OS lane of ``.github/workflows/tests-os.yml`` to scope+what the macOS/Windows lanes import: ``-m platforms`` filters AFTER+collection, and collection imports every test module under ``tests/``, so+narrowing the imported paths keeps each lane's failure signal about its+own tests instead of failing on ~900 unrelated imports.++This script only decides which files are IMPORTED, never which tests run+(``-m platforms`` plus the conftest's per-test host skips stay+authoritative). Over-selection is harmless — the skips drop the extras —+so whenever a file's gating cannot be evaluated statically (non-literal+spec, unknown leaf) OR the file itself cannot be read or parsed, the file+is conservatively listed; the lane, not this selector, then reports the+problem. UNDER-selection, which silently drops coverage, is the failure+mode this tool exists to prevent.++Spec recognition is AST-based over the conftest gate's vocabulary:+decorator and module-level ``pytestmark`` forms, quoted string specs,+negation (``"not macos"``), the grouping specs (``"posix"`` = linux+macos+hosts, ``"any"`` = all), and ``arch=``/``arch_negate=`` keyword filters.+A file is listed for platform P when any spec could run a test on a P+host.Usage:python scripts/ci/list_os_marked_tests.py macos [tests_root]Prints one path per line (POSIX separators, repo-relative), sorted. Exits-non-zero when no file matches (a renamed spec or broken selection would-otherwise report a green lane that ran nothing).+non-zero when no file matches — a renamed spec or broken selection would+otherwise report a green lane that ran nothing."""from __future__ import annotations-import re+import astimport sysfrom pathlib import Path_VALID_PLATFORMS = ("linux", "macos", "windows")+# Host sets each positive leaf spec can run on (mirrors the conftest's+# _PLATFORM_ALIASES evaluation, expressed over lane names).+_SPEC_HOSTS = {+ "linux": {"linux"},+ "macos": {"macos"},+ "windows": {"windows"},+ "posix": {"linux", "macos"},+ "any": {"linux", "macos", "windows"},+}+++def _platforms_call_matches_p(call: ast.Call, platform: str) -> bool | None:+ """Could this platforms(...) call gate a test onto a *platform* host?++ Returns True/False, or None when the call cannot be evaluated+ statically (non-literal spec) — the caller then over-selects.+ """+ literal_specs: list[str] = []+ for arg in call.args:+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):+ literal_specs.append(arg.value)+ else:+ return None # non-literal spec: cannot evaluate → over-select+ if not literal_specs:+ return None # no specs at all: conftest treats it as matches-everything+ matched = False+ for spec in literal_specs:+ text = spec.strip().lower()+ negate = text.startswith("not ")+ leaf = text[4:].strip() if negate else text+ if negate:+ # Negation excludes hosts, so the gate can pass on any host+ # outside the leaf's set — including this lane's.+ return True+ if leaf not in _SPEC_HOSTS:+ return None # unknown leaf: conftest hard-errors; over-select+ if platform in _SPEC_HOSTS[leaf]:+ matched = True+ return matched+++def _file_matches_platform(tree: ast.AST, platform: str) -> bool | None:+ """True/False/None(unevaluable) from one parsed test module."""+ verdict: bool | None = False+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ is_platforms_call = (+ isinstance(func, ast.Name) and func.id == "platforms"+ ) or (isinstance(func, ast.Attribute) and func.attr == "platforms")+ if not is_platforms_call:+ continue+ # arch=/arch_negate= narrow the per-test skip, not file selection —+ # the lane's machine isn't statically known, so ignore them.+ hit = _platforms_call_matches_p(node, platform)+ if hit is None:+ verdict = None+ elif hit:+ return True+ return verdict+def find_marked_files(platform: str, root: Path) -> list[Path]:"""Return every ``test_*.py`` under *root* gating on *platform*."""- pattern = re.compile(- rf'platforms\(\s*[^)]*?"[^")]*\b{re.escape(platform)}\b[^")]*"'- )hits: list[Path] = []for path in sorted(root.rglob("test_*.py")):try:- text = path.read_text(encoding="utf-8-sig", errors="replace")- except OSError:+ source = path.read_bytes()+ except OSError as exc:+ # Fail closed: an unreadable file is conservatively SELECTED so+ # the lane fails visibly there instead of silently dropping+ # whatever coverage the file carries.+ print(f"warning: unreadable {path}: {exc}", file=sys.stderr)+ hits.append(path)+ continue+ try:+ tree = ast.parse(source, filename=str(path))+ except SyntaxError as exc:+ print(f"warning: unparseable {path}: {exc}", file=sys.stderr)+ hits.append(path)continue- if pattern.search(text):+ match = _file_matches_platform(tree, platform)+ if match is None or match:hits.append(path)return hitsdiff --git a/scripts/desktop-cli/launcher-wrapper.py b/scripts/desktop-cli/launcher-wrapper.pyindex 0634184229a..b5a441c73b3 100644--- a/scripts/desktop-cli/launcher-wrapper.py+++ b/scripts/desktop-cli/launcher-wrapper.py@@ -95,6 +95,7 @@ def main(argv=None):argv = list(sys.argv if argv is None else argv)here = launcher_dir(argv[0] if argv else sys.argv[0])configure(here)+ importlib.import_module("hermes_bootstrap")module = importlib.import_module(HERMES_ENTRY_MODULE)target = getattr(module, HERMES_ENTRY_FUNC)# main() reads sys.argv; hand it the real argv (argv[0] stays thediff --git a/scripts/install.ps1 b/scripts/install.ps1index 40496792209..203092f3e16 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -190,7 +190,6 @@ if ($IncludeDesktop) {$Stages += @{ name = "desktop"; title = "Build desktop app"; category = "runtime"; needs_user_input = $false }}$Stages += @{ name = "complete"; title = "Finish install"; category = "runtime"; needs_user_input = $false }-function Stage-Prerequisites {if (-not (Ensure-Git)) {Fail "git is required. Install Git for Windows: https://git-scm.com/download/win"@@ -305,8 +304,65 @@ function Stage-Gateway {}function Stage-Desktop {- Install-DesktopVoiceDeps- Install-Desktop+ # Desktop support via the CURRENT runtime paths only. wake/voice extras+ # ride pm's venv sync ([all] does not include them; lazy install at+ # first use remains the fallback -- policy: Teknium, July 2026, #70509).+ # The build is `hermes desktop --build-only`, the same authority as+ # `hermes gui` and the update flow; the deleted installer-local+ # npm/Electron helpers must not reappear here.+ $venvPython = Join-Path $InstallDir "venv\Scripts\python.exe"+ if (-not (Test-Path $venvPython)) { Fail "venv python missing at $venvPython" }+ Push-Location $InstallDir+ try {+ Log "ensuring desktop voice/wake dependencies via pm venv sync"+ & $venvPython -c "from pm.ensure import sync_venv; sync_venv(['wake', 'voice'], explicit=True)"+ if ($LASTEXITCODE) {+ Write-Host "[hermes] voice/wake dependency sync failed (exit $LASTEXITCODE) -- they will lazy-install at first use" -ForegroundColor Yellow+ }+ Log "building desktop app (hermes desktop --build-only)"+ & $venvPython (Join-Path $InstallDir "hermes") desktop --build-only+ $code = $LASTEXITCODE+ if ($code) { Fail "desktop build failed (hermes desktop --build-only exited $code)" }++ # Probe the produced artifact -- the same candidates+ # hermes_cli/main_desktop._desktop_packaged_executable resolves+ # (verified: --build-only returns the packaged app under+ # apps/desktop/release/, not the --source dist/).+ $desktopDir = Join-Path $InstallDir "apps\desktop"+ $candidates = @(+ (Join-Path $desktopDir "release\win-unpacked\Hermes.exe"),+ (Join-Path $desktopDir "release\win-ia32-unpacked\Hermes.exe"),+ (Join-Path $desktopDir "release\win-arm64-unpacked\Hermes.exe")+ )+ $desktopExe = $null+ foreach ($cand in $candidates) {+ if (Test-Path $cand) { $desktopExe = $cand; break }+ }+ if (-not $desktopExe) {+ Fail "desktop build produced no Hermes.exe under $desktopDir\release\*-unpacked\"+ }+ Log "Desktop ready: $desktopExe"++ # Grant ALL APPLICATION PACKAGES (S-1-15-2-2) RX on the unpacked+ # app directory: Chromium's GPU/renderer sandboxes CHECK-fail with+ # 0x80000003 without this ACE beside orphan AppContainer SIDs under+ # %LOCALAPPDATA% (electron/electron#51761, hermes-agent#38216).+ # Best-effort -- never fail an otherwise-good install over ACL.+ try {+ $appDir = Split-Path -Parent $desktopExe+ & icacls $appDir /grant "*S-1-15-2-2:(OI)(CI)(RX)" /T /C /Q | Out-Null+ if ($LASTEXITCODE -eq 0) {+ Log "Granted AppContainer read access on $appDir"+ } else {+ Write-Host "[hermes] icacls AppContainer grant returned exit $LASTEXITCODE for $appDir" -ForegroundColor Yellow+ }+ } catch {+ Write-Host "[hermes] Could not grant AppContainer ACL: $($_.Exception.Message)" -ForegroundColor Yellow+ }+ } finally {+ Pop-Location+ }+ New-DesktopShortcuts -TargetExe $desktopExe}function Stage-Complete {@@ -324,335 +380,6 @@ function Stage-Complete {}}-function Install-DesktopVoiceDeps {- # Desktop ships with working voice out of the box: eagerly install the- # wake-word + local-STT stacks ([wake] + [voice] extras) instead of- # leaving them to lazy first-use install. Policy change (Teknium, July- # 2026, #70509 testing): the first ear-click used to trigger a- # multi-minute onnxruntime pip install that froze the UI and blew RPC- # timeouts. Best-effort -- lazy install remains the fallback for anything- # this step fails to fetch.- if (-not $script:UvCmd) { Resolve-UvCmd }- if (-not $script:UvCmd) {- Write-Warn "uv unavailable -- voice/wake deps will lazy-install at first use instead"- return- }- $env:VIRTUAL_ENV = "$InstallDir\venv"- Write-Info "Installing voice + wake-word dependencies (onnxruntime, faster-whisper -- 1-3min)..."- Push-Location $InstallDir- try {- Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install -e ".[wake,voice]" }- if ($LASTEXITCODE -eq 0) {- Write-Success "Voice + wake-word dependencies installed"- } else {- Write-Warn "Voice/wake dependency install failed (exit $LASTEXITCODE) -- they will lazy-install at first use"- }- } finally {- Pop-Location- }-}--function Install-Desktop {- # Build apps/desktop into a launchable Hermes.exe. Only called from- # Stage-Desktop, which is itself only included in the manifest when- # -IncludeDesktop was passed to install.ps1.- #- # The workspace npm install at repo root (done by Install-NodeDeps for- # browser tools) does NOT pull apps/desktop's dependencies, because the- # browser-tools workspace at $InstallDir\package.json is a separate- # workspace from apps/*. We do a full root-level `npm install` here- # so the workspace resolves apps/desktop's deps (including Electron- # itself, ~150MB), then run `npm run pack` in apps/desktop which- # produces the unpacked binary at apps/desktop/release/<os>-unpacked/.- #- # The Tauri bootstrap installer's launch_hermes_desktop command- # resolves apps/desktop/release/win-unpacked/Hermes.exe directly,- # so an "unpacked" build (electron-builder --dir) is enough -- we- # don't need to produce an NSIS/MSI artifact here.-- # Always re-resolve Node here. Stages run in separate PowerShell processes,- # so $script:HasNode from Stage-Node isn't visible; more importantly Test-Node- # enforces the supported Node lines and prepends the Hermes-managed Node to- # PATH, so the build never runs on an unsupported system Node -- the cause- # of the opaque "Build desktop app ... exit code 1" failure (Vite crashes on- # old Node).- Test-Node | Out-Null- if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {- Write-Warn "Skipping desktop build (Node.js / npm not on PATH)"- $script:_StageSkippedReason = "Node.js not available"- return- }-- $desktopDir = "$InstallDir\apps\desktop"- if (-not (Test-Path "$desktopDir\package.json")) {- Write-Warn "Skipping desktop build (apps/desktop not present in checkout)"- $script:_StageSkippedReason = "apps/desktop not present"- return- }-- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue- if (-not $npmCmd) {- Write-Warn "Skipping desktop build (npm not on PATH)"- $script:_StageSkippedReason = "npm not found"- return- }- $npmExe = $npmCmd.Source- if ($npmExe -like "*.ps1") {- $sibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"- if (Test-Path $sibling) { $npmExe = $sibling }- }-- # 1. Workspace-level install so apps/desktop's deps (Electron, Vite,- # node-pty prebuilds, etc.) actually land in node_modules. This is- # the SAME `npm install` Install-NodeDeps does for browser tools,- # but at the root rather than the browser-tools workspace, so all- # apps/* workspaces resolve.- Write-Info "Installing desktop workspace dependencies (this includes Electron ~150MB, takes 1-3min)..."- Push-Location $InstallDir- $prevEAP = $ErrorActionPreference- try {- $ErrorActionPreference = "Continue"- # Drop --silent so npm emits its full progress + error trail.- # When this fails on a non-dev box (e.g. native-module build- # without VS Build Tools, ETARGET on a transitive, etc.), the- # actual reason needs to reach the Tauri installer's log; with- # --silent it was completely suppressed and the user just saw- # "exit 1" with no actionable detail.- #- # The streaming sink in bootstrap.rs's run_install_script- # captures every stdout/stderr line as it's emitted, so we don't- # need a side TEMP log file -- the installer's bootstrap log- # IS the artifact a support engineer reads.- #- # Prefer `npm ci`: it wipes node_modules and reinstalls from the- # lockfile, always producing a complete tree. Bare `npm install`- # can report "up to date" against a stale- # node_modules\.package-lock.json marker while node_modules is- # actually empty (Windows workspace-hoisting flake), leaving- # tsc/typescript unresolved so `npm run pack`'s `tsc -b` dies with- # no obvious cause. Fall back to `npm install` only if `npm ci`- # fails (lockfile out of sync / very old npm without ci).- #- # Tee the merged output into $npmOut while still emitting every line- # live. We don't need a side log file (the bootstrap streaming sink- # is the artifact), but on failure we scan $npmOut for the TLS-trust- # signature so corporate-proxy users get the NODE_EXTRA_CA_CERTS hint- # instead of an opaque "exit 1" (issue #38016).- & $npmExe ci 2>&1 | ForEach-Object { "$_" } | Tee-Object -Variable npmOut- $code = $LASTEXITCODE- if ($code -ne 0) {- Write-Info " npm ci failed (exit $code) -- retrying with npm install..."- & $npmExe install 2>&1 | ForEach-Object { "$_" } | Tee-Object -Variable npmOut- $code = $LASTEXITCODE- }- $ErrorActionPreference = $prevEAP- if ($code -ne 0) {- if (Test-ElectronPkgStagedMissingDist -InstallDir $InstallDir) {- Write-Warn "Desktop dependency install failed with a missing Electron dist; attempting self-heal..."- Try-RestoreElectronDist -InstallDir $InstallDir | Out-Null- } else {- Show-NpmCertHint ($npmOut -join "`n") | Out-Null- # Replay npm's own debug log into our stream: the terse- # summary above rarely contains the postinstall stderr- # (e.g. Electron's install.js) that explains the failure.- Write-NpmDebugLogTail -NpmOutput ($npmOut -join "`n")- throw "desktop workspace npm install failed (exit $code) -- see lines above for cause"- }- } else {- Write-Success "Desktop workspace dependencies installed"- }- } catch {- if ($prevEAP) { $ErrorActionPreference = $prevEAP }- Pop-Location- throw- }- Pop-Location-- # 2. Build apps/desktop. `npm run pack` runs:- # assert-root-install + write-build-stamp + stage-native-deps +- # tsc -b + vite build + electron-builder --dir- # The --dir mode produces an unpacked Hermes.exe in- # apps/desktop/release/win-unpacked/ without bundling NSIS/MSI;- # we don't need a distributable installer artifact, just a- # launchable binary the Tauri installer can spawn.- #- # CSC_IDENTITY_AUTO_DISCOVERY=false tells electron-builder we are- # NOT signing the output. Combined with signAndEditExecutable=false in- # apps/desktop/package.json's build.win block, electron-builder never- # invokes signtool and therefore never fetches/extracts winCodeSign- # (whose macOS symlinks crash 7-Zip on non-admin Windows -- a dead end we- # are NOT trying to work around). The Hermes icon + product name are- # stamped onto Hermes.exe by our own rcedit step (Set-DesktopExeIdentity)- # AFTER this build, completely decoupled from electron-builder signing.- #- # WIN_CSC_LINK and WIN_CSC_KEY_PASSWORD explicitly cleared as- # belt-and-suspenders: if the user's environment has them set- # for some other tool, electron-builder would still try to sign.- Write-Info "Building desktop app (this takes 1-3 minutes)..."- $buildLog = "$env:TEMP\hermes-desktop-build-$(Get-Random).log"- # Seed GITHUB_SHA for write-build-stamp.mjs. The stamp prefers CI env vars- # over `git rev-parse`, so this covers: (1) node can't find git.exe on PATH- # even though this PowerShell session can, (2) ZIP/init trees that still- # lack a HEAD after a failed post-extract fetch. Without it the desktop- # pack dies with "could not determine git commit" (#50823).- if (-not $env:GITHUB_SHA) {- if ($Commit) {- $env:GITHUB_SHA = $Commit- } else {- Push-Location $InstallDir- try {- $global:LASTEXITCODE = 0- $resolvedSha = & git -c windows.appendAtomically=false rev-parse HEAD 2>$null- if ($LASTEXITCODE -ne 0 -or -not $resolvedSha) {- # ZIP path may have FETCH_HEAD after a fetch even when HEAD is unset.- $global:LASTEXITCODE = 0- $resolvedSha = & git -c windows.appendAtomically=false rev-parse FETCH_HEAD 2>$null- }- if ($LASTEXITCODE -eq 0 -and $resolvedSha) {- $env:GITHUB_SHA = ("$resolvedSha").Trim()- }- } catch { } finally {- Pop-Location- }- }- }- if (-not $env:GITHUB_REF_NAME) {- $env:GITHUB_REF_NAME = if ($Branch) { $Branch } else { "main" }- }- if ($env:GITHUB_SHA) {- $shaPreview = if ($env:GITHUB_SHA.Length -ge 12) { $env:GITHUB_SHA.Substring(0, 12) } else { $env:GITHUB_SHA }- Write-Info "Desktop build stamp: $shaPreview ($($env:GITHUB_REF_NAME))"- } else {- Write-Warn "Could not resolve a git commit for the desktop stamp -- write-build-stamp will use its non-git fallback"- }- Push-Location $desktopDir- $prevEAP = $ErrorActionPreference- $prevCSCAuto = $env:CSC_IDENTITY_AUTO_DISCOVERY- $prevWinCscLink = $env:WIN_CSC_LINK- $prevWinCscKeyPassword = $env:WIN_CSC_KEY_PASSWORD- try {- $ErrorActionPreference = "Continue"- $env:CSC_IDENTITY_AUTO_DISCOVERY = "false"- $env:WIN_CSC_LINK = ""- $env:WIN_CSC_KEY_PASSWORD = ""- & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog- $code = $LASTEXITCODE- if ($code -ne 0) {- $purged = @()- $restored = $false- if (-not (Test-ElectronDist -InstallDir $InstallDir)) {- $purged = @(Clear-ElectronBuildCache -DesktopDir $desktopDir)- $restored = Restore-ElectronDist -InstallDir $InstallDir- }- if ($restored) {- Write-Warn "Desktop build failed - refreshed the Electron download, retrying once:"- foreach ($p in $purged) { Write-Info " - $p" }- & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog- $code = $LASTEXITCODE- }- }- if ($code -ne 0 -and -not $env:ELECTRON_MIRROR) {- $mirror = $script:DesktopElectronFallbackMirror- Write-Warn "Desktop build still failing - the Electron download from GitHub looks blocked."- Write-Warn "Re-downloading Electron via a public mirror ($mirror), then rebuilding:"- Write-Info " (set ELECTRON_MIRROR yourself to use a different/trusted mirror)"- if (-not (Test-ElectronDist -InstallDir $InstallDir)) {- Restore-ElectronDist -InstallDir $InstallDir -Mirror $mirror | Out-Null- }- $prevMirror = $env:ELECTRON_MIRROR- $env:ELECTRON_MIRROR = $mirror- try {- & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog- $code = $LASTEXITCODE- } finally {- $env:ELECTRON_MIRROR = $prevMirror- }- }- $ErrorActionPreference = $prevEAP- if ($code -ne 0) {- $errText = Get-Content $buildLog -Raw -ErrorAction SilentlyContinue- if ($errText) {- $snippet = if ($errText.Length -gt 1800) { $errText.Substring(0, 1800) + "..." } else { $errText }- Write-Info " desktop build output:"- foreach ($line in $snippet -split "`n") { Write-Host " $line" -ForegroundColor DarkGray }- Write-Info " Full log: $buildLog"- }- # `npm run pack` failures (lifecycle script exits) also land in- # npm's debug log; replay it so the bootstrap log carries the- # full evidence even when $buildLog's tail cuts off the cause.- Write-NpmDebugLogTail -NpmOutput $errText- throw "apps/desktop build failed (exit $code)"- }- Write-Success "Desktop app built"- Remove-Item -LiteralPath $buildLog -Force -ErrorAction SilentlyContinue- } catch {- if ($prevEAP) { $ErrorActionPreference = $prevEAP }- Pop-Location- throw- } finally {- # Restore env to whatever the caller had -- don't leak our- # signing-off override into anything install.ps1 invokes later- # (Stage-PlatformSdks, etc.).- $env:CSC_IDENTITY_AUTO_DISCOVERY = $prevCSCAuto- $env:WIN_CSC_LINK = $prevWinCscLink- $env:WIN_CSC_KEY_PASSWORD = $prevWinCscKeyPassword- }- Pop-Location-- # 3. Sanity-check the produced binary. Probe both arches so this works- # on x64 and arm64 build machines.- $exeCandidates = @(- "$desktopDir\release\win-unpacked\Hermes.exe",- "$desktopDir\release\win-arm64-unpacked\Hermes.exe"- )- $found = $false- $desktopExe = $null- foreach ($cand in $exeCandidates) {- if (Test-Path $cand) {- Write-Success "Desktop ready: $cand"- $desktopExe = $cand- $found = $true- break- }- }- if (-not $found) {- throw "Desktop build completed but no Hermes.exe was found under $desktopDir\release\*-unpacked\"- }-- # 3b. The Hermes icon + identity are stamped onto Hermes.exe by the- # electron-builder `afterPack` hook (apps/desktop/scripts/after-pack.mjs)- # during `npm run pack` above -- for every build, so the installer's- # --update rebuild stays branded too. No separate stamp step needed here.- # electron-builder's own rcedit step stays disabled (signAndEditExecutable- # =false) because enabling it drags in signtool -> winCodeSign -> the- # unfixable symlink crash; the afterPack hook runs rcedit directly.-- # 3c. Grant ALL APPLICATION PACKAGES (S-1-15-2-2) RX on the unpacked app- # directory. Chromium's GPU/renderer sandboxes CHECK-fail with- # 0x80000003 when this ACE is missing alongside orphan AppContainer- # SIDs under %LOCALAPPDATA% (electron/electron#51761, hermes-agent#38216).- # Best-effort -- never fail an otherwise-good install over ACL repair.- try {- $appDir = Split-Path -Parent $desktopExe- & icacls $appDir /grant "*S-1-15-2-2:(OI)(CI)(RX)" /T /C /Q | Out-Null- if ($LASTEXITCODE -eq 0) {- Write-Success "Granted AppContainer read access on $appDir"- } else {- Write-Warn "icacls AppContainer grant returned exit $LASTEXITCODE for $appDir"- }- } catch {- Write-Warn "Could not grant AppContainer ACL: $($_.Exception.Message)"- }-- # 4. Create Start Menu + Desktop shortcuts pointing DIRECTLY at the packed- # Hermes.exe. We deliberately do NOT point them at `hermes desktop`: that- # command rebuilds (npm install + electron-builder) on every launch,- # which would cost minutes each time. The packed exe is the consumer --- # launching it directly is instant, and updates flow through the- # installer's --update path (which rebuilds once, then relaunches).- New-DesktopShortcuts -TargetExe $desktopExe-}-function New-DesktopShortcuts {param([Parameter(Mandatory = $true)][string]$TargetExe)@@ -692,9 +419,9 @@ function New-DesktopShortcuts {$sc.IconLocation = $iconLocation$sc.Description = 'Hermes Agent'$sc.Save()- Write-Success "Shortcut created: $lnkPath"+ Write-Host "[hermes] Shortcut created: $lnkPath" -ForegroundColor Green} catch {- Write-Warn "Could not create shortcut $lnkPath : $($_.Exception.Message)"+ Write-Host "[hermes] Could not create shortcut $lnkPath : $($_.Exception.Message)" -ForegroundColor Yellow}}@@ -710,285 +437,10 @@ function New-DesktopShortcuts {# ie4uinit may be absent/renamed on some SKUs -- ignore.}} catch {- Write-Warn "Skipping shortcut creation: $($_.Exception.Message)"+ Write-Host "[hermes] Skipping shortcut creation: $($_.Exception.Message)" -ForegroundColor Yellow}}-function Install-PlatformSdks {- # Ensure messaging-platform SDKs matching tokens the user added to- # ~/.hermes/.env are importable. Two problems this solves:- #- # 1. The tiered `uv pip install` cascade above can fall through to a- # lower tier when the first fails (common when RL git deps choke),- # which silently skips some messaging SDKs from [messaging].- # 2. `uv` creates the venv without pip. If a messaging SDK ends up- # missing, the user can't `pip install python-telegram-bot` to- # recover -- pip simply isn't in their venv.- #- # Strategy: bootstrap pip via `python -m ensurepip` (idempotent), then- # for each token set in .env, verify the matching SDK imports. If not,- # run one targeted `pip install` as last-chance recovery. Keeps fresh- # Windows installs from hitting silent "python-telegram-bot not installed"- # at runtime.- if ($NoVenv) {- Write-Info "Skipping platform-SDK verification (-NoVenv: no venv to bootstrap)"- return- }-- $pythonExe = "$InstallDir\venv\Scripts\python.exe"- if (-not (Test-Path $pythonExe)) {- Write-Warn "Skipping platform-SDK verification: $pythonExe not found"- return- }-- $envPath = "$HermesHome\.env"- if (-not (Test-Path $envPath)) { return }- $envLines = Get-Content $envPath -ErrorAction SilentlyContinue-- # Map: env var set in .env -> (import name, pip spec matching [messaging] extra).- # Specs mirror pyproject.toml to avoid version drift.- $sdkMap = @(- @{ Var = "TELEGRAM_BOT_TOKEN"; Import = "telegram"; Spec = "python-telegram-bot[webhooks]>=22.6,<23" },- @{ Var = "DISCORD_BOT_TOKEN"; Import = "discord"; Spec = "discord.py[voice]>=2.7.1,<3" },- @{ Var = "SLACK_BOT_TOKEN"; Import = "slack_sdk"; Spec = "slack-sdk>=3.27.0,<4" },- @{ Var = "SLACK_APP_TOKEN"; Import = "slack_bolt";Spec = "slack-bolt>=1.18.0,<2" },- @{ Var = "WHATSAPP_ENABLED"; Import = "qrcode"; Spec = "qrcode>=7.0,<8" }- )-- # Which tokens are actually set (not placeholder)?- $needed = @()- foreach ($sdk in $sdkMap) {- $match = $envLines | Where-Object {- $_ -match ("^" + [regex]::Escape($sdk.Var) + "=.+") `- -and $_ -notmatch "your-token-here" `- -and $_ -notmatch "^\s*#"- }- if ($match) { $needed += $sdk }- }- if ($needed.Count -eq 0) { return }-- Write-Host ""- Write-Info "Verifying platform SDKs for tokens found in $envPath ..."-- # Verify each SDK's import without triggering side-effect imports.- # Quirk: PowerShell wraps non-zero-exit native stderr as a- # NativeCommandError that prints even with `2>$null` / `*> $null`- # unless we set $ErrorActionPreference to SilentlyContinue for the- # span. Save + restore rather than nuking globally.- $prevEAP = $ErrorActionPreference- $ErrorActionPreference = "SilentlyContinue"- try {- $missing = @()- foreach ($sdk in $needed) {- & $pythonExe -c "import $($sdk.Import)" 2>&1 | Out-Null- if ($LASTEXITCODE -ne 0) {- $missing += $sdk- Write-Warn " $($sdk.Import) NOT importable (needed for $($sdk.Var))"- } else {- Write-Success " $($sdk.Import) OK"- }- }- } finally {- $ErrorActionPreference = $prevEAP- }- if ($missing.Count -eq 0) { return }-- # Bootstrap pip into the venv if it isn't there. `uv` creates venvs- # without pip; ensurepip is the stdlib-blessed way to add it.- $prevEAP = $ErrorActionPreference- $ErrorActionPreference = "SilentlyContinue"- try {- & $pythonExe -m pip --version 2>&1 | Out-Null- if ($LASTEXITCODE -ne 0) {- Write-Info "Bootstrapping pip into venv (uv doesn't ship pip)..."- & $pythonExe -m ensurepip --upgrade 2>&1 | Out-Null- if ($LASTEXITCODE -ne 0) {- Write-Warn "ensurepip failed -- can't auto-install missing SDKs."- Write-Info "Manual recovery: $UvCmd pip install `"$($missing[0].Spec)`""- return- }- }-- foreach ($sdk in $missing) {- Write-Info " Installing $($sdk.Spec) ..."- & $pythonExe -m pip install $sdk.Spec 2>&1 | ForEach-Object { Write-Host " $_" }- if ($LASTEXITCODE -eq 0) {- Write-Success " Installed $($sdk.Import)"- } else {- Write-Warn " Failed to install $($sdk.Spec). Recover manually: $pythonExe -m pip install `"$($sdk.Spec)`""- }- }- } finally {- $ErrorActionPreference = $prevEAP- }-}--function Invoke-SetupWizard {- if ($SkipSetup) {- Write-Info "Skipping setup wizard (-SkipSetup)"- return- }-- if ($NonInteractive) {- # The setup wizard prompts for API keys, model choice, persona, etc.- # Non-interactive callers (GUI installer) own that UX themselves; let- # them drive it after install.ps1 returns.- Write-Info "Skipping setup wizard (non-interactive). Configure via the GUI or 'hermes setup'."- return- }-- Write-Host ""- Write-Info "Starting setup wizard..."- Write-Host ""-- Push-Location $InstallDir-- # Run hermes setup using the venv Python directly (no activation needed)- if (-not $NoVenv) {- & ".\venv\Scripts\python.exe" -m hermes_cli.main setup- } else {- python -m hermes_cli.main setup- }-- Pop-Location-}--function Start-GatewayIfConfigured {- $envPath = "$HermesHome\.env"- if (-not (Test-Path $envPath)) { return }-- $hasMessaging = $false- $content = Get-Content $envPath -ErrorAction SilentlyContinue- foreach ($var in @("TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "WHATSAPP_ENABLED")) {- $match = $content | Where-Object { $_ -match "^${var}=.+" -and $_ -notmatch "your-token-here" }- if ($match) { $hasMessaging = $true; break }- }-- if (-not $hasMessaging) { return }-- $hermesCmd = "$InstallDir\venv\Scripts\hermes.exe"- if (-not (Test-Path $hermesCmd)) {- $hermesCmd = "hermes"- }-- # If WhatsApp is enabled but not yet paired, run foreground for QR scan- $whatsappEnabled = $content | Where-Object { $_ -match "^WHATSAPP_ENABLED=true" }- $whatsappSession = "$HermesHome\whatsapp\session\creds.json"- if ($whatsappEnabled -and -not (Test-Path $whatsappSession)) {- Write-Host ""- Write-Info "WhatsApp is enabled but not yet paired."- Write-Info "Running 'hermes whatsapp' to pair via QR code..."- Write-Host ""- # Non-interactive callers (GUI installer, CI) skip the QR-pair prompt;- # WhatsApp pairing requires a human looking at a phone camera, so the- # downstream UI is responsible for surfacing this when it makes sense.- if (-not $NonInteractive) {- $response = Read-Host "Pair WhatsApp now? [Y/n]"- if ($response -eq "" -or $response -match "^[Yy]") {- try {- & $hermesCmd whatsapp- } catch {- # Expected after pairing completes- }- }- } else {- Write-Info "Skipping WhatsApp pairing prompt (non-interactive)."- }- }-- Write-Host ""- Write-Info "Messaging platform token detected!"- Write-Info "The gateway handles messaging platforms and cron job execution."- Write-Host ""-- # In non-interactive mode the gateway lifecycle is the caller's problem- # (the GUI manages its own gateway process, CI doesn't want background- # services on the build agent, etc.). Treat it like the user declined.- if ($NonInteractive) {- Write-Info "Skipping gateway autostart prompt (non-interactive)."- Write-Info "Start the gateway later with: hermes gateway"- return- }-- $response = Read-Host "Would you like to start the gateway now? [Y/n]"-- if ($response -eq "" -or $response -match "^[Yy]") {- Write-Info "Starting gateway in background..."- try {- $logFile = "$HermesHome\logs\gateway.log"- Start-Process -FilePath $hermesCmd -ArgumentList "gateway" `- -RedirectStandardOutput $logFile `- -RedirectStandardError "$HermesHome\logs\gateway-error.log" `- -WindowStyle Hidden- Write-Success "Gateway started! Your bot is now online."- Write-Info "Logs: $logFile"- Write-Info "To stop: close the gateway process from Task Manager"- } catch {- Write-Warn "Failed to start gateway. Run manually: hermes gateway"- }- } else {- Write-Info "Skipped. Start the gateway later with: hermes gateway"- }-}--function Write-Completion {- Write-Host ""- Write-Host "+---------------------------------------------------------+" -ForegroundColor Green- Write-Host "| [OK] Installation Complete! |" -ForegroundColor Green- Write-Host "+---------------------------------------------------------+" -ForegroundColor Green- Write-Host ""-- # Show file locations- Write-Host "* Your files:" -ForegroundColor Cyan- Write-Host ""- Write-Host " Config: " -NoNewline -ForegroundColor Yellow- Write-Host "$HermesHome\config.yaml"- Write-Host " API Keys: " -NoNewline -ForegroundColor Yellow- Write-Host "$HermesHome\.env"- Write-Host " Data: " -NoNewline -ForegroundColor Yellow- Write-Host "$HermesHome\cron\, sessions\, logs\"- Write-Host " Code: " -NoNewline -ForegroundColor Yellow- Write-Host "$HermesHome\hermes-agent\"- Write-Host ""-- Write-Host "---------------------------------------------------------" -ForegroundColor Cyan- Write-Host ""- Write-Host "* Commands:" -ForegroundColor Cyan- Write-Host ""- Write-Host " hermes " -NoNewline -ForegroundColor Green- Write-Host "Start chatting"- Write-Host " hermes setup " -NoNewline -ForegroundColor Green- Write-Host "Configure API keys & settings"- Write-Host " hermes config " -NoNewline -ForegroundColor Green- Write-Host "View/edit configuration"- Write-Host " hermes config edit " -NoNewline -ForegroundColor Green- Write-Host "Open config in editor"- Write-Host " hermes gateway " -NoNewline -ForegroundColor Green- Write-Host "Start messaging gateway (Telegram, Discord, etc.)"- Write-Host " hermes update " -NoNewline -ForegroundColor Green- Write-Host "Update to latest version"- Write-Host ""-- Write-Host "---------------------------------------------------------" -ForegroundColor Cyan- Write-Host ""- Write-Host "[*] Restart your terminal for PATH changes to take effect" -ForegroundColor Yellow- Write-Host ""-- if (-not $HasNode) {- Write-Host "Note: Node.js could not be installed automatically." -ForegroundColor Yellow- Write-Host "Browser tools need Node.js. Install manually:" -ForegroundColor Yellow- Write-Host " https://nodejs.org/en/download/" -ForegroundColor Yellow- Write-Host ""- }-- if (-not $HasRipgrep) {- Write-Host "Note: ripgrep (rg) was not installed. For faster file search:" -ForegroundColor Yellow- Write-Host " winget install BurntSushi.ripgrep.MSVC" -ForegroundColor Yellow- Write-Host ""- }-}--function Invoke-StageByName([string]$name) {switch ($name) {"prerequisites" { Stage-Prerequisites }@@ -1014,13 +466,20 @@ if ($Manifest) {}if ($Stage) {+ # The $Stages table is the single authoritative list: it drives the+ # -Manifest output AND the no-flag ladder, so -IncludeDesktop affects+ # the real run exactly as the manifest advertises. "desktop" stays+ # directly dispatchable via -Stage even without the flag (long-standing+ # external-caller contract; the bootstrap frontend always pairs it+ # with -IncludeDesktop when it lists the stage).$known = @($Stages | ForEach-Object { $_.name })if ($known -notcontains $Stage -and $Stage -ne "desktop") {if ($Json) { Emit-Frame $false $Stage $false "unknown stage: $Stage" }else { [Console]::Error.WriteLine("unknown stage: $Stage") }exit 2}- $needsInput = ($Stage -eq "setup") -or ($Stage -eq "gateway")+ $stageDef = $Stages | Where-Object { $_.name -eq $Stage } | Select-Object -First 1+ $needsInput = $stageDef -and $stageDef.needs_user_inputif ($NonInteractive -and $needsInput) {if ($Json) { Emit-Frame $true $Stage $true "needs user input" }exit 0@@ -1035,7 +494,8 @@ if ($Stage) {}}-# No -Stage: run the whole ladder.-foreach ($s in @("prerequisites","repository","venv","python-deps","node-deps","path","config","setup","gateway","complete")) {- Invoke-StageByName $s+# No -Stage: run the whole ladder — the same authoritative list the+# manifest prints, so -IncludeDesktop inserts desktop here too.+foreach ($s in $Stages) {+ Invoke-StageByName $s.name}diff --git a/scripts/install.sh b/scripts/install.shindex 6368b15c17d..00769e1508d 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -180,23 +180,42 @@ json_frame() {fi}+# The single authoritative stage list: emit_manifest prints it AND the+# no-flag ladder runs it, so --include-desktop affects the real run+# exactly as the manifest advertises.+stage_names() {+ printf '%s\n' prerequisites repository venv python-deps node-deps path config setup gateway+ [ "$INCLUDE_DESKTOP" = true ] && printf '%s\n' desktop+ printf '%s\n' complete+}++# "$1" stage name -> its manifest record fields (title|category|needs_user_input).+stage_record() {+ case "$1" in+ prerequisites) echo "System prerequisites|runtime|false" ;;+ repository) echo "Download Hermes Agent|runtime|false" ;;+ venv) echo "Create Python environment|runtime|false" ;;+ python-deps) echo "Install Python dependencies|runtime|false" ;;+ node-deps) echo "Install tool dependencies|runtime|false" ;;+ path) echo "Install hermes command|runtime|false" ;;+ config) echo "Prepare config and skills|configuration|false" ;;+ setup) echo "Configure API keys and settings|configuration|true" ;;+ gateway) echo "Configure gateway service|configuration|true" ;;+ desktop) echo "Build desktop app|runtime|false" ;;+ complete) echo "Finish install|runtime|false" ;;+ esac+}+emit_manifest() {- local desktop=""- if [ "$INCLUDE_DESKTOP" = true ]; then- desktop='{"name":"desktop","title":"Build desktop app","category":"runtime","needs_user_input":false},'- fiprintf '%s' '{"protocol_version":1,"stages":['- printf '%s' '{"name":"prerequisites","title":"System prerequisites","category":"runtime","needs_user_input":false},'- printf '%s' '{"name":"repository","title":"Download Hermes Agent","category":"runtime","needs_user_input":false},'- printf '%s' '{"name":"venv","title":"Create Python environment","category":"runtime","needs_user_input":false},'- printf '%s' '{"name":"python-deps","title":"Install Python dependencies","category":"runtime","needs_user_input":false},'- printf '%s' '{"name":"node-deps","title":"Install tool dependencies","category":"runtime","needs_user_input":false},'- printf '%s' '{"name":"path","title":"Install hermes command","category":"runtime","needs_user_input":false},'- printf '%s' '{"name":"config","title":"Prepare config and skills","category":"configuration","needs_user_input":false},'- printf '%s' '{"name":"setup","title":"Configure API keys and settings","category":"configuration","needs_user_input":true},'- printf '%s' '{"name":"gateway","title":"Configure gateway service","category":"configuration","needs_user_input":true},'- printf '%s' "$desktop"- printf '%s\n' '{"name":"complete","title":"Finish install","category":"runtime","needs_user_input":false}]}'+ _sep=""+ for _s in $(stage_names); do+ IFS='|' read -r _title _category _needs <<< "$(stage_record "$_s")"+ printf '%s{"name":"%s","title":"%s","category":"%s","needs_user_input":%s}' \+ "$_sep" "$_s" "$_title" "$_category" "$_needs"+ _sep=","+ done+ printf '%s\n' ']}'}stage_prerequisites() {@@ -214,7 +233,38 @@ stage_repository() {elselog "cloning $REPO_URL ($BRANCH) into $INSTALL_DIR"mkdir -p "$(dirname "$INSTALL_DIR")"- git clone --branch "$BRANCH" "$REPO_URL" "$INSTALL_DIR" || fail "git clone failed"+ local staged attempt cloned=false+ staged="$(mktemp -d "$(dirname "$INSTALL_DIR")/.hermes-clone-XXXXXX")" || fail "cannot stage clone"+ for attempt in 1 2 3; do+ if git clone --branch "$BRANCH" "$REPO_URL" "$staged/tree"; then+ cloned=true+ break+ fi+ rm -rf "$staged/tree"+ [ "$attempt" = 3 ] || sleep "$((attempt * 5))"+ done+ if [ "$cloned" = false ]; then+ log "direct clone failed; trying deferred blob download"+ if git clone --depth 1 --single-branch --filter=blob:none --no-checkout \+ --branch "$BRANCH" "$REPO_URL" "$staged/tree"; then+ for attempt in 1 2; do+ if git -C "$staged/tree" reset --hard HEAD; then+ cloned=true+ break+ fi+ [ "$attempt" = 2 ] || sleep 5+ done+ fi+ fi+ if [ "$cloned" = false ]; then+ rm -rf "$staged"+ fail "git clone failed; no checkout published"+ fi+ if ! mv "$staged/tree" "$INSTALL_DIR"; then+ rm -rf "$staged"+ fail "cannot publish cloned checkout"+ fi+ rmdir "$staged"fiif [ -n "$INSTALL_COMMIT" ]; thengit -C "$INSTALL_DIR" checkout "$INSTALL_COMMIT" || fail "could not pin commit $INSTALL_COMMIT"@@ -332,7 +382,9 @@ stage_gateway() {}stage_desktop() {- "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/hermes" desktop build || fail "desktop build failed"+ # `hermes desktop --build-only` is the current authority (same path as+ # `hermes gui` / the update flow); no installer-local node/electron code.+ "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/hermes" desktop --build-only || fail "desktop build failed"}stage_complete() {@@ -364,29 +416,35 @@ run_stage() {esac}-if [ "$WANT_MANIFEST" = true ]; then- emit_manifest- exit 0-fi--check_platform--if [ -n "$STAGE" ]; then- if [ "$NON_INTERACTIVE" = true ] && { [ "$STAGE" = setup ] || [ "$STAGE" = gateway ]; }; then- [ "$JSON" = true ] && json_frame true "$STAGE" true "needs user input"+# Main. Guarded so the script can be SOURCED for its functions (the+# installer-test harness sources it with --manifest, which must define+# the functions and stop before main).+if [ "${BASH_SOURCE[0]}" = "$0" ]; then+ if [ "$WANT_MANIFEST" = true ]; then+ emit_manifestexit 0fi- if run_stage "$STAGE"; then- [ "$JSON" = true ] && json_frame true "$STAGE" false- exit 0- else- rc=$?- [ "$JSON" = true ] && json_frame false "$STAGE" false "stage failed"- exit "$rc"++ check_platform++ if [ -n "$STAGE" ]; then+ if [ "$NON_INTERACTIVE" = true ] && { [ "$STAGE" = setup ] || [ "$STAGE" = gateway ]; }; then+ [ "$JSON" = true ] && json_frame true "$STAGE" true "needs user input"+ exit 0+ fi+ if run_stage "$STAGE"; then+ [ "$JSON" = true ] && json_frame true "$STAGE" false+ exit 0+ else+ rc=$?+ [ "$JSON" = true ] && json_frame false "$STAGE" false "stage failed"+ exit "$rc"+ fifi-fi-# No --stage: run the whole ladder.-for s in prerequisites repository venv python-deps node-deps path config setup gateway complete; do- run_stage "$s"-done+ # No --stage: run the whole ladder — the same authoritative list the+ # manifest prints, so --include-desktop inserts desktop here too.+ for s in $(stage_names); do+ run_stage "$s"+ done+fidiff --git a/scripts/r2-release.mjs b/scripts/r2-release.mjsindex 46d2a78a38c..c7784d2d22b 100644--- a/scripts/r2-release.mjs+++ b/scripts/r2-release.mjs@@ -434,14 +434,27 @@ async function cmdFinalize({ tag, dir }) {console.log(`✓ r2: finalized ${tag} → ${channel} feed manifests`)}-/** Parse a ListObjectsV2 XML body into { keys: string[], truncated, nextToken }. */+/** Parse a ListObjectsV2 XML body into { keys, lastModified, truncated, nextToken }. */export function parseListXml(xml) {const unescape = (s) =>s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&')const keys = [...xml.matchAll(/<Key>([^<]+)<\/Key>/g)].map((m) => unescape(m[1]))+ const lastModified = {}+ for (const m of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {+ const key = m[1].match(/<Key>([^<]+)<\/Key>/)+ const lm = m[1].match(/<LastModified>([^<]+)<\/LastModified>/)+ if (key && lm) lastModified[unescape(key[1])] = Date.parse(lm[1])+ }const truncated = /<IsTruncated>true<\/IsTruncated>/.test(xml)const tokenMatch = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)- return { keys, truncated, nextToken: tokenMatch ? unescape(tokenMatch[1]) : null }+ return { keys, lastModified, truncated, nextToken: tokenMatch ? unescape(tokenMatch[1]) : null }+}++/** GET one object's body, or null when it does not exist / cannot be read. */+async function getObject(creds, base, bucket, key, now) {+ const url = `${base}/${bucket}/${encodeKeyPath(key)}`+ const { res, text } = await signedFetch('GET', url, { bodyHash: EMPTY_SHA, creds, now })+ return res.ok ? text : null}async function listObjects(prefix = '') {@@ -453,6 +466,7 @@ async function listObjects(prefix = '') {const base = s3Endpoint(accountId)const keys = []+ const lastModified = {}let token = nullfor (;;) {const params = { 'list-type': '2', 'max-keys': '1000' }@@ -465,14 +479,16 @@ async function listObjects(prefix = '') {if (!res.ok) process.exit(1)const parsed = parseListXml(text)keys.push(...parsed.keys)+ Object.assign(lastModified, parsed.lastModified)if (!parsed.truncated || !parsed.nextToken) breaktoken = parsed.nextToken}- return keys+ return { keys, lastModified }}async function cmdList({ prefix }) {- for (const key of await listObjects(prefix)) console.log(key)+ const { keys } = await listObjects(prefix)+ for (const key of keys) console.log(key)}/** Keys whose own canary date (YYYYMMDD in the name) is before `cutoff`. */@@ -483,6 +499,94 @@ export function canaryDoomedKeys(keys, cutoff) {})}+/** Feed publish order: the immutable .msixbundle FIRST, the pointer LAST. */+export function publishFeedUploads(plan, upload) {+ upload(`${plan.channelDir}/${plan.bundleFilename}`, plan.bundleFile)+ upload(`${plan.channelDir}/${plan.appinstallerName}`, plan.appinstallerFile)+}++/**+ * Bundle basenames a .appinstaller manifest still references, parsed from the+ * KNOWN generated shape (MainPackage/MainBundle Uri attributes only — never+ * any Uri=" in the document). An unrecognized/empty manifest returns [], and+ * the pruner treats [] as "block this directory" (fail closed).+ */+function feedBundleUris(appinstallerXml) {+ const xml = String(appinstallerXml || '').trim()+ // Only our complete generated shape is eligible for destructive retention.+ if (!/^(?:<\?xml[^?]*\?>\s*)?<AppInstaller\b[^>]*>[\s\S]*<\/AppInstaller>$/.test(xml)) return []+ const elements = [...xml.matchAll(/<(?:MainPackage|MainBundle)\b[^>]*\/>/g)]+ if (elements.length !== 1) return []+ const uri = elements[0][0].match(/\bUri="([^"]+)"/)+ return uri && /\.(?:msixbundle|msix)$/i.test(uri[1]) ? [uri[1]] : []+}++export function referencedFeedBundleFilenames(appinstallerXml) {+ return feedBundleUris(appinstallerXml).map(uri => uri.split('/').pop())+}++/**+ * Full bucket keys a manifest references: each referenced bundle inside its+ * feed dir, plus any MainPackage/MainBundle Uri carrying an absolute path+ * (e.g. /releases/tag/<tag>/… — tag-archive targets), protected by exact key.+ */+export function feedReferencedKeys(dir, appinstallerXml) {+ const keys = []+ for (const uri of feedBundleUris(appinstallerXml)) {+ keys.push(`${dir}/${uri.split('/').pop()}`)+ try {+ const p = new URL(uri, 'https://placeholder.invalid').pathname+ if (p.startsWith('/releases/')) keys.push(decodeURIComponent(p.slice(1)))+ } catch { /* relative Uri — already covered by the basename key */ }+ }+ return keys+}++/**+ * Canary feed-dir retention: the `-canary.YYYYMMDD` matcher cannot see feed+ * bundles (numeric 4-part MSIX version names). A bundle is doomed when its+ * feed dir's manifests were ALL readable AND it is referenced by none of+ * them AND its actual list LastModified predates cutoffMs. Fail-closed on+ * every unknown: unreadable/unrecognized manifest (zero references) blocks+ * the whole dir; stable dirs and unknown dirs are never pruned; a missing+ * LastModified keeps the object.+ *+ * @param {string[]} keys all bucket keys+ * @param {Record<string, (string|null)[]>} feedXmlByDir dir → manifest texts (null = unreadable)+ * @param {Record<string, number>} lastModifiedMs key → epoch ms from listObjects+ * @param {number} cutoffMs+ * @returns {string[]} doomed feed-dir bundle keys+ */+export function staleFeedBundleKeys(keys, feedXmlByDir, lastModifiedMs = {}, cutoffMs = -Infinity) {+ const doomed = []+ for (const [dir, manifests] of Object.entries(feedXmlByDir || {})) {+ if (!/\/canary$/.test(dir.replace(/\/+$/, ''))) continue // canaries only+ const referenced = new Set()+ let blocked = false+ for (const xml of manifests || []) {+ const names = referencedFeedBundleFilenames(xml)+ if (names.length === 0) {+ // Unreadable or unrecognized manifest in this dir → prune nothing here.+ blocked = true+ console.warn(`::warning::feed manifest unreadable/unrecognized, skipping feed retention for ${dir}/`)+ break+ }+ for (const name of names) referenced.add(name)+ }+ if (blocked || referenced.size === 0) continue+ const prefix = `${dir.replace(/\/+$/, '')}/`+ for (const key of keys) {+ if (!key.startsWith(prefix)) continue+ if (!/\.(?:msixbundle|msix)$/i.test(key)) continue // pointers + metadata stay+ if (referenced.has(key.slice(prefix.length))) continue+ const lm = lastModifiedMs[key]+ if (!Number.isFinite(lm) || lm >= cutoffMs) continue // keep-days grace (fail-closed)+ doomed.push(key)+ }+ }+ return doomed+}+async function cmdPrune({ keepDays, dryRun }) {const accountId = requiredEnv('CLOUDFLARE_R2_ACCOUNT_ID')const accessKeyId = requiredEnv('CLOUDFLARE_R2_ACCESS_KEY_ID')@@ -494,13 +598,35 @@ async function cmdPrune({ keepDays, dryRun }) {// Cutoff dated by the canary suffix in the KEY (like release.py's// --prune-canaries: a re-uploaded old tag never resets its clock).const cutoff = new Date(Date.now() - keepDays * 86400_000).toISOString().slice(0, 10).replace(/-/g, '')- const keys = await listObjects()- const doomed = canaryDoomedKeys(keys, cutoff)+ const cutoffMs = Date.now() - keepDays * 86400_000+ const { keys, lastModified } = await listObjects()+ const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')++ // Read EVERY .appinstaller per feed dir (union of references protects the+ // dir; any unreadable/unrecognized one blocks retention for that dir —+ // handled inside staleFeedBundleKeys, null = unreadable).+ const feedXmlByDir = {}+ const protectedKeys = new Set()+ for (const key of keys.filter((k) => k.endsWith('.appinstaller'))) {+ const dir = key.slice(0, key.lastIndexOf('/'))+ const xml = await getObject(creds, base, bucket, key, now)+ if (feedBundleUris(xml).length === 0) {+ throw new Error(`Cannot establish live references from ${key}; refusing to prune`)+ }+ ;(feedXmlByDir[dir] ??= []).push(xml)+ for (const k of feedReferencedKeys(dir, xml)) protectedKeys.add(k)+ }++ const doomed = [+ ...canaryDoomedKeys(keys, cutoff),+ ...staleFeedBundleKeys(keys, feedXmlByDir, lastModified, cutoffMs),+ // Live referenced objects (incl. tag-archive targets) are never deleted.+ ].filter((key) => !protectedKeys.has(key))+if (doomed.length === 0) {console.log(`✓ r2: no canary objects older than ${keepDays} days`)return}- const now = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')for (const key of doomed.sort()) {if (dryRun) {console.log(`(dry-run) would delete r2:${key}`)@@ -558,7 +684,8 @@ export async function main(argv = process.argv.slice(2)) {} else if (cmd === 'prune-canaries') {const keepDays = Number(args['keep-days'])if (!Number.isFinite(keepDays) || keepDays <= 0) usage()- await cmdPrune({ keepDays, dryRun: Boolean(args.dryRun) })+ // '--dry-run' parses to args['dry-run'] (flag.slice(2) keeps the dash).+ await cmdPrune({ keepDays, dryRun: Boolean(args['dry-run']) })} else {usage()}diff --git a/scripts/run_tests_parallel.py b/scripts/run_tests_parallel.pyindex dd1092d5f68..9913c88c32c 100644--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.py@@ -460,6 +460,9 @@ def _run_one_file_once(# runner over one suite.shutil.rmtree(temproot, ignore_errors=True)+ if rc not in (0, 5) and not output.strip():+ output = f"pytest child exited {rc} (0x{rc & 0xffffffff:08x}) with no output: {file}\n"+if rc == 5:# No tests collected in THIS file — legitimate per-file: a# platform-gated or fully-marker-filtered file (e.g. a win32-onlydiff --git a/scripts/stage-msixbundle.mjs b/scripts/stage-msixbundle.mjsindex 4c8f897884f..6405a1c67af 100644--- a/scripts/stage-msixbundle.mjs+++ b/scripts/stage-msixbundle.mjs@@ -6,7 +6,9 @@//// 1. OUT-OF-STORE FEED: bundle the x64 + arm64 per-arch .msix into one// universal .msixbundle, sign the bundle envelope, write the per-channel-// .appinstaller, and upload both to the win32 feed dirs:+// .appinstaller, and upload both to the win32 feed dirs — bundle FIRST,+// .appinstaller pointer LAST (a failed bundle upload leaves the previous+// feed intact):// releases/win32/<stable|canary>/<name>-<ver>.win.msixbundle// releases/win32/<stable|canary>/stable.appinstaller (or canary.*)// The .appinstaller is the install + auto-update entry point; the bundle@@ -28,6 +30,7 @@ import path from 'node:path'import { fileURLToPath } from 'node:url'import { appIdentity, buildAppInstaller, resolveWinSdkTools } from './msix-shared.mjs'+import { publishFeedUploads } from './r2-release.mjs'const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')@@ -243,7 +246,7 @@ const appinstaller = buildAppInstaller({const appinstallerName = `${channel}.appinstaller`fs.writeFileSync(path.join(releaseDir, appinstallerName), appinstaller)-const upload = (key, file, keyIsFull = false) => {+const upload = (key, file, keyIsFull = true) => {// NOTE: no fs.readFileSync here — the msixbundle can exceed Node's 2GiB// buffer limit (ERR_FS_FILE_TOO_LARGE). r2-release.mjs put reads + hashes// the file itself; log the size via stat instead.@@ -258,10 +261,19 @@ const upload = (key, file, keyIsFull = false) => {})}-// Feed dir manifests (the install + update source). Content-Types matter:-// .appinstaller / .msixbundle must reach the OS App Installer, not download.-upload(`${channelDir}/${appinstallerName}`, path.join(releaseDir, appinstallerName), true)-upload(`${channelDir}/${name}-${version}-win.msixbundle`, bundle, true)+// C22 ordering: bundle FIRST, pointer LAST. r2-release.mjs PUTs then+// HEAD-verifies the remote content-length — a failed/short upload throws+// and aborts this job before the pointer is written.+publishFeedUploads(+ {+ channelDir,+ appinstallerName,+ bundleFilename: `${name}-${version}-win.msixbundle`,+ bundleFile: bundle,+ appinstallerFile: path.join(releaseDir, appinstallerName),+ },+ upload,+)// The Store-submission .msix files were already uploaded to the tag archive// by the win legs (Store- prefix); nothing for this job to re-upload.diff --git a/tests-js/r2-release.test.mjs b/tests-js/r2-release.test.mjsindex 3ea6d0d08de..2ddf7eec891 100644--- a/tests-js/r2-release.test.mjs+++ b/tests-js/r2-release.test.mjs@@ -16,7 +16,7 @@import assert from 'node:assert/strict'-import { test } from 'vitest'+import { test, vi } from 'vitest'import {authHeader,@@ -26,8 +26,12 @@ import {contentTypeFor,encodeKeyPath,feedDirFor,+ feedReferencedKeys,mergeFeedYmls,canaryDoomedKeys,+ publishFeedUploads,+ referencedFeedBundleFilenames,+ staleFeedBundleKeys,rewriteFeedPaths,stagingKeyFor,parseListXml,@@ -271,3 +275,233 @@ releaseDate: '2026-08-18T00:00:00.000Z'// Idempotent: merging the merged output adds nothing new.assert.equal(mergeFeedYmls([merged, arm64]), merged)})+++// ── C22: artifact first, feed pointer last ──────────────────────────────────++test('publishFeedUploads uploads the msixbundle BEFORE the .appinstaller pointer', () => {+ const calls = []+ publishFeedUploads(+ {+ channelDir: 'releases/win32/canary',+ appinstallerName: 'canary.appinstaller',+ bundleFilename: 'HermesBundled-0.27.2.9-win.msixbundle',+ bundleFile: 'C:/rel/HermesBundled-0.27.2.9-win.msixbundle',+ appinstallerFile: 'C:/rel/canary.appinstaller',+ },+ (key, file) => calls.push([key, file]),+ )+ assert.deepEqual(calls, [+ ['releases/win32/canary/HermesBundled-0.27.2.9-win.msixbundle', 'C:/rel/HermesBundled-0.27.2.9-win.msixbundle'],+ ['releases/win32/canary/canary.appinstaller', 'C:/rel/canary.appinstaller'],+ ])+})++test('publishFeedUploads never writes the pointer when the bundle upload fails', () => {+ const calls = []+ assert.throws(() =>+ publishFeedUploads(+ {+ channelDir: 'releases/win32/stable',+ appinstallerName: 'stable.appinstaller',+ bundleFilename: 'HermesBundled-0.28.0.0-win.msixbundle',+ bundleFile: 'bundle',+ appinstallerFile: 'feed',+ },+ (key) => {+ calls.push(key)+ throw new Error('R2 PUT -> 503')+ },+ ),+ )+ assert.deepEqual(calls, ['releases/win32/stable/HermesBundled-0.28.0.0-win.msixbundle'])+})++// ── C22: canary feed-dir retention (fail-closed, keep-days grace) ───────────++const CANARY_FEED_XML = `<?xml version="1.0" encoding="utf-8"?>+<AppInstaller Uri="https://r2.example/releases/win32/canary/canary.appinstaller" Version="0.27.2.9" xmlns="http://schemas.microsoft.com/appx/appinstaller/2017/2">+ <MainPackage Name="NousResearch.HermesBundled" Publisher="CN=..." Version="0.27.2.9" Uri="https://r2.example/releases/win32/canary/HermesBundled-0.27.2.9-win.msixbundle" />+</AppInstaller>+`++test('referencedFeedBundleFilenames reads MainPackage only; unrecognized -> []', () => {+ assert.deepEqual(referencedFeedBundleFilenames(CANARY_FEED_XML), ['HermesBundled-0.27.2.9-win.msixbundle'])+ // The AppInstaller ROOT Uri (the feed pointer itself) must NOT count.+ assert.ok(!referencedFeedBundleFilenames(CANARY_FEED_XML).includes('canary.appinstaller'))+ assert.deepEqual(referencedFeedBundleFilenames(''), [])+ assert.deepEqual(referencedFeedBundleFilenames('<html>ServiceUnavailable</html>'), [])+ // A bundle Uri OUTSIDE MainPackage/MainBundle is not a reference.+ assert.deepEqual(referencedFeedBundleFilenames('<Foo Uri="https://x/HermesBundled-1.0.0-win.msixbundle" />'), [])+})++test('feedReferencedKeys protects the referenced bundle and absolute tag Uris by exact key', () => {+ const tagFeed = CANARY_FEED_XML.replace(+ /Uri="https:\/\/r2\.example\/releases\/win32\/canary\/HermesBundled-0\.27\.2\.9-win\.msixbundle"/,+ 'Uri="https://r2.example/releases/tag/v0.27.2-canary.20260829/HermesBundled-0.27.2-win-x64.msix"',+ )+ const keys = feedReferencedKeys('releases/win32/canary', tagFeed)+ assert.ok(keys.includes('releases/win32/canary/HermesBundled-0.27.2-win-x64.msix'))+ assert.ok(keys.includes('releases/tag/v0.27.2-canary.20260829/HermesBundled-0.27.2-win-x64.msix'))+})++const CANARY_DIR = 'releases/win32/canary'+const OLD_MS = Date.parse('2026-08-01T00:00:00Z')+const FRESH_MS = Date.parse('2026-09-03T00:00:00Z')+const CUTOFF_MS = Date.parse('2026-08-21T00:00:00Z')++function canaryKeys(extra = []) {+ return [+ `${CANARY_DIR}/canary.appinstaller`,+ `${CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle`, // referenced+ `${CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle`, // stale+ `${CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle`, // uploaded, not yet pointed+ 'releases/win32/stable/stable.appinstaller',+ 'releases/win32/stable/HermesBundled-0.28.0.0-win.msixbundle', // referenced+ 'releases/win32/stable/HermesBundled-0.27.0.0-win.msixbundle', // stale stable+ ...extra,+ ]+}++function lastModifiedFor(keys, overrides = {}) {+ const lm = {}+ for (const k of keys) lm[k] = OLD_MS+ return Object.assign(lm, overrides)+}++test('staleFeedBundleKeys: old unreferenced canary bundle doomed, referenced and fresh ones kept', () => {+ const keys = canaryKeys()+ const lm = lastModifiedFor(keys, {+ // Uploaded-but-not-yet-pointed canary bundle is FRESH -> survives grace.+ [`${CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle`]: FRESH_MS,+ })+ const doomed = staleFeedBundleKeys(keys, { [CANARY_DIR]: [CANARY_FEED_XML] }, lm, CUTOFF_MS)+ assert.deepEqual(doomed, [`${CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle`])+})++test('staleFeedBundleKeys: stable dirs are never pruned', () => {+ const keys = canaryKeys()+ const lm = lastModifiedFor(keys, {+ // Uploaded-but-not-yet-pointed bundle is fresh here; its fate is covered+ // by the dedicated grace test.+ [`${CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle`]: FRESH_MS,+ })+ const feeds = {+ [CANARY_DIR]: [CANARY_FEED_XML],+ 'releases/win32/stable': [CANARY_FEED_XML.replace(/0\.27\.2\.9/g, '0.28.0.0').replace('HermesBundled-0.27.2.9-win', 'HermesBundled-0.28.0.0-win')],+ }+ const doomed = staleFeedBundleKeys(keys, feeds, lm, CUTOFF_MS)+ assert.deepEqual(doomed, [`${CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle`])+})++test('staleFeedBundleKeys: empty/malformed manifest dooms NOTHING in its dir (fail closed)', () => {+ const keys = canaryKeys()+ for (const bad of ['', '<html>boom</html>', null, '<Foo Uri="https://x/HermesBundled-1-win.msixbundle" />',+ '<MainPackage Uri="https://x/old.msixbundle" />',+ '<AppInstaller><MainBundle Uri="https://x/old.msixbundle" />',+ ]) {+ assert.deepEqual(+ staleFeedBundleKeys(keys, { [CANARY_DIR]: [bad] }, lastModifiedFor(keys), CUTOFF_MS),+ [],+ `bad manifest must block the dir: ${JSON.stringify(bad)}`,+ )+ }+})++test('staleFeedBundleKeys: two manifests in one dir — union protected, one bad blocks all', () => {+ const second = CANARY_FEED_XML.replace(/0\.27\.2\.9/g, '0.27.3.0').replace(+ 'HermesBundled-0.27.2.9-win',+ 'HermesBundled-0.27.3.0-win',+ )+ const keys = canaryKeys([`${CANARY_DIR}/second.appinstaller`, `${CANARY_DIR}/HermesBundled-0.27.3.0-win.msixbundle`])+ const lm = lastModifiedFor(keys, { [`${CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle`]: FRESH_MS })+ // Union of both feeds: both referenced bundles kept, the rest pruned.+ assert.deepEqual(staleFeedBundleKeys(keys, { [CANARY_DIR]: [CANARY_FEED_XML, second] }, lm, CUTOFF_MS), [+ `${CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle`,+ ])+ // ONE unreadable/unrecognized manifest in the dir blocks feed retention.+ assert.deepEqual(staleFeedBundleKeys(keys, { [CANARY_DIR]: [CANARY_FEED_XML, null] }, lm, CUTOFF_MS), [])+ assert.deepEqual(staleFeedBundleKeys(keys, { [CANARY_DIR]: [CANARY_FEED_XML, ''] }, lm, CUTOFF_MS), [])+})++test('staleFeedBundleKeys: missing LastModified metadata keeps the object (fail closed)', () => {+ const keys = canaryKeys()+ for (const unknown of [undefined, NaN, Infinity]) {+ const metadata = Object.fromEntries(keys.map(key => [key, unknown]))+ const doomed = staleFeedBundleKeys(keys, { [CANARY_DIR]: [CANARY_FEED_XML] }, metadata, CUTOFF_MS)+ assert.deepEqual(doomed, [])+ }+})++test('prune-canaries --dry-run via main(): controlled clock, env restored, no DELETEs', async () => {+ const { main } = await import('../scripts/r2-release.mjs')+ // Clock: 2026-09-04, keep-days 14 -> cutoff 2026-08-21.+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-09-04T00:00:00Z'))+ const STABLE_FEED = CANARY_FEED_XML.replace(/0\.27\.2\.9/g, '0.28.0.0').replace(+ 'releases/win32/canary/canary.appinstaller',+ 'releases/win32/stable/stable.appinstaller',+ )+ const bucketKeys = [+ ['releases/tag/v0.27.2-canary.20260801034013/HermesBundled-0.27.2-canary.20260801034013-win-x64.msix', OLD_MS],+ [`${CANARY_DIR}/canary.appinstaller`, OLD_MS],+ [`${CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle`, OLD_MS],+ [`${CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle`, OLD_MS],+ [`${CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle`, FRESH_MS],+ ['releases/win32/stable/stable.appinstaller', OLD_MS],+ ['releases/win32/stable/HermesBundled-0.27.0.0-win.msixbundle', OLD_MS],+ ]+ const BUCKET_XML = `<?xml version="1.0" encoding="UTF-8"?>+<ListBucketResult><IsTruncated>false</IsTruncated>+${bucketKeys.map(([k, t]) => ` <Contents><Key>${k}</Key><LastModified>${new Date(t).toISOString()}</LastModified></Contents>`).join('\n')}+</ListBucketResult>`+ const deletes = []+ const realFetch = globalThis.fetch+ globalThis.fetch = async (url, init = {}) => {+ const u = String(url)+ if (init.method === 'DELETE') {+ deletes.push(u)+ return { ok: true, status: 204, headers: new Map(), text: async () => '' }+ }+ if (u.includes('list-type=2')) return { ok: true, status: 200, headers: new Map(), text: async () => BUCKET_XML }+ if (u.endsWith('/canary.appinstaller')) return { ok: true, status: 200, headers: new Map(), text: async () => CANARY_FEED_XML }+ if (u.endsWith('/stable.appinstaller')) return { ok: true, status: 200, headers: new Map(), text: async () => STABLE_FEED }+ throw new Error(`unexpected fetch ${init.method ?? 'GET'} ${u}`)+ }+ const logs = []+ const origLog = console.log+ const origWarn = console.warn+ console.log = (...a) => logs.push(a.join(' '))+ console.warn = (...a) => logs.push('WARN ' + a.join(' '))+ for (const [k, v] of Object.entries({+ CLOUDFLARE_R2_ACCOUNT_ID: 'abc123',+ CLOUDFLARE_R2_ACCESS_KEY_ID: 'AKIDEXAMPLE',+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',+ CLOUDFLARE_R2_BUCKET: 'hermes-releases',+ })) vi.stubEnv(k, v)+ try {+ await main(['prune-canaries', '--keep-days', '14', '--dry-run'])+ } finally {+ console.log = origLog+ console.warn = origWarn+ globalThis.fetch = realFetch+ vi.unstubAllEnvs()+ vi.useRealTimers()+ }+ // Doomed: the old tag-archive canary + the old UNREFERENCED canary bundle.+ assert.ok(logs.some((l) => l.includes('would delete r2:releases/tag/v0.27.2-canary.20260801034013/')))+ assert.ok(logs.some((l) => l.includes(`would delete r2:${CANARY_DIR}/HermesBundled-0.27.1.12000-win.msixbundle`)))+ // Survivors: referenced bundle (old but referenced), fresh not-yet-pointed+ // bundle (keep-days grace), stable dir (never pruned), pointers.+ for (const keep of [+ `r2:${CANARY_DIR}/HermesBundled-0.27.2.9-win.msixbundle`,+ `r2:${CANARY_DIR}/HermesBundled-0.27.2.99-win.msixbundle`,+ 'r2:releases/win32/stable/HermesBundled-0.27.0.0-win.msixbundle',+ ]) {+ assert.ok(!logs.some((l) => l.includes(`would delete ${keep}`)), `must survive: ${keep}`)+ }+ assert.ok(!logs.some((l) => l.includes('would delete') && l.includes('.appinstaller')))+ assert.deepEqual(deletes, [], 'dry-run must not issue any DELETE')+ // Env restoration: stubEnv values were unstubbed (none pre-existed here).+ assert.equal(process.env.CLOUDFLARE_R2_ACCOUNT_ID, undefined)+})diff --git a/tests/acp/test_edit_approval.py b/tests/acp/test_edit_approval.pyindex 8cdbf82fd2c..01107560362 100644--- a/tests/acp/test_edit_approval.py+++ b/tests/acp/test_edit_approval.py@@ -68,6 +68,43 @@ def test_requester_exception_denies_and_does_not_mutate(tmp_path):assert target.read_text(encoding="utf-8") == "before\n"+def test_approved_existing_file_edit_applies(tmp_path):+ target = tmp_path / "sample.txt"+ target.write_text("before\n", encoding="utf-8")++ set_edit_approval_requester(lambda _proposal: True)++ result = json.loads(+ handle_function_call(+ "write_file",+ {"path": str(target), "content": "after\n"},+ task_id="acp-edit-approve",+ )+ )++ assert "error" not in result+ assert target.read_text(encoding="utf-8") == "after\n"+++def test_rejected_existing_file_edit_denies_with_clean_message(tmp_path):+ target = tmp_path / "sample.txt"+ target.write_text("before\n", encoding="utf-8")++ set_edit_approval_requester(lambda _proposal: False)++ result = json.loads(+ handle_function_call(+ "write_file",+ {"path": str(target), "content": "after\n"},+ task_id="acp-edit-reject",+ )+ )++ assert "denied by ACP client" in result["error"]+ assert "not defined" not in result["error"]+ assert target.read_text(encoding="utf-8") == "before\n"++def test_patch_replace_rejection_does_not_mutate(tmp_path):target = tmp_path / "sample.txt"target.write_text("alpha\nbeta\n", encoding="utf-8")diff --git a/tests/acp_adapter/test_acp_images.py b/tests/acp_adapter/test_acp_images.pyindex 296701c2a04..317649a370c 100644--- a/tests/acp_adapter/test_acp_images.py+++ b/tests/acp_adapter/test_acp_images.py@@ -61,6 +61,14 @@ def test_acp_resource_link_file_is_inlined_as_text(tmp_path):[email protected]("windows")+def test_native_drive_path_and_file_uri_refer_to_same_attachment(tmp_path):+ from acp_adapter.content import _path_from_file_uri+ path = tmp_path / "notes with spaces.md"+ path.write_text("body", encoding="utf-8")+ assert _path_from_file_uri(str(path)) == _path_from_file_uri(path.as_uri()) == path++@pytest.mark.asyncioasync def test_initialize_advertises_image_prompt_capability():response = await HermesACPAgent().initialize()diff --git a/tests/agent/test_aux_progress_streaming.py b/tests/agent/test_aux_progress_streaming.pyindex 6d30f17f0bf..22de72185d0 100644--- a/tests/agent/test_aux_progress_streaming.py+++ b/tests/agent/test_aux_progress_streaming.py@@ -464,7 +464,7 @@ class TestContentBearingProgress:assert touches == [1, 1]- def test_keepalive_chunks_do_not_reset_the_compression_fence(self):+ def test_keepalive_chunks_do_not_reset_the_compression_fence(self, monkeypatch):"""End-to-end bug pin (#96707): content-free frames must not refreshCompressionCommitFence._last_progress.@@ -472,7 +472,10 @@ class TestContentBearingProgress:seconds_since_progress(); before the fix, every keepalive chunk fedthrough _ChatStreamAccumulator ticked the fence, so a stalledsummary stream never hit the inactivity timeout."""+ now = [10.0]+ monkeypatch.setattr("agent.conversation_compression.time.monotonic", lambda: now[0])fence = CompressionCommitFence()+ now[0] = 20.0accumulator = _ChatStreamAccumulator()keepalive = SimpleNamespace(id=None, model=None, choices=[], usage=None)empty_role_chunk = _chunk(content="", reasoning="")diff --git a/tests/agent/test_aux_stream_host_deadline.py b/tests/agent/test_aux_stream_host_deadline.pyindex 924b0766a8f..8d9bd355e40 100644--- a/tests/agent/test_aux_stream_host_deadline.py+++ b/tests/agent/test_aux_stream_host_deadline.py@@ -112,7 +112,9 @@ def test_stream_ceiling_structurally_outlives_the_default_host_ceiling():# ── The fence must publish the deadline it already owns ──────────────────-def test_commit_fence_publishes_its_shared_deadline():+def test_commit_fence_publishes_its_shared_deadline(monkeypatch):+ now = [10.0]+ monkeypatch.setattr("agent.conversation_compression.time.monotonic", lambda: now[0])fence = CompressionCommitFence()assert fence.deadline_monotonic is None@@ -123,7 +125,7 @@ def test_commit_fence_publishes_its_shared_deadline():assert not fence.deadline_exceededfence.set_total_ceiling_seconds(0.001)- time.sleep(0.01)+ now[0] += 1.0assert fence.deadline_exceededassert fence.deadline_monotonic <= time.monotonic()diff --git a/tests/agent/test_codex_aux_timeout_fd_ownership.py b/tests/agent/test_codex_aux_timeout_fd_ownership.pyindex 1758e13e144..64922eae2ad 100644--- a/tests/agent/test_codex_aux_timeout_fd_ownership.py+++ b/tests/agent/test_codex_aux_timeout_fd_ownership.py@@ -71,13 +71,18 @@ class TestCodexAuxiliaryTimeoutFdOwnership:shutdown(); the real close() must land on the owning thread in theadapter's ``finally``."""+ interrupted = threading.Event()def _stalled():- deadline = time.monotonic() + 30.0- while time.monotonic() < deadline:- time.sleep(0.02)- yield SimpleNamespace(type="response.in_progress")+ assert interrupted.wait(10), "watchdog did not interrupt the stalled transport"+ yield SimpleNamespace(type="response.in_progress")adapter, events = _adapter_with_recording_client(_stalled())+ socket = adapter._client._client._transport._pool._connections[0].get_extra_info("socket")+ original_shutdown = socket.shutdown+ def shutdown(how):+ original_shutdown(how)+ interrupted.set()+ socket.shutdown = shutdownowner_tid = threading.get_ident()def _consume(stream, *, model, on_event):diff --git a/tests/agent/test_coding_context.py b/tests/agent/test_coding_context.pyindex 58ed8d9921a..f57ef08675a 100644--- a/tests/agent/test_coding_context.py+++ b/tests/agent/test_coding_context.py@@ -29,6 +29,11 @@ def _git_init(path):(Path(path) / "main.py").write_text("print('hi')\n")for args in (["init", "-q", "-b", "main"],+ # Pin line-ending handling to the repo itself: with a host-global+ # core.autocrlf=true, a just-committed tree can report "1 modified"+ # immediately after init (CRLF round-trip), which poisons the+ # clean-status contract this suite asserts.+ ["config", "core.autocrlf", "false"],["add", "-A"],["commit", "-q", "-m", "init commit"],):diff --git a/tests/agent/test_credential_pool_profile_oauth_fork.py b/tests/agent/test_credential_pool_profile_oauth_fork.pyindex eec0c6c52e6..df28e3ac6d3 100644--- a/tests/agent/test_credential_pool_profile_oauth_fork.py+++ b/tests/agent/test_credential_pool_profile_oauth_fork.py@@ -470,7 +470,21 @@ def _seed_codex_grant(root):(root / "auth.json").write_text(json.dumps(store))-def _shared_profile(fleet, name, *, link):+def _link_same_file(target, alias):+ """Make ``alias`` the SAME store as ``target``: a symlink where the host+ permits one, a hardlink where it does not (Windows without SeCreateSymbolicLink+ privilege raises WinError 1314). Both flavors are one file — the heal contract+ (``_is_same_auth_store``) is ``samefile``/resolved-path equality, not the link+ flavor, so the test exercises the same contract on either host."""+ try:+ alias.symlink_to(target)+ except (OSError, NotImplementedError):+ if alias.is_symlink() or alias.exists():+ alias.unlink()+ os.link(target, alias)+++def _shared_profile(fleet, name, *, link=_link_same_file):"""Profile whose auth.json IS the root store (``link`` makes the alias)."""pdir = _profile(fleet, name)pdir.mkdir(parents=True, exist_ok=True)@@ -491,12 +505,14 @@ def test_heal_skips_profile_auth_json_symlinked_to_the_root_store(fleet):_seed_codex_grant(root)before = (root / "auth.json").read_text()- shared = _shared_profile(fleet, "shared", link=lambda target, alias: alias.symlink_to(target))+ shared = _shared_profile(fleet, "shared")fleet["use"](shared)assert heal_forked_single_use_oauth_grants("openai-codex") is Noneassert (root / "auth.json").read_text() == before- assert (shared / "auth.json").is_symlink()+ # Same-store contract, flavor-independent: whatever link type the host+ # gave us, the alias must be the root store itself, not a copy.+ assert (shared / "auth.json").samefile(root / "auth.json")assert consume_oauth_heal_notices() == []store = json.loads((root / "auth.json").read_text())assert [r["id"] for r in store["credential_pool"]["openai-codex"]] == ["cdx001"]@@ -534,12 +550,13 @@ def test_heal_leaves_an_aliased_anthropic_singleton_alone(fleet):kid = _profile(fleet, "kid")kid.mkdir(parents=True, exist_ok=True)(kid / "auth.json").write_text(json.dumps({"providers": {}, "credential_pool": {}}))- (kid / ".anthropic_oauth.json").symlink_to(root / ".anthropic_oauth.json")+ _link_same_file(root / ".anthropic_oauth.json", kid / ".anthropic_oauth.json")before = (root / ".anthropic_oauth.json").read_text()fleet["use"](kid)assert heal_forked_single_use_oauth_grants("anthropic") is None- assert (kid / ".anthropic_oauth.json").is_symlink()+ # Same-store contract, flavor-independent (hardlink on symlink-hostile hosts).+ assert (kid / ".anthropic_oauth.json").samefile(root / ".anthropic_oauth.json")assert (root / ".anthropic_oauth.json").read_text() == before@@ -550,7 +567,7 @@ def test_heal_same_store_skip_is_memoized_off_the_hot_path(fleet, monkeypatch):root = fleet["root"]_seed_codex_grant(root)- shared = _shared_profile(fleet, "shared", link=lambda target, alias: alias.symlink_to(target))+ shared = _shared_profile(fleet, "shared")fleet["use"](shared)assert auth_mod.heal_forked_single_use_oauth_grants("openai-codex") is Nonediff --git a/tests/agent/test_custom_provider_ca_probes.py b/tests/agent/test_custom_provider_ca_probes.pyindex 1c32edc3fc3..e1ebc40ac80 100644--- a/tests/agent/test_custom_provider_ca_probes.py+++ b/tests/agent/test_custom_provider_ca_probes.py@@ -102,20 +102,21 @@ class TestResolveRequestsVerifyProviderScoped:assert _resolve_requests_verify(_BASE) is Falsedef test_no_base_url_does_not_consult_config(self, clean_env, bundle_file):- """Existing callers pass no base_url — env-only behavior, no config read."""+ """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() == bundle_file+ assert _resolve_requests_verify() is Trueprobe.assert_not_called()- def test_unmatched_base_url_falls_through_to_env(self, clean_env, bundle_file):+ def test_unmatched_base_url_env_ignored_returns_true(self, clean_env, bundle_file):+ """An unmatched base_url and an ambient CA env var both leave trust at the OS store."""clean_env.setenv("REQUESTS_CA_BUNDLE", bundle_file)with patch("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) == bundle_file+ assert _resolve_requests_verify(_BASE) is Truedef test_unmatched_base_url_no_env_returns_true(self, clean_env):with patch(@@ -124,21 +125,24 @@ class TestResolveRequestsVerifyProviderScoped:):assert _resolve_requests_verify(_BASE) is True- def test_provider_ca_missing_file_falls_through_to_env(self, clean_env, bundle_file):- clean_env.setenv("SSL_CERT_FILE", bundle_file)+ def test_provider_ca_missing_file_env_ignored_returns_true(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")with patch("hermes_cli.config.get_compatible_custom_providers",return_value=_providers(_BASE, ssl_ca_cert="/does/not/exist.pem"),):- assert _resolve_requests_verify(_BASE) == bundle_file+ assert _resolve_requests_verify(_BASE) is True- def test_config_lookup_failure_falls_through_to_env(self, clean_env, bundle_file):- clean_env.setenv("SSL_CERT_FILE", bundle_file)+ def test_config_lookup_failure_env_ignored_returns_true(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) == bundle_file+ assert _resolve_requests_verify(_BASE) is Trueclass TestCustomProviderSSLContext:diff --git a/tests/agent/test_estimator_parity_84371.py b/tests/agent/test_estimator_parity_84371.pyindex 3b015646bf3..26f60fc2298 100644--- a/tests/agent/test_estimator_parity_84371.py+++ b/tests/agent/test_estimator_parity_84371.py@@ -328,3 +328,7 @@ class TestNoProgressDeadLoopBreaker:"no_progress must arm the per-session backoff — otherwise ""the dead loop re-fires a full aux summarization every turn")+ # Release the sqlite handle BEFORE the TemporaryDirectory cleanup:+ # on a real Windows host an open sqlite file cannot be unlinked+ # (WinError 32), which would fail teardown even for a green body.+ db.close()diff --git a/tests/agent/test_model_metadata_ssl.py b/tests/agent/test_model_metadata_ssl.pyindex eaa28e46655..8624cfde4ea 100644--- a/tests/agent/test_model_metadata_ssl.py+++ b/tests/agent/test_model_metadata_ssl.py@@ -1,16 +1,19 @@-"""Tests for _resolve_requests_verify() env var precedence.+"""Tests for _resolve_requests_verify() trust-source contract.-Verifies that custom provider `/models` fetches honour the three supported-CA bundle env vars (HERMES_CA_BUNDLE, REQUESTS_CA_BUNDLE, SSL_CERT_FILE)-in the documented priority order, and that non-existent paths are-skipped gracefully rather than breaking the request.+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 filesystem or network I/O required — we use tmp_path to create real-CA bundle stand-in files and monkeypatch env vars.+No network I/O: CA env vars point at tmp_path stand-in files only; the OS+trust store is never written."""-from pathlib import Path+from __future__ import annotations+from pathlib import Pathimport pytest@@ -40,16 +43,18 @@ class TestResolveRequestsVerify:def test_no_env_returns_true(self, clean_env):assert _resolve_requests_verify() is True---- def test_priority_hermes_over_requests(self, clean_env, tmp_path, bundle_file):+ 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))- assert _resolve_requests_verify() == bundle_file---+ 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 Truediff --git a/tests/agent/test_provider_scope_keys.py b/tests/agent/test_provider_scope_keys.pynew file mode 100644index 00000000000..ba4fad03211--- /dev/null+++ b/tests/agent/test_provider_scope_keys.py@@ -0,0 +1,30 @@+"""Equivalent home paths address one provider slot and generation."""+import logging++from agent.provider_registry import ProviderRegistry+from hermes_constants import hermes_home_key+++class Provider:+ name = "sample"+++def test_scoped_reads_and_restore_share_canonical_key(tmp_path, monkeypatch):+ registry = ProviderRegistry(label="sample", provider_cls=Provider, logger=logging.getLogger(__name__))+ home = tmp_path / "Profile"+ home.mkdir()+ raw = str(home / ".." / home.name)+ key = hermes_home_key(home)+ monkeypatch.setenv("HERMES_HOME", str(home))+ global_provider, scoped, replacement = Provider(), Provider(), Provider()+ registry.register(global_provider)+ registry.register(scoped, scope=raw)+ assert registry.get_provider("sample") is scoped+ assert registry.get_provider("sample", scope=key) is scoped+ assert registry.snapshot_registration("sample") is global_provider+ assert registry.snapshot_registration("sample", scope=key) is scoped+ generation = registry.registry_generation(scope=key)+ registry.register(replacement, scope=key)+ assert registry.registry_generation(scope=raw) != generation+ assert registry.restore_registration("sample", replacement, None, scope=raw)+ assert registry.get_provider("sample", scope=key) is global_providerdiff --git a/tests/agent/test_relay_runtime_plugins.py b/tests/agent/test_relay_runtime_plugins.pyindex b8f44c64dec..fd9cb9a97ad 100644--- a/tests/agent/test_relay_runtime_plugins.py+++ b/tests/agent/test_relay_runtime_plugins.py@@ -1082,7 +1082,7 @@ enabled = true[[components.config.atof.sinks]]type = "file"-output_directory = "{project_atof_dir}"+output_directory = "{project_atof_dir.as_posix()}"filename = "events.jsonl"mode = "overwrite"""".strip(),@@ -1105,7 +1105,7 @@ enabled = true[[components.config.atof.sinks]]type = "file"-output_directory = "{selected_atof_dir}"+output_directory = "{selected_atof_dir.as_posix()}"filename = "events.jsonl"mode = "overwrite"""".strip(),diff --git a/tests/agent/test_subdirectory_hints.py b/tests/agent/test_subdirectory_hints.pyindex 296adc25a9b..852a40fd8d8 100644--- a/tests/agent/test_subdirectory_hints.py+++ b/tests/agent/test_subdirectory_hints.py@@ -111,7 +111,7 @@ class TestSubdirectoryHintTracker:result = tracker.check_tool_call("read_file", {"path": str(sub / "file.py")})assert result is not Noneassert "HEAD-MARKER" in result and "TAIL-MARKER" in result- assert "truncated AGENTS.md" in result and "bigdir/AGENTS.md" in result+ assert "truncated AGENTS.md" in result and str(Path("bigdir") / "AGENTS.md") in resultassert len(result) < len(body)assert any("TRUNCATED" in r.message and "AGENTS.md" in r.message for r in caplog.records)diff --git a/tests/ci/test_desktop_cli_entrypoints.py b/tests/ci/test_desktop_cli_entrypoints.pydeleted file mode 100644index 37c2afa105a..00000000000--- a/tests/ci/test_desktop_cli_entrypoints.py+++ /dev/null@@ -1,61 +0,0 @@-"""Structural guards for the bundled payload's CLI entrypoint wiring.--The rust shim (apps/desktop/shim) is gone: win32 payloads mint distlib-launcher exes, POSIX payloads stage $0-relative bash trampolines-(scripts/desktop-cli/, driven by scripts/build-bundled-desktop.mjs step 5b).-The real generators are exercised by apps/desktop/scripts/cli-launchers.test.mjs-(vitest) and tests/scripts/test_desktop_cli_wrapper.py /-test_mint_launchers.py; what a python CI test can still prove is the-STRUCTURE of the wiring, so a regression back to a compiled shim (or an-alias manifest still assuming one exe + argv[0] dispatch) fails loudly-even when the js/py suites aren't run on the lane.-"""--from __future__ import annotations---from pathlib import Path--_REPO = Path(__file__).resolve().parents[2]-_BUILD = _REPO / "scripts" / "build-bundled-desktop.mjs"-_BEFORE_BUILD = _REPO / "apps" / "desktop" / "scripts" / "before-build.mjs"----def test_build_script_no_longer_compiles_a_rust_shim():- text = _BUILD.read_text(encoding="utf-8")- assert "cargo build" not in text.lower(), "the desktop bundle must not need the rust toolchain"- assert "'cargo'" not in text and '"cargo"' not in text- assert "shim-target.txt" not in text, "the sidecar died with the rust shim"---def test_build_script_stages_the_desktop_cli_generators():- text = _BUILD.read_text(encoding="utf-8")- for needle in (- "cli-entrypoints.mjs",- "posixTrampolineScripts",- "renderWinWrapper",- "mint-launchers.py",- "launcher-wrapper.py",- ):- assert needle in text, f"build-bundled-desktop.mjs lost its wiring to {needle}"- # Minting runs on the payload's own store python (its arch IS the- # target arch — distlib picks the launcher stub by minting platform).- assert "pythonEntry" in text and "mint interpreter" in text---def test_before_build_declares_one_alias_extension_per_launcher_exe():- text = _BEFORE_BUILD.read_text(encoding="utf-8")- # The minted exes are three REAL executables; an AppExecutionAlias's- # Executable must name the exact exe that serves the alias, so the- # builder emits one uap5:Extension per launcher, deriving the list from- # cli-entrypoints (no hardcoded, drifting names).- assert "CLI_LAUNCHER_SPECS" in text- assert "Executable=\"${executable(name)}\"" in text- assert '<uap5:ExecutionAlias Alias="${name}.exe" />' in text- # The default IS the full launcher set.- assert "launchers = CLI_LAUNCHER_SPECS.map((s) => s.name)" in text---def test_the_shim_crate_is_gone():- assert not (_REPO / "apps" / "desktop" / "shim").exists(), "apps/desktop/shim must be deleted"diff --git a/tests/ci/test_list_os_marked_tests.py b/tests/ci/test_list_os_marked_tests.pyindex 724fbb2ea36..3e46c8e904e 100644--- a/tests/ci/test_list_os_marked_tests.py+++ b/tests/ci/test_list_os_marked_tests.py@@ -97,6 +97,88 @@ def test_negated_spec_lists_for_that_lane(tmp_path):assert any(p.endswith("test_negated.py") for p in listed)+def test_posix_spec_lists_for_both_posix_lanes_only(tmp_path):+ """``platforms("posix")`` runs on linux+macos hosts, not windows.++ The file must be listed for the macos lane (its tests RUN there);+ under-selecting it would silently drop that coverage.+ """+ _write(+ tmp_path,+ "test_posix.py",+ "import pytest\n\n\[email protected](\"posix\")\ndef test_x():\n pass\n",+ )+ for platform, expected in [("macos", True), ("linux", True), ("windows", False)]:+ result = _run(platform, str(tmp_path))+ listed = result.stdout.split()+ assert any(p.endswith("test_posix.py") for p in listed) is expected, platform+++def test_any_spec_lists_for_every_lane(tmp_path):+ _write(+ tmp_path,+ "test_any.py",+ "import pytest\n\n\[email protected](\"any\")\ndef test_x():\n pass\n",+ )+ for platform in ("linux", "macos", "windows"):+ result = _run(platform, str(tmp_path))+ assert result.returncode == 0, result.stderr+ assert any(p.endswith("test_any.py") for p in result.stdout.split()), platform+++def test_arch_filter_still_lists_the_file(tmp_path):+ """arch= narrows per-test skips, not file selection.++ The lane's machine is not statically known here; over-selecting is+ corrected by the per-test host skip, so an arch-filtered file must+ still be listed for its platform's lane.+ """+ _write(+ tmp_path,+ "test_arch.py",+ 'import pytest\n\n\[email protected]("windows", arch="arm64")\n'+ "def test_x():\n pass\n",+ )+ result = _run("windows", str(tmp_path))+ assert result.returncode == 0, result.stderr+ assert any(p.endswith("test_arch.py") for p in result.stdout.split())+++def test_multiline_and_single_quoted_spec_lists(tmp_path):+ """Real call shapes: multiline decorator args and single-quoted specs."""+ _write(+ tmp_path,+ "test_multiline.py",+ "import pytest\n\n\n"+ '@pytest.mark.platforms(\n "windows",\n arch="arm64",\n)\n'+ "def test_x():\n pass\n",+ )+ _write(+ tmp_path,+ "test_single_quote.py",+ "import pytest\n\n\[email protected]('macos')\ndef test_y():\n pass\n",+ )+ result = _run("windows", str(tmp_path))+ listed = result.stdout.split()+ assert any(p.endswith("test_multiline.py") for p in listed)+ result = _run("macos", str(tmp_path))+ assert any(p.endswith("test_single_quote.py") for p in result.stdout.split())+++def test_negated_exclusive_spec_still_lists_other_lanes(tmp_path):+ """``platforms("not linux")`` runs on macos+windows — list it there."""+ _write(+ tmp_path,+ "test_not_linux.py",+ 'import pytest\n\n\[email protected]("not linux")\ndef test_x():\n pass\n',+ )+ for platform in ("macos", "windows"):+ result = _run(platform, str(tmp_path))+ assert any(p.endswith("test_not_linux.py") for p in result.stdout.split()), (+ platform+ )++def test_unknown_platform_is_rejected(tmp_path):result = _run("amiga", str(tmp_path))assert result.returncode == 2@@ -148,3 +230,22 @@ def test_real_tree_selects_files_for_every_platform():result = _run(platform)assert result.returncode == 0, (platform, result.stderr)assert result.stdout.split(), f"{platform} selected nothing in the real tree"++def test_unparseable_file_is_still_listed(tmp_path):+ """A file the selector cannot parse is conservatively listed so the lane+ fails visibly there rather than silently dropping that coverage."""+ _write(+ tmp_path,+ "test_gated.py",+ 'import pytest\n\n\[email protected]("macos")\ndef test_x():\n pass\n',+ )+ _write(tmp_path, "test_broken.py", "def f(:\n")++ result = _run("macos", str(tmp_path))++ assert result.returncode == 0, result.stderr+ listed = result.stdout.split()+ assert any(p.endswith("test_broken.py") for p in listed)+ assert any(p.endswith("test_gated.py") for p in listed)+ # The problem is still reported, not swallowed.+ assert "test_broken.py" in result.stderrdiff --git a/tests/cli/test_cli_image_command.py b/tests/cli/test_cli_image_command.pyindex 80e00068878..1b42df1b927 100644--- a/tests/cli/test_cli_image_command.py+++ b/tests/cli/test_cli_image_command.py@@ -31,6 +31,18 @@ class TestImageCommand:assert cli_obj._attached_images == [img]+ def test_handle_image_command_bare_shows_usage(self):+ """Bare ``/image`` prints the usage hint through the CLI's real printing+ helpers — this branch raised NameError before the lazy import existed."""+ cli_obj = _make_cli()++ with patch("cli._cprint") as mock_print:+ cli_obj._handle_image_command("/image")++ assert cli_obj._attached_images == []+ rendered = " ".join(str(arg) for call in mock_print.call_args_list for arg in call.args)+ assert "Usage: /image <path>" in rendered+def test_handle_image_command_rejects_non_image_file(self, tmp_path):file_path = tmp_path / "notes.txt"file_path.write_text("hello\n", encoding="utf-8")diff --git a/tests/cli/test_modify_other_keys_aliases.py b/tests/cli/test_modify_other_keys_aliases.pyindex 5b04d1d7dc2..30e626ae8e7 100644--- a/tests/cli/test_modify_other_keys_aliases.py+++ b/tests/cli/test_modify_other_keys_aliases.py@@ -20,6 +20,7 @@ import pytestfrom prompt_toolkit.input.ansi_escape_sequences import ANSI_SEQUENCESfrom prompt_toolkit.input.vt100_parser import Vt100Parserfrom prompt_toolkit.keys import Keys+from prompt_toolkit.output import DummyOutputfrom hermes_cli.pt_input_extras import install_modify_other_keys_aliases@@ -460,7 +461,7 @@ def test_buffer_level_shift_space_no_raw_csi():buf = Buffer()with create_pipe_input() as inp:app = Application(- layout=Layout(HSplit([Window(BufferControl(buf))])), input=inp+ layout=Layout(HSplit([Window(BufferControl(buf))])), input=inp, output=DummyOutput())run_task = asyncio.ensure_future(app.run_async())await asyncio.sleep(0.05)@@ -512,7 +513,7 @@ def test_buffer_level_shift_letter_no_raw_csi():buf = Buffer()with create_pipe_input() as inp:app = Application(- layout=Layout(HSplit([Window(BufferControl(buf))])), input=inp+ layout=Layout(HSplit([Window(BufferControl(buf))])), input=inp, output=DummyOutput())run_task = asyncio.ensure_future(app.run_async())await asyncio.sleep(0.05)diff --git a/tests/cli/test_worktree_pushed_tier.py b/tests/cli/test_worktree_pushed_tier.pyindex c1f49905370..45737fde062 100644--- a/tests/cli/test_worktree_pushed_tier.py+++ b/tests/cli/test_worktree_pushed_tier.py@@ -12,6 +12,7 @@ no network and no mocks.import osimport subprocessimport time+from pathlib import Pathimport pytest@@ -268,12 +269,12 @@ class TestCronWorktreeMaintenance:lambda: [{"workdir": str(repo)}],)repos = sched._worktree_maintenance_repos()- assert str(repo) not in repos+ assert repo not in [Path(p) for p in repos]# Adding .worktrees/ makes it eligible.(repo / ".worktrees").mkdir()repos = sched._worktree_maintenance_repos()- assert str(repo) in repos+ assert repo in [Path(p) for p in repos]def test_maintenance_prunes_via_real_pruner(self, repo_with_bare_origin, monkeypatch):import cron.scheduler as scheddiff --git a/tests/compat/old_updater_surface.json b/tests/compat/old_updater_surface.jsonindex bee0f7a30e7..c097fec115b 100644--- a/tests/compat/old_updater_surface.json+++ b/tests/compat/old_updater_surface.json@@ -4,7 +4,17 @@"mode": "tree","files_analyzed": ["hermes_cli/post_update.py",+ "hermes_cli/runtime_repair.py","hermes_cli/update_cmd.py",+ "hermes_cli/update_cmd_common.py",+ "hermes_cli/update_cmd_config.py",+ "hermes_cli/update_cmd_deps.py",+ "hermes_cli/update_cmd_fleet.py",+ "hermes_cli/update_cmd_git.py",+ "hermes_cli/update_cmd_maint.py",+ "hermes_cli/update_cmd_stash.py",+ "hermes_cli/update_cmd_windows.py",+ "hermes_cli/update_cmd_zip.py","hermes_cli/update_lock.py","pm/__init__.py","pm/cli.py",@@ -21,39 +31,161 @@"bare": ["gateway.status::_get_process_start_time","gateway.status::_pid_exists",+ "gateway.status::get_process_start_time",+ "gateway.status::looks_like_gateway_command_line","gateway.status::terminate_pid",+ "hermes_cli._install_repair::migrate_windows_bin_path","hermes_cli._scan_venv_blockers::_is_pausable_gateway",- "hermes_cli.backup::_foreign_db_holder_pids",+ "hermes_cli._subprocess_compat::pid_is_hermes",+ "hermes_cli._subprocess_compat::windows_hide_flags",+ "hermes_cli.backup::_quick_snapshot_root",+ "hermes_cli.backup::_sibling_profile_homes",+ "hermes_cli.backup::create_pre_update_snapshots_all_profiles",+ "hermes_cli.backup::create_quick_snapshot",+ "hermes_cli.backup::restore_config_model_settings_all_profiles",+ "hermes_cli.backup::restore_config_model_settings_if_rewritten",+ "hermes_cli.backup::restore_cron_jobs_all_profiles",+ "hermes_cli.backup::restore_cron_jobs_if_emptied","hermes_cli.backup::verify_sqlite_integrity",+ "hermes_cli.backup_restore::_foreign_db_holder_pids","hermes_cli.banner::_github_compare_behind","hermes_cli.config::check_config_version","hermes_cli.config::get_config_path","hermes_cli.config::get_env_path",+ "hermes_cli.config::get_hermes_home","hermes_cli.config::get_missing_config_fields","hermes_cli.config::get_missing_env_vars",+ "hermes_cli.config::load_config","hermes_cli.config::migrate_config","hermes_cli.config_migrations::SUPPORT_FLOOR_VERSION","hermes_cli.config_migrations::support_floor_message",+ "hermes_cli.gateway::GATEWAY_LOOP_WEDGED",+ "hermes_cli.gateway::_capture_gateway_argv",+ "hermes_cli.gateway::_ensure_user_systemd_env",+ "hermes_cli.gateway::_escalate_wedged_gateway",+ "hermes_cli.gateway::_find_legacy_hermes_units",+ "hermes_cli.gateway::_get_restart_drain_timeout",+ "hermes_cli.gateway::_get_service_pids","hermes_cli.gateway::_graceful_restart_via_sigusr1",+ "hermes_cli.gateway::_is_pid_ancestor_of_current_process","hermes_cli.gateway::_launchd_kickstart",- "hermes_cli.gateway::_launchd_service_registered","hermes_cli.gateway::_locate_launchd_gateway_service",+ "hermes_cli.gateway::_prepare_profile_gateway_update_restart",+ "hermes_cli.gateway::_request_gateway_self_restart",+ "hermes_cli.gateway::_wait_for_gateway_exit","hermes_cli.gateway::_wait_for_launchd_service_pid",+ "hermes_cli.gateway::find_gateway_pids",+ "hermes_cli.gateway::find_profile_gateway_processes",+ "hermes_cli.gateway::find_windows_gateway_services","hermes_cli.gateway::get_launchd_label","hermes_cli.gateway::get_launchd_plist_path",+ "hermes_cli.gateway::has_legacy_hermes_units","hermes_cli.gateway::is_macos",+ "hermes_cli.gateway::launch_detached_gateway_restart_by_cmdline",+ "hermes_cli.gateway::launch_detached_profile_gateway_restart","hermes_cli.gateway::launchd_gateway_labels_for_install","hermes_cli.gateway::launchd_restart",+ "hermes_cli.gateway::probe_gateway_loop_liveness",+ "hermes_cli.gateway::supports_systemd_services","hermes_cli.gateway::wait_for_launchd_gateway_supervision","hermes_cli.gitlock::clear_stale_git_locks","hermes_cli.gitlock::clear_stale_tmp_packs",+ "hermes_cli.model_catalog::seed_cache_from_checkout",+ "hermes_cli.plugin_compat::compat_report",+ "hermes_cli.plugin_compat::removal_in_effect",+ "hermes_cli.plugin_compat::summary_lines",+ "hermes_cli.process_identity::ledger_entries",+ "hermes_cli.process_identity::spawner_is_dead",+ "hermes_cli.profiles::_PROFILE_ID_RE",+ "hermes_cli.profiles::_get_profiles_root",+ "hermes_cli.profiles::backfill_profile_envs",+ "hermes_cli.profiles::list_profiles",+ "hermes_cli.profiles::seed_profile_skills",+ "hermes_cli.runtime_paths::install_state_dir",+ "hermes_cli.runtime_paths::runtime_facts_path",+ "hermes_cli.runtime_paths::selected_venv",+ "hermes_cli.runtime_paths::site_packages",+ "hermes_cli.runtime_paths::store_root","hermes_cli.sizefmt::format_bytes",+ "hermes_cli.sqlite_runtime::probe_sqlite_runtime",+ "hermes_cli.sqlite_safe_read::LiveConnectionError",+ "hermes_cli.sqlite_safe_read::offline_file_access","hermes_cli.steward::STEWARD_DESKTOP","hermes_cli.steward::read_install_stamp",+ "hermes_cli.tools_config::install_cua_driver","hermes_cli.update_channel::CHANNEL_STABLE",+ "hermes_cli.update_cmd::_UPDATE_CRITICAL_MODULES",+ "hermes_cli.update_cmd::_abort_recovery_is_complete",+ "hermes_cli.update_cmd::_add_upstream_remote",+ "hermes_cli.update_cmd::_branch_head_suffix",+ "hermes_cli.update_cmd::_capture_head_sha",+ "hermes_cli.update_cmd::_check_and_apply_config_migration",+ "hermes_cli.update_cmd::_count_commits_between",+ "hermes_cli.update_cmd::_critical_module_import_failures",+ "hermes_cli.update_cmd::_current_checkout_sha",+ "hermes_cli.update_cmd::_desktop_owns_gateway_lifecycle",+ "hermes_cli.update_cmd::_finish_dashboard_update_cleanup",+ "hermes_cli.update_cmd::_gateway_prompt",+ "hermes_cli.update_cmd::_git_untracked_paths",+ "hermes_cli.update_cmd::_has_upstream_remote",+ "hermes_cli.update_cmd::_locate_real_git",+ "hermes_cli.update_cmd::_m",+ "hermes_cli.update_cmd::_mark_skip_upstream_prompt",+ "hermes_cli.update_cmd::_migrate_sibling_profile_configs",+ "hermes_cli.update_cmd::_no_prompt_git_kwargs",+ "hermes_cli.update_cmd::_path_uid",+ "hermes_cli.update_cmd::_post_update_sqlite_runtime_status",+ "hermes_cli.update_cmd::_print_curator_first_run_notice",+ "hermes_cli.update_cmd::_print_curator_recent_run_notice",+ "hermes_cli.update_cmd::_print_update_summary",+ "hermes_cli.update_cmd::_read_project_version",+ "hermes_cli.update_cmd::_rebuild_desktop_after_update",+ "hermes_cli.update_cmd::_record_update_step",+ "hermes_cli.update_cmd::_recover_gateway_restart_after_abort",+ "hermes_cli.update_cmd::_refuse_gateway_ancestor_tree_kill",+ "hermes_cli.update_cmd::_reload_config_modules",+ "hermes_cli.update_cmd::_reload_process_scan_modules",+ "hermes_cli.update_cmd::_restore_windows_gateway_service",+ "hermes_cli.update_cmd::_restored_python_paths",+ "hermes_cli.update_cmd::_run_config_check_fresh",+ "hermes_cli.update_cmd::_run_migrate_config_fresh",+ "hermes_cli.update_cmd::_run_pending_fleet_restart",+ "hermes_cli.update_cmd::_should_skip_upstream_prompt",+ "hermes_cli.update_cmd::_start_windows_gateway_service",+ "hermes_cli.update_cmd::_stop_windows_gateway_service",+ "hermes_cli.update_cmd::_surviving_pre_update_serve_runtimes",+ "hermes_cli.update_cmd::_update_complete_message",+ "hermes_cli.update_cmd::_update_node_dependencies",+ "hermes_cli.update_cmd::_validate_critical_modules_import",+ "hermes_cli.update_cmd::_validate_python_files_syntax",+ "hermes_cli.update_cmd::_verify_and_restore_state_dbs_post_update",+ "hermes_cli.update_cmd::_warn_stale_serve_runtimes",+ "hermes_cli.update_cmd::_write_gateway_update_exit_code",+ "hermes_cli.update_cmd::_write_lazy_refresh_incomplete_marker",+ "hermes_cli.update_cmd::_write_update_incomplete_marker",+ "hermes_cli.update_cmd::get_default_hermes_root",+ "hermes_cli.update_cmd::get_hermes_home",+ "hermes_cli.update_cmd_config::",+ "hermes_cli.update_cmd_git::_git_run",+ "hermes_cli.update_cmd_maint::_print_bundled_skills_sync_report",+ "hermes_cli.update_cmd_maint::_sweep_bytecode_after_update",+ "hermes_cli.update_inventory::collect_runtime_inventory",+ "hermes_cli.update_inventory::match_runtime_outcomes",+ "hermes_cli.update_inventory::record_plan_in_receipt",+ "hermes_cli.update_inventory::report_unaccounted_runtimes",+ "hermes_cli.update_receipt::",+ "hermes_cli.update_receipt::begin_update_receipt",+ "hermes_cli.update_receipt::collect_fleet_versions",+ "hermes_cli.update_receipt::finalize_update_receipt",+ "hermes_cli.update_receipt::print_fleet_version_matrix",+ "hermes_cli.update_receipt::record_gateway_restart",+ "hermes_cli.update_receipt::record_step","hermes_cli::boot_bootstrap",+ "hermes_cli::gateway_windows","hermes_cli::main",+ "hermes_cli::runtime_paths","hermes_cli::venv_sync",+ "hermes_constants::","hermes_constants::FIRST_PARTY_MODULE_ROOTS","hermes_constants::display_hermes_home","hermes_constants::get_default_hermes_root",@@ -61,102 +193,71 @@"hermes_constants::get_process_hermes_home","hermes_constants::is_wsl","hermes_constants::project_venv_dir",+ "hermes_constants::reset_hermes_home_override",+ "hermes_constants::set_hermes_home_override","hermes_constants::with_hermes_node_path",+ "plugins.memory.honcho.cli::sync_honcho_profiles_quiet","pm.downloader::Download","pm.downloader::Source","pm.downloader::_OPENER",- "pm.ensure::_facts",- "pm.ensure::_store",+ "pm.downloader::gc_protected_names",+ "pm.ensure::_identity",+ "pm.ensure::_installed_location",+ "pm.ensure::_lockfile","pm.ensure::env_for","pm.ensure::lazy_installs_allowed","pm.ensure::sealed","pm.ensure::sync_venv","pm.ensure::uv",+ "pm.features::installed_extras",+ "pm.features::read_features",+ "pm.features::write_features","pm.lock::Facts",+ "pm.package::InstallError","pm.package::machine_matches_binary",+ "pm.packages::uv_cache_dir","pm.packages::uv_env","pm.paths::repo_root",+ "pm.paths::runtime_facts_path",+ "pm.paths::store_root","pm.registry::get_package","pm.store::extract",+ "pm.store::tree_digest",+ "pm.workspace::enabled_member_dirs",+ "pm.workspace::lock_and_sync",+ "pm.workspace::members_stamp","pm::","pm::paths",+ "pm::receipt",+ "tools.browser_tool_install::warm_agent_browser_npx_cache","tools.skills_sync::sync_skills","utils::atomic_json_write"],"guarded_only": ["agent::curator","gateway.control_socket::pause_gateway_for_update",- "gateway.status::looks_like_gateway_command_line",- "hermes_cli._install_repair::migrate_windows_bin_path",+ "hermes_cli._launchers::resolve_store_python","hermes_cli._parser::build_top_level_parser","hermes_cli._subprocess_compat::",- "hermes_cli.backup::_quick_snapshot_root","hermes_cli.backup::create_pre_update_backup",- "hermes_cli.backup::create_pre_update_snapshots_all_profiles",- "hermes_cli.backup::create_quick_snapshot",- "hermes_cli.backup::restore_cron_jobs_all_profiles",- "hermes_cli.backup::restore_cron_jobs_if_emptied","hermes_cli.config::","hermes_cli.config::get_config_value",- "hermes_cli.config::get_hermes_home",- "hermes_cli.config::load_config","hermes_cli.config_defaults::","hermes_cli.config_migrations::","hermes_cli.dashboard_procs::",- "hermes_cli.gateway::GATEWAY_LOOP_WEDGED",- "hermes_cli.gateway::_capture_gateway_argv",- "hermes_cli.gateway::_ensure_user_systemd_env",- "hermes_cli.gateway::_escalate_wedged_gateway",- "hermes_cli.gateway::_find_legacy_hermes_units",- "hermes_cli.gateway::_get_restart_drain_timeout","hermes_cli.gateway::_get_restart_exit_wait_budget",- "hermes_cli.gateway::_get_service_pids",- "hermes_cli.gateway::_prepare_profile_gateway_update_restart",- "hermes_cli.gateway::_wait_for_gateway_exit",- "hermes_cli.gateway::find_gateway_pids",- "hermes_cli.gateway::find_profile_gateway_processes",- "hermes_cli.gateway::find_windows_gateway_services",- "hermes_cli.gateway::has_legacy_hermes_units","hermes_cli.gateway::is_windows","hermes_cli.gateway::kill_gateway_processes",- "hermes_cli.gateway::launch_detached_gateway_restart_by_cmdline",- "hermes_cli.gateway::launch_detached_profile_gateway_restart",- "hermes_cli.gateway::probe_gateway_loop_liveness",- "hermes_cli.gateway::supports_systemd_services",+ "hermes_cli.macos_tcc_anchor::ensure_tcc_anchor","hermes_cli.memory_setup::_install_dependencies",- "hermes_cli.model_catalog::seed_cache_from_checkout","hermes_cli.process_identity::REAPABLE_PURPOSES",- "hermes_cli.process_identity::ledger_entries",- "hermes_cli.process_identity::spawner_is_dead",- "hermes_cli.profiles::_PROFILE_ID_RE",- "hermes_cli.profiles::_get_profiles_root",- "hermes_cli.profiles::backfill_profile_envs",- "hermes_cli.profiles::list_profiles",- "hermes_cli.profiles::seed_profile_skills",- "hermes_cli.tools_config::install_cua_driver","hermes_cli.update_channel::resolve_update_channel",- "hermes_cli.update_inventory::collect_runtime_inventory",- "hermes_cli.update_inventory::match_runtime_outcomes",- "hermes_cli.update_inventory::record_plan_in_receipt",- "hermes_cli.update_inventory::report_unaccounted_runtimes",- "hermes_cli.update_receipt::",- "hermes_cli.update_receipt::begin_update_receipt",- "hermes_cli.update_receipt::collect_fleet_versions",- "hermes_cli.update_receipt::finalize_update_receipt",- "hermes_cli.update_receipt::print_fleet_version_matrix",+ "hermes_cli.update_cmd_windows::_detect_venv_python_processes","hermes_cli.update_receipt::read_latest_receipt",- "hermes_cli.update_receipt::record_gateway_restart",- "hermes_cli.update_receipt::record_step","hermes_cli.version_info::get_code_identity",- "hermes_cli::gateway_windows","hermes_cli::tools_config",- "hermes_constants::",- "hermes_constants::reset_hermes_home_override",- "hermes_constants::set_hermes_home_override",+ "hermes_constants::venv_python_path","hermes_state::SessionDB",- "plugins.memory.honcho.cli::sync_honcho_profiles_quiet",- "pm.extras::",- "tools.browser_tool::warm_agent_browser_npx_cache",- "tools.environments.local::"+ "pm.ensure::enabled_extras"]}diff --git a/tests/conftest.py b/tests/conftest.pyindex d815eb8763b..6e5a648451d 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1010,6 +1010,9 @@ def _ensure_current_event_loop(request):_LIVE_SYSTEM_GUARD_BYPASS_MARK = "live_system_guard_bypass"_REQUIRES_WAL_MARK = "requires_wal"+# Tests may designate a temporary repo to exercise the real guard safely.+_LIVE_GUARD_PROTECTED_GIT_ROOTS = (PROJECT_ROOT,)+def _wal_is_usable() -> bool:"""True when Hermes will actually put a database into WAL mode here.@@ -1384,7 +1387,9 @@ def _live_system_guard(request, monkeypatch):tokens[0]), so ``bash -c "systemctl restart hermes-gateway"``,``sudo systemctl ...``, ``env systemctl ...``, ``setsid systemctl ...``are all caught. ``pkill``/``killall``/``taskkill`` invocations- targeting hermes/python patterns are also blocked.+ targeting hermes/python patterns are also blocked. Bare ``git``+ commands may not mutate a protected checkout. Git writes against+ temporary repositories and read-only Git commands remain allowed."""if request.node.get_closest_marker(_LIVE_SYSTEM_GUARD_BYPASS_MARK):yield@@ -1569,7 +1574,17 @@ def _live_system_guard(request, monkeypatch):return Truereturn False- def _check_subprocess_cmd(name, cmd):+ from tests.git_safety import blocked_git_mutation++ def _check_subprocess_cmd(name, cmd, kwargs=None):+ git_verb = blocked_git_mutation(cmd, kwargs, _LIVE_GUARD_PROTECTED_GIT_ROOTS)+ if git_verb is not None:+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"subprocess.{name}({cmd!r}) — `git {git_verb}` would mutate "+ "the protected checkout. Use a temporary repository or mock "+ "the update boundary; live_system_guard_bypass is for deliberate live tests."+ )if _is_blocked_systemctl(cmd):raise RuntimeError(f"tests/conftest.py live-system guard: blocked "@@ -1624,7 +1639,7 @@ def _live_system_guard(request, monkeypatch):def _wrap_subprocess(name, real):def _guarded(cmd, *args, **kwargs):- _check_subprocess_cmd(name, cmd)+ _check_subprocess_cmd(name, cmd, kwargs)return real(cmd, *args, **kwargs)_guarded.__name__ = f"_guarded_{name}"# Make the wrapper subscriptable like the wrapped callable when@@ -1642,7 +1657,7 @@ def _live_system_guard(request, monkeypatch):class _GuardedPopen(real): # type: ignore[misc, valid-type]def __init__(self, cmd, *args, **kwargs):- _check_subprocess_cmd("Popen", cmd)+ _check_subprocess_cmd("Popen", cmd, kwargs)super().__init__(cmd, *args, **kwargs)_GuardedPopen.__name__ = "Popen"@@ -1686,7 +1701,7 @@ def _live_system_guard(request, monkeypatch):return real_os_system(command)def _guarded_os_popen(cmd, *args, **kwargs):- _check_subprocess_cmd("os.popen", cmd)+ _check_subprocess_cmd("os.popen", cmd, kwargs)return real_os_popen(cmd, *args, **kwargs)monkeypatch.setattr(_os, "system", _guarded_os_system)@@ -1699,7 +1714,7 @@ def _live_system_guard(request, monkeypatch):real_pty_spawn = _pty.spawndef _guarded_pty_spawn(argv, *args, **kwargs):- _check_subprocess_cmd("pty.spawn", argv)+ _check_subprocess_cmd("pty.spawn", argv, kwargs)return real_pty_spawn(argv, *args, **kwargs)monkeypatch.setattr(_pty, "spawn", _guarded_pty_spawn)@@ -1714,12 +1729,12 @@ def _live_system_guard(request, monkeypatch):async def _guarded_async_exec(program, *args, **kwargs):_check_subprocess_cmd(- "asyncio.create_subprocess_exec", [program, *args]+ "asyncio.create_subprocess_exec", [program, *args], kwargs)return await real_async_exec(program, *args, **kwargs)async def _guarded_async_shell(cmd, *args, **kwargs):- _check_subprocess_cmd("asyncio.create_subprocess_shell", cmd)+ _check_subprocess_cmd("asyncio.create_subprocess_shell", cmd, kwargs)return await real_async_shell(cmd, *args, **kwargs)monkeypatch.setattr(_asyncio, "create_subprocess_exec", _guarded_async_exec)diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.pyindex a68260d3d1a..222781d4a08 100644--- a/tests/cron/test_cron_script.py+++ b/tests/cron/test_cron_script.py@@ -224,7 +224,7 @@ class TestRunJobScript:)assert captured["kwargs"]["creationflags"] == expected_flagsenv = captured["kwargs"]["env"]- assert env["VIRTUAL_ENV"] == str(venv)+ assert "VIRTUAL_ENV" not in env # store-python boot uses explicit import pathsassert str(site_packages) in env["PYTHONPATH"]def test_bootstrap_argv_makes_pth_editable_installs_importable(self, cron_env, tmp_path):diff --git a/tests/cron/test_lifecycle_guard_budget.py b/tests/cron/test_lifecycle_guard_budget.pyindex 181461744f8..e63a9f49ae1 100644--- a/tests/cron/test_lifecycle_guard_budget.py+++ b/tests/cron/test_lifecycle_guard_budget.py@@ -11,6 +11,8 @@ deterministic; ``_LifecycleScanBudget`` reads them at construction time.from __future__ import annotationsimport pytest+import shlex+from pathlib import Pathimport cron.lifecycle_guard as lifecycle_guard@@ -82,8 +84,8 @@ def test_unique_path_budget_bounds_reads_and_fails_closed(monkeypatch, tmp_path)for i in range(3):(tmp_path / f"s{i}.sh").write_text("echo ok\n", encoding="utf-8")- two = " && ".join(f"bash {tmp_path}/s{i}.sh" for i in range(2))- three = " && ".join(f"bash {tmp_path}/s{i}.sh" for i in range(3))+ two = " && ".join(f"bash {shlex.quote(str(tmp_path / f's{i}.sh'))}" for i in range(2))+ three = " && ".join(f"bash {shlex.quote(str(tmp_path / f's{i}.sh'))}" for i in range(3))assert guard(two) is Falseassert guard(three) is True@@ -94,7 +96,7 @@ def test_repeated_path_does_not_spend_unique_path_budget(monkeypatch, tmp_path):script = tmp_path / "s.sh"script.write_text("echo ok\n", encoding="utf-8")- assert guard(f"bash {script} && bash {script} && sh {script}") is False+ assert guard(f"bash {shlex.quote(str(script))} && bash {shlex.quote(str(script))} && sh {shlex.quote(str(script))}") is Falsedef test_remote_read_budget_charged_before_remote_read(monkeypatch):@@ -112,7 +114,7 @@ def test_remote_read_budget_charged_before_remote_read(monkeypatch):)is True)- assert reads == ["/remote/a.sh"]+ assert [Path(p) for p in reads] == [Path("/remote/a.sh").resolve()]def test_cumulative_text_budget_bounds_recursive_scan(monkeypatch, tmp_path):@@ -177,7 +179,7 @@ def test_line_budget_fails_closed_before_tokenizing_every_line(return real_shlex(*args, **kwargs)monkeypatch.setattr(lifecycle_guard.shlex, "shlex", counting)- root = f"bash {script}"+ root = f"bash {shlex.quote(str(script))}"assert guard(root) is True# Only the one-line root was tokenized (a handful of lexers across the# direct scans); the 10-line script never was.@@ -229,13 +231,13 @@ def test_default_budget_admits_a_wide_benign_wrapper_graph(tmp_path):child.write_text("echo step && ls -la /tmp\n" * 20, encoding="utf-8")children.append(child)hub = tmp_path / "hub.sh"- hub.write_text("".join(f"bash {c}\n" for c in children), encoding="utf-8")+ hub.write_text("".join(f"bash {shlex.quote(str(c))}\n" for c in children), encoding="utf-8")- assert guard(f"bash {hub}") is False+ assert guard(f"bash {shlex.quote(str(hub))}") is False# ...and a lifecycle command hidden behind the 200 benign scripts is still# found: the budget bounds work, it does not stop the walk early.evil = tmp_path / "evil.sh"evil.write_text("hermes gateway restart\n", encoding="utf-8")- hub.write_text(hub.read_text() + f"bash {evil}\n", encoding="utf-8")- assert guard(f"bash {hub}") is True+ hub.write_text(hub.read_text() + f"bash {shlex.quote(str(evil))}\n", encoding="utf-8")+ assert guard(f"bash {shlex.quote(str(hub))}") is Truediff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.pyindex 68143eb9102..8c65abaec11 100644--- a/tests/cron/test_restart_safe_worker.py+++ b/tests/cron/test_restart_safe_worker.py@@ -77,7 +77,7 @@ def test_genuine_external_worker_crash_is_recovered_unknown(assert "whether side effects ran is unknown" in recovered["error"][email protected]_only[email protected]("linux")def test_restart_safe_gateway_child_fails_closed_without_scope(monkeypatch):import tools.process_registry as process_registry@@ -462,7 +462,7 @@ def test_lost_execution_start_cas_prevents_side_effects(monkeypatch):run.assert_not_called()[email protected]_only[email protected]("linux")@pytest.mark.live_system_guard_bypassdef test_managed_gateway_restart_preserves_active_worker_and_single_side_effect(tmp_path, monkeypatchdiff --git a/tests/desktop/test_appinstaller_check_script.py b/tests/desktop/test_appinstaller_check_script.pynew file mode 100644index 00000000000..1f0e9873cd0--- /dev/null+++ b/tests/desktop/test_appinstaller_check_script.py@@ -0,0 +1,192 @@+"""Tests: apps/desktop/scripts/check-appinstaller-update.py speaks the REAL+pywinrt projection (subprocess-level, stub winrt on PYTHONPATH — no packaged+process, no network, no OS update call).++Root causes pinned here (audit C08):+- ``Package.current`` is a PROPERTY, not a callable.+- ``PackageManager.check_package_update_availability_async`` does not exist;+ the method lives on the Package instance.+- A not-packaged process is identifiable by the package-identity HRESULT+ (0x80073D54); ANY other failure must surface as unknown, never as+ "no update".+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+from pathlib import Path+++HERMES_PYTHON = sys.executable+SCRIPT = (+ Path(__file__).resolve().parents[2]+ / "apps/desktop/scripts/check-appinstaller-update.py"+)++_NO_PACKAGE_IDENTITY_HRESULT = -2147009196 # 0x80073D54+++def _stub_module(*, identity_error: bool, availability: str | None, check_raises: bool) -> str:+ current_body = (+ " exc = OSError('The process has no package identity.')\n"+ f" exc.winerror = {_NO_PACKAGE_IDENTITY_HRESULT}\n"+ " raise exc"+ if identity_error+ else " return _FakePackage()"+ )+ get_body = (+ ' raise RuntimeError("rpc boom")'+ if check_raises+ else " return _AvailabilityResult(self._availability)"+ )+ check_body = (+ ' raise RuntimeError("winrt blew up")'+ if check_raises+ else f" return _AsyncOp({availability!r})"+ )+ return "\n".join(+ [+ "import enum",+ "",+ "class PackageUpdateAvailability(enum.Enum):",+ ' UNKNOWN = "unknown"',+ ' NO_UPDATES = "noUpdates"',+ ' AVAILABLE = "available"',+ ' REQUIRED = "required"',+ ' ERROR = "error"',+ "",+ "class _AvailabilityResult:",+ " def __init__(self, availability):",+ " self.availability = availability",+ "",+ "class _AsyncOp:",+ " def __init__(self, availability):",+ " self._availability = availability",+ "",+ " def get(self):",+ get_body,+ "",+ "class _FakePackage:",+ " def check_update_availability_async(self):",+ check_body,+ "",+ "class _PackageMeta(type):",+ " @property",+ " def current(cls):",+ current_body,+ "",+ "class Package(metaclass=_PackageMeta):",+ " pass",+ "",+ ]+ )+++def _stub_winrt(tmp_path: Path, package_module: str) -> Path:+ """Render a stub winrt tree whose Package comes from ``package_module``.+ PackageManager deliberately has NO check_package_update_availability_async:+ the real projection's shape is part of the contract under test."""+ root = tmp_path / "stub"+ appmodel = root / "winrt/windows/applicationmodel"+ deployment = root / "winrt/windows/management/deployment"+ for d in (appmodel, deployment):+ d.mkdir(parents=True)+ (root / "winrt/__init__.py").write_text("")+ (root / "winrt/windows/__init__.py").write_text("")+ (root / "winrt/windows/management/__init__.py").write_text("")+ (deployment / "__init__.py").write_text("from .deployment import PackageManager\n")+ (deployment / "deployment.py").write_text(+ "class PackageManager:\n"+ " # No check_package_update_availability_async — it does not exist in\n"+ " # the real projection; the method lives on Package instances.\n"+ " pass\n"+ )+ (appmodel / "__init__.py").write_text(package_module)+ return root+++def _run(root: Path) -> tuple[int, dict]:+ env = {"PYTHONPATH": str(root)}+ if os.environ.get("SYSTEMROOT"):+ env["SYSTEMROOT"] = os.environ["SYSTEMROOT"]+ proc = subprocess.run(+ [HERMES_PYTHON, str(SCRIPT)],+ capture_output=True, text=True, timeout=60, env=env,+ )+ return proc.returncode, json.loads(proc.stdout.strip().splitlines()[-1])+++def test_not_packaged_is_reported_as_not_packaged(tmp_path):+ root = _stub_winrt(tmp_path, _stub_module(identity_error=True, availability=None, check_raises=False))+ code, payload = _run(root)+ assert code == 0+ assert payload == {"available": False, "reason": "not-packaged"}+++def test_update_available_exit_2(tmp_path):+ root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="available", check_raises=False))+ code, payload = _run(root)+ assert code == 2+ assert payload["available"] is True+ assert payload["availability"] == "AVAILABLE"+++def test_no_update_exit_0(tmp_path):+ root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="noUpdates", check_raises=False))+ code, payload = _run(root)+ assert code == 0+ assert payload["available"] is False+++def test_unknown_availability_is_not_no_update(tmp_path):+ """UNKNOWN (enum 0) is an unknown, never available:false (C06-09 review)."""+ root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="unknown", check_raises=False))+ code, payload = _run(root)+ assert code == 1+ assert payload["available"] is None+ assert "error" in payload+++def test_error_availability_is_not_no_update(tmp_path):+ """ERROR (enum 4) is an unknown with an extended error, never available:false."""+ root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="error", check_raises=False))+ code, payload = _run(root)+ assert code == 1+ assert payload["available"] is None+ assert "error" in payload+++def test_check_failure_is_unknown_not_no_update(tmp_path):+ root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability=None, check_raises=True))+ code, payload = _run(root)+ assert code == 1+ assert payload["available"] is None+ assert "error" in payload+++def test_unexpected_package_identity_error_is_unknown(tmp_path):+ """A non-identity failure while reading the current package is a real+ error — it must never masquerade as not-packaged (available:false)."""+ module = _stub_module(identity_error=False, availability="available", check_raises=False).replace(+ " return _FakePackage()",+ ' raise OSError(5, "access denied", None, -2147024891)',+ )+ root = _stub_winrt(tmp_path, module)+ code, payload = _run(root)+ assert code == 1+ assert payload["available"] is None+++def test_projection_without_current_property_is_unknown(tmp_path):+ """A projection that does not expose the current-package static must+ degrade to unknown — the checker may not guess an API shape."""+ module = _stub_module(identity_error=False, availability="available", check_raises=False).replace(+ "class Package(metaclass=_PackageMeta):", "class PackageNotProjected(metaclass=_PackageMeta):"+ )+ root = _stub_winrt(tmp_path, module)+ code, payload = _run(root)+ assert code == 1+ assert payload["available"] is Nonediff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.pyindex a52f177d2cf..dd12d747542 100644--- a/tests/gateway/test_buzz_adapter.py+++ b/tests/gateway/test_buzz_adapter.py@@ -616,7 +616,7 @@ class TestCliErrorContract:["x" * 100_000,json.dumps({"error": "relay_error", "message": "x" * 100_000}),- ],+ ], ids=["plain-large", "json-large"],)def test_bounds_untrusted_cli_error_output(self, stderr):msg = _cli_error_message(stderr, 2)@@ -2769,7 +2769,7 @@ class TestInboundMediaLocalisation:assert event.message_type == MessageType.DOCUMENTassert event.media_types == ["application/pdf"]assert len(event.media_urls) == 1- assert "/cache/documents/" in event.media_urls[0]+ assert "/cache/documents/" in Path(event.media_urls[0]).as_posix()@pytest.mark.asyncioasync def test_download_failure_preserves_caption_and_alt_text(diff --git a/tests/gateway/test_feishu.py b/tests/gateway/test_feishu.pyindex 4120b376cfd..7142d77c145 100644--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@ -15,8 +15,18 @@ from unittest.mock import AsyncMock, Mock, patchfrom gateway.platforms.base import ProcessingOutcome-import os as _os-_SYS_ENV = {k: _os.environ[k] for k in ("SYSTEMROOT", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME") if k in _os.environ}+import pytest+_SYS_ENV = {}++[email protected](autouse=True)+def _isolated_adapter_env(monkeypatch, tmp_path):+ # Clear only the adapter settings. Whole-environment replacement discards+ # conftest's sandbox and sends background persistence into the real home.+ for key in tuple(os.environ):+ if key.startswith(("FEISHU_", "LARK_")):+ monkeypatch.delenv(key)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))try:import lark_oapi@@ -188,7 +198,7 @@ class TestFeishuAdapterMessaging(unittest.TestCase):@patch.dict(os.environ, {**_SYS_ENV,"FEISHU_APP_ID": "cli_app","FEISHU_APP_SECRET": "secret_app",- }, clear=True)+ }, clear=False)def test_connect_websocket_sets_channel_ua_tag(self):"""Verify that FeishuWSClient receives extra_ua_tags=["channel"].@@ -245,7 +255,7 @@ class TestFeishuAdapterMessaging(unittest.TestCase):"extra_ua_tags must be ['channel'] to enable group event routing")- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_edit_message_falls_back_to_text_when_post_update_is_rejected(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -371,7 +381,7 @@ def _admits_group(adapter, message, sender_id, chat_id=""):class TestAdapterBehavior(unittest.TestCase):- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_build_event_handler_registers_reaction_and_card_processors(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -453,7 +463,7 @@ class TestAdapterBehavior(unittest.TestCase):],)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_bot_origin_reactions_are_dropped_to_avoid_feedback_loops(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -474,7 +484,7 @@ class TestAdapterBehavior(unittest.TestCase):adapter._on_reaction_event("im.message.reaction.created_v1", data)run_threadsafe.assert_not_called()- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_user_reaction_with_managed_emoji_is_still_routed(self):# Operator-origin filter is enough to prevent feedback loops; we must# not additionally swallow user-origin reactions just because their@@ -532,7 +542,7 @@ class TestAdapterBehavior(unittest.TestCase):adapter.get_chat_info = AsyncMock(return_value={"name": "Test Chat"})return adapter- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_reaction_on_peer_bot_message_is_not_routed(self):# GET im/v1/messages sender for bot messages carries id=app_id; a peer# bot's message has a different app_id than ours, so it must be dropped.@@ -642,7 +652,7 @@ class TestAdapterBehavior(unittest.TestCase):)- @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_GROUP_POLICY": "open"}, clear=True)+ @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_GROUP_POLICY": "open"}, clear=False)def test_group_message_matches_bot_name_when_only_name_available(self):"""Name fallback engages when either side lacks an open_id. When BOTHthe mention and the bot carry open_ids, IDs are authoritative — a@@ -700,7 +710,7 @@ class TestAdapterBehavior(unittest.TestCase):)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_extract_post_message_downloads_embedded_resources(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -737,7 +747,7 @@ class TestAdapterBehavior(unittest.TestCase):)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_extract_audio_message_downloads_and_caches(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -764,7 +774,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertEqual(media_types, ["audio/ogg"])- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_extract_text_message_starting_with_slash_becomes_command(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -802,7 +812,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertEqual(event.message_type.value, "command")self.assertEqual(event.text, "/help test")- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_extract_text_file_injects_content(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -820,7 +830,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertIn("hello from feishu", text)self.assertIn("[Content of", text)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_message_event_submits_to_adapter_loop(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -855,7 +865,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertTrue(submit.called)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_webhook_request_uses_same_message_dispatch_path(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -879,7 +889,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertEqual(response.status, 200)adapter._on_message_event.assert_called_once()- @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_VERIFICATION_TOKEN": "expected-token"}, clear=True)+ @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_VERIFICATION_TOKEN": "expected-token"}, clear=False)def test_url_verification_requires_configured_verification_token(self):"""url_verification must be rejected when token is set but mismatched.@@ -907,7 +917,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertEqual(response.status, 401)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_process_inbound_message_uses_event_sender_identity_only(self):from gateway.config import PlatformConfigfrom gateway.platforms.base import MessageType@@ -960,7 +970,7 @@ class TestAdapterBehavior(unittest.TestCase):**_SYS_ENV,"HERMES_FEISHU_TEXT_BATCH_MAX_MESSAGES": "2",},- clear=True,+ clear=False,)def test_text_batch_flushes_when_message_count_limit_is_hit(self):from gateway.config import PlatformConfig@@ -1005,7 +1015,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertEqual(first.text, "A\nB")self.assertEqual(second.text, "C")- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_media_batch_merges_rapid_photo_messages(self):from gateway.config import PlatformConfigfrom gateway.platforms.base import MessageEvent, MessageType@@ -1195,7 +1205,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertTrue(asyncio.run(second._is_duplicate("om_same")))- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_send_document_reply_uses_thread_flag(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1251,7 +1261,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertTrue(captured["request"].request_body.reply_in_thread)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_send_uses_post_for_every_chunk_of_multi_chunk_markdown(self):"""Regression for #26841: when a long Markdown message is splitacross multiple chunks, every chunk must go out as@@ -1311,7 +1321,7 @@ class TestAdapterBehavior(unittest.TestCase):self.assertEqual(msg_types, ["post", "post"])- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_send_splits_fenced_code_blocks_into_separate_post_rows(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1391,7 +1401,7 @@ class TestHydrateBotIdentity(unittest.TestCase):return FeishuAdapter(PlatformConfig())- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_hydration_populates_open_id_from_bot_info(self):adapter = self._make_adapter()adapter._client = Mock()@@ -1419,7 +1429,7 @@ class TestHydrateBotIdentity(unittest.TestCase):"FEISHU_BOT_OPEN_ID": "ou_env","FEISHU_BOT_NAME": "Env Hermes",},- clear=True,+ clear=False,)def test_hydration_refreshes_env_values_when_bot_info_available(self):adapter = self._make_adapter()@@ -1451,7 +1461,7 @@ class TestPendingInboundQueue(unittest.TestCase):before or during adapter loop transitions must be queued for replayrather than silently dropped."""- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_event_queued_when_loop_not_ready(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1471,7 +1481,7 @@ class TestPendingInboundQueue(unittest.TestCase):# Drain scheduled flag set.self.assertTrue(adapter._pending_drain_scheduled)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_drainer_replays_queued_events_when_loop_becomes_ready(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1526,7 +1536,7 @@ class TestWebhookSecurity(unittest.TestCase):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter- with patch.dict(os.environ, {**_SYS_ENV, "FEISHU_APP_ID": "cli", "FEISHU_APP_SECRET": "sec", "FEISHU_ENCRYPT_KEY": encrypt_key}, clear=True):+ with patch.dict(os.environ, {**_SYS_ENV, "FEISHU_APP_ID": "cli", "FEISHU_APP_SECRET": "sec", "FEISHU_ENCRYPT_KEY": encrypt_key}, clear=False):return FeishuAdapter(PlatformConfig())def test_signature_valid_passes(self):@@ -1581,7 +1591,7 @@ class TestWebhookSecurity(unittest.TestCase):self.assertEqual(content.read_sizes, [_FEISHU_WEBHOOK_MAX_BODY_BYTES + 1])- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_webhook_connect_requires_inbound_auth_secret(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1594,7 +1604,7 @@ class TestWebhookSecurity(unittest.TestCase):)self.assertFalse(asyncio.run(adapter.connect()))- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_webhook_loads_auth_secrets_from_platform_extra(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1618,7 +1628,7 @@ class TestWebhookSecurity(unittest.TestCase):class TestDedupTTL(unittest.TestCase):"""Tests for TTL-aware deduplication."""- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_duplicate_within_ttl_is_rejected(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1630,7 +1640,7 @@ class TestDedupTTL(unittest.TestCase):self.assertTrue(asyncio.run(adapter._is_duplicate("om_dup")))- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_load_tolerates_malformed_timestamp_values(self):"""Regression #13632 — a non-numeric timestamp in the persisteddedup state must not crash adapter startup. The bad key is@@ -1641,7 +1651,7 @@ class TestDedupTTL(unittest.TestCase):from plugins.platforms.feishu.adapter import FeishuAdapterwith tempfile.TemporaryDirectory() as temp_home:- with patch.dict(os.environ, {**_SYS_ENV, "HERMES_HOME": temp_home}, clear=True):+ with patch.dict(os.environ, {**_SYS_ENV, "HERMES_HOME": temp_home}, clear=False):adapter = FeishuAdapter(PlatformConfig())adapter._dedup_state_path.parent.mkdir(parents=True, exist_ok=True)adapter._dedup_state_path.write_text(@@ -1661,7 +1671,7 @@ class TestDedupTTL(unittest.TestCase):assert "om_bad_str" not in adapter._seen_message_idsassert "om_bad_null" not in adapter._seen_message_ids- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, {}, clear=False)def test_persist_on_new_message_runs_off_event_loop_thread(self):"""atomic_json_write() calls os.fsync(), which blocks until the writereaches stable storage. _is_duplicate() runs on the event loop for@@ -1687,7 +1697,7 @@ class TestDedupTTL(unittest.TestCase):self.assertTrue(write_threads)self.assertTrue(all(tid != loop_thread for tid in write_threads))- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, {}, clear=False)def test_concurrent_dedup_persists_land_in_order(self):"""Two in-flight _is_duplicate() calls (two chats) must not let anolder seen-ids snapshot overwrite a newer one on disk."""@@ -1721,7 +1731,7 @@ class TestGroupMentionAtAll(unittest.TestCase):"""Tests for @_all (Feishu @everyone) group mention routing."""- @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_GROUP_POLICY": "allowlist", "FEISHU_ALLOWED_USERS": "ou_allowed"}, clear=True)+ @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_GROUP_POLICY": "allowlist", "FEISHU_ALLOWED_USERS": "ou_allowed"}, clear=False)def test_at_all_still_requires_policy_gate(self):"""@_all bypasses mention gating but NOT the allowlist policy."""from gateway.config import PlatformConfig@@ -1742,7 +1752,7 @@ class TestSenderNameResolution(unittest.TestCase):"""Tests for _resolve_sender_name_from_api (contact API + cache)."""- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_returns_cached_name_within_ttl(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1754,7 +1764,7 @@ class TestSenderNameResolution(unittest.TestCase):result = asyncio.run(adapter._resolve_sender_name_from_api("ou_cached"))self.assertEqual(result, "Alice")- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_fetches_and_caches_name_from_api(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1811,7 +1821,7 @@ class TestBotNameResolution(unittest.TestCase):adapter._client = SimpleNamespace(request=_fake_request)return adapter, calls- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_returns_cached_bot_name_without_api_call(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@ -1824,7 +1834,7 @@ class TestBotNameResolution(unittest.TestCase):result = asyncio.run(adapter._resolve_sender_name_from_api("ou_peer", is_bot=True))self.assertEqual(result, "Peer Bot")- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_fetches_and_caches_bot_name(self):adapter, calls = self._build_adapter_with_bots({"ou_peer": "Peer Bot"})@@ -1910,7 +1920,7 @@ class TestProcessingReactions(unittest.TestCase):return patch("plugins.platforms.feishu.adapter.asyncio.to_thread", side_effect=_direct)# ------------------------------------------------------------------ start- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_start_adds_typing_and_caches_reaction_id(self):adapter, tracker = self._build_adapter(next_reaction_id="r_typing")with self._patch_to_thread():@@ -1920,7 +1930,7 @@ class TestProcessingReactions(unittest.TestCase):# --------------------------------------------------------------- complete- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_success_removes_typing_and_adds_nothing(self):adapter, tracker = self._build_adapter(next_reaction_id="r_typing")with self._patch_to_thread():@@ -1932,7 +1942,7 @@ class TestProcessingReactions(unittest.TestCase):self.assertEqual(tracker.delete_calls, ["r_typing"])self.assertNotIn("om_msg", adapter._pending_processing_reactions)- @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_failure_removes_typing_then_adds_cross_mark(self):adapter, tracker = self._build_adapter(next_reaction_id="r_typing")with self._patch_to_thread():@@ -1945,7 +1955,7 @@ class TestProcessingReactions(unittest.TestCase):# ------------------------- delete failure: don't stack badges ------------ @patch.dict(os.environ, _SYS_ENV, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_delete_failure_on_failure_outcome_skips_cross_mark(self):# Removing Typing is best-effort — but if it fails, we must NOT# additionally add CrossMark, or the UI would show two contradictorydiff --git a/tests/gateway/test_hosted_room_links.py b/tests/gateway/test_hosted_room_links.pyindex 7f834641fef..d9ae4fd2d84 100644--- a/tests/gateway/test_hosted_room_links.py+++ b/tests/gateway/test_hosted_room_links.py@@ -3,6 +3,7 @@from __future__ import annotationsimport stat+import pytestfrom concurrent.futures import ThreadPoolExecutorfrom gateway.hosted_room_links import (@@ -35,7 +36,6 @@ def test_room_link_store_is_private_transactional_and_upserted(tmp_path):trace_id="trace-1",)save_room_link(path, first)- assert stat.S_IMODE(path.stat().st_mode) == 0o600assert load_room_links(path) == (first,)replacement = make_stored_link(@@ -52,6 +52,17 @@ def test_room_link_store_is_private_transactional_and_upserted(tmp_path):assert load_room_links(path) == (replacement,)[email protected]("posix")+def test_room_link_store_has_owner_only_mode(tmp_path):+ path = tmp_path / "state.db"+ save_room_link(path, make_stored_link(+ room_id="room", member_id="member", target_url="https://peer.example.test",+ target_profile="default", grant="grant", catalog=_catalog(),+ cancellation_scope_id="cancel", trace_id="trace",+ ))+ assert stat.S_IMODE(path.stat().st_mode) == 0o600++def test_room_link_store_keeps_distinct_room_member_routes(tmp_path):path = tmp_path / "state.db"for member in ("member-a", "member-b"):diff --git a/tests/gateway/test_hosted_room_peer.py b/tests/gateway/test_hosted_room_peer.pyindex 8b4f6c160d0..63daf1cc632 100644--- a/tests/gateway/test_hosted_room_peer.py+++ b/tests/gateway/test_hosted_room_peer.py@@ -49,11 +49,17 @@ def test_gateway_room_grant_secret_is_private_persistent_and_not_an_api_key(secret_path = home / ".room-link-grant-secret"assert first == secondassert len(first) == 32- assert stat.S_IMODE(secret_path.stat().st_mode) == 0o600assert secret_path.read_bytes() != firstassert first != derive_room_grant_secret("gateway-api-key-1234567890")[email protected]("posix")+def test_gateway_room_grant_secret_has_owner_only_mode(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ gateway_room_grant_secret()+ assert stat.S_IMODE((tmp_path / ".room-link-grant-secret").stat().st_mode) == 0o600++def test_gateway_room_grant_secret_is_atomic_across_concurrent_workers(tmp_path, monkeypatch):diff --git a/tests/gateway/test_matrix_deps_rebind.py b/tests/gateway/test_matrix_deps_rebind.pynew file mode 100644index 00000000000..8791255438b--- /dev/null+++ b/tests/gateway/test_matrix_deps_rebind.py@@ -0,0 +1,96 @@+"""Regression: ensure_matrix_deps() fresh-dependency rebind must not NameError.++sdk-bindings-review.md #43: ``_import()`` referenced ``PaginationDirection`` /+``SyncToken`` that were never imported, and ``pm.extras.ensure_and_bind`` catches+only ImportError — so a fresh install (missing packages) crashed adapter creation+instead of rebinding the type globals or returning False with the install hint.++Tests run through the real ``ensure_and_bind`` boundary with the install seam+(``pm.extras.ensure_import``) no-op'd — no network, no live Matrix.+"""+import sys+import types++import pytest+from unittest.mock import patch++import pm.extras as pm_extras+from plugins.platforms.matrix import adapter as matrix_adapter+++def _fake_mautrix_types():+ """Minimal mautrix.types with the 8 names the adapter imports/binds."""+ mod = types.ModuleType("mautrix.types")++ class EventType:+ ROOM_MESSAGE = "m.room.message"+ REACTION = "m.reaction"++ class UserID(str):+ pass++ class RoomID(str):+ pass++ class EventID(str):+ pass++ class ContentURI(str):+ pass++ class RoomCreatePreset:+ PRIVATE = "private_chat"++ class PresenceState:+ ONLINE = "online"++ class TrustState:+ UNVERIFIED = 0++ mod.EventType = EventType+ mod.UserID = UserID+ mod.RoomID = RoomID+ mod.EventID = EventID+ mod.ContentURI = ContentURI+ mod.RoomCreatePreset = RoomCreatePreset+ mod.PresenceState = PresenceState+ mod.TrustState = TrustState+ return mod+++def fresh_dependency_boundary(monkeypatch):+ """Simulate a fresh install: ``missing()`` reports a gap, the install is a+ no-op success, and ``from mautrix.types import ...`` resolves against a fake."""+ monkeypatch.setattr(pm_extras, "missing", lambda extra: ("asyncpg",))+ monkeypatch.setattr(pm_extras, "ensure_import", lambda *a, **kw: None)+ monkeypatch.delenv("MATRIX_E2EE_MODE", raising=False)+ monkeypatch.delenv("MATRIX_ENCRYPTION", raising=False)+ # ensure_and_bind writes module globals; isolate even successful rebinding.+ for name in ("EventType", "UserID", "RoomID", "EventID", "ContentURI", "RoomCreatePreset", "PresenceState", "TrustState"):+ monkeypatch.setattr(matrix_adapter, name, getattr(matrix_adapter, name))+ fake_types = _fake_mautrix_types()+ mautrix = types.ModuleType("mautrix")+ mautrix.types = fake_types+ with patch.dict(sys.modules, {"mautrix": mautrix, "mautrix.types": fake_types}):+ yield fake_types+++def test_fresh_install_rebinds_type_globals_without_nameerror(fresh_dependency_boundary):+ assert matrix_adapter.ensure_matrix_deps() is True+ # The rebind actually landed on the adapter module globals.+ assert matrix_adapter.EventType is fresh_dependency_boundary.EventType+ assert matrix_adapter.UserID is fresh_dependency_boundary.UserID+ assert matrix_adapter.TrustState is fresh_dependency_boundary.TrustState+++def test_failed_install_returns_false_with_hint_and_never_raises(+ fresh_dependency_boundary, caplog+):+ # Same fresh state but the post-install import genuinely fails (no mautrix):+ # must return False with the install hint — and, per the bug class, must not+ # leak anything other than ImportError out of ensure_and_bind.+ with patch.dict(sys.modules, {"mautrix": None, "mautrix.types": None}):+ with caplog.at_level("WARNING", logger="plugins.platforms.matrix.adapter"):+ assert matrix_adapter.ensure_matrix_deps() is False+ assert any("required packages not installed" in r.message for r in caplog.records)diff --git a/tests/gateway/test_multiplex_mcp_discovery.py b/tests/gateway/test_multiplex_mcp_discovery.pyindex ba586ae3f44..d5f03912c51 100644--- a/tests/gateway/test_multiplex_mcp_discovery.py+++ b/tests/gateway/test_multiplex_mcp_discovery.py@@ -117,7 +117,8 @@ def test_deregister_scope_kwarg_targets_overlay_and_keeps_plugin_confinement() -assert reg.snapshot_registration("mcp__s__t", scope="/home/p1") is None# A plugin module may not name another profile's overlay.- reg._plugin_module_scopes["hermes_plugins.p"] = {"/home/p1"}+ from hermes_constants import hermes_home_key+ reg._plugin_module_scopes["hermes_plugins.p"] = {hermes_home_key("/home/p1")}reg._caller_module = staticmethod(lambda: "hermes_plugins.p")with pytest.raises(PermissionError):reg.deregister("anything", scope="/home/p2")diff --git a/tests/gateway/test_session_db_replaced_fallback.py b/tests/gateway/test_session_db_replaced_fallback.pyindex 21c97006667..f4980c10b04 100644--- a/tests/gateway/test_session_db_replaced_fallback.py+++ b/tests/gateway/test_session_db_replaced_fallback.py@@ -27,6 +27,7 @@ def _assert_diverted(tmp_path, sid, needle):assert needle in jsonl.read_text(encoding="utf-8")[email protected]("posix")def test_replaced_state_db_diverts_pending_without_fts_rebuild(tmp_path, monkeypatch):import hermes_statediff --git a/tests/gateway/test_shutdown_watchdog.py b/tests/gateway/test_shutdown_watchdog.pyindex ec0e93e5c31..409f6dacc17 100644--- a/tests/gateway/test_shutdown_watchdog.py+++ b/tests/gateway/test_shutdown_watchdog.py@@ -123,25 +123,13 @@ def short_home():shutil.rmtree(path, ignore_errors=True)[email protected]("windows")@pytest.mark.asyncioasync def test_loop_tick_witness_arms_over_tcp_on_windows(short_home, caplog, monkeypatch):"""Non-POSIX never touches AF_UNIX; the witness arms over TCP loopback."""tmp_path = short_home- # Pretend the platform is Windows as seen from the module under test.- # A plain monkeypatch of the global os.name would flip pathlib.Path- # dispatch (Path.__new__ reads os.name at runtime) and crash pytest's- # own tmp-dir machinery, so swap the module's `os` binding for a proxy- # whose `.name` is "nt" and which delegates everything else to real os.- class _WindowsOsProxy:- name = "nt"-- def __getattr__(self, item):- return getattr(os, item)-- monkeypatch.setattr(shutdown_watchdog_module, "os", _WindowsOsProxy())-start_unix_server_calls = []def _forbid_start_unix_server(*args, **kwargs):@@ -151,7 +139,7 @@ async def test_loop_tick_witness_arms_over_tcp_on_windows(with patch.object(shutdown_watchdog_module.asyncio,"start_unix_server",- side_effect=_forbid_start_unix_server,+ side_effect=_forbid_start_unix_server, create=True,), caplog.at_level(logging.DEBUG, logger="gateway.shutdown_watchdog"):payload = await _run_heartbeat_until_payload(tmp_path)@@ -171,6 +159,7 @@ async def test_loop_tick_witness_arms_over_tcp_on_windows(assert not list(tmp_path.glob("**/gateway.loop-tick.*.sock"))[email protected]("posix")@pytest.mark.asyncioasync def test_loop_tick_witness_arms_on_posix(short_home):payload = await _run_heartbeat_until_payload(short_home)diff --git a/tests/gateway/test_status_command.py b/tests/gateway/test_status_command.pyindex 5f2016e8892..eed202ed708 100644--- a/tests/gateway/test_status_command.py+++ b/tests/gateway/test_status_command.py@@ -460,7 +460,7 @@ async def test_profile_command_reports_source_stamped_profile(monkeypatch, tmp_p# /profile reports the home via display_hermes_home(), which collapses a# home-relative path to "~/…" (Windows tmp paths live under USERPROFILE).try:- expected_home = "~/" + str(profile_home.relative_to(Path.home()))+ expected_home = "~/" + profile_home.relative_to(Path.home()).as_posix()except ValueError:expected_home = str(profile_home)assert f"**Home:** `{expected_home}`" in resultdiff --git a/tests/gateway/test_telegram_media_read_timeout.py b/tests/gateway/test_telegram_media_read_timeout.pyindex 017245a6d8a..1f26b88aba3 100644--- a/tests/gateway/test_telegram_media_read_timeout.py+++ b/tests/gateway/test_telegram_media_read_timeout.py@@ -24,7 +24,8 @@ from plugins.platforms.telegram.adapter import TelegramAdapter # noqa: E402@pytest.fixture-def adapter():+def adapter(monkeypatch):+ monkeypatch.setattr("tools.url_safety.is_safe_url", lambda *a, **k: True)a = TelegramAdapter(PlatformConfig(enabled=True, token="fake-token"))a._bot = MagicMock()a._metadata_thread_id = lambda metadata: Nonediff --git a/tests/gateway/test_voice_command.py b/tests/gateway/test_voice_command.pyindex beb06d35e80..7d864633f0f 100644--- a/tests/gateway/test_voice_command.py+++ b/tests/gateway/test_voice_command.py@@ -914,7 +914,7 @@ class TestDiscordVoiceChannelMethods:with patch("plugins.platforms.discord.adapter.VoiceReceiver.pcm_to_wav"), \patch("tools.transcription_tools.transcribe_audio",return_value={"success": True, "transcript": "Hello"}), \- patch("tools.voice_mode.is_whisper_hallucination", return_value=False):+ patch("tools.voice_mode_transcript.is_whisper_hallucination", return_value=False):await adapter._process_voice_input(111, 42, pcm_data)callback.assert_called_once_with(guild_id=111, user_id=42, transcript="Hello")diff --git a/tests/gateway/test_windows_service_frontend.py b/tests/gateway/test_windows_service_frontend.pydeleted file mode 100644index 400cc6051b5..00000000000--- a/tests/gateway/test_windows_service_frontend.py+++ /dev/null@@ -1,81 +0,0 @@-"""Tests: the Windows SCM service frontend (gateway/windows_service.py).--Hermetic — pywin32 pieces are probed/stubbed, the child spawn is faked,-the planned-stop marker write is asserted by name. The frontend's-CONTRACTS are what's tested here; the SCM protocol itself is pywin32's-and gets its live proof in the wine2e lane (plan Task 1/W5.6).-"""--from __future__ import annotations--import sys-from unittest.mock import patch--import pytest--import gateway.windows_service as ws---def test_service_name_matches_manifest_key():- # The manifest names this exact service; the CLI verbs key off it too.- assert ws.SERVICE_NAME == "HermesGateway"---def test_drain_window_default_below_scm_window():- # The frontend's own deadline must sit BELOW the SCM's- # WaitToKillServiceTimeout with margin — else the SCM force-kill- # races the graceful drain (Task 3's whole contract).- window = ws._drain_window_s()- assert window <= ws._SCM_WINDOW_FALLBACK_S - ws._STOP_MARGIN_S---def test_drain_window_env_override_capped():- with patch.dict(ws.os.environ, {"HERMES_RESTART_DRAIN_TIMEOUT": "600"}):- assert ws._drain_window_s() == float(ws._SCM_WINDOW_FALLBACK_S - ws._STOP_MARGIN_S)---def test_drain_window_env_override_respected_when_smaller():- with patch.dict(ws.os.environ, {"HERMES_RESTART_DRAIN_TIMEOUT": "8"}):- assert ws._drain_window_s() == 8.0---def test_stop_marker_write_uses_planned_stop_path(monkeypatch):- """The graceful nudge MUST be the existing planned-stop marker — the- same path `hermes gateway stop` uses; no second stop protocol."""- calls = {}-- import gateway.status as status_mod-- monkeypatch.setattr(- status_mod, "write_planned_stop_marker", lambda pid: calls.setdefault("pid", pid)- )- ws._write_stop_marker(4242)- assert calls == {"pid": 4242}---def test_stop_marker_failure_falls_back_to_terminate(monkeypatch):- """Marker machinery unavailable (partial payload): terminate the pid- rather than leave an unstoppable child."""- terminated = {}-- def boom(pid):- raise RuntimeError("no gateway.status here")-- import gateway.status as status_mod-- monkeypatch.setattr(status_mod, "write_planned_stop_marker", boom)- monkeypatch.setattr(ws.os, "kill", lambda pid, sig: terminated.update(pid=pid, sig=sig))- ws._write_stop_marker(99)- assert terminated == {"pid": 99, "sig": 15}--[email protected]("windows")-def test_no_pywin32_means_friendly_error(tmp_path, capfd):- """A user running --service BY HAND (not via SCM): pywin32 is present- but Initialize/dispatcher refuse without the SCM — the frontend must- print guidance, never hang. (Simulated: ImportError shape.)"""- with patch.dict(sys.modules, {"win32serviceutil": None, "servicemanager": None}):- rc = ws.run_as_service()- assert rc == 2- out = capfd.readouterr().err- assert "foreground gateway run" in outdiff --git a/tests/git_safety.py b/tests/git_safety.pynew file mode 100644index 00000000000..9ef2ae670f9--- /dev/null+++ b/tests/git_safety.py@@ -0,0 +1,90 @@+"""Classify accidental Git mutations before tests can touch their checkout."""+import os+import shlex+from pathlib import Path++_WRAPPERS = {"env", "nohup", "setsid", "timeout", "sudo", "xargs", "nice", "ionice", "stdbuf", "flock"}++# Guard accidental checkout writes by update tests, not arbitrary shell code.+_MUTATIONS = {+ "pull", "reset", "stash", "checkout", "switch", "restore",+ "clean", "rebase", "merge", "cherry-pick", "revert", "apply", "am",+}+_TARGET_OPTIONS = {"--git-dir", "--work-tree"}+_VALUE_OPTIONS = _TARGET_OPTIONS | {"-C", "-c", "--namespace", "--super-prefix"}++def _command_name(token):+ return str(token).replace("\\", "/").rsplit("/", 1)[-1].lower().removesuffix(".exe")++def _git_argv_tail(cmd):+ if isinstance(cmd, (list, tuple)):+ tokens = [os.fsdecode(t) for t in cmd]+ else:+ try:+ tokens = shlex.split(os.fsdecode(cmd), posix=os.name != "nt")+ except ValueError:+ return None+ if os.name == "nt":+ tokens = [t[1:-1] if len(t) >= 2 and t[0] == t[-1] and t[0] in "\"'" else t for t in tokens]+ if not tokens:+ return None+ head = _command_name(tokens[0])+ if head == "git":+ return tokens[1:]+ if head in {"sh", "bash", "zsh", "dash", "cmd", "powershell", "pwsh"}:+ for index, token in enumerate(tokens[1:], 1):+ if token.lower() in {"-c", "-lc", "/c", "-command"} and index + 1 < len(tokens):+ return _git_argv_tail(tokens[index + 1])+ return None+ if head in _WRAPPERS:+ for index, token in enumerate(tokens[1:], 1):+ if _command_name(token) == "git":+ return tokens[index + 1:]+ return None++def _git_verb_and_targets(tail, kwargs):+ cwd = Path(kwargs.get("cwd") or os.getcwd())+ env = kwargs.get("env")+ if env is None:+ env = os.environ+ explicit = {key: env[value] for key, value in+ (("--git-dir", "GIT_DIR"), ("--work-tree", "GIT_WORK_TREE")) if env.get(value)}+ index = 0+ while index < len(tail):+ token = tail[index]+ index += 1+ if not token.startswith("-"):+ targets = [cwd, *(cwd / value for value in explicit.values())]+ return token, targets, tail[index:]+ name, separator, value = token.partition("=")+ if token.startswith("-C") and token != "-C":+ name, value, separator = "-C", token[2:], "="+ if name in _VALUE_OPTIONS:+ if not separator:+ if index == len(tail):+ break+ value = tail[index]+ index += 1+ if name == "-C":+ cwd = cwd / value+ elif name in _TARGET_OPTIONS:+ explicit[name] = value+ return None, [], []++def blocked_git_mutation(cmd, kwargs, protected_roots):+ tail = _git_argv_tail(cmd)+ if tail is None:+ return None+ verb, targets, after = _git_verb_and_targets(tail, kwargs or {})+ if verb not in _MUTATIONS:+ return None+ if verb == "stash" and after and after[0] in {"list", "show"}:+ return None+ for target in targets:+ try:+ resolved = target.resolve()+ if any(resolved.is_relative_to(Path(root).resolve()) for root in protected_roots):+ return verb+ except (OSError, ValueError):+ return verb+ return Nonediff --git a/tests/hermes_cli/test_apply_profile_override.py b/tests/hermes_cli/test_apply_profile_override.pyindex 90837cf9406..a626822e0c1 100644--- a/tests/hermes_cli/test_apply_profile_override.py+++ b/tests/hermes_cli/test_apply_profile_override.py@@ -15,6 +15,12 @@ import osimport sysfrom pathlib import Pathfrom types import SimpleNamespace+import pytest++[email protected](autouse=True)+def _platform_home(tmp_path, monkeypatch):+ monkeypatch.setattr("hermes_constants._get_platform_default_hermes_home", lambda: tmp_path / ".hermes")def _run_apply_profile_override(@@ -99,6 +105,7 @@ class TestApplyProfileOverrideHermesHomeGuard:)+ @pytest.mark.platforms("posix")def test_sudo_explicit_profile_resolves_invoking_users_profile(self, tmp_path, monkeypatch):"""sudo elias ... should resolve `-p elias` under SUDO_USER, not root."""root_home = tmp_path / "root"diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex 1fc00723cb2..da621a8f1b2 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -384,7 +384,7 @@ class TestValidateBackupZip:def test_state_db_passes(self, tmp_path):"""A zip containing state.db is accepted as a valid Hermes backup."""- from hermes_cli.backup import _validate_backup_zip+ from hermes_cli.backup_restore import _validate_backup_zipzip_path = tmp_path / "backup.zip"self._make_zip(zip_path, ["state.db", "sessions/abc.json"])with zipfile.ZipFile(zip_path, "r") as zf:@@ -416,6 +416,11 @@ class TestImport:hermes_home.mkdir()monkeypatch.setenv("HERMES_HOME", str(hermes_home))monkeypatch.setattr(Path, "home", lambda: tmp_path)+ # Windows: the native default home is %LOCALAPPDATA%\hermes, not+ # ~\.hermes. Without redirecting LOCALAPPDATA the non-default-home+ # guard below sees the developer's real install and (correctly)+ # declines the auto-install, failing the test on Windows only.+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "AppData" / "Local"))calls = []monkeypatch.setattr(@@ -649,7 +654,7 @@ class TestValidation:def test_validate_with_config(self):"""Zip with config.yaml passes validation."""import io- from hermes_cli.backup import _validate_backup_zip+ from hermes_cli.backup_restore import _validate_backup_zipbuf = io.BytesIO()with zipfile.ZipFile(buf, "w") as zf:@@ -664,7 +669,7 @@ class TestValidation:def test_detect_prefix_only_dirs(self):"""Prefix detection returns empty for zip with only directory entries."""import io- from hermes_cli.backup import _detect_prefix+ from hermes_cli.backup_restore import _detect_prefixbuf = io.BytesIO()with zipfile.ZipFile(buf, "w") as zf:@@ -1799,7 +1804,8 @@ class TestPreMigrationBackup:def test_restorable_with_hermes_import(self, hermes_home, tmp_path):"""The zip produced by pre-migration backup must be a valid Hermesbackup — `hermes import` should accept it."""- from hermes_cli.backup import create_pre_migration_backup, _validate_backup_zip+ from hermes_cli.backup import create_pre_migration_backup+ from hermes_cli.backup_restore import _validate_backup_zipout = create_pre_migration_backup(hermes_home=hermes_home)assert out is not Nonewith zipfile.ZipFile(out) as zf:@@ -2361,9 +2367,12 @@ class TestImportLiveSessionDatabase:):"""A refused live-safe restore is a warning, not a counted success."""import hermes_cli.backup as backup_mod+ # _import_db_member (the run_import .db publish path) lives in+ # hermes_cli.backup_restore and resolves _safe_restore_db there.+ import hermes_cli.backup_restore as backup_restore_modhome, live_db, zip_path = self._prepare(tmp_path, monkeypatch)- monkeypatch.setattr(backup_mod, "_safe_restore_db", lambda src, dst: False)+ monkeypatch.setattr(backup_restore_mod, "_safe_restore_db", lambda src, dst: False)backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True))diff --git a/tests/hermes_cli/test_boot_bootstrap.py b/tests/hermes_cli/test_boot_bootstrap.pyindex 966ce1d450b..b7f0cb0b8bd 100644--- a/tests/hermes_cli/test_boot_bootstrap.py+++ b/tests/hermes_cli/test_boot_bootstrap.py@@ -9,6 +9,7 @@ import jsonimport osimport shutilimport subprocess+import sysimport timefrom pathlib import Path@@ -261,26 +262,8 @@ def fake_steps(monkeypatch):from hermes_cli import post_update- monkeypatch.setattr(post_update, "HOME_STEPS", (("h", home_step),))- monkeypatch.setattr(post_update, "MACHINE_STEPS", (("m", machine_step),))- # Machine steps run on a thread; make THOSE synchronous for the test.- # boot_bootstrap does `import threading` inside the function, so patching- # the stdlib module's Thread attribute is what reaches it — but only the- # bootstrap's own threads may be faked: subprocess.communicate creates- # reader Threads on Windows and needs the real class.- import threading-- real_thread = threading.Thread-- class _SyncThread(real_thread):- def start(self):- if str(getattr(self, "name", "")).startswith("hermes-bootstrap"):- if self._target is not None:- self._target(*self._args, **self._kwargs)- return- real_thread.start(self)-- monkeypatch.setattr(threading, "Thread", _SyncThread)+ monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("h", home_step),))+ monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", (("m", machine_step),))return calls@@ -291,7 +274,7 @@ def test_run_boot_bootstrap_runs_then_noops(repo, tmp_path, monkeypatch, fake_stfirst = run_boot_bootstrap(repo)assert fake_steps == {"home": 1, "machine": 1}assert first["home"] == {"h": {"ok": True}}- assert first["machine"] == "deferred"+ assert first["machine"] == {"m": {"ok": True}}second = run_boot_bootstrap(repo)assert fake_steps == {"home": 1, "machine": 1} # no re-run@@ -320,8 +303,8 @@ def test_step_failure_still_writes_record(repo, tmp_path, monkeypatch):def boom():raise RuntimeError("step exploded")- monkeypatch.setattr(post_update, "HOME_STEPS", (("boom", boom),))- monkeypatch.setattr(post_update, "MACHINE_STEPS", ())+ monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("boom", boom),))+ monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", ())run_boot_bootstrap(repo)record = read_last_known(record_path(repo, "home"))@@ -361,34 +344,58 @@ def test_maybe_run_never_raises(monkeypatch, tmp_path):boot_bootstrap.maybe_run_boot_bootstrap(tmp_path) # must not raise-def test_deferred_machine_steps_execute(repo, tmp_path, monkeypatch):- """The machine scope defers to a REAL thread — the record is written- first (boot readiness must not wait on network installers), and the- steps still actually run. No synchronous-thread fake here on purpose:- the claim under test is that the deferred work happens."""- import threading+def test_boot_machine_scope_is_check_only(repo, tmp_path, monkeypatch):+ """Automatic boot NEVER installs: a drifted machine must get a drift+ report (and a written record), while pm's ensure/sync_venv stay+ reserved for the explicit update pass (MACHINE_STEPS)."""+ import pmfrom hermes_cli import post_updatemonkeypatch.setattr(Path, "home", lambda: tmp_path)monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- ran = threading.Event()- monkeypatch.setattr(post_update, "HOME_STEPS", ())- monkeypatch.setattr(- post_update,- "MACHINE_STEPS",- (("probe", lambda: (ran.set(), {"ok": True})[1]),),- )+ installed: list[str] = []+ monkeypatch.setattr(pm, "check", lambda: ["node: not installed or outdated"])++ class _Boom:+ @staticmethod+ def ensure(*_a, **_kw):+ installed.append("ensure")++ @staticmethod+ def sync_venv(*_a, **_kw):+ installed.append("sync_venv")++ monkeypatch.setitem(sys.modules, "pm.ensure", _Boom)result = run_boot_bootstrap(repo)- assert result["machine"] == "deferred"- # The record was written BEFORE the steps finished (that ordering is- # the design: a crash mid-step must not retrigger every boot).- record = boot_bootstrap.record_path(repo, "machine")- assert json.loads(record.read_text())["results"]["deferred"] is True- assert ran.wait(timeout=10), "deferred machine steps never executed"+ assert result["machine"]["report_runtime_drift"]["drift"] == [+ "node: not installed or outdated"+ ]+ assert installed == [], "boot must not install anything"+ record = read_last_known(record_path(repo, "machine"))+ assert record["results"]["report_runtime_drift"]["ok"] is True+ # the installing registry is untouched for the explicit update owner+ assert ("provision_runtimes", post_update.step_provision_runtimes) in (+ post_update.MACHINE_STEPS+ )+ assert ("report_runtime_drift", post_update.step_report_runtime_drift) in (+ post_update.BOOT_MACHINE_STEPS+ )+++def test_boot_machine_scope_current_is_skipped(repo, tmp_path, monkeypatch):+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ import pm++ monkeypatch.setattr(pm, "check", lambda: [])+ result = run_boot_bootstrap(repo)+ assert result["machine"] == {+ "report_runtime_drift": {"ok": True, "skipped": "current"}+ }def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):@@ -419,8 +426,8 @@ def test_sealed_tree_bootstrap_end_to_end(tmp_path, monkeypatch):calls["n"] += 1return {"ok": True}- monkeypatch.setattr(post_update, "HOME_STEPS", (("h", count),))- monkeypatch.setattr(post_update, "MACHINE_STEPS", ())+ monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("h", count),))+ monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", ())assert run_boot_bootstrap(sealed)["home"] != "skipped"assert calls["n"] == 1@@ -564,8 +571,8 @@ class TestSealedDriftBackstop:monkeypatch.setattr(Path, "home", lambda: tmp_path)monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))monkeypatch.setattr(pm, "check", lambda: ["uv: not installed or outdated"])- monkeypatch.setattr(post_update, "HOME_STEPS", ())- monkeypatch.setattr(post_update, "MACHINE_STEPS", ())+ monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", ())+ monkeypatch.setattr(post_update, "BOOT_MACHINE_STEPS", ())summary = run_boot_bootstrap(root)assert "uv" in summary.get("sealed_runtime_drift", "")diff --git a/tests/hermes_cli/test_boot_wiring.py b/tests/hermes_cli/test_boot_wiring.pynew file mode 100644index 00000000000..7cdb2caa66e--- /dev/null+++ b/tests/hermes_cli/test_boot_wiring.py@@ -0,0 +1,237 @@+"""C26 wiring: the boot registry is reached by the real entry points, and+the cadence has a production caller.++Proven with real imports against a temp HERMES_HOME; the external+boundaries (pm store, network check seams, process identity) are+stubbed — the wiring itself is exercised through the exact public+invocation (``hermes_cli.main.main()``, ``gateway.run`` housekeeping).+"""++from __future__ import annotations++import time++import pytest+++def hermes_home(tmp_path, monkeypatch):+ """Temp HERMES_HOME + runtime dir so no test touches a real profile."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "runtime"))+ return tmp_path+++def boot_probe(monkeypatch):+ """Record every maybe_run_boot_bootstrap call without running steps."""+ import hermes_cli.boot_bootstrap as bb++ calls: list = []+ monkeypatch.setattr(+ bb, "maybe_run_boot_bootstrap", lambda root: calls.append(str(root))+ )+ return calls+++# ── CLI entry point reaches the registry ─────────────────────────────+++def _run_cli_main(argv):+ import sys++ from hermes_cli import main as cli_main++ old_argv = sys.argv+ sys.argv = argv+ try:+ cli_main.main()+ except SystemExit: # argparse help/usage paths exit cleanly+ pass+ finally:+ sys.argv = old_argv+++def test_cli_main_runs_boot_bootstrap_once(hermes_home, boot_probe, capsys):+ _run_cli_main(["hermes", "--version"])++ assert len(boot_probe) == 1, "every dispatch through main() reaches the registry"+ # the root probed is THIS checkout (identity: git HEAD)+ import hermes_cli.boot_bootstrap as bb++ assert boot_probe[0] == str(bb.default_project_root())+++def test_cli_main_skips_boot_bootstrap_during_update(hermes_home, boot_probe):+ _run_cli_main(["hermes", "update", "--help"])++ assert boot_probe == [], "the update flow owns its own maintenance pass"+++def test_boot_bootstrap_reaches_post_update_registry(hermes_home, tmp_path, monkeypatch):+ """The real maybe_run_boot_bootstrap runs due steps from ONE registry+ (no inline duplicate maintenance in the boot path)."""+ import sys++ from hermes_cli import boot_bootstrap, post_update++ ran: list[str] = []+ monkeypatch.setattr(+ post_update,+ "BOOT_HOME_STEPS",+ (("probe_home", lambda: (ran.append("home"), {"ok": True})[1]),),+ )+ monkeypatch.setattr(+ post_update,+ "BOOT_MACHINE_STEPS",+ (("probe_machine", lambda: (ran.append("machine"), {"ok": True})[1]),),+ )++ root = tmp_path / "install"+ root.mkdir()+ (root / ".git").mkdir(parents=True)+ import subprocess as sp++ head = sp.run(+ ["git", "init", "-q", "-b", "main"], cwd=root, capture_output=True+ )+ assert head.returncode == 0+ (root / "f.txt").write_text("1", encoding="utf-8")+ for args in (["add", "."], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "one"]):+ sp.run(["git", *args], cwd=root, capture_output=True, check=True)++ boot_bootstrap.maybe_run_boot_bootstrap(root)++ assert sorted(ran) == ["home", "machine"]+ # second boot: record-gated no-op, no doubled maintenance+ boot_bootstrap.maybe_run_boot_bootstrap(root)+ assert sorted(ran) == ["home", "machine"]+++# ── gateway entry point reaches the registry ─────────────────────────+# (the gr.main() contract is tests/gateway/test_pm_activation.py; here we+# prove the wiring call exists on the real function's module)+++# ── the cadence tick on the existing housekeeping loop ───────────────+++def test_housekeeping_chore_delegates_to_cadence(hermes_home, monkeypatch):+ import gateway.run as gr+ import hermes_cli.plugins_cadence as cad++ called: list = []+ monkeypatch.setattr(+ cad, "maybe_run_gateway_check", lambda **kw: called.append(kw)+ )++ gr._housekeeping_chore("Plugin update check", gr._housekeeping_plugin_update_check)++ assert len(called) == 1+++# ── the production cadence wrapper ───────────────────────────────────+++class _Result:+ def __init__(self, name, klass="git", update_available=None, needs_fixing=None):+ self.name = name+ self.klass = klass+ self.update_available = update_available+ self.needs_fixing = needs_fixing+++def _write_fresh_marker():+ import hermes_constants++ d = hermes_constants.get_hermes_home() / "plugin-update-checks"+ d.mkdir(parents=True, exist_ok=True)+ marker = d / "last-run"+ marker.write_text(str(int(time.time())), encoding="utf-8")+++def test_gateway_check_not_due_makes_no_request(hermes_home, monkeypatch):+ import hermes_cli.plugins_cadence as cad++ _write_fresh_marker()++ def _explode(*_a, **_kw):+ raise AssertionError("network must not be touched when not due")++ assert (+ cad.maybe_run_gateway_check(+ run_checks_fn=_explode, plugins_dir=hermes_home / "plugins"+ )+ is None+ )+++def test_gateway_check_disabled_makes_no_request(hermes_home, monkeypatch):+ import hermes_cli.plugins_cadence as cad++ monkeypatch.setattr(+ cad, "check_interval_hours", lambda config_get=None: 0.0+ )++ def _explode(*_a, **_kw):+ raise AssertionError("disabled cadence must not request")++ assert (+ cad.maybe_run_gateway_check(run_checks_fn=_explode, plugins_dir=None) is None+ )+++def test_gateway_check_due_runs_and_defaults_apply_seam(hermes_home, monkeypatch):+ import hermes_cli.plugins_cadence as cad+ import hermes_cli.plugins_cmd as plugins_cmd++ results = [_Result("plug", update_available=True)]+ seen: dict = {}++ def _checks(plugins_dir):+ seen["dir"] = plugins_dir+ return results++ applied: list[str] = []+ monkeypatch.setattr(+ plugins_cmd, "cmd_update", lambda name, **kw: applied.append(name), raising=True+ )+ monkeypatch.setattr(cad, "auto_apply_enabled", lambda config_get=None: True)++ out = cad.maybe_run_gateway_check(+ run_checks_fn=_checks, plugins_dir=hermes_home / "plugins", now=time.time()+ )++ assert out == results+ assert applied == ["plug"], "git-class updates apply through the manual update flow"+ # the marker was stamped+ import hermes_constants++ marker = hermes_constants.get_hermes_home() / "plugin-update-checks" / "last-run"+ assert marker.is_file()+++def test_gateway_check_network_error_never_applies(hermes_home, monkeypatch):+ import hermes_cli.plugins_cadence as cad+ import hermes_cli.plugins_cmd as plugins_cmd++ def _checks(_plugins_dir):+ raise OSError("network unreachable")++ applied: list[str] = []+ monkeypatch.setattr(+ plugins_cmd, "cmd_update", lambda name, **kw: applied.append(name), raising=True+ )+ monkeypatch.setattr(cad, "auto_apply_enabled", lambda config_get=None: True)++ out = cad.maybe_run_gateway_check(+ run_checks_fn=_checks, plugins_dir=hermes_home / "plugins", now=time.time()+ )++ assert out == []+ assert applied == [], "a failed check must never trigger an apply"+ # and the failed tick is stamped so it does not hammer the network+ import hermes_constants++ marker = hermes_constants.get_hermes_home() / "plugin-update-checks" / "last-run"+ assert marker.is_file()diff --git a/tests/hermes_cli/test_bundled_desktop_launch.py b/tests/hermes_cli/test_bundled_desktop_launch.pyindex 97676307181..d82c9b2e54a 100644--- a/tests/hermes_cli/test_bundled_desktop_launch.py+++ b/tests/hermes_cli/test_bundled_desktop_launch.py@@ -244,28 +244,17 @@ class TestCmdGuiOnABundle:launches.append([str(a) for a in argv])return SimpleNamespace(pid=4242)+ from hermes_cli import main_desktop, main_install_repair, main_web_buildmonkeypatch.setattr(cli_main, "PROJECT_ROOT", repo)- monkeypatch.setattr(cli_main, "_resolve_node_runtime_npm", lambda: "/usr/bin/npm")- monkeypatch.setattr(cli_main, "_desktop_build_needed", lambda *a, **k: True)- monkeypatch.setattr(cli_main, "_write_desktop_build_stamp", lambda *a, **k: None)- monkeypatch.setattr(- cli_main, "_run_npm_install_deterministic", record_npm_install- )- monkeypatch.setattr(- cli_main, "_stop_desktop_processes_locking_build", lambda *a, **k: []- )- monkeypatch.setattr(- cli_main, "_desktop_linux_sandbox_fixup", lambda *a, **k: launcher_ok- )- monkeypatch.setattr(- cli_main, "_desktop_linux_needs_no_sandbox", lambda: not launcher_ok- )- monkeypatch.setattr(- cli_main,- "_desktop_linux_sandbox_helper_is_regular_file",- lambda *a, **k: True,- )- monkeypatch.setattr(cli_main, "_detect_linux_password_store", lambda: None)+ monkeypatch.setattr(main_install_repair, "_resolve_node_runtime_npm", lambda: "/usr/bin/npm")+ monkeypatch.setattr(main_desktop, "_desktop_build_needed", lambda *a, **k: True)+ monkeypatch.setattr(main_desktop, "_write_desktop_build_stamp", lambda *a, **k: None)+ monkeypatch.setattr(main_web_build, "_run_npm_install_deterministic", record_npm_install)+ monkeypatch.setattr(main_desktop, "_stop_desktop_processes_locking_build", lambda *a, **k: [])+ monkeypatch.setattr(main_desktop, "_desktop_linux_sandbox_fixup", lambda *a, **k: launcher_ok)+ monkeypatch.setattr(main_desktop, "_desktop_linux_needs_no_sandbox", lambda: not launcher_ok)+ monkeypatch.setattr(main_desktop, "_desktop_linux_sandbox_helper_is_regular_file", lambda *a, **k: True)+ monkeypatch.setattr(main_desktop, "_detect_linux_password_store", lambda: None)with patch("hermes_cli.bundled_app.subprocess.Popen", side_effect=record_popen), \patch.object(cli_main.subprocess, "run", side_effect=record_run), \diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.pyindex c2297447525..2d00adaa02f 100644--- a/tests/hermes_cli/test_cmd_update.py+++ b/tests/hermes_cli/test_cmd_update.py@@ -86,7 +86,7 @@ def _patch_gateway_discovery():patch("hermes_cli.main._detect_venv_python_processes", return_value=[]), \patch("hermes_cli.main._fleet_probe_expected_runtimes", return_value=False), \patch("os.kill"), \- patch("pm.ensure.sync_venv"), \+ patch("pm.sync_venv"), \patch("hermes_cli.update_inventory.collect_runtime_inventory",return_value=SimpleNamespace(runtimes=[], to_dict=lambda: {}),@@ -253,6 +253,7 @@ class TestCmdUpdateBranchFallback:origin but behind NousResearch/hermes-agent silently misses updates."""from hermes_cli import main as hm+ from hermes_cli import update_cmdmock_run.side_effect = _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"@@ -262,7 +263,17 @@ class TestCmdUpdateBranchFallback:hm,"_get_origin_url",return_value="https://github.com/example/hermes-agent.git",- ), patch.object(hm, "_sync_with_upstream_if_needed") as sync_mock:+ ), patch.object(hm, "_sync_with_upstream_if_needed") as sync_mock, patch.object(+ update_cmd,+ "_venv_core_imports_healthy",+ return_value=(True, ""),+ ), patch.object(+ update_cmd, "_update_node_dependencies", return_value=[]+ ), patch.object(+ update_cmd, "_rebuild_desktop_after_update", return_value=True+ ), patch.object(+ update_cmd, "_check_and_apply_config_migration"+ ):cmd_update(mock_args)expected_git_cmd = (@@ -305,7 +316,12 @@ class TestCmdUpdateBranchFallback:update_cmd, "_add_upstream_remote") as add_remote, patch.object(update_cmd, "_mark_skip_upstream_prompt"- ) as mark_skip, patch("builtins.input") as stdin_input:+ ) as mark_skip, patch.object(+ # PM-era node resolution lives on the purge-protected hub (it must+ # survive _reload_updated_runtime_modules); stub it with the same+ # "no npm" fact shutil.which(None) stubs.+ hm, "_resolve_node_runtime_npm", return_value=None+ ), patch("builtins.input") as stdin_input:cmd_update(SimpleNamespace(yes=True))stdin_input.assert_not_called()@@ -354,12 +370,8 @@ class TestCmdUpdateBranchFallback:(False, "broken before repair"),(health_after_repair, "broken after repair"),],- ), patch.object(- hm, "_install_python_dependencies_with_optional_fallback"- ), patch.object(- hm, "_refresh_active_lazy_features"- ), patch.object(- hm, "_restore_active_tool_dependencies"+ ), patch("pm.sync_venv"), patch.object(+ update_cmd, "_rebuild_desktop_after_update", return_value=True), patch.object(update_cmd, "_write_update_incomplete_marker"), patch.object(@@ -491,6 +503,8 @@ class TestCmdUpdateBranchFallback:def test_update_non_interactive_runs_safe_config_migrations(self, mock_args, capsys):"""Dashboard/web updates apply non-interactive migrations before restart."""with patch("shutil.which", return_value=None), patch(+ "hermes_cli.main._resolve_node_runtime_npm", return_value=None+ ), patch("subprocess.run") as mock_run, patch("builtins.input") as mock_input, patch("hermes_cli.config.get_missing_env_vars", return_value=["MISSING_KEY"]@@ -535,6 +549,8 @@ class TestCmdUpdateMigrationPrompt:):"""Only the version moved → apply non-interactively, never prompt."""with patch("shutil.which", return_value=None), patch(+ "hermes_cli.main._resolve_node_runtime_npm", return_value=None+ ), patch("subprocess.run") as mock_run, patch("builtins.input") as mock_input, patch("hermes_cli.config.get_missing_env_vars", return_value=[]@@ -574,6 +590,8 @@ class TestCmdUpdateMigrationPrompt:warnings must be re-surfaced even in the silent branch."""with patch("shutil.which", return_value=None), patch(+ "hermes_cli.main._resolve_node_runtime_npm", return_value=None+ ), patch("subprocess.run") as mock_run, patch("builtins.input") as mock_input, patch("hermes_cli.config.get_missing_env_vars", return_value=[]@@ -616,6 +634,8 @@ class TestCmdUpdateMigrationPrompt:{"key": "display.new_widget", "description": "New config option: display.new_widget"},]with patch("shutil.which", return_value=None), patch(+ "hermes_cli.main._resolve_node_runtime_npm", return_value=None+ ), patch("subprocess.run") as mock_run, patch("builtins.input", return_value="n"), patch("hermes_cli.config.get_missing_env_vars", return_value=env_items@@ -710,6 +730,7 @@ class TestCmdUpdateProfileSkillSync:patch("hermes_cli.profiles.list_profiles", return_value=all_profiles),patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),patch("tools.skills_sync.sync_skills", return_value=empty_sync),+ patch("hermes_cli.main._resolve_node_runtime_npm", return_value=None),):cmd_update(mock_args)@@ -744,6 +765,7 @@ class TestCmdUpdateProfileSkillSync:patch("hermes_cli.profiles.list_profiles", return_value=[default_p]),patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),patch("tools.skills_sync.sync_skills", return_value=empty_sync),+ patch("hermes_cli.main._resolve_node_runtime_npm", return_value=None),):cmd_update(mock_args)@@ -801,7 +823,10 @@ class TestCmdUpdateBranchFlag:)args = SimpleNamespace(branch="bb/gui")- cmd_update(args)+ with patch(+ "hermes_cli.main._resolve_node_runtime_npm", return_value=None+ ):+ cmd_update(args)commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]@@ -1418,6 +1443,7 @@ class TestUpdateNodeDependencies:(tmp_path / "package.json").write_text("{}")monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)+ monkeypatch.setattr(hm, "_resolve_node_runtime_npm", lambda: None)update_cmd._update_node_dependencies()diff --git a/tests/hermes_cli/test_dashboard_unified_launch.py b/tests/hermes_cli/test_dashboard_unified_launch.pyindex 55d1d4877da..d02a2c127b4 100644--- a/tests/hermes_cli/test_dashboard_unified_launch.py+++ b/tests/hermes_cli/test_dashboard_unified_launch.py@@ -35,7 +35,6 @@ class TestUnifiedDashboardRouting:monkeypatch.setattr("hermes_cli.profiles.get_active_profile_name", lambda: "worker_x")- monkeypatch.setattr(main_mod, "_dashboard_listening", lambda host, port: False)monkeypatch.setattr(main_dashboard, "_dashboard_listening", lambda host, port: False)execs = []diff --git a/tests/hermes_cli/test_dep_ensure.py b/tests/hermes_cli/test_dep_ensure.pyindex 84bc0a5bada..216a243e4a1 100644--- a/tests/hermes_cli/test_dep_ensure.py+++ b/tests/hermes_cli/test_dep_ensure.py@@ -29,75 +29,6 @@ def test_available_dep_short_circuits(monkeypatch):-def test_has_npx_agent_browser_true_when_npx_resolves():- """agent-browser resolves lazily via npx on the default install (#43564)- — _has_npx_agent_browser mirrors the runtime cascade so the "browser" dep- check doesn't wrongly report it missing."""- from hermes_cli.dep_ensure import _has_npx_agent_browser-- with patch.object(bt_install, "_find_agent_browser", return_value="npx agent-browser"), \- patch.object(bt_install, "_requires_real_termux_browser_install", return_value=False):- assert _has_npx_agent_browser() is True---def test_has_npx_agent_browser_false_on_termux_local_bare_npx():- from hermes_cli.dep_ensure import _has_npx_agent_browser-- with patch.object(bt_install, "_find_agent_browser", return_value="npx agent-browser"), \- patch.object(bt_install, "_requires_real_termux_browser_install", return_value=True):- assert _has_npx_agent_browser() is False---def test_has_npx_agent_browser_false_when_nothing_resolves():- from hermes_cli.dep_ensure import _has_npx_agent_browser-- def _raise(**_kw):- raise FileNotFoundError("agent-browser CLI not found")-- with patch.object(bt_install, "_find_agent_browser", _raise):- assert _has_npx_agent_browser() is False---def test_find_agent_browser_lazy_install_cycle_terminates(monkeypatch):- """tools.browser_tool_install._find_agent_browser's "nothing found" branch calls- ensure_dependency("browser"), whose "browser" check now includes- _has_npx_agent_browser() -> _find_agent_browser(validate=False) again.- That nested call must NOT be able to trigger another ensure_dependency- call (only validate=True does that) — verifying the cycle is bounded to- one extra rescan, not unbounded recursion, using the real functions on- both sides rather than mocking the cycle away."""- import shutil- import tools.browser_tool as bt- from hermes_cli import dep_ensure-- monkeypatch.setattr(bt, "_cached_agent_browser", None)- monkeypatch.setattr(bt, "_agent_browser_resolved", False)- monkeypatch.setattr(shutil, "which", lambda *a, **k: None)- monkeypatch.setattr("tools.browser_tool_install._resolve_npx_bin", lambda: None)- monkeypatch.setattr(dep_ensure, "_has_system_browser", lambda: False)- monkeypatch.setattr(dep_ensure, "_has_hermes_agent_browser", lambda: False)- monkeypatch.setattr(dep_ensure, "_find_install_script", lambda *a, **k: (None, None))-- real_find_agent_browser = bt_install._find_agent_browser- validate_calls = []-- def counting_find_agent_browser(*, validate=True):- validate_calls.append(validate)- return real_find_agent_browser(validate=validate)-- monkeypatch.setattr(bt_install, "_find_agent_browser", counting_find_agent_browser)-- with pytest.raises(FileNotFoundError):- bt_install._find_agent_browser(validate=True)-- # One outer validate=True call, plus exactly one bounded nested- # validate=False rescan from _has_npx_agent_browser inside- # ensure_dependency's "browser" check — not unbounded recursion, and not- # a second ensure_dependency("browser") call (which would show up as a- # second `True` in this list).- assert validate_calls == [True, False]--def test_missing_dep_installs_through_pm(monkeypatch):from hermes_cli import dep_ensurediff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.pyindex f241b182ce0..cee278fd86b 100644--- a/tests/hermes_cli/test_doctor.py+++ b/tests/hermes_cli/test_doctor.py@@ -8,6 +8,7 @@ import typesimport ioimport contextlibfrom argparse import Namespace+from pathlib import Pathfrom types import SimpleNamespaceimport pytest@@ -18,6 +19,7 @@ from hermes_cli import config as config_modimport hermes_cli.gateway as gateway_clifrom hermes_cli import doctor as doctor_modfrom hermes_cli.doctor_config import _has_provider_env_config+from hermes_cli.doctor_report import Findingimport shutilfrom hermes_cli import doctor_toolsfrom hermes_cli import doctor_state@@ -26,6 +28,48 @@ from hermes_cli import doctor_configfrom tools import browser_tool_install as bt_install+def _tls_out_normalized(out: str) -> str:+ """Doctor print matcher for TLS rows: key on words, not spacing."""+ return " ".join(out.lower().split())+++def test_check_certificates_exercises_real_tls_policy(monkeypatch, capsys):+ """install_truststore True: the check exercises the actual policy+ (agent.ssl_verify platform trust store), reports TLS as configured, and+ never presents context construction as certificate verification."""+ monkeypatch.setattr("agent.ssl_verify.install_truststore", lambda: True)++ doctor_platform.check_certificates()++ out = _tls_out_normalized(capsys.readouterr().out)+ assert "✓" in out+ assert "tls" in out+ assert "skipped" not in out+ assert "verification active" not in out # configuration, not proof of validation+ assert "platform trust" in out or "configured" in out+++def test_check_certificates_fallback_names_openssl_without_platform_trust_claim(monkeypatch, capsys):+ """install_truststore False + a constructible context is an OpenSSL fallback:+ the output names the actual fallback, stays available, and no ✓ row claims+ the platform trust store is active."""+ monkeypatch.setattr("agent.ssl_verify.install_truststore", lambda: False)++ doctor_platform.check_certificates()++ raw = capsys.readouterr().out+ out = _tls_out_normalized(raw)+ assert "⚠" in raw+ assert "trust store" in out+ assert "openssl" in out # names the actual fallback+ assert "verification active" not in out # construction proves nothing verified+ assert "available" in out # status is context available, not verification proven+ assert not any(+ line.startswith("✓") and "platform trust" in line+ for line in raw.splitlines()+ )++class TestDoctorPlatformHints:def test_sqlite_upgrade_hint_recreates_docker_containers(self, monkeypatch):monkeypatch.setattr(config_mod, "detect_install_method", lambda _root: "docker")@@ -41,13 +85,15 @@ class TestDoctorPlatformHints:assert "run `hermes update`" in hint- def test_sqlite_upgrade_hint_apt_stamp_falls_back_to_generic_update(self):- # The Termux 'apt' lane was removed; a legacy stamp now routes to the- # generic `hermes update` path.- hint = doctor._sqlite_upgrade_hint("apt")+ def test_sqlite_upgrade_hint_apt_stamp_names_termux_external_update(self):+ # The "apt" install method is Termux APT by contract (config.py+ # _UPDATE_COMMAND_BY_METHOD). Deployment kinds are first-class: doctor+ # reports the correct external update command instead of routing an+ # out-of-place method through the in-place `hermes update` path.+ hint = doctor_platform._sqlite_upgrade_hint("apt")- assert "run `hermes update`" in hint- assert "pkg upgrade" not in hint+ assert "run `pkg upgrade hermes-agent`" in hint+ assert "hermes update" not in hintdef test_sqlite_upgrade_hint_preserves_nix_guidance_as_prose(self):from hermes_cli.config import recommended_update_command_for_method@@ -1644,63 +1690,101 @@ class TestMacOSTCCGrants:assert "stable" not in out-class TestPmVenvActive:- """_pm_venv_active() resolves the runtime venv from pm's facts/store,- not from sys.prefix sniffing (which degrades under- no-boot-through-venv, where sys.prefix == sys.base_prefix always and- VIRTUAL_ENV is unset in bundled installs)."""-- def test_pm_provisioned_venv_is_active_without_virtual_env(self, tmp_path, monkeypatch):- import json-- payload = tmp_path / "payload"- store = payload / "tools"- (payload / "venv").mkdir(parents=True)- store.mkdir(parents=True, exist_ok=True)- (payload / "manifest.json").write_text("{}", encoding="utf-8")- (store / "facts.json").write_text(- json.dumps(- {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}- ),- encoding="utf-8",- )- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))- monkeypatch.delenv("VIRTUAL_ENV", raising=False)- # No sys.prefix venv: the legacy probe alone would say False.- monkeypatch.setattr(doctor_mod.sys, "prefix", "/usr")- monkeypatch.setattr(doctor_mod.sys, "base_prefix", "/usr")-- assert doctor_mod._pm_venv_active() is True-- def test_no_venv_fact_falls_back_to_legacy_probe(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "no-such-store"))- monkeypatch.delenv("VIRTUAL_ENV", raising=False)- monkeypatch.setattr(doctor_mod.sys, "prefix", "/usr")- monkeypatch.setattr(doctor_mod.sys, "base_prefix", "/usr")-- assert doctor_mod._pm_venv_active() is False-- monkeypatch.setattr(doctor_mod.sys, "prefix", "/some/venv")- assert doctor_mod._pm_venv_active() is True-- def test_bundled_venv_fact_without_venv_dir_is_not_active(self, tmp_path, monkeypatch):- import json-- payload = tmp_path / "payload"- store = payload / "tools"- store.mkdir(parents=True)- (payload / "manifest.json").write_text("{}", encoding="utf-8")- (store / "facts.json").write_text(- json.dumps(- {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}- ),- encoding="utf-8",- )- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))- monkeypatch.setattr(doctor_mod.sys, "prefix", "/usr")- monkeypatch.setattr(doctor_mod.sys, "base_prefix", "/usr")+class TestStagedRuntimeVenv:+ """doctor_platform._check_python_environment distinguishes staged+ dependencies (pm's Venv().venv_dir() resolved state) from the active+ interpreter: under no-boot-through-venv bundled installs+ sys.prefix == sys.base_prefix by design, so "not active" must not read+ as "missing dependencies" when pm has staged the runtime venv."""++ @staticmethod+ def _stub_venv(monkeypatch, venv_dir):+ class _StubVenv:+ def venv_dir(self):+ return venv_dir++ monkeypatch.setattr("pm.packages.Venv", _StubVenv)++ # --- _staged_venv_dir: pm authority + provisioned-venv marker ---++ def test_staged_venv_dir_returns_provisioned_venv(self, tmp_path, monkeypatch):+ import pm.packages as pm_packages++ venv = tmp_path / "venv"+ venv.mkdir()+ (venv / "pyvenv.cfg").write_text("home = /usr\n", encoding="utf-8")+ self._stub_venv(monkeypatch, venv)- assert doctor_mod._pm_venv_active() is False+ assert doctor_platform._staged_venv_dir() == venv+ # Sanity: the stub really replaced pm's own Venv (no real-repo read).+ assert pm_packages.Venv is not None++ def test_resolved_path_without_venv_marker_is_not_staged(self, tmp_path, monkeypatch):+ empty = tmp_path / "venv"+ empty.mkdir()+ self._stub_venv(monkeypatch, empty)++ assert doctor_platform._staged_venv_dir() is None++ def test_unreadable_pm_degrades_to_none(self, monkeypatch):+ class _BrokenVenv:+ def venv_dir(self):+ raise RuntimeError("pm unavailable")++ monkeypatch.setattr("pm.packages.Venv", _BrokenVenv)++ assert doctor_platform._staged_venv_dir() is None++ # --- the check's staged-vs-active rows ---++ def test_staged_but_not_active_reports_staged_dependencies(self, monkeypatch, capsys):+ monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: Path("/payload/venv"))+ monkeypatch.setattr(doctor_platform.sys, "prefix", "/usr")+ monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr")++ doctor_platform._check_python_environment(False)++ out = capsys.readouterr().out+ assert "Runtime venv staged" in out+ assert "runs outside it" in out+ assert "Not in virtual environment" not in out # dependencies exist; no false alarm++ def test_unrelated_active_venv_is_not_claimed_as_the_staged_one(self, monkeypatch, capsys):+ """A process running in some OTHER venv must not be labeled active-in+ the staged one: the comparison is resolved prefix vs staged dir."""+ monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: Path("/payload/venv"))+ monkeypatch.setattr(doctor_platform.sys, "prefix", "/some/other/venv")+ monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr")++ doctor_platform._check_python_environment(False)++ out = capsys.readouterr().out+ assert "Runtime venv staged" in out+ assert "runs outside it" in out+ assert "active in this process" not in out++ def test_staged_and_active_names_both_facts(self, monkeypatch, capsys):+ staged = Path("/payload/venv")+ monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: staged)+ monkeypatch.setattr(doctor_platform.sys, "prefix", str(staged))+ monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr")++ doctor_platform._check_python_environment(False)++ out = capsys.readouterr().out+ assert "Runtime venv staged" in out+ assert "active in this process" in out++ def test_nothing_staged_keeps_legacy_interpreter_probe(self, monkeypatch, capsys):+ monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: None)+ monkeypatch.setattr(doctor_platform.sys, "prefix", "/usr")+ monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr")++ doctor_platform._check_python_environment(False)++ out = capsys.readouterr().out+ assert "Runtime venv staged" not in out+ assert "Not in virtual environment" in outdef test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):helper = TestDoctorMemoryProviderSection()diff --git a/tests/hermes_cli/test_doctor_channel_hygiene.py b/tests/hermes_cli/test_doctor_channel_hygiene.pyindex 525ac56fdb1..9057f2677cb 100644--- a/tests/hermes_cli/test_doctor_channel_hygiene.py+++ b/tests/hermes_cli/test_doctor_channel_hygiene.py@@ -9,7 +9,7 @@ into a warning, silence on a clean config.from unittest.mock import patch-from hermes_cli.doctor import _check_channel_record_hygiene+from hermes_cli.doctor_config import _check_channel_record_hygienedef test_clean_config_prints_nothing(capsys):diff --git a/tests/hermes_cli/test_doctor_legacy_checkout.py b/tests/hermes_cli/test_doctor_legacy_checkout.pyindex 3ff8a0477df..274bdd68a51 100644--- a/tests/hermes_cli/test_doctor_legacy_checkout.py+++ b/tests/hermes_cli/test_doctor_legacy_checkout.py@@ -6,7 +6,7 @@ import subprocessimport pytestimport hermes_cli.doctor as doctor-from hermes_cli.doctor import check_legacy_desktop_checkout+from hermes_cli.doctor_state import check_legacy_desktop_checkoutdef _git(cwd, *args):@@ -45,11 +45,14 @@ def embedded_context(tmp_path, monkeypatch):class TestLegacyDesktopCheckout:- def test_pristine_checkout_gets_a_deletion_suggestion(self, embedded_context, capsys):+ def test_pristine_checkout_gets_report_without_deletion_command(self, embedded_context, capsys):check_legacy_desktop_checkout()out = capsys.readouterr().outassert "Unused checkout" in out- assert "rm -rf" in out+ # Report-review posture: no deletion command is ever suggested —+ # pristineness proves nothing about unpublished commits or other clients.+ assert "rm -rf" not in out+ assert "delete" not in out.lower() or "does not delete" in out.lower()def test_dirty_checkout_warns_and_suggests_nothing(self, embedded_context, capsys):(embedded_context / "f.txt").write_text("local work\n")diff --git a/tests/hermes_cli/test_doctor_pm_store_probe.py b/tests/hermes_cli/test_doctor_pm_store_probe.pyindex 55c181f2115..c7b73c347b2 100644--- a/tests/hermes_cli/test_doctor_pm_store_probe.py+++ b/tests/hermes_cli/test_doctor_pm_store_probe.py@@ -7,7 +7,9 @@ on the tool being present."""from __future__ import annotations-from hermes_cli import doctor+import sys++from hermes_cli import doctor_toolsclass TestPmToolPath:@@ -25,8 +27,6 @@ class TestPmToolPath:return storedef test_staged_tool_resolves_to_its_store_binary(self, tmp_path, monkeypatch):- import sys-store = self._store(tmp_path, monkeypatch,{"ripgrep": {"entry": "ripgrep-15.0.0-test", "version": "15.0.0", "env": {}}},@@ -36,15 +36,41 @@ class TestPmToolPath:binary = entry / ("rg.exe" if sys.platform == "win32" else "rg")binary.write_text("", encoding="utf-8")- assert doctor._pm_tool_path("ripgrep") == binary+ assert doctor_tools._pm_tool_path("ripgrep") == binarydef test_unstaged_tool_resolves_to_none(self, tmp_path, monkeypatch):self._store(tmp_path, monkeypatch, {})- assert doctor._pm_tool_path("ripgrep") is None+ assert doctor_tools._pm_tool_path("ripgrep") is Nonedef test_recorded_but_deleted_binary_resolves_to_none(self, tmp_path, monkeypatch):self._store(tmp_path, monkeypatch,{"ripgrep": {"entry": "ripgrep-15.0.0-test", "version": "15.0.0", "env": {}}},)- assert doctor._pm_tool_path("ripgrep") is None+ assert doctor_tools._pm_tool_path("ripgrep") is None+++class TestGitAndRgWiring:+ """_check_git_and_rg probes the store first, so a managed install is+ never reported as "not found" just because the store is off PATH."""++ def test_staged_rg_is_found_and_labeled_pm_store(self, tmp_path, monkeypatch, capsys):+ store = tmp_path / "tools"+ store.mkdir()+ (store / "facts.json").write_text(+ '{"schema": 1, "packages": {"ripgrep": {"entry": "ripgrep-15.0.0-test"}}}',+ encoding="utf-8",+ )+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))+ entry = store / "ripgrep-15.0.0-test"+ entry.mkdir()+ (entry / ("rg.exe" if sys.platform == "win32" else "rg")).write_text("", encoding="utf-8")+ # Nothing on PATH: the old probe alone reported "not found". Patched at+ # the real shutil.which boundary, not a doctor wrapper.+ monkeypatch.setattr(doctor_tools.shutil, "which", lambda _cmd: None)++ doctor_tools._check_git_and_rg(False)++ out = capsys.readouterr().out+ assert "✓ ripgrep (rg) (pm store)" in out+ assert "ripgrep (rg) not found" not in outdiff --git a/tests/hermes_cli/test_dump_git_commit.py b/tests/hermes_cli/test_dump_git_commit.pyindex 76dcd6762bb..d51c1238f64 100644--- a/tests/hermes_cli/test_dump_git_commit.py+++ b/tests/hermes_cli/test_dump_git_commit.py@@ -2,13 +2,17 @@``hermes dump`` prints the running commit so support bug reports identify theexact version. Source installs resolve it live via git; packaged builds-(Docker, Nix) use the install stamp. Both paths go through-``version_info.get_version_info()``.+(Docker, Nix) use the install stamp via ``version_info`` — but ONLY when the+requested project_root IS the running install, because version_info has no+per-root API and would otherwise answer with an unrelated install's identity.-These tests cover both paths plus the failure modes (no stamp, no git).+These tests cover both paths plus the failure modes (no stamp, no git, and a+project_root the running install cannot speak for)."""-from unittest.mock import MagicMock, patch+from pathlib import Path+from subprocess import run as _run+from unittest.mock import patchfrom hermes_cli.version_info import VersionInfo, _reset_version_info_cache@@ -17,6 +21,11 @@ def setup_function():_reset_version_info_cache()+def _patch_running_install(repo_dir):+ """Make the requested repo_dir the running install for the fallback path."""+ return patch("hermes_cli.dump.get_project_root", return_value=repo_dir.resolve())++def test_get_git_commit_uses_live_git_when_available(tmp_path):"""Source install: version_info resolves commit from live git."""from hermes_cli import dump@@ -24,7 +33,8 @@ def test_get_git_commit_uses_live_git_when_available(tmp_path):repo_dir = tmp_path / "repo"repo_dir.mkdir()- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \patch("hermes_cli.version_info._git_version_info",return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git")):@@ -40,7 +50,8 @@ def test_get_git_commit_uses_stamp_when_no_git(tmp_path):repo_dir = tmp_path / "no-git-here"repo_dir.mkdir()- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \patch("hermes_cli.version_info._stamp_version_info",return_value=VersionInfo("0.19.0", "0.19.0", None, "cafef00d" * 5, None, "docker")):@@ -56,7 +67,8 @@ def test_get_git_commit_returns_unknown_when_neither_source_available(tmp_path):repo_dir = tmp_path / "repo"repo_dir.mkdir()- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: None):commit = dump._get_git_commit(repo_dir)@@ -71,7 +83,8 @@ def test_get_git_commit_output_format_identical_between_sources(tmp_path):repo_dir.mkdir()# Live-git path.- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \patch("hermes_cli.version_info._git_version_info",return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "b2f477a3" * 5, "main", "git")):@@ -79,7 +92,8 @@ def test_get_git_commit_output_format_identical_between_sources(tmp_path):live = dump._get_git_commit(repo_dir)# Stamp path.- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \patch("hermes_cli.version_info._stamp_version_info",return_value=VersionInfo("0.19.0", "0.19.0", None, "b2f477a3" * 5, None, "docker")):@@ -98,7 +112,8 @@ def test_get_git_commit_date_uses_version_info(tmp_path):repo_dir = tmp_path / "repo"repo_dir.mkdir()- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \patch("hermes_cli.version_info._git_version_info",return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git", False, 1718662620)):@@ -115,9 +130,64 @@ def test_get_git_commit_date_empty_when_unknown(tmp_path):repo_dir = tmp_path / "no-git-here"repo_dir.mkdir()- with patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \+ with _patch_running_install(repo_dir), \+ patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \patch("hermes_cli.version_info._resolve_repo_dir", lambda: None):_reset_version_info_cache()date = dump._get_git_commit_date(repo_dir)assert date == ""+++# --------------------------------------------------------------------------+# Authority: the requested project_root decides, never the running install+# --------------------------------------------------------------------------+++def test_get_git_commit_unknown_for_other_root_without_git(tmp_path):+ """A non-git project_root that is NOT the running install → '(unknown)'.++ No mocks: the running install (this checkout) HAS git provenance, so the+ pre-authority fallback would have answered with THIS repo's sha — an+ unrelated install's identity — instead of admitting unknown.+ """+ from hermes_cli import dump++ other_root = tmp_path / "plain-dir"+ other_root.mkdir()+ assert (other_root / ".git").exists() is False++ commit = dump._get_git_commit(other_root)+ assert commit == "(unknown)"+++def test_get_git_commit_authoritative_for_real_temp_repo(tmp_path):+ """A real temp git repo reports ITS OWN commit, not the running install's."""+ from hermes_cli import dump++ repo_dir = tmp_path / "scratch-repo"+ repo_dir.mkdir()+ (repo_dir / "file.txt").write_text("x", encoding="utf-8")+ for args in (+ ["init", "-b", "main"],+ ["-c", "[email protected]", "-c", "user.name=t", "add", "."],+ ["-c", "[email protected]", "-c", "user.name=t",+ "commit", "-m", "scratch", "--no-gpg-sign"],+ ):+ _run(["git", *args], cwd=repo_dir, capture_output=True, check=True)+ expected = _run(["git", "rev-parse", "--short=8", "HEAD"], cwd=repo_dir,+ capture_output=True, text=True, check=True).stdout.strip()++ commit = dump._get_git_commit(repo_dir)+ assert commit == expected+ assert commit != dump._get_git_commit(Path(dump.__file__).parent.parent)+++def test_get_git_commit_date_unknown_for_other_root_without_git(tmp_path):+ """Same authority rule for the date helper: other root without git → ''."""+ from hermes_cli import dump++ other_root = tmp_path / "plain-dir"+ other_root.mkdir()++ assert dump._get_git_commit_date(other_root) == ""diff --git a/tests/hermes_cli/test_ensure_windows_bin_launchers.py b/tests/hermes_cli/test_ensure_windows_bin_launchers.pyindex 5a9a2a127a2..e9b92754ed4 100644--- a/tests/hermes_cli/test_ensure_windows_bin_launchers.py+++ b/tests/hermes_cli/test_ensure_windows_bin_launchers.py@@ -90,8 +90,10 @@ def _assert_boot_is_store_not_venv(launcher: Path, root: Path, store: Path):else:body = launcher.read_text(encoding="utf-8")assert venv_python not in body- assert "python-*" in body # store-python boot-time resolution- assert "pm install" in body # instructive failure until pm lands it+ if "python-*" in body:+ assert "pm install" in body # unmaterialized-store delegator+ else:+ assert str(store) in body # resolved-store .cmd fallback@pytest.fixture@@ -153,7 +155,9 @@ def test_legacy_venv_trampoline_is_replaced_by_store_launcher(assert set(Path(p).stem for p in map(Path, restored)) == set(_WINDOWS_BIN_LAUNCHERS)for name in _WINDOWS_BIN_LAUNCHERS:- _assert_boot_is_store_not_venv(bin_dir / f"{name}.exe", root, store)+ exe = bin_dir / f"{name}.exe"+ launcher = exe if exe.exists() and b"legacy trampoline" not in exe.read_bytes() else bin_dir / f"{name}.cmd"+ _assert_boot_is_store_not_venv(launcher, root, store)def test_healthy_store_launcher_is_a_noop(tmp_path, monkeypatch):@@ -186,7 +190,9 @@ def test_healthy_canonical_layout_with_placeholder_cmds_gets_upgraded(ensure_windows_bin_launchers(root, windows=True, user_path_entries=[])for name in _WINDOWS_BIN_LAUNCHERS:- _assert_boot_is_store_not_venv(bin_dir / f"{name}.exe", root, store)+ exe = bin_dir / f"{name}.exe"+ launcher = exe if exe.exists() and b"legacy trampoline" not in exe.read_bytes() else bin_dir / f"{name}.cmd"+ _assert_boot_is_store_not_venv(launcher, root, store)def test_legacy_bin_restaged_only_while_on_user_path(managed_install):diff --git a/tests/hermes_cli/test_external_process_auth_status.py b/tests/hermes_cli/test_external_process_auth_status.pyindex bc9ac1df827..6feb4be9187 100644--- a/tests/hermes_cli/test_external_process_auth_status.py+++ b/tests/hermes_cli/test_external_process_auth_status.py@@ -24,8 +24,11 @@ from hermes_cli.auth import (@pytest.fixture()-def _clean_copilot_env(monkeypatch):+def _clean_copilot_env(tmp_path, monkeypatch):"""Neutralize host state so tests pin behaviour, not this machine."""+ from pathlib import Path+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("USERPROFILE", str(tmp_path))for var in ("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN","HERMES_COPILOT_ACP_COMMAND", "COPILOT_CLI_PATH",diff --git a/tests/hermes_cli/test_external_process_provider_seam.py b/tests/hermes_cli/test_external_process_provider_seam.pyindex 47f3f476682..f0e927c9937 100644--- a/tests/hermes_cli/test_external_process_provider_seam.py+++ b/tests/hermes_cli/test_external_process_provider_seam.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport osimport stat+from pathlib import Pathimport pytest@@ -46,7 +47,7 @@ def fake_cli(tmp_path, monkeypatch):bindir = tmp_path / "bin"bindir.mkdir()for name in ("acme-cli", "copilot", "custom-acme"):- exe = bindir / name+ exe = bindir / (name + ".exe" if os.name == "nt" else name)exe.write_text("#!/bin/sh\nexit 0\n")exe.chmod(exe.stat().st_mode | stat.S_IEXEC)monkeypatch.setenv("PATH", f"{bindir}{os.pathsep}{os.environ.get('PATH', '')}")@@ -62,12 +63,13 @@ def test_an_out_of_tree_external_process_provider_resolves_end_to_end(fake_cli,assert resolve_provider("acme") == "acme-acp"creds = resolve_external_process_provider_credentials("acme-acp")- assert (creds["command"], creds["args"], creds["api_key"]) == (str(fake_cli / "acme-cli"), ["--acp"], "acme-acp")+ assert Path(creds["command"]) == fake_cli / ("acme-cli.exe" if os.name == "nt" else "acme-cli")+ assert (creds["args"], creds["api_key"]) == (["--acp"], "acme-acp")- monkeypatch.setenv("ACME_CLI_PATH", str(fake_cli / "custom-acme"))+ monkeypatch.setenv("ACME_CLI_PATH", str(fake_cli / ("custom-acme.exe" if os.name == "nt" else "custom-acme")))monkeypatch.setenv("ACME_ACP_ARGS", "--acp=true --verbose")creds = resolve_external_process_provider_credentials("acme-acp")- assert (creds["command"], creds["args"]) == (str(fake_cli / "custom-acme"), ["--acp=true", "--verbose"])+ assert (creds["command"], creds["args"]) == (str(fake_cli / ("custom-acme.exe" if os.name == "nt" else "custom-acme")), ["--acp=true", "--verbose"])runtime = resolve_runtime_provider(requested="acme", target_model="acme")assert (runtime["provider"], runtime["base_url"], runtime["source"]) == ("acme-acp", "acp://acme", "process")@@ -78,9 +80,9 @@ def test_copilot_acp_launch_details_are_unchanged(fake_cli, monkeypatch):from hermes_cli.runtime_provider import resolve_runtime_providercreds = resolve_external_process_provider_credentials("copilot-acp")- assert creds["command"] == str(fake_cli / "copilot")+ assert Path(creds["command"]) == fake_cli / ("copilot.exe" if os.name == "nt" else "copilot")assert (creds["args"], creds["api_key"], creds["base_url"]) == (["--acp", "--stdio"], "copilot-acp", "acp://copilot")- monkeypatch.setenv("COPILOT_CLI_PATH", str(fake_cli / "custom-acme"))- assert resolve_external_process_provider_credentials("copilot-acp")["command"] == str(fake_cli / "custom-acme")+ monkeypatch.setenv("COPILOT_CLI_PATH", str(fake_cli / ("custom-acme.exe" if os.name == "nt" else "custom-acme")))+ assert resolve_external_process_provider_credentials("copilot-acp")["command"] == str(fake_cli / ("custom-acme.exe" if os.name == "nt" else "custom-acme"))assert resolve_runtime_provider(requested="copilot-acp", target_model="x")["base_url"] == "acp://copilot"diff --git a/tests/hermes_cli/test_gateway_proc_fallback.py b/tests/hermes_cli/test_gateway_proc_fallback.pyindex f9c2cf99829..32cfe40ebf7 100644--- a/tests/hermes_cli/test_gateway_proc_fallback.py+++ b/tests/hermes_cli/test_gateway_proc_fallback.py@@ -55,7 +55,6 @@ def _fake_proc_dir(entries: dict):# ---------------------------------------------------------------------------[email protected]("linux")class TestProcFallback:"""_scan_gateway_pids reads /proc when available, skips ps.diff --git a/tests/hermes_cli/test_gateway_scm_feature_removed.py b/tests/hermes_cli/test_gateway_scm_feature_removed.pynew file mode 100644index 00000000000..d8a0fe4970b--- /dev/null+++ b/tests/hermes_cli/test_gateway_scm_feature_removed.py@@ -0,0 +1,51 @@+"""Pins the REMOVAL of the MSIX SCM Windows service feature (audit C06/C07).++Settled user decision (2026-09-03): Windows gateway supervision stays on the+existing user-logon Scheduled Task. The desktop6:Service manifest fragment+and the `gateway run --service` / `hermes gateway service` frontend were+removed because the desktop6 schema cannot grant the promised installing-user+account model (StartAccount is required and limited to+localSystem|localService|networkService). These tests pin the surface the+feature used to own so it cannot silently come back.+"""++from __future__ import annotations++import argparse++import hermes_cli.config_defaults as config_defaults+from hermes_cli.subcommands import gateway as gateway_subcommands+++def _build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser()+ subparsers = parser.add_subparsers(dest="command")+ gateway_subcommands.build_gateway_parser(+ subparsers, cmd_gateway=lambda *_: None, cmd_proxy=lambda *_: None,+ cmd_gateway_enroll=lambda *_: None,+ )+ return parser+++def test_gateway_subparser_has_no_service_subcommand(capsys):+ parser = _build_parser()+ try:+ parser.parse_args(["gateway", "service", "on"])+ except SystemExit:+ pass+ else:+ raise AssertionError("`hermes gateway service` must stay removed")+ finally:+ capsys.readouterr()+++def test_gateway_run_has_no_service_flag():+ parser = _build_parser()+ args = parser.parse_args(["gateway", "run"])+ assert not hasattr(args, "service"), "gateway run --service must stay removed"+++def test_config_defaults_have_no_gateway_service_key():+ assert "service" not in config_defaults.DEFAULT_CONFIG["gateway"], (+ "gateway.service (the SCM posture key) must stay removed"+ )diff --git a/tests/hermes_cli/test_gateway_scm_service.py b/tests/hermes_cli/test_gateway_scm_service.pydeleted file mode 100644index 4149331cf4f..00000000000--- a/tests/hermes_cli/test_gateway_scm_service.py+++ /dev/null@@ -1,142 +0,0 @@-"""Tests: `hermes gateway service` verbs + the updater's SCM restart branch.--Hermetic — pywin32/SCM calls stubbed; the CONTRACTS are what's tested:-dispatch, config persistence, the sealed+running gate for the updater's-Restart-Service path, and the fall-through to ordinary restarts on every-other machine shape.-"""--from __future__ import annotations--from unittest.mock import patch--import pytest--import hermes_cli.gateway as gw---def _fake_scm(monkeypatch, *, installed=True, running=True, calls=None):- """Stub the pywin32 SCM surface; record calls into `calls`."""- import sys- import types-- if calls is None:- calls = []- mod = types.ModuleType("win32service")- mod.SERVICE_AUTO_START = 2- mod.SERVICE_DEMAND_START = 3- util_mod = types.ModuleType("win32serviceutil")- util_mod.QueryServiceStatus = lambda name: (None, 4 if running else 1) if installed else (_ for _ in ()).throw(OSError("not installed"))- util_mod.ChangeServiceConfig = lambda name, starttype: calls.append(("config", starttype))- util_mod.StartService = lambda name: calls.append(("start",))- util_mod.StopService = lambda name: calls.append(("stop",))- util_mod.RestartService = lambda name: calls.append(("restart",))- monkeypatch.setitem(sys.modules, "win32service", mod)- monkeypatch.setitem(sys.modules, "win32serviceutil", util_mod)- return calls---def test_service_status_not_installed(monkeypatch, capfd):- monkeypatch.setattr(gw.sys, "platform", "win32")- import sys as _sys-- _sys.modules.pop("win32service", None)- _sys.modules.pop("win32serviceutil", None)-- import types-- mod = types.ModuleType("win32service")- mod.SERVICE_AUTO_START = 2- mod.SERVICE_DEMAND_START = 3- util_mod = types.ModuleType("win32serviceutil")-- def boom(name):- raise OSError("not installed")-- util_mod.QueryServiceStatus = boom- monkeypatch.setitem(_sys.modules, "win32service", mod)- monkeypatch.setitem(_sys.modules, "win32serviceutil", util_mod)-- gw._windows_scm_service_command(None)- out = capfd.readouterr().out- assert "not installed" in out---def test_service_on_configures_starts_persists(monkeypatch, capfd):- monkeypatch.setattr(gw.sys, "platform", "win32")- calls = _fake_scm(monkeypatch, installed=True, running=True)- saved = {}- monkeypatch.setattr("cli.save_config_value", lambda k, v: saved.update({k: v}))-- gw._windows_scm_service_command("on")- assert ("config", 2) in calls # SERVICE_AUTO_START- assert ("start",) in calls- assert saved == {"gateway.service": True}- assert "automatic at logon" in capfd.readouterr().out---def test_service_off_demand_stops_persists(monkeypatch, capfd):- monkeypatch.setattr(gw.sys, "platform", "win32")- calls = _fake_scm(monkeypatch, installed=True, running=True)- saved = {}- monkeypatch.setattr("cli.save_config_value", lambda k, v: saved.update({k: v}))-- gw._windows_scm_service_command("off")- assert ("config", 3) in calls # SERVICE_DEMAND_START- assert ("stop",) in calls- assert saved == {"gateway.service": False}---def test_service_unknown_action_is_an_error(monkeypatch, capfd):- monkeypatch.setattr(gw.sys, "platform", "win32")- calls = _fake_scm(monkeypatch, installed=True, running=True)- monkeypatch.setattr("cli.save_config_value", lambda k, v: None)- gw._windows_scm_service_command("dance")- assert "Unknown service action" in capfd.readouterr().out---# ── the updater's SCM restart branch ─────────────────────────────────---def test_updater_scm_restart_gated_on_running_service(monkeypatch):- """Sealed + HermesGateway RUNNING → Restart-Service, True (skip the- detached watcher); any other shape → False (ordinary paths)."""- monkeypatch.setattr(gw.sys, "platform", "win32")- calls = _fake_scm(monkeypatch, installed=True, running=True)-- import importlib- import sys-- sys.modules.pop("pm.ensure", None)- pm_ensure = importlib.import_module("pm.ensure")-- monkeypatch.setattr(pm_ensure, "sealed", lambda: True)-- assert gw._try_scm_service_restart() is True- assert ("restart",) in calls---def test_updater_scm_restart_false_when_not_sealed(monkeypatch):- monkeypatch.setattr(gw.sys, "platform", "win32")- calls = _fake_scm(monkeypatch, installed=True, running=True)- import importlib-- pm_ensure = importlib.import_module("pm.ensure")- monkeypatch.setattr(pm_ensure, "sealed", lambda: False)- assert gw._try_scm_service_restart() is False- assert calls == [] # no SCM touch---def test_updater_scm_restart_false_when_service_stopped(monkeypatch):- monkeypatch.setattr(gw.sys, "platform", "win32")- calls = _fake_scm(monkeypatch, installed=True, running=False)- import importlib-- pm_ensure = importlib.import_module("pm.ensure")- monkeypatch.setattr(pm_ensure, "sealed", lambda: True)- assert gw._try_scm_service_restart() is False---def test_updater_scm_restart_false_on_posix(monkeypatch):- monkeypatch.setattr(gw.sys, "platform", "linux")- assert gw._try_scm_service_restart() is Falsediff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.pyindex a548ac12c6a..a9b5ce81bb8 100644--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@ -142,6 +142,7 @@ def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):root = _make_desktop_tree(tmp_path)+ monkeypatch.setattr(main_desktop, "_ensure_desktop_exe_launchable", lambda _root, exe: (exe, False))desktop_dir = root / "apps" / "desktop"monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)packaged_exe = _make_packaged_executable(root, monkeypatch)@@ -150,7 +151,7 @@ def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):pack_ok = subprocess.CompletedProcess(["npm", "run", "pack"], 0)launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=install_ok) as mock_install, \patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \@@ -195,37 +196,33 @@ def test_gui_install_env_prepends_managed_node_on_bare_path(tmp_path, monkeypatcimport osroot = _make_desktop_tree(tmp_path)+ monkeypatch.setattr(main_desktop, "_ensure_desktop_exe_launchable", lambda _root, exe: (exe, False))monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)_make_packaged_executable(root, monkeypatch)- # A pm-installed Node/npm on disk so with_hermes_node_path() actually- # prepends the store dirs.+ # Record tool identities matching the actual pin table; path-only legacy+ # facts are intentionally not eligible for runtime activation.+ from pm.ensure import _lockfile+ from pm.lock import Facts+ from pm.registry import get_package+ from pm.store import current_targethome = tmp_path / "hermes-home"store_root = home / "tools"- node_entry = store_root / "node-v22.0.0"- npm_entry = store_root / "npm-9.0.0" / "bin"- node_entry.mkdir(parents=True)- npm_entry.mkdir(parents=True)- (store_root / "facts.json").write_text(- json.dumps(- {- "schema": 1,- "packages": {- "node": {- "entry": "node-v22.0.0",- "version": "22.0.0",- "env": {"PATH": ["{{store}}/node-v22.0.0"]},- },- "npm": {- "entry": "npm-9.0.0",- "version": "9.0.0",- "env": {"PATH": ["{{store}}/npm-9.0.0/bin"]},- },- },- }- ),- encoding="utf-8",- )+ lock = _lockfile()+ target = current_target()+ dirs = {}+ for name in ("node", "npm"):+ package = get_package(name)+ entry_name = package.store_entry(lock.version(name), target)+ entry = store_root / entry_name+ tool_dir = entry / "bin" if name == "npm" else entry+ tool_dir.mkdir(parents=True)+ dirs[name] = tool_dir+ Facts(store_root / "facts.json").record(+ name, lock.version(name), entry_name, {"PATH": [str(tool_dir)]}, store_root,+ target=target, artifacts=[a["sha256"] for a in lock.artifacts(name, target)],+ )+ node_entry, npm_entry = dirs["node"], dirs["npm"]monkeypatch.setenv("HERMES_HOME", str(home))monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store_root))# Simulate the stripped PATH the desktop updater chain hands us.@@ -1478,6 +1475,7 @@ def test_gui_failed_pack_leaves_previous_app_untouched(tmp_path, monkeypatch, cadef test_gui_successful_pack_swaps_new_app_into_release(tmp_path, monkeypatch):root = _make_desktop_tree(tmp_path)+ monkeypatch.setattr(main_desktop, "_ensure_desktop_exe_launchable", lambda _root, exe: (exe, False))desktop_dir = root / "apps" / "desktop"monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)live_exe = _make_packaged_executable(root, monkeypatch)diff --git a/tests/hermes_cli/test_install_cua_driver.py b/tests/hermes_cli/test_install_cua_driver.pyindex a05dd5f9476..8e7c54298b3 100644--- a/tests/hermes_cli/test_install_cua_driver.py+++ b/tests/hermes_cli/test_install_cua_driver.py@@ -30,6 +30,51 @@ from unittest.mock import patchimport pytest+def test_pip_install_drives_pm_uv_with_composed_env(tmp_path, monkeypatch):+ """``tools_config_cua._pip_install`` drives uv through ``pm.ensure.uv`` with+ ``realize=True, venv=<live venv root>`` and hands the bridge's COMPOSED env+ (not a hand-built map) to the subprocess boundary. When pm cannot supply uv,+ it degrades to the pre-existing pip ladder."""+ import importlib+ import subprocess+ from pathlib import Path++ from hermes_cli import tools_config_cua as cua++ pm_ensure = importlib.import_module("pm.ensure")++ stub_uv = tmp_path / "uv-stub.exe"+ stub_uv.write_text("")+ composed_env = {"VIRTUAL_ENV": str(tmp_path / "venv")}+ seen = {}++ def fake_run_text(cmd, **kwargs):+ seen["cmd"] = list(cmd)+ seen["env"] = kwargs.get("env")+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(cua, "_run_text", fake_run_text)++ calls = []++ def fake_pm_uv(*, realize, venv):+ calls.append({"realize": realize, "venv": venv})+ return str(stub_uv), dict(composed_env)++ monkeypatch.setattr(pm_ensure, "uv", fake_pm_uv)+ result = cua._pip_install(["cua-driver"])+ assert result.returncode == 0+ assert calls == [{"realize": True, "venv": Path(sys.executable).parent.parent}]+ assert seen["cmd"] == [str(stub_uv), "pip", "install", "cua-driver"]+ assert seen["env"] == composed_env++ # uv unavailable: probe --version succeeds via the stub, install goes to pip.+ monkeypatch.setattr(pm_ensure, "uv", lambda **kw: (None, {}))+ result = cua._pip_install(["cua-driver"])+ assert result.returncode == 0+ assert seen["cmd"] == [sys.executable, "-m", "pip", "install", "cua-driver"]++def _runtime_manifest(version="0.20.0", *, omit=None):omit = set(omit or ())required = {diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.pyindex b8ef26f8634..b41d66813cf 100644--- a/tests/hermes_cli/test_kanban_db.py+++ b/tests/hermes_cli/test_kanban_db.py@@ -1200,8 +1200,8 @@ def test_resolve_hermes_argv_falls_back_to_module_form_when_no_path_shim(monkeypmonkeypatch.setattr(shutil, "which", lambda name: None)# On Windows _resolve_hermes_argv() uses _safe_which_no_cwd() instead of# shutil.which — mock that too so the "no shim" path is the one tested.- monkeypatch.setattr(kb, "_safe_which_no_cwd", lambda name: None)- argv = kb._resolve_hermes_argv()+ monkeypatch.setattr(kbd, "_safe_which_no_cwd", lambda name: None)+ argv = kbd._resolve_hermes_argv()argv = kbd._resolve_hermes_argv()assert argv == [sys.executable, "-m", "hermes_cli.main"]diff --git a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py b/tests/hermes_cli/test_kanban_gateway_restart_handoff.pyindex 3b7bd85cfc1..d7e3c316638 100644--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py@@ -49,7 +49,7 @@ def worker_setup(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path,return workspace, task[email protected]_only[email protected]("linux")def test_managed_gateway_worker_is_spawned_in_restart_safe_scope(worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch) -> None:@@ -90,7 +90,7 @@ def test_managed_gateway_worker_is_spawned_in_restart_safe_scope(assert "ANTHROPIC_API_KEY" not in captured_env[email protected]_only[email protected]("linux")def test_managed_gateway_worker_spawn_fails_closed_without_scope(worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch) -> None:@@ -106,7 +106,7 @@ def test_managed_gateway_worker_spawn_fails_closed_without_scope(assert popen_calls == [][email protected]_only[email protected]("linux")def test_managed_gateway_scope_builder_fails_closed_if_binary_disappears(worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch) -> None:@@ -141,7 +141,7 @@ def test_standalone_dispatcher_keeps_direct_worker_spawn(assert captured_cmd[:3] == ["hermes", "-p", "coder"][email protected]_only[email protected]("linux")def test_real_user_systemd_scope_preserves_worker_context(worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/hermes_cli/test_kanban_transfer.py b/tests/hermes_cli/test_kanban_transfer.pyindex c5fb70553f9..9e437d8ed24 100644--- a/tests/hermes_cli/test_kanban_transfer.py+++ b/tests/hermes_cli/test_kanban_transfer.py@@ -319,15 +319,12 @@ def test_traversal_members_are_rejected(member):def test_extract_refuses_a_symlink_member(tmp_path):- payload = tmp_path / "payload"- payload.mkdir()- (payload / "real.txt").write_text("fine")- link = payload / "link"- link.symlink_to("/etc/passwd")-archive = tmp_path / "evil.tar.gz"with tarfile.open(archive, "w:gz") as tf:- tf.add(payload, arcname="payload")+ link = tarfile.TarInfo("payload/link")+ link.type = tarfile.SYMTYPE+ link.linkname = "/etc/passwd"+ tf.addfile(link)with pytest.raises(ValueError, match="Unsupported archive member"):safe_extract_targz(archive, tmp_path / "out")diff --git a/tests/hermes_cli/test_launcher_runtime_selection.py b/tests/hermes_cli/test_launcher_runtime_selection.pynew file mode 100644index 00000000000..84bbdc214b9--- /dev/null+++ b/tests/hermes_cli/test_launcher_runtime_selection.py@@ -0,0 +1,59 @@+"""Launch-time dependency selection survives a change after launcher minting."""+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++from hermes_cli import _launchers+from hermes_cli.runtime_paths import install_state_dir, site_packages++[email protected]("windows")+def test_minted_launcher_reads_current_selection_and_editable_members(tmp_path, monkeypatch):+ from hermes_cli import runtime_paths+ import hermes_constants++ root = tmp_path / "repo"+ package = root / "hermes_cli"+ package.mkdir(parents=True)+ (package / "__init__.py").write_text("")+ # Real selection code, with a fixture entry point rather than a live CLI.+ (package / "runtime_paths.py").write_bytes(Path(runtime_paths.__file__).read_bytes())+ (root / "hermes_constants.py").write_bytes(Path(hermes_constants.__file__).read_bytes())+ (root / "hermes_bootstrap.py").write_text(+ "from pathlib import Path\nfrom hermes_cli.runtime_paths import activate_dependencies\n"+ "activate_dependencies(Path(__file__).resolve().parent)\n"+ )+ (package / "main.py").write_text(+ "import selection_probe, editable_probe\n"+ "def main():\n print(selection_probe.VALUE, editable_probe.VALUE)\n return 0\n"+ )+ base = site_packages(root / "venv")+ base.mkdir(parents=True)+ (base / "selection_probe.py").write_text("VALUE = 'base'\n")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ state = install_state_dir(root)+ out = tmp_path / "bin"+ out.mkdir()+ launcher = _launchers.mint_launcher("hermes", root, out, Path(sys.executable), base)+ assert launcher is not None++ selected = state / "environments" / "selected" / "venv"+ site = site_packages(selected)+ site.mkdir(parents=True)+ (selected / "pyvenv.cfg").write_text("home = fixture\n")+ (site / "selection_probe.py").write_text("VALUE = 'selected'\n")+ editable = tmp_path / "editable"+ editable.mkdir()+ (editable / "editable_probe.py").write_text("VALUE = 'editable'\n")+ (site / "member.pth").write_text(str(editable) + "\n")+ (state / "facts.json").write_text(json.dumps({"packages": {"venv": {"environment": str(selected)}}}))+ env = dict(os.environ)+ env.pop("PYTHONPATH", None)+ env.pop("PYTHONHOME", None)+ result = subprocess.run([str(launcher)], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout.strip() == "selected editable"diff --git a/tests/hermes_cli/test_lazy_refresh_venv_repair.py b/tests/hermes_cli/test_lazy_refresh_venv_repair.pyindex 21387cb10ca..698b3e060c5 100644--- a/tests/hermes_cli/test_lazy_refresh_venv_repair.py+++ b/tests/hermes_cli/test_lazy_refresh_venv_repair.py@@ -90,55 +90,23 @@ def test_repair_runs_force_reinstall_with_pyproject_pins(assert detect_calls["count"] == 1-def test_refresh_repairs_venv_after_lazy_failure(tmp_path, monkeypatch, capsys):- import tools.lazy_deps as lazy_deps_mod-- monkeypatch.setattr(lazy_deps_mod, "active_features", lambda: ["platform.matrix"])- monkeypatch.setattr(- lazy_deps_mod,- "refresh_active_features",- lambda **kw: {"platform.matrix": "failed: pip install failed"},- )-- repair_calls: list[list[str]] = []-- def fake_repair(prefix, packages, *, env=None):- repair_calls.append(packages)- return True-- monkeypatch.setattr(main_install_repair, "_detect_broken_lazy_refresh_imports", lambda *a, **k: ["PyYAML"])- monkeypatch.setattr(main_install_repair, "_repair_broken_lazy_refresh_imports", fake_repair)-- ok = m._refresh_active_lazy_features(["uv", "pip"], env={"VIRTUAL_ENV": str(tmp_path)})- out = capsys.readouterr().out-- assert ok is True- assert repair_calls == [["PyYAML"]]- assert "Venv repair succeeded" in out- assert "import probes" in out- assert "Backends keep their previously-installed version" not in out+def test_refresh_failure_reports_pm_error(monkeypatch, capsys):+ import importlib+ ensure = importlib.import_module("pm.ensure")+ def fail(*args, **kwargs):+ raise RuntimeError("resolution failed")+ monkeypatch.setattr(ensure, "sync_venv", fail)+ assert m._refresh_active_lazy_features(["matrix"]) is False+ assert "resolution failed" in capsys.readouterr().outdef test_refresh_uses_pre_rebuild_snapshot_when_provided(monkeypatch):- """Replacement runtimes must not re-detect features after packages vanish."""- import tools.lazy_deps as lazy_deps_mod-- monkeypatch.setattr(- lazy_deps_mod,- "active_features",- lambda: pytest.fail("post-rebuild detection must not run"),- )- restored = []- monkeypatch.setattr(- lazy_deps_mod,- "restore_features",- lambda features: restored.append(features) or {"platform.telegram": "restored"},- )-- assert m._refresh_active_lazy_features(- ["uv", "pip"], features=["platform.telegram"]- ) is True- assert restored == [["platform.telegram"]]+ import importlib+ ensure = importlib.import_module("pm.ensure")+ calls = []+ monkeypatch.setattr(ensure, "sync_venv", lambda extras, **kwargs: calls.append((extras, kwargs)))+ assert m._refresh_active_lazy_features(["telegram"]) is True+ assert calls == [(["telegram"], {"explicit": True})]def test_capture_active_tool_dependencies_uses_tools_status_probes(monkeypatch):@@ -153,29 +121,6 @@ def test_capture_active_tool_dependencies_uses_tools_status_probes(monkeypatch):assert m._capture_active_tool_dependencies() == ["ddgs", "langfuse"]-def test_restore_active_tool_dependencies_uses_static_allowlist(monkeypatch):- calls = []- monkeypatch.setattr(- m,- "_run_install_with_heartbeat",- lambda cmd, *, env=None: calls.append((cmd, env)),- )- monkeypatch.setattr(- hermes_cli_main_install_repair,- "_run_package_only_install",- lambda cmd, *, env=None: calls.append((cmd, env)),- )-- env = {"VIRTUAL_ENV": "/tmp/venv"}- m._restore_active_tool_dependencies(- ["langfuse", "not-allowlisted"],- ["uv", "pip"],- env=env,- )-- assert calls == [(["uv", "pip", "install", "langfuse", "--quiet"], env)]--def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(tmp_path, monkeypatch):@@ -186,9 +131,8 @@ def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(snapshot = ["platform.telegram"]tool_snapshot = ["langfuse"]refresh_calls = []- restore_calls = []- class RestoreReached(Exception):+ class SyncReached(Exception):passdef fake_run(cmd, **kwargs):@@ -201,9 +145,9 @@ def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(def fake_sync(extras=None, *, explicit=False):refresh_calls.append((sorted(extras or []), explicit))- def fake_restore(dependencies, prefix, *, env=None):- restore_calls.append((dependencies, prefix, env))- raise RestoreReached+ def fake_sync_raises(extras=None, *, explicit=False):+ refresh_calls.append((sorted(extras or []), explicit))+ raise SyncReachedmonkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)monkeypatch.setattr(m, "_capture_active_lazy_features", lambda: snapshot.copy())@@ -227,7 +171,7 @@ def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(monkeypatch.setattr(m, "_install_python_dependencies_with_optional_fallback", lambda *a, **k: None)- monkeypatch.setattr(m, "_restore_active_tool_dependencies", fake_restore)+ # _restore_active_tool_dependencies retired (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(m.subprocess, "run", fake_run)import pmfrom pm.packages import uv_env as _uv_env@@ -239,7 +183,7 @@ def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(return "uv", envmonkeypatch.setattr(pm, "uv", fake_uv)- monkeypatch.setattr(pm, "sync_venv", fake_sync)+ monkeypatch.setattr(pm, "sync_venv", fake_sync_raises)args = SimpleNamespace(yes=True,@@ -249,31 +193,10 @@ def test_cmd_update_captures_and_propagates_pre_rebuild_snapshot(backup=False,branch=None,)- with pytest.raises(RestoreReached):+ with pytest.raises(SyncReached):update_cmd._cmd_update_impl(args, gateway_mode=False)# The repair phase is one explicit pm sync carrying the pre-rebuild- # extras snapshot; tool-dep restore still runs against the managed env- # (#83914: UV vars stripped, VIRTUAL_ENV pointed at the install's venv).- from pm.packages import uv_env as managed_python_env-- expected_env = managed_python_env()- expected_env["VIRTUAL_ENV"] = str(tmp_path / "venv")+ # extras snapshot. Tool-dep pip restore is retired (pm-clean-audit-49945b1402+ # final-gates item 9): the staged generation owns its dependency set.assert refresh_calls == [(sorted(["all", *snapshot]), True)]- assert restore_calls == [- (- tool_snapshot,- ["uv", "pip"],- expected_env,- )- ]----------diff --git a/tests/hermes_cli/test_local_models_routes.py b/tests/hermes_cli/test_local_models_routes.pyindex 79ebc2b4002..8c8863bd26e 100644--- a/tests/hermes_cli/test_local_models_routes.py+++ b/tests/hermes_cli/test_local_models_routes.py@@ -14,6 +14,10 @@ from pathlib import Pathimport pytestfrom fastapi.testclient import TestClient+# The real loopback range server (shared with tests/pm): importing the+# fixture name at module scope registers it for these tests too.+from tests.pm._range_server import dl_server, url as _srv_url # noqa: F401+@pytest.fixturedef client(tmp_path, monkeypatch):@@ -433,3 +437,267 @@ def test_download_pause_reaches_paused_status(client, monkeypatch):breaktime.sleep(0.05)assert status is not None and status["status"] == "paused"+++# ── pause / resume against a real loopback range server ──────+++def _pin_budget(monkeypatch):+ """Deterministic variant selection: a generous GPU budget so the+ download path (not selection) is what the test exercises."""+ from hermes_cli.local_runtime.estimator import HardwareBudget++ budget = HardwareBudget(usable_vram_bytes=64 << 30,+ total_device_bytes=64 << 30,+ ram_available_bytes=64 << 30)+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",+ lambda **kw: budget)+++def _serve_plan(monkeypatch, dl_server, tmp_partials, bodies):+ """Point the download plan at the real loopback range server: one+ served body per plan file, dests under the temp models dir, partials+ under a temp dir (never the machine's cache)."""+ from pm import paths as pm_paths+ from tests.pm._range_server import RangeHandler+ from hermes_cli.local_runtime.bootstrap import models_dir+ from hermes_cli.web_routers import local_models as lm++ RangeHandler.chunk = 128 * 1024+ RangeHandler.slow_per_chunk = 0.2+ RangeHandler.payloads = {}+ plan = []+ for name, body in bodies.items():+ RangeHandler.payloads[f"/{name}"] = body+ dest = models_dir() / f"{name}.gguf"+ plan.append((_srv_url(dl_server, f"/{name}"), dest, len(body)))+ monkeypatch.setattr(pm_paths, "partials_root", lambda: Path(tmp_partials))+ monkeypatch.setattr(lm, "_download_plan", lambda entry, variant: plan)+ monkeypatch.setattr(+ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",+ lambda: False)+ return plan+++def _poll_job(client, job_id, deadline_s=15, until=("paused", "done", "error")):+ deadline = time.time() + deadline_s+ status = None+ while time.time() < deadline:+ status = client.get(f"/api/local-models/jobs/{job_id}").json()+ if status["status"] in until:+ return status+ time.sleep(0.03)+ return status+++def _pause_when_flowing(client, job_id):+ """Pause once bytes are actually moving, so the pause lands mid-flight+ (the downloader stops between chunks) rather than before the probe."""+ deadline = time.time() + 15+ while time.time() < deadline:+ status = client.get(f"/api/local-models/jobs/{job_id}").json()+ if (status.get("done_bytes") or 0) > 0:+ break+ time.sleep(0.03)+ deadline = time.time() + 15+ while time.time() < deadline:+ pr = client.post("/api/local-models/download/pause",+ json={"job_id": job_id})+ if pr.status_code == 200 and pr.json().get("paused") is True:+ return+ time.sleep(0.03)+ raise AssertionError("pause never reached the live download handle")+++_BIG_BODY = bytes(range(256)) * (8 * 1024 * 1024 // 256) # 8 MiB, deterministic+++def test_download_pause_parks_job_with_handle_and_partials(+ client, monkeypatch, dl_server, tmp_path):+ """Mid-flight pause: the job parks as 'paused' (never 'done'/'error'),+ the resume handle stays registered, and the downloader's partial+ state survives on disk for the later resume."""+ _pin_budget(monkeypatch)+ from hermes_cli.local_runtime.catalog import CATALOG+ from hermes_cli.web_routers import local_models as lm++ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",+ {"PartA": _BIG_BODY})++ job_id = client.post("/api/local-models/download",+ json={"model_id": CATALOG[0].id}).json()["job_id"]+ _pause_when_flowing(client, job_id)++ status = _poll_job(client, job_id)+ assert status["status"] == "paused", status+ assert status["error"] is None+ # The resume handle survives the pause — the route can pick it up.+ assert lm._RUNNING[job_id].get("resume") is not None+ # Partial state is the downloader's own and must be intact.+ partials = list(Path(tmp_path / "partials").glob("*.part"))+ assert partials and any(p.stat().st_size > 0 for p in partials)+++def test_download_resume_completes_bytes(client, monkeypatch, dl_server,+ tmp_path):+ """Resume after a mid-flight pause finishes the remaining ranges and+ stages the exact file the server serves."""+ _pin_budget(monkeypatch)+ from tests.pm._range_server import RangeHandler+ from hermes_cli.local_runtime.bootstrap import models_dir+ from hermes_cli.local_runtime.catalog import CATALOG+ from hermes_cli.web_routers import local_models as lm++ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",+ {"PartA": _BIG_BODY})++ job_id = client.post("/api/local-models/download",+ json={"model_id": CATALOG[0].id}).json()["job_id"]+ _pause_when_flowing(client, job_id)+ status = _poll_job(client, job_id)+ assert status["status"] == "paused", status++ RangeHandler.slow_per_chunk = 0.0 # let the resume run at full speed+ assert client.post("/api/local-models/download/resume",+ json={"job_id": job_id}).json()["resumed"] is True++ status = _poll_job(client, job_id, until=("done", "error"))+ assert status["status"] == "done", status+ assert (models_dir() / "PartA.gguf").read_bytes() == _BIG_BODY+ # Finished jobs release their handles again.+ assert job_id not in lm._RUNNING+++def test_repeated_resume_never_spawns_concurrent_writers(+ client, monkeypatch, dl_server, tmp_path):+ """Spamming resume while a worker is already running must not build a+ second Download — one writer per job, ever."""+ import threading as _threading++ _pin_budget(monkeypatch)+ from tests.pm._range_server import RangeHandler+ from hermes_cli.local_runtime.catalog import CATALOG+ from hermes_cli.web_routers import local_models as lm++ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",+ {"PartA": _BIG_BODY})++ job_id = client.post("/api/local-models/download",+ json={"model_id": CATALOG[0].id}).json()["job_id"]+ _pause_when_flowing(client, job_id)+ assert _poll_job(client, job_id)["status"] == "paused"++ built = []+ started = _threading.Event()+ release = _threading.Event()+ real_download = lm.Download++ class _Counting(real_download):+ def __init__(self, *a, **kw):+ super().__init__(*a, **kw)+ built.append(self)++ def run(self, *a, **kw):+ started.set()+ assert release.wait(timeout=15)+ return super().run(*a, **kw)++ monkeypatch.setattr(lm, "Download", _Counting)++ try:+ client.post("/api/local-models/download/resume", json={"job_id": job_id})+ assert started.wait(timeout=15), "resume never built a Download"+ # Keep the real downloader parked while repeated requests contend.+ for _ in range(2):+ response = client.post("/api/local-models/download/resume", json={"job_id": job_id})+ assert response.json()["resumed"] is False+ assert len(built) == 1+ finally:+ RangeHandler.slow_per_chunk = 0.0+ release.set()+ status = _poll_job(client, job_id, until=("done", "error"))+ assert status["status"] == "done", status+++def test_quickstart_pause_stops_the_sequence(client, monkeypatch, dl_server,+ tmp_path):+ """A quickstart paused mid-download must stop dead: no second file, no+ server start, no default assignment — the job parks for a resume, and+ its resume handle stays registered."""+ _pin_budget(monkeypatch)+ from tests.pm._range_server import RangeHandler+ from hermes_cli.web_routers import local_models as lm++ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",+ {"QsPartA": _BIG_BODY, "QsPartB": _BIG_BODY})+ monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags",+ lambda: ["b99999"]) # runtime leg already satisfied+ monkeypatch.setattr(lm, "_runtime_target",+ lambda requested=None: ("b1", "cpu"))++ calls = {"server": 0, "assign": 0}++ def _fail_server(*a, **kw):+ calls["server"] += 1+ raise RuntimeError("server must not start after a pause")++ monkeypatch.setattr(+ "hermes_cli.local_runtime.bootstrap.ensure_local_runtime", _fail_server)++ class _RecordLate:+ def __call__(self, *a, **kw):+ calls["assign"] += 1++ monkeypatch.setattr(lm.web_deps, "late", _RecordLate())++ from hermes_cli.local_runtime.catalog import CATALOG++ job_id = client.post("/api/local-models/quickstart",+ json={"model_id": CATALOG[0].id}).json()["job_id"]+ _pause_when_flowing(client, job_id)++ status = _poll_job(client, job_id)+ assert status["status"] == "paused", status+ assert calls == {"server": 0, "assign": 0}+ # The second plan file must never have been touched after the pause.+ from hermes_cli.local_runtime.bootstrap import models_dir++ assert not (models_dir() / "QsPartB.gguf").exists()+ assert lm._RUNNING[job_id].get("resume") is not None+ assert lm._QUICKSTART_LOCK.locked(), "paused quickstart must retain setup ownership"++ def activate(*args, **kwargs):+ calls["server"] += 1++ def assign(*args, **kwargs):+ calls["assign"] += 1++ monkeypatch.setattr(lm, "_ensure_server", activate)+ monkeypatch.setattr(lm, "_assign_default", assign)+ RangeHandler.slow_per_chunk = 0+ assert client.post("/api/local-models/quickstart", json={"model_id": CATALOG[0].id}).status_code == 409+ assert client.post("/api/local-models/download/resume", json={"job_id": job_id}).json()["resumed"]+ status = _poll_job(client, job_id, until=("done", "error"))+ assert status["status"] == "done", status+ assert calls == {"server": 1, "assign": 1}+ assert (models_dir() / "QsPartA.gguf").read_bytes() == _BIG_BODY+ assert (models_dir() / "QsPartB.gguf").read_bytes() == _BIG_BODY+ assert job_id not in lm._RUNNING+ assert not lm._QUICKSTART_LOCK.locked()+++def test_download_failure_releases_resume_handle(client, monkeypatch):+ from hermes_cli.local_runtime.catalog import CATALOG+ from hermes_cli.web_routers import local_models as lm++ _pin_budget(monkeypatch)+ monkeypatch.setattr(lm, "_download_plan", lambda *args: [])++ def fail(*args):+ raise OSError("download failed")++ monkeypatch.setattr(lm, "_download_job", fail)+ job_id = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id}).json()["job_id"]+ status = _poll_job(client, job_id)+ assert status["status"] == "error", status+ assert job_id not in lm._RUNNINGdiff --git a/tests/hermes_cli/test_local_quickstart.py b/tests/hermes_cli/test_local_quickstart.pyindex f6a8f56193a..f4d90435db4 100644--- a/tests/hermes_cli/test_local_quickstart.py+++ b/tests/hermes_cli/test_local_quickstart.py@@ -65,13 +65,14 @@ def test_quickstart_runs_all_three_legs(client, monkeypatch, tmp_path):lambda tag, backend, progress=None: calls.append("install"))# Leg 2: nothing staged; the download writes the files the plan names.- def _fake_download(url, dest, job, *, base_done=0, keep_totals=False):- Path(dest).parent.mkdir(parents=True, exist_ok=True)- Path(dest).write_bytes(b"GGUF\x00")+ def _fake_download(job, plan):+ for _url, dest, _size in plan:+ Path(dest).parent.mkdir(parents=True, exist_ok=True)+ Path(dest).write_bytes(b"GGUF\x00")calls.append("download")monkeypatch.setattr(- "hermes_cli.web_routers.local_models.download_file", _fake_download)+ "hermes_cli.web_routers.local_models._download_job", _fake_download)# Leg 3: activation — stub the server start and the model assignment.monkeypatch.setattr(@@ -80,11 +81,9 @@ def test_quickstart_runs_all_three_legs(client, monkeypatch, tmp_path):monkeypatch.setattr("hermes_cli.web_routers.local_models._state_endpoint",lambda: {"base_url": "http://127.0.0.1:1/v1", "api_key": "k"})- from hermes_cli import web_deps-monkeypatch.setattr(- web_deps, "late",- lambda name: (lambda *a, **k: calls.append("assign")))+ "hermes_cli.web_routers.local_models._assign_default",+ lambda *a, **k: calls.append("assign"))r = client.post("/api/local-models/quickstart", json={})assert r.status_code == 200@@ -125,7 +124,7 @@ def test_quickstart_skips_satisfied_legs(client, monkeypatch):monkeypatch.setattr("hermes_cli.local_runtime.bootstrap.staged_model_ids", lambda: all_ids)monkeypatch.setattr(- "hermes_cli.web_routers.local_models.download_file",+ "hermes_cli.web_routers.local_models._download_job",lambda *a, **k: calls.append("download"))monkeypatch.setattr("hermes_cli.local_runtime.bootstrap.ensure_local_runtime",@@ -133,11 +132,9 @@ def test_quickstart_skips_satisfied_legs(client, monkeypatch):monkeypatch.setattr("hermes_cli.web_routers.local_models._state_endpoint",lambda: {"base_url": "http://127.0.0.1:1/v1", "api_key": "k"})- from hermes_cli import web_deps-monkeypatch.setattr(- web_deps, "late",- lambda name: (lambda *a, **k: calls.append("assign")))+ "hermes_cli.web_routers.local_models._assign_default",+ lambda *a, **k: calls.append("assign"))r = client.post("/api/local-models/quickstart", json={})assert r.status_code == 200diff --git a/tests/hermes_cli/test_nous_subscription.py b/tests/hermes_cli/test_nous_subscription.pyindex 7901daa1759..b9435d27dde 100644--- a/tests/hermes_cli/test_nous_subscription.py+++ b/tests/hermes_cli/test_nous_subscription.py@@ -481,7 +481,7 @@ def test_has_agent_browser_true_for_npx_only_resolution(monkeypatch):calls.append({"validate": validate})return "npx agent-browser"- monkeypatch.setattr(browser_tool, "_find_agent_browser", fake_find_agent_browser)+ monkeypatch.setattr(bt_install, "_find_agent_browser", fake_find_agent_browser)assert ns._has_agent_browser() is True# A readiness probe must resolve without spawning the daemon.diff --git a/tests/hermes_cli/test_plugin_admission_transaction.py b/tests/hermes_cli/test_plugin_admission_transaction.pynew file mode 100644index 00000000000..9ede2f1d411--- /dev/null+++ b/tests/hermes_cli/test_plugin_admission_transaction.py@@ -0,0 +1,21 @@+"""Installing a disabled plugin must not alter the selected dependency environment."""+from unittest.mock import Mock++import pytest++from hermes_cli import plugins_cmd as plugins+++def test_install_disabled_does_not_prepare_dependencies(tmp_path, monkeypatch):+ target = tmp_path / "plug"+ target.mkdir()+ manifest = {"name": "plug", "python_dependencies": ["new-package>=1,<2"]}+ monkeypatch.setattr(plugins, "_install_plugin_core", lambda *a, **k: (target, manifest, "plug"))+ monkeypatch.setattr(plugins, "_looks_like_plugin_dir", lambda *_: True)+ monkeypatch.setattr(plugins, "_prompt_plugin_env_vars", lambda *a: None)+ monkeypatch.setattr(plugins, "_display_after_install", lambda *a: None)+ monkeypatch.setattr(plugins, "_declared_capabilities_from_manifest", lambda *a: [])+ def forbidden(*a, **k):+ raise AssertionError("disabled installation changed dependencies")+ monkeypatch.setattr(plugins, "_install_plugin_python_deps", forbidden)+ plugins.cmd_install("https://example.invalid/owner/plug", enable=False)diff --git a/tests/hermes_cli/test_plugins_admission_setter.py b/tests/hermes_cli/test_plugins_admission_setter.pynew file mode 100644index 00000000000..2b035227d90--- /dev/null+++ b/tests/hermes_cli/test_plugins_admission_setter.py@@ -0,0 +1,276 @@+"""C13 enable admission: every UI path's proposed enabled/disabled sets go+through ONE authority — the candidate union resolves against the active+environment and the config commits inside pm's single locked transaction+(sync's before_publish hook). Refusal (dep conflict OR config-write+failure) publishes nothing: previous config bytes and previous environment+stay exactly in place. Real temp HERMES_HOME — no live user writes."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++import hermes_cli.plugins_cmd as pc+from hermes_cli import plugins_admission as adm+++class _Console:+ def __init__(self):+ self.lines: list[str] = []++ def print(self, *args, **kwargs):+ for arg in args:+ self.lines.append(str(arg))+++def plugin_home(tmp_path, monkeypatch):+ """Isolated HERMES_HOME: config.yaml, plugins/, facts all under tmp."""+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "plugins").mkdir()+ return home+++def _enabled_set(home) -> set:+ from hermes_cli.config import load_config++ cfg = load_config()+ return set(((cfg.get("plugins") or {}).get("enabled")) or [])+++def _write_sets(home, enabled=(), disabled=()):+ pc._write_config_value("plugins", "enabled", sorted(enabled))+ pc._write_config_value("plugins", "disabled", sorted(disabled))+++def sync_calls(monkeypatch):+ """pm.ensure is shadowed by a pm.ensure() function — patch the MODULE."""+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")+ ensure = sys.modules["pm.ensure"]+ calls = []++ def _sync(extras=None, *, explicit=False, plugin_dirs=None, before_publish=None):+ calls.append(list(plugin_dirs or []))+ if before_publish is not None:+ before_publish() # same contract: config commits under the sync++ monkeypatch.setattr(ensure, "sync_venv", _sync)+ return calls+++def _dep_plugin(home) -> Path:+ d = home / "plugins" / "dep-plug"+ d.mkdir(exist_ok=True)+ (d / "plugin.yaml").write_text(+ 'name: dep-plug\npython_dependencies:\n - "somepkg>=1"\n', encoding="utf-8"+ )+ return d+++def _entry(dir_path: Path):+ return ("dep-plug", "1.0", "test plugin", "user", dir_path, "dep-plug")+++def _discovery(monkeypatch, *entries):+ monkeypatch.setattr(pc, "_discover_all_plugins", lambda: list(entries))+ monkeypatch.setattr(pc, "_declared_capabilities_for_key", lambda key: [])+++def _refusing_sync(monkeypatch, message="uv lock exited 1: unsatisfiable"):+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")+ ensure = sys.modules["pm.ensure"]++ def _boom(*a, **k):+ raise RuntimeError(message)++ monkeypatch.setattr(ensure, "sync_venv", _boom)+++# ── cmd_enable (CLI path) ────────────────────────────────────────────────────+++def test_enable_refusal_keeps_config(plugin_home, monkeypatch, sync_calls):+ plug = _dep_plugin(plugin_home)+ _discovery(monkeypatch, _entry(plug))+ _refusing_sync(monkeypatch)+ console = _Console()+ monkeypatch.setattr(pc, "_console", lambda: console)+ with pytest.raises(adm.AdmissionRefused):+ pc.cmd_enable("dep-plug", allow_tool_override=False)+ assert _enabled_set(plugin_home) == set() # config untouched+ assert any("refused" in line for line in console.lines)+++def test_enable_success_commits_candidate_union_once(plugin_home, monkeypatch, sync_calls):+ plug = _dep_plugin(plugin_home)+ _discovery(monkeypatch, _entry(plug))+ pc.cmd_enable("dep-plug", allow_tool_override=False)+ assert sync_calls == [[plug]] # exactly ONE sync: the candidate union+ assert _enabled_set(plugin_home) == {"dep-plug"}+++def test_enable_removal_filters_candidate(plugin_home, monkeypatch, sync_calls):+ other = plugin_home / "plugins" / "other"+ other.mkdir()+ (other / "pyproject.toml").write_text("[project]\nname='o'\n", encoding="utf-8")+ _write_sets(plugin_home, enabled=["other"])+ plug = _dep_plugin(plugin_home)+ _discovery(monkeypatch, _entry(plug))+ pc.cmd_enable("dep-plug", allow_tool_override=False)+ # proposed-sets driven: 'other' stays enabled (it IS in the candidate set)+ assert sync_calls[-1] and set(sync_calls[-1]) == {other, plug}+ assert _enabled_set(plugin_home) == {"other", "dep-plug"}+++def test_deps_free_enable_does_not_churn_venv(plugin_home, monkeypatch, sync_calls):+ plain = plugin_home / "plugins" / "plain"+ plain.mkdir()+ (plain / "plugin.yaml").write_text("name: plain\n", encoding="utf-8")+ _discovery(monkeypatch, ("plain", "1.0", "p", "user", plain, "plain"))+ pc.cmd_enable("plain", allow_tool_override=False)+ assert sync_calls == [[]] # no members: cheap stamp check only+++# ── composite UI + dashboard paths ──────────────────────────────────────────+++def test_composite_selection_refusal_not_saved(plugin_home, monkeypatch, sync_calls):+ plug = _dep_plugin(plugin_home)+ _discovery(monkeypatch, _entry(plug))+ _refusing_sync(monkeypatch, "conflict")+ with pytest.raises(adm.AdmissionRefused):+ pc._persist_plugin_selection(["dep-plug"], {0}, set())+ assert _enabled_set(plugin_home) == set()+++def test_dashboard_enable_refusal_reports_not_ok(plugin_home, monkeypatch, sync_calls):+ plug = _dep_plugin(plugin_home)+ monkeypatch.setattr(pc, "_resolve_plugin_key", lambda name: "dep-plug")+ _refusing_sync(monkeypatch, "conflict")+ result = pc.dashboard_set_agent_plugin_enabled("dep-plug", enabled=True)+ assert result["ok"] is False+ assert _enabled_set(plugin_home) == set()+++# ── the before_publish hook: config commits under the lock, undo on facts failure ─+++def test_config_commit_undo_restores_previous_bytes(plugin_home):+ _write_sets(plugin_home, enabled=["old"])+ config_path = plugin_home / "config.yaml"+ previous = config_path.read_bytes()++ undo = adm._config_commit({"dep-plug"}, set())+ assert _enabled_set(plugin_home) == {"dep-plug"} # committed exactly once+ undo() # facts write failed afterwards → restore+ assert config_path.read_bytes() == previous+++def test_facts_failure_triggers_undo_inside_one_transaction(plugin_home, monkeypatch):+ """Real sync_venv: apply stages → before_publish commits config → facts+ write fails → undo restores the previous config bytes atomically; the+ receipt records the failure."""+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")+ ensure = sys.modules["pm.ensure"]++ rdir = plugin_home / "receipts"+ monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)+ plug = _dep_plugin(plugin_home)+ _write_sets(plugin_home, enabled=["old"])+ previous = (plugin_home / "config.yaml").read_bytes()++ monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: False)+ monkeypatch.setattr(ensure, "_facts", lambda: {})+ monkeypatch.setattr(+ ensure, "get_package",+ lambda name: SimpleNamespace(+ expected_stamp=lambda enabled, **kw: "stamp1", apply=lambda enabled, **kw: {}+ ),+ )++ order = []++ def before_publish():+ 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):+ 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+ latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))+ assert latest["outcome"] == "failed"+++# ── pm receipt invariant: every sync outcome writes a receipt ───────────────+++def test_lazy_refusal_writes_failed_receipt(plugin_home, monkeypatch):+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")+ ensure = sys.modules["pm.ensure"]+ rdir = plugin_home / "receipts"+ monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)+ monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: False)+ monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: False)+ with pytest.raises(Exception):+ ensure.sync_venv(extras=["somepkg"])+ latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))+ assert latest["kind"] == "sync"+ assert latest["outcome"] == "failed"+++def test_noop_sync_writes_ok_receipt_rebuild_false(plugin_home, monkeypatch):+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")+ ensure = sys.modules["pm.ensure"]+ rdir = plugin_home / "receipts"+ monkeypatch.setattr("pm.receipt._receipt_dir", lambda: rdir)+ monkeypatch.setattr(ensure, "_runtime_state_matches", lambda fact, stamp: True)+ committed = []+ ensure.sync_venv(extras=[], before_publish=lambda: committed.append(True))+ assert committed == [True], "unchanged dependencies must still commit a plugin selection"+ latest = json.loads((rdir / "latest.json").read_text(encoding="utf-8-sig"))+ assert latest["outcome"] == "ok"+ assert latest["venv_rebuild"]["ok"] is False+ assert latest["venv_rebuild"]["reason"] == "already in sync"diff --git a/tests/hermes_cli/test_plugins_cadence.py b/tests/hermes_cli/test_plugins_cadence.pyindex 18bf363051f..28f6e561bda 100644--- a/tests/hermes_cli/test_plugins_cadence.py+++ b/tests/hermes_cli/test_plugins_cadence.py@@ -62,41 +62,16 @@ def test_interval_reads_config(homed):def test_run_writes_receipt_and_marker(homed):- calls = {"checks": 0}- receipt_calls = []-- import pm.receipt as receipt_mod-- orig_begin, orig_finalize = receipt_mod.begin, receipt_mod.finalize- monkey = pytest.MonkeyPatch()- monkey.setattr(receipt_mod, "begin", lambda kind: receipt_calls.append(("begin", kind)))- monkey.setattr(- receipt_mod, "finalize",- lambda outcome, exit_code=0: receipt_calls.append(("finalize", outcome)),- )- try:- def fake_run_checks(plugins_dir):- calls["checks"] += 1- return [_Result("plug", update_available=True)]-- results = cad.run_scheduled_check(- run_checks_fn=fake_run_checks,- plugins_dir=homed / "plugins",- now=time.time(),- )- assert calls["checks"] == 1- assert results[0].name == "plug"- assert ("begin", "plugin-check") in receipt_calls- assert ("finalize", "updates-available") in receipt_calls- # marker stamped → second run is a no-op- assert cad.run_scheduled_check(- run_checks_fn=fake_run_checks,- plugins_dir=homed / "plugins",- now=time.time(),- ) is None- assert calls["checks"] == 1- finally:- monkey.undo()+ import pm.receipt as receipts+ calls = []+ def checks(directory):+ calls.append(directory)+ return [_Result("plug", update_available=True)]+ result = cad.run_scheduled_check(run_checks_fn=checks, plugins_dir=homed / "plugins")+ assert result[0].name == "plug"+ assert receipts.latest()["outcome"] == "updates-available"+ assert cad.run_scheduled_check(run_checks_fn=checks, plugins_dir=homed / "plugins") is None+ assert len(calls) == 1def test_needs_fixing_logged_not_applied(homed):@@ -106,7 +81,7 @@ def test_needs_fixing_logged_not_applied(homed):monkey = pytest.MonkeyPatch()monkey.setattr(receipt_mod, "begin", lambda kind: None)- monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0: None)+ monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None)try:results = cad.run_scheduled_check(run_checks_fn=lambda d: [_Result("plug", needs_fixing="mismatch")],@@ -126,7 +101,7 @@ def test_auto_apply_only_git_rows_and_only_when_opted_in(homed):monkey = pytest.MonkeyPatch()monkey.setattr(receipt_mod, "begin", lambda kind: None)- monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0: None)+ monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None)try:results = [_Result("gitplug", klass="git", update_available=True),_Result("pipplug", klass="pip", update_available=True)]@@ -159,7 +134,7 @@ def test_check_failure_is_never_fatal_and_stamps_marker(homed):monkey = pytest.MonkeyPatch()monkey.setattr(receipt_mod, "begin", lambda kind: None)- monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0: None)+ monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None)try:def boom(d):raise RuntimeError("network down")diff --git a/tests/hermes_cli/test_plugins_check_updates.py b/tests/hermes_cli/test_plugins_check_updates.pyindex ecb0048fa0a..c89d33f5dbe 100644--- a/tests/hermes_cli/test_plugins_check_updates.py+++ b/tests/hermes_cli/test_plugins_check_updates.py@@ -8,6 +8,8 @@ shape without network.from __future__ import annotationsimport json+import os+import shutilimport subprocessfrom pathlib import Path@@ -43,6 +45,42 @@ def _git_prov(**row):return _prov(ProvenanceClass.GIT, row=row)+# ── local git, one resolver for every repo-spawning test ────────────+++def _git_exe():+ """Conventional git from PATH — tests run with Git for Windows' cmd+ dir leading PATH, never the MSIX payload (spawn denial, WinError 5)."""+ return shutil.which("git") or "git"+++def _git_env():+ return {k: v for k, v in os.environ.items() if k != "GIT_DIR"}+++def _local_repo(path: Path, *init_args):+ """A real local git repo; returns (run, head) bound to it."""+ git = _git_exe()+ env = _git_env()++ def run(*args):+ subprocess.run(+ [git, *args], cwd=path, check=True, capture_output=True, env=env+ )++ def head():+ return subprocess.run(+ [git, "rev-parse", "HEAD"], cwd=path, check=True,+ capture_output=True, text=True, env=env,+ ).stdout.strip()++ path.mkdir(parents=True)+ run("init", "-q", *init_args)+ run("-c", "user.email=t@e", "-c", "user.name=t",+ "commit", "--allow-empty", "-qm", "one")+ return run, head++# ── provenance-class short-circuits ────────────────────────────────@@ -127,7 +165,8 @@ def test_matching_tag_fetches_feed(tmp_path):plug = tmp_path / "plug"plug.mkdir()(plug / "plugin.yaml").write_text(- "name: plug\nupdate_url: https://feed.example/f.yml\n", encoding="utf-8"+ "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",)prov = _git_prov(update_url="https://feed.example/f.yml")prov.path = plug@@ -142,21 +181,214 @@ def test_matching_tag_fetches_feed(tmp_path):assert fetched == ["https://feed.example/f.yml"]assert r.latest == "1.2.0"assert r.min_hermes == "0.27.0"- assert r.update_available is True # revision sha != 1.2.0+ assert r.update_available is True # installed 1.0.0 vs feed 1.2.0-def test_feed_version_equal_to_current_means_no_update(tmp_path):+def test_feed_version_equal_to_installed_version_means_no_update(tmp_path):+ """C17 convergence: feed semantic version vs installed semantic version."""+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nversion: 1.2.0\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",+ )+ prov = _git_prov(update_url="https://feed.example/f.yml")+ prov.path = plug+ r = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no)+ assert r.update_available is False+++def test_feed_version_with_no_installed_version_is_unknown(tmp_path):+ """A semantic feed vs a versionless manifest cannot be compared — report+ unknown, never a revision-vs-version inequality."""plug = tmp_path / "plug"plug.mkdir()(plug / "plugin.yaml").write_text("name: plug\nupdate_url: https://feed.example/f.yml\n", encoding="utf-8")- prov = _git_prov(update_url="https://feed.example/f.yml", revision="1.2.0")+ prov = _git_prov(update_url="https://feed.example/f.yml")prov.path = plugr = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no)+ assert r.update_available is None+ assert r.latest == "1.2.0"+++def test_feed_git_sha_artifact_compares_sha_to_sha(tmp_path):+ """C17 like-for-like: a full git SHA in the feed's artifacts.git is+ compared against the recorded revision, never to a semantic version —+ and both reported fields are the shas actually compared."""+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nversion: 9.9.9\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",+ )+ feed = "version: 1.2.0\nartifacts:\n git: %s\n" % ("c" * 40)+ prov = _git_prov(update_url="https://feed.example/f.yml")+ prov.path = plug++ r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no)+ assert r.update_available is True # c*40 != a*40+ assert r.current == "a" * 40+ assert r.latest == "c" * 40++ prov2 = _git_prov(update_url="https://feed.example/f.yml", revision="c" * 40)+ prov2.path = plug+ r2 = check_provenanced(prov2, fetch=lambda u: feed, ls_remote=_no)+ assert r2.update_available is False # SHA vs SHA: converged+ assert r2.current == "c" * 40+ assert r2.latest == "c" * 40+++def test_feed_git_sha_case_equivalent_is_not_an_update(tmp_path):+ """Hex identity is case-insensitive — but only after format validation."""+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nupdate_url: https://feed.example/f.yml\n", encoding="utf-8"+ )+ feed = "version: 1.2.0\nartifacts:\n git: %s\n" % ("C" * 40)+ prov = _git_prov(update_url="https://feed.example/f.yml", revision="c" * 40)+ prov.path = plug+ r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no)assert r.update_available is False+def test_feed_git_tag_artifact_falls_to_semantic_compare(tmp_path):+ """A non-sha artifacts.git (repo URL, tag) is not a comparable git+ identity — the feed's semantic version is compared against the+ installed manifest's version instead."""+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",+ )+ feed = "version: 9.9.9\nartifacts:\n git: https://example/o/r\n"+ prov = _git_prov(update_url="https://feed.example/f.yml")+ prov.path = plug+ r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no)+ assert r.update_available is True+ assert r.current == "1.0.0"+ assert r.latest == "9.9.9"+++def test_feed_git_sha_with_no_recorded_revision_is_unknown(tmp_path):+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nversion: 9.9.9\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",+ )+ feed = "version: 1.2.0\nartifacts:\n git: %s\n" % ("c" * 40)+ prov = _git_prov(update_url="https://feed.example/f.yml", revision="")+ prov.path = plug+ r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no)+ assert r.update_available is None+ assert "no full revision sha" in r.reason+++def test_feed_git_sha_against_tagged_revision_is_unknown(tmp_path):+ """A recorded tag is not a full sha — never compared by inequality."""+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nversion: 9.9.9\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",+ )+ feed = "version: 1.2.0\nartifacts:\n git: %s\n" % ("c" * 40)+ prov = _git_prov(+ update_url="https://feed.example/f.yml", revision="v1.2.0"+ )+ prov.path = plug+ r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no)+ assert r.update_available is None+++def test_feed_semantic_branch_reports_installed_version_as_current(tmp_path):+ """The semantic branch compares version vs version, so the reported+ current is the installed version — not the unrelated revision sha."""+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text(+ "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n",+ encoding="utf-8",+ )+ prov = _git_prov(update_url="https://feed.example/f.yml")+ prov.path = plug+ r = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no)+ assert r.update_available is True+ assert r.current == "1.0.0"+ assert r.latest == "1.2.0"+++def test_malformed_yaml_feed_reports_unknown_row(tmp_path):+ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / "plugin.yaml").write_text("update_url: https://feed.example/f.yml\n", encoding="utf-8")+ prov = _git_prov(update_url="https://feed.example/f.yml")+ prov.path = plug+ result = check_provenanced(prov, fetch=lambda _: "version: [", ls_remote=_no)+ assert result.update_available is None+ assert "unparseable" in result.reason+++def test_parse_feed_rejects_non_string_git_artifact():+ feed = "version: 1.2.0\nartifacts:\n git:\n url: x\n"+ with pytest.raises(ValueError):+ parse_feed_yml(feed)+++def test_ls_remote_lifecycle_current_available_applied(tmp_path):+ """The git-path gate, end to end against a real local repo: current ->+ ls-remote sees a new HEAD -> revision recorded -> current. No network,+ no manual manifest rewriting — every comparison is the real command."""+ repo = tmp_path / "repo"+ run, head = _local_repo(repo, "-b", "main")+ sha1 = head()+ ls_remote = _real_ls_remote()++ plug = tmp_path / "plug"+ plug.mkdir()+ (plug / ".git").mkdir()+ prov = _git_prov(revision=sha1, source=str(repo))+ prov.path = plug++ def check():+ return check_provenanced(prov, fetch=_no, ls_remote=ls_remote)++ assert check().update_available is False # current++ run("-c", "user.email=t@e", "-c", "user.name=t",+ "commit", "--allow-empty", "-qm", "two")+ sha2 = head()+ assert sha2 != sha1+ r = check()+ assert r.update_available is True # available+ assert r.latest == sha2++ # once the update pipeline has recorded the new revision, converged+ prov3 = _git_prov(revision=sha2, source=str(repo))+ prov3.path = plug+ assert check_provenanced(prov3, fetch=_no, ls_remote=ls_remote).update_available is False+++def _real_ls_remote():+ git = _git_exe()+ env = _git_env()++ def ls_remote(source):+ proc = subprocess.run(+ [git, "ls-remote", source, "HEAD"],+ capture_output=True, text=True, timeout=10, env=env,+ )+ if proc.returncode != 0:+ raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200])+ out = (proc.stdout or "").strip()+ return out.split("\t")[0] if out else ""+ return ls_remote++def test_feed_fetch_failure_is_row_level_reason(tmp_path):plug = tmp_path / "plug"plug.mkdir()@@ -197,30 +429,17 @@ def test_ls_remote_fallback(tmp_path):def test_real_ls_remote_against_bare_repo(tmp_path):- import os- import shutil-- # The host PATH may resolve git to the MSIX payload (package-boundary- # spawn denial, WinError 5) — prefer a conventional install.- git_bin = shutil.which("git") or "git"- for candidate in (- "C:/Program Files/Git/cmd/git.exe",- "/usr/bin/git",- ):- if Path(candidate).is_file():- git_bin = candidate- break-source = tmp_path / "bare.git"- env = {k: v for k, v in os.environ.items() if k != "GIT_DIR"}+ git = _git_exe()+ env = _git_env()subprocess.run(- [git_bin, "init", "--bare", "-q", str(source)],+ [git, "init", "--bare", "-q", str(source)],check=True, capture_output=True, env=env,)# ls-remote on an empty bare repo: exit 0, empty HEAD — the command# SHAPE works; empty maps to unknown, never a crashproc = subprocess.run(- [git_bin, "ls-remote", str(source), "HEAD"],+ [git, "ls-remote", str(source), "HEAD"],capture_output=True, text=True, timeout=10, env=env,)assert proc.returncode == 0@@ -270,6 +489,43 @@ def test_pip_not_on_pypi_reports_unknown():assert "not on PyPI" in rs[0].reason+class _Dist:+ def __init__(self, name):+ self._name = name++ @property+ def metadata(self):+ return {"Name": self._name}+++def test_pip_uses_owning_distribution_not_import_root():+ """C17: the dist name comes from the entry point's owning distribution,+ never guessed from the value's first import module."""+ ep = _EP("mnemosyne", "some.module:register", None)+ ep.dist = _Dist("mnemosyne-hermes")+ seen = []++ rs = check_pip_plugins(+ installed_version=lambda d: (seen.append(d), "0.5.0")[1],+ pypi_latest=lambda d: None,+ entry_points=[ep],+ )+ assert seen == ["mnemosyne-hermes"]+ assert rs[0].current == "0.5.0"+++def test_pip_entry_point_without_distribution_is_unknown_not_guessed():+ ep = _EP("orphan", "some.module:register", None)+ rs = check_pip_plugins(+ installed_version=lambda d: pytest.fail(f"guessed dist {d!r}"),+ pypi_latest=lambda d: pytest.fail("no fetch without a dist"),+ entry_points=[ep],+ )+ assert rs[0].update_available is None+ assert rs[0].latest is None+ assert "distribution" in rs[0].reason++# ── run_checks composition ───────────────────────────────────────────diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.pyindex 283e410531c..7401d263622 100644--- a/tests/hermes_cli/test_plugins_cmd.py+++ b/tests/hermes_cli/test_plugins_cmd.py@@ -199,6 +199,7 @@ class TestGitPullPluginDirAutostash:origin = tmp_path / "origin"origin.mkdir()git(origin, "init", "-q", "-b", "main")+ git(origin, "config", "core.autocrlf", "false")git(origin, "config", "user.email", "t@t")git(origin, "config", "user.name", "t")pad = "\n".join(f"# pad {i}" for i in range(12))@@ -238,7 +239,7 @@ class TestGitPullPluginDirAutostash:assert ok is Truecontent = (checkout / "plugin.py").read_text(encoding="utf-8")assert "VALUE = 2" in content # update landed- assert "OTHER = 'local'" in content # local edit survived+ assert "OTHER = 'local'" in content, msg # local edit survivedassert "re-applied" in msg# Clean re-apply drops the autostash entry.assert git(checkout, "stash", "list").strip() == ""@@ -490,33 +491,24 @@ class TestCmdRemove:class TestCmdList:"""Test the list command."""- @patch("hermes_cli.plugins_cmd._plugins_dir")- def test_list_empty_plugins_dir(self, mock_plugins_dir):- from hermes_cli.plugins_cmd import cmd_list-- mock_plugins_dir_val = MagicMock()- mock_plugins_dir_val.iterdir.return_value = []- mock_plugins_dir.return_value = mock_plugins_dir_val-- cmd_list()-- @patch("hermes_cli.plugins_cmd._plugins_dir")- @patch("hermes_cli.plugins_cmd._read_manifest")- def test_list_with_plugins(self, mock_read_manifest, mock_plugins_dir):- from hermes_cli.plugins_cmd import cmd_list-- mock_plugins_dir_val = MagicMock()- mock_plugin_dir = MagicMock()- mock_plugin_dir.name = "test-plugin"- mock_plugin_dir.is_dir.return_value = True- mock_plugin_dir.__truediv__ = lambda self, x: MagicMock(- exists=MagicMock(return_value=False)- )- mock_plugins_dir_val.iterdir.return_value = [mock_plugin_dir]- mock_plugins_dir.return_value = mock_plugins_dir_val- mock_read_manifest.return_value = {"name": "test-plugin", "version": "1.0.0"}+ def test_list_empty_plugins_dir(self, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd+ monkeypatch.setattr(plugins_cmd, "_plugins_dir", lambda: tmp_path)+ console = MagicMock()+ monkeypatch.setattr(plugins_cmd, "_console", lambda: console)+ plugins_cmd.cmd_list()+ console.print.assert_called()- cmd_list()+ def test_list_with_plugins(self, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd+ plugin = tmp_path / "test-plugin"+ plugin.mkdir()+ (plugin / "plugin.yaml").write_text("name: test-plugin\nversion: 1.0.0\n", encoding="utf-8")+ monkeypatch.setattr(plugins_cmd, "_plugins_dir", lambda: tmp_path)+ console = MagicMock()+ monkeypatch.setattr(plugins_cmd, "_console", lambda: console)+ plugins_cmd.cmd_list()+ console.print.assert_called()# ── _copy_example_files tests ─────────────────────────────────────────────────diff --git a/tests/hermes_cli/test_plugins_cmd_deps_flow.py b/tests/hermes_cli/test_plugins_cmd_deps_flow.pyindex f9adad83e67..d6b9cb209c4 100644--- a/tests/hermes_cli/test_plugins_cmd_deps_flow.py+++ b/tests/hermes_cli/test_plugins_cmd_deps_flow.py@@ -37,9 +37,6 @@ def resolve_env(monkeypatch):importlib.import_module("pm.ensure")ensure_mod = sys.modules["pm.ensure"]monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)- monkeypatch.setattr(- "pm.workspace.enabled_member_dirs", lambda: []- )def _legacy_plugin(target: Path) -> None:@@ -98,38 +95,65 @@ def test_decline_skips_install(tmp_path, monkeypatch, resolve_env):assert not called-def test_conflict_reports_reason_not_crash(tmp_path, monkeypatch, resolve_env):+def test_conflict_surfaces_at_admission_not_consent(tmp_path, monkeypatch, resolve_env):+ home = tmp_path / ".hermes"+ (home / "plugins").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))plug = tmp_path / "dep-plug"_legacy_plugin(plug)monkeypatch.setattr(pc.sys.stdin, "isatty", lambda: True, raising=False)monkeypatch.setattr(pc.sys.stdout, "isatty", lambda: True, raising=False)monkeypatch.setattr("builtins.input", lambda *a: "y")+ # Consent succeeds — resolution moved OUT of consent (C13):+ ok, reason = pc._install_plugin_python_deps(+ {"name": "dep-plug", "python_dependencies": ["somepkg==9.9.9"]},+ plug,+ _Console(),+ )+ assert ok is True and reason is None++ # The conflict surfaces when the enable COMMITS, with config untouched:+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")+ ensure = sys.modules["pm.ensure"]+def boom(*a, **k):raise RuntimeError("uv lock exited 1: Because dep-plug depends on somepkg==9.9.9 ""and hermes-agent depends on somepkg==1.0.0, unsatisfiable")- monkeypatch.setattr("pm.workspace.lock_and_sync", boom)- ok, reason = pc._install_plugin_python_deps(- {"name": "dep-plug", "python_dependencies": ["somepkg==9.9.9"]},- plug,- _Console(),- )- assert ok is False- assert "unsatisfiable" in reason+ monkeypatch.setattr(ensure, "sync_venv", boom)+ from hermes_cli import plugins_admission as adm++ with pytest.raises(adm.AdmissionRefused) as excinfo:+ adm.admit_plugin_set_change(+ {"dep-plug"}, set(), active_plugins_dir=home / "plugins", extra_dirs=[plug]+ )+ assert "unsatisfiable" in str(excinfo.value)+ from hermes_cli.config import load_config++ assert not ((load_config().get("plugins") or {}).get("enabled"))-def test_success_installs_and_legacy_bridge_materializes(tmp_path, monkeypatch, resolve_env):+def test_success_consents_without_plugin_dir_writes(tmp_path, monkeypatch, resolve_env):plug = tmp_path / "dep-plug"_legacy_plugin(plug)monkeypatch.setattr(pc.sys.stdin, "isatty", lambda: True, raising=False)monkeypatch.setattr(pc.sys.stdout, "isatty", lambda: True, raising=False)monkeypatch.setattr("builtins.input", lambda *a: "y")synced = []+ import importlib+ import sys++ if "pm.ensure" not in sys.modules:+ importlib.import_module("pm.ensure")monkeypatch.setattr(- "pm.workspace.lock_and_sync", lambda *a, **k: synced.append(a)+ sys.modules["pm.ensure"], "sync_venv", lambda *a, **k: synced.append(a))ok, reason = pc._install_plugin_python_deps({"name": "dep-plug", "python_dependencies": ["somepkg>=1,<2"]},@@ -137,8 +161,6 @@ def test_success_installs_and_legacy_bridge_materializes(tmp_path, monkeypatch,_Console(),)assert ok is True and reason is None- assert synced # the union ran- # the legacy bridge materialized the pyproject before the resolve- generated = plug / "pyproject.toml"- assert generated.is_file()- assert "GENERATED by pm" in generated.read_text(encoding="utf-8")+ assert not synced # consent only — the resolve runs in the admission transaction+ # no plugin-dir writes: legacy deps stage as virtual members in pm's workspace+ assert not (plug / "pyproject.toml").exists()diff --git a/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py b/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.pyindex 38e1b57a7c4..bd71ef18c9c 100644--- a/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py+++ b/tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py@@ -15,6 +15,16 @@ from unittest.mock import patchimport pytest[email protected](autouse=True)+def _capture_selection(monkeypatch):+ import hermes_cli.plugins_cmd as pc+ from hermes_cli import plugins_admission+ def save(enabled, disabled, **kwargs):+ pc._save_enabled_set(enabled)+ pc._save_disabled_set(disabled)+ monkeypatch.setattr(plugins_admission, "admit_plugin_set_change", save)++def _make_plugin_dir(parent: Path, name: str, manifest: dict) -> Path:d = parent / named.mkdir(parents=True, exist_ok=True)diff --git a/tests/hermes_cli/test_plugins_update_sync.py b/tests/hermes_cli/test_plugins_update_sync.pyindex 29584eea8c4..b41288cc6b5 100644--- a/tests/hermes_cli/test_plugins_update_sync.py+++ b/tests/hermes_cli/test_plugins_update_sync.py@@ -66,6 +66,23 @@ def test_member_plugin_triggers_post_pull_sync(plugin_env, monkeypatch):assert synced == [None] # explicit sync with recorded extras+def test_update_scans_once_after_pull(plugin_env, monkeypatch):+ """C04: exactly ONE post-pull security scan — the rescan pipeline's, not a+ duplicated inline copy (which crashed with NameError on an undefined name)."""+ import tools.plugin_guard as guard++ scans = []+ monkeypatch.setattr(+ guard, "scan_plugin", lambda target, source: scans.append(source)+ )+ monkeypatch.setattr(+ guard, "should_allow_plugin_install", lambda result, **k: (True, "")+ )+ monkeypatch.setattr(pc, "_scan_on_install_enabled", lambda: True)+ pc.cmd_update("plug")+ assert scans == ["plug"]++def test_plain_plugin_skips_sync(plugin_env, monkeypatch):# no pyproject.toml — nothing to unionimport pmdiff --git a/tests/hermes_cli/test_profile_export_default_path.py b/tests/hermes_cli/test_profile_export_default_path.pyindex 23092e7250e..537f218968e 100644--- a/tests/hermes_cli/test_profile_export_default_path.py+++ b/tests/hermes_cli/test_profile_export_default_path.py@@ -215,6 +215,7 @@ def test_every_candidate_inside_a_checkout_fails_closed(profiles.get_profile_export_path("default")[email protected]("posix")def test_export_dir_symlink_is_rejected(tmp_path, monkeypatch, profiles):"""A pre-created symlink at the managed export path (predictable-pathattack on shared hosts) must be refused, not silently followed."""diff --git a/tests/hermes_cli/test_restore_own_holder_guard.py b/tests/hermes_cli/test_restore_own_holder_guard.pyindex 0535633d908..7e7a5637eee 100644--- a/tests/hermes_cli/test_restore_own_holder_guard.py+++ b/tests/hermes_cli/test_restore_own_holder_guard.py@@ -14,7 +14,7 @@ import sysimport pytest-from hermes_cli import backup as backup_mod+from hermes_cli import backup_restore as backup_restore_modfrom hermes_cli import update_cmdfrom hermes_cli.sqlite_safe_read import connect_tracked@@ -84,7 +84,7 @@ def test_safe_restore_fallback_refuses_under_own_live_connection(live_held_db):wal = dst.with_name(dst.name + "-wal")wal_ino = wal.stat().st_ino- assert backup_mod._safe_restore_db(src, dst) is False+ assert backup_restore_mod._safe_restore_db(src, dst) is False# The held generation must survive: same WAL inode, no deleted-fd ghosts.assert wal.exists() and wal.stat().st_ino == wal_ino@@ -114,7 +114,7 @@ def test_safe_restore_fallback_still_works_without_holder(tmp_path):with open(dst, "r+b") as fh:fh.write(b"\x00" * 100)- assert backup_mod._safe_restore_db(src, dst) is True+ assert backup_restore_mod._safe_restore_db(src, dst) is Trueassert _read_marker(dst) == "snapshot-good"diff --git a/tests/hermes_cli/test_uninstall_gateway_service.py b/tests/hermes_cli/test_uninstall_gateway_service.pynew file mode 100644index 00000000000..b0e01c5a6ee--- /dev/null+++ b/tests/hermes_cli/test_uninstall_gateway_service.py@@ -0,0 +1,70 @@+"""Tests for ``uninstall_gateway_service`` — the per-platform service dispatch.++The dispatch is table-driven (``_GATEWAY_SERVICE_REMOVERS``, keyed by+``platform.system()``): exactly the current host's remover runs, a remover+failure is reported with the table's warning label, and a platform with no+entry (tested here via an empty table) cleans up nothing. The tests run on the+actual host — no OS faking — and all removers plus the standalone-process kill+are stubbed, so no real service is stopped and no real gateway process is+killed.+"""+from __future__ import annotations++import platform++import pytest++import hermes_cli.gateway as gateway+import hermes_cli.uninstall as uninstall+++def no_live_gateways(monkeypatch: pytest.MonkeyPatch) -> None:+ """The standalone-process sweep finds nothing (and must not kill)."""+ monkeypatch.setattr(gateway, "find_gateway_pids", lambda *a, **k: [])+ monkeypatch.setattr(+ gateway, "kill_gateway_processes",+ lambda *a, **k: pytest.fail("kill_gateway_processes must not run without live pids"))+ # Neutral env in case the CI runner exports Termux variables; this host+ # always reaches the dispatch table.+ monkeypatch.delenv("TERMUX_VERSION", raising=False)+ monkeypatch.setenv("PREFIX", "")+++def _dispatch_table(calls: list) -> dict:+ """A remover table that records which platform's remover ran."""+ def remover(name):+ def run():+ calls.append(name)+ return True+ return run+ return {+ "Linux": (remover("Linux"), "linux label"),+ "Darwin": (remover("Darwin"), "darwin label"),+ "Windows": (remover("Windows"), "windows label"),+ }+++def test_current_platform_remover_runs_and_others_do_not(monkeypatch, no_live_gateways):+ calls: list = []+ monkeypatch.setattr(uninstall, "_GATEWAY_SERVICE_REMOVERS", _dispatch_table(calls))++ assert uninstall.uninstall_gateway_service() is True+ assert calls == [platform.system()]+++def test_remover_failure_reports_the_table_label(monkeypatch, no_live_gateways, capsys):+ table = _dispatch_table([])+ def boom():+ raise RuntimeError("no service manager here")+ table[platform.system()] = (boom, "remover blew up")+ monkeypatch.setattr(uninstall, "_GATEWAY_SERVICE_REMOVERS", table)++ assert uninstall.uninstall_gateway_service() is False+ assert "remover blew up" in capsys.readouterr().out+++def test_unknown_platform_runs_no_remover(monkeypatch, no_live_gateways):+ monkeypatch.setattr(uninstall, "_GATEWAY_SERVICE_REMOVERS", {})++ assert uninstall.uninstall_gateway_service() is Falsediff --git a/tests/hermes_cli/test_uninstall_install_kind.py b/tests/hermes_cli/test_uninstall_install_kind.pyindex 5a8bb61bbfe..78b4d823b1f 100644--- a/tests/hermes_cli/test_uninstall_install_kind.py+++ b/tests/hermes_cli/test_uninstall_install_kind.py@@ -214,6 +214,23 @@ def test_gui_summary_reports_steward_and_gate(monkeypatch, tmp_path):assert summary["code_removal_allowed"] is True+def test_gui_summary_classifies_the_agent_root(tmp_path, monkeypatch):+ """The steward facts classify the home's ``hermes-agent`` checkout — the+ tree the code-removal modes would delete — not some unrelated root."""+ import hermes_cli.gui_uninstall as gu+ from hermes_cli import steward as st++ seen = []+ monkeypatch.setattr(st, "classify_install", lambda root: seen.append(root) or ("git", True))+ monkeypatch.setattr(gu, "packaged_gui_app_paths", lambda: [])+ monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "none")++ home = tmp_path / ".hermes"+ gu.gui_install_summary(home)++ assert seen == [home / "hermes-agent"]++# ---------------------------------------------------------------------------# module entrypoint routing# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_uninstall_node_symlinks.py b/tests/hermes_cli/test_uninstall_node_symlinks.pyindex 4c01ffed29d..4bf37cda2fc 100644--- a/tests/hermes_cli/test_uninstall_node_symlinks.py+++ b/tests/hermes_cli/test_uninstall_node_symlinks.py@@ -37,6 +37,21 @@ def _make_hermes_node(hermes_home: Path) -> Path:[email protected]("owned", [False, True])+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"+ 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)++@pytest.mark.require_symlinksdef test_leaves_unrelated_symlinks_untouched(fake_home):"""A node symlink the user repointed at nvm must survive uninstall."""diff --git a/tests/hermes_cli/test_uninstall_shell_configs.py b/tests/hermes_cli/test_uninstall_shell_configs.pyindex 1ba87c9551f..d19831c5451 100644--- a/tests/hermes_cli/test_uninstall_shell_configs.py+++ b/tests/hermes_cli/test_uninstall_shell_configs.py@@ -60,6 +60,20 @@ class TestHappyPath:assert uninstall.remove_path_from_shell_configs() == []assert rc.read_text(encoding="utf-8") == "export EDITOR=vim\n"+ def test_all_shell_rc_candidates_are_swept(self, fake_home: Path):+ """Every rc name the shell-config resolver knows gets the PATH sweep.++ Guards the single resolver's coverage: an rc the resolver misses keeps+ a stale Hermes PATH entry after uninstall.+ """+ names = (".bashrc", ".bash_profile", ".profile", ".zshrc", ".zprofile")+ for name in names:+ (fake_home / name).write_text(ZSHRC, encoding="utf-8")++ removed = uninstall.remove_path_from_shell_configs()++ assert sorted(p.name for p in removed) == sorted(names)+class TestCrashDurability:def test_shell_config_survives_an_interrupted_rewrite(self, fake_home: Path):diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.pyindex 8cf696b6786..10c24f024b2 100644--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@ -25,7 +25,7 @@ def _patch_managed_uv(request, patch_pm_uv_to_shutil_which):@pytest.fixture(autouse=True)-def _patch_gateway_discovery():+def _patch_gateway_discovery(monkeypatch):"""Keep cmd_update's gateway auto-restart phase off this machine's gateways.Tests in this file that reach the full success path (e.g. the #87694@@ -41,6 +41,10 @@ def _patch_gateway_discovery():UNPATCHED copy of the module — silently discarding every mock here andletting real gateway discovery (and real ``os.kill``) run on the dev box."""+ monkeypatch.setattr(hermes_main, "_pause_windows_gateways_for_update", lambda: None)+ monkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a: None)+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)+ monkeypatch.setattr("hermes_cli.update_cmd_maint._run_post_update_maintenance", lambda *a, **k: None)with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.pyindex fce5696a85b..3602b43fa03 100644--- a/tests/hermes_cli/test_update_channel.py+++ b/tests/hermes_cli/test_update_channel.py@@ -16,6 +16,7 @@ from hermes_cli.update_channel import (CHANNEL_CANARY,CHANNEL_STABLE,default_channel,+ handle_channel_flags,install_id,resolve_update_channel,set_install_channel,@@ -202,6 +203,29 @@ class TestSetChannel:assert written["update"]["installs"][install_id(other)]["channel"] == "canary"assert written["update"]["installs"][install_id(root)]["channel"] == "stable"+ def test_preserves_comments_in_config(self, tmp_path, monkeypatch):+ """Persisting a channel must not strip user comments from+ config.yaml — the write goes through the shared comment-preserving+ atomic round-trip writer."""+ home = self._home(tmp_path, monkeypatch)+ (home / "config.yaml").write_text(+ "# my hand-maintained settings\n"+ "model:\n"+ " provider: nous # keep this\n"+ )+ root = tmp_path / "install"+ _stamp(root, "self")+ set_install_channel("stable", root)++ text = (home / "config.yaml").read_text()+ assert "# my hand-maintained settings" in text+ assert "# keep this" in text+ import yaml++ written = yaml.safe_load(text)+ assert written["model"] == {"provider": "nous"}+ assert written["update"]["installs"][install_id(root)]["channel"] == "stable"+def test_external_mechanism_refuses(self, tmp_path, monkeypatch):self._home(tmp_path, monkeypatch)root = tmp_path / "nix-tree"@@ -220,6 +244,125 @@ class TestSetChannel:class TestSetChannelCLI:"""cmd_update --set-channel: the switch texts (design record)."""+ @pytest.fixture(autouse=True)+ def _fail_fast_updater_sentinel(self, monkeypatch, tmp_path):+ """Isolation harness (C03 revalidation).++ If the informational flags were ever unhandled in preflight,+ ``cmd_update`` would enter the real updater (lock, git, backups,+ process pause) — that must fail HERE, at a ``_cmd_update_impl``+ sentinel, instead of mutating anything. Subprocess and network+ are denied outright, and the install root is pinned to ``tmp_path``+ (a real root, never this checkout) so stamp reads cannot touch the+ worktree either.+ """+ import socket+ import subprocess++ def _sentinel(*_a, **_kw):+ raise AssertionError(+ "fail-fast sentinel: _cmd_update_impl entered — channel "+ "flags were not handled by the update preflight"+ )++ def _denied(what):+ def _deny(*_a, **_kw):+ raise AssertionError(+ f"fail-fast guard: {what} attempted from a channel-flag test"+ )++ return _deny++ monkeypatch.setattr(+ "hermes_cli.update_cmd._cmd_update_impl", _sentinel+ )+ for name in ("Popen", "run", "call", "check_call", "check_output"):+ monkeypatch.setattr(subprocess, name, _denied(f"subprocess.{name}"))+ monkeypatch.setattr(+ socket, "create_connection", _denied("socket.create_connection")+ )+ monkeypatch.setattr(socket.socket, "connect", _denied("socket.connect"))+ # Real root, real filesystem — but a temp one, never the checkout.+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(tmp_path))++ def _home(self, tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir(exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home++ def test_malformed_update_section_refused_not_normalized(self, tmp_path, monkeypatch):+ """A scalar/malformed ``update`` (or ``update.installs``) is refused —+ the dotted writer would silently turn it into a mapping and destroy+ the user's value. The file is left byte-identical."""+ for bad in ("update: not-a-mapping\n", "update:\n installs: 7\n"):+ home = self._home(tmp_path, monkeypatch)+ cfg = home / "config.yaml"+ cfg.write_text("# user header\n" + bad)+ root = tmp_path / "install"+ _stamp(root, "self")+ with pytest.raises(ValueError, match="not a mapping"):+ set_install_channel("stable", root)+ assert cfg.read_text() == "# user header\n" + bad+ # cleanup between loop iterations+ import shutil++ shutil.rmtree(home)++ def test_stored_record_outranks_running_stamp_in_switch_text(+ self, tmp_path, monkeypatch, capsys+ ):+ """The reported previous channel comes from the stored per-install+ record when one exists — not from what the running artifact implies."""+ home = self._home(tmp_path, monkeypatch)+ root = tmp_path # == HERMES_INSTALL_ROOT (see sentinel fixture)+ (root / "install-stamp.json").write_text(json.dumps({+ "schemaVersion": 2,+ "updateMechanism": "electron-updater",+ "displayVersion": "0.28.0-canary.20260818",+ }))+ import yaml++ (home / "config.yaml").write_text(+ yaml.safe_dump(+ {"update": {"installs": {+ install_id(root): {"path": str(root), "channel": "stable"}+ }}}+ )+ )+ from types import SimpleNamespace++ args = SimpleNamespace(+ check=False, gateway=False, branch=None, channel=None,+ set_channel="canary", install_id=False, plan=False,+ )+ with pytest.raises(SystemExit) as exc:+ handle_channel_flags(args)+ assert exc.value.code == 0+ assert "Channel set to 'canary' (was 'stable')" in capsys.readouterr().out++ def test_hint_requires_a_valid_canary_shape(self, tmp_path, monkeypatch, capsys):+ """A ``displayVersion`` only reads as canary when it validates as a+ canary version shape — 'nightly' builds must not claim the canary+ switch text."""+ home = self._home(tmp_path, monkeypatch)+ root = tmp_path # == HERMES_INSTALL_ROOT (see sentinel fixture)+ (root / "install-stamp.json").write_text(json.dumps({+ "schemaVersion": 2,+ "updateMechanism": "electron-updater",+ "displayVersion": "0.28.0-nightly.123",+ }))+ from types import SimpleNamespace++ args = SimpleNamespace(+ check=False, gateway=False, branch=None, channel=None,+ set_channel="stable", install_id=False, plan=False,+ )+ with pytest.raises(SystemExit) as exc:+ handle_channel_flags(args)+ assert exc.value.code == 0+ assert "Channel set to 'stable' (was 'stable')" in capsys.readouterr().out+def _args(self, **kw):from types import SimpleNamespacediff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.pyindex bc02063cf75..db46ca813d6 100644--- a/tests/hermes_cli/test_update_fleet_restart_pending.py+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py@@ -82,6 +82,7 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):"""Patch ``_cmd_update_impl`` helpers. Mirrors test_update_head_moved_gate."""monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect)monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)(tmp_path / ".git").mkdir()monkeypatch.setattr(hermes_main, "_resolve_update_branch", lambda args: "main")monkeypatch.setattr(hermes_main, "_is_windows", lambda: False)diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.pyindex 114207b0c4c..c014b074b3e 100644--- a/tests/hermes_cli/test_update_head_moved_gate.py+++ b/tests/hermes_cli/test_update_head_moved_gate.py@@ -89,6 +89,7 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):"""monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect)monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)(tmp_path / ".git").mkdir() # pass the "is a git repo" gatemonkeypatch.setattr(hermes_main, "_resolve_update_branch", lambda args: "main"diff --git a/tests/hermes_cli/test_update_interrupted_recovery.py b/tests/hermes_cli/test_update_interrupted_recovery.pyindex 44dabe8ea97..c46c84cfbd2 100644--- a/tests/hermes_cli/test_update_interrupted_recovery.py+++ b/tests/hermes_cli/test_update_interrupted_recovery.py@@ -43,7 +43,12 @@ def _stub_install_env(monkeypatch, m, seen):returncode = 0monkeypatch.setattr(m.subprocess, "run", lambda *a, **k: R())- monkeypatch.setattr("pm.uv", lambda **kw: (None, {}))+ # Recovery resolves uv through the pm.ensure.uv bridge (the defining seam);+ # patching the pm package re-export would not intercept it.+ import importlib++ pm_ensure = importlib.import_module("pm.ensure")+ monkeypatch.setattr(pm_ensure, "uv", lambda **kw: (None, {}))# The install executor moved to hermes_cli._install_repair (shared between# the pre-import early pass and this late recovery path) — stub WHERE it# is executed, not the legacy main.py wrapper it replaced.@@ -112,3 +117,29 @@ def sys_executable_path():return sys.executable+def test_default_venv_install_target_follows_pm_uv_seam(tmp_path, monkeypatch):+ """``_default_venv_install_target`` resolves uv through ``pm.ensure.uv`` (the+ defining seam, not the ``pm.uv`` re-export) and keeps the pre-existing pip+ fallback — ``[sys.executable, -m pip]`` with no env — when pm cannot supply+ one. Contract, not source shape: both arms run the real function."""+ import importlib+ import sys++ monkeypatch.setattr(m, "PROJECT_ROOT", tmp_path)+ pm_ensure = importlib.import_module("pm.ensure")++ stub_uv = tmp_path / "uv-stub.exe"+ stub_uv.write_text("")+ monkeypatch.setattr(pm_ensure, "uv", lambda **kw: (str(stub_uv), {}))+ prefix, env = main_install_repair._default_venv_install_target()+ assert prefix == [str(stub_uv), "pip"]+ # project_venv_dir(tmp_path) is None (no venv/ or .venv/), so the pre-existing+ # fallback layout names tmp_path/venv; VIRTUAL_ENV stays the seam's own env job.+ assert env["VIRTUAL_ENV"] == str(tmp_path / "venv")++ monkeypatch.setattr(pm_ensure, "uv", lambda **kw: (None, {}))+ prefix, env = main_install_repair._default_venv_install_target()+ assert prefix == [sys.executable, "-m", "pip"]+ assert env is None++diff --git a/tests/hermes_cli/test_update_parked_branch_guard.py b/tests/hermes_cli/test_update_parked_branch_guard.pyindex 9417f04a7af..8e269fa3877 100644--- a/tests/hermes_cli/test_update_parked_branch_guard.py+++ b/tests/hermes_cli/test_update_parked_branch_guard.py@@ -319,9 +319,11 @@ def test_update_switches_unmerged_parked_branch_with_kept_notice(class _StopFlow(Exception):pass+ # Retired self-lock guard replaced by the first post-pull dependency phase as the+ # flow-stop sentinel (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(- hermes_main,- "_abort_dependency_sync_if_self_locked",+ update_cmd,+ "_sync_python_dependencies_after_pull",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)@@ -373,9 +375,11 @@ def test_update_updates_unmerged_branch_in_place_when_configured(class _StopFlow(Exception):pass+ # Retired self-lock guard replaced by the first post-pull dependency phase as the+ # flow-stop sentinel (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(- hermes_main,- "_abort_dependency_sync_if_self_locked",+ update_cmd,+ "_sync_python_dependencies_after_pull",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)@@ -428,9 +432,11 @@ def test_switch_branch_flag_overrides_in_place_strategy(class _StopFlow(Exception):pass+ # Retired self-lock guard replaced by the first post-pull dependency phase as the+ # flow-stop sentinel (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(- hermes_main,- "_abort_dependency_sync_if_self_locked",+ update_cmd,+ "_sync_python_dependencies_after_pull",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(@@ -478,9 +484,11 @@ def test_unmerged_branch_still_updates_in_place_without_the_flag(class _StopFlow(Exception):pass+ # Retired self-lock guard replaced by the first post-pull dependency phase as the+ # flow-stop sentinel (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(- hermes_main,- "_abort_dependency_sync_if_self_locked",+ update_cmd,+ "_sync_python_dependencies_after_pull",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(@@ -508,13 +516,15 @@ def test_update_auto_switches_clean_merged_parked_branch(guard re-parks the checkout and this test fails on the branch assert)."""_patch_update_flow(monkeypatch, repo_pair)# Stop the flow right after the pull/branch logic: the dependency- # install phase begins with _abort_dependency_sync_if_self_locked.+ # install phase begins with _sync_python_dependencies_after_pull.class _StopFlow(Exception):pass+ # Retired self-lock guard replaced by the first post-pull dependency phase as the+ # flow-stop sentinel (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(- hermes_main,- "_abort_dependency_sync_if_self_locked",+ update_cmd,+ "_sync_python_dependencies_after_pull",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)@@ -595,9 +605,11 @@ def test_update_on_main_fast_path_unchanged(repo_pair, monkeypatch, capsys):class _StopFlow(Exception):pass+ # Retired self-lock guard replaced by the first post-pull dependency phase as the+ # flow-stop sentinel (pm-clean-audit-49945b1402 item 9).monkeypatch.setattr(- hermes_main,- "_abort_dependency_sync_if_self_locked",+ update_cmd,+ "_sync_python_dependencies_after_pull",lambda *a, **k: (_ for _ in ()).throw(_StopFlow()),)args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False)diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.pyindex 95ab333b4c2..6ce876dcd5a 100644--- a/tests/hermes_cli/test_update_self_lock.py+++ b/tests/hermes_cli/test_update_self_lock.py@@ -1,275 +1,11 @@-"""Regression coverage for the updater self-lock deferral (#83569, #86735).--``_detect_venv_python_processes`` excludes the calling process and its-ancestors by design — a CLI ``hermes update`` IS the venv python. Before-this guard, an updater that had already imported a native venv extension-(e.g. ``cryptography.hazmat.bindings._rust``) died mid-sync with-``os error 5`` when ``uv`` tried to replace the mapped ``.pyd``, stranding-the venv half-updated (#83569).--The first version of the guard (#86687) fired as a PRE-FETCH preflight and-keyed on nothing but "is the module in sys.modules" — which was ALWAYS true-while ``bitwarden.py`` imported cryptography at module level, so every-Windows ``hermes update`` exited 2 before even fetching and the update-looped forever (#86735 / #86780 / #86781). The guard is now honest:--* it only reports a loaded module when the dependency sync would actually- REWRITE that distribution (``_dependency_sync_would_rewrite`` — installed- version vs the on-disk pyproject pins);-* it runs AFTER the code swap, immediately before the venv rewrite- (``_abort_dependency_sync_if_self_locked``), so a deferral leaves the- user on NEW code with only the dependency install pending.-"""--from __future__ import annotations-+"""CLI metadata dispatch keeps credential implementations lazy."""import subprocessimport sysimport textwrapfrom pathlib import Path-from unittest.mock import MagicMock, patch--import pytest--import hermes_cli.main as cli_main-import hermes_cli.update_cmd as update_cmd-from hermes_cli import _early_recoveryROOT = Path(__file__).resolve().parents[2]--# ----------------------------------------------------------------------------# _dependency_sync_would_rewrite-# ------------------------------------------------------------------------------class TestDependencySyncWouldRewrite:- def _with_pyproject(self, tmp_path, body: str):- (tmp_path / "pyproject.toml").write_text(body, encoding="utf-8")- return patch.object(cli_main, "PROJECT_ROOT", tmp_path)-- def test_satisfied_pin_means_no_rewrite(self, tmp_path):- with self._with_pyproject(- tmp_path,- '[project]\nname = "x"\ndependencies = ["cryptography==1.2.3"]\n',- ), patch("importlib.metadata.version", return_value="1.2.3"):- assert cli_main._dependency_sync_would_rewrite("cryptography") is False-- def test_stale_pin_means_rewrite(self, tmp_path):- with self._with_pyproject(- tmp_path,- '[project]\nname = "x"\ndependencies = ["cryptography==2.0.0"]\n',- ), patch("importlib.metadata.version", return_value="1.2.3"):- assert cli_main._dependency_sync_would_rewrite("cryptography") is True-- def test_missing_distribution_means_rewrite(self, tmp_path):- with self._with_pyproject(- tmp_path,- '[project]\nname = "x"\ndependencies = ["cryptography==2.0.0"]\n',- ), patch(- "importlib.metadata.version",- side_effect=Exception("not installed"),- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is True-- def test_pin_in_optional_extra_is_honored(self, tmp_path):- body = textwrap.dedent(- """- [project]- name = "x"- dependencies = []- [project.optional-dependencies]- all = ["cryptography>=2,<3"]- """- )- with self._with_pyproject(tmp_path, body), patch(- "importlib.metadata.version", return_value="2.5.0"- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is False- with self._with_pyproject(tmp_path, body), patch(- "importlib.metadata.version", return_value="1.0.0"- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is True-- def test_unpinned_distribution_is_unknown(self, tmp_path):- with self._with_pyproject(- tmp_path, '[project]\nname = "x"\ndependencies = ["requests"]\n'- ), patch("importlib.metadata.version", return_value="1.0.0"):- assert cli_main._dependency_sync_would_rewrite("pyyaml") is None-- def test_broken_pyproject_is_unknown_never_raises(self, tmp_path):- with self._with_pyproject(tmp_path, "not [valid toml"), patch(- "importlib.metadata.version", return_value="1.0.0"- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is None---# ----------------------------------------------------------------------------# _detect_self_loaded_native_modules — version-gated detection-# -----------------------------------------------------------------------------[email protected](cli_main, "_is_windows", return_value=False)-def test_self_lock_detection_is_noop_off_windows(_winp):- with patch.dict(sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}):- assert cli_main._detect_self_loaded_native_modules() == []--[email protected](cli_main, "_is_windows", return_value=True)-def test_loaded_module_with_pending_version_change_is_flagged(_winp):- with patch.dict(- sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}- ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):- assert "cryptography (_rust.pyd)" in cli_main._detect_self_loaded_native_modules()--[email protected](cli_main, "_is_windows", return_value=True)-def test_loaded_module_already_at_target_version_is_not_flagged(_winp):- """#86735 core fix: loaded-but-not-changing must NOT trip the deferral.-- Installed cryptography already satisfies the on-disk pins → the sync- will not touch ``_rust.pyd`` → no lock risk → the update must proceed.- """- with patch.dict(- sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}- ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=False):- assert cli_main._detect_self_loaded_native_modules() == []--[email protected](cli_main, "_is_windows", return_value=True)-def test_unknown_rewrite_risk_fails_open(_winp):- """Uncertain rewrite risk must NOT defer (None → proceed).-- PyYAML is loaded by every CLI process; deferring on an unparseable- pyproject would recreate the #86735 always-firing loop. The missed-- deferral downside is the pre-existing mid-sync failure, which the- marker recovery already handles.- """- with patch.dict(- sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}- ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=None):- assert cli_main._detect_self_loaded_native_modules() == []--[email protected](cli_main, "_is_windows", return_value=True)-def test_self_lock_detection_clean_when_rust_not_loaded(_winp):- sys.modules.pop("cryptography.hazmat.bindings._rust", None)- with patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):- assert (- "cryptography (_rust.pyd)"- not in cli_main._detect_self_loaded_native_modules()- )---def test_recovered_update_retry_builds_parser_without_native_secret_modules(- monkeypatch,-):- """Parser registration must not re-lock a freshly recovered updater."""- called = []- monkeypatch.setattr(_early_recovery, "_UPDATE_RETRY_RECOVERED", True)- monkeypatch.setattr(cli_main, "cmd_update", lambda args: called.append(args))- monkeypatch.setattr(sys, "argv", ["hermes", "update", "--yes"])- sys.modules.pop("cryptography.hazmat.bindings._rust", None)-- cli_main.main()-- assert len(called) == 1- assert "cryptography.hazmat.bindings._rust" not in sys.modules---# ----------------------------------------------------------------------------# _abort_dependency_sync_if_self_locked — deferral wiring-# ------------------------------------------------------------------------------def test_abort_helper_noop_when_nothing_at_risk():- with patch.object(- cli_main, "_detect_self_loaded_native_modules", return_value=[]- ), patch.object(cli_main, "_defer_update_for_self_lock") as defer:- cli_main._abort_dependency_sync_if_self_locked()- defer.assert_not_called()---def test_abort_helper_defers_and_exits_2(capsys):- marker_writes = []- with patch.object(- cli_main,- "_detect_self_loaded_native_modules",- return_value=["cryptography (_rust.pyd)"],- ), patch.object(- cli_main,- "_write_update_incomplete_marker",- side_effect=lambda: marker_writes.append("written"),- ), pytest.raises(SystemExit) as exc:- cli_main._abort_dependency_sync_if_self_locked()- assert exc.value.code == 2- # Deferral contract: marker dropped so the next fresh launch completes- # the dependency install (the code swap has already happened by now).- assert marker_writes == ["written"]- out = capsys.readouterr().out- assert "cryptography (_rust.pyd)" in out- assert "deferred" in out---def test_abort_helper_resumes_paused_gateways_before_exit():- resume_calls = []- sentinel = object()- with patch.object(- cli_main,- "_detect_self_loaded_native_modules",- return_value=["cryptography (_rust.pyd)"],- ), patch.object(cli_main, "_write_update_incomplete_marker"), patch.object(- cli_main,- "_resume_windows_gateways_after_update",- side_effect=lambda token: resume_calls.append(token),- ), pytest.raises(SystemExit):- cli_main._abort_dependency_sync_if_self_locked(sentinel)- assert resume_calls == [sentinel]---# ----------------------------------------------------------------------------# Placement: the deferral must NOT fire before the fetch (#86735 / #86780)-# ------------------------------------------------------------------------------def test_pre_fetch_flow_has_no_self_lock_preflight():- """#86780 regression: a loaded native module must not block the git fetch.-- The old preflight sat between the venv-holder sweep and the fetch, so a- universally-loaded module (bitwarden's module-level cryptography import)- deferred every update before any code was pulled — the Windows infinite- update loop. The deferral now lives at the dependency-sync boundaries- only; the stretch of _cmd_update_impl between the venv-holder sweep and- the fetch must not consult the detector at all.- """- import inspect-- src = inspect.getsource(update_cmd._cmd_update_impl)- fetch_idx = src.index("Fetching updates")- pre_fetch = src[:fetch_idx]- assert "_detect_self_loaded_native_modules()" not in pre_fetch- assert "_m()._abort_dependency_sync_if_self_locked" not in pre_fetch- # ... and it must still guard the dependency sync after the code swap- # (the sync itself lives in _sync_python_dependencies_after_pull).- post_fetch = src[fetch_idx:] + inspect.getsource(update_cmd._apply_pulled_update)- assert "_sync_python_dependencies_after_pull(" in post_fetch- sync_src = inspect.getsource(update_cmd._sync_python_dependencies_after_pull)- assert "_m()._abort_dependency_sync_if_self_locked" in sync_src---def test_zip_update_guards_dependency_sync():- import inspect-- src = inspect.getsource(update_cmd._update_via_zip)- swap_idx = src.index("Updating Python dependencies")- assert "_abort_dependency_sync_if_self_locked" in src[:swap_idx]---# ----------------------------------------------------------------------------# Import hygiene: the update entrypoint must not load cryptography at all-# -----------------------------------------------------------------------------class TestUpdateEntrypointImportHygiene:"""Subprocess-verified: the CLI/update path never eagerly loads crypto.@@ -294,15 +30,6 @@ class TestUpdateEntrypointImportHygiene:"""import sysimport hermes_cli.main- from hermes_cli.update_cmd import _SELF_LOCKING_NATIVE_MODULES- loaded = [- p for p in _SELF_LOCKING_NATIVE_MODULES- if p in sys.modules and not p.startswith("yaml")- ]- # PyYAML is a base dep every CLI process needs (config parsing);- # it is version-gated instead of import-gated. Everything else- # in the registry must stay lazy.- assert not loaded, f"eagerly loaded self-locking modules: {loaded}"assert "cryptography.hazmat.bindings._rust" not in sys.modulesprint("OK")"""diff --git a/tests/hermes_cli/test_update_serve_generation_recovery.py b/tests/hermes_cli/test_update_serve_generation_recovery.pyindex 36c6884bbda..0dfc1922ea8 100644--- a/tests/hermes_cli/test_update_serve_generation_recovery.py+++ b/tests/hermes_cli/test_update_serve_generation_recovery.py@@ -1001,6 +1001,7 @@ def test_restarted_dashboard_unit_is_not_killed_by_the_continued_scan(monkeypatcassert result["killed"] == [][email protected]("posix")def test_serve_backend_survives_selection_when_the_dashboard_unit_restarts(monkeypatch):"""A serve PID owned by a DIFFERENT unit is still selected for recovery."""from hermes_cli import dashboard_procsdiff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.pyindex bd47d4a2a42..857120557d0 100644--- a/tests/hermes_cli/test_update_shim_self_lock.py+++ b/tests/hermes_cli/test_update_shim_self_lock.py@@ -212,51 +212,6 @@ def test_up_to_date_run_never_hands_off(venv, monkeypatch, capsys):assert calls == [], "an up-to-date run must not spawn a detached child"-def test_sync_guard_hands_off_when_only_the_shim_is_held(venv, monkeypatch):- """No native module mapped, but we ARE the shim: hand off and exit 0."""- from hermes_cli import update_cmd-- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])- monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])- calls = _capture_popen(monkeypatch)-- with pytest.raises(SystemExit) as excinfo:- update_cmd._abort_dependency_sync_if_self_locked()-- assert excinfo.value.code == 0- assert calls, "expected the dependency sync to be handed to the venv python"---def test_sync_guard_defers_native_lock_before_considering_the_shim(venv, monkeypatch):- """A mapped .pyd still exits 2 — the marker recovery owns that case."""- from hermes_cli import update_cmd-- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])- monkeypatch.setattr(- cli_main, "_detect_self_loaded_native_modules", lambda: ["PyYAML (_yaml.pyd)"]- )- monkeypatch.setattr(cli_main, "_defer_update_for_self_lock", lambda loaded: None)- calls = _capture_popen(monkeypatch)-- with pytest.raises(SystemExit) as excinfo:- update_cmd._abort_dependency_sync_if_self_locked()-- assert excinfo.value.code == 2- assert calls == [], "a native-module deferral must not also spawn a child"---def test_sync_guard_is_a_noop_when_nothing_is_held(venv, monkeypatch):- """Off the shim with nothing mapped, the sync just proceeds in-process."""- from hermes_cli import update_cmd-- monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])- calls = _capture_popen(monkeypatch)-- update_cmd._abort_dependency_sync_if_self_locked()- assert calls == []---# ---------------------------------------------------------------------------# Reboot-deferred renames# ---------------------------------------------------------------------------diff --git a/tests/hermes_cli/test_update_venv_ownership_preflight.py b/tests/hermes_cli/test_update_venv_ownership_preflight.pyindex 9a7820c2e4d..4058ecd2785 100644--- a/tests/hermes_cli/test_update_venv_ownership_preflight.py+++ b/tests/hermes_cli/test_update_venv_ownership_preflight.py@@ -46,6 +46,7 @@ def test_all_owned_preflight_proceeds(tmp_path, monkeypatch, capsys):assert capsys.readouterr().out == ""[email protected]("posix")def test_foreign_owned_dist_info_child_detected(tmp_path, monkeypatch):venv = _make_fake_venv(tmp_path)installer = str(@@ -65,6 +66,7 @@ def test_foreign_owned_dist_info_child_detected(tmp_path, monkeypatch):assert foreign == [(installer, 0)][email protected]("posix")def test_foreign_owned_refuses_with_chown_hint(tmp_path, monkeypatch, capsys):venv = _make_fake_venv(tmp_path)hermes_bin = str(venv / "bin" / "hermes")diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.pyindex 13ae6c1a795..de68900ba3b 100644--- a/tests/hermes_cli/test_update_yes_flag.py+++ b/tests/hermes_cli/test_update_yes_flag.py@@ -25,6 +25,7 @@ def _isolate_venv_holders(monkeypatch):import hermes_cli.main as cli_mainmonkeypatch.setattr(cli_main, "_detect_venv_python_processes", lambda: [])+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)def _make_run_side_effect(diff --git a/tests/hermes_cli/test_update_zip_symlink_reject.py b/tests/hermes_cli/test_update_zip_symlink_reject.pyindex 88b615c0915..f82191fcd99 100644--- a/tests/hermes_cli/test_update_zip_symlink_reject.py+++ b/tests/hermes_cli/test_update_zip_symlink_reject.py@@ -49,6 +49,7 @@ def test_update_via_zip_rejects_symlink_member(tmp_path, monkeypatch):from hermes_cli.update_cmd import _update_via_zipmonkeypatch.setattr(hermes_main, "PROJECT_ROOT", fake_root)+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)args = type("Args", (), {})()@@ -108,6 +109,7 @@ def test_update_via_zip_accepts_normal_member(tmp_path, monkeypatch, capsys):from hermes_cli import main as hermes_mainmonkeypatch.setattr(hermes_main, "PROJECT_ROOT", fake_root)+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)args = type("Args", (), {})()diff --git a/tests/hermes_cli/test_update_zip_sync_failure.py b/tests/hermes_cli/test_update_zip_sync_failure.pynew file mode 100644index 00000000000..3e8faff3b43--- /dev/null+++ b/tests/hermes_cli/test_update_zip_sync_failure.py@@ -0,0 +1,41 @@+"""A failed dependency transaction must stop the ZIP update, not report success."""+import pytest++import pm+from hermes_cli import update_cmd_zip+++def test_zip_dependency_failure_propagates_before_followup_mutations(monkeypatch):+ import hermes_cli.main as main+ monkeypatch.setattr(pm, "ensure", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(pm, "uv", lambda **_kwargs: ("uv", {}))+ def fail(*args, **kwargs):+ raise pm.InstallError("venv", "network unavailable")+ monkeypatch.setattr(pm, "sync_venv", fail)+ def forbidden(*args, **kwargs):+ raise AssertionError("follow-up mutation after failed sync")+ monkeypatch.setattr(main, "_refresh_active_memory_provider_dependencies", forbidden)+ with pytest.raises(pm.InstallError, match="network unavailable"):+ update_cmd_zip._reinstall_python_deps_after_zip([])+++def test_pull_dependency_failure_keeps_recovery_marker(tmp_path, monkeypatch):+ import hermes_cli.main as main+ from hermes_cli import update_cmd_deps, update_cmd++ monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)+ monkeypatch.setattr(main, "_refuse_update_for_contended_shims", lambda *a: None, raising=False)+ monkeypatch.setattr(update_cmd, "_write_update_incomplete_marker", lambda: None)+ monkeypatch.setattr(main, "_capture_active_tool_dependencies", lambda: [])+ def fail(*a, **k):+ raise pm.InstallError("venv", "sync stopped")+ monkeypatch.setattr(pm, "sync_venv", fail)+ monkeypatch.setattr(pm, "uv", lambda **k: (None, {}))+ def forbidden(*a, **k):+ raise AssertionError("must retain recovery marker")+ monkeypatch.setattr(main, "_clear_update_incomplete_marker", forbidden)+ with pytest.raises(pm.InstallError, match="sync stopped"):+ update_cmd_deps._sync_python_dependencies_after_pull(+ ["git"], "main", "a" * 40, active_lazy_features=[], active_tool_dependencies=[],+ _windows_gateway_resume=[], desktop_dir=tmp_path, had_desktop_app_before_update=False,+ )diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.pyindex 89b2552e0aa..79a1fcb8572 100644--- a/tests/hermes_cli/test_update_zip_two_phase.py+++ b/tests/hermes_cli/test_update_zip_two_phase.py@@ -151,45 +151,6 @@ def test_venv_helpers_are_platform_consistent():assert (bin_name, exe_name) in {("Scripts", "python.exe"), ("bin", "python")}-def test_no_open_coded_venv_layout_remains_in_hermes_cli():- """Fails if a new call site hand-rolls Scripts/bin again (#76105).-- Uses AST rather than substring matching: an earlier `"if" in line` version- matched any word containing "if" (mod*if*y, ver*if*y) and still missed- `os.path.join(venv, "Scripts")`.-- ``stdio.py`` is exempt: it builds a list of literal *Windows-only* PATH- candidates, not a cross-platform layout derivation, so ``venv_bin_dir()``- (which branches on the host platform) would be the wrong tool there.- """- import ast- import hermes_cli-- exempt = {"stdio.py"}- pkg = Path(hermes_cli.__file__).parent- offenders = []- for py in pkg.rglob("*.py"):- if py.name in exempt:- continue- try:- tree = ast.parse(py.read_text(encoding="utf-8", errors="replace"))- except SyntaxError:- continue- for node in ast.walk(tree):- # Any *code* string literal "Scripts" is a hand-rolled layout;- # docstrings and comments never reach ast.Constant in an expr- # position we care about here.- if isinstance(node, ast.Constant) and node.value == "Scripts":- offenders.append(f"{py.relative_to(pkg)}:{node.lineno}")- assert not offenders, (- "open-coded venv layout found (use hermes_constants.venv_bin_dir):\n"- + "\n".join(offenders)- )---# ----------------------------------------------------------------------------# Top-level FILES must be atomic too (#76104 review, C1)-# ---------------------------------------------------------------------------def test_top_level_files_are_swapped_atomically(tmp_path):"""The repo root holds 20 first-party modules (run_agent.py, cli.py,diff --git a/tests/hermes_cli/test_web_memory_provider_setup_install.py b/tests/hermes_cli/test_web_memory_provider_setup_install.pynew file mode 100644index 00000000000..d3227901e39--- /dev/null+++ b/tests/hermes_cli/test_web_memory_provider_setup_install.py@@ -0,0 +1,143 @@+"""C16: web dashboard memory-provider setup must install declared provider+extras through pm's sync authority (plugin.yaml ``extra:`` / materialized+legacy ``python_dependencies``), never ``tools.lazy_deps`` or raw pip, and+must report restart-required truthfully when the boot-selected environment+can't see a fresh install."""++from types import SimpleNamespace+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from hermes_cli.web_routers import memory_providers as mp+++def routed(monkeypatch):+ """Mutable harness over the module-level collaborators."""+ state = SimpleNamespace(+ importable=set(), # dep names that import cleanly+ manifest={},+ plugin_dir=None,+ sync_calls=[], # (extras, explicit)+ materialized=[], # plugin_dir args+ sync_error=None,+ )++ monkeypatch.setattr(mp, "_memory_provider_manifest", lambda name: state.manifest)++ import plugins.memory as plugins_memory+ monkeypatch.setattr(+ plugins_memory, "find_provider_dir", lambda name: state.plugin_dir,+ raising=False,+ )++ import hermes_cli.web_server_memory as wsm+ _IMPORT_OF = {"mem0ai": "mem0", "honcho-ai": "honcho"}++ def fake_importable(dep):+ package = dep.split("[")[0]+ for ch in "<>=!~;":+ package = package.split(ch)[0]+ return _IMPORT_OF.get(package.strip(), package.strip().replace("-", "_")) in state.importable++ monkeypatch.setattr(mp, "_dependency_importable", fake_importable)++ import pm+ def fake_sync_venv(extras=None, *, explicit=False, plugin_dirs=None):+ state.sync_calls.append((extras, explicit))+ state.materialized.extend(plugin_dirs or [])+ if state.sync_error:+ raise state.sync_error+ # A successful sync makes freshly installed dists importable in-process.+ if getattr(state, "sync_effect", True):+ state.importable |= {"mem0", "honcho", "freshpkg"}++ monkeypatch.setattr(pm, "sync_venv", fake_sync_venv)++ return state+++class TestDeclaredExtraRouting:+ def test_extra_synced_explicitly_when_import_missing(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.importable = set()++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert routed.sync_calls == [(["mem0"], True)]+ assert rows[0]["status"] == "installed"++ def test_no_sync_when_everything_imports(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.importable = {"mem0"}++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert routed.sync_calls == []+ assert rows[0]["status"] == "already_installed"++ def test_sync_failure_reports_failed_row(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.sync_error = RuntimeError("sealed venv refuses extras")++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert rows[0]["status"] == "failed"+ assert "sealed venv" in rows[0]["stderr"]+++class TestLegacyPythonDependencies:+ def test_third_party_python_dependencies_bridge(self, routed, tmp_path):+ routed.manifest = {"python_dependencies": ["freshpkg"]}+ routed.plugin_dir = tmp_path / "external-provider"+ routed.plugin_dir.mkdir()+ (routed.plugin_dir / "plugin.yaml").write_text("name: ext\npython_dependencies: [freshpkg]\n")+ routed.importable = set()++ rows = mp._install_memory_provider_pip_dependencies("ext", ["freshpkg"])++ assert routed.materialized == [routed.plugin_dir]+ assert routed.sync_calls == [(None, True)]+ assert rows[0]["status"] == "installed"++ def test_legacy_specs_without_plugin_dir_fail_honestly(self, routed):+ routed.manifest = {"python_dependencies": ["freshpkg"]}+ routed.plugin_dir = None++ rows = mp._install_memory_provider_pip_dependencies("ext", ["freshpkg"])++ assert routed.sync_calls == []+ assert rows[0]["status"] == "failed"+++class TestRestartTruthfulness:+ def test_install_that_boot_env_cannot_see_is_restart_required(self, routed):+ routed.manifest = {"extra": "mem0"}+ routed.importable = set()+ # Sync succeeds but the freshly installed dist stays invisible+ # to this boot-selected interpreter.+ routed.sync_effect = False++ rows = mp._install_memory_provider_pip_dependencies("mem0", ["mem0ai"])++ assert rows[0]["status"] == "restart_required"+ assert rows[0]["status"] != "failed"++ def test_setup_result_counts_restart_required_as_not_failed(self, routed, monkeypatch):+ routed.manifest = {"extra": "mem0"}+ monkeypatch.setattr(+ mp, "_install_memory_provider_pip_dependencies",+ lambda name, deps: [{"kind": "pip", "name": "mem0ai", "status": "restart_required",+ "command": "hermes pm install mem0", "returncode": None,+ "stdout": "", "stderr": ""}],+ )+ monkeypatch.setattr(mp, "_memory_provider_setup_manifest",+ lambda name: {"pip_dependencies": ["mem0ai"], "external_dependencies": [],+ "required_env": []})+ monkeypatch.setattr(mp, "_discover_memory_provider_statuses", lambda: {})++ result = mp._install_memory_provider_setup("mem0")++ assert result["ok"] is Truediff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 39eac3af164..6c77b39c841 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -904,8 +904,11 @@ class TestWebServerEndpoints:import hermes_cli.web_server as web_serverimport pm- # honcho declares pip_dependencies: [honcho-ai]; force it missing.- monkeypatch.setattr(_web_server_memory, "_dependency_importable", lambda dep: False)+ # Force a provider with declared legacy dependencies and an owned extra.+ manifest = {"pip_dependencies": ["honcho-ai"], "extra": "honcho"}+ monkeypatch.setattr("hermes_cli.web_server_memory._memory_provider_manifest", lambda name: manifest)+ monkeypatch.setattr("hermes_cli.web_routers.memory_providers._memory_provider_manifest", lambda name: manifest)+ monkeypatch.setattr("hermes_cli.web_routers.memory_providers._dependency_importable", lambda dep: False)installed = []@@ -931,7 +934,7 @@ class TestWebServerEndpoints:assert resp.status_code == 200data = resp.json()pip_rows = [row for row in data["results"] if row["kind"] == "pip"]- assert pip_rows and pip_rows[0]["status"] == "installed"+ assert pip_rows and pip_rows[0]["status"] == "restart_required"assert pip_rows[0]["command"] == "hermes pm install"assert installed == [("honcho",)]@@ -1275,7 +1278,7 @@ class TestWebServerEndpoints:# guidance instead of Termux-specific refusal.import hermes_cli.web_server as web_server- monkeypatch.setattr(web_server, "_dashboard_local_update_managed_externally", lambda: False)+ monkeypatch.setattr("hermes_cli.web_server_files._dashboard_local_update_managed_externally", lambda: False)monkeypatch.setattr(_cfg_mod, "detect_install_method", lambda _root: "unknown")check = self.client.get("/api/hermes/update/check")diff --git a/tests/hermes_cli/test_windows_native_docs.py b/tests/hermes_cli/test_windows_native_docs.pyindex b996d0b5196..659f586e0a5 100644--- a/tests/hermes_cli/test_windows_native_docs.py+++ b/tests/hermes_cli/test_windows_native_docs.py@@ -3,7 +3,6 @@ from pathlib import Pathdef test_windows_native_install_path_docs_match_installer() -> None:doc = Path("website/docs/user-guide/windows-native.md").read_text()- install = Path("scripts/install.ps1").read_text()# The launchers live in the managed binary dir OUTSIDE the git checkout# (HERMES_HOME\bin, next to the managed uv) — NOT the whole venv\Scripts@@ -14,9 +13,3 @@ def test_windows_native_install_path_docs_match_installer() -> None:"Get-Command hermes # should print ""C:\\Users\\<you>\\AppData\\Local\\hermes\\bin\\hermes.exe") in doc- # Installer exposes $HermesHome\bin, and must copy the launchers into it.- assert 'Join-Path $HermesHome "bin"' in install- assert "hermes.exe" in install and "hermes-acp.exe" in install- # Guard against regressions to either legacy layout.- assert '$hermesBin = "$InstallDir\\venv\\Scripts"' not in install- assert '$hermesBin = "$InstallDir\\bin"' not in installdiff --git a/tests/hermes_cli/test_worktree_gc.py b/tests/hermes_cli/test_worktree_gc.pyindex 03e24a51ed4..5ed39bc8377 100644--- a/tests/hermes_cli/test_worktree_gc.py+++ b/tests/hermes_cli/test_worktree_gc.py@@ -159,7 +159,8 @@ class TestReclaim:records = worktree_gc.audit_worktrees(str(repo), with_sizes=False)worktree_gc.reclaim_worktrees(str(repo), records=records)assert not tree.exists()- archive_root = Path.home() / ".hermes" / "archive" / "worktree-prune"+ from hermes_constants import get_hermes_home+ archive_root = get_hermes_home() / "archive" / "worktree-prune"archived = list(archive_root.rglob("NOTES.md"))assert archived, "untracked file must be archived, not destroyed"assert archived[0].read_text() == "important scribbles\n"diff --git a/tests/hermes_state/test_shared_session_db_registry.py b/tests/hermes_state/test_shared_session_db_registry.pyindex 58d4837625d..7dfe80b79e5 100644--- a/tests/hermes_state/test_shared_session_db_registry.py+++ b/tests/hermes_state/test_shared_session_db_registry.py@@ -55,6 +55,7 @@ def _replace_file_preserving_schema(src: Path, dst: Path) -> None:os.rename(tmp, dst)[email protected]("posix")class TestInodeReplacement:def test_live_holders_keep_working_handle_across_replacement(self, tmp_path):"""Two active refs → inode replacement → third caller gets NEWdiff --git a/tests/hermes_state/test_state_db_corrupt_quarantine.py b/tests/hermes_state/test_state_db_corrupt_quarantine.pyindex 2acac229391..a4a0dd31d31 100644--- a/tests/hermes_state/test_state_db_corrupt_quarantine.py+++ b/tests/hermes_state/test_state_db_corrupt_quarantine.py@@ -163,6 +163,7 @@ class TestQuarantineScope:finally:db.close()+ @pytest.mark.platforms("posix")def test_replaced_file_takes_precedence_over_corrupt(self, tmp_path):import osdiff --git a/tests/hermes_state/test_state_db_file_identity.py b/tests/hermes_state/test_state_db_file_identity.pyindex 3cc1ca12720..e402807a167 100644--- a/tests/hermes_state/test_state_db_file_identity.py+++ b/tests/hermes_state/test_state_db_file_identity.py@@ -33,6 +33,7 @@ def _require_identity(db: SessionDB) -> None:pytest.skip("filesystem does not expose st_dev/st_ino for identity checks")[email protected]("posix")def test_replace_with_new_inode_fails_loudly_without_fts_repair(tmp_path):live = tmp_path / "state.db"other = tmp_path / "other.db"@@ -56,6 +57,7 @@ def test_replace_with_new_inode_fails_loudly_without_fts_repair(tmp_path):db.close()[email protected]("posix")def test_second_write_after_halt_does_not_attempt_repair(tmp_path):live = tmp_path / "state.db"other = tmp_path / "other.db"@@ -125,6 +127,7 @@ def test_new_sessiondb_on_replaced_path_records_new_identity(tmp_path):reopened.close()[email protected]("posix")def test_fts_scoped_error_on_replaced_file_skips_fts_fail_open(tmp_path):"""Even FTS-provenance corruption must not authorize surgery on areplaced file. (A generic malformed error never reaches fail-open atdiff --git a/tests/monitoring/test_gateway_health_export.py b/tests/monitoring/test_gateway_health_export.pyindex 5e24671e5d2..bdff8a7d29d 100644--- a/tests/monitoring/test_gateway_health_export.py+++ b/tests/monitoring/test_gateway_health_export.py@@ -100,6 +100,82 @@ def test_diagnostic_log_attributes_are_allowlisted_redacted_and_profile_free():+def test_gateway_health_metrics_reach_loopback_collector():+ """Exercise the real SDK loader, metric provider and OTLP transport together."""+ import threading+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++ import pytest++ pytest.importorskip("opentelemetry.sdk.metrics", reason="otlp extra not installed")+ from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ExportMetricsServiceRequest+ from agent.monitoring.gateway_health_export import start_gateway_health_export++ received = []+ delivered = threading.Event()++ class Collector(BaseHTTPRequestHandler):+ def do_POST(self):+ payload = self.rfile.read(int(self.headers["Content-Length"]))+ received.append((self.path, ExportMetricsServiceRequest.FromString(payload)))+ self.send_response(200)+ self.send_header("Content-Length", "0")+ self.end_headers()+ delivered.set()++ def log_message(self, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Collector)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ runtime = None+ try:+ runtime = start_gateway_health_export({"monitoring": {+ "install_id": "test-install",+ "export": {"otlp": {"enabled": True, "endpoint": f"http://127.0.0.1:{server.server_port}/v1/traces"}},+ "gateway_health_export": {+ "enabled": True, "metrics_enabled": True, "diagnostic_events_enabled": False,+ },+ }})+ assert runtime.enabled, runtime.reason+ assert runtime.metric_provider.force_flush(timeout_millis=10000)+ assert delivered.wait(timeout=10)+ assert all(path == "/v1/metrics" for path, _ in received)+ names = {metric.name for _, request in received+ for resource in request.resource_metrics+ for scope in resource.scope_metrics for metric in scope.metrics}+ assert "hermes.gateway.up" in names+ finally:+ if runtime is not None:+ runtime.shutdown()+ server.shutdown()+ server.server_close()+ thread.join(timeout=10)+++def test_start_gateway_health_export_reports_otlp_unavailable_when_sdk_missing(monkeypatch):+ import agent.monitoring.gateway_health_export as gw+ from agent.monitoring.otlp_exporter import OTLPUnavailable++ config = {+ "monitoring": {+ "export": {"otlp": {"enabled": True, "endpoint": "http://127.0.0.1:4318"}},+ "gateway_health_export": {"enabled": True, "metrics_enabled": True, "diagnostic_events_enabled": False},+ }+ }++ def no_sdk(*args, **kwargs):+ raise OTLPUnavailable("missing")++ monkeypatch.setattr(gw.otlp_exporter, "_require_sdk", no_sdk)++ runtime = gw.start_gateway_health_export(config)++ assert runtime.enabled is False+ assert runtime.reason == "otlp_unavailable"++def test_install_id_persists_across_calls(tmp_path, monkeypatch):"""A minted install id must survive restarts (service.instance.id continuity)."""monkeypatch.setenv("HERMES_HOME", str(tmp_path))diff --git a/tests/plugins/image_gen/test_meta_ai_provider.py b/tests/plugins/image_gen/test_meta_ai_provider.pyindex 3ff129a539a..17d5549b52e 100644--- a/tests/plugins/image_gen/test_meta_ai_provider.py+++ b/tests/plugins/image_gen/test_meta_ai_provider.py@@ -290,7 +290,7 @@ class TestGenerate:result = provider.generate("a cat")assert result["success"] is True- assert result["image"].startswith("/")+ assert Path(result["image"]) == mock_save_url.return_valueassert "example.com" not in result["image"]mock_save_url.assert_called_once()diff --git a/tests/plugins/memory/test_hindsight_embedded_runtime.py b/tests/plugins/memory/test_hindsight_embedded_runtime.pynew file mode 100644index 00000000000..6b04d04c453--- /dev/null+++ b/tests/plugins/memory/test_hindsight_embedded_runtime.py@@ -0,0 +1,305 @@+"""The isolated local_embedded Hindsight runtime (embedded_runtime).++Real imports of the plugin modules; the only fakes sit at the subprocess+boundary (the uv bridge invocations and the side-python bridge) — the URL the+daemon reports is proven against a real loopback HTTP /health server, never a+constant port. The boot-selected main environment is never touched.+"""++import http.server+import json+import subprocess+import threading+from types import SimpleNamespace++import pytest++import plugins.memory.hindsight.embedded_runtime as rt++_STATE = rt._STATE_FILE+++def side_root(tmp_path, monkeypatch):+ root = tmp_path / "hermes-home" / "profiles" / "Hindsight" / "env"+ monkeypatch.setattr(rt, "sideenv_root", lambda: root)+ return root+++def _fake_completed(returncode=0, stdout="", stderr=""):+ return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)+++# -- pinned pyproject ---------------------------------------------------------+++def test_sideenv_pyproject_pins_exact_pair():+ text = rt.sideenv_pyproject()+ assert 'hindsight-embed==0.9.2' in text+ assert 'hindsight-api-slim[all]==0.9.2' in text # [all]: full feature parity+ assert 'requires-python = ">=3.11"' in text+++# -- ensure_sideenv: candidate build -> atomic commit via the pm uv bridge ----+++def test_ensure_sideenv_builds_and_publishes_generation(side_root, monkeypatch):+ calls = []++ def fake_bridge(venv):+ calls.append(("bridge", venv))+ return "uv-bin", {"VIRTUAL_ENV": str(venv)}++ def fake_run(uv_bin, env, args, timeout):+ calls.append(("run", [uv_bin, *args], env))+ return _fake_completed()++ monkeypatch.setattr(rt, "_uv_bridge", fake_bridge)+ monkeypatch.setattr(rt, "_run_uv", fake_run)++ gen = rt.ensure_sideenv()++ # The generation was built at its FINAL path (no rename), published by the+ # selection record, and no candidate/prev leftovers exist.+ assert gen.is_dir() and gen.name.startswith("gen-")+ assert rt.sideenv_pyproject() in (gen / "pyproject.toml").read_text(encoding="utf-8")+ assert json.loads((gen / _STATE).read_text(encoding="utf-8"))["pins"] == rt._EXPECTED+ assert json.loads((side_root / "active.json").read_text(encoding="utf-8"))["generation"] == gen.name+ assert [p for p in side_root.iterdir() if p.is_dir()] == [gen]+ # uv invoked for lock+sync against the generation's own venv.+ runs = [c for c in calls if c[0] == "run"]+ assert [c[1][1] for c in runs] == ["lock", "sync"]+ assert all(c[2]["VIRTUAL_ENV"].endswith(".venv") for c in runs)+ assert calls[0][1] == gen / ".venv"+++def test_ensure_sideenv_short_circuits_when_current(side_root, monkeypatch):+ gen = side_root / "gen-1"+ gen.mkdir(parents=True)+ (side_root / "active.json").write_text(json.dumps({"generation": "gen-1", "pins": rt._EXPECTED}), encoding="utf-8")+ (gen / _STATE).write_text(json.dumps({"pins": rt._EXPECTED}), encoding="utf-8")+ scripts = gen / ".venv" / "Scripts"+ scripts.mkdir(parents=True)+ (scripts / "python.exe").write_bytes(b"")+ monkeypatch.setattr(rt, "_uv_bridge", lambda venv: pytest.fail("bridge used for an up-to-date env"))+ assert rt.ensure_sideenv() == gen+++def test_ensure_sideenv_failure_preserves_previous_generation(side_root, monkeypatch):+ old = side_root / "gen-old"+ old.mkdir(parents=True)+ (old / "keep.txt").write_text("old", encoding="utf-8")+ (side_root / "active.json").write_text(json.dumps({"generation": "gen-old"}), encoding="utf-8")++ def boom(*a, **kw):+ raise RuntimeError("uv sync failed: disk full")++ monkeypatch.setattr(rt, "_uv_bridge", boom)+ with pytest.raises(RuntimeError, match="disk full"):+ rt.ensure_sideenv()+ # Previous generation untouched and still the published one; the failed+ # unpublished generation is gone.+ assert (old / "keep.txt").read_text(encoding="utf-8") == "old"+ assert json.loads((side_root / "active.json").read_text(encoding="utf-8"))["generation"] == "gen-old"+ assert [p for p in side_root.iterdir() if p.is_dir()] == [old]+++# -- runtime probe: side interpreter, never the boot env ----------------------+++def test_check_local_runtime_probes_the_side_python(side_root, monkeypatch):+ py = _install_side_python(side_root)+ seen = {}++ def fake_run(cmd, **kw):+ seen["cmd"] = list(cmd)+ return _fake_completed()++ monkeypatch.setattr(rt.subprocess, "run", fake_run)+ assert rt.check_local_runtime() == (True, None)+ assert seen["cmd"][0] == str(py)+ # The probe covers the API + manager + embedding stack (old-CPU NumPy class).+ assert "hindsight_embed.daemon_embed_manager" in seen["cmd"][2]+ assert "hindsight_api" in seen["cmd"][2]+ assert "sentence_transformers" in seen["cmd"][2]+++def test_check_local_runtime_reports_probe_failure(side_root, monkeypatch):+ _install_side_python(side_root)+ monkeypatch.setattr(+ rt.subprocess, "run",+ lambda cmd, **kw: _fake_completed(returncode=1, stderr="Illegal instruction (core dumped)"),+ )+ ok, reason = rt.check_local_runtime()+ assert ok is False+ assert "Illegal instruction" in reason+++def test_check_local_runtime_missing_env_names_the_fix(side_root):+ ok, reason = rt.check_local_runtime()+ assert ok is False+ assert "hermes memory setup" in reason+ assert str(side_root) in reason+++# -- daemon bridge: URL from the side env, loopback-proven --------------------+++class _LoopbackHealth(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"ok")++ def log_message(self, *args):+ pass+++def loopback_health():+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _LoopbackHealth)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ yield f"http://127.0.0.1:{server.server_address[1]}"+ server.shutdown()+ server.server_close()+++def _install_side_python(side_root, name="gen-1"):+ """A minimal 'installed' generation: selection record + interpreter file."""+ gen = side_root / name+ scripts = gen / ".venv" / "Scripts"+ scripts.mkdir(parents=True, exist_ok=True)+ (side_root / "active.json").write_text(json.dumps({"generation": name}), encoding="utf-8")+ py = scripts / "python.exe"+ py.write_bytes(b"")+ return py+++def test_ensure_daemon_url_from_sideenv_output_is_reachable(side_root, monkeypatch, loopback_health):+ """The bridge subprocess reports the URL the side env resolved (here: a real+ loopback /health server) — the plugin never invents a port."""+ py = _install_side_python(side_root)+ seen = {}++ def fake_run(cmd, *, env=None, **kw):+ seen["cmd"], seen["env"] = list(cmd), env+ # Manager noise on stdout; the marked JSON line is the authoritative tail.+ return _fake_completed(+ stdout=" Loading profile hermes\n"+ f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health})+ )++ monkeypatch.setattr(rt.subprocess, "run", fake_run)+ url = rt.ensure_daemon_and_url({"profile": "hermes"})+ assert url == loopback_health+ # E2E: the reported daemon answers /health 200 on the real loopback.+ import urllib.request++ with urllib.request.urlopen(url + "/health", timeout=5) as resp:+ assert resp.status == 200+ assert seen["cmd"][0] == str(py)+ assert seen["cmd"][3] == "hermes"+++def test_ensure_daemon_env_carries_grace_and_version_pin(side_root, monkeypatch, loopback_health):+ _install_side_python(side_root)+ captured = {}++ def fake_run(cmd, *, env=None, **kw):+ captured["env"] = env+ return _fake_completed(stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health}))++ monkeypatch.setattr(rt.subprocess, "run", fake_run)+ monkeypatch.delenv("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT", raising=False)+ monkeypatch.delenv("HINDSIGHT_EMBED_API_VERSION", raising=False)++ rt.ensure_daemon_and_url({"profile": "hermes", "port_health_grace_timeout": 60})++ # The grace window is read at IMPORT time of the side manager process, so it+ # rides the subprocess env (not Hermes' own environment).+ assert captured["env"]["HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"] == "60.0"+ assert captured["env"]["HINDSIGHT_EMBED_API_VERSION"] == "0.9.2"+ # Main-env interpreter markers are stripped so the side python resolves only+ # its own environment.+ assert "VIRTUAL_ENV" not in captured["env"]+ assert "PYTHONPATH" not in captured["env"]+++def test_ensure_daemon_missing_runtime_raises_with_hint(side_root, monkeypatch):+ with pytest.raises(RuntimeError, match="hermes memory setup"):+ rt.ensure_daemon_and_url({"profile": "hermes"})+++def test_ensure_daemon_bridge_failure_surfaces(side_root, monkeypatch):+ _install_side_python(side_root)+ monkeypatch.setattr(+ rt.subprocess, "run",+ lambda cmd, **kw: _fake_completed(returncode=1, stderr="boom inside side env"),+ )+ with pytest.raises(RuntimeError, match="boom inside side env"):+ rt.ensure_daemon_and_url({"profile": "hermes"})+++def test_ensure_daemon_not_ok_surfaces_bridge_error(side_root, monkeypatch):+ _install_side_python(side_root)+ monkeypatch.setattr(+ rt.subprocess, "run",+ lambda cmd, **kw: _fake_completed(+ stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": False, "url": None, "error": "daemon did not start"})),+ )+ with pytest.raises(RuntimeError, match="daemon did not start"):+ rt.ensure_daemon_and_url({"profile": "hermes"})+++# -- local hint ---------------------------------------------------------------+++def test_local_runtime_hint_points_at_isolated_install(side_root):+ hint = rt._local_runtime_hint("No module named 'hindsight'")+ assert "hermes memory setup" in hint+ assert "hindsight-embed==0.9.2" in hint+ assert "hindsight-api-slim[all]==0.9.2" in hint+ assert str(side_root) in hint+ # The main Hermes environment is never the target of the fix.+ assert "uv pip install --python" not in hint+++# -- trace logging on every local_embedded path -------------------------------+++def test_trace_logs_on_daemon_start_and_ready(side_root, monkeypatch, caplog, loopback_health):+ _install_side_python(side_root)+ monkeypatch.setattr(+ rt.subprocess, "run",+ lambda cmd, **kw: _fake_completed(stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health})),+ )+ with caplog.at_level("INFO", logger="plugins.memory.hindsight.embedded_runtime"):+ rt.ensure_daemon_and_url({"profile": "hermes"})+ messages = [r.getMessage() for r in caplog.records]+ assert any("starting side-env daemon manager" in m for m in messages)+ assert any("daemon ready" in m for m in messages)+++def test_trace_logs_on_startup_failure(side_root, monkeypatch, caplog):+ _install_side_python(side_root)+ monkeypatch.setattr(+ rt.subprocess, "run",+ lambda cmd, **kw: _fake_completed(returncode=1, stderr="no dice"),+ )+ with caplog.at_level("WARNING", logger="plugins.memory.hindsight.embedded_runtime"):+ with pytest.raises(RuntimeError):+ rt.ensure_daemon_and_url({"profile": "hermes"})+ assert any("bridge failed" in r.getMessage() for r in caplog.records)+++def test_no_in_process_import_of_the_embedded_stack():+ # The isolation contract: importing the plugin must not pull the heavy+ # embedded stack into the boot env (it lives only in the side env).+ import sys++ import plugins.memory.hindsight # noqa: F401++ assert "hindsight_embed" not in sys.modules+ assert "hindsight_api" not in sys.modules+ assert "hindsight" not in sys.modulesdiff --git a/tests/plugins/memory/test_hindsight_local_runtime_hint.py b/tests/plugins/memory/test_hindsight_local_runtime_hint.pyindex 075cb38e3a4..7742a4c8672 100644--- a/tests/plugins/memory/test_hindsight_local_runtime_hint.py+++ b/tests/plugins/memory/test_hindsight_local_runtime_hint.py@@ -1,45 +1,36 @@-"""NousResearch/hermes-agent#7718 — actionable message when local_embedded-runtime (`hindsight-all`) is missing.+"""The install hint for an unavailable local_embedded side runtime.-`local_embedded` imports `from hindsight import HindsightEmbedded`, provided-only by `hindsight-all`. When it's absent the provider disables itself; the-disable warning should point the user at the fix rather than just echoing-`No module named 'hindsight'`.+The embedded stack lives in the isolated side env (embedded_runtime); the fix+is always 'hermes memory setup' (Local Embedded) — the main Hermes environment+is never a pip target for it."""-import sys-import plugins.memory.hindsight as hsfrom plugins.memory.hindsight import HindsightMemoryProvider, _local_runtime_hint-def test_hint_for_missing_hindsight_all():+def test_hint_for_missing_runtime_names_the_isolated_install():hint = _local_runtime_hint("No module named 'hindsight'")- assert "hindsight-all" in hintassert "hermes memory setup" in hint- assert sys.executable in hint-+ assert "hindsight-embed==0.9.2" in hint+ assert "hindsight-api-slim[all]==0.9.2" in hint-def test_hint_for_missing_hindsight_embed():- hint = _local_runtime_hint("No module named 'hindsight_embed.daemon_embed_manager'")- assert "hindsight-all" in hint--def test_no_hint_for_unrelated_runtime_error():- # e.g. the NumPy-on-old-CPU failure _check_local_runtime also guards against- assert _local_runtime_hint("Illegal instruction (NumPy SIMD)") == ""- assert _local_runtime_hint(None) == ""+def test_hint_includes_probe_reason():+ hint = _local_runtime_hint("Illegal instruction (NumPy SIMD)")+ assert "NumPy SIMD" in hint # truthful: reinstall may not fix a CPU limit+ assert "hermes memory setup" in hint-# unavailable_reason() — surfaces the hint through the reachable path (#7718):-# is_available() gates initialize() out, so the hint must come from here.+def test_hint_without_reason_still_actionable():+ assert "hermes memory setup" in _local_runtime_hint(None)def test_unavailable_reason_surfaces_hint_for_local_embedded(monkeypatch):monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "local_embedded"})monkeypatch.setattr(hs, "_check_local_runtime", lambda: (False, "No module named 'hindsight'"))reason = HindsightMemoryProvider().unavailable_reason()- assert "hindsight-all" in reason+ assert "hermes memory setup" in reasonassert reason == reason.strip() # no leading/trailing whitespacediff --git a/tests/plugins/memory/test_hindsight_provider.py b/tests/plugins/memory/test_hindsight_provider.pyindex 8395362bdb2..e8cf29c325c 100644--- a/tests/plugins/memory/test_hindsight_provider.py+++ b/tests/plugins/memory/test_hindsight_provider.py@@ -347,16 +347,26 @@ class TestConfig:assert env["HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT"] == "0"- def test_get_client_passes_idle_timeout_to_hindsight_embedded(self, monkeypatch):+ def test_get_client_connects_http_client_to_sideenv_daemon(self, monkeypatch):captured = {}- class FakeHindsightEmbedded:+ class FakeHindsight:def __init__(self, **kwargs):captured.update(kwargs)- monkeypatch.setitem(sys.modules, "hindsight", SimpleNamespace(HindsightEmbedded=FakeHindsightEmbedded))- monkeypatch.setattr("plugins.memory.hindsight._check_local_runtime", lambda: (True, ""))+ monkeypatch.setitem(sys.modules, "hindsight_client", SimpleNamespace(Hindsight=FakeHindsight))+ # The daemon URL comes from the side env; no port is hardcoded here.+ side_calls = []++ def fake_start(cfg, **kwargs):+ side_calls.append(cfg)+ return "http://127.0.0.1:9157"+ monkeypatch.setattr("plugins.memory.hindsight._start_sideenv_daemon", fake_start)+ # The lazy client install is the pm boundary, not what this test exercises.+ monkeypatch.setattr("plugins.memory.hindsight._ensure_client_dependency", lambda: None)++ monkeypatch.setattr("plugins.memory.hindsight._materialize_embedded_profile_env", lambda *a: None)p = HindsightMemoryProvider()p._mode = "local_embedded"p._config = {@@ -370,8 +380,11 @@ class TestConfig:p._get_client()- assert captured["idle_timeout"] == 0- assert captured["llm_provider"] == "openai"+ # The side-env daemon manager receives the config (LLM keys ride the+ # materialized profile .env, not the client); Hermes talks HTTP.+ assert side_calls == [p._config]+ assert captured["base_url"] == "http://127.0.0.1:9157"+ assert p._api_url == "http://127.0.0.1:9157"class TestPostSetup:@@ -409,6 +422,8 @@ class TestPostSetup:user_home.mkdir()monkeypatch.setenv("HOME", str(user_home))+ monkeypatch.setattr("plugins.memory.hindsight.setup._sync_client_dependency", lambda: True)+ monkeypatch.setattr("plugins.memory.hindsight.setup._install_embedded_runtime", lambda: True)selections = iter([1, 0]) # local_embedded, openaimonkeypatch.setattr("hermes_cli.memory_setup._curses_select", lambda *args, **kwargs: next(selections))monkeypatch.setattr("shutil.which", lambda name: None)@@ -1512,20 +1527,16 @@ class TestSharedEventLoopLifecycle:class TestShutdown:- def test_local_embedded_shutdown_closes_inner_async_client_on_shared_loop(self, provider):- inner_client = _make_mock_client()- embedded = MagicMock()- embedded._client = inner_client- embedded.close = MagicMock()-+ def test_local_embedded_shutdown_closes_client_on_shared_loop(self, provider):+ """The embedded client is hindsight_client.Hindsight (HTTP to the side-env+ daemon): same aclose-on-shared-loop path as cloud."""+ client = _make_mock_client()provider._mode = "local_embedded"- provider._client = embedded+ provider._client = clientprovider.shutdown()- inner_client.aclose.assert_awaited_once()- embedded.close.assert_called_once()- assert embedded._client is None+ client.aclose.assert_awaited_once()assert provider._client is None@@ -1659,17 +1670,14 @@ class TestMultiplexBackgroundScope:created = []- class FakeHindsightEmbedded:- def __init__(self, **kwargs):- created.append(kwargs["llm_api_key"])- self._manager = SimpleNamespace(is_running=lambda profile: False, stop=lambda profile: None)- self._ensure_started = lambda: None-- dem = SimpleNamespace(console=None)- monkeypatch.setitem(sys.modules, "hindsight", SimpleNamespace(HindsightEmbedded=FakeHindsightEmbedded))- monkeypatch.setitem(sys.modules, "hindsight_embed", SimpleNamespace(daemon_embed_manager=dem))- monkeypatch.setitem(sys.modules, "hindsight_embed.daemon_embed_manager", dem)+ from plugins.memory.hindsight.embedded import _embedded_profile_env_path, _load_simple_env+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "user-home"))+ def start(cfg, **kwargs):+ created.append(_load_simple_env(_embedded_profile_env_path(cfg))["HINDSIGHT_API_LLM_API_KEY"])+ return "http://127.0.0.1:9158"+ monkeypatch.setattr("plugins.memory.hindsight._start_sideenv_daemon", start)monkeypatch.setattr("plugins.memory.hindsight._check_local_runtime", lambda: (True, ""))+ monkeypatch.setattr("plugins.memory.hindsight._ensure_client_dependency", lambda: None)home = tmp_path / "profiles" / "p1"(home / "hindsight").mkdir(parents=True)@@ -1706,4 +1714,4 @@ class TestMultiplexBackgroundScope:if t.name == "hindsight-daemon-start":t.join(timeout=5)assert created == ["p1-secret"]- assert "Daemon started successfully" in (home / "logs" / "hindsight-embed.log").read_text()+ p.shutdown()diff --git a/tests/plugins/memory/test_hindsight_setup_deps.py b/tests/plugins/memory/test_hindsight_setup_deps.pynew file mode 100644index 00000000000..dbe8c5021f8--- /dev/null+++ b/tests/plugins/memory/test_hindsight_setup_deps.py@@ -0,0 +1,136 @@+"""C16: hindsight run_setup dependency install must route through pm — the+declared ``extra: hindsight`` (uv.lock pin) for all modes — and the+local_embedded wizard must ACTUALLY install the isolated side-env runtime via+embedded_runtime.ensure_sideenv (hindsight-embed + hindsight-api-slim[all],+pinned, built by the pm.ensure.uv bridge). Never the deleted ``tools.lazy_deps``."""++import sys+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+++def setup_mod():+ import plugins.memory.hindsight.setup as mod+ return mod+++def _fake_provider(existing=None):+ return SimpleNamespace(_config=existing or {}, save_config=MagicMock())+++def _no_network_setup(monkeypatch, setup_mod, tmp_path, mode):+ """Drive run_setup non-interactively: fixed selections, empty secrets,+ templates disabled, profile-env materialization stubbed."""+ monkeypatch.setattr(setup_mod, "_select", lambda title, items, values, current: mode)+ monkeypatch.setattr(setup_mod, "_secret_prompt", lambda label: "")+ monkeypatch.setattr(setup_mod, "_materialize_embedded_profile_env", lambda *a, **kw: None)+ import builtins+ monkeypatch.setattr(builtins, "input", lambda prompt="": "")+ import plugins.memory.hindsight.templates as templates+ monkeypatch.setattr(templates, "supported_for_mode", lambda mode: False)+ import hermes_cli.config as hermes_config+ monkeypatch.setattr(hermes_config, "save_config", lambda config: None)+ return _fake_provider(), str(tmp_path / "home"), {"memory": {}}+++class TestClientModeUsesDeclaredExtra:+ def test_cloud_mode_syncs_hindsight_extra(self, monkeypatch, setup_mod, tmp_path):+ calls = []+ import pm+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: calls.append((extras, explicit)))+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "cloud")++ setup_mod.run_setup(provider, home, config)++ assert calls == [(["hindsight"], True)]++ def test_local_external_mode_syncs_hindsight_extra(self, monkeypatch, setup_mod, tmp_path):+ calls = []+ import pm+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: calls.append((extras, explicit)))+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_external")++ setup_mod.run_setup(provider, home, config)++ assert calls == [(["hindsight"], True)]+++class TestSyncFailureSurfaces:+ def test_sealed_refusal_warns_not_crashes(self, monkeypatch, setup_mod, tmp_path, capsys):+ import pm++ def refuse(extras=None, *, explicit=False):+ raise RuntimeError("venv refuses: frozen feature set")++ monkeypatch.setattr(pm, "sync_venv", refuse)+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "cloud")++ setup_mod.run_setup(provider, home, config)++ out = capsys.readouterr().out+ assert "frozen feature set" in out+ assert "hermes pm install" in out+++class TestEmbeddedInstallsIsolatedSideEnv:+ def test_embedded_installs_isolated_runtime_not_shared_venv(self, monkeypatch, setup_mod, tmp_path, capsys):+ calls = []+ import pm+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: calls.append(extras))+ installed = []+ import plugins.memory.hindsight.embedded_runtime as rt+ monkeypatch.setattr(rt, "ensure_sideenv", lambda: installed.append("gen") or rt.sideenv_root())+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_embedded")++ setup_mod.run_setup(provider, home, config)++ out = capsys.readouterr().out+ # The client extra goes through pm; the heavy stack installs into the+ # isolated side env — never the shared venv.+ assert calls == [["hindsight"]]+ assert installed == ["gen"]+ assert "Isolated Hindsight runtime installed" in out+ assert "not modified" in out++ def test_embedded_install_failure_is_truthful_and_non_fatal(self, monkeypatch, setup_mod, tmp_path, capsys):+ import pm+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)+ import plugins.memory.hindsight.embedded_runtime as rt+ monkeypatch.setattr(rt, "ensure_sideenv",+ lambda: (_ for _ in ()).throw(RuntimeError("uv sync failed: disk full")))+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_embedded")++ setup_mod.run_setup(provider, home, config)++ out = capsys.readouterr().out+ assert "Isolated runtime install failed" in out+ assert "disk full" in out+ provider.save_config.assert_not_called()+ assert config["memory"] == {}++ def test_embedded_config_still_saved(self, monkeypatch, setup_mod, tmp_path):+ import pm+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)+ import plugins.memory.hindsight.embedded_runtime as rt+ monkeypatch.setattr(rt, "ensure_sideenv", lambda: rt.sideenv_root())+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_embedded")++ setup_mod.run_setup(provider, home, config)++ saved = provider.save_config.call_args[0][0]+ assert saved["mode"] == "local_embedded"+ assert saved["bank_id"] == "hermes"+++class TestNoLazyDeps:+ def test_tools_lazy_deps_absent_after_setup(self, monkeypatch, setup_mod, tmp_path):+ import pm+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "cloud")++ setup_mod.run_setup(provider, home, config)++ assert "tools.lazy_deps" not in sys.modulesdiff --git a/tests/plugins/platforms/photon/test_presence_watchdog.py b/tests/plugins/platforms/photon/test_presence_watchdog.pyindex 65256e990ac..24ab5b597e4 100644--- a/tests/plugins/platforms/photon/test_presence_watchdog.py+++ b/tests/plugins/platforms/photon/test_presence_watchdog.py@@ -38,6 +38,24 @@ def test_probe_config_defaults(monkeypatch: pytest.MonkeyPatch) -> None:assert a._probe_enabled is True+def test_probe_config_explicit_zero_disables_watchdog(monkeypatch: pytest.MonkeyPatch) -> None:+ # Explicit 0 in extra must NOT fall through to the default (``or`` bug):+ # a non-positive interval is the documented escape hatch that disables the watchdog.+ a = _make_adapter(monkeypatch, probe_interval_seconds=0)+ assert a._probe_interval == 0+ assert a._probe_enabled is False+++def test_probe_config_invalid_values_fall_back_to_defaults(monkeypatch: pytest.MonkeyPatch) -> None:+ # Unparseable values degrade to defaults instead of aborting construction.+ a = _make_adapter(monkeypatch, probe_interval_seconds="soon", probe_timeout_seconds=None,+ probe_max_failures="lots")+ assert a._probe_interval == 600.0+ assert a._probe_timeout == 10.0+ assert a._probe_max_failures == 3+ assert a._probe_enabled is True++def test_note_activity_resets_failures(monkeypatch: pytest.MonkeyPatch) -> None:a = _make_adapter(monkeypatch)a._probe_failures = 2diff --git a/tests/plugins/test_hindsight_health_grace_timeout.py b/tests/plugins/test_hindsight_health_grace_timeout.pyindex 0e068d12710..108ec6480ef 100644--- a/tests/plugins/test_hindsight_health_grace_timeout.py+++ b/tests/plugins/test_hindsight_health_grace_timeout.py@@ -1,64 +1,50 @@-"""Embedded-daemon health grace timeout export (issue #13125 comment thread).+"""Embedded-daemon health grace timeout (issue #13125 comment thread).On resource-contended hosts the embedded Hindsight daemon can exceed a single2s /health check and get needlessly killed + restarted. Upstream exposes the-grace window via HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT (read at import-time). The plugin surfaces it as a config.json knob and exports it to the-process env BEFORE daemon_embed_manager is imported.+grace window via HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT, read at import+time of the process that runs DaemonEmbedManager — which is now the SIDE-env+daemon bridge process, so the value must ride the subprocess environment+built by embedded_runtime (never Hermes' own os.environ)."""-import importlib+import plugins.memory.hindsight.embedded_runtime as rt-import pytest+_ENV = rt._PORT_HEALTH_GRACE_ENV-hindsight = importlib.import_module("plugins.memory.hindsight")-_export = hindsight._export_port_health_grace_timeout-_ENV = importlib.import_module("plugins.memory.hindsight.embedded")._PORT_HEALTH_GRACE_ENV+def test_configured_value_rides_subprocess_env():+ env = rt._daemon_subprocess_env({"port_health_grace_timeout": 60})+ assert float(env[_ENV]) == 60.0[email protected](autouse=True)-def _clear_env(monkeypatch):- monkeypatch.delenv(_ENV, raising=False)+def test_string_value_parsed():+ env = rt._daemon_subprocess_env({"port_health_grace_timeout": "45"})+ assert float(env[_ENV]) == 45.0-def test_configured_value_exported(monkeypatch):- _export({"port_health_grace_timeout": 60})- import os- assert float(os.environ[_ENV]) == 60.0+def test_blank_and_missing_are_noops():+ env = rt._daemon_subprocess_env({})+ assert _ENV not in env+ assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": ""})+ assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": None})-def test_string_value_parsed(monkeypatch):- _export({"port_health_grace_timeout": "45"})- import os-- assert float(os.environ[_ENV]) == 45.0---def test_blank_and_missing_are_noops(monkeypatch):- import os-- _export({})- assert _ENV not in os.environ- _export({"port_health_grace_timeout": ""})- assert _ENV not in os.environ- _export({"port_health_grace_timeout": None})- assert _ENV not in os.environ---def test_invalid_and_negative_ignored(monkeypatch):- import os-- _export({"port_health_grace_timeout": "not-a-number"})- assert _ENV not in os.environ- _export({"port_health_grace_timeout": -5})- assert _ENV not in os.environ+def test_invalid_and_negative_ignored():+ assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": "not-a-number"})+ assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": -5})def test_explicit_env_wins_over_config(monkeypatch):- import os-monkeypatch.setenv(_ENV, "99")- _export({"port_health_grace_timeout": 60})+ env = rt._daemon_subprocess_env({"port_health_grace_timeout": 60})# setdefault must not clobber an operator-set env override.- assert os.environ[_ENV] == "99"+ assert env[_ENV] == "99"+++def test_main_env_interpreter_markers_stripped(monkeypatch):+ monkeypatch.setenv("VIRTUAL_ENV", "/some/main-venv")+ monkeypatch.setenv("PYTHONPATH", "/some/shim")+ env = rt._daemon_subprocess_env({})+ assert "VIRTUAL_ENV" not in env+ assert "PYTHONPATH" not in envdiff --git a/tests/pm/test_activate_scripts.py b/tests/pm/test_activate_scripts.pyindex 23e13d80726..2fd4e38f234 100644--- a/tests/pm/test_activate_scripts.py+++ b/tests/pm/test_activate_scripts.py@@ -223,8 +223,11 @@ def test_activate_fails_cleanly_without_a_store(tmp_path: Path):env = os.environ.copy()env["HERMES_RUNTIME_DIR"] = _posix(tmp_path / "empty-store")env.pop(CANARY, None)+ isolated = tmp_path / "no-install" / "activate"+ isolated.parent.mkdir()+ shutil.copy2(ACTIVATE, isolated)script = (- f'source "{_posix(ACTIVATE)}" 2>/dev/null; '+ f'source "{_posix(isolated)}" 2>/dev/null; 'f'test $? -ne 0 && echo refused')result = subprocess.run(diff --git a/tests/pm/test_activation_runtime.py b/tests/pm/test_activation_runtime.pynew file mode 100644index 00000000000..2d2f06f3c99--- /dev/null+++ b/tests/pm/test_activation_runtime.py@@ -0,0 +1,57 @@+"""Activation runs read-only from any cwd and restores the caller environment."""+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys++import pytest++[email protected]("windows")+def test_powershell_activation_roundtrip_selected_environment(tmp_path, monkeypatch):+ from hermes_cli.runtime_paths import runtime_facts_path+ from pm.paths import repo_root+ from pm.store import current_target+ from pm.lock import Lockfile++ root = repo_root()+ home = tmp_path / "home"+ monkeypatch.setenv("HERMES_HOME", str(home))+ facts = runtime_facts_path(root)+ selected = facts.parent / "environments" / "a" / "venv"+ site = selected / "Lib" / "site-packages"+ site.mkdir(parents=True)+ (selected / "pyvenv.cfg").write_text("home = test")+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(selected)}}}))+ store = tmp_path / "tools"+ store.mkdir()+ lock = Lockfile(root / "pm" / "lock.json")+ target = current_target()+ entry = store / "python-test"+ entry.mkdir()+ (store / "facts.json").write_text(json.dumps({"schema": 1, "packages": {"python": {+ "entry": entry.name, "version": lock.version("python"), "target": target,+ "artifacts": [a["sha256"] for a in lock.artifacts("python", target)],+ "env": {"HERMES_ACTIVATE_CANARY": "active"},+ }}}))+ env = dict(os.environ, HERMES_RUNTIME_DIR=str(store), PYTHONPATH="caller-original",+ PATHEXT=".COM;.EXE;.BAT;.CMD")+ script = tmp_path / "run.ps1"+ script.write_text(+ f"$ErrorActionPreference='Stop'; . '{root / 'activate.ps1'}'; "+ "[PSCustomObject]@{canary=$env:HERMES_ACTIVATE_CANARY;pythonpath=$env:PYTHONPATH}|ConvertTo-Json -Compress; "+ "deactivate; Write-Output ('restored=' + $env:PYTHONPATH); "+ "Write-Output ('canary=' + $env:HERMES_ACTIVATE_CANARY)", encoding="utf-8",+ )+ powershell = shutil.which("powershell")+ assert powershell+ run = subprocess.run([powershell,"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",str(script)],+ cwd=tmp_path,env=env,capture_output=True,text=True,timeout=40)+ assert run.returncode == 0, run.stdout + run.stderr+ lines = run.stdout.splitlines()+ record = json.loads(lines[0])+ assert record["canary"] == "active"+ assert record["pythonpath"] == str(root) + os.pathsep + str(site)+ assert lines[1:] == ["restored=caller-original", "canary="]diff --git a/tests/pm/test_ffmpeg_resolution.py b/tests/pm/test_ffmpeg_resolution.pynew file mode 100644index 00000000000..d82c9c1ebd1--- /dev/null+++ b/tests/pm/test_ffmpeg_resolution.py@@ -0,0 +1,58 @@+"""Ffmpeg pin resolution uses the advertised version and target, never a guessed URL."""+from __future__ import annotations++import pytest++from pm import update+from pm.package import InstallError+from pm.packages import Ffmpeg+++def indexes(monkeypatch):+ monkeypatch.setattr(update, "_btbn_cache", update._TTL())+ monkeypatch.setattr(update, "_martin_cache", update._TTL())+ tag = "autobuild-2026-09-01-12-00"+ version = "9.1.2"+ assets = [+ f"ffmpeg-n{version}-1-gabcdef-linux64-gpl-9.1.tar.xz",+ f"ffmpeg-n{version}-1-gabcdef-win64-gpl-shared-9.1.zip",+ f"ffmpeg-n{version}-1-gabcdef-win64-lgpl-9.1.zip",+ f"ffmpeg-n{version}-1-gabcdef-win64-gpl-9.1.zip",+ f"ffmpeg-n{version}-1-gabcdef-winarm64-gpl-9.1.zip",+ ]+ monkeypatch.setattr(update, "_get_json", lambda url: [+ {"tag_name": tag, "assets": [{"name": name} for name in assets]},+ ])+ paths = {+ f"{osname}-{arch}": f"{source_os}/{source_arch}/1788300000_{version}/ffmpeg.zip"+ for osname, source_os in (("linux", "linux"), ("darwin", "macos"))+ for arch, source_arch in (("x64", "amd64"), ("arm64", "arm64"))+ }+ monkeypatch.setattr(update, "_get_text", lambda url: "\n".join(+ f'<a href="/download/{path}">Ffmpeg</a>' for path in paths.values()+ ))+ return version, tag, paths++[email protected]("target", [+ "win32-x64", "win32-arm64", "linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64",+])+def test_resolved_version_fetches_its_exact_target_asset(indexes, target):+ version, tag, paths = indexes+ package = Ffmpeg()+ # URL resolution and update discovery must agree about target identities.+ url = package.fetch_url(version, target)+ assert version in package.latest_versions(target)+ if target.startswith("win32"):+ arch = "64" if target.endswith("-x64") else "arm64"+ expected = f"ffmpeg-n{version}-1-gabcdef-win{arch}-gpl-9.1.zip"+ assert url == f"https://github.com/BtbN/FFmpeg-Builds/releases/download/{tag}/{expected}"+ else:+ assert url == f"https://ffmpeg.martin-riedl.de/download/{paths[target]}"++[email protected]("target", ["win32-x64", "win32-arm64", "linux-x64", "darwin-arm64"])+def test_unadvertised_version_refuses_instead_of_relabelling_old_bytes(indexes, target):+ with pytest.raises(InstallError, match="9.9.9"):+ Ffmpeg().fetch_url("9.9.9", target)diff --git a/tests/pm/test_install_default_closure.py b/tests/pm/test_install_default_closure.pynew file mode 100644index 00000000000..394e2a3e17e--- /dev/null+++ b/tests/pm/test_install_default_closure.py@@ -0,0 +1,69 @@+"""The default `pm install` closure must stage the interpreter boot requires.++A fresh source install emits boot launchers (scripts/install.sh stage_path,+hermes_cli/_launchers.py) that exec the pm STORE interpreter. The `python`+package is marked optional (dev installs use their own venv; sealed bundles+adopt a shipped one), so the old default closure — every non-optional+lockfile package — skipped it and left `hermes` unbootable (audit C05).++Behavioral: drive cmd_install with the real lockfile/registry and stub+installers, asserting on the requested package names, not on script text.+"""++from __future__ import annotations++import argparse+import importlib++import pytest++import pm.cli+from pm.lock import Lockfile+from pm.paths import repo_root+from pm.registry import get_package+++def install_spy(monkeypatch):+ calls = {"names": None, "sync_extras": None}++ def fake_install_names(names):+ calls["names"] = list(names)+ return 0++ def fake_sync_venv(extras=None, **kwargs):+ calls["sync_extras"] = list(extras or [])+ return None++ monkeypatch.setattr(pm.cli, "_install_names", fake_install_names)+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "sync_venv", fake_sync_venv)+ return calls+++def test_default_closure_includes_the_boot_interpreter(install_spy) -> None:+ assert pm.cli.cmd_install(argparse.Namespace(names=None)) == 0++ lockfile = Lockfile(repo_root() / "pm" / "lock.json")+ names = install_spy["names"]+ # The launchers' interpreter must be requested...+ assert "python" in names+ # ...through the existing authorities: it is pinned in pm/lock.json and+ # defined in the package registry — no parallel hand-written list here.+ assert "python" in lockfile.names()+ get_package("python")+ # ...and the rest of the root closure is unchanged (non-optional packages).+ expected = {+ n for n in lockfile.names() if not get_package(n).optional+ } | {"python"}+ assert set(names) == expected+++def test_default_closure_still_syncs_the_venv_with_all_extras(install_spy) -> None:+ assert pm.cli.cmd_install(argparse.Namespace(names=None)) == 0+ assert install_spy["sync_extras"] == ["all"]+++def test_explicit_names_pass_through_untouched(install_spy) -> None:+ assert pm.cli.cmd_install(argparse.Namespace(names=["npm", "ripgrep"])) == 0+ assert install_spy["names"] == ["npm", "ripgrep"]+ assert install_spy["sync_extras"] is Nonediff --git a/tests/pm/test_member_selection.py b/tests/pm/test_member_selection.pynew file mode 100644index 00000000000..1b6f0e4ce03--- /dev/null+++ b/tests/pm/test_member_selection.py@@ -0,0 +1,18 @@+"""The workspace and admission paths agree on scoped keys and disabled plugins."""+from pm.workspace import enabled_member_dirs+++def test_scoped_members_respect_disabled_and_keep_other_profiles(tmp_path, monkeypatch):+ home = tmp_path / "home"+ monkeypatch.setenv("HERMES_HOME", str(home))+ current = home / "plugins" / "group" / "plugin"+ other_home = home / "profiles" / "other"+ other = other_home / "plugins" / "same"+ for member in (current, other):+ member.mkdir(parents=True)+ (member / "pyproject.toml").write_text('[project]\nname="test"\nversion="1"\n')+ (home / "config.yaml").write_text('plugins:\n enabled: [group/plugin]\n disabled: []\n')+ (other_home / "config.yaml").write_text('plugins:\n enabled: [same]\n')+ assert set(enabled_member_dirs()) == {current, other}+ (home / "config.yaml").write_text('plugins:\n enabled: [group/plugin]\n disabled: [group/plugin]\n')+ assert enabled_member_dirs() == [other]diff --git a/tests/pm/test_no_lazy_deps.py b/tests/pm/test_no_lazy_deps.pyindex 37f3ec8092a..4f9e2f67d2d 100644--- a/tests/pm/test_no_lazy_deps.py+++ b/tests/pm/test_no_lazy_deps.py@@ -1,72 +1,225 @@-"""Contract: no production code imports the deleted tools.lazy_deps.+"""Contract tests for scripts/ci/check_lazy_deps_imports.py.-tools/lazy_deps.py was deleted by the pm migration; pm.extras (available /-ensure_import / ensure_and_bind) is the only lazy-install surface. A new-``from tools.lazy_deps import ...`` in production code is a crash at call-time (ImportError), so this contract keeps the migration complete.+``tools/lazy_deps.py`` was deleted by the pm migration; pm.extras+(available / ensure_import / ensure_and_bind) is the only lazy-install+surface. A ``tools.lazy_deps`` import left in production code is an+ImportError at call time.-Exclusions, each load-bearing:-- ``scripts/release.py`` — a contributor-credit COMMENT referencing a- historical PR title; not an import, harmless.-- ``tests/`` — tests may reference lazy_deps to assert it is gone.+Each test drives the real checker CLI (subprocess) against a fresh+per-test git fixture repo, so the tests are order-independent: the guard+must be red/green on both sides of the contract, and a repo it cannot+inventory (not a git repo, no tracked ``*.py`` files, unreadable or+unparseable tracked file) must FAIL rather than quietly scan nothing."""from __future__ import annotations+import os+import subprocess+import sysfrom pathlib import Path-# Directories that are not production source, or that mirror it.-_EXCLUDED_DIRS = {- "node_modules",- ".venv",- "venv",- "build",- "dist",- "release",- "__pycache__",- "agent-payload",- ".git",-}+import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+SCRIPT = REPO_ROOT / "scripts" / "ci" / "check_lazy_deps_imports.py"-# Files allowed to mention lazy_deps (see docstring for why).-_ALLOWED = {- # historical contributor-credit comment (PR #26294 in the credit map)- "scripts/release.py",- # the dashboard's legacy-pip-deps surface documents the old pipeline- # it replaced until the workspace bridge wires it (see plugin-deps plan).- "hermes_cli/web_server.py",+_GIT_ENV = {+ "GIT_AUTHOR_NAME": "t",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "t",+ "GIT_COMMITTER_EMAIL": "[email protected]",}-def _production_python_files(repo_root: Path):- for path in repo_root.rglob("*.py"):- rel = path.relative_to(repo_root).as_posix()- if not rel.startswith("tests/") and rel not in _ALLOWED:- if not any(part in _EXCLUDED_DIRS for part in path.parts):- yield rel, path---def test_no_production_imports_of_lazy_deps():- """Every production .py must be free of tools.lazy_deps imports."""- repo_root = Path(__file__).resolve().parents[2]- offenders: list[str] = []- pattern = "tools.lazy_deps"- try:- candidates = list(_production_python_files(repo_root))- except OSError:- # rglob can raise FileNotFoundError on a dangling worktree junction- # (WinError 3) mid-walk on Windows — not this contract's business.- candidates = []- for rel, path in candidates:- try:- text = path.read_text(encoding="utf-8-sig")- except (OSError, UnicodeDecodeError):- # Broken junctions/dangling links raise on read.- continue- if pattern in text:- offenders.append(rel)- assert not offenders, (- "production code references tools.lazy_deps (deleted module — "- "ImportError at call time). Migrate to pm.ensure_import / "- f"pm.extras: {offenders}"+def fixture_repo(tmp_path: Path) -> Path:+ """A fresh minimal tracked git repo per test.++ ``git add`` is enough — the checker's inventory is ``git ls-files``,+ which reads the index, so no commit is made (or needed).+ """+ env = {**os.environ, **_GIT_ENV}++ def _git(*args: str) -> None:+ subprocess.run(+ ["git", *args], cwd=tmp_path, env=env, check=True, capture_output=True+ )++ _git("init", "-q")+ (tmp_path / "app.py").write_text("x = 1\n", encoding="utf-8")+ (tmp_path / "tests").mkdir()+ (tmp_path / "tests" / "test_x.py").write_text(+ "def test_x():\n pass\n", encoding="utf-8"+ )+ _git("add", "-A")+ return tmp_path+++def _run_checker(root: Path) -> subprocess.CompletedProcess:+ return subprocess.run(+ [sys.executable, str(SCRIPT), str(root)],+ capture_output=True,+ text=True,+ timeout=120,+ )+++def _track(root: Path, relpath: str, body: str) -> None:+ path = root / relpath+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body, encoding="utf-8")+ subprocess.run(+ ["git", "add", relpath], cwd=root, check=True, capture_output=True)+++def test_clean_repo_passes(fixture_repo):+ result = _run_checker(fixture_repo)+ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout.strip() == ""+++ ("body", "lineno"),+ [+ ("from tools.lazy_deps import install_specs\n", 1),+ ("from tools import lazy_deps\n\nlazy_deps.ensure('x')\n", 1),+ ("from tools.lazy_deps.sub import x\n", 1),+ ("import tools.lazy_deps\n", 1),+ ("import tools.lazy_deps.submodule as s\n", 1),+ ("if True:\n from tools.lazy_deps import ensure\n", 2),+ ],+ ids=[+ "from-module",+ "from-parent",+ "from-dotted-child",+ "plain-import",+ "dotted-import",+ "nested",+ ],+)+def test_each_import_form_is_caught_with_exact_site(fixture_repo, body, lineno):+ _track(fixture_repo, "app.py", body)+ result = _run_checker(fixture_repo)+ assert result.returncode == 1, result.stdout + result.stderr+ assert f"app.py:{lineno}" in result.stdout+ assert "lazy_deps" in result.stdout+++ ("relpath", "body", "lineno"),+ [+ ("tools/helper.py", "from . import lazy_deps\n\nlazy_deps.ensure('x')\n", 1),+ ("tools/helper.py", "from .lazy_deps import ensure\n", 1),+ ("tools/sub/mod.py", "from .. import lazy_deps\n", 1),+ ("tools/__init__.py", "from . import lazy_deps\n", 1),+ ],+ ids=["from-dot", "from-dot-module", "from-dotdot-in-subpackage", "pkg-init"],+)+def test_relative_import_resolved_inside_tools_is_caught(+ fixture_repo, relpath, body, lineno+):+ """``from . import lazy_deps`` inside the tracked tools/ package IS an+ import of the deleted tools.lazy_deps module."""+ _track(fixture_repo, "tools/__init__.py", "")+ _track(fixture_repo, relpath, body)+ result = _run_checker(fixture_repo)+ assert result.returncode == 1, result.stdout + result.stderr+ assert f"{relpath}:{lineno}" in result.stdout+++def test_relative_import_outside_tools_is_not_flagged(fixture_repo):+ """A same-package ``lazy_deps`` elsewhere is not the deleted module."""+ _track(fixture_repo, "pkg/__init__.py", "")+ _track(fixture_repo, "pkg/other.py", "from . import lazy_deps\n")+ result = _run_checker(fixture_repo)+ assert result.returncode == 0, result.stdout + result.stderr+++def test_comments_and_prose_are_not_imports(fixture_repo):+ _track(+ fixture_repo,+ "app.py",+ (+ "# tools.lazy_deps was deleted; see pm.extras\n"+ '\"\"\"Best-effort tools.lazy_deps.ensure: failures are swallowed.\"\"\"\n'+ "x = 1\n"+ ),+ )+ result = _run_checker(fixture_repo)+ assert result.returncode == 0, result.stdout + result.stderr+++def test_untracked_files_are_not_scanned(fixture_repo):+ # Untracked debris (not in the tracked inventory) must not be scanned.+ (fixture_repo / "debris.py").write_text(+ "from tools.lazy_deps import ensure\n", encoding="utf-8"+ )+ result = _run_checker(fixture_repo)+ assert result.returncode == 0, result.stdout + result.stderr+++def test_not_a_git_repo_fails_the_check(tmp_path):+ # The inventory cannot be built: the checker must fail loudly+ # (nonzero, inventory error) — never pass by scanning nothing.+ result = _run_checker(tmp_path)+ assert result.returncode == 2+ assert "inventory" in (result.stdout + result.stderr).lower()+++def test_repo_without_tracked_python_fails_the_check(tmp_path):+ """A git repo whose tracked inventory contains no ``*.py`` files fails.++ The guard's policy is to fail rather than pass an empty inventory:+ for this repo a zero-candidate inventory means the scan is broken,+ not clean.+ """+ subprocess.run(+ ["git", "init", "-q"], cwd=tmp_path, check=True, capture_output=True+ )+ (tmp_path / "README.md").write_text("hi\n", encoding="utf-8")+ subprocess.run(+ ["git", "add", "README.md"], cwd=tmp_path, check=True, capture_output=True+ )++ result = _run_checker(tmp_path)++ assert result.returncode == 2, result.stdout + result.stderr+ assert "inventory" in (result.stdout + result.stderr).lower()+++def test_unparseable_tracked_file_fails_the_check(fixture_repo):+ # A tracked file that cannot be parsed is an error, not a skip: the+ # check must fail rather than silently scan a partial inventory.+ _track(fixture_repo, "broken.py", "def f(:\n")+ result = _run_checker(fixture_repo)+ assert result.returncode == 2, result.stdout + result.stderr+ assert "broken.py" in (result.stdout + result.stderr)+++def test_deleted_tracked_files_are_not_live_source(fixture_repo):+ _track(fixture_repo, "removed.py", "from tools import lazy_deps\n")+ (fixture_repo / "removed.py").unlink()+ result = _run_checker(fixture_repo)+ assert result.returncode == 0, result.stdout + result.stderr+++def test_real_repo_invocation_stays_deterministic():+ """Drive the checker against THIS repo.++ Exit 0 = migration complete (stdout empty). Exit 1 = live offenders+ remain — output must be the deterministic exact-site list the+ lazy-deps-guard CI job blocks on (migration owned elsewhere; the+ fixture tests above, not this visibility check, are the red/green+ proof of the guard itself).+ """+ result = _run_checker(REPO_ROOT)+ assert result.returncode in (0, 1), result.stdout + result.stderr+ if result.returncode == 0:+ assert result.stdout.strip() == ""+ return+ for line in result.stdout.splitlines():+ path, lineno, rest = line.split(":", 2)+ assert path.endswith(".py") and lineno.isdigit()+ assert "lazy_deps" in restdiff --git a/tests/pm/test_node_release_candidates.py b/tests/pm/test_node_release_candidates.pynew file mode 100644index 00000000000..85ce499f03c--- /dev/null+++ b/tests/pm/test_node_release_candidates.py@@ -0,0 +1,11 @@+"""The package lock must never choose an unstable Node release."""+from pm import update+++def test_node_candidates_exclude_prereleases(monkeypatch):+ monkeypatch.setattr(update, "_get_json", lambda url: [+ {"version": "v26.8.0-alpha.0"}, {"version": "v26.7.0"},+ {"version": "v24.0.0-rc.1"}, {"version": "v24.20.0"},+ ])+ versions = update.node_latest_versions()+ assert versions == ["26.7.0", "24.20.0"]diff --git a/tests/pm/test_node_sidecar.py b/tests/pm/test_node_sidecar.pyindex 7ab4df1e145..0d6b110e5c6 100644--- a/tests/pm/test_node_sidecar.py+++ b/tests/pm/test_node_sidecar.py@@ -87,6 +87,35 @@ def test_npm_failure_returns_reason_not_raise(tmp_path, lazy_on):assert "exited 1" in reason and "ERESOLVE" in reason+def test_real_npm_installs_locked_sidecar_and_keeps_parent_unchanged(tmp_path, lazy_on):+ import json+ import os+ import shutil+ import subprocess++ npm = shutil.which("npm.cmd" if os.name == "nt" else "npm")+ node = shutil.which("node")+ if not npm or not node:+ pytest.skip("npm and node are required")+ dependency = tmp_path / "side-dep"+ dependency.mkdir()+ (dependency / "package.json").write_text(json.dumps({"name": "side-dep", "version": "1.0.0", "main": "index.js"}))+ (dependency / "index.js").write_text("module.exports = 'isolated';")+ plugin = tmp_path / "plugin"+ plugin.mkdir()+ (plugin / "package.json").write_text(json.dumps({"name": "plugin", "version": "1.0.0", "dependencies": {"side-dep": "file:../side-dep"}}))+ ambient = dict(os.environ)+ assert ws.install_node_sidecar(plugin, npm_bin=npm) is None+ lock = (plugin / "package-lock.json").read_bytes()+ assert ws.install_node_sidecar(plugin, npm_bin=npm) is None+ assert (plugin / "package-lock.json").read_bytes() == lock+ assert dict(os.environ) == ambient+ result = subprocess.run([node, "-e", "console.log(require('side-dep'))"], cwd=plugin, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "isolated"+ assert not (tmp_path / "node_modules").exists()++def test_runner_explosion_is_a_reason(tmp_path, lazy_on):plug = _plug(tmp_path)diff --git a/tests/pm/test_plugins_state.py b/tests/pm/test_plugins_state.pyindex 28e1d26d5cd..a2d4e02c98f 100644--- a/tests/pm/test_plugins_state.py+++ b/tests/pm/test_plugins_state.py@@ -7,6 +7,7 @@ owns.from __future__ import annotations+import refrom pathlib import Pathimport pytest@@ -130,3 +131,78 @@ def test_memory_provider_already_enabled_not_duplicated(homes):by_root = pstate.enabled_plugins_ordered()assert by_root[default_home / "plugins"] == ["dual"] # once, not twice+++def test_disable_preserves_comments_and_formatting(homes):+ """C18: the disable write must go through the round-trip YAML writer —+ comments/quotes/formatting OUTSIDE the mutated plugins.enabled key+ survive (a truncate reserialization of the whole file loses them)."""+ default_home, _ = homes+ (default_home / "config.yaml").write_text(+ "# my personal config — do not reformat\n"+ "plugins:\n"+ " enabled:\n"+ " - 'bad-plug'\n"+ " - keep-plug\n"+ "model: 'glm-5.3'\n"+ "# model notes below\n",+ encoding="utf-8",+ )+ pstate.disable_plugins(["bad-plug"])+ text = (default_home / "config.yaml").read_text(encoding="utf-8")+ assert "# my personal config — do not reformat" in text+ assert "# model notes below" in text+ assert "'glm-5.3'" in text # quoting style preserved+ assert "- keep-plug" in text+ # and the removal actually happened+ assert "bad-plug" not in text+++def test_disable_write_failure_is_surfaced(homes, monkeypatch):+ """A failed write must not silently claim the plugin was removed."""+ default_home, profile_home = homes+ _write_config(default_home, ["bad-plug"])+ _write_config(profile_home, ["bad-plug"])++ import utils++ def boom(path, key_path, value):+ raise OSError("disk full")++ monkeypatch.setattr(utils, "atomic_roundtrip_yaml_update", boom)+ with pytest.raises(OSError, match="disk full"):+ pstate.disable_plugins(["bad-plug"])+++def test_read_parses_config_once_per_home(homes, monkeypatch):+ """enabled_plugins_ordered must parse each home's config.yaml once,+ not once for plugins.enabled and again for memory.provider."""+ default_home, profile_home = homes+ _write_config(default_home, ["a-plug"])+ _write_config(profile_home, ["c-plug"])++ import utils++ calls: list = []+ real = utils.fast_safe_load++ def counting(stream):+ calls.append(stream)+ return real(stream)++ monkeypatch.setattr(utils, "fast_safe_load", counting)+ pstate.enabled_plugins_ordered()+ assert len(calls) == 2 # one per home, not one per query+++def test_disable_surfaces_malformed_config(homes):+ """An existing but unparseable config.yaml must not be silently+ skipped — disable would report success while the plugin stays+ enabled in that home. It must raise, naming the home."""+ default_home, profile_home = homes+ _write_config(default_home, ["bad-plug"])+ (profile_home / "config.yaml").write_text(+ "plugins:\n enabled: [unclosed\n", encoding="utf-8"+ )+ with pytest.raises(ValueError, match=re.escape(str(profile_home))):+ pstate.disable_plugins(["bad-plug"])diff --git a/tests/pm/test_pm_authority.py b/tests/pm/test_pm_authority.pyindex d230cc38d24..b5256a4f323 100644--- a/tests/pm/test_pm_authority.py+++ b/tests/pm/test_pm_authority.py@@ -73,7 +73,6 @@ def pm_env(tmp_path, served, monkeypatch):ensure_mod = importlib.import_module("pm.ensure")monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)- paths._stamp.cache_clear()saved = dict(registry._packages)registry._packages.clear()@@ -152,6 +151,150 @@ def test_same_version_different_sha_is_not_installed_and_repaired(pm_env):assert fact["artifacts"] == [digest_b][email protected]("matching_fact", [False, True])[email protected]("damage", ["missing-binary", "changed-bytes", "entry-is-file"])+def test_install_repairs_corrupt_entry_from_verified_archive(pm_env, matching_fact, damage):+ from pm.cli import cmd_doctor+ from pm.ensure import ensure++ ensure("faketool", base_env={})+ facts_path = paths.facts_path()+ fact = Facts(facts_path).get("faketool")+ entry = paths.store_root() / fact["entry"]+ binary = entry / "bin" / "faketool"+ if damage == "missing-binary":+ binary.unlink()+ elif damage == "changed-bytes":+ binary.write_bytes(b"corrupted")+ else:+ shutil.rmtree(entry)+ entry.write_bytes(b"not a directory")+ if not matching_fact:+ data = json.loads(facts_path.read_text())+ data["packages"]["faketool"].pop("artifacts")+ facts_path.write_text(json.dumps(data))++ ensure("faketool", explicit=True, base_env={})++ assert binary.read_bytes() == b"#!x"+ assert cmd_doctor(None) == 0+ assert Facts(facts_path).get("faketool")["digest"] == tree_digest(binary.parent.parent)++[email protected]("replacement", ["invalid", "publish-failure", "interrupted", "facts-failure"])+def test_failed_replacement_preserves_entry_and_facts(pm_env, monkeypatch, replacement):+ from pm.ensure import ensure+ from pm.package import InstallError++ env = pm_env+ ensure("faketool", base_env={})+ facts_path = paths.facts_path()+ old_facts = facts_path.read_bytes()+ old = Facts(facts_path).get("faketool")+ binary = paths.store_root() / old["entry"] / "bin" / "faketool"+ files = {"bin/unrelated": "bad layout"} if replacement == "invalid" else {"bin/faketool": "#!new"}+ _, digest = make_tar(env["docroot"], "replacement.tar.gz", files)+ lockfile = Lockfile(env["lockfile_path"])+ lockfile.set_pin("faketool", "1.0", {"any": {+ "url": f"{env['base_url']}/replacement.tar.gz", "sha256": digest,+ }})+ lockfile.save()+ if replacement in ("publish-failure", "interrupted"):+ original = Store.publish++ def fail_package_publish(self, staged, name):+ if name == old["entry"]:+ if replacement == "interrupted":+ raise KeyboardInterrupt()+ raise OSError("replacement publication failed")+ return original(self, staged, name)++ monkeypatch.setattr(Store, "publish", fail_package_publish)+ elif replacement == "facts-failure":+ def fail_record(*args, **kwargs):+ raise OSError("facts write failed")+ monkeypatch.setattr(Facts, "record", fail_record)++ expected_error = KeyboardInterrupt if replacement == "interrupted" else InstallError+ with pytest.raises(expected_error):+ ensure("faketool", explicit=True, base_env={})++ assert binary.read_bytes() == b"#!x"+ assert facts_path.read_bytes() == old_facts+++def test_killed_replacement_recovers_on_next_install(pm_env):+ """A process exit between moving old bytes and publishing new bytes is recoverable."""+ import os+ import subprocess+ import sys+ import textwrap++ from pm.ensure import ensure++ env = pm_env+ ensure("faketool", base_env={})+ old_fact = Facts(paths.facts_path()).get("faketool")+ _, digest = make_tar(env["docroot"], "replacement.tar.gz", {"bin/faketool": "#!new"})+ lockfile = Lockfile(env["lockfile_path"])+ lockfile.set_pin("faketool", "1.0", {"any": {+ "url": f"{env['base_url']}/replacement.tar.gz", "sha256": digest,+ }})+ lockfile.save()+ code = textwrap.dedent("""+ import os, sys+ from pathlib import Path+ import pm.paths as paths+ import pm.registry as registry+ from pm.store import Store+ from tests.pm.test_pm_authority import FakeTool+ from pm.ensure import ensure+ paths.lockfile_path = lambda: Path(sys.argv[1])+ registry._packages[FakeTool.name] = FakeTool()+ publish = Store.publish+ def crash(self, staged, name):+ if name.startswith('faketool-'):+ os._exit(17)+ return publish(self, staged, name)+ Store.publish = crash+ ensure('faketool', explicit=True, base_env={})+ """)+ child = subprocess.run(+ [sys.executable, "-c", code, str(env["lockfile_path"])],+ env=dict(os.environ), capture_output=True, text=True, timeout=30,+ )+ assert child.returncode == 17, child.stderr+ assert Facts(paths.facts_path()).get("faketool") == old_fact+ ensure("faketool", explicit=True, base_env={})+ fact = Facts(paths.facts_path()).get("faketool")+ entry = paths.store_root() / fact["entry"]+ assert (entry / "bin" / "faketool").read_bytes() == b"#!new"+ assert fact["digest"] == tree_digest(entry)+++def test_failed_restore_preserves_both_interrupted_versions(pm_env, monkeypatch):+ from pm.ensure import ensure+ from pm.package import InstallError++ ensure("faketool", base_env={})+ fact = Facts(paths.facts_path()).get("faketool")+ entry = paths.store_root() / fact["entry"]+ previous = entry.with_name(".previous-" + entry.name)+ previous.mkdir()+ (previous / "saved").write_text("previous")+ (entry / "bin" / "faketool").write_text("uncommitted replacement")+ real_rename = Path.rename+ def fail_restore(self, target):+ if self == previous:+ raise PermissionError("restore refused")+ return real_rename(self, target)+ monkeypatch.setattr(Path, "rename", fail_restore)+ with pytest.raises((PermissionError, InstallError), match="restore refused"):+ ensure("faketool", explicit=True, base_env={})+ assert (entry / "bin" / "faketool").read_text() == "uncommitted replacement"+ assert (previous / "saved").read_text() == "previous"++def test_poisoned_fetch_cache_is_redownloaded(pm_env):"""The fetch cache is keyed on the FULL sha and re-hashed before it istrusted; poisoned bytes are deleted and re-downloaded."""@@ -297,7 +440,7 @@ def test_adopt_adopts_intact_payload(pm_env):from pm.ensure import adopt_bundle_payload(pm_env)- marker = paths.store_root().parent / ".adopted"+ marker = paths.runtime_facts_path().parent / ".adopted"assert not marker.is_file()assert adopt() is Trueassert marker.is_file()@@ -313,7 +456,7 @@ def test_adopt_refuses_on_missing_staged_binary(pm_env):binary = paths.store_root() / fact["entry"] / "bin" / "faketool"binary.unlink()- marker = paths.store_root().parent / ".adopted"+ marker = paths.runtime_facts_path().parent / ".adopted"assert adopt() is Falseassert not marker.is_file()@@ -329,7 +472,7 @@ def test_adopt_refuses_on_tampered_staged_binary(pm_env):binary = paths.store_root() / fact["entry"] / "bin" / "faketool"binary.write_bytes(b"#!substituted")- marker = paths.store_root().parent / ".adopted"+ marker = paths.runtime_facts_path().parent / ".adopted"assert adopt() is Falseassert not marker.is_file()diff --git a/tests/pm/test_pm_core.py b/tests/pm/test_pm_core.pyindex 9f5fe77a78d..82e44e58c48 100644--- a/tests/pm/test_pm_core.py+++ b/tests/pm/test_pm_core.py@@ -100,7 +100,6 @@ def pm_env(tmp_path, served, monkeypatch):ensure_mod = importlib.import_module("pm.ensure")monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)- paths._stamp.cache_clear()saved = dict(registry._packages)registry._packages.clear()@@ -351,15 +350,14 @@ def test_corrupt_facts_degrades_to_empty(pm_env):assert (runtime / "facts.corrupt").is_file()-def test_sealed_install_refuses_even_explicit(pm_env, monkeypatch):- from pm.ensure import ensure+def test_sealed_install_explicit_addition_leaves_payload_unchanged(pm_env, monkeypatch):+ from pm.ensure import ensure, is_installed_, runtime, *_ = pm_env- (runtime.parent / "manifest.json").write_text(- '{"schema": 1}', encoding="utf-8"- )- with pytest.raises(InstallError, match="sealed"):- ensure("faketool", base_env={}, explicit=True)+ (runtime.parent / "manifest.json").write_text('{"schema": 1}', encoding="utf-8")+ ensure("faketool", base_env={}, explicit=True)+ assert is_installed("faketool")+ assert not (runtime / "facts.json").exists()def test_concurrent_installs_do_not_clobber(pm_env):@@ -590,7 +588,6 @@ def test_adopt_noop_without_facts(pm_env, monkeypatch):from pm import pathsmonkeypatch.setenv("HERMES_RUNTIME_DIR", str(paths.store_root() / "nowhere"))- paths._stamp.cache_clear()assert pm.adopt() is Falsediff --git a/tests/pm/test_receipt.py b/tests/pm/test_receipt.pyindex d81c2ef3e48..e23fb5ce89f 100644--- a/tests/pm/test_receipt.py+++ b/tests/pm/test_receipt.py@@ -13,6 +13,15 @@ import pytestimport pm.receipt as receipt[email protected](autouse=True)+def _isolated_receipt_context():+ """The ContextVar is module state — tests must not see each other's+ in-flight receipt (a leaked begin would corrupt the next test)."""+ receipt._current.set(None)+ yield+ receipt._current.set(None)++@pytest.fixturedef homed(tmp_path, monkeypatch):"""Receipt dir inside a temp hermes home."""@@ -70,3 +79,167 @@ def test_snapshot_returns_inflight(homed):def test_latest_none_when_empty(homed):assert receipt.latest() is None+++def test_latest_does_not_create_dirs(homed):+ """Reading a receipt must be side-effect free — no logs/ mkdir."""+ import shutil++ logs = homed / "logs"+ if logs.exists():+ shutil.rmtree(logs)+ assert receipt.latest() is None+ assert not logs.exists()+++def test_concurrent_finalize_writes_unique_names(homed):+ """Overlapping syncs (threaded cadence/ensure) must each get their own+ receipt file — no stamp collision overwrites."""+ import threading++ paths: list = []+ errors: list = []++ def run(i):+ try:+ receipt.begin("sync")+ receipt.record_step(f"step-{i}", True)+ paths.append(receipt.finalize("ok"))+ except Exception as exc: # pragma: no cover+ errors.append(exc)++ threads = [threading.Thread(target=run, args=(i,)) for i in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert not errors+ assert all(p is not None and p.is_file() for p in paths)+ assert len({p.name for p in paths}) == 8+++def test_rotation_only_removes_pm_receipts(homed):+ """The shared receipts dir also holds the updater's update_*.json —+ pm rotation must never delete those."""+ d = homed / "logs" / "update_receipts"+ d.mkdir(parents=True)+ updater = d / "update_20260101_000000_123.json"+ updater.write_text('{"kind": "update"}\n', encoding="utf-8")+ for i in range(25):+ (d / f"pm_20260101T0000{i:02d}Z-sync-1-0001.json").write_text(+ '{"kind": "sync"}\n', encoding="utf-8"+ )+ receipt._rotate(d)+ assert updater.is_file()+ kept = sorted(p.name for p in d.glob("pm_*.json"))+ assert len(kept) == 20 # oldest pm receipts rotated, updater receipt untouched+++def test_receipt_state_is_thread_scoped(homed):+ """begin/record must not leak across threads: an overlapping sync in+ another thread neither sees nor clobbers this one's in-flight receipt."""+ import threading++ receipt.begin("sync")+ receipt.record_step("mine", True)+ seen: dict = {}++ def other():+ seen["snapshot_from_other"] = receipt.snapshot()+ receipt.begin("update")+ receipt.record_step("theirs", False)+ receipt.finalize("failed")+ seen["after_other"] = receipt.snapshot()++ t = threading.Thread(target=other)+ t.start()+ t.join()+ # the other thread never saw our in-flight receipt+ assert seen["snapshot_from_other"] is None+ # its begin/finalize did not clobber ours+ snap = receipt.snapshot()+ assert snap is not None and snap["kind"] == "sync"+ assert [s["name"] for s in snap["steps"]] == ["mine"]+ path = receipt.finalize("ok")+ assert path is not None and path.is_file()+++def test_copied_context_does_not_corrupt_parent_receipt():+ """A copied context (asyncio.to_thread / task group pattern) inherits+ the SAME ContextVar dict — record_step must copy-on-write, never+ mutate the parent's in-flight receipt in place."""+ import contextvars++ receipt.begin("sync")+ receipt.record_step("parent", True)+ parent_before = receipt.snapshot()++ def child():+ receipt.record_step("child", False)+ return receipt.snapshot()++ ctx = contextvars.copy_context()+ child_seen = ctx.run(child)++ # the child saw the parent's receipt (ambient inheritance) and+ # appended its own step — in ITS copy only+ assert [s["name"] for s in child_seen["steps"]] == ["parent", "child"]+ # the parent's receipt is untouched by the child's record+ parent_after = receipt.snapshot()+ assert [s["name"] for s in parent_after["steps"]] == ["parent"]+ assert parent_after == parent_before+ receipt.finalize("ok")+++def test_copied_context_finalize_does_not_finish_parent(homed):+ import contextvars++ receipt.begin("sync")+ contextvars.copy_context().run(receipt.finalize, "failed", 1)+ assert receipt.snapshot()["outcome"] is None+++def test_recorded_values_are_not_mutable_through_the_input():+ receipt.begin("sync")+ decisions = [{"plugin": "a", "action": "kept"}]+ receipt.record_bisect(decisions)+ decisions[0]["action"] = "disabled"+ assert receipt.snapshot()["plugin_bisect"][0]["action"] == "kept"+++def test_snapshot_returns_a_copy():+ """Mutating the snapshot must not touch the authoritative receipt."""+ receipt.begin("sync")+ receipt.record_step("a", True)+ snap = receipt.snapshot()+ snap["steps"].append({"name": "injected", "ok": True})+ snap["kind"] = "hijacked"+ live = receipt.snapshot()+ assert [s["name"] for s in live["steps"]] == ["a"]+ assert live["kind"] == "sync"+++def test_nested_begin_with_token_restores_outer():+ """A nested begin (same context) with the token from finalize must+ restore the OUTER receipt instead of discarding it."""+ outer = receipt.begin("sync")+ receipt.record_step("outer-step", True)+ inner = receipt.begin("update")+ receipt.record_step("inner-step", True)+ receipt.finalize("ok", token=inner)+ # outer receipt survives the inner finalize+ live = receipt.snapshot()+ assert live is not None and live["kind"] == "sync"+ assert [s["name"] for s in live["steps"]] == ["outer-step"]+ path = receipt.finalize("ok", token=outer)+ assert path is not None and path.is_file()+ assert receipt.snapshot() is None+++def test_finalize_without_token_pops_receipt():+ """Ambient (no token) finalize still pops the receipt — the existing+ linear begin→finalize consumers keep working."""+ receipt.begin("sync")+ assert receipt.finalize("ok") is not None+ assert receipt.snapshot() is None+ assert receipt.finalize("ok") is None # nothing begundiff --git a/tests/pm/test_runtime_selection.py b/tests/pm/test_runtime_selection.pynew file mode 100644index 00000000000..99605f35d07--- /dev/null+++ b/tests/pm/test_runtime_selection.py@@ -0,0 +1,116 @@+"""Install-scoped dependency selection is readable before third-party imports."""+import json+from pathlib import Path++import pytest+++def test_install_runtime_selection_is_scoped_and_read_only(tmp_path, monkeypatch):+ from hermes_cli import runtime_paths++ home = tmp_path / "home"+ monkeypatch.setenv("HERMES_HOME", str(home))+ first, second = tmp_path / "first", tmp_path / "second"+ for root in (first, second):+ (root / ".venv").mkdir(parents=True)+ assert runtime_paths.selected_venv(first) == first / ".venv"+ assert not home.exists()+ state = runtime_paths.install_state_dir(first)+ assert state != runtime_paths.install_state_dir(second)+ generation = state / "environments" / "candidate" / "venv"+ generation.mkdir(parents=True)+ (generation / "pyvenv.cfg").write_text("home = test\n")+ (state / "facts.json").write_text(json.dumps({+ "schema": 1, "packages": {"venv": {"environment": str(generation), "stamp": "verified"}},+ }))+ assert runtime_paths.selected_venv(first) == generation+ assert runtime_paths.selected_venv(second) == second / ".venv"+ monkeypatch.setenv("HERMES_HOME", str(home / "profiles" / "work"))+ assert runtime_paths.selected_venv(first) == generation+++def test_boot_uses_one_selected_dependency_tree_in_fresh_process(tmp_path, monkeypatch):+ import os+ import subprocess+ import sys+ from hermes_cli import runtime_paths++ root = tmp_path / "repo"+ base = root / "venv"+ home = tmp_path / "home"+ monkeypatch.setenv("HERMES_HOME", str(home))+ state = runtime_paths.install_state_dir(root)+ selected = state / "environments" / "new" / "venv"+ def site_of(venv):+ return venv / ("Lib/site-packages" if os.name == "nt" else f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")+ for venv, version in [(base, "old"), (selected, "new")]:+ site = site_of(venv)+ site.mkdir(parents=True)+ (venv / "pyvenv.cfg").write_text("home = test")+ (site / "probe_package.py").write_text(f"version = {version!r}")+ (site_of(base) / "base_only.py").write_text("version = 'must-not-leak'")+ (state / "facts.json").write_text(json.dumps({"schema": 1, "packages": {+ "venv": {"environment": str(selected)}+ }}))+ code = (+ "import sys; from pathlib import Path; from hermes_cli.runtime_paths import activate_dependencies; "+ "sys.path.insert(0, sys.argv[2]); activate_dependencies(Path(sys.argv[1])); "+ "import probe_package, importlib.util; print(probe_package.version); "+ "print(importlib.util.find_spec('base_only') is None)"+ )+ process = subprocess.run([sys.executable, "-c", code, str(root), str(site_of(base))],+ env=dict(os.environ), text=True, capture_output=True, timeout=30)+ assert process.returncode == 0, process.stderr+ assert process.stdout.splitlines() == ["new", "True"]++[email protected]("command,allowed", [(["pm", "install", "--help"], True), (["pm", "doctor"], True), (["chat"], False), (["chat", "pm", "install"], False)])+def test_broken_environment_keeps_explicit_repair_entry_reachable(tmp_path, monkeypatch, command, allowed):+ import os+ import subprocess+ import sys+ from hermes_cli.runtime_paths import runtime_facts_path++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ repo = Path(__file__).resolve().parents[2]+ record = runtime_facts_path(repo)+ record.parent.mkdir(parents=True)+ record.write_text(json.dumps({"packages": {"venv": {"environment": str(tmp_path / "missing")}}}))+ code = "import sys; sys.argv = ['hermes', *sys.argv[1:]]; import hermes_bootstrap; print('bootstrap-ready')"+ result = subprocess.run([sys.executable, "-c", code, *command], env=dict(os.environ),+ capture_output=True, text=True, timeout=30)+ assert (result.returncode == 0) is allowed, result.stderr+ if not allowed:+ assert "hermes pm install" in result.stderr+ assert "Traceback" not in result.stderr++[email protected]("data", [[], {"packages": []}, {"packages": {"venv": []}}])+def test_malformed_selection_has_actionable_error(tmp_path, monkeypatch, data):+ from hermes_cli import runtime_paths+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ record = runtime_paths.runtime_facts_path(tmp_path / "repo")+ record.parent.mkdir(parents=True)+ record.write_text(json.dumps(data))+ with pytest.raises(RuntimeError, match="dependency environment"):+ runtime_paths.selected_venv(tmp_path / "repo")++[email protected]("bad_path", ["outside", "missing"])+def test_invalid_selected_environment_never_silently_falls_back(tmp_path, monkeypatch, bad_path):+ from hermes_cli import runtime_paths++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ root = tmp_path / "repo"+ (root / "venv").mkdir(parents=True)+ state = runtime_paths.install_state_dir(root)+ state.mkdir(parents=True)+ candidate = tmp_path / "outside" if bad_path == "outside" else state / "environments" / "missing"+ if bad_path == "outside":+ candidate.mkdir()+ (candidate / "pyvenv.cfg").write_text("home = test\n")+ (state / "facts.json").write_text(json.dumps({+ "schema": 1, "packages": {"venv": {"environment": str(candidate)}},+ }))+ with pytest.raises(RuntimeError, match="environment"):+ runtime_paths.selected_venv(root)diff --git a/tests/pm/test_runtime_transaction.py b/tests/pm/test_runtime_transaction.pynew file mode 100644index 00000000000..21d9e7b2f57--- /dev/null+++ b/tests/pm/test_runtime_transaction.py@@ -0,0 +1,129 @@+"""Preparing dependencies never mutates the selected environment or plugin config."""+from pathlib import Path+import importlib++import pytest++from pm.lock import Facts+from pm.package import InstallError++[email protected]("failure", ["build", "record", "missing", None])+def test_sync_commits_only_a_successful_candidate(tmp_path, monkeypatch, failure):+ import pm.paths as paths+ import pm.registry as registry+ from hermes_cli.runtime_paths import selected_venv+ from pm.packages import Venv++ ensure = importlib.import_module("pm.ensure")+ root = tmp_path / "repo"+ root.mkdir()+ (root / "uv.lock").write_text("initial-lock")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(paths, "repo_root", lambda: root)+ monkeypatch.setattr(ensure, "sealed", lambda: False)+ monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: True)+ monkeypatch.setattr("pm.workspace.enabled_member_dirs", lambda: [])+ config = tmp_path / "home" / "config.yaml"+ config.parent.mkdir()+ config.write_text("plugins:\n enabled: [working]\n")+ original_config = config.read_bytes()+ runtime_facts = Facts(paths.runtime_facts_path())+ previous = paths.runtime_facts_path().parent / "environments" / "previous" / "venv"+ previous.mkdir(parents=True)+ (previous / "pyvenv.cfg").write_text("home = previous")+ runtime_facts.record_state("venv", "old", ["base"], environment=previous)+ if failure == "missing":+ (previous / "pyvenv.cfg").unlink()+ runtime_facts.record_state("venv", "new", ["base", "new-extra"], environment=previous)+ before = runtime_facts.path.read_bytes()+ candidate = previous.parent.parent / "candidate" / "venv"++ class TestVenv(Venv):+ def expected_stamp(self, extras):+ return "new"++ def apply(self, extras):+ if failure != "missing":+ assert selected_venv(root) == previous+ assert extras == ["base", "new-extra"]+ if failure == "build":+ raise InstallError("venv", "download unavailable")+ candidate.mkdir(parents=True)+ (candidate / "pyvenv.cfg").write_text("home = candidate")+ return {"environment": candidate}++ monkeypatch.setitem(registry._packages, "venv", TestVenv())+ if failure == "record":+ def refuse_record(self, *args, **kwargs):+ raise OSError("disk full")+ monkeypatch.setattr(Facts, "record_state", refuse_record)+ if failure in ("build", "record"):+ with pytest.raises((InstallError, OSError)):+ ensure.sync_venv(["new-extra"], explicit=True)+ assert runtime_facts.path.read_bytes() == before+ assert selected_venv(root) == previous+ else:+ ensure.sync_venv(["new-extra"], explicit=True)+ assert selected_venv(root) == candidate+ assert Facts(runtime_facts.path).get("venv")["extras"] == ["base", "new-extra"]+ assert previous.is_dir()+ assert config.read_bytes() == original_config+++def test_real_uv_builds_separate_environment_before_selection(tmp_path, monkeypatch):+ import shutil+ import subprocess+ import sys+ import pm.paths as paths+ from pm.packages import Venv+ from hermes_cli.runtime_paths import selected_venv++ uv = shutil.which("uv")+ assert uv is not None, "uv is required for the real environment contract"+ core = tmp_path / "core"+ core.mkdir()+ (core / "pyproject.toml").write_text(+ '[project]\nname="environment-test"\nversion="1"\nrequires-python=">=3.11"\n'+ '[tool.uv]\npackage=false\n', encoding="utf-8",+ )+ subprocess.run([uv, "lock", "--offline", "--python", sys.executable], cwd=core, check=True, capture_output=True)+ original_lock = (core / "uv.lock").read_bytes()+ base = core / "venv"+ base.mkdir()+ (base / "pyvenv.cfg").write_text("home = previous")+ monkeypatch.setattr(paths, "repo_root", lambda: core)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr("pm.workspace.enabled_member_dirs", lambda: [])+ ensure = importlib.import_module("pm.ensure")+ from pm.packages import uv_env+ monkeypatch.setattr(ensure, "uv", lambda **kw: (uv, uv_env()))+ prepared = Venv().apply([])+ assert selected_venv(core) == base+ candidate = prepared["environment"]+ assert candidate != base and (candidate / "pyvenv.cfg").is_file()+ python = candidate / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+ probe = subprocess.run([str(python), "-c", "import sys; print(sys.prefix)"], capture_output=True, text=True, check=True)+ assert Path(probe.stdout.strip()).resolve() == candidate.resolve()+ assert (core / "uv.lock").read_bytes() == original_lock+++def test_lazy_import_reports_restart_instead_of_importing_mixed_versions(tmp_path, monkeypatch):+ from hermes_cli.runtime_paths import runtime_facts_path+ import pm.extras as extras+ import pm.paths as paths++ root = tmp_path / "repo"+ root.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(paths, "repo_root", lambda: root)+ monkeypatch.setattr(extras, "available", lambda _: False)+ monkeypatch.setattr(extras, "extra_supported", lambda _: True)+ candidate = runtime_facts_path(root).parent / "environments" / "new" / "venv"+ candidate.mkdir(parents=True)+ (candidate / "pyvenv.cfg").write_text("home = test")+ def prepare(requested):+ Facts(runtime_facts_path(root)).record_state("venv", "new", requested, environment=candidate)+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "sync_venv", prepare)+ with pytest.raises(InstallError, match="restart"):+ extras.ensure_import("new-extra")diff --git a/tests/pm/test_store_extensions.py b/tests/pm/test_store_extensions.pynew file mode 100644index 00000000000..5aad33bf21b--- /dev/null+++ b/tests/pm/test_store_extensions.py@@ -0,0 +1,62 @@+"""A bundle reuses shipped bytes and adds missing pinned tools outside its seal."""+import json+from pathlib import Path++import pytest++import pm.paths as paths+from pm.lock import Facts, Lockfile+from tests.pm.test_pm_authority import pm_env, served # noqa: F401 — fixtures++[email protected]("sealed_install", [True, False])+def test_missing_bundle_tool_is_installed_in_writable_store(pm_env, tmp_path, monkeypatch, sealed_install):+ from pm.ensure import ensure, env_for, is_installed+ import importlib++ fixture = pm_env+ shipped = tmp_path / "payload" / "tools"+ shipped.mkdir(parents=True)+ (shipped.parent / "manifest.json").write_text('{"repo":"core","store":"tools","venv":"venv"}')+ monkeypatch.setattr(paths, "store_root", lambda: shipped)+ monkeypatch.setattr(paths, "facts_path", lambda: shipped / "facts.json")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ ensure_module = importlib.import_module("pm.ensure")+ monkeypatch.setattr(ensure_module, "lazy_installs_allowed", lambda: True)+ monkeypatch.setattr(ensure_module, "sealed", lambda: sealed_install)+ before = sorted(p.relative_to(shipped).as_posix() for p in shipped.rglob("*"))+ runner = ensure("faketool", explicit=True, base_env={})+ assert is_installed("faketool")+ assert sorted(p.relative_to(shipped).as_posix() for p in shipped.rglob("*")) == before+ writable = paths.writable_store_root()+ fact = Facts(writable / "facts.json").get("faketool")+ assert fact is not None and (writable / fact["entry"] / "bin" / "faketool").is_file()+ assert str(writable) in runner.env["PATH"]+ assert env_for("faketool", base_env={}) == runner.env+++def test_adoption_records_verification_outside_shipped_payload(pm_env, monkeypatch):+ from pm.ensure import adopt+ from tests.pm.test_pm_authority import _bundle_payload++ _bundle_payload(pm_env)+ shipped_roots = (paths.store_root(), paths.repo_root())+ def snapshot():+ return {p: p.read_bytes() for root in shipped_roots for p in root.rglob("*") if p.is_file()}+ before = snapshot()+ assert adopt() is True+ assert snapshot() == before+ assert not (paths.store_root().parent / ".adopted").exists()+ assert adopt() is False+++def test_corrupt_shipped_facts_are_only_read(tmp_path, monkeypatch):+ store = tmp_path / "payload" / "tools"+ store.mkdir(parents=True)+ (store.parent / "manifest.json").write_text("{}")+ facts = store / "facts.json"+ facts.write_text("{broken")+ monkeypatch.setattr(paths, "store_root", lambda: store)+ assert Facts(facts).get("anything") is None+ assert facts.read_text() == "{broken"+ assert not facts.with_suffix(".corrupt").exists()diff --git a/tests/pm/test_store_resume.py b/tests/pm/test_store_resume.pyindex ae150c05484..c6b0c359cfa 100644--- a/tests/pm/test_store_resume.py+++ b/tests/pm/test_store_resume.py@@ -53,7 +53,6 @@ def test_store_fetch_resumes_interrupted_download(tmp_path, dl_server, monkeypat# Isolate the store root (and thus the managed partials area) to tmp_path.runtime = tmp_path / "runtime"monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))- paths._stamp.cache_clear()# Serve in small pieces so the mid-body abort fires inside the single# byte range (the shared fixture resets this to 1 MiB).diff --git a/tests/pm/test_uv_cache.py b/tests/pm/test_uv_cache.pyindex 14a4ddeebf8..4322619b525 100644--- a/tests/pm/test_uv_cache.py+++ b/tests/pm/test_uv_cache.py@@ -1,10 +1,4 @@-"""pm uv cache: hermes-owned UV_CACHE_DIR + sealed-venv bootstrap seed.--The cache ships with bundles and is copied out to the writable machine-cache on first use; every pm-internal uv invocation pins UV_CACHE_DIR.-The mutable venv on sealed installs lives in the machine hermes root,-seeded from the payload's shipped venv when lazy installs are off.-"""+"""PM caches are writable; shipped dependency environments stay immutable."""from __future__ import annotations@@ -63,66 +57,21 @@ def test_uv_cache_dir_cold_machine_no_payload(monkeypatch, tmp_path):assert (machine / ".seeded").is_file()-def test_venv_dir_sealed_goes_to_machine_root(monkeypatch, tmp_path):- home = tmp_path / "home"- home.mkdir()- import sys-- import hermes_constants-- monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: home)- ensure_mod = sys.modules["pm.ensure"]- monkeypatch.setattr(ensure_mod, "sealed", lambda: True)- venv = pkgs.Venv()- assert venv.venv_dir() == home / "venv"---def test_seed_mutable_venv_copies_payload_venv(monkeypatch, tmp_path):- home = tmp_path / "home"- home.mkdir()- payload = tmp_path / "payload"- (payload / "venv" / "Scripts").mkdir(parents=True)- (payload / "venv" / "Scripts" / "python.exe").write_text("bin", encoding="utf-8")-- import hermes_constants-- monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: home)- import sys-- ensure_mod = sys.modules["pm.ensure"]- import pm.paths as paths_mod-- monkeypatch.setattr(ensure_mod, "sealed", lambda: True)- monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: False)- monkeypatch.setattr(paths_mod, "store_root", lambda: payload / "tools")-- venv = pkgs.Venv()- reason = venv.seed_mutable_venv()- assert reason is None- seeded = home / "venv"- assert (seeded / "Scripts" / "python.exe").read_text(encoding="utf-8") == "bin"- # idempotent: second call is a no-op- assert venv.seed_mutable_venv() is None-[email protected]("lazy_allowed", [False, True])+def test_bundle_uses_shipped_environment_until_an_extension_is_committed(monkeypatch, tmp_path, lazy_allowed):+ import json+ import importlib+ import pm.paths as paths-def test_seed_mutable_venv_lazy_on_skips_copy(monkeypatch, tmp_path):home = tmp_path / "home"- home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))payload = tmp_path / "payload"- (payload / "venv").mkdir(parents=True)-- import hermes_constants-- monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: home)- import sys-- ensure_mod = sys.modules["pm.ensure"]- import pm.paths as paths_mod-- monkeypatch.setattr(ensure_mod, "sealed", lambda: True)- monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)- monkeypatch.setattr(paths_mod, "store_root", lambda: payload / "tools")-- venv = pkgs.Venv()- assert venv.seed_mutable_venv() is None- assert not (home / "venv").exists() # builds fresh later, no seed copy+ core = payload / "hermes-agent"+ core.mkdir(parents=True)+ shipped = payload / "venv"+ shipped.mkdir()+ (payload / "manifest.json").write_text(json.dumps({"repo": "hermes-agent", "venv": "venv"}))+ monkeypatch.setattr(paths, "repo_root", lambda: core)+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "lazy_installs_allowed", lambda: lazy_allowed)+ assert pkgs.Venv().venv_dir() == shipped+ assert not home.exists(), "selecting shipped dependencies must not copy or mutate them"diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.pyindex a041d99897a..2621e7212ec 100644--- a/tests/pm/test_workspace.py+++ b/tests/pm/test_workspace.py@@ -10,6 +10,8 @@ core + plugin deps into ONE lock; conflict = loud refusal.from __future__ import annotations+import os+import subprocessfrom pathlib import Pathimport pytest@@ -46,10 +48,11 @@ def layout(tmp_path, monkeypatch):return tmp_path, core, plug_a, store-def test_workspace_root_lives_in_the_store(layout):- _, _, _, store = layout- assert ws.workspace_root() == store / ".pm-workspace"- assert ws.workspace_root() == ws.workspace_root() # stable+def test_workspace_root_is_per_install_not_in_the_store(layout):+ from hermes_cli.runtime_paths import install_state_dir+ _, core, _, store = layout+ assert ws.workspace_root() == install_state_dir(core) / ".pm-workspace"+ assert not ws.workspace_root().is_relative_to(store)def test_build_writes_core_pyproject_verbatim(layout):@@ -94,51 +97,6 @@ def test_zero_plugins_still_builds_a_root_with_no_members(layout):assert "[tool.uv.workspace]" not in text or "members = []" in text-def test_resolve_union_passes_through_on_clean_resolve(monkeypatch):- a, b = Path("/x/a"), Path("/x/b")- calls = []- monkeypatch.setattr(- ws, "lock_and_sync", lambda members, extras=None, **k: calls.append(members)- )- survivors, decisions = ws.resolve_union([a, b], ["web"])- assert survivors == [a, b]- assert decisions == []- assert calls == [[a, b]]---def test_resolve_union_disables_fail_alone_plugins(monkeypatch):- a, b, bad = Path("/x/a"), Path("/x/b"), Path("/x/bad")- from pm.package import InstallError-- def fake_lock(members, extras=None, **k):- if any(m == bad for m in members):- raise InstallError("venv", "bad conflicts with core pin")- return None-- monkeypatch.setattr(ws, "lock_and_sync", fake_lock)- survivors, decisions = ws.resolve_union([a, bad, b])- assert bad not in survivors- assert [d["plugin"] for d in decisions] == ["bad"]- assert "core pin" in decisions[0]["reason"]---def test_resolve_union_incumbent_wins_on_mutual_conflict(monkeypatch):- old, new = Path("/x/old-plug"), Path("/x/new-plug")- from pm.package import InstallError-- def fake_lock(members, extras=None, **k):- if old in members and new in members:- raise InstallError("venv", "old-plug and new-plug are incompatible")- return None-- monkeypatch.setattr(ws, "lock_and_sync", fake_lock)- # newest-enabled LAST (the tiebreak contract)- survivors, decisions = ws.resolve_union([old, new])- assert survivors == [old] # incumbent survives- assert [d["plugin"] for d in decisions] == ["new-plug"]- assert "incompatible" in decisions[0]["reason"]--def test_member_stamp_hash_changes_with_plugin_set(layout):_, _, plug_a, _ = layoutstamp_empty = ws.members_stamp([])@@ -234,87 +192,6 @@ def test_enabled_member_dirs_empty_when_nothing_enabled(tmp_path, monkeypatch):assert ws.enabled_member_dirs() == []-def test_record_disabled_plugins_writes_back(monkeypatch):- calls = []-- def fake_disable(names):- calls.append(names)-- monkeypatch.setattr("pm.plugins_state.disable_plugins", fake_disable)- removed = ws.record_disabled_plugins(- [- {"plugin": "bad", "action": "disabled", "reason": "conflict"},- {"plugin": "good", "action": "kept", "reason": ""},- ]- )- assert removed == ["bad"]- assert calls == [["bad"]]---def lazy_on(monkeypatch):- import sys-- ensure_mod = sys.modules["pm.ensure"]- monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)---def test_materialize_legacy_pyproject_from_pip_dependencies(tmp_path, lazy_on):- plug = tmp_path / "legacy-plug"- plug.mkdir()- (plug / "plugin.yaml").write_text(- "name: legacy-plug\n"- "version: 1.0.0\n"- "pip_dependencies:\n"- " - \"mcp>=2,<3\"\n"- " - 'click==8.1.7'\n",- encoding="utf-8",- )-- generated = ws.materialize_legacy_pyproject(plug)- assert generated is not None and generated.is_file()- text = generated.read_text(encoding="utf-8")- assert "GENERATED by pm" in text- assert 'name = "legacy-plug"' in text- assert "'mcp>=2,<3'" in text- assert "'click==8.1.7'" in text-- # idempotent: regenerating with same specs is byte-identical- again = ws.materialize_legacy_pyproject(plug)- assert again.read_text(encoding="utf-8") == text-- # spec change rewrites- (plug / "plugin.yaml").write_text(- "name: legacy-plug\npip_dependencies:\n - \"requests>=2\"\n",- encoding="utf-8",- )- ws.materialize_legacy_pyproject(plug)- assert "'requests>=2'" in generated.read_text(encoding="utf-8")---def test_materialize_skips_modern_and_depless_plugins(tmp_path):- # modern plugin: has its own pyproject — untouched- modern = tmp_path / "modern"- modern.mkdir()- (modern / "pyproject.toml").write_text("[project]\n", encoding="utf-8")- (modern / "plugin.yaml").write_text(- "name: modern\npython_dependencies:\n - \"x\"\n", encoding="utf-8"- )- assert ws.materialize_legacy_pyproject(modern) is None- assert '[project]' == (modern / "pyproject.toml").read_text(encoding="utf-8").strip()-- # dep-less plugin: nothing to bridge- plain = tmp_path / "plain"- plain.mkdir()- (plain / "plugin.yaml").write_text("name: plain\n", encoding="utf-8")- assert ws.materialize_legacy_pyproject(plain) is None-- # no manifest at all- empty = tmp_path / "empty"- empty.mkdir()- assert ws.materialize_legacy_pyproject(empty) is None--def test_scan_plugin_classifies_dep_surfaces(tmp_path):full = tmp_path / "full-plug"full.mkdir()@@ -354,16 +231,142 @@ def test_enabled_member_dirs_survives_unreadable_roots(tmp_path, monkeypatch):assert [p.name for p in found] == ["member"]-def test_materialize_never_when_lazy_off(tmp_path, monkeypatch):- import sys+# --- classified failures + staging surface (FINAL-RUNTIME-CONTRACT) ---- ensure_mod = sys.modules["pm.ensure"]- monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: False)- plug = tmp_path / "legacy-plug"- plug.mkdir()- (plug / "plugin.yaml").write_text(- "name: legacy-plug\npip_dependencies:\n - \"requests>=2\"\n",- encoding="utf-8",++def test_classify_resolver_conflict_is_resolutionconflict():+ from pm.package import InstallError+ from pm.workspace import ResolutionConflict, classify_uv_failure++ err = classify_uv_failure(+ "lock", 1,+ " x No solution found for `hermes-agent>=0.1.0` because only the "+ "following versions are available:\n",+ )+ assert isinstance(err, ResolutionConflict)+ assert isinstance(err, InstallError)+ assert "no solution found" in str(err).lower()+++def test_classify_network_failure_stays_generic():+ from pm.workspace import ResolutionConflict, classify_uv_failure++ err = classify_uv_failure("lock", 1, "error: Failed to fetch https://pypi.org (timed out)")+ assert not isinstance(err, ResolutionConflict)+++def test_sync_failure_is_never_a_conflict(tmp_path, monkeypatch):+ """--frozen: the lock already resolved, so a sync failure (download,+ build, tooling) must stay generic — it must not disable plugins."""+ from pm.package import InstallError+ from pm.workspace import ResolutionConflict++ class FakeProc:+ returncode = 1+ stderr = "error: Failed to download wheel (connection reset)"+ stdout = ""++ monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (Path("/x/ws"), False))+ monkeypatch.setattr(ws, "_uv_binary", lambda: "uv")+ monkeypatch.setattr("pm.packages.uv_env", lambda env=None: {"UV_CACHE_DIR": "/x/cache"})++ captured = {}++ def fake_run(cmd, **kwargs):+ captured["cmd"] = cmd+ return FakeProc()++ monkeypatch.setattr(ws.subprocess, "run", fake_run)+ with pytest.raises(InstallError) as excinfo:+ ws.lock_and_sync([], [], venv_dir=tmp_path / "candidate")+ assert not isinstance(excinfo.value, ResolutionConflict)+++def test_staging_root_and_env_are_honored_without_live_mutation(monkeypatch, tmp_path):+ """lock_and_sync must resolve into the PARENT-SUPPLIED staging root ++ venv, pass a COPY of the environment (never mutate the live one), and+ leave the default generated root untouched."""+ staging = tmp_path / "staging-ws"+ staging.mkdir()++ seen = {}++ class FakeProc:+ returncode = 0+ stderr = ""+ stdout = ""++ def fake_run(cmd, cwd=None, env=None, **kwargs):+ seen["cwd"] = cwd+ seen["env"] = env+ return FakeProc()++ monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (staging, False))+ monkeypatch.setattr(ws, "_uv_binary", lambda: "uv")+ monkeypatch.setattr(+ "pm.packages.uv_env",+ lambda env=None: {**(env or {}), "UV_CACHE_DIR": "/x/cache"},)- assert ws.materialize_legacy_pyproject(plug) is None- assert not (plug / "pyproject.toml").exists()+ monkeypatch.setattr(ws.subprocess, "run", fake_run)++ live_key = "PM_WORKSPACE_TEST_SENTINEL"+ os.environ[live_key] = "live"+ try:+ ws.lock_and_sync(+ [], [], venv_dir=tmp_path / "staging-venv", root=staging,+ env={"PATH": "/staged/bin", live_key: "staged"},+ )++ assert Path(seen["cwd"]) == staging+ assert seen["env"][live_key] == "staged" # staged env wins+ assert seen["env"]["UV_CACHE_DIR"] == "/x/cache" # uv_env layered on top+ assert seen["env"]["UV_PROJECT_ENVIRONMENT"] == str(tmp_path / "staging-venv")+ assert os.environ[live_key] == "live" # live env untouched+ finally:+ del os.environ[live_key]+++def test_changed_root_seeds_from_committed_lock_unchanged_keeps_extended(+ layout, monkeypatch, tmp_path+):+ """Seed the CURRENT resolution without writing shipped bytes: a fresh+ root seeds from the committed lock; an existing root seeds from its+ own extended lock; an explicit parent-supplied seed_lock wins."""+ _, core, plug_a, store = layout+ (core / "uv.lock").write_bytes(b"committed-bytes\n")++ class FakeProc:+ returncode = 0+ stderr = ""+ stdout = ""++ monkeypatch.setattr(ws, "_uv_binary", lambda: "uv")+ monkeypatch.setattr(ws.subprocess, "run", lambda cmd, **k: FakeProc())++ root = ws.workspace_root()+ venv = tmp_path / "venv"++ # First sync: fresh root -> seeded from the COMMITTED lock.+ ws.lock_and_sync([plug_a], [], venv_dir=venv)+ assert (root / "uv.lock").read_bytes() == b"committed-bytes\n"++ # Changed surface (new member), root's own EXTENDED lock present ->+ # the current extended resolution is the seed, not the committed one.+ (root / "uv.lock").write_bytes(b"extended-bytes\n")+ plug_b = layout[0] / "home" / "plugins" / "plug-b"+ plug_b.mkdir(parents=True)+ (plug_b / "pyproject.toml").write_text("[project]\n", encoding="utf-8")+ ws.lock_and_sync([plug_a, plug_b], [], venv_dir=venv)+ assert (root / "uv.lock").read_bytes() == b"extended-bytes\n"++ # Parent-supplied seed_lock wins over both.+ other = tmp_path / "parent-extended.lock"+ other.write_bytes(b"parent-bytes\n")+ plug_c = layout[0] / "home" / "plugins" / "plug-c"+ plug_c.mkdir(parents=True)+ (plug_c / "pyproject.toml").write_text("[project]\n", encoding="utf-8")+ ws.lock_and_sync([plug_a, plug_b, plug_c], [], venv_dir=venv, seed_lock=other)+ assert (root / "uv.lock").read_bytes() == b"parent-bytes\n"++ # Shipped core lock untouched throughout.+ assert (core / "uv.lock").read_bytes() == b"committed-bytes\n"diff --git a/tests/pm/test_workspace_build_inputs.py b/tests/pm/test_workspace_build_inputs.pynew file mode 100644index 00000000000..d2dee5010ac--- /dev/null+++ b/tests/pm/test_workspace_build_inputs.py@@ -0,0 +1,141 @@+"""Workspace generation carries the source inputs of a buildable core."""+import importlib+import json+from pathlib import Path+import shutil+import subprocess+import sys++import pytest++from pm import workspace+++def test_real_build_inputs_stay_in_generated_root(tmp_path, monkeypatch):+ core = tmp_path / "core"+ core.mkdir()+ (core / "pyproject.toml").write_text(+ '[project]\nname="buildable-core"\nversion="1.0"\nreadme="README.md"\n'+ 'requires-python=">=3.11"\nlicense="MIT"\nlicense-files=["LICENSE"]\n'+ '[build-system]\nrequires=["setuptools==83.0.0","wheel==0.46.3"]\n'+ 'build-backend="setuptools.build_meta"\n'+ '[tool.setuptools.packages.find]\ninclude=["buildable_core", "buildable_core.*"]\n', encoding="utf-8",+ )+ (core / "README.md").write_text("# Real core\n")+ (core / "LICENSE").write_text("MIT\n")+ package = core / "buildable_core"+ package.mkdir()+ (package / "__init__.py").write_text("VALUE = 'from actual source'\n")+ (core / ".env").write_text("must not copy")+ monkeypatch.setattr(workspace.paths, "repo_root", lambda: core)+ root, venv = tmp_path / "staging", tmp_path / "venv"+ uv = shutil.which("uv")+ assert uv is not None+ monkeypatch.setattr(workspace, "_uv_binary", lambda: uv)+ workspace.lock_and_sync([], [], root=root, venv_dir=venv)+ python = venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+ probe = subprocess.run([str(python), "-c", "import buildable_core; print(buildable_core.VALUE)"],+ cwd=tmp_path, text=True, capture_output=True, check=True, timeout=30)+ assert probe.stdout.strip() == "from actual source"+ assert not (root / ".env").exists()+ assert not list(core.glob("*.egg-info")), "build must not write into the original core"+ assert not (core / "uv.lock").exists()+++def test_source_refresh_does_not_need_metadata_change_and_refuses_live_root(tmp_path, monkeypatch):+ core = tmp_path / "core"+ core.mkdir()+ (core / "pyproject.toml").write_text('[project]\nname="x"\nversion="1"\n')+ (core / "code.py").write_text("VALUE = 1\n")+ monkeypatch.setattr(workspace.paths, "repo_root", lambda: core)+ staged = tmp_path / "staged"+ workspace.build_root([], root=staged)+ (core / "code.py").write_text("VALUE = 2\n")+ workspace.build_root([], root=staged)+ assert (staged / "code.py").read_text() == "VALUE = 2\n"+ before = (core / "code.py").read_bytes()+ with pytest.raises(workspace.InstallError, match="source"):+ workspace.build_root([], root=core)+ assert (core / "code.py").read_bytes() == before+++def test_legacy_member_is_generated_only_inside_workspace(tmp_path, monkeypatch):+ import tomllib+ core, plugin = tmp_path / "core", tmp_path / "readonly-plugin"+ core.mkdir(); plugin.mkdir()+ (core / "pyproject.toml").write_text('[project]\nname="core"\nversion="1"\n')+ manifest = plugin / "plugin.yaml"+ manifest.write_text('name: legacy\npython_dependencies: ["example>=1,<2"]\n')+ monkeypatch.setattr(workspace.paths, "repo_root", lambda: core)+ stamp = workspace.members_stamp([plugin])+ generated = workspace.build_root([plugin], tmp_path / "stage")+ metadata = tomllib.loads((generated / "pyproject.toml").read_text())+ member = (generated / metadata["tool"]["uv"]["workspace"]["members"][0]).resolve()+ assert member.is_relative_to(generated)+ assert not (plugin / "pyproject.toml").exists()+ assert tomllib.loads((member / "pyproject.toml").read_text())["project"]["dependencies"] == ["example>=1,<2"]+ manifest.write_text('name: legacy\npython_dependencies: ["example>=2,<3"]\n')+ assert workspace.members_stamp([plugin]) != stamp+++def _wheel(directory, name, version, requirements=()):+ import zipfile++ metadata = f"{name}-{version}.dist-info"+ entries = {+ f"{name}/__init__.py": f"__version__ = {version!r}\n",+ f"{metadata}/METADATA": f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"+ + "".join(f"Requires-Dist: {requirement}\n" for requirement in requirements),+ f"{metadata}/WHEEL": "Wheel-Version: 1.0\nGenerator: fixture\nRoot-Is-Purelib: true\nTag: py3-none-any\n",+ }+ entries[f"{metadata}/RECORD"] = "".join(f"{path},,\n" for path in entries)+ with zipfile.ZipFile(directory / f"{name}-{version}-py3-none-any.whl", "w") as archive:+ for path, body in entries.items():+ archive.writestr(path, body)++[email protected]("exact", [False, True])+def test_plugin_can_move_compatible_transitive_but_not_exact_requirement(tmp_path, monkeypatch, exact):+ import os+ import tomllib++ core = tmp_path / "core"+ core.mkdir()+ wheels = tmp_path / "wheels"+ wheels.mkdir()+ _wheel(wheels, "pkga", "1.0", ["pkgb>=1.2,<2"])+ _wheel(wheels, "pkgb", "1.2")+ core_requirement = '["pkga==1.0", "pkgb==1.2"]' if exact else '["pkga==1.0"]'+ (core / "pyproject.toml").write_text(+ '[project]\nname="core-proof"\nversion="1"\nrequires-python=">=3.11"\n'+ f'dependencies={core_requirement}\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+ monkeypatch.setattr(workspace.paths, "repo_root", lambda: core)+ monkeypatch.setattr(workspace, "_uv_binary", lambda: uv)+ baseline, first_env = tmp_path / "baseline", tmp_path / "first-env"+ workspace.lock_and_sync([], [], root=baseline, venv_dir=first_env)+ first_lock = (baseline / "uv.lock").read_bytes()+ assert next(p["version"] for p in tomllib.loads(first_lock.decode())["package"] if p["name"] == "pkgb") == "1.2"+ _wheel(wheels, "pkgb", "1.3")+ plugin = tmp_path / "plugin"+ plugin.mkdir()+ (plugin / "pyproject.toml").write_text(+ '[project]\nname="plugin-proof"\nversion="1"\nrequires-python=">=3.11"\ndependencies=["pkgb==1.3"]\n',+ encoding="utf-8",+ )+ extended, candidate = tmp_path / "extended", tmp_path / "candidate"+ if exact:+ with pytest.raises(workspace.ResolutionConflict):+ workspace.lock_and_sync([plugin], [], root=extended, venv_dir=candidate, seed_lock=baseline / "uv.lock")+ else:+ workspace.lock_and_sync([plugin], [], root=extended, venv_dir=candidate, seed_lock=baseline / "uv.lock")+ installed = tomllib.loads((extended / "uv.lock").read_text(encoding="utf-8"))["package"]+ assert next(p["version"] for p in installed if p["name"] == "pkgb") == "1.3"+ python = candidate / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ result = subprocess.run([str(python), "-c", "import pkga, pkgb; print(pkga.__version__, pkgb.__version__)"],+ capture_output=True, text=True, check=True, timeout=30)+ assert result.stdout.strip() == "1.0 1.3"+ assert (baseline / "uv.lock").read_bytes() == first_lockdiff --git a/tests/run_agent/test_in_place_persist_marker_98450.py b/tests/run_agent/test_in_place_persist_marker_98450.pyindex e86bdd60550..bee77c6a897 100644--- a/tests/run_agent/test_in_place_persist_marker_98450.py+++ b/tests/run_agent/test_in_place_persist_marker_98450.py@@ -17,6 +17,7 @@ stamps after its ``archive_and_compact`` call; both now share"""import os+from contextlib import closingimport tempfilefrom pathlib import Pathfrom unittest.mock import patch@@ -83,8 +84,7 @@ class TestInPlaceCommitPersistMarker:from agent.conversation_compression import compress_contextfrom agent.context_compressor import _DB_PERSISTED_MARKER- with tempfile.TemporaryDirectory() as tmp:- db = SessionDB(db_path=Path(tmp) / "t.db")+ with tempfile.TemporaryDirectory() as tmp, closing(SessionDB(db_path=Path(tmp) / "t.db")) as db:sid = "20260830_120000_marker"_seed(db, sid, n=8)agent = _make_agent(db, sid)@@ -150,8 +150,7 @@ class TestInPlaceCommitPersistMarker:_DB_PERSISTED_MARKER,)- with tempfile.TemporaryDirectory() as tmp:- db = SessionDB(db_path=Path(tmp) / "m.db")+ with tempfile.TemporaryDirectory() as tmp, closing(SessionDB(db_path=Path(tmp) / "m.db")) as db:sid = "20260830_120001_micro0"_seed(db, sid, n=4)compressor = ContextCompressor.__new__(ContextCompressor)diff --git a/tests/scripts/test_compat_inventory.py b/tests/scripts/test_compat_inventory.pynew file mode 100644index 00000000000..1b264c29cd8--- /dev/null+++ b/tests/scripts/test_compat_inventory.py@@ -0,0 +1,23 @@+"""The migration check prunes excluded trees before traversing them."""+from scripts import check_compat_pointers as checker+++def test_inventory_does_not_descend_into_excluded_trees(tmp_path, monkeypatch):+ included = tmp_path / "hermes_cli"+ included.mkdir()+ (included / "entry.py").touch()+ nested = included / "node_modules"+ nested.mkdir()+ (nested / "not_source.py").touch()+ real_walk = checker.os.walk+ visited = []++ def walk(*args, **kwargs):+ for directory, dirs, files in real_walk(*args, **kwargs):+ visited.append(directory)+ yield directory, dirs, files++ monkeypatch.setattr(checker, "ROOT", tmp_path)+ monkeypatch.setattr(checker.os, "walk", walk)+ assert list(checker._py_files()) == [included / "entry.py"]+ assert str(nested) not in visiteddiff --git a/tests/scripts/test_contributor_map.py b/tests/scripts/test_contributor_map.pyindex b6082ccfe5d..61a05d1fee7 100644--- a/tests/scripts/test_contributor_map.py+++ b/tests/scripts/test_contributor_map.py@@ -157,7 +157,8 @@ def test_add_contributor_refuses_a_case_collision(tmp_path, monkeypatch):monkeypatch.setattr(mod, "EMAILS_DIR", d)assert mod.add_contributor("[email protected]", "otherperson") == 1- assert not (d / "[email protected]").exists()+ assert [p.name for p in d.iterdir()] == ["[email protected]"]+ assert (d / "[email protected]").read_text() == "someone\n"def test_add_contributor_refuses_case_collision_even_for_same_login(emails_dir, capsys):diff --git a/tests/scripts/test_desktop_cli_wrapper.py b/tests/scripts/test_desktop_cli_wrapper.pyindex 795b7960385..f85237910da 100644--- a/tests/scripts/test_desktop_cli_wrapper.py+++ b/tests/scripts/test_desktop_cli_wrapper.py@@ -163,7 +163,7 @@ def _render(tmp_path: Path) -> Path:return out[email protected](sys.platform != "win32", reason="minted launchers only exist on win32 payloads")[email protected]("windows")def test_rendered_wrapper_dispatches_to_the_entry_module(tmp_path):"""The full wrapper contract without distlib: a rendered copy placed inbin/ next to a stub repo + venv resolves its own dir from sys.argv[0],@@ -173,8 +173,10 @@ def test_rendered_wrapper_dispatches_to_the_entry_module(tmp_path):(bin_dir / ".." / "repo" / "hermes_cli").mkdir(parents=True, exist_ok=True)(bin_dir / ".." / "venv" / "Lib" / "site-packages").mkdir(parents=True, exist_ok=True)(bin_dir / ".." / "repo" / "hermes_cli" / "__init__.py").write_text("")+ (bin_dir / ".." / "repo" / "hermes_bootstrap.py").write_text("READY = True\n")(bin_dir / ".." / "repo" / "hermes_cli" / "main.py").write_text("import sys\n"+ "assert sys.modules['hermes_bootstrap'].READY\n""def main():\n"" assert sys.argv[0].endswith('hermes.exe'), sys.argv[0]\n"" assert sys.argv[1:] == ['--version']\n"diff --git a/tests/scripts/test_release_canary.py b/tests/scripts/test_release_canary.pyindex 48e2e883860..4457b23e730 100644--- a/tests/scripts/test_release_canary.py+++ b/tests/scripts/test_release_canary.py@@ -116,7 +116,7 @@ class TestCanaryBuildNumberGuards:monkeypatch.setattr(subprocess, "run", fake_run)monkeypatch.delenv("GITHUB_OUTPUT", raising=False)- release.cmd_canary(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))+ release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))assert calls == [], "same-minute same-line re-cut must not create a release"def test_same_minute_new_line_allowed(self, monkeypatch, tmp_path):@@ -147,7 +147,7 @@ class TestCanaryBuildNumberGuards:monkeypatch.setattr(subprocess, "run", fake_run)monkeypatch.delenv("GITHUB_OUTPUT", raising=False)- release.cmd_canary(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))+ release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))create = [c for c in captured if c[:3] == ["gh", "release", "create"]]assert len(create) == 1, captured@@ -170,7 +170,7 @@ class TestCanaryBuildNumberGuards:monkeypatch.delenv("GITHUB_OUTPUT", raising=False)with pytest.raises(SystemExit) as exc:- release.cmd_canary(SimpleNamespace(date="20260829000000", publish=True, remote="origin"))+ release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260829000000", publish=True, remote="origin"))assert exc.value.code == 1@@ -213,7 +213,7 @@ class TestCanaryIsDrafted:monkeypatch.setattr(subprocess, "run", fake_run)monkeypatch.delenv("GITHUB_OUTPUT", raising=False)- release.cmd_canary(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))+ release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))return next(c for c in captured if c[:3] == ["gh", "release", "create"])def test_created_as_a_draft_prerelease(self, monkeypatch, tmp_path):@@ -264,7 +264,7 @@ class TestCanaryStartsItsOwnBuild:monkeypatch.setattr(subprocess, "run", fake_run)monkeypatch.delenv("GITHUB_OUTPUT", raising=False)- release.cmd_canary(SimpleNamespace(date="20260818103000", publish=True, remote="origin"))+ release.cmd_canary(SimpleNamespace(no_changelog=True, date="20260818103000", publish=True, remote="origin"))return captureddef test_dispatches_the_build_for_the_tag_it_cut(self, monkeypatch, tmp_path):diff --git a/tests/security/test_gitspawn_config_injection.py b/tests/security/test_gitspawn_config_injection.pyindex bd212f9e3cb..7e591931462 100644--- a/tests/security/test_gitspawn_config_injection.py+++ b/tests/security/test_gitspawn_config_injection.py@@ -102,12 +102,18 @@ def _make_malicious_repo(tmp: Path) -> tuple[Path, Path]:hooks = repo / "evil-hooks"hooks.mkdir()hook = hooks / "post-checkout"- hook.write_text(f"#!/bin/sh\ntouch {marker}.hook\n")+ marker_shell = marker.as_posix()+ hook.write_text(f"#!/bin/sh\ntouch '{marker_shell}.hook'\n")hook.chmod(0o755)- with (repo / ".git" / "config").open("a") as f:- f.write(f'[core]\n\tfsmonitor = "touch {marker}.fsmonitor"\n\thooksPath = {hooks}\n')- f.write(f'[diff "evil"]\n\tcommand = "touch {marker}.extdiff"\n')- f.write(f'\ttextconv = "sh -c \'touch {marker}.textconv; cat\'"\n')+ # Let git encode config values; raw Windows backslashes are escapes.+ settings = {+ "core.fsmonitor": f"touch '{marker_shell}.fsmonitor'",+ "core.hooksPath": hooks.as_posix(),+ "diff.evil.command": f"touch '{marker_shell}.extdiff'",+ "diff.evil.textconv": f"touch '{marker_shell}.textconv'; cat",+ }+ for key, value in settings.items():+ subprocess.run(["git", "-C", str(repo), "config", key, value], check=True, env=clean)(repo / ".gitattributes").write_text("* diff=evil\n")(repo / "README").write_text("changed\n") # dirty working tree so diffs runreturn repo, markerdiff --git a/tests/state/test_state_db_holders.py b/tests/state/test_state_db_holders.pyindex 4fb5c24f383..d48231d726d 100644--- a/tests/state/test_state_db_holders.py+++ b/tests/state/test_state_db_holders.py@@ -7,7 +7,7 @@ import pytestimport hermes_state_holders[email protected]_only[email protected]("linux")def test_foreign_holder_accepts_same_inode_reached_through_an_alias(tmp_path, monkeypatch):diff --git a/tests/test_compat_manifest_targets.py b/tests/test_compat_manifest_targets.pyindex 461636586e2..6b2b31ab27a 100644--- a/tests/test_compat_manifest_targets.py+++ b/tests/test_compat_manifest_targets.py@@ -12,6 +12,7 @@ import importlibimport jsonimport pkgutilimport sqlite3+import sysfrom pathlib import Pathimport pytest@@ -52,6 +53,8 @@ def test_moved_lazy_pointers_resolve_to_the_split_off_siblings_object():bad = []for e in _entries():facade, name = e["facade"], e["name"]+ if sys.platform == "win32" and e["target"] == "hermes_cli.pty_bridge":+ continue # POSIX PTYs; Windows uses ConPTY, not this external bridgesibs = _sibling_modules(facade)if not sibs:continue@@ -60,11 +63,17 @@ def test_moved_lazy_pointers_resolve_to_the_split_off_siblings_object():except Exception as exc: # unresolvable pointer is its own failurebad.append((facade, name, f"unresolvable: {exc!r}"))continue+ # Importing siblings may reload a lazy provider module. Resolve the+ # facade again after imports before comparing the current objects.+ modules = []for s in sibs:try:mod = importlib.import_module(s)except Exception:continue+ modules.append((s, mod))+ got = getattr(importlib.import_module(facade), name)+ for s, mod in modules:if name in vars(mod):sib_obj = vars(mod)[name]same = (sib_obj == got) if isinstance(got, (int, float, str, bytes, bool, type(None))) else (sib_obj is got)@@ -89,4 +98,8 @@ def test_kanban_db_connect_opens_a_kanban_board(tmp_path, monkeypatch):conn.close()assert "tasks" in tables, tablesassert not (tmp_path / "projects.db").exists()- assert isinstance(sqlite3.connect(db), sqlite3.Connection)+ conn = sqlite3.connect(db)+ try:+ assert isinstance(conn, sqlite3.Connection)+ finally:+ conn.close()diff --git a/tests/test_hermes_logging.py b/tests/test_hermes_logging.pyindex 070cf65dc75..0188accbc67 100644--- a/tests/test_hermes_logging.py+++ b/tests/test_hermes_logging.py@@ -138,9 +138,8 @@ class TestSetupLogging:assert "profile-routed cron record" in (profile_home / "logs" / "agent.log").read_text()- assert "profile-routed cron record" not in (- hermes_home / "logs" / "agent.log"- ).read_text()+ default_log = hermes_home / "logs" / "agent.log"+ assert not default_log.exists() or "profile-routed cron record" not in default_log.read_text()diff --git a/tests/test_install_clone_throttle_fallback.py b/tests/test_install_clone_throttle_fallback.pyindex cb476889328..71aff2e78be 100644--- a/tests/test_install_clone_throttle_fallback.py+++ b/tests/test_install_clone_throttle_fallback.py@@ -1,135 +1,51 @@-"""Fresh-install clone throttle handling (#89624).--GitHub throttles packfile generation for this repo with repo-scoped HTTP-429s (not client IP limits): the single big pack behind `--depth 1` dies-mid-transfer with "RPC failed; HTTP 429 / expected 'packfile'", and-clone_repo's HTTPS branch had no retry and no fallback — a fresh install-on an ordinary unauthenticated machine exited 1 at the download stage-(same throttle as the update path in #89287).--The contract pinned here:-- The HTTPS clone is retried with backoff before giving up.-- A failed direct attempt is retried after removing the partial clone.-- When every direct attempt fails, the installer degrades to a blobless- partial clone (`--filter=blob:none --no-checkout`) and materializes the- working tree with `git reset --hard HEAD` — the clone itself is- commits+trees only (small, passes the throttle) and the reset becomes- the separate blob fetch the retry can wrap (review of #89629: without- --no-checkout the blob fetch runs inside `git clone`'s own checkout,- so the throttle kills the whole clone and the fallback degrades to one- more failed clone).-- Materialization fails closed: both reset attempts failing must remove- the checkout and report a clone failure, never report success over an- unusable tree.-"""--from __future__ import annotations--import re-import shutil+"""A throttled clone is retried without publishing a partial checkout."""+import osfrom pathlib import Path+import shlex+import subprocessimport pytest-REPO_ROOT = Path(__file__).resolve().parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--pytestmark = pytest.mark.skipif(- shutil.which("git") is None or shutil.which("bash") is None,- reason="needs git and bash",-)---def _https_branch() -> str:- text = INSTALL_SH.read_text()- m = re.search(- r"log_info \"SSH failed, trying HTTPS\.\.\..*?(?=\n fi\n)",- text,- re.DOTALL,- )- assert m is not None, "HTTPS clone branch not found in install.sh"- return m.group(0)---def test_https_clone_is_retried_with_backoff():- branch = _https_branch()- assert re.search(r"for attempt in \$\(seq 1 \"\$max_attempts\"\)", branch), (- "the HTTPS clone must be retried a bounded number of times, with the "- "loop bound driven by the same variable the messages report"- )- assert re.search(r"sleep \$\(\(attempt \* 5\)\)", branch), (- "retries must back off between attempts"- )- # A failed direct attempt leaves a partial clone; it must be removed- # before the next attempt or git refuses to clone into a non-empty dir.- assert re.search(- r"rm -rf \"\$INSTALL_DIR\" 2>/dev/null # partial clone is unusable",- branch,- ), "each failed direct attempt must clean up the partial clone"---def test_blobless_partial_clone_fallback_exists():- branch = _https_branch()- assert "--filter=blob:none" in branch, (- "after direct attempts fail, degrade to a blobless partial clone "- "(many small packs — what gets past the repo-scoped 429)"- )- assert re.search(- r"git clone --depth 1 --single-branch --filter=blob:none \\\n"- r"\s*--no-checkout --branch \"\$BRANCH\"",- branch,- ), (- "the partial clone must defer the checkout (--no-checkout): the blob "- "fetch otherwise runs inside git clone's own checkout step, the "- "throttle kills the whole clone, and the fallback never engages"- )- assert re.search(r"git reset --hard HEAD", branch), (- "the partial clone's working tree must be materialized so the rest "- "of the installer sees the normal files"- )---def test_materialization_fails_closed():- """A failed blob materialization must not report a successful clone.-- The reset on a --no-checkout clone is the step that fetches the blobs,- so it is the step most likely to be throttled. `|| true` plus an- unconditional `clone_ok=true` would hand the rest of the installer a- half-materialized tree while printing "Cloned via HTTPS".- """- branch = _https_branch()- fallback = branch.split('log_info "Direct clone throttled')[1]- assert "|| true" not in fallback, (- "the materialization retry must not swallow a hard failure"- )- m = re.search(- r"if \(cd \"\$INSTALL_DIR\" \\\n"- r"\s*&& \(git reset --hard HEAD",- fallback,- )- assert m is not None, (- "the reset must be guarded: its success is the condition that sets "- "clone_ok, and a failed reset must clean up the checkout"- )---def test_partial_clone_failure_still_cleans_up_and_exits():- branch = _https_branch()- m = re.search(- r'if \[ "\$clone_ok" = true \]; then\n\s*log_success "Cloned via HTTPS"'- r"\n\s*else\n\s*log_error \"Failed to clone repository\"\n\s*exit 1",- branch,- )- assert m is not None, (- "when the fallback also fails the installer must still report the "- "failure and exit 1"- )---def test_fallback_runs_only_after_all_direct_attempts_fail():- branch = _https_branch()- direct = branch.split('log_info "Direct clone throttled')[0]- assert re.search(r"clone_ok != true|clone_ok\" != true", direct), (- "the blobless fallback must be gated on every direct attempt having "- "failed — a successful direct clone must never take the fallback path"- )+ROOT = Path(__file__).resolve().parents[1]++[email protected]("materialize_fails", [False, True])+def test_clone_retries_and_publishes_only_materialized_tree(tmp_path, materialize_fails):+ origin = tmp_path / "origin"+ origin.mkdir()+ def git(*args):+ return subprocess.run(["git", "-C", str(origin), *args], check=True, capture_output=True, text=True)+ git("init", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "Fixture")+ (origin / "README").write_text("complete checkout\n")+ git("add", "README")+ git("commit", "-m", "fixture")+ dest = tmp_path / "install"+ attempts = tmp_path / "attempts"+ env = dict(os.environ, HOME=tmp_path.as_posix(), HERMES_HOME=(tmp_path / "home").as_posix(),+ HERMES_INSTALL_DIR=dest.as_posix(), HERMES_REPO_URL=origin.as_posix())+ # Inject throttling at the network boundary; the fallback and checkout use real Git.+ script = f'''source {shlex.quote((ROOT / 'scripts/install.sh').as_posix())} --manifest+sleep() {{ :; }}+git() {{+ if [ "$1" = clone ]; then+ printf '%s\\n' "$*" >> {shlex.quote(attempts.as_posix())}+ case " $* " in *" --filter=blob:none "*) ;; *) return 1 ;; esac+ fi+ if [ "{int(materialize_fails)}" = 1 ] && [ "${{3:-}}" = reset ]; then return 1; fi+ command git "$@"+}}+stage_repository+'''+ result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30)+ calls = attempts.read_text().splitlines()+ assert len([x for x in calls if "--filter=blob:none" not in x]) > 1+ assert "--no-checkout" in calls[-1]+ if materialize_fails:+ assert result.returncode != 0+ assert not dest.exists()+ else:+ assert result.returncode == 0, result.stdout + result.stderr+ assert (dest / "README").read_text() == "complete checkout\n"+ assert not list(tmp_path.glob(".hermes-clone-*"))diff --git a/tests/test_install_ps1_desktop_stage.py b/tests/test_install_ps1_desktop_stage.pynew file mode 100644index 00000000000..47d6461f0b6--- /dev/null+++ b/tests/test_install_ps1_desktop_stage.py@@ -0,0 +1,289 @@+"""install.ps1 desktop stage + single authoritative stage list (audit C27).++The retained desktop stage used to call helpers deleted by the PM+consolidation (Resolve-UvCmd, Test-Node, the electron-dist recovery set) —+runtime failures under `-Stage desktop`. The stage must use the CURRENT+paths: pm's venv sync for the wake/voice extras and the product CLI+(`hermes desktop --build-only`) for the build. The $Stages table must be+the ONE list: -Manifest prints it and the no-flag ladder runs it, so+-IncludeDesktop affects the real loop exactly as the manifest advertises.+`-Stage desktop` stays directly dispatchable without the flag (the+bootstrap frontend iterates manifest stages and always pairs the flag;+standalone dispatch is the long-standing contract).++Boundary: the test generates a PowerShell wrapper that defines stub+functions (New-Object intercepting WScript.Shell, icacls, ie4uinit.exe)+and then DOT-SOURCES the real install.ps1 with -Stage desktop — the full+stage runs in one real PowerShell process against a temp home/install+dir, with every external effect either fake (compiled fake venv python)+or logged instead of written. Nothing touches the user's known folders.+If the artifact check fails, the assertion message carries the fake+python's actual logged arguments for debugging.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+from pathlib import Path++import pytest++pytestmark = pytest.mark.platforms("windows")++REPO_ROOT = Path(__file__).resolve().parents[1]+INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"++_FAKE_PY = r'''+using System;+using System.IO;++public static class FakePy {+ public static int Main(string[] args) {+ string log = Environment.GetEnvironmentVariable("FAKE_PY_LOG");+ File.AppendAllText(log, string.Join("\u0001", args) + Environment.NewLine);+ if (Array.IndexOf(args, "-c") >= 0) { return 0; }+ if (args.Length >= 2+ && args[args.Length - 2] == "desktop"+ && args[args.Length - 1] == "--build-only") {+ string dir = Path.Combine(+ Environment.GetEnvironmentVariable("FAKE_INSTALL_DIR"),+ "apps", "desktop", "release", "win-unpacked");+ Directory.CreateDirectory(dir);+ File.WriteAllText(Path.Combine(dir, "Hermes.exe"), "fake");+ }+ return 0;+ }+}+'''++# The test boundary: stub the three external-effect primitives, then run the+# REAL installer. Dot-sourcing binds -Stage desktop and exits this wrapper+# with the installer's own exit code. Functions win over external commands in+# PowerShell's name resolution, so `& icacls` / `& ie4uinit.exe` hit the+# stubs; other New-Object callers go through the module-qualified real one.+_WRAPPER = r'''+param(+ [Parameter(Mandatory = $true)][string]$InstallerPath,+ [Parameter(Mandatory = $true)][string]$HermesHome,+ [Parameter(Mandatory = $true)][string]$InstallDir+)+$ErrorActionPreference = "Stop"++function New-StubShortcut {+ $sc = [pscustomobject]@{+ TargetPath = ""+ WorkingDirectory = ""+ IconLocation = ""+ Description = ""+ }+ $sc | Add-Member -MemberType ScriptMethod -Name Save -Value {+ Add-Content -Path $env:WSH_LOG `+ -Value "SAVED:$($this.TargetPath)|$($this.WorkingDirectory)|$($this.IconLocation)"+ }+ return $sc+}++function New-StubShell {+ $shell = [pscustomobject]@{}+ $shell | Add-Member -MemberType ScriptMethod -Name CreateShortcut -Value {+ return New-StubShortcut+ }+ return $shell+}++function New-Object {+ param([string]$ComObject, [string]$TypeName, [object[]]$ArgumentList)+ if ($ComObject -eq "WScript.Shell") {+ return New-StubShell+ }+ if ($TypeName) {+ return Microsoft.PowerShell.Utility\New-Object -TypeName $TypeName -ArgumentList $ArgumentList+ }+ return Microsoft.PowerShell.Utility\New-Object -ComObject $ComObject -ArgumentList $ArgumentList+}++function New-Item {+ param([string]$ItemType, [switch]$Force, [string]$Path)+ if (-not [IO.Path]::GetFullPath($Path).StartsWith(+ [IO.Path]::GetFullPath($env:FAKE_INSTALL_DIR), [StringComparison]::OrdinalIgnoreCase)) {+ throw "test blocked directory creation outside temporary install: $Path"+ }+ Microsoft.PowerShell.Management\New-Item -ItemType $ItemType -Force:$Force -Path $Path+}++function icacls {+ Add-Content -Path $env:ICACLS_LOG -Value ("icacls " + ($args -join " "))+ $global:LASTEXITCODE = 0+}++function ie4uinit.exe {+ Add-Content -Path $env:ICACLS_LOG -Value ("ie4uinit.exe " + ($args -join " "))+ $global:LASTEXITCODE = 0+}++. $InstallerPath -Stage desktop -Json -HermesHome $HermesHome -InstallDir $InstallDir+exit $LASTEXITCODE+'''+++def _compile_fake_python(powershell: str, output: Path) -> None:+ source = output.with_suffix(".cs")+ source.write_text(_FAKE_PY, encoding="utf-8")+ compile_script = output.with_name("compile-fake-py.ps1")+ compile_script.write_text(+ "param([string]$Source, [string]$Output)\n"+ "Add-Type -Path $Source -OutputAssembly $Output "+ "-OutputType ConsoleApplication\n",+ encoding="utf-8",+ )+ subprocess.run(+ [powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",+ "-File", str(compile_script), "-Source", str(source), "-Output", str(output)],+ check=True, capture_output=True, text=True, timeout=120,+ stdin=subprocess.DEVNULL,+ )+++def _run(powershell: str, tmp_path: Path, args: list[str], env: dict[str, str] | None = None):+ return subprocess.run(+ [powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",+ "-File", str(INSTALL_PS1), *args,+ "-HermesHome", str(tmp_path / "hermes-home"),+ "-InstallDir", str(tmp_path / "install")],+ cwd=tmp_path,+ env=env,+ stdin=subprocess.DEVNULL,+ capture_output=True,+ text=True,+ check=False,+ timeout=180,+ )+++def _manifest_stages(run) -> list[str]:+ assert run.returncode == 0, run.stdout + run.stderr+ return [s["name"] for s in json.loads(run.stdout)["stages"]]+++def test_manifest_without_flag_lists_no_desktop(tmp_path: Path) -> None:+ powershell = shutil.which("powershell")+ if not powershell:+ pytest.skip("Windows PowerShell is required")+ assert "desktop" not in _manifest_stages(_run(powershell, tmp_path, ["-Manifest"]))+++def test_manifest_with_include_desktop_orders_desktop_before_complete(tmp_path: Path) -> None:+ powershell = shutil.which("powershell")+ if not powershell:+ pytest.skip("Windows PowerShell is required")+ names = _manifest_stages(_run(powershell, tmp_path, ["-Manifest", "-IncludeDesktop"]))+ assert names.index("desktop") < names.index("complete")+ assert names[-1] == "complete"+++def test_unknown_stage_is_rejected(tmp_path: Path) -> None:+ powershell = shutil.which("powershell")+ if not powershell:+ pytest.skip("Windows PowerShell is required")+ run = _run(powershell, tmp_path, ["-Stage", "bogus", "-Json"])+ assert run.returncode == 2+ frame = json.loads(run.stdout.splitlines()[-1])+ assert frame["ok"] is False and frame["stage"] == "bogus"+++def test_complete_stage_writes_pinned_install_marker(tmp_path: Path) -> None:+ powershell = shutil.which("powershell")+ if not powershell:+ pytest.skip("Windows PowerShell is required")+ install = tmp_path / "install"+ install.mkdir()+ commit = "a" * 40+ run = _run(powershell, tmp_path, ["-Stage", "complete", "-Commit", commit, "-Json"])+ assert run.returncode == 0, run.stdout + run.stderr+ assert json.loads(run.stdout.splitlines()[-1])["ok"] is True+ marker = json.loads((install / ".hermes-bootstrap-complete").read_text(encoding="utf-8-sig"))+ assert marker["pinnedCommit"] == commit+ assert marker["pinnedBranch"] == "main"+++def test_desktop_stage_uses_pm_sync_and_product_cli(tmp_path: Path) -> None:+ """-Stage desktop (without -IncludeDesktop — the standalone contract)+ runs the CURRENT paths: pm's venv sync for wake/voice, then+ `hermes desktop --build-only` through the venv python; the produced+ artifact is probed, ACL-granted, and shortcut-ed — with icacls,+ ie4uinit.exe, and WScript.Shell intercepted in the wrapper boundary so+ nothing outside the temp dirs is touched."""+ powershell = shutil.which("powershell")+ if not powershell:+ pytest.skip("Windows PowerShell is required")++ install_dir = tmp_path / "install"+ scripts = install_dir / "venv" / "Scripts"+ scripts.mkdir(parents=True)+ py_log = tmp_path / "fake-python.log"+ wsh_log = tmp_path / "wsh.log"+ icacls_log = tmp_path / "icacls.log"+ fake_python = scripts / "python.exe"+ _compile_fake_python(powershell, fake_python)++ (install_dir / "hermes").write_text("# python entry shim\n", encoding="ascii")++ wrapper = tmp_path / "boundary-wrapper.ps1"+ wrapper.write_text(_WRAPPER, encoding="utf-8-sig")+ env = {+ **os.environ,+ "PATHEXT": ";".join(dict.fromkeys([*os.environ.get("PATHEXT", "").split(";"), ".EXE"])),+ "FAKE_PY_LOG": str(py_log),+ "FAKE_INSTALL_DIR": str(install_dir),+ "WSH_LOG": str(wsh_log),+ "ICACLS_LOG": str(icacls_log),+ }+ run = subprocess.run(+ [powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",+ "-File", str(wrapper),+ "-InstallerPath", str(INSTALL_PS1),+ "-HermesHome", str(tmp_path / "hermes-home"),+ "-InstallDir", str(install_dir)],+ cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, check=False, timeout=180,+ )++ calls = [l.split("\u0001") for l in py_log.read_text().splitlines()] if py_log.exists() else "NO LOG"+ assert run.returncode == 0, f"{run.stdout}{run.stderr}\nFAKE LOG:\n{calls}"+ frame = json.loads(run.stdout.splitlines()[-1])+ assert frame["ok"] is True and frame["stage"] == "desktop"++ assert isinstance(calls, list)+ # 1. wake/voice extras via pm's venv sync (the pm-owned path).+ assert any(+ len(c) >= 2 and c[0] == "-c" and "sync_venv" in c[1]+ and "'wake'" in c[1] and "'voice'" in c[1] and "explicit=True" in c[1]+ for c in calls+ ), calls+ # 2. the build through the parsed product CLI (never a `build` subcommand+ # or any deleted helper).+ assert any(c[-2:] == ["desktop", "--build-only"] for c in calls), calls+ # 3. the stage probed the artifact the fake build produced.+ exe = install_dir / "apps" / "desktop" / "release" / "win-unpacked" / "Hermes.exe"+ assert exe.is_file(), calls+ # 4. ACL grant hit the intercepted icacls with the produced exe's dir.+ icacls_lines = icacls_log.read_text().splitlines()+ assert any(+ line.startswith("icacls ") and str(exe.parent) in line+ and "*S-1-15-2-2:(OI)(CI)(RX)" in line+ for line in icacls_lines+ ), icacls_lines+ # 5. icon-cache bust hit the intercepted ie4uinit.exe stub.+ assert any(line.startswith("ie4uinit.exe") for line in icacls_lines), icacls_lines+ # 6. shortcut creation went through the intercepted WScript.Shell stub:+ # logged, pointing at the produced exe, and NOT written to any real+ # known folder.+ shortcuts = wsh_log.read_text().splitlines()+ assert len(shortcuts) == 2, shortcuts+ for line in shortcuts:+ assert line.startswith("SAVED:"), shortcuts+ target = line.split("|")[0][len("SAVED:"):]+ assert target == str(exe), shortcutsdiff --git a/tests/test_install_ps1_managed_python_provenance.py b/tests/test_install_ps1_managed_python_provenance.pyindex 34eeca5737f..0a8d297c81d 100644--- a/tests/test_install_ps1_managed_python_provenance.py+++ b/tests/test_install_ps1_managed_python_provenance.py@@ -1,7 +1,4 @@-"""Behavioral regression for Hermes-managed Python provenance on Windows."""--from __future__ import annotations-+"""Installer delegates dependency selection to the pinned PM bootstrap."""import jsonimport osfrom pathlib import Path@@ -10,260 +7,42 @@ import subprocessimport pytest-from tests.install_ps1_fake_uv import compile_fake_uv--pytestmark = pytest.mark.platforms("windows")--_INSTALL_PS1 = Path(__file__).resolve().parents[1] / "scripts" / "install.ps1"---def test_fresh_install_manifest_orders_repo_before_checkout_scoped_python(- tmp_path: Path,-) -> None:- powershell = shutil.which("powershell")- if not powershell:- pytest.skip("Windows PowerShell is required")-- install_dir = tmp_path / "install"- run = subprocess.run(- [- powershell,- "-NoProfile",- "-ExecutionPolicy",- "Bypass",- "-File",- str(_INSTALL_PS1),- "-Manifest",- "-HermesHome",- str(tmp_path / "hermes-home"),- "-InstallDir",- str(install_dir),- ],- cwd=tmp_path,- capture_output=True,- text=True,- check=False,- timeout=45,- )-- assert run.returncode == 0, run.stdout + run.stderr- manifest = json.loads(run.stdout)- stages = [stage["name"] for stage in manifest["stages"]]- assert (- stages.index("repository")- < stages.index("python")- < stages.index("venv")- )- assert not install_dir.exists(), "manifest lookup must remain read-only"---def _run_venv_stage(- powershell: str,- tmp_path: Path,- hermes_home: Path,- install_dir: Path,- env: dict[str, str],-) -> subprocess.CompletedProcess[str]:- return subprocess.run(- [- powershell,- "-NoProfile",- "-ExecutionPolicy",- "Bypass",- "-File",- str(_INSTALL_PS1),- "-Stage",- "venv",- "-HermesHome",- str(hermes_home),- "-InstallDir",- str(install_dir),- ],- cwd=tmp_path,- env=env,- capture_output=True,- text=True,- check=False,- timeout=45,- )---def test_venv_stage_rejects_third_party_python_and_uses_managed_path(- tmp_path: Path,-) -> None:- powershell = shutil.which("powershell")- if not powershell:- pytest.skip("Windows PowerShell is required")-- hermes_home = tmp_path / "hermes-home"- install_dir = tmp_path / "install"- managed_root = install_dir / ".hermes-runtime" / "python"- managed_python = managed_root / "cpython-3.11" / "python.exe"- third_party = tmp_path / "KiCad" / "bin" / "python.exe"- log = tmp_path / "uv.log"- uv = hermes_home / "bin" / "uv.exe"- uv.parent.mkdir(parents=True)- install_dir.mkdir()- managed_python.parent.mkdir(parents=True)- third_party.parent.mkdir(parents=True)- third_party.write_text("fake", encoding="ascii")- compile_fake_uv(powershell, uv)- shutil.copy2(uv, managed_python)-- env = {- **os.environ,- "FAKE_UV_LOG": str(log),- "FAKE_MANAGED_PYTHON": str(managed_python),- "FAKE_THIRD_PARTY_PYTHON": str(third_party),- "UV_PYTHON": str(third_party),- "UV_NO_MANAGED_PYTHON": "1",- "UV_SYSTEM_PYTHON": "1",- }- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)- installer_stdout = run.stdout- installer_stderr = run.stderr- frames = [- json.loads(line) for line in installer_stdout.splitlines() if line.startswith("{")- ]- assert run.returncode == 0, installer_stdout + installer_stderr- assert frames[-1]["ok"] is True- commands = log.read_text(encoding="utf-8").splitlines()- assert any(- command.startswith("python find 3.11") and "--managed-python" in command- for command in commands- )- venv_command = next(command for command in commands if command.startswith("venv venv"))- assert f"--python {managed_python}" in venv_command- assert "--managed-python" in venv_command- assert "--no-python-downloads" in venv_command---def test_fallback_minor_is_reported_from_resolved_managed_interpreter(- tmp_path: Path,-) -> None:- powershell = shutil.which("powershell")- if not powershell:- pytest.skip("Windows PowerShell is required")-- hermes_home = tmp_path / "hermes-home"- install_dir = tmp_path / "install"- managed_python = (- install_dir / ".hermes-runtime" / "python" / "cpython-3.12" / "python.exe"- )- uv = hermes_home / "bin" / "uv.exe"- uv.parent.mkdir(parents=True)- managed_python.parent.mkdir(parents=True)- install_dir.mkdir(exist_ok=True)- compile_fake_uv(powershell, uv)- shutil.copy2(uv, managed_python)- env = {- **os.environ,- "FAKE_UV_LOG": str(tmp_path / "uv.log"),- "FAKE_MANAGED_PYTHON": str(managed_python),- "FAKE_MANAGED_PYTHON_VERSION": "3.12",- "FAKE_PYTHON_VERSION": "Python 3.12.13",- }-- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)-- assert run.returncode == 0, run.stdout + run.stderr- assert "Creating virtual environment with Python 3.12" in run.stdout- assert "Virtual environment ready (Python 3.12)" in run.stdout- created_python = install_dir / "venv" / "Scripts" / "python.exe"- version = subprocess.run(- [str(created_python), "--version"],- env=env,- capture_output=True,- text=True,- check=True,- )- assert version.stdout.strip() == "Python 3.12.13"---def test_python_find_drains_large_stderr_without_deadlock(tmp_path: Path) -> None:- powershell = shutil.which("powershell")- if not powershell:- pytest.skip("Windows PowerShell is required")-- hermes_home = tmp_path / "hermes-home"- install_dir = tmp_path / "install"- managed_python = (- install_dir / ".hermes-runtime" / "python" / "cpython-3.11" / "python.exe"- )- uv = hermes_home / "bin" / "uv.exe"- uv.parent.mkdir(parents=True)- managed_python.parent.mkdir(parents=True)- compile_fake_uv(powershell, uv)- shutil.copy2(uv, managed_python)- env = {- **os.environ,- "FAKE_UV_LOG": str(tmp_path / "uv.log"),- "FAKE_MANAGED_PYTHON": str(managed_python),- "FAKE_UV_FIND_STDERR_BYTES": str(1024 * 1024),- }-- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)-- assert run.returncode == 0, run.stdout + run.stderr- assert "Creating virtual environment with Python 3.11" in run.stdout+INSTALLER = Path(__file__).resolve().parents[1] / "scripts" / "install.ps1"-def test_python_find_timeout_kills_uv_and_fails_stage(tmp_path: Path) -> None:[email protected]("exit_code", [0, 17])+def test_python_stage_delegates_to_pin_without_touching_existing_env(tmp_path, exit_code):powershell = shutil.which("powershell")- if not powershell:- pytest.skip("Windows PowerShell is required")-- hermes_home = tmp_path / "hermes-home"- install_dir = tmp_path / "install"- uv = hermes_home / "bin" / "uv.exe"- uv.parent.mkdir(parents=True)- install_dir.mkdir()- compile_fake_uv(powershell, uv)- env = {- **os.environ,- "FAKE_UV_LOG": str(tmp_path / "uv.log"),- "FAKE_UV_FIND_DELAY_MS": "60000",- }-- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)-- assert run.returncode != 0- assert "uv python find 3.11 timed out after 30000 ms" in (run.stdout + run.stderr)---def test_venv_failure_fails_stage_and_restores_existing_environment(- tmp_path: Path,-) -> None:- powershell = shutil.which("powershell")- if not powershell:- pytest.skip("Windows PowerShell is required")-- hermes_home = tmp_path / "hermes-home"- install_dir = tmp_path / "install"- managed_python = (- install_dir / ".hermes-runtime" / "python" / "cpython-3.11" / "python.exe"- )- old_python = install_dir / "venv" / "Scripts" / "python.exe"- uv = hermes_home / "bin" / "uv.exe"- for directory in (uv.parent, managed_python.parent, old_python.parent):- directory.mkdir(parents=True, exist_ok=True)- old_python.write_text("previous environment", encoding="ascii")- compile_fake_uv(powershell, uv)- shutil.copy2(uv, managed_python)- env = {- **os.environ,- "FAKE_UV_LOG": str(tmp_path / "uv.log"),- "FAKE_MANAGED_PYTHON": str(managed_python),- "FAKE_UV_VENV_EXIT": "37",- }-- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)-- assert run.returncode != 0- assert "Failed to create virtual environment (uv venv exited with 37)" in (- run.stdout + run.stderr- )- assert old_python.read_text(encoding="ascii") == "previous environment"- frames = [json.loads(line) for line in run.stdout.splitlines() if line.startswith("{")]- assert frames[-1]["ok"] is False+ assert powershell+ install = tmp_path / "install"+ (install / "pm").mkdir(parents=True)+ (install / "pm" / "lock.json").write_text(json.dumps({"packages": {"python": {"version": "3.12.8+fixture"}}}))+ existing = install / "venv" / "sentinel"+ existing.parent.mkdir()+ existing.write_text("previous generation")+ log = tmp_path / "uv-call.json"+ wrapper = tmp_path / "boundary.ps1"+ wrapper.write_text(r'''+param([string]$Installer, [string]$InstallDir, [string]$HomeDir, [string]$Log)+$ErrorActionPreference = 'Stop'+function uv {+ ConvertTo-Json -Compress -InputObject @($args) | Set-Content -Encoding UTF8 $Log+ $global:LASTEXITCODE = [int]$env:PROBE_EXIT+}+function Get-Command {+ param([string]$Name)+ if ($Name -eq 'uv') { return [pscustomobject]@{ Source = 'uv' } }+ Microsoft.PowerShell.Core\Get-Command $Name+}+function Invoke-WebRequest { throw 'network access outside test boundary' }+. $Installer -Stage python-deps -Json -InstallDir $InstallDir -HermesHome $HomeDir+exit $LASTEXITCODE+''', encoding="utf-8-sig")+ run = subprocess.run([powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(wrapper),+ "-Installer", str(INSTALLER), "-InstallDir", str(install), "-HomeDir", str(tmp_path / "home"), "-Log", str(log)],+ cwd=tmp_path, env=dict(os.environ, PROBE_EXIT=str(exit_code)), stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=120)+ assert (run.returncode == 0) == (exit_code == 0), run.stdout + run.stderr+ assert json.loads(log.read_text(encoding="utf-8-sig")) == ["run", "--no-project", "--python", "3.12", "python", "-m", "pm.cli", "install"]+ assert existing.read_text() == "previous generation"diff --git a/tests/test_install_sh_desktop_stage.py b/tests/test_install_sh_desktop_stage.pynew file mode 100644index 00000000000..44e997a1b9c--- /dev/null+++ b/tests/test_install_sh_desktop_stage.py@@ -0,0 +1,112 @@+"""install.sh desktop stage: real invocation + authoritative stage list.++The desktop stage must delegate to the product CLI's parsed invocation+(``hermes desktop --build-only``) and the stage list must be authored ONCE:+``--manifest`` prints it and the no-flag ladder runs it, so+``--include-desktop`` affects the real run exactly as the manifest+advertises (audit C27's shell-side sibling).++Behavioral: the manifest is executed for real; stage_names()/stage_desktop()+are invoked after sourcing the installer with --manifest (the documented+sourcing contract — arg parsing prints the manifest and stops before main).+No product install/build happens: the venv python is a fake logging stub.+"""++from __future__ import annotations++import json+import shutil+import subprocess+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[1]+INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"++pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash")+++def _manifest(*flags: str) -> list[str]:+ result = subprocess.run(+ ["bash", str(INSTALL_SH), "--manifest", *flags],+ capture_output=True,+ text=True,+ check=True,+ timeout=60,+ )+ return [s["name"] for s in json.loads(result.stdout)["stages"]]+++def test_manifest_without_desktop_lists_no_desktop() -> None:+ assert "desktop" not in _manifest()+++def test_manifest_with_include_desktop_orders_desktop_before_complete() -> None:+ names = _manifest("--include-desktop")+ assert names.index("desktop") < names.index("complete")+ assert names[-1] == "complete"+++def _shpath(path: Path) -> str:+ """Embed a Windows path in a bash script safely: forward slashes."""+ return str(path).replace("\\", "/")+++def _source(prefix: str) -> str:+ """Source the installer (arg parsing prints the manifest and exits+ before main), so every function is defined and nothing runs."""+ return f'source "{INSTALL_SH}" --manifest >/dev/null\n{prefix}\n'+++def test_stage_names_is_the_single_authoritative_list(tmp_path: Path) -> None:+ script = _source(+ f"""+INCLUDE_DESKTOP=false+printf '%s\\n' $(stage_names) > "{_shpath(tmp_path / "without.txt")}"+INCLUDE_DESKTOP=true+printf '%s\\n' $(stage_names) > "{_shpath(tmp_path / "with.txt")}"+"""+ )+ result = subprocess.run(["bash", "-c", script], capture_output=True, text=True, check=True)+ assert result.returncode == 0, result.stderr++ without = (tmp_path / "without.txt").read_text().split()+ with_desktop = (tmp_path / "with.txt").read_text().split()+ assert "desktop" not in without+ assert with_desktop.index("desktop") < with_desktop.index("complete")+ # The flag's ONLY effect on the list is inserting desktop.+ assert [n for n in with_desktop if n != "desktop"] == without+++def test_stage_desktop_invokes_the_parsed_product_cli(tmp_path: Path) -> None:+ install_dir = tmp_path / "install"+ venv_bin = install_dir / "venv" / "bin"+ venv_bin.mkdir(parents=True)+ log = tmp_path / "fake-python.log"+ fake_python = venv_bin / "python"+ fake_python.write_text(+ "#!/usr/bin/env bash\n"+ f'printf \'%s\\n\' "$*" >> "{_shpath(log)}"\n'+ "exit 0\n",+ encoding="utf-8",+ )+ fake_python.chmod(0o755)+ (install_dir / "hermes").write_text("#!/usr/bin/env bash\nexit 0\n", encoding="utf-8")++ script = _source(+ f"""+INCLUDE_DESKTOP=true+INSTALL_DIR="{_shpath(install_dir)}"+stage_desktop+"""+ )+ result = subprocess.run(+ ["bash", "-c", script], capture_output=True, text=True, check=False, timeout=60+ )+ assert result.returncode == 0, result.stdout + result.stderr++ lines = log.read_text().splitlines()+ assert lines[-1] == f"{_shpath(install_dir / 'hermes')} desktop --build-only", (+ "stage_desktop must invoke the parsed CLI flags, not a removed 'build' subcommand"+ )diff --git a/tests/test_install_sh_node_deps_workspaces.py b/tests/test_install_sh_node_deps_workspaces.pyindex 176e9efad30..23a1f0c3e45 100644--- a/tests/test_install_sh_node_deps_workspaces.py+++ b/tests/test_install_sh_node_deps_workspaces.py@@ -1,94 +1,19 @@-"""A CLI install must never resolve the desktop workspace.--``apps/desktop`` declares ``node-pty``, which ships no Linux prebuild and so-falls back to ``node-gyp rebuild``. A bare ``npm install`` at the repo root-resolves the root ``apps/*`` workspace glob and drags it in, so a host with no-make/gcc cannot finish an install for a machine that will never launch Electron-or a PTY addon (#38311, #38772). Since #85297 a failed npm install aborts the-whole install, so this is the difference between a working CLI install and none.--These exercise the real ``node_deps_workspace_args`` from ``scripts/install.sh``.-``--manifest`` makes the installer print its stage manifest and stop before-``main``, so sourcing it defines every function without running an install.-"""--import shutil-import subprocess+"""Bootstrap does not ask npm to resolve an unrelated desktop workspace."""+import osfrom pathlib import Path+import subprocess-import pytest--REPO_ROOT = Path(__file__).resolve().parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"--pytestmark = pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash")---def workspace_args(install_dir: Path) -> list[str]:- """Return the npm arguments install.sh would use for ``install_dir``."""- script = (- f'source "{INSTALL_SH}" --manifest >/dev/null\n'- f'node_deps_workspace_args "{install_dir}"\n'- 'printf "%s\\n" "${NODE_DEPS_WORKSPACE_ARGS[@]}"\n'- )- result = subprocess.run(- ["bash", "-c", script],- capture_output=True,- text=True,- check=True,- )- return result.stdout.split()---def make_checkout(root: Path, workspaces: tuple[str, ...]) -> Path:- """Lay out a checkout with a root package and the given workspace dirs."""- (root / "package.json").write_text('{"workspaces": ["apps/*", "ui-tui", "web"]}')- for workspace in ("apps/desktop", *workspaces):- directory = root / workspace- directory.mkdir(parents=True)- (directory / "package.json").write_text("{}")- return root---def selected_workspaces(args: list[str]) -> list[str]:- return [value for flag, value in zip(args, args[1:]) if flag == "--workspace"]--- "workspaces",- [("ui-tui", "web"), ("ui-tui",), ("web",), ()],- ids=["full", "tui-only", "web-only", "bare"],-)-def test_desktop_workspace_is_never_selected(tmp_path, workspaces):- """No checkout shape may let apps/desktop (and its node-pty) resolve."""- args = workspace_args(make_checkout(tmp_path, workspaces))-- assert "desktop" not in " ".join(args)- # Constraining npm is the whole point: an empty argument list would leave- # npm resolving every workspace, including apps/*.- assert args, "npm must be constrained, otherwise apps/* resolves"- assert "--workspaces=false" in args or selected_workspaces(args)---def test_present_workspaces_are_installed_alongside_the_root(tmp_path):- """ui-tui and web are what a CLI install needs; the root owns shared- devDependencies that a scoped install would otherwise prune."""- args = workspace_args(make_checkout(tmp_path, ("ui-tui", "web")))-- assert selected_workspaces(args) == ["ui-tui", "web"]- assert "--include-workspace-root" in args---def test_absent_workspace_is_not_named(tmp_path):- """npm fails hard on a workspace it cannot find, so a partial checkout- must only name the workspaces that exist."""- args = workspace_args(make_checkout(tmp_path, ("ui-tui",)))-- assert selected_workspaces(args) == ["ui-tui"]-+ROOT = Path(__file__).resolve().parents[1]-def test_bare_checkout_installs_the_root_only(tmp_path):- """With no installable workspace, npm still must not walk apps/*."""- args = workspace_args(make_checkout(tmp_path, ()))- assert args == ["--workspaces=false"]+def test_node_stage_does_not_invoke_ambient_npm(tmp_path):+ sentinel = tmp_path / "npm-called"+ script = f"""source "{(ROOT / 'scripts/install.sh').as_posix()}" --manifest+npm() {{ touch "{sentinel.as_posix()}"; return 99; }}+INSTALL_DIR="{tmp_path.as_posix()}"+stage_node_deps+"""+ env = dict(os.environ, HOME=tmp_path.as_posix(), HERMES_HOME=tmp_path.as_posix())+ result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert not sentinel.exists()diff --git a/tests/test_install_sh_node_prerelease.py b/tests/test_install_sh_node_prerelease.pydeleted file mode 100644index 2b2a613ed9b..00000000000--- a/tests/test_install_sh_node_prerelease.py+++ /dev/null@@ -1,122 +0,0 @@-"""The installer must never adopt a pre-release Node.js build.--`nodejs.org/dist/latest-v26.x/` serves `node-v26.8.0-<os>-<arch>.tar.xz` — a-filename that looks like a final release — whose binary reports-`v26.8.0-alpha.0.0.0`. Node publishes a headers tarball only for final-releases, so `process.release.headersUrl` 404s for that build and node-gyp-cannot compile against it.--That is fatal rather than cosmetic: `node-pty` ships prebuilds for darwin and-win32 only, so every Linux install compiles it, and the failure surfaces as an-opaque `[email protected] install: command failed` because the package's-`node scripts/prebuild.js || node-gyp rebuild` fallback swallows gyp's stderr.--These tests drive the real blocks out of `scripts/install.sh` rather than-asserting on a copy, so the guard cannot drift away from the test.-"""--import re-import subprocess-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"-NODE_BOOTSTRAP = REPO_ROOT / "scripts" / "lib" / "node-bootstrap.sh"---def _extract_function(text: str, name: str) -> str:- match = re.search(- rf"^{re.escape(name)}\(\) \{{\n.*?^\}}\n", text, re.M | re.S- )- assert match, (- f"could not locate {name}() in scripts/install.sh — "- "if it was renamed, update this test with it"- )- return match.group(0)---def _node_satisfies_build(version: str) -> bool:- """Run the real node_satisfies_build() against one `node --version` string."""- script = (- _extract_function(INSTALL_SH.read_text(encoding="utf-8"), "node_satisfies_build")- + f'\nnode_satisfies_build "{version}"\n'- )- return subprocess.run(["bash", "-c", script]).returncode == 0---def test_prerelease_node_never_satisfies_the_build_floor() -> None:- """The exact build that breaks node-pty, plus the other pre-release tags."""- assert not _node_satisfies_build("v26.8.0-alpha.0.0.0")- assert not _node_satisfies_build("v24.0.0-rc.1")- assert not _node_satisfies_build("v23.5.0-nightly20260101abcdef")- assert not _node_satisfies_build("v22.22.0-pre")---def test_final_releases_still_satisfy_the_build_floor() -> None:- """The guard must not cost us any version that actually works."""- assert _node_satisfies_build("v22.22.0") # the floor itself- assert _node_satisfies_build("v24.20.0")- assert _node_satisfies_build("v26.8.0") # a real 26 release, once one ships---def test_versions_below_the_floor_are_still_rejected() -> None:- assert not _node_satisfies_build("v22.21.0")- assert not _node_satisfies_build("v20.19.0")- assert not _node_satisfies_build("not-a-version")---def test_install_node_falls_back_to_an_older_release_line(tmp_path: Path) -> None:- """A rejected line must not end the install — the next one is tried.-- install_node_line() cannot be exercised here (it downloads), so it is- stubbed to reject 26 the way a pre-release tarball does and accept 24.- """- body = _extract_function(INSTALL_SH.read_text(encoding="utf-8"), "install_node")- script = f"""-set -e-NODE_VERSION=26-DISTRO=linux-OS=linux-uname() {{ echo x86_64; }}-log_info(){{ :; }}; log_warn(){{ :; }}; log_success(){{ :; }}-install_node_line() {{- echo "$1" >> "$TRIED"- [ "$1" = 24 ]-}}-{body}-install_node-"""- tried = tmp_path / "tried"- result = subprocess.run(- ["bash", "-c", script],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- env={"PATH": "/usr/bin:/bin", "TRIED": str(tried)},- )- assert result.returncode == 0, result.stderr- # 26 first, then the previous even (LTS) line; stops once one works.- assert tried.read_text(encoding="utf-8").split() == ["26", "24"]---def test_downloaded_tree_is_probed_before_it_replaces_anything() -> None:- """The filename is not evidence — the extracted binary must be checked.-- Guarded as a text assertion because the surrounding block downloads; the- fallback behaviour it feeds is covered functionally above.- """- text = INSTALL_SH.read_text(encoding="utf-8")- probe = text.index('candidate_ver=$("$extracted_dir/bin/node" --version 2>/dev/null)')- reject = text.index('if ! node_satisfies_build "$candidate_ver"; then', probe)- # The probe has to run before the tree is moved into place, or a bad build- # has already clobbered a working managed Node.- assert reject < text.index('mv "$extracted_dir" "$HERMES_HOME/node"', probe)---def test_node_bootstrap_mirrors_the_prerelease_guard() -> None:- """The sourceable helper answers the same question and must agree."""- text = NODE_BOOTSTRAP.read_text(encoding="utf-8")- assert "_nb_node_is_prerelease" in text- assert "_nb_node_is_prerelease && return 1" in text-diff --git a/tests/test_install_sh_node_probe_87460.py b/tests/test_install_sh_node_probe_87460.pydeleted file mode 100644index 83e50e10a4b..00000000000--- a/tests/test_install_sh_node_probe_87460.py+++ /dev/null@@ -1,207 +0,0 @@-"""Behavioral coverage for install_node's post-install version probe (#87460).--The probe used to be `installed_ver=$(node --version 2>/dev/null)` under-`set -e`: a Node binary that exists but cannot start (Node 26 linux-x64-links libatomic.so.1, missing on minimal Debian/Ubuntu) aborted the whole-installer at exit 127 with the loader's explanation discarded — installs-died mid-sentence with no output at all. The probe must degrade with a-clear error carrying the loader's message, and Debian/Ubuntu installs-must attempt libatomic1 up front.-"""--from __future__ import annotations--import io-import os-import re-import subprocess-import tarfile-from pathlib import Path---REPO_ROOT = Path(__file__).resolve().parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"---def _extract_function(src: str, name: str) -> str:- match = re.search(rf"^{name}\(\) \{{\n(.*?)^\}}", src, re.S | re.M)- assert match is not None, f"{name}() not found in scripts/install.sh"- return match.group(1)---def _extract_install_node() -> str:- src = INSTALL_SH.read_text(encoding="utf-8")- return _extract_function(src, "install_node")---def _extract_install_node_line() -> str:- """The line-walking refactor split the download/probe body into- install_node_line(); the sandboxed driver needs both functions."""- src = INSTALL_SH.read_text(encoding="utf-8")- return _extract_function(src, "install_node_line")---def _extract_node_satisfies_build() -> str:- src = INSTALL_SH.read_text(encoding="utf-8")- return _extract_function(src, "node_satisfies_build")---def _make_node_tarball(path: Path, node_body: str) -> None:- """A .tar.xz-named gzip archive — both bsdtar and modern GNU tar sniff- compression by content, so the extension mismatch is irrelevant here."""- root = "node-v26.7.0-linux-x64"- with tarfile.open(path, "w:gz") as tar:- for name, body, mode in (- (f"{root}/bin/node", node_body, 0o755),- (f"{root}/bin/npm", "#!/bin/sh\nexit 0\n", 0o755),- (f"{root}/bin/npx", "#!/bin/sh\nexit 0\n", 0o755),- ):- data = body.encode("utf-8")- info = tarfile.TarInfo(name=name)- info.size = len(data)- info.mode = mode- tar.addfile(info, io.BytesIO(data))---def _run_install_node(tmp_path: Path, node_body: str) -> tuple[int, str, str, list[str]]:- bin_dir = tmp_path / "bin"- home = tmp_path / "home"- link_dir = tmp_path / "links"- fixture = tmp_path / "fixture.tar.xz"- apt_log = tmp_path / "apt-calls"-- bin_dir.mkdir()- home.mkdir()- link_dir.mkdir()- _make_node_tarball(fixture, node_body)-- def _stub(name: str, body: str) -> None:- stub = bin_dir / name- stub.write_text(body, encoding="utf-8")- stub.chmod(0o755)-- _stub(- "uname",- "#!/bin/sh\n"- 'if [ "${1:-}" = "-m" ]; then echo x86_64; else echo Linux; fi\n',- )- _stub(- "curl",- "#!/bin/sh\n"- "# Called as: curl -fsSL <index-url> (stdout -> tarball name)\n"- "# curl -fsSL <download-url> -o <path>\n"- "if [ \"${3:-}\" = \"-o\" ]; then\n"- ' cp "$FIXTURE" "$4"\n'- "else\n"- " echo 'node-v26.7.0-linux-x64.tar.xz'\n"- "fi\n",- )- _stub("sudo", "#!/bin/sh\nshift_if_env() { :; }\nexec env \"$@\"\n")- _stub(- "apt-get",- "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$APT_LOG\"\nexit 0\n",- )-- env = os.environ.copy()- env.update(- {- "FIXTURE": str(fixture),- "APT_LOG": str(apt_log),- "PATH": f"{bin_dir}:{env['PATH']}",- }- )-- driver = tmp_path / "driver.sh"- driver.write_text(- "#!/usr/bin/env bash\n"- "set -euo pipefail\n"- "OS=linux\n"- "DISTRO=ubuntu\n"- "NODE_VERSION=26\n"- f"HERMES_HOME={home}\n"- "HAS_NODE=maybe\n"- "log_info() { printf 'INFO %s\\n' \"$*\"; }\n"- "log_success() { printf 'OK %s\\n' \"$*\"; }\n"- "log_warn() { printf 'WARN %s\\n' \"$*\"; }\n"- "log_error() { printf 'ERROR %s\\n' \"$*\" >&2; }\n"- f"get_command_link_dir() {{ echo {link_dir}; }}\n"- "configure_managed_node_npm_prefix() { return 0; }\n"- "node_satisfies_build() {\n"- f"{_extract_node_satisfies_build()}"- "}\n"- "install_node_line() {\n"- f"{_extract_install_node_line()}"- "}\n"- "install_node() {\n"- f"{_extract_install_node()}"- "}\n"- "install_node\n"- 'printf "HAS_NODE=%s\\n" "$HAS_NODE"\n',- encoding="utf-8",- )-- proc = subprocess.run(- ["bash", str(driver)],- env=env,- capture_output=True,- text=True,- check=False,- )- apt_calls = (- apt_log.read_text(encoding="utf-8").splitlines()- if apt_log.exists()- else []- )- return proc.returncode, proc.stdout, proc.stderr, apt_calls---BROKEN_NODE = (- "#!/bin/sh\n"- "echo 'node: error while loading shared libraries: libatomic.so.1: "- "cannot open shared object file: No such file or directory' >&2\n"- "exit 127\n"-)--HEALTHY_NODE = "#!/bin/sh\necho v26.7.0\n"---def test_broken_node_degrades_with_clear_error(tmp_path: Path) -> None:- code, stdout, stderr, _ = _run_install_node(tmp_path, BROKEN_NODE)-- # Old behavior: silent abort at exit 127 with no output (#87460).- # With the pre-release line-walk (#96601 salvage), a binary that cannot- # start now fails the pre-adoption probe (node_satisfies_build on the- # extracted tree), so it is rejected BEFORE replacing anything and the- # walker reports no usable line — strictly stronger than the old- # post-adoption cleanup, which this test previously pinned.- assert code == 0, stderr- combined = stdout + stderr- assert "cannot build native modules" in combined- assert "No usable Node.js release line found" in combined- assert "HAS_NODE=false" in stdout- assert "HAS_NODE=true" not in stdout- # The broken candidate must never be adopted: no managed tree, no links.- home = tmp_path / "home"- link_dir = tmp_path / "links"- assert not (home / "node").exists(), "broken managed Node tree left behind"- assert not (link_dir / "node").exists(), "broken node symlink left behind"- assert not (link_dir / "npm").exists(), "broken npm symlink left behind"- # AI-review follow-up: the broken tree and bin links must not linger- # — retries and later installer steps resolve `node` cleanly.- assert not (home / "node").exists(), "broken managed Node tree left behind"- assert not (link_dir / "node").exists(), "broken node symlink left behind"- assert not (link_dir / "npm").exists(), "broken npm symlink left behind"---def test_healthy_node_reports_success(tmp_path: Path) -> None:- code, stdout, stderr, _ = _run_install_node(tmp_path, HEALTHY_NODE)-- assert code == 0, stderr- assert "Node.js v26.7.0 installed" in stdout- assert "HAS_NODE=true" in stdout---def test_libatomic1_is_preinstalled_on_ubuntu(tmp_path: Path) -> None:- _, _, _, apt_calls = _run_install_node(tmp_path, HEALTHY_NODE)-- assert any("libatomic1" in call for call in apt_calls), apt_callsdiff --git a/tests/test_install_sh_termux_python_bounds.py b/tests/test_install_sh_termux_python_bounds.pydeleted file mode 100644index 443873bf641..00000000000--- a/tests/test_install_sh_termux_python_bounds.py+++ /dev/null@@ -1,220 +0,0 @@-"""Behavioral regression tests for Termux Python selection."""--from __future__ import annotations--import os-import shutil-import stat-import subprocess-import sys-from pathlib import Path---REPO_ROOT = Path(__file__).resolve().parent.parent-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"-SETUP_HERMES_SH = REPO_ROOT / "setup-hermes.sh"---def _write_executable(path: Path, content: str) -> Path:- path.write_text(content)- path.chmod(path.stat().st_mode | stat.S_IXUSR)- return path---def _write_fake_python(bin_dir: Path, name: str, version: str) -> Path:- return _write_executable(- bin_dir / name,- f"""#!{sys.executable}-import os-import sys--VERSION = {version!r}-VERSION_INFO = tuple(int(part) for part in VERSION.split('.')[:3]) + ('final', 0)--if len(sys.argv) >= 2 and sys.argv[1] == '--version':- print(f'Python {{VERSION}}')- raise SystemExit(0)--if len(sys.argv) >= 3 and sys.argv[1] == '-c':- sys.version = f'{{VERSION}} (fake)'- sys.version_info = VERSION_INFO- exec(sys.argv[2], {{'__name__': '__main__'}})- raise SystemExit(0)--if len(sys.argv) >= 3 and sys.argv[1:3] == ['-m', 'venv']:- target = sys.argv[3] if len(sys.argv) >= 4 else 'venv'- bin_path = os.path.join(target, 'bin')- os.makedirs(bin_path, exist_ok=True)- python_path = os.path.join(bin_path, 'python')- with open(python_path, 'w', encoding='utf-8') as handle:- handle.write('''#!/bin/sh\nif [ "${{1:-}}" = '-m' ] && [ "${{2:-}}" = 'pip' ]; then\n exit 0\nfi\nexit 0\n''')- os.chmod(python_path, 0o755)- raise SystemExit(0)--raise SystemExit(0)-""",- )---def _write_unsupported_explicit_pythons(bin_dir: Path, *except_names: str) -> None:- for name in ("python3.11", "python3.12", "python3.13"):- if name not in except_names and not (bin_dir / name).exists():- _write_fake_python(bin_dir, name, "3.14.6")---def _write_termux_command_stubs(bin_dir: Path) -> None:- _write_executable(- bin_dir / "uname",- "#!/bin/sh\n[ \"${1:-}\" = '-s' ] && echo Linux || echo Linux\n",- )- if not (bin_dir / "pkg").exists():- _write_executable(bin_dir / "pkg", "#!/bin/sh\nexit 0\n")- _write_executable(bin_dir / "git", "#!/bin/sh\necho 'git version 2.50.0'\n")- _write_executable(bin_dir / "node", "#!/bin/sh\necho 'v22.12.0'\n")- _write_executable(bin_dir / "npm", "#!/bin/sh\nexit 0\n")- _write_executable(bin_dir / "curl", "#!/bin/sh\nexit 0\n")- _write_executable(bin_dir / "rg", "#!/bin/sh\nexit 0\n")---def _termux_env(tmp_path: Path, bin_dir: Path) -> dict[str, str]:- prefix = tmp_path / "com.termux" / "files" / "usr"- (prefix / "bin").mkdir(parents=True)- env = os.environ.copy()- env.update({- "ANDROID_API_LEVEL": "35",- "HOME": str(tmp_path / "home"),- "HERMES_HOME": str(tmp_path / "home" / ".hermes"),- "PATH": f"{bin_dir}{os.pathsep}{env.get('PATH', os.defpath)}",- "PREFIX": str(prefix),- "TERMUX_VERSION": "0.118.0",- })- return env---def _run_install_prerequisites(tmp_path: Path) -> subprocess.CompletedProcess[str]:- bin_dir = tmp_path / "bin"- bin_dir.mkdir(exist_ok=True)- _write_termux_command_stubs(bin_dir)- env = _termux_env(tmp_path, bin_dir)- bash = shutil.which("bash") or "/bin/bash"- return subprocess.run(- [bash, str(INSTALL_SH), "--stage", "prerequisites", "--non-interactive"],- env=env,- text=True,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- check=False,- )---def _copy_setup_checkout(tmp_path: Path) -> Path:- checkout = tmp_path / "checkout"- checkout.mkdir()- shutil.copy2(SETUP_HERMES_SH, checkout / "setup-hermes.sh")- return checkout---def _run_setup(tmp_path: Path) -> subprocess.CompletedProcess[str]:- bin_dir = tmp_path / "bin"- bin_dir.mkdir(exist_ok=True)- _write_termux_command_stubs(bin_dir)- env = _termux_env(tmp_path, bin_dir)- checkout = _copy_setup_checkout(tmp_path)- bash = shutil.which("bash") or "/bin/bash"- return subprocess.run(- [bash, str(checkout / "setup-hermes.sh")],- env=env,- input="n\n",- text=True,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- check=False,- )---def test_install_stage_prefers_compatible_minor_over_unsupported_default(- tmp_path: Path,-) -> None:- bin_dir = tmp_path / "bin"- bin_dir.mkdir()- _write_fake_python(bin_dir, "python3.11", "3.11.15")- _write_fake_python(bin_dir, "python", "3.14.6")-- result = _run_install_prerequisites(tmp_path)-- assert result.returncode == 0, result.stdout- assert "Python found: Python 3.11.15" in result.stdout---def test_install_stage_rejects_post_install_unsupported_default(tmp_path: Path) -> None:- bin_dir = tmp_path / "bin"- bin_dir.mkdir()- _write_fake_python(bin_dir, "python", "3.14.6")- _write_unsupported_explicit_pythons(bin_dir)-- result = _run_install_prerequisites(tmp_path)-- assert result.returncode == 1- assert "Termux Python Python 3.14.6 is not supported" in result.stdout- assert "Hermes requires Python >=3.11,<3.14" in result.stdout- assert "pkg install tur-repo && pkg install python3.13" in result.stdout---def test_install_stage_provisions_supported_python_from_tur(tmp_path: Path) -> None:- """When the default Termux python is too new, the installer falls back to- the Termux User Repository (TUR) and picks up a supported interpreter that- `pkg install python3.13` provides."""- bin_dir = tmp_path / "bin"- bin_dir.mkdir()- _write_fake_python(bin_dir, "python", "3.14.6")- # Shadow any host python3.11/3.12/3.13 so the candidate scan can't find a- # supported interpreter before the TUR fallback runs.- _write_unsupported_explicit_pythons(bin_dir)-- # Stateful pkg stub: `pkg install -y python3.13` drops a supported fake- # interpreter into PATH, mimicking a successful TUR package install.- staged = tmp_path / "staged"- staged.mkdir()- _write_fake_python(staged, "python3.13", "3.13.7")- _write_executable(- bin_dir / "pkg",- "#!/bin/sh\n"- "for arg in \"$@\"; do\n"- f" if [ \"$arg\" = 'python3.13' ]; then cp {staged}/python3.13 {bin_dir}/python3.13; fi\n"- "done\n"- "exit 0\n",- )-- result = _run_install_prerequisites(tmp_path)-- assert result.returncode == 0, result.stdout- assert "Python installed from TUR: Python 3.13.7" in result.stdout---def test_setup_script_prefers_compatible_minor_over_unsupported_default(- tmp_path: Path,-) -> None:- bin_dir = tmp_path / "bin"- bin_dir.mkdir()- _write_fake_python(bin_dir, "python3.11", "3.14.6")- _write_fake_python(bin_dir, "python3.12", "3.12.11")- _write_fake_python(bin_dir, "python", "3.14.6")-- result = _run_setup(tmp_path)-- assert result.returncode == 0, result.stdout- assert "Python 3.12.11 found" in result.stdout- assert (tmp_path / "checkout" / "venv" / "bin" / "python").exists()---def test_setup_script_rejects_unsupported_default(tmp_path: Path) -> None:- bin_dir = tmp_path / "bin"- bin_dir.mkdir()- _write_fake_python(bin_dir, "python", "3.14.6")- _write_unsupported_explicit_pythons(bin_dir)-- result = _run_setup(tmp_path)-- assert result.returncode == 1- assert "Termux Python Python 3.14.6 is not supported" in result.stdout- assert "Hermes requires Python >=3.11,<3.14" in result.stdoutdiff --git a/tests/test_iron_proxy.py b/tests/test_iron_proxy.pyindex 33e00abef4a..1d0c937989c 100644--- a/tests/test_iron_proxy.py+++ b/tests/test_iron_proxy.py@@ -55,6 +55,24 @@ def test_mint_proxy_token_has_prefix_and_length():assert len(t) >= len("alpha-") + 32+def test_management_token_path_is_single_authority(hermes_home):+ """One token path: <hermes_home>/proxy/management.token, shared by mint, reuse and readers."""+ assert ip._management_token_path() == ip._proxy_state_dir_ro() / "management.token"+ assert not (hermes_home / "proxy").exists()++ token = ip.ensure_management_token()+ assert token+ p = ip._management_token_path()+ assert p.is_file()+ assert p.read_text(encoding="utf-8-sig").strip() == token+ # 0600-style private write: reuse without minting a second token.+ assert ip.ensure_management_token() == token+ # Forced rotation mints a new token at the same single path.+ rotated = ip.ensure_management_token(force=True)+ assert rotated != token+ assert ip._management_token_path().read_text(encoding="utf-8-sig").strip() == rotated++diff --git a/tests/test_live_system_guard.py b/tests/test_live_system_guard.pyindex 83e98565f95..e0d9545d6d9 100644--- a/tests/test_live_system_guard.py+++ b/tests/test_live_system_guard.py@@ -5,12 +5,47 @@ The guard must treat only argv[0] of a list/tuple command as the executablewhile still scanning every token of wrapper invocations like ``bash -c``.All blocked-case commands use patterns that match no real process, so aguard regression cannot kill anything.++The git worktree-mutation tests below follow the same fail-safe discipline,+stronger: every *blocked-case* command targets a ``tmp_path`` repo that the+test itself DESIGNATES as the protected root (via+``tests.conftest._LIVE_GUARD_PROTECTED_GIT_ROOTS``). If the guard regresses,+the mutating verb actually dispatches — against the throwaway repo only —+and the assertion fails; the real checkout is never touched, even RED.+Read-only git against the real checkout (``stash list``) is asserted ALLOWED:+the guard targets mutating verbs, not git as such."""import subprocessimport pytest+import tests.conftest as _guard_conftest+++def _git(cwd, *args):+ return subprocess.run(+ ["git", *args], cwd=str(cwd), capture_output=True, text=True+ )+++def _init_repo(tmp_path):+ """A real throwaway git repo with one tracked file and one commit."""+ repo = tmp_path / "checkout"+ repo.mkdir()+ tracked = repo / "tracked.txt"+ tracked.write_text("canary\n")+ for args in (+ ("init", "-q"),+ ("config", "user.email", "[email protected]"),+ ("config", "user.name", "guard"),+ ("add", "."),+ ("commit", "-q", "-m", "canary"),+ ):+ result = _git(repo, *args)+ assert result.returncode == 0, result.stderr+ return repo, tracked+def test_argv_arguments_are_not_treated_as_executables(tmp_path):"""A file argument whose basename is a killer name must not trip the@@ -37,3 +72,120 @@ def test_wrapped_killer_command_is_still_blocked():def test_env_wrapped_killer_command_is_still_blocked():with pytest.raises(RuntimeError, match="live-system guard"):subprocess.run(["env", "GUARD_TEST=1", "pkill", "-f", "hermes-guard-regression-nomatch"])+++# ──────────────── git worktree-mutation guard ────────────────+++def test_git_init_commit_status_in_temp_repo_allowed(tmp_path):+ """Arbitrary temp repo fixtures keep full git freedom: init + commit ++ status must dispatch normally (no RuntimeError)."""+ repo, _tracked = _init_repo(tmp_path)+ result = _git(repo, "status", "--porcelain")+ assert result.returncode == 0+ assert result.stdout == ""+++def test_git_stash_list_on_real_checkout_is_allowed():+ """Read-only git against the ACTUAL checkout must stay allowed.++ ``stash list`` mutates nothing, so even a total guard regression leaves+ this command harmless. (The review doc asserted the opposite — blocked —+ contradicting its own read-only exception list; rejected.)+ """+ result = _git(_guard_conftest.PROJECT_ROOT, "stash", "list")+ assert result.returncode == 0++[email protected]("primitive", ["run", "Popen", "check_output", "getoutput", "os.system", "asyncio"])+def test_git_stash_on_designated_protected_root_is_blocked(tmp_path, monkeypatch, primitive):+ """``git stash push`` via the ``cwd`` kwarg (the real cmd_update incident+ vector: plain cwd, no -C) must be rejected BEFORE dispatch."""+ repo, tracked = _init_repo(tmp_path)+ monkeypatch.setattr(+ _guard_conftest, "_LIVE_GUARD_PROTECTED_GIT_ROOTS", (repo,)+ )+ monkeypatch.chdir(repo)+ command = ["git", "stash", "push", "-m", "guard-canary"]+ with pytest.raises(RuntimeError, match="live-system guard"):+ if primitive == "os.system":+ import os+ os.system("git stash push")+ elif primitive == "asyncio":+ import asyncio+ asyncio.run(asyncio.create_subprocess_exec(*command, cwd=str(repo)))+ elif primitive == "getoutput":+ subprocess.getoutput("git stash push")+ else:+ getattr(subprocess, primitive)(command, cwd=str(repo))+ # Nothing dispatched: no stash entry exists, the canary file is intact.+ assert _git(repo, "stash", "list").stdout.strip() == ""+ assert tracked.read_text() == "canary\n"+++def test_git_reset_hard_on_designated_protected_root_is_blocked(tmp_path, monkeypatch):+ repo, tracked = _init_repo(tmp_path)+ monkeypatch.setattr(+ _guard_conftest, "_LIVE_GUARD_PROTECTED_GIT_ROOTS", (repo,)+ )+ tracked.write_text("dirty\n") # reset --hard would destroy this+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.run(["git", "reset", "--hard"], cwd=repo)+ assert tracked.read_text() == "dirty\n"+++def test_git_stash_via_dash_c_target_is_blocked(tmp_path, monkeypatch):+ """The explicit ``-C <path>`` target form resolves too."""+ repo, tracked = _init_repo(tmp_path)+ monkeypatch.setattr(+ _guard_conftest, "_LIVE_GUARD_PROTECTED_GIT_ROOTS", (repo,)+ )+ with pytest.raises(RuntimeError, match="live-system guard"):+ # cwd is the tmp root (outside the checkout): if the guard ever+ # regresses, git -C dispatches against the throwaway repo only.+ subprocess.run(["git", "-C", str(repo), "stash", "push"], cwd=str(tmp_path))+ assert _git(repo, "stash", "list").stdout.strip() == ""+ assert tracked.read_text() == "canary\n"+++def test_git_stash_string_shell_form_on_designated_root_is_blocked(tmp_path, monkeypatch):+ repo, _tracked = _init_repo(tmp_path)+ monkeypatch.setattr(+ _guard_conftest, "_LIVE_GUARD_PROTECTED_GIT_ROOTS", (repo,)+ )+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.run("git stash push -m guard-canary", shell=True, cwd=str(repo))++[email protected]("invocation", ["native-exe", "relative-c", "chained-c", "git-dir", "shell-wrapper"])+def test_git_mutation_resolves_native_executable_and_target(tmp_path, monkeypatch, invocation):+ import shutil++ repo, tracked = _init_repo(tmp_path)+ tracked.write_text("dirty\n")+ monkeypatch.setattr(_guard_conftest, "_LIVE_GUARD_PROTECTED_GIT_ROOTS", (repo,))+ git = shutil.which("git")+ assert git is not None+ commands = {+ "native-exe": [git, "reset", "--hard"],+ "relative-c": ["git", "-C", repo.name, "reset", "--hard"],+ "chained-c": ["git", "-C", str(tmp_path), "-C", repo.name, "reset", "--hard"],+ "git-dir": ["git", "--git-dir", str(repo / ".git"), "--work-tree", str(tmp_path / "elsewhere"), "reset", "--hard"],+ "shell-wrapper": ["bash", "-c", f'git -C "{repo.as_posix()}" reset --hard'],+ }+ cwd = repo if invocation == "native-exe" else tmp_path+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.run(commands[invocation], cwd=cwd, capture_output=True, text=True, timeout=15)+ assert tracked.read_text() == "dirty\n"+++def test_git_pull_in_temp_repo_allowed(tmp_path):+ """A mutating verb OUTSIDE the protected roots stays allowed — fixture+ repos must not lose pull capability."""+ repo, _tracked = _init_repo(tmp_path)+ result = _git(repo, "pull")+ # No remote configured: git itself fails, but the GUARD must not — a+ # guard block surfaces as RuntimeError before dispatch, never as a+ # CompletedProcess.+ assert result.returncode != 0+ assert "live-system guard" not in result.stderrdiff --git a/tests/test_managed_runtime_resolution.py b/tests/test_managed_runtime_resolution.pyindex 19be3acdbd3..9e5c15682d5 100644--- a/tests/test_managed_runtime_resolution.py+++ b/tests/test_managed_runtime_resolution.py@@ -1,220 +1,21 @@-"""Guard: Hermes-owned subprocesses must not resolve managed runtimes by bare PATH.+"""Managed workspace tooling wins; PATH is only a pre-install fallback."""+import importlib+import shutil-Hermes installs runtimes for itself — ``uv`` at ``$HERMES_HOME/bin/uv``, Node at-``$HERMES_HOME/node``. Neither directory is on the ambient PATH of an arbitrary-process, so ``shutil.which("uv")`` / ``shutil.which("node")`` in Hermes's own-code has two failure modes:+from pm.workspace import _uv_binary-* the managed runtime is invisible, so the caller reports "not installed" or- degrades to a slower tier on a machine that has exactly what it needed; and-* when a system copy also exists, the one Hermes does not own wins — which is- how a generated systemd unit or launchd plist can bake a system Node in and- keep resolving it across reboots.-The fix per call site is one of ``find_node_executable()``, ``pm.env_for()``,-``pm.ensure()``, or (transitional)-``pm.uv()``. This test is-the ratchet that stops a new bare lookup from being added back.+def test_workspace_uv_prefers_managed_tool_without_path_probe(monkeypatch):+ ensure = importlib.import_module("pm.ensure")+ monkeypatch.setattr(ensure, "uv", lambda **kwargs: ("managed/uv", {}))+ def reject_path(*args, **kwargs):+ raise AssertionError("managed uv must win before PATH")+ monkeypatch.setattr(shutil, "which", reject_path)+ assert _uv_binary() == "managed/uv"-Reading source is normally banned (see AGENTS.md). It is the right tool here and-only here: the property under test is "no call site anywhere in the tree spells-it this way", which is a statement about the whole codebase rather than about-one function's behavior, and there is no runtime seam that can observe a lookup-that was never written. Every entry in the allow-list below names a call site-whose behavior is separately covered by a real test.-"""-from __future__ import annotations--import ast-import subprocess-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parents[1]--# Runtimes Hermes provisions into HERMES_HOME and must therefore resolve-# through a managed-aware helper rather than PATH.-_MANAGED_COMMANDS = frozenset({"uv", "node", "npm", "npx"})--# Directories that are not Hermes-owned subprocess code: plugins ship their own-# resolution policy, tests assert against PATH deliberately, and skills/scripts-# run as standalone user-invoked programs.-_EXEMPT_DIRS = (- "tests",- "plugins",- "skills",- "optional-skills",- "scripts",- "website",- "node_modules",- ".git",- ".venv",- "venv",- ".worktrees",-)--# Call sites where a bare PATH lookup is the correct answer. Each entry is-# (path, command) -> why. Keep this list short and justified — the default-# answer for a new call site is a managed-aware helper, not a new exemption.-_ALLOWED: dict[tuple[str, str], str] = {- ("tools/env_probe.py", "uv"): (- "Reports the environment the MODEL sees in the terminal tool. The model "- "can only run what is on that subshell's PATH, which local.py populates "- "with the managed dirs — so PATH is the correct question to ask here."- ),- ("hermes_cli/update_cmd_deps.py", "npm"): (- "WSL diagnostic: deliberately inspects what PATH resolves so it can "- "warn that the only reachable npm is the Windows one."- ),- ("tools/browser_use_cli.py", "uv"): (- "install_cli()'s fallback after pm.uv() misses — a user-installed "- "uv on PATH is a legitimate last rung before giving up with install "- "guidance."- ),- ("hermes_cli/gateway.py", "node"): (- "Fallback rung of _append_node_dir_for_service(), after the pm "- "store's managed dirs are already appended."- ),- ("hermes_cli/main_tui_launch.py", "node"): (- "_ensure_tui_node()'s idempotence gate: the question really is 'is "- "node already discoverable on PATH', before bootstrapping one."- ),- ("hermes_cli/main_tui_launch.py", "npm"): (- "Same _ensure_tui_node() gate as node."- ),- ("hermes_cli/main_install_repair.py", "npm"): (- "_resolve_node_runtime_npm()'s WSL re-scan: PATH minus /mnt/* IS the question."- ),- ("tools/browser_tool_install.py", "npx"): (- "agent-browser runs via `npx`, resolved against the extended browser "- "PATH that _merge_browser_path() already seeds with the managed dirs."- ),-}---def _iter_which_calls(tree: ast.AST):- """Yield (command, lineno) for every ``which("<cmd>")`` call in *tree*.-- AST rather than a regex so prose in docstrings and comments that mentions- ``shutil.which("npm")`` is not mistaken for a call site.- """- for node in ast.walk(tree):- if not isinstance(node, ast.Call) or not node.args:- continue- func = node.func- name = (- func.attr- if isinstance(func, ast.Attribute)- else func.id if isinstance(func, ast.Name) else None- )- if name != "which":- continue- first = node.args[0]- if isinstance(first, ast.Constant) and first.value in _MANAGED_COMMANDS:- yield first.value, node.lineno---def _source_files() -> list[Path]:- # Enumerate the .py files git TRACKS, not the working directory. git knows- # the source of truth, and that excludes every build artifact by- # construction — .venv/, .worktrees/, apps/desktop/build/ and- # apps/desktop/release/ (which each bundle a full copy of this source tree- # for the MSIX pack), and any sdist/egg extraction. Walking the disk with- # rglob would re-find every already-exempted call site inside those copies- # under a nested path prefix that can never match an _ALLOWED key. A- # gitignored dir cannot carry this branch's real code, so skipping it is- # correct, not lossy.- try:- out = subprocess.run(- ["git", "ls-files", "-z", "--", "*.py"],- cwd=REPO_ROOT,- capture_output=True,- check=True,- ).stdout- except (subprocess.CalledProcessError, FileNotFoundError):- # Not a git checkout (installed copy, etc.) — fall back to a disk- # walk so the guard still runs rather than silently passing.- return sorted(REPO_ROOT.rglob("*.py"))- rels = out.decode("utf-8", "replace").split("\0")- return [REPO_ROOT / rel for rel in rels if rel]---def _findings() -> list[tuple[str, str, int]]:- """Return (relpath, command, lineno) for every bare managed lookup."""- found: list[tuple[str, str, int]] = []- for path in _source_files():- rel = path.relative_to(REPO_ROOT)- if rel.parts and rel.parts[0] in _EXEMPT_DIRS:- continue- try:- source = path.read_text(encoding="utf-8")- except (OSError, UnicodeDecodeError):- continue- if "which(" not in source:- continue- try:- tree = ast.parse(source)- except SyntaxError:- continue- for command, lineno in _iter_which_calls(tree):- found.append((rel.as_posix(), command, lineno))- return found---def test_no_unreviewed_bare_managed_runtime_lookups():- """Every bare which() for a managed runtime is a reviewed exemption."""- unexpected = [- (rel, cmd, lineno)- for rel, cmd, lineno in _findings()- if (rel, cmd) not in _ALLOWED- ]-- assert not unexpected, (- "Bare PATH lookup for a Hermes-managed runtime.\n\n"- + "\n".join(f" {rel}:{lineno} which({cmd!r})" for rel, cmd, lineno in unexpected)- + "\n\n$HERMES_HOME/bin (uv) and $HERMES_HOME/node are not on an "- "arbitrary process's PATH, so this resolves a system copy — or nothing "- "— on an install that has a managed one.\n"- "Use instead:\n"- " uv -> pm.uv(realize=False) (lookup) or pm.uv() (may realize)\n"- " node/npm -> hermes_constants.find_node_executable()\n"- " PATH env -> hermes_constants.with_hermes_node_path()\n"- "If PATH really is the right question, add the site to _ALLOWED with a "- "reason."- )---def test_allowlist_has_no_stale_entries():- """A fixed call site must be dropped from the allow-list, not left to rot."""- live = {(rel, cmd) for rel, cmd, _lineno in _findings()}- stale = sorted(set(_ALLOWED) - live)-- assert not stale, (- "Allow-list entries no longer match any source line — the call site was "- "fixed or moved. Remove them:\n"- + "\n".join(f" {rel} ({cmd})" for rel, cmd in stale)- )--- "helper",- [- "find_node_executable",- "with_hermes_node_path",- ],-)-def test_managed_node_helpers_exist(helper):- """The alternatives this guard points contributors at must be importable."""- import hermes_constants-- assert callable(getattr(hermes_constants, helper))---def test_managed_uv_helpers_exist():- from pm import ensure, env_for, uv-- assert callable(uv)- assert callable(ensure)- assert callable(env_for)+def test_workspace_uv_accepts_developer_path_only_when_store_absent(monkeypatch):+ ensure = importlib.import_module("pm.ensure")+ monkeypatch.setattr(ensure, "uv", lambda **kwargs: (None, {}))+ monkeypatch.setattr(shutil, "which", lambda name: "developer/uv" if name == "uv" else None)+ assert _uv_binary() == "developer/uv"diff --git a/tests/test_model_tools_async_bridge.py b/tests/test_model_tools_async_bridge.pyindex 54fce36d2e1..e2e070712dc 100644--- a/tests/test_model_tools_async_bridge.py+++ b/tests/test_model_tools_async_bridge.py@@ -348,100 +348,23 @@ def _mock_vision_response():class TestVisionDispatchLoopSafety:- """Simulate the full registry.dispatch('vision_analyze') chain and- verify the event loop stays alive afterwards — the exact scenario- from issue #2104."""-- def test_vision_dispatch_keeps_loop_alive(self, tmp_path):- """After dispatching vision_analyze via the registry, the event- loop must remain open so cached async clients don't crash on GC."""- from model_tools import _get_tool_loop- from tools.registry import registry-- fake_response = _mock_vision_response()-- with (- patch(- "tools.vision_tools.async_call_llm",- new_callable=AsyncMock,- return_value=fake_response,- ),- patch(- "tools.vision_tools._download_image",- new_callable=AsyncMock,- side_effect=lambda url, dest, **kw: _write_fake_image(dest),- ),- patch(- "tools.vision_tools._validate_image_url_async",- new_callable=AsyncMock,- return_value=True,- ),- patch(- "tools.vision_tools._image_to_base64_data_url",- return_value="data:image/jpeg;base64,abc",- ),- ):- result_json = registry.dispatch(- "vision_analyze",- {"image_url": "https://example.com/cat.png", "question": "What is this?"},- )-- result = json.loads(result_json)- assert result.get("success") is True, f"dispatch failed: {result}"- assert "cat" in result.get("analysis", "").lower()-- loop = _get_tool_loop()- assert not loop.is_closed(), (- "Event loop closed after vision_analyze dispatch — cached async "- "clients will crash with 'Event loop is closed' (issue #2104)"- )-- def test_two_consecutive_vision_dispatches(self, tmp_path):- """Two back-to-back vision_analyze dispatches must both succeed- and share the same loop (simulates 'first call fails, second- works' from the issue report)."""+ def test_consecutive_image_dispatches_keep_the_loop_alive(self):+ import base64+ import io+ from PIL import Imagefrom model_tools import _get_tool_loopfrom tools.registry import registry- fake_response = _mock_vision_response()-- with (- patch(- "tools.vision_tools.async_call_llm",- new_callable=AsyncMock,- return_value=fake_response,- ),- patch(- "tools.vision_tools._download_image",- new_callable=AsyncMock,- side_effect=lambda url, dest, **kw: _write_fake_image(dest),- ),- patch(- "tools.vision_tools._validate_image_url_async",- new_callable=AsyncMock,- return_value=True,- ),- patch(- "tools.vision_tools._image_to_base64_data_url",- return_value="data:image/jpeg;base64,abc",- ),- ):- args = {"image_url": "https://example.com/cat.png", "question": "Describe"}-- r1 = json.loads(registry.dispatch("vision_analyze", args))- loop_after_first = _get_tool_loop()-- r2 = json.loads(registry.dispatch("vision_analyze", args))- loop_after_second = _get_tool_loop()-- assert r1.get("success") is True- assert r2.get("success") is True- assert loop_after_first is loop_after_second, "Loop changed between dispatches"- assert not loop_after_second.is_closed()---def _write_fake_image(dest):- """Write minimal bytes so vision_analyze_tool thinks download succeeded."""- dest.parent.mkdir(parents=True, exist_ok=True)- dest.write_bytes(b"\xff\xd8\xff" + b"\x00" * 16)- return dest+ image = io.BytesIO()+ Image.new("RGB", (8, 8), "blue").save(image, format="PNG")+ args = {"image_url": "data:image/png;base64," + base64.b64encode(image.getvalue()).decode(),+ "question": "Describe"}+ with patch("tools.vision_tools.async_call_llm", new_callable=AsyncMock,+ return_value=_mock_vision_response()):+ first = json.loads(registry.dispatch("vision_analyze", args))+ loop = _get_tool_loop()+ second = json.loads(registry.dispatch("vision_analyze", args))+ assert first.get("success") is True, first+ assert second.get("success") is True, second+ assert "cat" in first["analysis"].lower()+ assert _get_tool_loop() is loop and not loop.is_closed()diff --git a/tests/test_run_tests_parallel.py b/tests/test_run_tests_parallel.pyindex f83e9a55634..950f0dc9c3f 100644--- a/tests/test_run_tests_parallel.py+++ b/tests/test_run_tests_parallel.py@@ -21,6 +21,7 @@ POSIX-only: Windows has its own grandchild lifecycle (no shared session,from __future__ import annotationsimport json+import shutilimport osimport subprocessimport sys@@ -31,6 +32,13 @@ from pathlib import Pathimport pytest[email protected](autouse=True)+def isolated_probe_environment(monkeypatch):+ # Probe files exercise pytest/runner mechanics, not installed third-party+ # plugins. Autoloading the developer environment changes their startup cost.+ monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")++# Both tests share the same handoff file: the leaker writes here, the# verifier reads here. We park it in $TMPDIR with a unique-per-run name# so concurrent invocations of the suite don't clobber each other.@@ -42,6 +50,14 @@ def _handoff_path_for(nonce: str) -> Path:return _HANDOFF_DIR / f"grandchild-{nonce}.json"+def _probe_root(tmp_path):+ root = tmp_path / "runner-root"+ scripts = root / "scripts"+ scripts.mkdir(parents=True, exist_ok=True)+ shutil.copy2(Path(__file__).resolve().parents[1] / "scripts" / "run_tests_parallel.py", scripts)+ return root++def _pid_alive(pid: int) -> bool:"""POSIX: send signal 0 to probe whether ``pid`` is still alive.@@ -65,7 +81,7 @@ def _pid_alive(pid: int) -> bool:def test_progress_output_tolerates_legacy_stdout_encoding(tmp_path: Path) -> None:"""Progress glyphs must not crash the runner on non-UTF-8 consoles."""- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)runner = repo_root / "scripts" / "run_tests_parallel.py"probe_dir = tmp_path / "probe"@@ -87,7 +103,7 @@ def test_progress_output_tolerates_legacy_stdout_encoding(tmp_path: Path) -> Non"--file-timeout","30",],- cwd=repo_root,+ cwd=probe_dir,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,@@ -100,7 +116,7 @@ def test_progress_output_tolerates_legacy_stdout_encoding(tmp_path: Path) -> Nonassert "1 tests passed" in proc.stdout[email protected](sys.platform == "win32", reason="POSIX-only probe")[email protected]("posix")@pytest.mark.live_system_guard_bypassdef test_grandchild_leak_is_killed_by_runner(tmp_path: Path) -> None:"""Run the parallel runner over a probe file and verify cleanup.@@ -111,7 +127,7 @@ def test_grandchild_leak_is_killed_by_runner(tmp_path: Path) -> None:3. Wait for the grandchild PID to vanish (poll for ~5s).4. Assert the runner exited cleanly AND the grandchild is dead."""- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)runner = repo_root / "scripts" / "run_tests_parallel.py"assert runner.exists(), f"runner missing at {runner}"@@ -180,7 +196,7 @@ def test_grandchild_leak_is_killed_by_runner(tmp_path: Path) -> None:"--file-timeout","30",],- cwd=repo_root,+ cwd=probe_dir,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,# The runner declares its stdio UTF-8 (see _make_stdio_glyph_safe);@@ -253,12 +269,12 @@ def _make_probe_dir(tmp_path: Path) -> Path:def _run_runner(probe_dir: Path, *extra: str) -> subprocess.CompletedProcess:- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(probe_dir.parent)runner = repo_root / "scripts" / "run_tests_parallel.py"return subprocess.run([sys.executable, str(runner), "--paths", str(probe_dir),"-j", "1", "--file-timeout", "30", *extra],- cwd=repo_root,+ cwd=probe_dir,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,# The runner declares its stdio UTF-8 (see _make_stdio_glyph_safe);@@ -297,13 +313,13 @@ def test_bare_value_flag_keeps_its_value(tmp_path: Path) -> None:def test_positional_path_not_treated_as_flag(tmp_path: Path) -> None:"""A positional path arg still overrides discovery (not routed to pytest)."""probe_dir = _make_probe_dir(tmp_path)- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)runner = repo_root / "scripts" / "run_tests_parallel.py"# Pass the probe dir positionally (no --paths), plus a bare -q.proc = subprocess.run([sys.executable, str(runner), str(probe_dir), "-j", "1","--file-timeout", "30", "-q"],- cwd=repo_root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ cwd=probe_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,encoding="utf-8", errors="replace", timeout=60,)assert proc.returncode == 0, proc.stdout@@ -314,7 +330,7 @@ def test_positional_path_not_treated_as_flag(tmp_path: Path) -> None:def test_file_retry_self_heals_and_prints_both_attempts(tmp_path: Path) -> None:"""A pass-on-retry is green, loud, and retains the failing traceback."""- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)runner = repo_root / "scripts" / "run_tests_parallel.py"marker = tmp_path / "ran-once"probe = tmp_path / "test_flaky_probe.py"@@ -346,7 +362,7 @@ def test_file_retry_self_heals_and_prints_both_attempts(tmp_path: Path) -> None:"1","-q",],- cwd=repo_root,+ cwd=tmp_path,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,@@ -386,11 +402,11 @@ def test_node_id_selector_runs_the_named_test(tmp_path: Path) -> None:"""``file.py::test_alpha`` runs that test instead of discovering nothing."""probe_dir = _make_probe_dir(tmp_path)target = probe_dir / "test_flagprobe.py"- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)proc = subprocess.run([sys.executable, str(repo_root / "scripts" / "run_tests_parallel.py"),f"{target}::test_alpha", "-j", "1", "--file-timeout", "30"],- cwd=repo_root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ cwd=probe_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,text=True, timeout=60,)assert proc.returncode == 0, proc.stdout@@ -404,12 +420,12 @@ def test_explicit_k_wins_over_node_id_inference(tmp_path: Path) -> None:"""A caller's own ``-k`` is not overridden by the node-id translation."""probe_dir = _make_probe_dir(tmp_path)target = probe_dir / "test_flagprobe.py"- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)proc = subprocess.run([sys.executable, str(repo_root / "scripts" / "run_tests_parallel.py"),f"{target}::test_alpha", "-k", "test_beta","-j", "1", "--file-timeout", "30"],- cwd=repo_root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ cwd=probe_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,text=True, timeout=60,)# -k test_beta wins: one test ran, and it wasn't filtered to nothing.@@ -430,20 +446,20 @@ def test_multiple_absolute_paths_split_on_pathsep(tmp_path: Path) -> None:(dir_b / "test_flagprobe_b.py").write_text("def test_gamma():\n assert True\n")- repo_root = Path(__file__).resolve().parent.parent+ repo_root = _probe_root(tmp_path)runner = repo_root / "scripts" / "run_tests_parallel.py"proc = subprocess.run([sys.executable, str(runner),"--paths", os.pathsep.join([str(dir_a), str(dir_b)]),"-j", "1", "--file-timeout", "30", "-q"],- cwd=repo_root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ cwd=tmp_path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,encoding="utf-8", errors="replace", timeout=60,)assert proc.returncode == 0, proc.stdoutassert "Discovered 2 test files" in proc.stdout, proc.stdout[email protected](sys.platform != "win32", reason="drive-letter paths")[email protected]("windows")def test_drive_letter_colon_is_not_a_path_separator(tmp_path: Path) -> None:"""An absolute ``--paths`` value stays one root on Windows.diff --git a/tests/test_run_tests_parallel_stdio.py b/tests/test_run_tests_parallel_stdio.pyindex 2add57c3e25..d8de8f9d45f 100644--- a/tests/test_run_tests_parallel_stdio.py+++ b/tests/test_run_tests_parallel_stdio.py@@ -25,6 +25,18 @@ def _load_runner():return mod+def test_silent_child_failure_reports_exit_code(tmp_path, monkeypatch):+ from types import SimpleNamespace+ mod = _load_runner()+ child = SimpleNamespace(pid=123, returncode=23, communicate=lambda **kwargs: ("", None))+ monkeypatch.setattr(mod.subprocess, "Popen", lambda *args, **kwargs: child)+ monkeypatch.setattr(mod, "_kill_tree", lambda *args, **kwargs: None)+ _, code, output, counts, _ = mod._run_one_file_once(tmp_path / "test.py", [], tmp_path, 30)+ assert code == 23+ assert "23" in output and "no output" in output.lower()+ assert counts == {}++def _cp1252_stream() -> tuple[io.TextIOWrapper, io.BytesIO]:raw = io.BytesIO()return io.TextIOWrapper(raw, encoding="cp1252", errors="strict"), rawdiff --git a/tests/test_state_db_repair_live_writer_guard.py b/tests/test_state_db_repair_live_writer_guard.pyindex 4f0b477d463..3e0aeae73ea 100644--- a/tests/test_state_db_repair_live_writer_guard.py+++ b/tests/test_state_db_repair_live_writer_guard.py@@ -108,7 +108,7 @@ def test_repair_checks_foreign_holders_before_opening_sqlite(tmp_path, monkeypatassert "live writer" in (report["error"] or "").lower()[email protected]_only[email protected]("linux")def test_linux_holder_scan_does_not_require_psutil(tmp_path, monkeypatch):"""The Linux safety scan must not make psutil a repair dependency."""monkeypatch.setattr(hermes_state_holders, "psutil", None)@@ -120,7 +120,7 @@ def test_linux_holder_scan_does_not_require_psutil(tmp_path, monkeypatch):assert holders == [][email protected]_only[email protected]("linux")def test_incomplete_holder_scan_keeps_unknown_sentinel(tmp_path, monkeypatch):"""A partial scan must not hide uncertainty behind an ordinary holder."""db = tmp_path / "state.db"@@ -152,7 +152,7 @@ def test_incomplete_holder_scan_keeps_unknown_sentinel(tmp_path, monkeypatch):assert any(pid < 0 and "scan interrupted" in path for pid, path in holders)[email protected]_only[email protected]("linux")def test_uninspectable_watched_descriptor_blocks_repair_before_sqlite(tmp_path, monkeypatch):@@ -188,7 +188,7 @@ def test_uninspectable_watched_descriptor_blocks_repair_before_sqlite(assert "live writer" in (report["error"] or "").lower()[email protected]_only[email protected]("linux")@pytest.mark.parametrize(("argv", "should_block"),(@@ -252,7 +252,7 @@ def test_uninspectable_unknown_descriptor_uses_hermes_identity_at_repair_boundarassert "live writer" not in (report["error"] or "").lower()[email protected]_only[email protected]("linux")def test_uninspectable_watched_identity_blocks_alias_before_sqlite(tmp_path, monkeypatch):@@ -293,7 +293,7 @@ def test_uninspectable_watched_identity_blocks_alias_before_sqlite(assert "live writer" in (report["error"] or "").lower()[email protected]_only[email protected]("linux")def test_uninspectable_alias_descriptor_for_hermes_blocks_before_sqlite(tmp_path, monkeypatch):@@ -338,7 +338,7 @@ def test_uninspectable_alias_descriptor_for_hermes_blocks_before_sqlite(@pytest.mark.requires_wal[email protected]_only[email protected]("linux")def test_repair_refuses_while_foreign_process_holds_deleted_wal(tmp_path):"""Reproduce the inode split that a pathname lock probe cannot observe."""db = _make_wal_db(tmp_path)diff --git a/tests/test_wal_reset_repair_hint.py b/tests/test_wal_reset_repair_hint.pyindex c96b6498435..8d99e60358c 100644--- a/tests/test_wal_reset_repair_hint.py+++ b/tests/test_wal_reset_repair_hint.py@@ -7,7 +7,7 @@ installs get their steward's update command (#75153).from unittest.mock import patch-import hermes_state+import hermes_state_wal as hermes_statedef _hint_for(method):@@ -18,9 +18,7 @@ def _hint_for(method):def test_source_checkout_gets_venv_setup_hint():- assert _hint_for("source") == (- "source checkouts can repair the runtime by re-running their venv setup"- )+ assert _hint_for("source") == "CMD-source"def test_git_install_gets_hermes_managed_hint():diff --git a/tests/tools/test_browser_chromium_autoinstall.py b/tests/tools/test_browser_chromium_autoinstall.pyindex dea4d8957c0..a7fe4996382 100644--- a/tests/tools/test_browser_chromium_autoinstall.py+++ b/tests/tools/test_browser_chromium_autoinstall.py@@ -7,7 +7,6 @@ import pytestimport importlib-pm_ensure = importlib.import_module("pm.ensure")import tools.browser_tool as btfrom tools import browser_tool_install as bt_install@@ -29,8 +28,8 @@ def _no_subprocess(monkeypatch):class TestGating:def test_disabled_lazy_installs_skips(self, monkeypatch):- monkeypatch.setattr(bt, "_running_in_docker", lambda: False)- monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: False)+ monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)+ monkeypatch.setattr("pm.lazy_installs_allowed", lambda: False)calls = _no_subprocess(monkeypatch)assert bt_install._maybe_autoinstall_chromium() is Falseassert calls == []@@ -44,9 +43,9 @@ class TestGating:class TestInstall:def test_success_installs_binary_only_and_rechecks(self, monkeypatch):- monkeypatch.setattr(bt, "_running_in_docker", lambda: False)- monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)- monkeypatch.setattr(bt, "_find_agent_browser", lambda: "/x/agent-browser")+ monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)+ monkeypatch.setattr("pm.lazy_installs_allowed", lambda: True)+ monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda: "/x/agent-browser")monkeypatch.setattr(bt, "_build_browser_env", lambda: {})monkeypatch.setattr("tools.browser_tool_install._chromium_installed", lambda: True)@@ -63,9 +62,9 @@ class TestInstall:assert "--with-deps" not in captured["cmd"]def test_npx_form_is_binary_only(self, monkeypatch):- monkeypatch.setattr(bt, "_running_in_docker", lambda: False)- monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)- monkeypatch.setattr(bt, "_find_agent_browser", lambda: "npx agent-browser")+ monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)+ monkeypatch.setattr("pm.lazy_installs_allowed", lambda: True)+ monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda: "npx agent-browser")monkeypatch.setattr(bt, "_build_browser_env", lambda: {})monkeypatch.setattr("tools.browser_tool_install._chromium_installed", lambda: True)monkeypatch.setattr(shutil, "which", lambda _, path=None: "/usr/bin/npx")@@ -84,9 +83,9 @@ class TestInstall:assert "--with-deps" not in captured["cmd"]def test_nonzero_exit_returns_false(self, monkeypatch):- monkeypatch.setattr(bt, "_running_in_docker", lambda: False)- monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)- monkeypatch.setattr(bt, "_find_agent_browser", lambda: "/x/agent-browser")+ monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)+ monkeypatch.setattr("pm.lazy_installs_allowed", lambda: True)+ monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda: "/x/agent-browser")monkeypatch.setattr(bt, "_build_browser_env", lambda: {})monkeypatch.setattr(bt.subprocess, "run",@@ -97,9 +96,9 @@ class TestInstall:class TestOneShot:def test_second_call_does_not_reinstall(self, monkeypatch):- monkeypatch.setattr(bt, "_running_in_docker", lambda: False)- monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: True)- monkeypatch.setattr(bt, "_find_agent_browser", lambda: "/x/agent-browser")+ monkeypatch.setattr("tools.browser_tool_install._running_in_docker", lambda: False)+ monkeypatch.setattr("pm.lazy_installs_allowed", lambda: True)+ monkeypatch.setattr("tools.browser_tool_install._find_agent_browser", lambda: "/x/agent-browser")monkeypatch.setattr(bt, "_build_browser_env", lambda: {})monkeypatch.setattr("tools.browser_tool_install._chromium_installed", lambda: True)diff --git a/tests/tools/test_browser_chromium_check.py b/tests/tools/test_browser_chromium_check.pyindex 704f96cb354..17ca41045eb 100644--- a/tests/tools/test_browser_chromium_check.py+++ b/tests/tools/test_browser_chromium_check.py@@ -38,10 +38,11 @@ class TestChromiumSearchRoots:class TestChromiumInstalled:- def test_system_chromium_on_path_alone_is_not_enough(self, monkeypatch):+ def test_system_chromium_on_path_alone_is_not_enough(self, monkeypatch, tmp_path):"""Pinned-store-only (gap plan D3): a system Chromium in PATH doesNOT satisfy the check — only AGENT_BROWSER_EXECUTABLE_PATH or thepinned browser store do."""+ monkeypatch.setattr(bt_install, "_chromium_search_roots", lambda: [str(tmp_path)])monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)monkeypatch.setattr(shutil,@@ -49,14 +50,14 @@ class TestChromiumInstalled:lambda name, path=None: "/usr/bin/chromium" if name == "chromium" else None,)- assert bt._chromium_installed() is False+ assert bt_install._chromium_installed() is Falsedef test_true_when_agent_browser_executable_path_set(self, monkeypatch, tmp_path):exe = tmp_path / ("chrome.exe" if os.name == "nt" else "chrome")exe.write_bytes(b"")monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(exe))- assert bt._chromium_installed() is True+ assert bt_install._chromium_installed() is Truedef test_result_cached(self, monkeypatch, tmp_path):diff --git a/tests/tools/test_browser_lightpanda.py b/tests/tools/test_browser_lightpanda.pyindex ae33d520e51..77acb6fc96a 100644--- a/tests/tools/test_browser_lightpanda.py+++ b/tests/tools/test_browser_lightpanda.py@@ -439,7 +439,7 @@ class TestEngineOverride:patch("tools.interrupt.is_interrupted", return_value=False), \patch("tools.browser_tool_session._needs_chromium_sandbox_bypass", return_value=True), \patch("tools.browser_tool_lifecycle._write_owner_pid"), \- patch.dict(os.environ, {}, clear=True):+ patch.dict(os.environ, {}, clear=False):# AppArmor/root detection would normally auto-inject Chromium args.bt_session._run_browser_command("task1", "snapshot", [])diff --git a/tests/tools/test_browser_lightpanda_serve.py b/tests/tools/test_browser_lightpanda_serve.pyindex 259d4e2ec1e..e7c654f5ba4 100644--- a/tests/tools/test_browser_lightpanda_serve.py+++ b/tests/tools/test_browser_lightpanda_serve.py@@ -64,12 +64,14 @@ def _exe(path):class TestFindBinary:+ @pytest.mark.platforms("posix")def test_prefers_path(self, tmp_path, monkeypatch):exe = _exe(tmp_path / "bin" / "lightpanda")monkeypatch.setenv("PATH", str(tmp_path / "bin"))monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda p: p)assert lp.find_lightpanda_binary() == str(exe)+ @pytest.mark.platforms("posix")def test_falls_back_to_home_candidates(self, tmp_path, monkeypatch):monkeypatch.setenv("PATH", str(tmp_path / "empty"))monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda p: p)@@ -82,8 +84,8 @@ class TestFindBinary:monkeypatch.setattr("tools.browser_tool_install._merge_browser_path", lambda p: p)assert lp.find_lightpanda_binary() is None- def test_none_on_windows(self, monkeypatch):- monkeypatch.setattr(lp.os, "name", "nt")+ @pytest.mark.platforms("windows")+ def test_none_on_windows(self):assert lp.find_lightpanda_binary() is None@@ -107,6 +109,7 @@ class TestLaunch:server, err = lp.launch_lightpanda("lp_test", **kw)return server, err, calls+ @pytest.mark.platforms("posix")def test_missing_binary_returns_install_hint(self, monkeypatch):monkeypatch.setattr(lp, "find_lightpanda_binary", lambda: None)server, err = lp.launch_lightpanda("lp_test")diff --git a/tests/tools/test_browser_npx_warmup.py b/tests/tools/test_browser_npx_warmup.pyindex b11e82237c4..e0728c4f9d1 100644--- a/tests/tools/test_browser_npx_warmup.py+++ b/tests/tools/test_browser_npx_warmup.py@@ -16,6 +16,7 @@ npx PID — on timeout.from __future__ import annotationsimport subprocess+import pytestfrom unittest.mock import MagicMock, patchfrom tools.browser_tool import AGENT_BROWSER_NPX_SPECdiff --git a/tests/tools/test_browser_open_timeout.py b/tests/tools/test_browser_open_timeout.pyindex df0465f22e0..294dc7e8b88 100644--- a/tests/tools/test_browser_open_timeout.py+++ b/tests/tools/test_browser_open_timeout.py@@ -111,6 +111,7 @@ class TestCommandTimeoutRecovery:supervisor_events = []monkeypatch.setattr(bt_install, "_find_agent_browser", lambda: "agent-browser")+ monkeypatch.setattr(bt_install, "_chromium_installed", lambda: True)monkeypatch.setattr("tools.browser_tool_lifecycle._start_browser_cleanup_thread", lambda: None)monkeypatch.setattr("tools.browser_tool_cdp._ensure_cdp_supervisor", lambda _: supervisor_events.append("ensure"))monkeypatch.setattr("tools.browser_tool_cdp._stop_cdp_supervisor", lambda _: supervisor_events.append("stop"))diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.pyindex 32a2d61a458..80e4d75a630 100644--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@ -14,6 +14,7 @@ Covers the three seams the integration relies on:import jsonimport osimport stat+import shutilimport timeimport pytest@@ -51,6 +52,10 @@ def _fake_cli(tmp_path, body):script = tmp_path / "browser-use"script.write_text("#!/bin/sh\n" + body)script.chmod(script.stat().st_mode | stat.S_IXUSR)+ if os.name == "nt":+ wrapper = script.with_suffix(".cmd")+ wrapper.write_text(f'@"{shutil.which("bash")}" "{script.as_posix()}" %*\n')+ return str(wrapper)return str(script)diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.pyindex 67a098c47d2..9eb5951ab11 100644--- a/tests/tools/test_code_execution.py+++ b/tests/tools/test_code_execution.py@@ -51,6 +51,20 @@ from tools.code_execution_tool import (from tools.registry import registry[email protected](autouse=True)+def _fresh_kernel_registry():+ """Session kernels are always on: dispose them per-test so one test's+ kernel child can't outlive the run (hangs pytest at exit) or leak its+ interpreter state / task key into the next test. Per-file process+ isolation does not replace per-test kernel ownership.+ """+ from tools.code_kernel import shutdown_all_kernels++ shutdown_all_kernels()+ yield+ shutdown_all_kernels()++def _mock_handle_function_call(function_name, function_args, task_id=None, user_task=None):"""Mock dispatcher that returns canned responses for each tool."""if function_name == "terminal":@@ -175,9 +189,14 @@ class TestExecuteCodeRemoteTempDir(unittest.TestCase):self.assertEqual(result["exit_code"], 0)self.assertFalse(result["stdout_truncated"])self.assertEqual(result["stdout_bytes_total"], len("hello\n".encode("utf-8")))- mkdir_cmd = env.commands[1][0]+ # The session-kernel path runs first and fails open on this fake env+ # (no PID from nohup), so search for the per-call sandbox commands+ # rather than pinning positions.+ mkdir_cmd = next(cmd for cmd, _, _ in env.commands+ if "mkdir -p" in cmd and "hermes_exec_" in cmd)run_cmd = next(cmd for cmd, _, _ in env.commands if "python3 script.py" in cmd)- cleanup_cmd = env.commands[-1][0]+ cleanup_cmd = next(cmd for cmd, _, _ in env.commands+ if "rm -rf" in cmd and "hermes_exec_" in cmd)self.assertIn("mkdir -p /var/host/tmp/hermes_exec_", mkdir_cmd)self.assertIn("HERMES_RPC_DIR=/var/host/tmp/hermes_exec_", run_cmd)self.assertIn("rm -rf /var/host/tmp/hermes_exec_", cleanup_cmd)diff --git a/tests/tools/test_code_execution_modes.py b/tests/tools/test_code_execution_modes.pyindex ce349660251..ac1298b7f64 100644--- a/tests/tools/test_code_execution_modes.py+++ b/tests/tools/test_code_execution_modes.py@@ -16,6 +16,7 @@ import jsonimport osimport subprocessimport sys+import timeimport unittestimport unittest.mockfrom contextlib import contextmanager, ExitStack@@ -216,17 +217,10 @@ class TestModeAwareSchema(unittest.TestCase):# ---------------------------------------------------------------------------# Integration: what actually happens when execute_code runs per mode+# (host-neutral: strict tmpdir + venv interpreter resolve fine on Windows'+# Scripts/python.exe layout; no POSIX-only layout is asserted)# ---------------------------------------------------------------------------- sys.platform == "win32",- reason=(- "Assumes POSIX venv layout (bin/python) and symlink creation "- "privileges. execute_code itself works on Windows — these "- "integration tests just haven't been ported to the Scripts/"- "python.exe layout yet."- ),-)class TestExecuteCodeModeIntegration(unittest.TestCase):"""End-to-end: verify the subprocess actually runs where we expect."""@@ -286,8 +280,12 @@ class TestExecuteCodeModeIntegration(unittest.TestCase):This is the PYTHONPATH fix — without it, switching to session CWDbreaks `from hermes_tools import terminal`."""+ import shutilimport tempfile- with tempfile.TemporaryDirectory() as td:+ from tools.code_kernel import shutdown_all_kernels++ td = tempfile.mkdtemp(prefix="hermes_test_cwd_")+ try:code = ("from hermes_tools import terminal\n""r = terminal('echo x')\n"@@ -296,6 +294,18 @@ class TestExecuteCodeModeIntegration(unittest.TestCase):result = self._run(code, mode="project", extra_env={"TERMINAL_CWD": td})self.assertEqual(result["status"], "success")self.assertIn("mock", result["output"])+ finally:+ # Release the child's cwd even when an assertion failed.+ shutdown_all_kernels()+ deadline = time.monotonic() + 10+ while True:+ try:+ shutil.rmtree(td)+ break+ except (PermissionError, FileNotFoundError):+ if time.monotonic() >= deadline:+ raise+ time.sleep(0.2)def test_strict_mode_can_still_import_hermes_tools(self):"""Regression: strict mode's tmpdir CWD still works for imports."""@@ -315,17 +325,10 @@ class TestExecuteCodeModeIntegration(unittest.TestCase):# These MUST pass in both strict and project mode. The whole tiered-mode# proposition rests on the claim that switching from strict to project only# changes CWD + interpreter, not the security posture.+# Host-neutral: env scrubbing and whitelist enforcement run identically on+# Windows — nothing here depends on POSIX venv layout.# ---------------------------------------------------------------------------- sys.platform == "win32",- reason=(- "Assumes POSIX venv layout (bin/python) and symlink creation "- "privileges. execute_code itself works on Windows — these "- "integration tests just haven't been ported to the Scripts/"- "python.exe layout yet."- ),-)class TestSecurityInvariantsAcrossModes(unittest.TestCase):def _run(self, code, mode):diff --git a/tests/tools/test_code_kernel.py b/tests/tools/test_code_kernel.pyindex 6c3dc5e51fc..26427e98634 100644--- a/tests/tools/test_code_kernel.py+++ b/tests/tools/test_code_kernel.py@@ -1,18 +1,18 @@#!/usr/bin/env python3-"""Tests for execute_code's session kernel mode.+"""Tests for execute_code's session kernel.-``code_execution.kernel_mode: session`` keeps one Python child alive per-(task, mode, interpreter, cwd, tool-set) so state survives across calls.-These tests pin the contract:+Session kernels are always on (the ``code_execution.kernel_mode`` key is+retired): each (task, mode, interpreter, cwd, tool-set) owner keeps one+Python child alive so state survives across calls. These tests pin the+contract:- - default stays per-call (no state carries over unless opted in)- state persists across cells and reset=true discards it- a raised exception keeps the kernel (and its state) alive- a timeout kills the kernel; the next call gets a fresh one- fd-level output from user-spawned subprocesses reaches the result- sys.exit() inside a cell ends the kernel deliberately-Mode is sourced from ``code_execution.kernel_mode`` in config.yaml only;+Mode is sourced from ``code_execution.mode`` in config.yaml only;tests patch ``_load_config`` directly, mirroring test_code_execution_modes."""@@ -46,8 +46,10 @@ from tools.code_kernel import _KERNELS, shutdown_all_kernels@contextmanagerdef _kernel_config(**overrides):- """Pin code_execution config; strict mode keeps the test hermetic."""- config = {"mode": "strict", "kernel_mode": "session", "timeout": 30}+ """Pin code_execution config; strict mode keeps the test hermetic.+ ``mode`` (strict/project) is the only config knob — session kernels are+ always on; the retired ``kernel_mode`` key is ignored by the tool."""+ config = {"mode": "strict", "timeout": 30}config.update(overrides)with patch("tools.code_execution_tool._load_config", return_value=config):yield@@ -338,26 +340,42 @@ class TestKernelOwnershipAndLifecycle(unittest.TestCase):"""Parallel cells for one owner race the first spawn. Each racerused to see proc=None as 'dead', replace the registry entry, andorphan the winner's process — 110 live kernels under a 4-capped- process (Sep 2026). Every kernel process must stay registry-owned."""- import subprocess+ process (Sep 2026). Every kernel process must stay registry-owned.++ Capture actual children so an unregistered spawn cannot hide behind+ the registry count. The owned process must exit on teardown."""import threading+ spawned = []+ real_popen = subprocess.Popen++ def _capturing_popen(args, **kwargs):+ proc = real_popen(args, **kwargs)+ spawned.append((proc, list(args)))+ return proc+results = []- with _kernel_config():- def _cell():- results.append(self._run_as("conv-a", "import time; time.sleep(0.3)", task_id="t"))- threads = [threading.Thread(target=_cell) for _ in range(6)]- for t in threads:- t.start()- for t in threads:- t.join()+ with patch("tools.code_kernel.subprocess.Popen", side_effect=_capturing_popen):+ with _kernel_config():+ def _cell():+ results.append(self._run_as("conv-a", "import time; time.sleep(0.3)", task_id="t"))+ threads = [threading.Thread(target=_cell) for _ in range(6)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()self.assertEqual([r["status"] for r in results], ["success"] * 6)self.assertEqual(len(_KERNELS), 1)- live = subprocess.run(- ["pgrep", "-fc", "-P", str(os.getpid()), "hermes_kernel_runner"],- capture_output=True, text=True,- ).stdout.strip()- self.assertEqual(live, "1")+ runners = [proc for proc, args in spawned+ if len(args) == 2 and Path(args[1]).name == "hermes_kernel_runner.py"]+ self.assertEqual(len(runners), 1, "parallel cells spawned an unowned kernel")+ kernel = next(iter(_KERNELS.values()))+ self.assertIs(kernel.proc, runners[0])+ self.assertIsNone(kernel.proc.poll())+ shutdown_all_kernels()+ for proc in runners:+ proc.wait(timeout=10)+ self.assertIsNotNone(proc.returncode)class TestPerCellRpcAuthority(unittest.TestCase):diff --git a/tests/tools/test_credential_files.py b/tests/tools/test_credential_files.pyindex 20bc21e68eb..b2dbe867639 100644--- a/tests/tools/test_credential_files.py+++ b/tests/tools/test_credential_files.py@@ -113,6 +113,7 @@ class TestSkillsDirectoryMount:# Symlink should NOT be presentassert not (safe_path / "evil_link").exists()+ @pytest.mark.require_symlinksdef test_sanitized_copy_skips_bookkeeping_dirs(self, tmp_path):"""The symlink-safe copy is what gets mounted, so it must apply thesame EXCLUDED_SKILL_DIRS rule as the per-file sync path."""diff --git a/tests/tools/test_file_operations_delete.py b/tests/tools/test_file_operations_delete.pynew file mode 100644index 00000000000..87dc97d461c--- /dev/null+++ b/tests/tools/test_file_operations_delete.py@@ -0,0 +1,39 @@+"""Behavior tests for ``ShellFileOperations.delete_file`` (real LocalEnvironment shell).++delete_file's python snippet contract: a regular file is unlinked; a directory+is refused (``is a directory``), never silently removed — no recursive delete+exists on this interface.+"""++import pytest++from tools.environments.local import LocalEnvironment+from tools.file_operations import ShellFileOperations+++def ops(tmp_path):+ env = LocalEnvironment(cwd=str(tmp_path))+ return ShellFileOperations(env, cwd=str(tmp_path))+++def test_delete_file_removes_regular_file(ops, tmp_path):+ target = tmp_path / "doomed.txt"+ target.write_text("bye", encoding="utf-8")++ result = ops.delete_file(str(target))++ assert result.error is None+ assert not target.exists()+++def test_delete_file_refuses_directory(ops, tmp_path):+ target = tmp_path / "dir"+ target.mkdir()+ (target / "keep.txt").write_text("still here", encoding="utf-8")++ result = ops.delete_file(str(target))++ assert result.error is not None+ assert "is a directory" in result.error+ assert target.exists()diff --git a/tests/tools/test_file_ops_single_roundtrip.py b/tests/tools/test_file_ops_single_roundtrip.pyindex b7d3e95835d..8165f018bca 100644--- a/tests/tools/test_file_ops_single_roundtrip.py+++ b/tests/tools/test_file_ops_single_roundtrip.py@@ -192,7 +192,7 @@ class TestReadFileNonTextPaths:assert len(calls) == 1 and READ_PROBE_MARK not in calls[0]assert r.is_image is True and r.file_size == 6- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_fifo_returns_not_regular_without_blocking(self, shell, tmp_path):if not hasattr(os, "mkfifo"):pytest.skip("no mkfifo")@@ -323,7 +323,7 @@ class TestNativeRead:for c in calls:assert c == "echo $HOME" or c.startswith("ls -1 '~; echo PWNED"), c- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_fifo_refused_without_a_shell_and_without_blocking(self, native, tmp_path):if not hasattr(os, "mkfifo"):pytest.skip("no mkfifo")diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex d4f29080ec3..29d31af9a3a 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -11,6 +11,7 @@ See: https://github.com/NousResearch/hermes-agent/issues/1264import osimport subprocessimport sys+import tempfilefrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -49,14 +50,15 @@ def _run_with_env(extra_os_env=None, self_env=None):and return the env dict passed to the subprocess."""captured = {}test_environ = {- "PATH": "/usr/bin:/bin",+ **os.environ,+ "PATH": os.environ.get("PATH", ""),"HOME": "/home/user","USER": "testuser",}if extra_os_env:test_environ.update(extra_os_env)- env = LocalEnvironment(cwd="/tmp", timeout=10, env=self_env)+ env = LocalEnvironment(cwd=tempfile.gettempdir(), timeout=10, env=self_env)with patch("tools.environments.local._find_bash", return_value="/bin/bash"), \patch("subprocess.Popen", side_effect=_make_fake_popen(captured)), \@@ -836,17 +838,17 @@ class TestPythonpathSelectiveStrip:# pm bundled-install layout: store + manifest + relocatable venv.payload = tmp_path / "payload"store = payload / "tools"- runtime_venv = payload / "venv"- runtime_sp = local._runtime_venv_site_packages(runtime_venv)+ runtime_venv = payload / "state" / "environments" / "candidate" / "venv"+ runtime_sp = __import__("hermes_cli.runtime_paths", fromlist=["site_packages"]).site_packages(runtime_venv)runtime_sp.mkdir(parents=True)store.mkdir(parents=True, exist_ok=True)(payload / "manifest.json").write_text("{}", encoding="utf-8")- (store / "facts.json").write_text(- json.dumps(- {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}- ),- encoding="utf-8",- )+ from hermes_cli.runtime_paths import runtime_facts_path+ monkeypatch.setattr("hermes_cli.runtime_paths.install_state_dir", lambda repo: payload / "state")+ facts = runtime_facts_path(Path(local.__file__).resolve().parents[2])+ facts.parent.mkdir(parents=True, exist_ok=True)+ (runtime_venv / "pyvenv.cfg").write_text("version = 3.11\n")+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(runtime_venv)}}}))monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))monkeypatch.delenv("VIRTUAL_ENV", raising=False)@@ -920,7 +922,7 @@ class TestPythonpathSelectiveStrip:"HOME": "/home/user","PYTHONPATH": os.pathsep.join([venv_sp, "/home/user/my-lib"]),}- with patch.dict(os.environ, seed, clear=True):+ with patch.dict(os.environ, seed, clear=False):if builder == "_make_run_env":result = local_mod._make_run_env({})elif builder == "_sanitize_subprocess_env":@@ -992,6 +994,7 @@ class TestPythonpathSelectiveStrip:captured["staging"] = os.path.dirname(cmd[1])proc = MagicMock()proc.stdout.read.return_value = b""+ proc.stdout.read1.return_value = b""proc.stderr.read.return_value = b""proc.wait.return_value = 0proc.returncode = 0@@ -1267,22 +1270,22 @@ class TestPythonpathSelectiveStrip:# pm bundled-install layout, entirely outside the repo aliases.payload = tmp_path / "payload"store = payload / "tools"- venv_dir = payload / "venv"- venv_sp = local._runtime_venv_site_packages(venv_dir)+ venv_dir = payload / "state" / "environments" / "candidate" / "venv"+ venv_sp = __import__("hermes_cli.runtime_paths", fromlist=["site_packages"]).site_packages(venv_dir)venv_sp.mkdir(parents=True)store.mkdir(parents=True, exist_ok=True)(payload / "manifest.json").write_text("{}", encoding="utf-8")- (store / "facts.json").write_text(- json.dumps(- {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}- ),- encoding="utf-8",- )+ from hermes_cli.runtime_paths import runtime_facts_path+ monkeypatch.setattr("hermes_cli.runtime_paths.install_state_dir", lambda repo: payload / "state")+ facts = runtime_facts_path(Path(local.__file__).resolve().parents[2])+ facts.parent.mkdir(parents=True, exist_ok=True)+ (venv_dir / "pyvenv.cfg").write_text("version = 3.11\n")+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(venv_dir)}}}))monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))- validated = local._validated_runtime_venv({"VIRTUAL_ENV": "/somewhere/else"})+ validated = local_pythonpath._validated_runtime_venv({"VIRTUAL_ENV": "/somewhere/else"})assert validated is not None- assert local._same_path(validated, venv_dir)+ assert local_pythonpath._same_path(validated, venv_dir)monkeypatch.setattr(local, "_hermes_site_packages", None)monkeypatch.setattr(local, "_in_venv", False)@@ -1290,7 +1293,7 @@ class TestPythonpathSelectiveStrip:str(venv_sp),"/home/user/my-lib",])}- local._strip_hermes_owned_pythonpath(env)+ local_pythonpath._strip_hermes_owned_pythonpath(env)assert env["PYTHONPATH"].split(os.pathsep) == ["/home/user/my-lib"]diff --git a/tests/tools/test_local_temp_dir.py b/tests/tools/test_local_temp_dir.pyindex c0e79a1d20c..bc08077f7bb 100644--- a/tests/tools/test_local_temp_dir.py+++ b/tests/tools/test_local_temp_dir.py@@ -7,6 +7,7 @@ logs/pid/exit files, code-execution sandboxes) at real storage.import osimport sys+from pathlib import Pathimport pytest@@ -23,7 +24,7 @@ def _make_local_env(env: dict) -> LocalEnvironment:def test_temp_dir_override_honored(tmp_path):target = str(tmp_path)env = _make_local_env({"TERMINAL_TEMP_DIR": target})- assert env.get_temp_dir() == target+ assert Path(env.get_temp_dir()) == Path(target)def test_temp_dir_from_process_env(tmp_path):@@ -32,7 +33,7 @@ def test_temp_dir_from_process_env(tmp_path):prev = os.environ.get("TERMINAL_TEMP_DIR")os.environ["TERMINAL_TEMP_DIR"] = targettry:- assert env.get_temp_dir() == target+ assert Path(env.get_temp_dir()) == Path(target)finally:if prev is None:os.environ.pop("TERMINAL_TEMP_DIR", None)@@ -53,7 +54,7 @@ def test_temp_dir_empty_falls_through(tmp_path, monkeypatch):"""An empty/relative terminal.temp_dir must not redirect."""monkeypatch.setenv("TMPDIR", str(tmp_path))env = _make_local_env({"TERMINAL_TEMP_DIR": ""})- assert env.get_temp_dir() == str(tmp_path)+ assert Path(env.get_temp_dir()) == tmp_pathdef test_default_is_hermes_cache_not_tmp(tmp_path, monkeypatch):@@ -66,7 +67,7 @@ def test_default_is_hermes_cache_not_tmp(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))env = _make_local_env({})result = env.get_temp_dir()- assert result == str(tmp_path / ".hermes" / "cache" / "terminal")+ assert Path(result) == tmp_path / ".hermes" / "cache" / "terminal"assert os.path.isdir(result)@@ -75,7 +76,7 @@ def test_tmpdir_still_beats_default(tmp_path, monkeypatch):monkeypatch.delenv("TERMINAL_TEMP_DIR", raising=False)monkeypatch.setenv("TMPDIR", str(tmp_path))env = _make_local_env({})- assert env.get_temp_dir() == str(tmp_path)+ assert Path(env.get_temp_dir()) == tmp_pathdef test_cleanup_terminal_temp_cache(tmp_path, monkeypatch):diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.pyindex 60c56038585..dbc7be012c3 100644--- a/tests/tools/test_macos_protected_search.py+++ b/tests/tools/test_macos_protected_search.py@@ -1,6 +1,7 @@"""macOS TCC-safe behavior for broad file searches."""import re+import pytestfrom pathlib import Pathimport tools.file_operations as file_operations@@ -75,13 +76,13 @@ def test_non_macos_search_has_no_implicit_exclusions(tmp_path):assert exclusions == [][email protected]("macos")def test_broad_file_search_passes_protected_globs_to_ripgrep(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"home.mkdir(parents=True)env = RecordingEnvironment(home)ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")result = ops.search("*.txt", path=str(home), target="files")@@ -92,13 +93,13 @@ def test_broad_file_search_passes_protected_globs_to_ripgrep(tmp_path, monkeypatassert "macOS protected folders" in result.warning[email protected]("macos")def test_broad_content_search_passes_protected_globs_to_ripgrep(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"home.mkdir(parents=True)env = RecordingEnvironment(home)ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")ops.search("needle", path=str(home), target="content")@@ -107,13 +108,13 @@ def test_broad_content_search_passes_protected_globs_to_ripgrep(tmp_path, monkeyassert f"!{dirname}/**" in rg_command[email protected]("macos")def test_empty_ripgrep_file_search_is_one_scan_with_protected_globs(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"home.mkdir(parents=True)env = RecordingEnvironment(home)ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")ops.search("*.txt", path=str(home), target="files")@@ -123,6 +124,7 @@ def test_empty_ripgrep_file_search_is_one_scan_with_protected_globs(tmp_path, moassert "!Downloads/**" in command[email protected]("macos")def test_grep_fallback_prunes_by_path_not_basename(tmp_path, monkeypatch):"""The grep fallback must NOT use --exclude-dir (basename-wide: it wouldskip every nested dir named Downloads anywhere under the root). It routes@@ -132,7 +134,6 @@ def test_grep_fallback_prunes_by_path_not_basename(tmp_path, monkeypatch):env = RecordingEnvironment(home)ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")monkeypatch.setattr(ops, "_has_command", lambda command: command == "grep")ops.search("needle", path=str(home), target="content")@@ -146,6 +147,7 @@ def test_grep_fallback_prunes_by_path_not_basename(tmp_path, monkeypatch):assert f"--exclude-dir='{dirname}'" not in pruned_command[email protected]("macos")def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypatch):"""A repo-internal directory literally named 'Downloads' must still besearched by the pruned grep path — the exact regression --exclude-dir had."""@@ -157,7 +159,6 @@ def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypprotected.mkdir()(protected / "secret.txt").write_text("needle protected\n")monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")ops = ShellFileOperations(LocalEnvironment(cwd=str(home)))monkeypatch.setattr(ops, "_has_command", lambda command: command == "grep")@@ -168,6 +169,7 @@ def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypassert not any(str(protected / "secret.txt") in p for p in matched_paths)[email protected]("macos")def test_remote_backend_never_prunes(tmp_path, monkeypatch):"""Non-local environments get no exclusions: platform facts describe thecontroller, not the execution host (macOS controller + Linux SSH backend@@ -178,7 +180,6 @@ def test_remote_backend_never_prunes(tmp_path, monkeypatch):env.is_local = False # remote/container-shaped backendops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")result = ops.search("*.txt", path=str(home), target="files")@@ -187,13 +188,13 @@ def test_remote_backend_never_prunes(tmp_path, monkeypatch):assert result.warning is None[email protected]("macos")def test_find_fallback_prunes_protected_directories(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"home.mkdir(parents=True)env = RecordingEnvironment(home)ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")monkeypatch.setattr(ops, "_has_command", lambda command: command == "find")ops.search("*.txt", path=str(home), target="files")@@ -212,7 +213,6 @@ def _multi_root_protected_search(tmp_path, monkeypatch, engine):env = RecordingEnvironment(home)ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")monkeypatch.setattr(ops, "_has_command", lambda command: command == engine)path_checks = 0@@ -232,6 +232,7 @@ def _multi_root_protected_search(tmp_path, monkeypatch, engine):return ops, env, result, downloads[email protected]("macos")def test_rg_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(tmp_path, monkeypatch):@@ -254,6 +255,7 @@ def test_rg_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(assert "Downloads" not in protected_warning[email protected]("macos")def test_find_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(tmp_path, monkeypatch):@@ -271,11 +273,11 @@ def test_find_multi_root_keeps_explicit_protected_root_and_reports_actual_skips(assert "Downloads" not in protected_warning[email protected]("macos")def test_rg_multi_root_scopes_protected_globs_and_restores_absolute_paths(monkeypatch):env = RecordingEnvironment("/")ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", "/Users/alice")- monkeypatch.setattr(file_operations.sys, "platform", "darwin")def execute(command, cwd=None, **kwargs):env.commands.append(command)@@ -312,11 +314,11 @@ def test_rg_multi_root_scopes_protected_globs_and_restores_absolute_paths(monkey][email protected]("macos")def test_rg_scoped_multi_root_handles_dot_spaces_and_overlapping_roots(monkeypatch):env = RecordingEnvironment("/Users/alice/work space")ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", "/Users/alice")- monkeypatch.setattr(file_operations.sys, "platform", "darwin")def execute(command, cwd=None, **kwargs):env.commands.append(command)@@ -339,11 +341,11 @@ def test_rg_scoped_multi_root_handles_dot_spaces_and_overlapping_roots(monkeypatassert result.files == ["/Users/alice/work space/local.txt"][email protected]("macos")def test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monkeypatch):env = RecordingEnvironment("/Users/alice")ops = ShellFileOperations(env)monkeypatch.setattr(file_operations, "_HOME", "/Users/alice")- monkeypatch.setattr(file_operations.sys, "platform", "darwin")def execute(command, cwd=None, **kwargs):env.commands.append(command)@@ -365,6 +367,7 @@ def test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monkeassert result.error is None[email protected]("macos")def test_real_ripgrep_does_not_descend_into_protected_folder(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"safe = home / "safe"@@ -374,7 +377,6 @@ def test_real_ripgrep_does_not_descend_into_protected_folder(tmp_path, monkeypat(safe / "visible.txt").write_text("needle")(protected / "protected.txt").write_text("needle")monkeypatch.setattr(file_operations, "_HOME", str(home))- monkeypatch.setattr(file_operations.sys, "platform", "darwin")ops = ShellFileOperations(LocalEnvironment(cwd=str(home)))result = ops.search("needle", path=str(home), target="content")diff --git a/tests/tools/test_mcp_npx_cached_bin.py b/tests/tools/test_mcp_npx_cached_bin.pyindex 1773688e905..d3f27cec00a 100644--- a/tests/tools/test_mcp_npx_cached_bin.py+++ b/tests/tools/test_mcp_npx_cached_bin.py@@ -18,7 +18,7 @@ import osimport pytest-from tools.mcp_tool import _npx_cached_bin+from tools.mcp_tool_config import _npx_cached_bindef _cache(tmp_path, *, package, deps=None, bin_field, make_bin=True, entry="abc123"):@@ -36,6 +36,8 @@ def _cache(tmp_path, *, package, deps=None, bin_field, make_bin=True, entry="abcbindir.mkdir(parents=True, exist_ok=True)name = bin_field if isinstance(bin_field, str) else list(bin_field)[0]target = bindir / (os.path.basename(package) if isinstance(bin_field, str) else name)+ if os.name == "nt":+ target = target.with_suffix(".cmd")if make_bin:target.write_text("#!/usr/bin/env node\n", encoding="utf-8")target.chmod(0o755)@@ -188,12 +190,13 @@ def test_windows_selects_launchers_never_the_sh_script():from tools.mcp_tool_config import _npx_bin_candidateswin = _npx_bin_candidates("/c/bin", "mcp-linear", windows=True)- assert win == ["/c/bin/mcp-linear.cmd", "/c/bin/mcp-linear.exe"]+ assert win == [os.path.join("/c/bin", "mcp-linear.cmd"), os.path.join("/c/bin", "mcp-linear.exe")]assert not any(c.endswith("mcp-linear") for c in win), "sh script must not be a candidate"- assert _npx_bin_candidates("/bin", "mcp-linear", windows=False) == ["/bin/mcp-linear"]+ assert _npx_bin_candidates("/bin", "mcp-linear", windows=False) == [os.path.join("/bin", "mcp-linear")][email protected]("posix")def test_posix_resolution_uses_the_helper(tmp_path):"""The resolver honours the helper's ordering (POSIX path end-to-end)."""target = _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "i.js"})diff --git a/tests/tools/test_modal_snapshot_isolation.py b/tests/tools/test_modal_snapshot_isolation.pyindex d6d20e69273..90b387f76a5 100644--- a/tests/tools/test_modal_snapshot_isolation.py+++ b/tests/tools/test_modal_snapshot_isolation.py@@ -197,13 +197,14 @@ def _install_modal_test_modules(}-def test_modal_environment_migrates_legacy_snapshot_key_and_uses_snapshot_id(tmp_path):+def test_modal_environment_migrates_legacy_snapshot_key_and_uses_snapshot_id(tmp_path, monkeypatch):state = _install_modal_test_modules(tmp_path)snapshot_store = state["snapshot_store"]snapshot_store.parent.mkdir(parents=True, exist_ok=True)snapshot_store.write_text(json.dumps({"task-legacy": "im-legacy123"}))modal_module = _load_module("tools.environments.modal", TOOLS_DIR / "environments" / "modal.py")+ monkeypatch.setattr(modal_module, "ensure_lazy_dep", lambda extra: None)env = modal_module.ModalEnvironment(image="python:3.11", task_id="task-legacy")try:diff --git a/tests/tools/test_read_special_file_guard.py b/tests/tools/test_read_special_file_guard.pyindex 9550a8f0d24..2e243106569 100644--- a/tests/tools/test_read_special_file_guard.py+++ b/tests/tools/test_read_special_file_guard.py@@ -50,6 +50,7 @@ class TestSpecialFileKind:link.symlink_to(fifo)assert "FIFO" in (_special_file_kind(link) or "")+ @pytest.mark.platforms("posix")def test_char_device(self):if not os.path.exists("/dev/null"):pytest.skip("no /dev/null")diff --git a/tests/tools/test_search_files_cpu_windows.py b/tests/tools/test_search_files_cpu_windows.pyindex 8839e72a53f..f91cb906d9d 100644--- a/tests/tools/test_search_files_cpu_windows.py+++ b/tests/tools/test_search_files_cpu_windows.py@@ -288,7 +288,7 @@ def test_remote_roots_are_normalized_lexically_against_backend_cwd(monkeypatch):assert absolute == relative[email protected]_only[email protected]("windows")def test_windows_local_root_spellings_share_one_normalized_key():env = LocalEnvironment.__new__(LocalEnvironment)env.cwd = "C:/Repo"diff --git a/tests/tools/test_search_files_engine_selection.py b/tests/tools/test_search_files_engine_selection.pyindex 72e9100f847..abe7db012f3 100644--- a/tests/tools/test_search_files_engine_selection.py+++ b/tests/tools/test_search_files_engine_selection.py@@ -350,7 +350,7 @@ def test_non_rg_command_cache_keeps_cached_misses_and_bool_values():assert len([c for c in env.commands if c.startswith("command -v find")]) == 1[email protected]_only[email protected]("windows")def test_off_path_windows_rg_miss_is_reprobed_then_success_is_cached(tmp_path, monkeypatch):@@ -395,7 +395,7 @@ def test_remote_resolution_never_probes_controller_host_paths(tmp_path, monkeypaassert str(tmp_path) not in env.commands[0][email protected]_only[email protected]("windows")def test_remote_msys_shaped_executable_is_not_rewritten_as_controller_path():env = RecordingEnvironment()@@ -418,7 +418,7 @@ def test_remote_msys_shaped_executable_is_not_rewritten_as_controller_path():assert "C:/remote-tools/rg" not in env.rg_commands[0][email protected]_only[email protected]("windows")def test_every_windows_drive_root_is_broad_even_when_home_is_on_another_drive(tmp_path, monkeypatch):diff --git a/tests/tools/test_self_repo_guard.py b/tests/tools/test_self_repo_guard.pyindex 2583bc2237d..1b0c5345543 100644--- a/tests/tools/test_self_repo_guard.py+++ b/tests/tools/test_self_repo_guard.py@@ -55,11 +55,11 @@ class TestBlocksMutationsInSourceRepo:assert hit is Truedef test_dash_c_targeting_repo_from_outside(self, repo, tmp_path):- hit, _ = _detect(f"git -C {repo} checkout pr-51020", tmp_path, repo)+ hit, _ = _detect(f"git -C {repo.as_posix()} checkout pr-51020", tmp_path, repo)assert hit is Truedef test_cd_into_repo_then_checkout(self, repo, tmp_path):- hit, _ = _detect(f"cd {repo} && git checkout pr-51020", tmp_path, repo)+ hit, _ = _detect(f"cd {repo.as_posix()} && git checkout pr-51020", tmp_path, repo)assert hit is Truedef test_relative_cd_into_repo(self, repo):@@ -105,12 +105,12 @@ class TestBlocksMutationsInSourceRepo:assert hit is Truedef test_explicit_work_tree_targeting_repo(self, repo, tmp_path):- command = f"git --git-dir={repo / '.git'} --work-tree={repo} checkout main"+ command = f"git --git-dir={(repo / '.git').as_posix()} --work-tree={repo.as_posix()} checkout main"hit, _ = _detect(command, tmp_path, repo)assert hit is Truedef test_git_environment_targeting_repo(self, repo, tmp_path):- command = f"GIT_DIR={repo / '.git'} GIT_WORK_TREE={repo} git checkout main"+ command = f"GIT_DIR={(repo / '.git').as_posix()} GIT_WORK_TREE={repo.as_posix()} git checkout main"hit, _ = _detect(command, tmp_path, repo)assert hit is True@@ -193,15 +193,15 @@ class TestAllowsSafeCommands:assert hit is Falsedef test_dash_c_redirects_out_of_repo(self, repo, tmp_path):- hit, _ = _detect(f"git -C {tmp_path} checkout main", repo, repo)+ hit, _ = _detect(f"git -C {tmp_path.as_posix()} checkout main", repo, repo)assert hit is Falsedef test_cd_out_of_repo_then_checkout(self, repo, tmp_path):- hit, _ = _detect(f"cd {tmp_path} && git checkout main", repo, repo)+ hit, _ = _detect(f"cd {tmp_path.as_posix()} && git checkout main", repo, repo)assert hit is Falsedef test_mentioning_repo_path_without_targeting_it(self, repo, tmp_path):- hit, _ = _detect(f"echo {repo} && git checkout main", tmp_path, repo)+ hit, _ = _detect(f"echo {repo.as_posix()} && git checkout main", tmp_path, repo)assert hit is Falsedef test_checkout_as_grep_pattern_not_git(self, repo):@@ -236,17 +236,17 @@ class TestAllowsSafeCommands:assert hit is Falsedef test_subshell_cd_does_not_leak(self, repo):- command = f"(cd {repo} && git status); git checkout main"+ command = f"(cd {repo.as_posix()} && git status); git checkout main"hit, _ = _detect(command, repo.parent, repo)assert hit is Falsedef test_pipeline_cd_does_not_leak(self, repo):- command = f"cd {repo} | cat; git checkout main"+ command = f"cd {repo.as_posix()} | cat; git checkout main"hit, _ = _detect(command, repo.parent, repo)assert hit is Falsedef test_successful_cd_or_branch_does_not_run(self, repo):- command = f"cd {repo} || git checkout main"+ command = f"cd {repo.as_posix()} || git checkout main"hit, _ = _detect(command, repo.parent, repo)assert hit is False@@ -283,16 +283,16 @@ class TestWorktreeTargetingSourceRoot:@pytest.mark.parametrize("action", ["remove", "remove -f", "remove --force"])def test_blocks_absolute_target_from_outside(self, repo, tmp_path, action):- hit, _ = _detect(f"git worktree {action} {repo}", tmp_path, repo)+ hit, _ = _detect(f"git worktree {action} {repo.as_posix()}", tmp_path, repo)assert hit is Truedef test_blocks_move_of_root_from_outside(self, repo, tmp_path):- command = f"git worktree move {repo} {tmp_path / 'moved'}"+ command = f"git worktree move {repo.as_posix()} {tmp_path / 'moved'}"hit, _ = _detect(command, tmp_path, repo)assert hit is Truedef test_blocks_dash_c_worktree_remove(self, repo, tmp_path):- hit, _ = _detect(f"git -C {tmp_path} worktree remove {repo}", tmp_path, repo)+ hit, _ = _detect(f"git -C {tmp_path.as_posix()} worktree remove {repo.as_posix()}", tmp_path, repo)assert hit is Truedef test_blocks_parent_relative_target_from_subdirectory(self, repo):diff --git a/tests/tools/test_skill_bundle_provenance.py b/tests/tools/test_skill_bundle_provenance.pyindex 409554500c7..47b52d4ab3a 100644--- a/tests/tools/test_skill_bundle_provenance.py+++ b/tests/tools/test_skill_bundle_provenance.py@@ -62,7 +62,7 @@ def served_repo(tmp_path, monkeypatch):if isinstance(content, bytes):path.write_bytes(content)else:- path.write_text(content)+ path.write_text(content, newline="\n")subprocess.run(["git", "init", "-q"], cwd=repo, check=True)subprocess.run(["git", "add", "."], cwd=repo, check=True)subprocess.run(@@ -120,8 +120,8 @@ def test_same_dir_linked_siblings_are_fetched(served_repo, monkeypatch):"""#96310: explicitly linked same-skill-directory files must ship in thebundle — dropping them made installs "succeed" with unresolved links."""repo, url = served_repo- (repo / "CONTEXT-FORMAT.md").write_text("format\n")- (repo / "DEEPENING.md").write_text("deepening\n")+ (repo / "CONTEXT-FORMAT.md").write_text("format\n", newline="\n")+ (repo / "DEEPENING.md").write_text("deepening\n", newline="\n")(repo / "SKILL.md").write_text(SKILL_MD + "See [the format](./CONTEXT-FORMAT.md) and [deepening](DEEPENING.md).\n")monkeypatch.setattr("tools.skills_hub.is_safe_url", lambda _url: True)monkeypatch.setattr("tools.skills_hub.check_website_access", lambda _url: None)@@ -451,7 +451,7 @@ def served_repo_missing_support(tmp_path, monkeypatch):}.items():path = repo / relpath.parent.mkdir(parents=True, exist_ok=True)- path.write_text(content)+ path.write_text(content, newline="\n")server = ThreadingHTTPServer(("127.0.0.1", 0), partial(_QuietHandler, directory=str(repo))diff --git a/tests/tools/test_skill_ledger.py b/tests/tools/test_skill_ledger.pyindex 408b0c7b678..4287414c697 100644--- a/tests/tools/test_skill_ledger.py+++ b/tests/tools/test_skill_ledger.py@@ -511,7 +511,7 @@ def test_backup_fill_does_not_clobber_disk_hash(ledger_env):skill_dir.mkdir()skill_md = skill_dir / "SKILL.md"live = VALID_SKILL_CONTENT.replace("Original body.", "Live body.")- skill_md.write_text(live, encoding="utf-8")+ skill_md.write_text(live, encoding="utf-8", newline="\n")_write_skills_tarball(ledger_env["home"],{@@ -553,7 +553,7 @@ def test_backup_fill_ignores_tar_path_traversal(ledger_env):captured = skill_ledger.snapshot_paths(skill_dir, complete_package=True)paths = [i["path"] for i in captured]# The legitimate missing file WAS filled — proof the fill is live.- assert any(p.endswith("references/legit.md") for p in paths), (+ assert any(Path(p).as_posix().endswith("references/legit.md") for p in paths), ("package fill did not restore the missing support file")# Malicious members are not.diff --git a/tests/tools/test_tts_lifecycle_leases.py b/tests/tools/test_tts_lifecycle_leases.pyindex 41a75c04da0..79155e23166 100644--- a/tests/tools/test_tts_lifecycle_leases.py+++ b/tests/tools/test_tts_lifecycle_leases.py@@ -9,6 +9,8 @@ resident local models.from __future__ import annotations+import shlex+import subprocessimport threadingimport pytest@@ -116,30 +118,27 @@ def test_warm_is_noop_for_cloud_provider_without_lazy_sdk(monkeypatch):def test_warm_lazy_sdk_provider_reports_cached_when_installed(monkeypatch):- import types+ import pm- fake = types.SimpleNamespace(- is_available=lambda feature: feature == "tts.edge",- ensure=lambda *a, **k: pytest.fail("ensure must not run when the SDK is present"),+ monkeypatch.setattr(pm, "available", lambda extra: extra == "edge-tts")+ monkeypatch.setattr(+ pm, "ensure_import",+ lambda *a, **k: pytest.fail("ensure_import must not run when the SDK is present"),)- monkeypatch.setitem(__import__("sys").modules, "tools.lazy_deps", fake)result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})assert result["warmed"] is Trueassert result["action"] == "cached"def test_warm_lazy_sdk_provider_installs_when_missing(monkeypatch):- import types+ import pmcalls = []- fake = types.SimpleNamespace(- is_available=lambda feature: False,- ensure=lambda feature, prompt: calls.append((feature, prompt)),- )- monkeypatch.setitem(__import__("sys").modules, "tools.lazy_deps", fake)+ monkeypatch.setattr(pm, "available", lambda extra: False)+ monkeypatch.setattr(pm, "ensure_import", lambda extra: calls.append(extra))result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})assert result["action"] == "installed"- assert calls == [("tts.edge", False)]+ assert calls == ["edge-tts"]# --------------------------------------------------------------------------@@ -278,6 +277,8 @@ def test_plugin_provider_warm_and_release_follow_the_lease(monkeypatch):def test_command_provider_runs_warm_and_release_commands(monkeypatch):+ import os+ran: list = []done = threading.Event()@@ -302,4 +303,9 @@ def test_command_provider_runs_warm_and_release_commands(monkeypatch):done.clear()tts_tool_lifecycle.release_tts_lease("desktop:read-aloud")assert done.wait(5)- assert ran == ["curl -s localhost:5002/load?model='kokoro v1'", "curl -s localhost:5002/unload"]+ # The {model} placeholder is unquoted in the template, so the renderer+ # shell-quotes it for the host platform (list2cmdline on Windows,+ # shlex.quote elsewhere) — compute the expectation the same way.+ quote = subprocess.list2cmdline([cfg["providers"]["srv"]["model"]]) if os.name == "nt" \+ else shlex.quote(cfg["providers"]["srv"]["model"])+ assert ran == [f"curl -s localhost:5002/load?model={quote}", "curl -s localhost:5002/unload"]diff --git a/tests/tools/test_voice_cli_integration.py b/tests/tools/test_voice_cli_integration.pyindex d0ed71d1ed6..84eab1f8053 100644--- a/tests/tools/test_voice_cli_integration.py+++ b/tests/tools/test_voice_cli_integration.py@@ -600,7 +600,7 @@ class TestVoiceFullDuplexListener:lambda path, model=None: {"success": True, "transcript": "stop"},)monkeypatch.setattr(- "tools.voice_mode.is_voice_stop_phrase",+ "tools.voice_mode_transcript.is_voice_stop_phrase",lambda text: text.strip().lower() == "stop",)diff --git a/tests/tools/test_voice_mode.py b/tests/tools/test_voice_mode.pyindex d4d0e6e78d3..2a10a77de2c 100644--- a/tests/tools/test_voice_mode.py+++ b/tests/tools/test_voice_mode.py@@ -199,6 +199,7 @@ class TestDetectAudioEnvironment:assert result["warnings"] == []assert any("SSH" in n for n in result.get("notices", []))+ @pytest.mark.platforms("linux")def test_wsl_without_pulse_blocks_voice(self, monkeypatch, tmp_path):"""WSL without PULSE_SERVER should block voice mode."""monkeypatch.delenv("SSH_CLIENT", raising=False)@@ -476,7 +477,7 @@ class TestTranscribeRecording:class TestWhisperHallucinationFilter:def test_known_hallucinations(self):- from tools.voice_mode import is_whisper_hallucination+ from tools.voice_mode_transcript import is_whisper_hallucinationassert is_whisper_hallucination("Thank you.") is Trueassert is_whisper_hallucination("thank you") is True@@ -486,7 +487,7 @@ class TestWhisperHallucinationFilter:assert is_whisper_hallucination("you") is Truedef test_real_speech_not_filtered(self):- from tools.voice_mode import is_whisper_hallucination+ from tools.voice_mode_transcript import is_whisper_hallucinationassert is_whisper_hallucination("Hello, how are you?") is Falseassert is_whisper_hallucination("Thank you for your help with the project.") is Falsediff --git a/tests/tools/test_voice_wsl_pipewire.py b/tests/tools/test_voice_wsl_pipewire.pyindex 395d401fbf4..9dd1e06fa78 100644--- a/tests/tools/test_voice_wsl_pipewire.py+++ b/tests/tools/test_voice_wsl_pipewire.py@@ -8,6 +8,9 @@ These tests mock /proc/version so they reproduce the WSL path on any host."""import builtinsimport io+import pytest++pytestmark = pytest.mark.platforms("linux")from unittest.mock import MagicMockWSL = "Linux version 5.15.0-microsoft-standard-WSL2 (oe-user@oe-host)"diff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.pyindex 2af4b9bd91c..0abe8a91042 100644--- a/tests/tools/test_wake_word.py+++ b/tests/tools/test_wake_word.py@@ -173,6 +173,23 @@ def test_requirements_fresh_install_lazy_allowed(monkeypatch):assert r["hint"] == ""+def test_requirements_lazy_disabled_returns_remedy_not_nameerror(monkeypatch):+ """Deps missing + lazy installs disabled → unavailable WITH a remedy hint.++ Regression (C29): a competing legacy hint ladder also ran on this path and+ referenced the deleted lazy-deps module by bare name — a NameError crashed+ the status probe instead of returning ``hint``.+ """+ _voice_loop_ready(monkeypatch)+ monkeypatch.setattr(ww, "_audio_available", lambda: True)+ monkeypatch.setattr(pm, "available", lambda f: False)+ monkeypatch.setattr(pm_ensure, "lazy_installs_allowed", lambda: False)+ r = ww.check_wake_word_requirements({"provider": "openwakeword"})+ assert r["available"] is False+ assert r["deps_available"] is False+ assert "uv sync --frozen --extra wake-openwakeword" in r["hint"]++def test_requirements_deps_present_but_no_audio_hint(monkeypatch):"""Once deps ARE installed, a failing audio probe blocks with a mic hint(lazy installs can't fix a missing audio device)."""diff --git a/tests/tools/test_working_diff.py b/tests/tools/test_working_diff.pyindex 27a14188877..2b71026f093 100644--- a/tests/tools/test_working_diff.py+++ b/tests/tools/test_working_diff.py@@ -32,6 +32,7 @@ def repo(tmp_path):d = tmp_path / "repo"d.mkdir()_git(d, "init", "-q")+ _git(d, "config", "core.autocrlf", "false")(d / "tracked.py").write_text("print('hello')\n")_git(d, "add", "-A")_git(d, "commit", "-q", "-m", "init")diff --git a/tests/tui_gateway/test_compute_host.py b/tests/tui_gateway/test_compute_host.pyindex 50270566076..2156ef385d2 100644--- a/tests/tui_gateway/test_compute_host.py+++ b/tests/tui_gateway/test_compute_host.py@@ -1,4 +1,5 @@import json+import pytestimport osimport queueimport subprocessdiff --git a/tests/tui_gateway/test_compute_host_phase1.py b/tests/tui_gateway/test_compute_host_phase1.pyindex bb7368d5588..f670ee3e183 100644--- a/tests/tui_gateway/test_compute_host_phase1.py+++ b/tests/tui_gateway/test_compute_host_phase1.py@@ -312,11 +312,12 @@ def test_shutdown_drain_sleep_never_overshoots_the_reserve(monkeypatch):_record_finalize(monkeypatch, events, "idle")slept: list[float] = []- real_sleep = time.sleep+ clock = [100.0]+ monkeypatch.setattr(compute_host.time, "monotonic", lambda: clock[0])def _recording_sleep(seconds: float) -> None:slept.append(seconds)- real_sleep(seconds)+ clock[0] += secondsmonkeypatch.setattr(compute_host.time, "sleep", _recording_sleep)diff --git a/tests/tui_gateway/test_serve_exit_flush.py b/tests/tui_gateway/test_serve_exit_flush.pyindex 6b86e482b2b..457367e44b7 100644--- a/tests/tui_gateway/test_serve_exit_flush.py+++ b/tests/tui_gateway/test_serve_exit_flush.py@@ -67,6 +67,7 @@ def _restore_signal_state(prev_handlers):server._exit_flush_handlers_installed = False[email protected]("posix")def test_sigterm_flushes_populated_session_into_state_db(registered_session, tmp_path, monkeypatch):@@ -111,6 +112,7 @@ def test_sigterm_flushes_populated_session_into_state_db(assert agent.flush_calls, "SIGTERM must flush in-memory sessions"rows = db.get_messages(sid)assert any("survive the kill" in str(r.get("content", "")) for r in rows)+ db.close()def test_exit_flush_is_bounded(registered_session):diff --git a/tools/approval_context.py b/tools/approval_context.pyindex 7bcaca32c83..ee8222d528d 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -251,7 +251,7 @@ def _get_approval_timeout() -> int:from agent.deadline import MAX_SAFE_TIMEOUT_Ssafe_cap = int(MAX_SAFE_TIMEOUT_S)except Exception:- safe_cap = 365 * 24 * 3600 # fail CLOSED: the raw value would re-open the overflow+ safe_cap = 300 # dependency failure must keep the safe defaultif raw > safe_cap:logger.warning("approvals.timeout=%s exceeds the platform-safe maximum; clamping to %ss", raw, safe_cap)return min(raw, safe_cap)diff --git a/tools/approval_human_wait.py b/tools/approval_human_wait.pyindex 37ad9942e45..4c8a1c1e3bb 100644--- a/tools/approval_human_wait.py+++ b/tools/approval_human_wait.py@@ -56,7 +56,8 @@ def human_wait_ceiling() -> float:``_get_approval_timeout`` caps at ``agent.deadline.MAX_SAFE_TIMEOUT_S`` so thevalue is always safe for ``Lock.acquire(timeout=...)`` / ``Thread.join(timeout=...)``."""from tools import approval_context- return float(approval_context._get_approval_timeout()) + HUMAN_WAIT_MARGIN_S+ from agent.deadline import MAX_SAFE_TIMEOUT_S+ return min(MAX_SAFE_TIMEOUT_S, float(approval_context._get_approval_timeout()) + HUMAN_WAIT_MARGIN_S)def _clamped_window_seconds(started: float, now: float, ceiling: float) -> float:diff --git a/tools/browser_tool_install.py b/tools/browser_tool_install.pyindex 232026e0b45..987d941397d 100644--- a/tools/browser_tool_install.py+++ b/tools/browser_tool_install.py@@ -227,7 +227,7 @@ def _has_chromium_build(root: str) -> bool:def _chromium_installed() -> bool:"""True when a usable Chromium (or headless-shell) build is on disk; cached.- Checks ``AGENT_BROWSER_EXECUTABLE_PATH``, then system Chrome/Chromium on PATH, then Playwright's cache.+ Checks ``AGENT_BROWSER_EXECUTABLE_PATH``, then the provisioned Playwright cache.Without a binary the CLI hangs on first use until the command timeout fires, so the tool must not be advertised."""_bt = _origin()@@ -236,7 +236,6 @@ def _chromium_installed() -> bool:ab_path = os.environ.get("AGENT_BROWSER_EXECUTABLE_PATH", "").strip()_bt._cached_chromium_installed = bool((ab_path and (os.path.isfile(ab_path) or shutil.which(ab_path)))- or any(shutil.which(name) for name in ("google-chrome", "chromium", "chromium-browser", "chrome"))or any(root and os.path.isdir(root) and _has_chromium_build(root) for root in _chromium_search_roots()))return _bt._cached_chromium_installed@@ -254,8 +253,8 @@ def _maybe_autoinstall_chromium() -> bool:_bt._chromium_autoinstall_attempted = Trueif _running_in_docker():return False- from tools.lazy_deps import _allow_lazy_installs- if not _allow_lazy_installs():+ from pm import lazy_installs_allowed+ if not lazy_installs_allowed():return Falsetry:browser_cmd = _find_agent_browser()diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex b9813b90fd2..5fd2772c9f3 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -218,12 +218,14 @@ def default_downgrade_notice() -> Optional[str]:if get_browser_backend() or _camofox_active() or _find_cli() is not None:return None # explicit choice / Camofox / CLI present — nothing downgradedstamp = Path(get_hermes_home()) / "cache" / ".browser_use_default_notice"+ now = time.time()with contextlib.suppress(OSError):- if 0 <= time.time() - stamp.stat().st_mtime < 24 * 3600:+ if 0 <= now - stamp.stat().st_mtime < 24 * 3600:return Nonewith contextlib.suppress(OSError):stamp.parent.mkdir(parents=True, exist_ok=True)stamp.touch()+ os.utime(stamp, (now, now))return ("Browser Use CLI not found — using the built-in browser tools. Run `hermes tools` ""(Browser Automation → Browser Use) to install it, or `browser.backend: off` in config.yaml to silence this.")except Exception as e: # pragma: no cover — a notice must never break startupdiff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex 39a9582651e..5d63fa7db3a 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -733,4 +733,173 @@ def execute_code(timeout=_cfg.get("timeout", DEFAULT_TIMEOUT),max_tool_calls=_cfg.get("max_tool_calls", DEFAULT_MAX_TOOL_CALLS),reset=bool(reset), is_interrupted=_is_interrupted,- )\ No newline at end of file+ )+++def _kill_process_group(proc, escalate: bool = False):+ """Kill the child and its whole process tree via agent.deadline.kill_process_tree: SIGTERM+ (killpg + psutil descendant sweep; ``taskkill /T /F`` on Windows, where sig is ignored); with+ ``escalate=True`` wait 5s then SIGKILL survivors. Never raises — falls back to ``proc.kill()``."""+ import signal as _signal+ def _tree_signal(sig) -> None:+ try:+ from agent.deadline import kill_process_tree+ kill_process_tree(proc.pid, sig=sig)+ except Exception as e:+ logger.debug("Could not terminate process tree: %s", e, exc_info=True)+ try:+ proc.kill()+ except Exception as e2:+ logger.debug("Could not kill process: %s", e2, exc_info=True)+ _tree_signal(getattr(_signal, "SIGTERM", None))+ if escalate:+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ _tree_signal(getattr(_signal, "SIGKILL", None))+++def _load_config() -> dict:+ """``code_execution`` config section via the lightweight raw reader — runs while the+ module-level schema is built at tool discovery, so it must not import ``cli``."""+ try:+ from hermes_cli.config import read_raw_config+ cfg = read_raw_config().get("code_execution", {})+ return cfg if isinstance(cfg, dict) else {}+ except Exception:+ return {}+++# ---- Execution mode resolution (strict vs project) ----++# Canonical code_execution.mode values (referenced by tests and the config layer). Session+# kernels are the only local execution model; a leftover kernel_mode config key is ignored.+EXECUTION_MODES = ("project", "strict")+DEFAULT_EXECUTION_MODE = "project"+++def _get_execution_mode() -> str:+ """``code_execution.mode`` (invalid → default with a warning). ``project``: session cwd + active+ venv python; ``strict``: isolated temp dir + ``sys.executable``. Scrubbing/whitelist apply to both."""+ cfg_value = str(_load_config().get("mode", DEFAULT_EXECUTION_MODE)).strip().lower()+ if cfg_value in EXECUTION_MODES:+ return cfg_value+ logger.warning(+ "Ignoring code_execution.mode=%r (expected one of %s), falling back to %r",+ cfg_value, EXECUTION_MODES, DEFAULT_EXECUTION_MODE,+ )+ return DEFAULT_EXECUTION_MODE+++# ---- OpenAI Function-Calling Schema ----++# Per-tool documentation lines for the execute_code description, in canonical display order.+_TOOL_DOC_LINES = [+ ("web_search", " web_search(query: str, limit: int = 5) -> dict\n"+ " Returns {\"data\": {\"web\": [{\"url\", \"title\", \"description\"}, ...]}}"),+ ("web_extract", " web_extract(urls: list[str], char_limit: int = None) -> dict\n"+ " Returns {\"results\": [{\"url\", \"title\", \"content\", \"error\"}, ...]} where content is markdown.\n"+ " No LLM summarization. Pages over char_limit (default 15000) are head+tail truncated; full text stored on disk (path in the content footer)."),+ ("read_file", " read_file(path: str, offset: int = 1, limit: int = 2000) -> dict\n"+ " Lines are 1-indexed. Returns {\"content\": \"...\", \"total_lines\": N}"),+ ("write_file", " write_file(path: str, content: str) -> dict\n Always overwrites the entire file."),+ ("search_files", " search_files(pattern: str, target=\"content\", path=\".\", file_glob=None, limit=50, order=\"discovery\") -> dict\n"+ " target: \"content\" (search inside files) or \"files\" (find files by name). Returns {\"matches\": [...]}"),+ ("patch", " patch(path: str, old_string: str, new_string: str, replace_all: bool = False) -> dict\n"+ " Replaces old_string with new_string in the file."),+ ("terminal", " terminal(command: str, timeout=None, workdir=None) -> dict\n"+ " Foreground only (no background/pty). Returns {\"output\": \"...\", \"exit_code\": N}"),+]+++def build_execute_code_schema(enabled_sandbox_tools: set = None,+ mode: str = None) -> dict:+ """execute_code schema listing only *enabled_sandbox_tools* — a disabled tool (e.g. web off)+ must not appear or the model keeps trying it. ``mode`` (None → config) picks the cwd sentence."""+ if enabled_sandbox_tools is None:+ enabled_sandbox_tools = SANDBOX_ALLOWED_TOOLS+ if mode is None:+ mode = _get_execution_mode()+ tool_lines = "\n".join(doc for name, doc in _TOOL_DOC_LINES if name in enabled_sandbox_tools)+ import_examples = [n for n in ("web_search", "terminal") if n in enabled_sandbox_tools]+ import_examples = import_examples or sorted(enabled_sandbox_tools)[:2]+ import_str = ", ".join(import_examples) + ", ..." if import_examples else "..."+ if mode == "strict":+ cwd_note = (+ "Scripts run in their own temp dir, not the session's CWD — pass "+ "absolute paths for any file that lives outside the session's "+ "working directory, or use terminal()/read_file() to reach it."+ )+ else:+ cwd_note = (+ "Scripts run in the session's working directory. Interpreter: "+ "the project's activated venv/conda python when one is active "+ "(VIRTUAL_ENV/CONDA_PREFIX — matches terminal()); otherwise "+ "Hermes's own python (the common case — stdlib plus Hermes's "+ "deps; check `import x` before relying on project packages)."+ )+ # Remote hosts that fail open to per-call are not worth schema words; the result's+ # `kernel` field tells the truth per call.+ # Session kernels are always on (kernel_mode retired in #96787): persistence is part of the tool's one+ # description, not a bolt-on paragraph behind a dead conditional.+ description = (+ "Run Python that calls Hermes tools programmatically. Use when you "+ "need 3+ tool calls with logic between them: filtering/reducing "+ "large outputs before they enter context, branching, or loops "+ "(N pages/files, retry on failure). Use normal tool calls for "+ "single calls, results you must reason over in full, or anything needing user interaction.\n\n"+ "Calls run in a persistent session kernel: variables, imports, and "+ "loaded data survive across execute_code calls, so build on earlier "+ "work instead of re-loading it. A timed-out or interrupted call loses that state.\n\n"+ f"Available via `from hermes_tools import ...`:\n\n"+ f"{tool_lines}\n\n"+ "Limits: 5-minute timeout, max 50 tool calls per call. Stdout over "+ "50KB shows head/tail inline; the FULL text is auto-saved to a file whose path rides in the result.\n\n"+ f"{cwd_note}\n\n"+ "Built-in helpers (no import): json_parse(text) — tolerant "+ "json.loads for terminal() output; shell_quote(s) — shlex.quote for "+ "dynamic shell args; retry(fn, max_attempts=3, delay=2) — exponential backoff."+ )+ return {+ "name": "execute_code",+ "description": description,+ "parameters": {+ "type": "object",+ "properties": {+ "code": {"type": "string", "description": (+ "Python code to execute. Import tools with "+ f"`from hermes_tools import {import_str}` "+ "and print your final result to stdout.")},+ "reset": {"type": "boolean", "description": (+ "Discard the kernel's persistent state and start fresh before running this code.")},+ },+ "required": ["code"],+ },+ }+++# Registration-time schema (all sandbox tools, configured mode); model_tools.py rebuilds per-session.+EXECUTE_CODE_SCHEMA = build_execute_code_schema()+++def _execute_code_handler(args: dict, **kwargs) -> str:+ """Redirect misdirected calls (terminal's ``command`` arg, non-string ``code``) with an+ actionable error before dispatching to ``execute_code``."""+ if "code" not in args and "command" in args:+ logger.warning("execute_code received 'command' instead of the required 'code' argument")+ return tool_error("execute_code received a 'command' parameter, but it requires "+ "Python source in 'code'. Use terminal(command=...) for shell "+ "commands; for Python, retry as execute_code(code=...).")+ code = args.get("code", "")+ if code is not None and not isinstance(code, str):+ return tool_error(f"execute_code received a {type(code).__name__} in 'code', but it "+ "requires Python source as a string. Retry as execute_code(code=\"...\").")+ return execute_code(code=code or "", task_id=kwargs.get("task_id"),+ enabled_tools=kwargs.get("enabled_tools"), reset=bool(args.get("reset", False)))+++registry.register(+ name="execute_code", toolset="code_execution", schema=EXECUTE_CODE_SCHEMA,+ handler=_execute_code_handler, check_fn=check_sandbox_requirements, emoji="🐍",+ max_result_size_chars=100_000,+)diff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.pyindex 2beb28422fa..faeb297ea26 100644--- a/tools/computer_use/cua_backend_driver.py+++ b/tools/computer_use/cua_backend_driver.py@@ -71,7 +71,7 @@ def _wsl_windows_path_to_posix(path: str) -> str:wsl = Falsewin = PureWindowsPath(path)drive = (win.drive or "").rstrip(":").lower()- return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:])) if wsl and drive else path+ return "/".join(["/mnt", drive, *win.parts[1:]]) if wsl and drive else pathdef _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]:"""Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is authoritativediff --git a/tools/credential_files.py b/tools/credential_files.pyindex d39e5c3250f..05dd412038b 100644--- a/tools/credential_files.py+++ b/tools/credential_files.py@@ -229,7 +229,7 @@ def _safe_skills_path(skills_dir: Path) -> str:def iter_skills_files(container_base: str = "/root/.hermes") -> List[Dict[str, str]]:"""Per-file entries for all skills files (for backends that upload individually)."""- return [_mount(item, f"{container_root}/{item.relative_to(host_dir)}")+ return [_mount(item, f"{container_root}/{item.relative_to(host_dir).as_posix()}")for host_dir, container_root in _skill_dir_roots(container_base)for _base, files in _walk_skill_tree(host_dir) for item in files]diff --git a/tools/environments/base.py b/tools/environments/base.pyindex fe55f263a8c..afaa57fdd78 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -483,7 +483,8 @@ class BaseEnvironment(ABC):# --- Process lifecycle ---def _wait_for_process(self, proc: ProcessHandle, timeout: int = 120, *,- bounded_capture: bool = False, watch_interrupt_tid: int | None = None) -> dict:+ bounded_capture: bool = False, watch_interrupt_tid: int | None = None,+ output=None) -> dict:"""Poll-based wait with interrupt checking and stdout draining (shared, not overridden).``bounded_capture=True`` (foreground terminal-tool path only) retains at most``tool_output.max_bytes`` in a head/tail window so a verbose subprocess cannot OOM the@@ -499,7 +500,8 @@ class BaseEnvironment(ABC):reads feeding the patch engine, code-execution RPC reads, log reads — where truncation would corruptdata. See #64435."""- output = _new_output_collector(proc, bounded_capture)+ if output is None:+ output = _new_output_collector(proc, bounded_capture)drain_thread = _start_drain_thread(proc, output)_now = time.monotonic()deadline = _now + timeout@@ -648,14 +650,18 @@ class BaseEnvironment(ABC):# deadline worker, so copy it across or long commands look idle.parent_activity_cb = get_activity_callback()proc_holder: list = []+ output_holder: list = []def _spawn_and_wait() -> dict:if parent_activity_cb is not None:set_activity_callback(parent_activity_cb)spawned = self._run_bash(wrapped, login=login, timeout=effective_timeout, stdin_data=effective_stdin)proc_holder.append(spawned)+ output = _new_output_collector(spawned, bounded_capture)+ output_holder.append(output)return self._wait_for_process(- spawned, timeout=effective_timeout, bounded_capture=bounded_capture, watch_interrupt_tid=parent_tid)+ spawned, timeout=effective_timeout, bounded_capture=bounded_capture,+ watch_interrupt_tid=parent_tid, output=output)def _on_timeout() -> None:if proc_holder:@@ -682,9 +688,15 @@ class BaseEnvironment(ABC):_on_timeout()raise- result = (- {"output": f"[Command timed out after {effective_timeout}s]", "returncode": 124}- if bounded.timed_out else bounded.value)+ if bounded.timed_out:+ suffix = f"\n[Command timed out after {effective_timeout}s]"+ if output_holder:+ collector = output_holder[0]+ result = self._finalize_wait_result(collector, collector.render(suffix=suffix).lstrip("\n"), 124)+ else:+ result = {"output": suffix.lstrip(), "returncode": 124}+ else:+ result = bounded.valueself._update_cwd(result)return resultdiff --git a/tools/environments/daytona.py b/tools/environments/daytona.pyindex 678becda4c3..b96d70de36a 100644--- a/tools/environments/daytona.py+++ b/tools/environments/daytona.py@@ -34,7 +34,7 @@ class DaytonaEnvironment(BaseEnvironment):memory: int = 5120, disk: int = 10240, persistent_filesystem: bool = True,task_id: str = "default"):super().__init__(cwd=cwd, timeout=timeout)- ensure_lazy_dep("terminal.daytona")+ ensure_lazy_dep("daytona")from daytona import Daytona, CreateSandboxFromImageParams, DaytonaError, Resources, SandboxStatetry:diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 2dbb16f4275..bd33f7249de 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -755,6 +755,10 @@ class LocalEnvironment(BaseEnvironment):string resolves in both Git Bash and native Python."""if _IS_WINDOWS:+ for key in ("TERMINAL_TEMP_DIR", "TMPDIR"):+ candidate = self.env.get(key) or os.environ.get(key)+ if candidate and os.path.isabs(candidate) and os.path.isdir(candidate):+ return Path(candidate).as_posix()cache_dir = (_default_terminal_temp_dir()or Path(tempfile.gettempdir()) / "hermes_terminal")cache_dir.mkdir(parents=True, exist_ok=True)diff --git a/tools/environments/local_pythonpath.py b/tools/environments/local_pythonpath.pyindex a7fcbeba083..6d92ab933ca 100644--- a/tools/environments/local_pythonpath.py+++ b/tools/environments/local_pythonpath.py@@ -74,6 +74,11 @@ def _validated_runtime_venv(env: dict) -> Path | None:"""Producer-owned runtime venv identified by VIRTUAL_ENV, or None. The variablealone is not provenance (users carry unrelated venvs): require the legacy Windowsbase-Python producer's exact ``<repo>/venv`` layout AND a real ``pyvenv.cfg``."""+ from hermes_cli.runtime_paths import runtime_facts_path, selected_venv++ root = Path(__file__).resolve().parents[2]+ if runtime_facts_path(root).is_file():+ return selected_venv(root)candidate = Path(env.get("VIRTUAL_ENV") or "")if not env.get("VIRTUAL_ENV") or not any(_same_path(candidate, root / "venv") for root in _state()._hermes_repo_root_aliases):@@ -106,7 +111,8 @@ def _get_hermes_site_packages(env: dict) -> list[Path]:runtime_venv = _validated_runtime_venv(env)if runtime_venv is not None:- runtime_site_packages = runtime_venv / "Lib" / "site-packages"+ from hermes_cli.runtime_paths import site_packages+ runtime_site_packages = site_packages(runtime_venv)if not any(_same_path(runtime_site_packages, existing) for existing in result):result.append(runtime_site_packages)return resultdiff --git a/tools/environments/modal.py b/tools/environments/modal.pyindex 94aa2de3aa9..f62fcb708ee 100644--- a/tools/environments/modal.py+++ b/tools/environments/modal.py@@ -62,7 +62,7 @@ def _delete_direct_snapshot(task_id: str, snapshot_id: str | None = None) -> Nondef _resolve_modal_image(image_spec: Any) -> Any:"""Convert registry references or snapshot ids into Modal image objects. Registry imagesget pip repaired (ensurepip) before Modal's bootstrap; ubuntu/debian also get python3."""- ensure_lazy_dep("terminal.modal")+ ensure_lazy_dep("modal")import modal as _modalif not isinstance(image_spec, str):diff --git a/tools/environments/remote_common.py b/tools/environments/remote_common.pyindex 17783dc0ed4..45f60398121 100644--- a/tools/environments/remote_common.py+++ b/tools/environments/remote_common.py@@ -19,14 +19,12 @@ def bash_argv(cmd_string: str, login: bool = False) -> list[str]:return ["bash", "-l", "-c", cmd_string] if login else ["bash", "-c", cmd_string]-def ensure_lazy_dep(feature: str) -> None:- """Lazy-install an optional SDK via ``tools.lazy_deps`` (idempotent). Missing ``tools.lazy_deps``- is tolerated (the SDK import that follows fails with its own message); any other failure- surfaces as ``ImportError``."""+def ensure_lazy_dep(extra: str) -> None:+ """Lazy-install an optional SDK's pm extra (idempotent). Install failures+ surface as ``ImportError``."""+ import pm+try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure(feature, prompt=False)- except ImportError:- pass+ pm.ensure_import(extra)except Exception as e:raise ImportError(str(e))diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.pyindex d138135b8c4..59eb197eef3 100644--- a/tools/environments/vercel_sandbox.py+++ b/tools/environments/vercel_sandbox.py@@ -25,7 +25,6 @@ from hermes_constants import get_hermes_homefrom tools.environments.base import BaseEnvironment, _load_json_store, _save_json_storefrom tools.environments.base_output import _ThreadedProcessHandlefrom tools.environments.file_sync import FileSyncManager, iter_sync_files, quoted_rm_command-from tools.environments.remote_common import ensure_lazy_deplogger = logging.getLogger(__name__)diff --git a/tools/file_operations.py b/tools/file_operations.pyindex e1e94d195b1..74c64d3f3a8 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -351,11 +351,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):agree on the path form. No-op off Windows and for plain POSIX paths.``translate_path=False`` skips that translation for non-path values- (regex patterns) whose backslashes are meaningful. On Windows those- backslashes are doubled first: the ``-c`` argument passes through- ``subprocess`` list-arg quoting (which wraps it in double quotes) and- ``bash`` then collapses ``\\\\`` → ``\\`` inside those double quotes,- so one level must survive the round trip.+ (regex patterns) whose backslashes are meaningful. Bash single+ quotes preserve those bytes; only path arguments are translated."""from tools.environments.local import _IS_WINDOWS, _bash_safe_path@@ -1069,7 +1066,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):snippet = ("import shutil, pathlib, sys\n"f"p = pathlib.Path({json.dumps(path)})\n"- f"recursive = {bool(recursive)!r}\n"+ "recursive = False\n""try:\n"" if p.is_dir() and not p.is_symlink():\n"" if recursive:\n"diff --git a/tools/file_operations_search.py b/tools/file_operations_search.pyindex 7c5e355a161..e3d164d497a 100644--- a/tools/file_operations_search.py+++ b/tools/file_operations_search.py@@ -514,7 +514,7 @@ class SearchMixin:glob_expr_probe = glob_exprprobe = self._exec(f"{rg} {flags} --count-matches{glob_expr_probe} "- f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "+ f"{self._escape_shell_arg(pattern, translate_path=False)} {self._escape_native_tool_arg(path)} "f"2>/dev/null | head -50",timeout=30)total, per_file = 0, []@@ -784,7 +784,7 @@ class SearchMixin:cmd_parts.extend(["--glob", self._escape_shell_arg(file_glob)])if output_mode in _OUTPUT_MODE_FLAGS:cmd_parts.append(_OUTPUT_MODE_FLAGS[output_mode])- cmd_parts.append(self._escape_shell_arg(pattern))+ cmd_parts.append(self._escape_shell_arg(pattern, translate_path=False))# rg is a native Windows binary (winget/cargo/choco): needs C:/... not MSYS /c/...cmd_parts.append(self._escape_native_tool_arg(path))ml_note = (@@ -803,7 +803,7 @@ class SearchMixin:parts.extend(["--include", self._escape_shell_arg(file_glob)])if output_mode in _OUTPUT_MODE_FLAGS:parts.append(_OUTPUT_MODE_FLAGS[output_mode])- parts.append(self._escape_shell_arg(pattern))+ parts.append(self._escape_shell_arg(pattern, translate_path=False))return partsdef _search_with_grep(self, pattern: str, path: str, file_glob: Optional[str],diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.pyindex 2196ac0f02c..f54a8115e7f 100644--- a/tools/mcp_tool_sampling.py+++ b/tools/mcp_tool_sampling.py@@ -5,10 +5,13 @@ import asyncioimport jsonimport loggingimport time-from typing import Callable, List, Optional+from typing import TYPE_CHECKING, Callable, List, Optionalfrom tools.mcp_tool_common import _MISSING, _exc_str, _safe_numeric, _sanitize_error, mcp_field, _corefrom tools.mcp_tool_schema import _normalize_mcp_input_schema+if TYPE_CHECKING: # annotations only; mcp_tool imports this module, so a real import is circular+ from tools.mcp_tool import MCPServerTask+logger = logging.getLogger("tools.mcp_tool")diff --git a/tools/patch_parser.py b/tools/patch_parser.pyindex 994e3c1c56d..5682928a14d 100644--- a/tools/patch_parser.py+++ b/tools/patch_parser.py@@ -9,7 +9,10 @@ import inspectimport refrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Any, Callable, Dict, List, Optional, Tuple+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple++if TYPE_CHECKING: # annotations only; the real import is per-call in apply_v4a_operations+ from tools.file_operations_common import PatchResultclass OperationType(Enum):diff --git a/tools/registry.py b/tools/registry.pyindex 9ddf201fec7..7a9f99bce6c 100644--- a/tools/registry.py+++ b/tools/registry.py@@ -399,6 +399,7 @@ class ToolRegistry:def _slot(self, scope: Optional[str], *, create: bool = False) -> Dict[str, ToolEntry]:"""The registration map for *scope*: global when None, else that profile's overlay."""+ scope = normalize_scope(scope)if scope is None:return self._toolsif create:@@ -411,7 +412,7 @@ class ToolRegistry:def _merged_tools(self, scope: Optional[str] = None) -> Dict[str, ToolEntry]:"""Return global tools overlaid with one profile's plugin tools."""- return {**self._tools, **self._scoped_tools.get(scope or self.current_scope_key(), {})}+ return {**self._tools, **self._scoped_tools.get(hermes_home_key(scope), {})}def _toolset_entries(self, toolset: str, scope: Optional[str]) -> List[ToolEntry]:return self._grouped(self._merged_tools(scope).values()).get(toolset, [])@@ -483,6 +484,7 @@ class ToolRegistry:) -> _PluginOverridePolicy:"""Bind a plugin module namespace to its current operator opt-in. The identity-bearingresult lets unload/reload revoke a stale authorization without losing attribution."""+ scope = normalize_scope(scope)with self._lock:policy = _PluginOverridePolicy(allowed)self._plugin_override_policy[(scope, module_namespace)] = policy@@ -673,6 +675,7 @@ class ToolRegistry:``register(override=True)``, else a plugin could deregister a tool it doesn't ownand re-register over the empty slot (the override check only runs when an entryexists). ``mcp-*`` toolsets are exempt — discovery repaves its own tools per refresh."""+ scope = normalize_scope(scope)with self._lock:caller_mod = self._caller_module()caller_owner = self._plugin_namespace_of_module(caller_mod)diff --git a/tools/skills_sync.py b/tools/skills_sync.pyindex 64cc73c8068..4d214919a6b 100644--- a/tools/skills_sync.py+++ b/tools/skills_sync.py@@ -126,8 +126,6 @@ def _read_manifest() -> Dict[str, str]:return resultexcept (OSError, IOError):return {}- pairs = (line.partition(":") for line in map(str.strip, lines) if line)- return {name.strip(): hash_val.strip() for name, _, hash_val in pairs}def _read_suppressed_names() -> set:diff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 45bee6685f3..9c1e259cfb4 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -371,7 +371,7 @@ def _skill_linked_files(skill_dir: Optional[Path]) -> dict:for sub, globs, recursive, files_only in _LINKED_FILE_SPECS if skill_dir else ():base = skill_dir / subfound = [- str(f.relative_to(skill_dir)) for g in globs if base.exists()+ f.relative_to(skill_dir).as_posix() for g in globs if base.exists()for f in (base.rglob(g) if recursive else base.glob(g))if not files_only or f.is_file()]if found:diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.pyindex 043c3b0cfbc..f37f60cffea 100644--- a/tools/skills_tool_plugin.py+++ b/tools/skills_tool_plugin.py@@ -58,7 +58,7 @@ def _available_skill_files(skill_dir: Path) -> Dict[str, List[str]]:for f in skill_dir.rglob("*"):if not f.is_file() or f.name == "SKILL.md":continue- rel = str(f.relative_to(skill_dir))+ rel = f.relative_to(skill_dir).as_posix()top = rel.split("/", 1)[0] if "/" in rel else Noneif top in _SUPPORT_DIRS or f.suffix in _SKILL_FILE_EXTS:groups.setdefault(top if top in _SUPPORT_DIRS else "other", []).append(rel)diff --git a/tools/transcription_audio.py b/tools/transcription_audio.pyindex 45658e01b4e..a77e547e9eb 100644--- a/tools/transcription_audio.py+++ b/tools/transcription_audio.py@@ -121,7 +121,7 @@ def _prepare_audio_for_transcription(file_path: str) -> tuple[Optional[str], Optreturn file_path, None, Noneif not _HAS_PILK:# pilk is a tiny silk-v3 codec binding — lazy-installed on first .silk voice note.- _lazy_ensure_quietly("stt.silk")+ _lazy_ensure_quietly("silk")if not _safe_find_spec("pilk"):return None, None, _error_result("Unsupported format: .silk. Install the optional 'pilk' dependency to enable WeChat voice transcription."diff --git a/tools/transcription_cloud.py b/tools/transcription_cloud.pyindex 21cfbb36495..ff487dc86d6 100644--- a/tools/transcription_cloud.py+++ b/tools/transcription_cloud.py@@ -174,7 +174,7 @@ def _transcribe_mistral(if not api_key:return _error_result("MISTRAL_API_KEY not set")try:- _lazy_ensure_quietly("stt.mistral")+ _lazy_ensure_quietly("mistral")from mistralai.client import Mistralwith Mistral(api_key=api_key) as client, open(file_path, "rb") as audio_file:# Language: hook override > stt.mistral.language > stt.language > env > auto.diff --git a/tools/transcription_common.py b/tools/transcription_common.pyindex 95b491e3ce3..8905eb01746 100644--- a/tools/transcription_common.py+++ b/tools/transcription_common.py@@ -57,13 +57,12 @@ def _ok_result(transcript: str, provider: str) -> Dict[str, Any]:return {"success": True, "transcript": transcript, "provider": provider}-def _lazy_ensure_quietly(dep: str) -> None:- """Best-effort ``tools.lazy_deps.ensure(dep, prompt=False)``; failures are swallowed.- prompt=False: a bare input() deadlocks under the interactive CLI where prompt_toolkit owns- stdin; installs are gated by ``security.allow_lazy_installs``."""+def _lazy_ensure_quietly(extra: str) -> None:+ """Best-effort ``pm.ensure_import(extra)``; failures are swallowed.+ Installs are gated by ``security.allow_lazy_installs`` inside pm."""try:- from tools.lazy_deps import ensure- ensure(dep, prompt=False)+ import pm+ pm.ensure_import(extra)except Exception:passdiff --git a/tools/transcription_local.py b/tools/transcription_local.pyindex 0dd110dceef..8f12cc7a8d2 100644--- a/tools/transcription_local.py+++ b/tools/transcription_local.py@@ -58,11 +58,10 @@ def _normalize_local_model(model_name: Optional[str]) -> str:def _try_lazy_install_stt() -> bool:"""Lazy-install faster-whisper and re-check dynamically so it's usable without a restart."""try:- from tools.lazy_deps import ensure- # prompt=False: a bare input() deadlocks under the interactive CLI where prompt_toolkit- # owns stdin; the install is already gated by security.allow_lazy_installs.- # prompt=False: never raise a blocking input() prompt mid-session. See #40490.- ensure("stt.faster_whisper", prompt=False)+ # pm installs are gated by security.allow_lazy_installs; never a blocking+ # prompt mid-session. See #40490.+ import pm+ pm.ensure_import("voice")if _ilu.find_spec("faster_whisper"):return Truelogger.warning("faster-whisper was installed but importlib still cannot find it (may require Python restart)")diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.pyindex d454c0e0c4d..43341b1ba8e 100644--- a/tools/tts_tool_lifecycle.py+++ b/tools/tts_tool_lifecycle.py@@ -38,8 +38,8 @@ def _local_tts_warmers() -> Dict[str, Callable[[Dict[str, Any]], Any]]:"kittentts": lambda cfg: _load_kittentts_model_for_config(cfg)[0]}-# tools.lazy_deps feature key for providers whose SDK installs on first use.-_LAZY_SDK_FEATURES = {"edge": "tts.edge", "elevenlabs": "tts.elevenlabs", "mistral": "tts.mistral"}+# pm extra for providers whose SDK installs on first use.+_LAZY_SDK_FEATURES = {"edge": "edge-tts", "elevenlabs": "tts-premium", "mistral": "mistral"}def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str) -> Optional[str]:@@ -111,11 +111,11 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Optfeature = _LAZY_SDK_FEATURES.get(name)if feature is not None:try:- from tools.lazy_deps import ensure, is_available- if is_available(feature):+ import pm+ if pm.available(feature):result.update(warmed=True, action="cached")else:- ensure(feature, prompt=False)+ pm.ensure_import(feature)result.update(warmed=True, action="installed")except Exception as exc:logger.debug("[TTS] SDK warm-up for %s skipped: %s", name, exc)diff --git a/tools/voice_mode.py b/tools/voice_mode.pyindex a17f2b7f1cc..ead96580674 100644--- a/tools/voice_mode.py+++ b/tools/voice_mode.py@@ -9,7 +9,6 @@ Dependencies (optional):or: uv sync --extra voice"""-import difflibimport loggingimport mathimport os@@ -959,197 +958,6 @@ def create_audio_recorder() -> AudioRecorder:return AudioRecorder()-# ============================================================================-# Whisper hallucination filter-# ============================================================================-# Whisper commonly hallucinates these phrases on silent/near-silent audio.-WHISPER_HALLUCINATIONS = {- "thank you.",- "thank you",- "thanks for watching.",- "thanks for watching",- "subscribe to my channel.",- "subscribe to my channel",- "like and subscribe.",- "like and subscribe",- "please subscribe.",- "please subscribe",- "thank you for watching.",- "thank you for watching",- "bye.",- "bye",- "you",- "the end.",- "the end",- # Non-English hallucinations (common on silence)- "продолжение следует",- "продолжение следует...",- "sous-titres",- "sous-titres réalisés par la communauté d'amara.org",- "sottotitoli creati dalla comunità amara.org",- "untertitel von stephanie geiges",- "amara.org",- "www.mooji.org",- "ご視聴ありがとうございました",-}--# Regex patterns for repetitive hallucinations (e.g. "Thank you. Thank you. Thank you.")-_HALLUCINATION_REPEAT_RE = re.compile(- r'^(?:thank you|thanks|bye|you|ok|okay|the end|\.|\s|,|!)+$',- flags=re.IGNORECASE,-)---def is_whisper_hallucination(transcript: str) -> bool:- """Check if a transcript is a known Whisper hallucination on silence."""- cleaned = transcript.strip().lower()- if not cleaned:- return True- # Exact match against known phrases- if cleaned.rstrip('.!') in WHISPER_HALLUCINATIONS or cleaned in WHISPER_HALLUCINATIONS:- return True- # Repetitive patterns (e.g. "Thank you. Thank you. Thank you. you")- if _HALLUCINATION_REPEAT_RE.match(cleaned):- return True- return False---# ============================================================================-# Voice-chat stop phrases-# ============================================================================--DEFAULT_VOICE_STOP_PHRASES = ("stop",)---def _load_voice_stop_phrases() -> tuple:- """Return the configured ``voice.stop_phrases`` list (default: ("stop",)).-- Malformed config (scalar, dict, list of non-strings) falls back to the- default rather than crashing the voice loop.- """- try:- from hermes_cli.config import load_config- voice_cfg = load_config().get("voice", {})- if isinstance(voice_cfg, dict):- raw = voice_cfg.get("stop_phrases", DEFAULT_VOICE_STOP_PHRASES)- if isinstance(raw, str):- raw = [raw]- if isinstance(raw, (list, tuple)):- phrases = tuple(- str(p).strip().lower() for p in raw- if isinstance(p, (str, int, float)) and str(p).strip()- )- return phrases # empty tuple = feature disabled- except Exception:- pass- return DEFAULT_VOICE_STOP_PHRASES---def is_voice_stop_phrase(transcript: str, stop_phrases: Optional[tuple] = None) -> bool:- """Return True when *transcript* is EXACTLY a configured stop phrase.-- Ends the voice conversation when the user says "stop" (or another- configured phrase) and nothing else. Deliberately strict: the whole- utterance — after lowercasing and stripping surrounding punctuation —- must equal a phrase, so "stop doing that and try again" still reaches- the agent. Configure via ``voice.stop_phrases`` in config.yaml- (set ``[]`` to disable).- """- if not transcript:- return False- cleaned = transcript.strip().lower().strip(".,!?;: \t\n\"'")- if not cleaned:- return False- if stop_phrases is None:- stop_phrases = _load_voice_stop_phrases()- return cleaned in stop_phrases---# Similarity ratio (difflib.SequenceMatcher, 0..1) above which a-# playback-phase barge transcript is treated as a self-capture of Hermes'-# own just-spoken TTS rather than genuine user speech. See #75780: the-# full-duplex listener has no acoustic echo cancellation, so speaker bleed-# on the mic can trip the barge trigger and get transcribed nearly-# verbatim from the TTS text, creating a TTS -> STT -> TTS feedback loop.-DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD = 0.6--# Minimum normalized-transcript length (in characters) required before the-# fragment sliding-window fallback runs. Below this, any same-length window-# of `spoken_text` that happens to contain the transcript verbatim (e.g. a-# genuine one-word barge-in like "yes" landing inside a longer reply that-# also says "yes") scores a trivial 1.0 ratio and would otherwise be-# misread as a self-capture. A real self-capture fragment spans at least-# the pre-roll buffer plus time-to-silence, so it is normally well above-# this length; a short genuine interjection is not (#75792 review).-MIN_FRAGMENT_LENGTH_FOR_ECHO = 10---def _normalize_for_echo_compare(text: str) -> str:- return re.sub(r"\s+", " ", text).strip().lower()---def is_tts_echo(- transcript: str,- spoken_text: str,- threshold: float = DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD,-) -> bool:- """Return True when *transcript* looks like a self-capture of *spoken_text*.-- Compares a playback-phase barge-in transcript against the TTS text- Hermes just spoke using a character-level similarity ratio, which works- across languages without word-tokenization. A genuine user interjection- is very unlikely to closely match Hermes' own words, so a high ratio is- a strong signal of speaker-bleed self-capture (fail-closed guard for the- playback-phase full-duplex listener, which has no acoustic echo- cancellation; see #75780).-- The playback-phase capture is cut immediately when the barge trigger- fires and only spans the pre-roll buffer plus time-to-silence, so for- any spoken reply longer than a clause the transcript is a short- FRAGMENT of `spoken_text`, not a near-verbatim repeat of the whole- thing. A whole-string ratio dilutes towards 0 as `spoken_text` grows- past the fragment's length, so when the whole-string check misses, we- also slide a window sized to the transcript's character length across- `spoken_text` and compare against each window, catching a short- fragment echoed from within a much longer multi-sentence reply. This- windowing is character-based (not word-split), so it also works for- languages without whitespace between words. Transcripts shorter than- `MIN_FRAGMENT_LENGTH_FOR_ECHO` skip this fallback entirely, since a- short genuine interjection can trivially match an equally short window- of unrelated spoken text.- """- if not transcript or not spoken_text:- return False- a = _normalize_for_echo_compare(transcript)- b = _normalize_for_echo_compare(spoken_text)- if not a or not b:- return False- if difflib.SequenceMatcher(None, a, b).ratio() >= threshold:- return True- if len(a) < MIN_FRAGMENT_LENGTH_FOR_ECHO or len(a) >= len(b):- return False- for start in range(0, len(b) - len(a) + 1):- window = b[start : start + len(a)]- if difflib.SequenceMatcher(None, a, window).ratio() >= threshold:- return True- return False---def voice_stop_hint() -> str:- """One-line 'Say "stop" to end the voice chat.' hint for voice-mode start.-- Sources the phrase from ``voice.stop_phrases`` (first entry) so a custom- phrase renders correctly; returns "" when stop phrases are disabled- (``stop_phrases: []``) so surfaces show no hint at all. Every surface- that announces voice-mode start (CLI /voice on, TUI, desktop) uses this- one owner instead of hardcoding the wording.- """- phrases = _load_voice_stop_phrases()- if not phrases:- return ""- return f'Say "{phrases[0]}" to end the voice chat.'--# ============================================================================# STT dispatch# ============================================================================@@ -1166,7 +974,9 @@ def transcribe_recording(wav_path: str, model: Optional[str] = None) -> Dict[strReturns:Dict with ``success``, ``transcript``, and optionally ``error``."""- from tools.transcription_common import MAX_FILE_SIZE, transcribe_audio+ from tools.transcription_common import MAX_FILE_SIZE+ from tools.transcription_tools import transcribe_audio+ from tools.voice_mode_transcript import is_voice_stop_phrase, is_whisper_hallucinationresult = transcribe_audio(wav_path, model=model, source="voice_mode")@@ -1237,6 +1047,7 @@ def _transcribe_wav_in_chunks(}transcript = result.get("transcript", "").strip()+ from tools.voice_mode_transcript import is_whisper_hallucinationif transcript and not is_whisper_hallucination(transcript):transcripts.append(transcript)@@ -2128,3 +1939,61 @@ def cleanup_temp_recordings(max_age_seconds: int = 3600) -> int:if deleted:logger.debug("Cleaned up %d old voice recordings", deleted)return deleted+++# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----+# Names external plugins imported from this module before the Sep 2026 decomposition.+# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).+# The whole block is removed by reverting the commit that added it.+import difflib # noqa: F401,E402+import re # noqa: F401,E402++WHISPER_HALLUCINATIONS = {+ "thank you.",+ "thank you",+ "thanks for watching.",+ "thanks for watching",+ "subscribe to my channel.",+ "subscribe to my channel",+ "like and subscribe.",+ "like and subscribe",+ "please subscribe.",+ "please subscribe",+ "thank you for watching.",+ "thank you for watching",+ "bye.",+ "bye",+ "you",+ "the end.",+ "the end",+ # Non-English hallucinations (common on silence)+ "продолжение следует",+ "продолжение следует...",+ "sous-titres",+ "sous-titres réalisés par la communauté d'amara.org",+ "sottotitoli creati dalla comunità amara.org",+ "untertitel von stephanie geiges",+ "amara.org",+ "www.mooji.org",+ "ご視聴ありがとうございました",+}+++_PLUGIN_COMPAT_LAZY = {+ 'DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD': ('tools.voice_mode_transcript', 'DEFAULT_TTS_ECHO_SIMILARITY_THRESHOLD'),+ 'DEFAULT_VOICE_STOP_PHRASES': ('tools.voice_mode_transcript', 'DEFAULT_VOICE_STOP_PHRASES'),+ 'MIN_FRAGMENT_LENGTH_FOR_ECHO': ('tools.voice_mode_transcript', 'MIN_FRAGMENT_LENGTH_FOR_ECHO'),+ 'is_tts_echo': ('tools.voice_mode_transcript', 'is_tts_echo'),+ 'voice_stop_hint': ('tools.voice_mode_transcript', 'voice_stop_hint'),+}+++def __getattr__(name): # PEP 562 — lazy so no import cycles+ target = _PLUGIN_COMPAT_LAZY.get(name)+ if target is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ import importlib+ from hermes_cli.plugin_compat import warn_once+ warn_once(__name__, name, *target)+ return getattr(importlib.import_module(target[0]), target[1])+# ---- END PLUGIN-COMPAT ----diff --git a/tools/wake_word.py b/tools/wake_word.pyindex 0189fd7c0dc..f8fc3da552c 100644--- a/tools/wake_word.py+++ b/tools/wake_word.py@@ -42,12 +42,12 @@ _DEFAULT_CONFIRMATION_FRAMES = 3_SILENCE_PEAK = 10_SILENCE_ALERT_SECONDS = 10-# provider alias -> (engine class name on this module, lazy_deps feature).+# provider alias -> (engine class name on this module, pm extra).# Unknown providers probe as openwakeword but fail to build._PROVIDERS: Dict[str, tuple[str, str]] = {- "porcupine": ("_PorcupineEngine", "wake.porcupine"),- **{k: ("_SherpaKwsEngine", "wake.sherpa") for k in ("sherpa", "sherpa-onnx", "kws", "open")},- **{k: ("_OpenWakeWordEngine", "wake.openwakeword") for k in ("openwakeword", "oww", "local")},+ "porcupine": ("_PorcupineEngine", "wake-porcupine"),+ **{k: ("_SherpaKwsEngine", "wake-sherpa") for k in ("sherpa", "sherpa-onnx", "kws", "open")},+ **{k: ("_OpenWakeWordEngine", "wake-openwakeword") for k in ("openwakeword", "oww", "local")},}@@ -774,20 +774,6 @@ def check_wake_word_requirements(cfg: Optional[Dict[str, Any]] = None) -> Dict[sf"(Voice section) or see the voice-mode docs.")capture_mode = resolve_capture_mode(cfg)- missing = " and ".join(n for n, ok in (("speech-to-text", stt_ok), ("text-to-speech", tts_ok)) if not ok)-- # Ordered remediation ladder: first true predicate wins.- ladder = (- (not key_ok, lambda: "Set PORCUPINE_ACCESS_KEY (free key at https://console.picovoice.ai)."),- (not deps_ok and not lazy_ok, lambda: lazy_deps.feature_install_command(feature) or ""),- (not tflite_ok,- lambda: "The wake word needs the tflite runtime on this Mac: pip install ai-edge-litert"),- (deps_ok and not audio_ok and capture_mode == "local",- lambda: "Microphone capture needs sounddevice + numpy and a working audio device."),- (bool(missing), lambda: (f"Wake word needs {missing} configured — run `hermes tools` "- f"(Voice section) or see the voice-mode docs.")),- )- hint = next((make() for cond, make in ladder if cond), "")# Client capture needs deps (engine) but not a server-side PortAudio device.if capture_mode == "client":diff --git a/tools/wake_word_engines.py b/tools/wake_word_engines.pyindex 2a9e623433d..455042c816c 100644--- a/tools/wake_word_engines.py+++ b/tools/wake_word_engines.py@@ -21,13 +21,19 @@ def _ww():def _ensure_dep(feature: str) -> None:- from tools import lazy_deps- lazy_deps.ensure(feature, prompt=False)+ # The old lazy-deps specs bundled sounddevice + numpy with every engine;+ # the wake-* sub-extras deliberately don't (audio-io composes [voice]),+ # so ensure capture deps alongside the engine's own extra.+ import pm++ pm.ensure_import(feature)+ if not pm.available("audio-io"):+ pm.ensure_import("audio-io")class _Engine:"""Minimal hotword-engine contract: feed int16 frames, get a bool. Subclasses set ``feature``- (lazy_deps name, ensured before ``_build``) and their own ``cfg`` sub-section ``section``."""+ (the pm extra ensured before ``_build``) and their own ``cfg`` sub-section ``section``."""feature: str = ""section: str = ""@@ -68,7 +74,7 @@ class _OpenWakeWordEngine(_Engine):``sensitivity`` IS the raw 0..1 threshold (higher = stricter). A real utterance holds the scorehigh across frames while a stray phoneme spikes one, so ``confirmation_frames`` hits are required."""- feature, section = "wake.openwakeword", "openwakeword"+ feature, section = "wake-openwakeword", "openwakeword"frame_length = 1280 # openWakeWord recommends 80 ms frames.def _build(self, cfg, sub, ww) -> None:@@ -100,7 +106,7 @@ class _OpenWakeWordEngine(_Engine):if framework != "tflite" or ww.ensure_tflite_runtime():return frameworktry:- _ensure_dep("wake.openwakeword.tflite")+ _ensure_dep("wake-tflite")except Exception as e:logger.debug("wake word: tflite runtime install failed: %s", e)if ww.ensure_tflite_runtime():@@ -168,7 +174,7 @@ class _SherpaKwsEngine(_Engine):"""sherpa-onnx open-vocabulary keyword spotting — any typed phrase, zero training. ``wake_word.phrase``is BPE-tokenized at runtime against the model's vocabulary: DETECTION config, not a cosmetic label."""- feature, section = "wake.sherpa", "sherpa"+ feature, section = "wake-sherpa", "sherpa"frame_length = 1280 # streaming zipformer accepts any chunk; match capture path.def _build(self, cfg, sub, ww) -> None:@@ -247,7 +253,7 @@ class _SherpaKwsEngine(_Engine):class _PorcupineEngine(_Engine):"""Picovoice Porcupine — premium, on-device, needs an access key."""- feature, section = "wake.porcupine", "porcupine"+ feature, section = "wake-porcupine", "porcupine"def _build(self, cfg, sub, ww) -> None:import pvporcupinediff --git a/tui_gateway/host_supervisor.py b/tui_gateway/host_supervisor.pyindex e7f4516f1e8..a3077af3e38 100644--- a/tui_gateway/host_supervisor.py+++ b/tui_gateway/host_supervisor.py@@ -50,6 +50,22 @@ def append_log_record(path: str | Path, record: str) -> None:"""Append one log record using O_APPEND and exactly one os.write call."""Path(path).parent.mkdir(parents=True, exist_ok=True)text = record if record.endswith("\n") else f"{record}\n"+ if os.name == "nt":+ # CRT O_APPEND is seek+write, not an atomic append across handles.+ # FILE_APPEND_DATA without FILE_WRITE_DATA makes the kernel append.+ import win32con+ import win32file+ from ntsecuritycon import FILE_APPEND_DATA+ handle = win32file.CreateFile(+ str(path), FILE_APPEND_DATA,+ win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,+ None, win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None,+ )+ try:+ win32file.WriteFile(handle, text.encode("utf-8", errors="replace"))+ finally:+ handle.Close()+ returnfd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)try:os.write(fd, text.encode("utf-8", errors="replace"))diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex b37588e7b0a..85246b88920 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -176,7 +176,7 @@ def _typed_stop_phrase_response(rid, text):# "stop" to the agent — the typed twin of the spoken stop phrase (PR #73106), applied at the ONE# server-side choke point every TUI submit passes through. (The desktop's voice conversation is# renderer-owned and never flips the backend flag, so it handles its own typed stop client-side.)- from tools.voice_mode import is_voice_stop_phrase+ from tools.voice_mode_transcript import is_voice_stop_phraseif not is_voice_stop_phrase(text):return Noneexcept Exception:diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.pyindex d13a6c3c858..18cf3b574c0 100644--- a/tui_gateway/methods_voice.py+++ b/tui_gateway/methods_voice.py@@ -250,7 +250,7 @@ def _deliver_fd_transcript(text: str) -> None:"""Emit the captured interjection; a bare stop phrase also ends the voice chat. The stopcheck must never break delivery (stubbed voice_mode in tests, partial installs)."""try:- from tools.voice_mode import is_voice_stop_phrase+ from tools.voice_mode_transcript import is_voice_stop_phraseis_stop = is_voice_stop_phrase(text)except Exception:is_stop = Falsediff --git a/website/docs/user-guide/features/gateway-service.md b/website/docs/user-guide/features/gateway-service.mddeleted file mode 100644index fc4eba1fcd4..00000000000--- a/website/docs/user-guide/features/gateway-service.md+++ /dev/null@@ -1,68 +0,0 @@-# Gateway Service--The messaging gateway (Telegram, Discord, WhatsApp, and every other-platform adapter) normally runs as a child of wherever you started it —-a terminal, `hermes serve`, or the desktop app's backend. On Windows,-the **bundled MSIX install** ships one more way: a real Windows Service.--## What it is--Installing the desktop app registers a service named **HermesGateway**-in the Windows Service Control Manager. It arrives **stopped** and-**demand-start** — it never starts on its own. When you turn it on, the-Service Control Manager owns the gateway's lifecycle:--- **automatic at logon** — bots start when you sign in, no app needed-- **restart on crash** — the SCM respawns the gateway if it dies-- **bots survive app close** — the service is not the desktop app's- child; closing the app never touches it--The service runs as *you* (the installing user), using your Hermes home-— the same sessions, memory, and config as every other surface. The-default profile's gateway is what it serves; multiplexed profiles ride-the same process, exactly as a foreground gateway.--## Turning it on--```bash-hermes gateway service on-```--That flips the service to automatic-at-logon and starts it now,-gracefully. Turning it off is the same shape:--```bash-hermes gateway service off # demand-start + graceful stop-hermes gateway service status # SCM state + the config key-```--The posture persists in the `gateway.service` config key, so `hermes-gateway service status` is the one command that answers "is this on?"--## Updates and the graceful stop--Stopping the service — by you, by an update, or by Windows shutdown —-is always graceful: in-flight agent sessions drain, the session database-flushes, and platform locks release (the same drain path `hermes-gateway stop` uses). `hermes update` on a service-managed install-restarts the service through the SCM (`Restart-Service`) — the drain-happens first, the respawn after, so a mixed-version gateway is never-left serving.--## Uninstall--Uninstalling the desktop app removes the service automatically (MSIX-registers it; MSIX removes it). Bots stop — same as today, where-uninstalling the payload removes the gateway's runtime.--## Platform notes--- **Windows MSIX installs only.** Source installs (and every other- platform) keep the foreground `hermes gateway run`, systemd, or- launchd paths — see [the CLI gateway- docs](/user-guide/cli#gateway).-- The service requires Windows 10 1903+ (the MSIX's minimum OS — the- same floor the desktop app ships with).-- `services.msc` shows it as "Hermes Gateway"; manage it there if you- like, though the `hermes gateway service` verbs keep the config key- in sync, which the SCM console does not.diff --git a/website/sidebars.ts b/website/sidebars.tsindex 38f8c2f76e5..eba4ad2e92f 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -68,7 +68,6 @@ const sidebars: SidebarsConfig = {items: ['user-guide/features/overview','user-guide/features/tool-gateway',- 'user-guide/features/gateway-service',{type: 'category',label: 'Core',