Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernet16652eea18a2
diff --cc AGENTS.md
index 2cf8a41ee1e,53ffead6454..4ef4c0ba05b
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -325,17 -320,17 +325,26 @@@ Table-driven beats condition ladders fo
All dependencies carry upper bounds (litellm compromise #2796/#2810; Mini Shai-Hulud worm,
May 2026). PyPI: `>=floor,<next_major` (`"httpx>=0.28.1,<1"`); pre-1.0: `<0.(minor+2)`
(`>=0.29,<0.32`). Git URLs: 40-char commit SHA. GitHub Actions: SHA + `# vN` comment. CI-only
-pip: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers. Run `uv lock` after
-changing `pyproject.toml`. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).
+Python requirements: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers.
+After changing `pyproject.toml`, run `python -m pm.build_env --source . --lock-only`
+with the checkout's prepared Python. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).
+
+PM owns Hermes Python dependency changes. Use `pm.sync_venv(['extra'], explicit=True)`
+for declared runtime extras, `hermes pm install` for setup/sync, and `hermes pm repair`
+for damaged dependencies. Do not mutate Hermes environments with raw pip or uv.
+Use `pm.build_environment` for fresh build outputs and `pm.ensure_environment` for
+isolated tool environments. Callers receive an interpreter or tool path, not uv.
+Nix's declarative uv2nix builds and unrelated user projects remain independently owned.
+ The `[tool.uv] exclude-newer = "14 days"` quarantine covers **Hermes's own dependencies only**
-(`uv lock`/`sync`, `hermes update`, `tools.lazy_deps.ensure` extras — `install policy "core"`).
-Plugin `python_dependencies` install under the plugin's own policy (`install_specs(policy="plugin")`
-→ `uv --no-config`, still inside the core constraints file); Teknium's ruling: "plugins dont have to
++(every registry package in core's `uv.lock`). Plugin `python_dependencies` follow the plugin's own
++policy: when PM generates the plugin workspace (`pm/workspace.py::_core_release_quarantine`) the
++global cutoff moves onto each core-locked package, so plugin-only packages are not filtered and a
++plugin still cannot drag a core package past the window. Teknium's ruling: "plugins dont have to
+ abide by our 14 day rule … Only hermes' dependencies themselves have to." We recommend (not require)
+ plugin authors adopt their own quarantine — the developer guide and `plugin-catalog/README.md` carry
+ that guidance.
+
## Commits, Merges, PRs
- **Squash merges from stale branches silently revert recent fixes.** Before squash-merging,
diff --cc apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts
index a2477675de0,1257d7e5009..e2d81c7fec2
--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts
@@@ -79,11 -79,9 +79,9 @@@ export interface TranscriptViewCutoff
// row whose content is byte-identical to an arm-time row stays hidden until
// the hold releases (bounded by the REST window).
export function transcriptRowContentKey(message: ChatMessage): string {
- return `${message.role}:${
- (message.parts ?? [])
- .map(part => part.type === 'text' ? `${part.type}:${part.text}` : JSON.stringify(part))
- .join('|')
- }`
+ return `${message.role}:${(message.parts ?? [])
- .map(part => ('text' in part && typeof part.text === 'string' ? `${part.type}:${part.text}` : JSON.stringify(part)))
++ .map(part => (part.type === 'text' ? `${part.type}:${part.text}` : JSON.stringify(part)))
+ .join('|')}`
}
export function suppressTranscriptForView(
diff --cc gateway/config.py
index fe3111e91c2,e484102a9a1..ec7ed9b0e6e
--- a/gateway/config.py
+++ b/gateway/config.py
@@@ -182,7 -181,7 +181,7 @@@ def _bundled_platform_manifest_name(plu
(plugin_dir / m for m in ("plugin.yaml", "plugin.yml") if (plugin_dir / m).exists()), None)
if manifest_file is None:
return None
- data = safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}
- data = fast_safe_load(manifest_file.read_text(encoding="utf-8")) or {}
++ data = fast_safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}
name = data.get("name") if isinstance(data, dict) else None
return str(name).strip().lower() or None
except Exception:
diff --cc gateway/config_loader.py
index da7af329087,10bc91fa90d..e367209fa55
--- a/gateway/config_loader.py
+++ b/gateway/config_loader.py
@@@ -388,10 -388,12 +388,12 @@@ def read_yaml_layers(home: Path) -> dic
config_yaml_path = home / "config.yaml"
yaml_cfg: dict = {}
if config_yaml_path.exists():
+ # The installer seeds config.yaml by copying cli-config.yaml.example (~120 KB, almost all
+ # comments), and nothing caches this loader — so the pure-Python parser dominates the load.
+ from utils import fast_safe_load
+
- with open(config_yaml_path, encoding="utf-8") as f:
+ with open(config_yaml_path, encoding="utf-8-sig") as f:
- yaml_cfg = yaml.safe_load(f) or {}
+ yaml_cfg = fast_safe_load(f) or {}
from hermes_cli.config import _expand_env_vars
diff --cc hermes_cli/managed_scope.py
index f8f742ff3ef,0cf20e33bed..28f94f76446
--- a/hermes_cli/managed_scope.py
+++ b/hermes_cli/managed_scope.py
@@@ -107,7 -106,8 +106,7 @@@ def _load_managed_file(name: str, cache
def load_managed_config() -> dict:
"""Parsed managed config.yaml, or {} when absent/malformed (fail-open)."""
- return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda p: yaml.safe_load(p.read_text(encoding="utf-8-sig")) or {})
-
- return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda p: fast_safe_load(p.read_text(encoding="utf-8")) or {})
++ return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda p: fast_safe_load(p.read_text(encoding="utf-8-sig")) or {})
def load_managed_env() -> Dict[str, str]:
diff --cc hermes_cli/update_cmd_maint.py
index f67e727c1bb,339bf3449ff..f434f9e611c
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@@ -961,8 -995,9 +961,14 @@@ def _run_post_update_maintenance
assume_yes=assume_yes, gateway_mode=gateway_mode, pre_update_snapshot_id=pre_update_snapshot_id,
)
- update_complete = _print_update_summary(
- node_failures=node_failures, desktop_build_ok=desktop_build_ok, pre_update_version=pre_update_version,
- )
+ print()
+ update_complete = _print_verified_update_completion(completion_message or _update_complete_message(pre_update_version))
++ # A multi-profile host whose gateway came back standalone on a guard says so here too — the
++ # update summary is the one line operators read (the boot log under s6 is not).
++ with suppress(Exception):
++ from hermes_cli.gateway_multiplex_mode import consume_rewritten_notice, recorded_standalone_warning_lines
++ for line in [*consume_rewritten_notice(), *recorded_standalone_warning_lines()]:
++ print(line)
_print_post_update_notices_and_self_heals()
return update_complete
diff --cc pm/workspace.py
index 218db498bef,00000000000..0fb587d04b4
mode 100644,000000..100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@@ -1,308 -1,0 +1,341 @@@
+"""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
+
+import hashlib
+import os
+import shutil
+from collections.abc import Mapping
+from pathlib import Path
+from typing import TYPE_CHECKING, Optional
+
+if TYPE_CHECKING:
+ from pm.environment import PythonEnvironment
+
+from pm import paths
+from pm.package import InstallError
+from pm.plugin_declarations import read_python_declaration, manifest_version_error
+
+_MEMBER_EXCLUDE = frozenset({".git", ".venv", "venv", "node_modules", "__pycache__"})
+
+
+def _member_ignored(directory, names):
+ return [name for name in names if name in _MEMBER_EXCLUDE or name.endswith(".egg-info")]
+
+
+# The uv failure classifier lives beside the uv runner (stdlib-only imports): the bootstrap
+# runner streams uv output from a pre-3.11 system python where this module's tomllib import
+# cannot load. Workspace callers keep reaching it from here.
+from pm.environment import ResolutionConflict, classify_uv_failure # noqa: E402,F401
+
+
+def member_sources(plugin_dirs) -> dict[Path, Path]:
+ """Map installed identities to build inputs, including staged plugin updates."""
+ rows = plugin_dirs.items() if isinstance(plugin_dirs, Mapping) else ((path, path) for path in plugin_dirs)
+ return {Path(identity).resolve(): Path(source).resolve() for identity, source in rows}
+
+
+def members_stamp(plugin_dirs) -> str:
+ """Hash the member inputs copied into a generation, independent of staging paths."""
+ h = hashlib.sha256()
+ for identity, entry in sorted(member_sources(plugin_dirs).items()):
+ h.update(str(identity).encode("utf-8"))
+ h.update(b"\0")
+ declaration = read_python_declaration(entry)
+ for source in declaration.files:
+ h.update(source.name.encode("utf-8"))
+ h.update(source.read_bytes())
+ h.update(b"\0")
+ if (entry / "pyproject.toml").is_file():
+ for directory, dirs, files in os.walk(entry):
+ dirs[:] = sorted(set(dirs) - set(_member_ignored(directory, dirs)))
+ for name in sorted(set(files) - set(_member_ignored(directory, files))):
+ path = Path(directory) / name
+ h.update(path.relative_to(entry).as_posix().encode())
+ h.update(b"\0")
+ h.update(os.readlink(path).encode() if path.is_symlink() else path.read_bytes())
+ h.update(b"\0")
+ return h.hexdigest()
+
+
+def _copy_core_inputs(source: Path, destination: Path) -> None:
+ """Build from a writable snapshot, never from signed/read-only source."""
+ 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
+ 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] | Mapping[Path, Path], root: Path, *, source: Path) -> None:
+ """Snapshot core and plugin build inputs into a fresh generation."""
+ source = source.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)
+
+ core_pyproject = source / "pyproject.toml"
+ core_text = core_pyproject.read_text(encoding="utf-8-sig")
+
+ members = [_workspace_member(source, root, identity=identity).relative_to(root).as_posix()
+ for identity, source in member_sources(plugin_dirs).items()
+ if _is_member_candidate(source)]
+
- lines = [core_text.rstrip("\n")]
+ if members:
- lines.append("")
- lines.append("[tool.uv.workspace]")
- lines.append("members = [" + ", ".join(f'"{m}"' for m in sorted(members)) + "]")
++ import tomllib
+
- text = "\n".join(lines) + "\n"
++ import tomli_w
++
++ document = tomllib.loads(core_text)
++ _core_release_quarantine(document, source / "uv.lock")
++ document.setdefault("tool", {}).setdefault("uv", {})["workspace"] = {"members": sorted(members)}
++ text = tomli_w.dumps(document)
++ else:
++ # Byte-identical to core: a member-less generation syncs frozen against core's own lock.
++ text = core_text.rstrip("\n") + "\n"
+ target = root / "pyproject.toml"
+ _copy_core_inputs(source, root)
+ target.write_text(text, encoding="utf-8")
+
+
++def _core_release_quarantine(document: dict, core_lock: Path) -> None:
++ """Scope core's ``exclude-newer`` to the packages in core's own lock.
++
++ The quarantine covers Hermes's own dependencies only; a plugin's dependencies
++ follow the plugin's own policy, so a catalog pin floored on a fresh release still
++ installs. A global cutoff would filter plugin-only packages too, so it moves onto
++ every registry package core locks. A plugin still cannot drag one of those past
++ the window, and core's own ``= false`` exemptions stay as written.
++ """
++ import re
++ import tomllib
++
++ settings = document.get("tool", {}).get("uv", {})
++ cutoff = settings.pop("exclude-newer", None)
++ if cutoff is None:
++ return
++
++ def normalized(name: str) -> str:
++ return re.sub(r"[-_.]+", "-", name).lower()
++
++ per_package = {normalized(name): value
++ for name, value in settings.get("exclude-newer-package", {}).items()}
++ for package in tomllib.loads(core_lock.read_text(encoding="utf-8-sig")).get("package", []):
++ if "registry" in package.get("source", {}):
++ per_package.setdefault(normalized(package["name"]), cutoff)
++ settings["exclude-newer-package"] = per_package
++
++
+def _is_member_candidate(plugin_dir: Path) -> bool:
+ return read_python_declaration(plugin_dir).is_member
+
+
+def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None) -> list[Path]:
+ """Resolve the effective plugin selection without filtering dependency declarations."""
+ from pm.plugins_state import _is_directory, enabled_plugins_ordered
+
+ selection = enabled_plugins_ordered(
+ proposed_home=proposed_home, enabled=enabled, disabled=disabled, installing=installing,
+ )
+ 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
+ proposed = installing is not None and plugin_dir.resolve() == installing.resolve()
+ if not proposed and not _is_directory(plugin_dir):
+ plugin_dir = paths.repo_root() / "plugins" / relative
+ if proposed or _is_directory(plugin_dir):
+ members.append(plugin_dir)
+ return list(dict.fromkeys(members))
+
+
+def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:
+ """Keep every selected member or refuse an incompatible selection."""
+ selected = enabled_plugin_dirs(proposed_home=proposed_home, enabled=enabled, disabled=disabled)
+ members = []
+ for path in selected:
+ declaration = read_python_declaration(path)
+ reason = manifest_version_error(declaration.manifest, path.name)
+ if reason:
+ raise InstallError("venv", reason)
+ if declaration.is_member:
+ members.append(path)
+ return members
+
+
+def _member_key(identity: Path) -> str:
+ """``<plugin dir name>-<sha256(path)[:16]>``: the hash keeps two same-named plugins from
+ different homes apart; the name is what a user sees in uv's conflict text
+ (``hermes-plugin-<key> depends on …``) — a bare hash told them nothing to disable."""
+ import re
+
+ digest = hashlib.sha256(str(identity.resolve()).encode()).hexdigest()[:16]
+ name = re.sub(r"[^a-z0-9._-]+", "-", identity.name.lower()).strip("-.") or "plugin"
+ return f"{name}-{digest}"
+
+
+def _workspace_member(plugin_dir: Path, root: Path, *, identity: Path) -> Path:
+ """Keep workspace members with their generation, not a temporary install clone."""
+ import json
+ import tomllib
+
+ key = _member_key(identity)
+ declaration = read_python_declaration(plugin_dir)
+ pyproject = declaration.pyproject
+ if pyproject is not None:
+ member = root / "plugin-sources" / key
+ shutil.copytree(plugin_dir, member, symlinks=True,
+ ignore=_member_ignored)
+ document = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))
+ changed = declaration.install_requirements != declaration.requirements
+ if changed:
+ document["project"]["dependencies"] = list(declaration.install_requirements)
+ for sources in document.get("tool", {}).get("uv", {}).get("sources", {}).values():
+ for spec in sources if isinstance(sources, list) else [sources]:
+ if not isinstance(spec, dict) or "path" not in spec:
+ continue
+ relative = Path(spec["path"])
+ if relative.is_absolute():
+ continue
+ resolved = (plugin_dir / relative).resolve()
+ if resolved.is_relative_to(plugin_dir.resolve()):
+ continue # The referenced tree was copied with this member.
+ spec["path"] = (identity / relative).resolve().as_posix()
+ changed = True
+ if changed:
+ import tomli_w
+
+ (member / "pyproject.toml").write_text(tomli_w.dumps(document), encoding="utf-8")
+ return member
+ specs = declaration.install_requirements
+ member = root / "plugin-deps" / key
+ member.mkdir(parents=True)
+ (member / "pyproject.toml").write_text(
+ f'[project]\nname = "hermes-plugin-{key}"\nversion = "0.0.0"\n'
+ 'requires-python = ">=3.11"\n'
+ f'dependencies = {json.dumps(specs)}\n[tool.uv]\npackage = false\n',
+ encoding="utf-8",
+ )
+ return member
+
+
+def install_node_sidecar(
+ plugin_dir: Path,
+ *,
+ explicit: bool = False,
+) -> Optional[str]:
+ """Install plugin-local dependencies using PM's paired npm/Node context.
+
+ Explicit user consent permits acquisition even when on-demand installs
+ are disabled. Returns None on success, otherwise a diagnostic.
+ """
+ package_json = plugin_dir / "package.json"
+ if not package_json.is_file():
+ return None # nothing to install
+
+ import pm
+ from pm.install import lazy_installs_allowed
+
+ # Tool availability does not authorize mutation of the sidecar itself.
+ if not explicit and not lazy_installs_allowed():
+ return "lazy installs are disabled — run `hermes plugins install` and approve Node dependencies"
+
+ # a lockfile means reproducible `npm ci`; plain `npm install` otherwise
+ install_cmd = ["ci"] if (plugin_dir / "package-lock.json").is_file() else ["install"]
+ try:
+ runner = pm.ensure("npm", explicit=explicit)
+ # Resolve inside the composed context, including npm.cmd on Windows;
+ # CreateProcess does not search a child's replacement PATH itself.
+ npm = shutil.which("npm", path=runner.env.get("PATH", ""))
+ if npm is None:
+ return "npm is missing from the prepared PM environment"
+ proc = runner.run(
+ [npm, *install_cmd, "--no-audit", "--no-fund"],
+ cwd=str(plugin_dir),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=900,
+ )
+ except Exception as exc:
+ return f"npm {install_cmd[0]} failed to run: {exc}"
+ if proc.returncode != 0:
+ tail = (proc.stderr or proc.stdout or "").strip()[-300:]
+ return f"npm {install_cmd[0]} exited {proc.returncode}: {tail}"
+ return None
+
+
+def lock_and_sync(
+ plugin_dirs: list[Path] | Mapping[Path, Path],
+ extras: list[str],
+ *,
+ root: Path,
+ source: Path,
+ seed_lock: Path | None,
+ environment: PythonEnvironment,
+ frozen: bool = False,
+ replay: Path | None = None,
+) -> None:
+ """Prepare a fresh generation using explicit inputs and a prepared engine.
+
+ The caller selects the seed; uv retains its compatible versions. Repair
+ copies the recorded build inputs and never reads current manifests.
+ Resolver conflicts remain distinct from download/build failures.
+ """
+ if root.exists() or root.is_symlink():
+ raise InstallError("venv", f"workspace must be fresh: {root}")
+ if replay is None:
+ _generate_pyproject(plugin_dirs, root, source=source)
+ if seed_lock is not None:
+ (root / "uv.lock").write_bytes(seed_lock.read_bytes())
+ else:
+ if not (replay / "pyproject.toml").is_file() or not (replay / "uv.lock").is_file():
+ raise InstallError("venv", f"recorded workspace is missing: {replay}")
+ # Sibling generations keep external relative paths at the same depth;
+ # snapshotted members and their exact lock travel with the workspace.
+ # Use the snapshot's exclusions: build/ may hold an in-tree backend.
+ shutil.copytree(replay, root, symlinks=True, ignore=_member_ignored)
+ frozen = True
+
+ environment.sync(root, extras=extras, frozen=frozen)
diff --cc providers/__init__.py
index 1827fac013d,9f09982b514..50392743f5d
--- a/providers/__init__.py
+++ b/providers/__init__.py
@@@ -226,17 -248,29 +248,34 @@@ def _bound_home_layer() -> tuple[_HomeL
layer = _HOME_LAYERS.get(key)
if layer is None:
layer = _HOME_LAYERS[key] = _HomeLayer()
- # Stamps are read before the scan: a plugin that lands mid-scan changes them and the next lookup
- # picks it up. Two threads scanning the same home at once only re-import idempotently.
- if home is not None and (stamps := _plugin_dir_stamps(home)) != layer.stamps:
+ return layer, home, key
+
+
+ def _refresh_home_layer(layer: _HomeLayer, home: Path | None, key: str, *, force: bool = False) -> bool:
+ """Re-stat the layer's plugin dirs when due (or *force*d); True when it stat'ed this call.
+
+ Stamps are read before the scan: a plugin that lands mid-scan changes them and the next
+ check picks it up. Checking on a short cadence keeps a newly installed plugin discoverable
+ without making every model lookup perform two filesystem stats.
+ """
+ now = time.monotonic()
+ if home is None or not (
+ force
+ or layer.stamp_checked_at is None
+ or now - layer.stamp_checked_at >= _PLUGIN_DIR_STAMP_TTL_SECONDS
+ ):
+ return False
+ stamps = _plugin_dir_stamps(home)
+ if stamps != layer.stamps:
_scan_home_layer(layer, key)
layer.stamps = stamps
+ # Publish the completed layer only after its stamp is current. Auth sync
+ # calls list_providers(), which re-enters this function; syncing from
+ # _scan_home_layer before this assignment recursively rescanned forever.
+ if _discovered and not _discovering:
+ _sync_auth_registry()
- return layer
+ layer.stamp_checked_at = now
+ return True
def _plugin_dir_stamps(home: Path) -> tuple:
diff --cc pyproject.toml
index 4cd87db1f9e,fad1079011e..adb27a5fb7a
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -547,42 -430,10 +547,42 @@@ build-backend = "setuptools.build_meta
[project.scripts]
hermes = "hermes_cli.main:main"
- hermes-agent = "run_agent:main"
+ hermes-agent = "agent.legacy_cli:main"
hermes-acp = "acp_adapter.entry:main"
+# Per-extra platform gates (settled 2026-09-02): an extra listed here is
+# only installable on platforms matching the marker. pm consults this
+# table (pm.extras.extra_supported) — ensure_import/sync_venv refuse a
+# gated-off extra with a clear message instead of resolving it to an
+# empty set. The per-package markers inside the extra stay (uv's
+# resolver needs them for --all-extras); this table is the readable
+# single-authority for WHICH extra is supported WHERE.
+
+[tool.hermes.extras-platforms]
+# mautrix[encryption] → python-olm: linux-only wheels, no win/darwin build.
+matrix = "sys_platform == 'linux'"
+# grpcio (via google-cloud-pubsub) has no win_arm64 wheel.
+google-chat = "platform_machine != 'ARM64' or sys_platform != 'win32'"
+# qdrant-client → grpcio (via mem0ai) has no win_arm64 wheel.
+mem0 = "platform_machine != 'ARM64' or sys_platform != 'win32'"
+# Match the engine dependency markers so PM refuses an unsupported install.
+wake-openwakeword = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or sys_platform != 'darwin')"
+# faster-whisper's closure is prebuilt-only: ctranslate2 has no win_arm64 wheel and onnxruntime
+# none for darwin-x64. Its ANCHOR is faster_whisper, so an unsupported machine could install the
+# extra, rebuild the whole dependency environment and still fail the anchor on every retry.
+# Gate the extra that carries only faster-whisper; [voice] also has ungated deps (sounddevice,
+# numpy) and stays installable, see test_declared_extra_gates_match_dependency_selection.
+stt-whisper = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or platform_system != 'Darwin')"
+# NeuTTS excludes Python 3.14. KittenTTS's misaki dependency excludes 3.13+.
+neutts = "python_version < '3.14'"
+kittentts = "python_version < '3.13'"
+piper = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or sys_platform != 'darwin')"
+
[tool.uv]
+# 3.11 is an install bridge for pre-PM updaters, never a runtime, so the lock
+# covers 3.14 only. Without this the lock must resolve every supported version,
+# where extras that only ever coexist on 3.14 (kittentts vs neutts) conflict.
+environments = ["python_version >= '3.14'"]
override-dependencies = [
# discord.py's latest published version, 2.7.1, pins pynacl at <1.6. however, pynacl 1.5.0 has known vulnerabilities.
# discord.py has updated pynacl to 1.6 on `main`, but has not yet published a patch release.
diff --cc scripts/run_tests.sh
index 9a8f1a10ad0,7db21c42d69..f1456e7bfbc
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@@ -161,10 -138,8 +161,11 @@@ _pf86="$(env | sed -n 's/^ProgramFiles(
# HERMES_GIT_SHA build-arg the workflow bakes in).
#
# These are test-infrastructure knobs, not credentials — same class as the
- # HERMES_RUN_SLOW_PET_TESTS / HERMES_E2E_BROWSER opt-ins already forwarded.
+ # HERMES_RUN_SLOW_PET_TESTS / HERMES_E2E_BROWSER / HERMES_RUN_E2E opt-ins
+ # forwarded below.
+# SSL_CERT_FILE/DIR are trust-store locations: the pinned interpreter's
+# OpenSSL has no compiled-in bundle path on NixOS, so network tests (PM
+# downloads, channel reads) need the host's pointer to verify TLS.
# Keep this an explicit allowlist (no HERMES_TEST_* glob) so the "no
# credential can leak" property stays auditable at a glance.
TEST_ENV=()
diff --cc tests/agent/test_model_metadata.py
index 3d8736f3c70,3d8736f3c70..fb3bd89fb60
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@@ -13,7 -13,7 +13,7 @@@ Coverage levels
import time
import pytest
--import yaml
++import hermes_yaml as yaml
from unittest.mock import patch, MagicMock
from agent.model_metadata import (
@@@ -492,8 -492,8 +492,8 @@@ class TestCodexOAuthContextLength
base_url = "https://chatgpt.com/backend-api/codex"
stale_key = f"gpt-5.5@{base_url}"
other_key = "other-model@https://api.openai.com/v1/"
-- import yaml as _yaml
-- cache_file.write_text(_yaml.dump({"context_lengths": {
++ import hermes_yaml as _yaml
++ cache_file.write_text(_yaml.safe_dump({"context_lengths": {
stale_key: stale_context,
other_key: 128_000,
}}))
@@@ -916,7 -916,7 +916,7 @@@ class TestNousPortalContextResolution
base_url = "https://inference-api.nousresearch.com/v1"
stale_key = f"qwen3.6-plus@{base_url}"
other_key = "other-model@https://api.openai.com/v1"
-- cache_file.write_text(yaml.dump({"context_lengths": {
++ cache_file.write_text(yaml.safe_dump({"context_lengths": {
stale_key: 1_000_000, # pre-fix OR-derived value
other_key: 128_000, # unrelated, must survive
}}))
diff --cc tests/cron/test_oneshot_guard_warning.py
index 86246a4d9f5,ed19e0f3b03..e6952e4a665
--- a/tests/cron/test_oneshot_guard_warning.py
+++ b/tests/cron/test_oneshot_guard_warning.py
@@@ -28,7 -33,8 +32,7 @@@ def temp_home(tmp_path, monkeypatch)
monkeypatch.setattr("cron.jobs.OUTPUT_DIR", tmp_path / "cron" / "output")
return tmp_path
- def test_rearmed_consumed_oneshot_is_removed_without_firing(temp_home):
-
+ def test_guard_warns_on_rearmed_consumed_record(temp_home, caplog):
job = create_job(
prompt="x",
schedule=(_hermes_now() + timedelta(hours=1)).isoformat(),
diff --cc tests/gateway/test_model_command_custom_providers.py
index 00000000000,baa59f02467..a1549b1fc4a
mode 000000,100644..100644
--- a/tests/gateway/test_model_command_custom_providers.py
+++ b/tests/gateway/test_model_command_custom_providers.py
@@@ -1,0 -1,61 +1,61 @@@
+ """Regression tests for gateway /model support of config.yaml custom_providers."""
+
+ import threading
+
+ import pytest
-import yaml
++import hermes_yaml as yaml
+
+ from gateway.config import Platform
+ from gateway.platforms.event import MessageEvent, MessageType
+ from gateway.run import GatewayRunner
+ from gateway.session import SessionSource
+
+
+ def _make_runner():
+ runner = object.__new__(GatewayRunner)
+ runner.adapters = {}
+ runner._voice_mode = {}
+ runner._session_model_overrides = {}
+ return runner
+
+
+ def _make_event(text="/model"):
+ return MessageEvent(
+ text=text,
+ message_type=MessageType.TEXT,
+ source=SessionSource(platform=Platform.TELEGRAM, chat_id="12345", chat_type="dm"),
+ )
+
+
+ @pytest.mark.asyncio
+ async def test_direct_model_switch_runs_off_the_event_loop(tmp_path, monkeypatch):
+ """A direct `/model <name>` switch must run switch_model() on a worker thread so the
+ blocking models.dev HTTP fetch can't freeze the gateway event loop (#20525)."""
+ from hermes_cli.model_switch import ModelSwitchResult
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ yaml.safe_dump({"model": {"default": "gpt-5.4", "provider": "openrouter"}}),
+ encoding="utf-8",
+ )
+
+ import gateway.run as gateway_run
+
+ monkeypatch.setattr(gateway_run, "_hermes_home", hermes_home)
+
+ switch_threads: list[int] = []
+
+ # Fail the switch so the handler returns before _finish_switch (which needs
+ # full runner state) — only where the switch ran matters here.
+ def _fake_switch(**kwargs):
+ switch_threads.append(threading.get_ident())
+ return ModelSwitchResult(success=False, error_message="nope")
+
+ monkeypatch.setattr("hermes_cli.model_switch.switch_model", _fake_switch)
+
+ result = await _make_runner()._handle_model_command(_make_event("/model gpt-5.4"))
+
+ assert switch_threads, "switch_model never ran"
+ assert threading.get_ident() not in switch_threads, "switch_model ran inline on the event-loop thread"
+ assert result is not None and "nope" in result
diff --cc tests/gateway/test_multiplex_hot_serve.py
index a8429633617,84a8ba3b07b..de5e6b40371
--- a/tests/gateway/test_multiplex_hot_serve.py
+++ b/tests/gateway/test_multiplex_hot_serve.py
@@@ -111,6 -111,82 +111,82 @@@ async def test_opt_out_rescans_and_opt_
assert runner._started.count("solo") == 2
+ @pytest.mark.asyncio
+ async def test_parked_profile_boot_and_reconcile(tmp_path, monkeypatch, caplog):
+ runner, home = _runner(tmp_path, monkeypatch)
+ secondary = _mkprofile(home, "worker")
+ marker = secondary / "gateway.parked"
+ marker.touch()
+ # Boot uses the real directory enumerator and config loaders, no bot/network.
+ del runner._start_one_profile_adapters
+ runner._register_config_hooks = lambda *a, **kw: None
+ caplog.set_level("INFO")
+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):
+ await runner._start_secondary_profile_adapters()
+ assert _served_record(home) == ["default"]
+ assert "profile 'worker' is parked (gateway.parked); not served by this gateway" in caplog.text
+ marker.unlink()
+ assert (await runner.reconcile_served_profiles())["added"] == ["worker"]
+ assert _served_record(home) == ["default", "worker"]
+ marker.touch()
+ assert (await runner.reconcile_served_profiles())["removed"] == ["worker"]
+ assert _served_record(home) == ["default"]
+
+
+ @pytest.mark.asyncio
+ async def test_profile_control_verbs_round_trip_and_refusals(tmp_path, monkeypatch):
+ from gateway import run_profile_reconcile as verbs
+ runner, home = _runner(tmp_path, monkeypatch)
+ secondary = _mkprofile(home, "worker", "DISCORD_BOT_TOKEN=worker-token\n")
+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):
+ await runner._start_secondary_profile_adapters()
+ stop = verbs.unserve_profile_verb(runner)
+ start = verbs.serve_profile_verb(runner)
+ for handler, name in [(stop, "default"), (stop, "missing"), (start, "missing"),
+ (start, "worker"), (start, "default")]:
+ assert (await asyncio.to_thread(handler, {"name": name}))["error"]
+ old = runner._profile_adapters["worker"][Platform.DISCORD]
+ answer = await asyncio.to_thread(stop, {"name": "worker"})
+ assert answer["unserved"] == "worker"
+ assert answer["served_profiles"] == _served_record(home) == ["default"]
+ assert old.disconnected
+ marker = secondary / "gateway.parked"
+ marker.touch()
+ assert (await asyncio.to_thread(start, {"name": "worker"}))["error"]
+ marker.unlink()
+ (secondary / ".env").write_text("DISCORD_BOT_TOKEN=new-worker-token\n")
+ answer = await asyncio.to_thread(start, {"name": "worker"})
+ assert answer["served"] == "worker"
+ assert answer["served_profiles"] == _served_record(home) == ["default", "worker"]
+ assert runner._profile_adapters["worker"][Platform.DISCORD].token.endswith("new-worker-token\n")
+
+
+ @pytest.mark.asyncio
+ async def test_profile_lifecycle_over_real_control_socket(tmp_path, monkeypatch):
+ from gateway.run import _start_gateway_start_control_socket
+ from gateway import control_socket
+ runner, home = _runner(tmp_path, monkeypatch)
+ secondary = _mkprofile(home, "worker")
+ with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):
+ await runner._start_secondary_profile_adapters()
+ server = await _start_gateway_start_control_socket(runner)
+ assert server is not None
+ try:
+ (secondary / "gateway.parked").touch()
+ stopped = await asyncio.to_thread(control_socket.request_unserve_profile, home, "worker")
+ assert stopped["unserved"] == "worker"
+ assert _served_record(home) == ["default"]
+ refused = await asyncio.to_thread(control_socket.request_serve_profile_hot, home, "worker")
+ assert "parked" in refused["error"]
+ (secondary / "gateway.parked").unlink()
+ started = await asyncio.to_thread(control_socket.request_serve_profile_hot, home, "worker")
+ assert started["served"] == "worker"
+ assert _served_record(home) == ["default", "worker"]
+ finally:
+ await server.stop()
+
+
@pytest.mark.asyncio
async def test_created_then_credentialed_profile_is_served_without_restart(tmp_path, monkeypatch):
runner, home = _runner(tmp_path, monkeypatch)
diff --cc tests/gateway/test_proxy_mode.py
index 2c5a9a9c64e,67c6e0696f2..c4aed5c87a0
--- a/tests/gateway/test_proxy_mode.py
+++ b/tests/gateway/test_proxy_mode.py
@@@ -156,6 -161,47 +156,46 @@@ class TestResolveProxyUrl
assert resolve_proxy_url(target_hosts=["149.154.167.220"]) is None
-
+ class TestMacosProxyProbeCache:
+ """``scutil --proxy`` is a ~11 ms fork and resolve_proxy_url runs it on the SEND path —
+ per chunk of an outbound message and per media attachment."""
+
+ SCUTIL_OUT = "<dictionary> {\n HTTPEnable : 1\n HTTPProxy : 10.0.0.1\n HTTPPort : 3128\n}"
+
+ @pytest.fixture(autouse=True)
+ def _isolate(self):
+ import gateway.platforms.base as base
+ base.reset_macos_proxy_cache()
+ yield
+ base.reset_macos_proxy_cache()
+
+ def _count_forks(self, monkeypatch):
+ import gateway.platforms.base as base
+ calls = []
+
+ def fake(*a, **kw):
+ calls.append(a)
+ return self.SCUTIL_OUT
+ monkeypatch.setattr(base.subprocess, "check_output", fake)
+ return base, calls
+
+ def test_repeated_probes_fork_scutil_once(self, monkeypatch):
+ base, calls = self._count_forks(monkeypatch)
+ results = [base._detect_macos_system_proxy() for _ in range(10)]
+ assert len(calls) == 1, f"expected 1 scutil fork for 10 probes, got {len(calls)}"
+ assert results == ["http://10.0.0.1:3128"] * 10
+
+ def test_expired_ttl_re_reads(self, monkeypatch):
+ base, calls = self._count_forks(monkeypatch)
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(base.time, "monotonic", lambda: clock["t"])
+ base._detect_macos_system_proxy()
+ clock["t"] += base._MACOS_PROXY_TTL_SECONDS + 1
+ base._detect_macos_system_proxy()
+ assert len(calls) == 2
+
+
class TestRunAgentProxyDispatch:
"""Test that _run_agent() delegates to proxy when configured."""
diff --cc tests/hermes_cli/test_actual_provider.py
index 97c7b172daa,8115a6c5d17..b2efb8b970f
--- a/tests/hermes_cli/test_actual_provider.py
+++ b/tests/hermes_cli/test_actual_provider.py
@@@ -31,6 -32,20 +31,19 @@@ def _clear_actual_env(monkeypatch)
monkeypatch.delenv("ACTUAL_BASE_URL", raising=False)
monkeypatch.delenv("ACTUAL_API_MODE", raising=False)
-
+ def _clear_ca_bundle_env(monkeypatch):
+ # Importing gateway.run (any earlier test in the same process) writes
+ # SSL_CERT_FILE into os.environ; an explicit CA env var disables the
+ # scoped certifi default these tests assert.
+ for key in (
+ "HERMES_CA_BUNDLE",
+ "SSL_CERT_FILE",
+ "REQUESTS_CA_BUNDLE",
+ "CURL_CA_BUNDLE",
+ ):
+ monkeypatch.delenv(key, raising=False)
+
+
def test_actual_aliases_and_profile_metadata():
profile = get_provider_profile("actual-computer")
diff --cc tests/hermes_cli/test_backup.py
index 62e7843ad25,43587fc3849..25401dde684
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@@ -1717,7 -1726,7 +1717,7 @@@ class TestRunPreUpdateBackup
@staticmethod
def _set_mode(hermes_home, value):
-- import yaml
++ import hermes_yaml as yaml
(hermes_home / "config.yaml").write_text(yaml.safe_dump({
"_config_version": 22,
"updates": {"pre_update_backup": value},
@@@ -1909,7 -1918,7 +1909,7 @@@ class TestRestoreConfigModelSettingsIfR
return cfg
def test_restores_rewritten_provider_and_dropped_moa(self, tmp_path):
-- import yaml
++ import hermes_yaml as yaml
from hermes_cli.backup import restore_config_model_settings_if_rewritten
hermes_home = tmp_path / ".hermes"
@@@ -1960,7 -1969,7 +1960,7 @@@
def test_preserves_legitimate_update_writes(self, tmp_path):
"""Only protected keys are restored — a version bump or a new section
the migration legitimately wrote must survive the restore."""
-- import yaml
++ import hermes_yaml as yaml
from hermes_cli.backup import restore_config_model_settings_if_rewritten
hermes_home = tmp_path / ".hermes"
diff --cc tests/hermes_cli/test_completer_config_reads.py
index b7a3fc46323,b7a3fc46323..008018df7a8
--- a/tests/hermes_cli/test_completer_config_reads.py
+++ b/tests/hermes_cli/test_completer_config_reads.py
@@@ -7,7 -7,7 +7,7 @@@ import o
from unittest.mock import patch
import pytest
--import yaml
++import hermes_yaml as yaml
import hermes_cli.commands_completion as commands_mod
diff --cc tests/hermes_cli/test_desktop_lifecycle_windows_live.py
index 00000000000,c77a2b1b2b2..4f08c6855f0
mode 000000,100644..100644
--- a/tests/hermes_cli/test_desktop_lifecycle_windows_live.py
+++ b/tests/hermes_cli/test_desktop_lifecycle_windows_live.py
@@@ -1,0 -1,161 +1,161 @@@
+ """LIVE Windows E2E for the Desktop-lifecycle cold-start skip (#76129/#76745).
+
+ Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``
+ lane). Exercises the REAL ownership predicate against REAL processes:
+
+ 1. A real child process self-registers in the REAL spawn ledger as a
+ ``serve`` purpose with THIS process as its live spawner — ownership
+ must hold, and ``_pause_windows_gateways_for_update`` must return None
+ (no cold-start plan) even with an autostart artifact present.
+ 2. Kill the child (dead serve) — ownership drops, the pause plan carries
+ ``cold_start_if_installed`` again.
+ 3. Venv-holder fallback rung: a real venv-python process with true
+ ``serve`` argv is detected by the scan and, having a live parent,
+ confers ownership; the token classifier rejects a ``kanban
+ --preserve-cache`` lookalike (the #90778 class the salvage fixed).
+ """
+
+ from __future__ import annotations
+
+ import json
+ import os
+ import subprocess
+ import sys
+ import time
+ from pathlib import Path
+
+ import pytest
+
-pytestmark = pytest.mark.windows_only
++pytestmark = pytest.mark.platforms("windows")
+
+ PROJECT_ROOT = Path(__file__).resolve().parents[2]
+
+
+ def _wait_until(predicate, timeout: float = 15.0, interval: float = 0.05) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(interval)
+ return bool(predicate())
+
+
+ def _argv_visible(pid: int, marker: str) -> bool:
+ """True once the process table shows *pid* with *marker* in its argv."""
+ import psutil
+
+ try:
+ return marker in " ".join(psutil.Process(pid).cmdline())
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ return False
+
+
+ @pytest.fixture()
+ def sleeper():
+ procs: list[subprocess.Popen] = []
+
+ def _spawn(*tail: str) -> subprocess.Popen:
+ p = subprocess.Popen(
+ [sys.executable, "-c", "import time; time.sleep(120)", *tail],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ procs.append(p)
+ assert _wait_until(lambda: _argv_visible(p.pid, "time.sleep(120)")), "sleeper argv never visible"
+ return p
+
+ yield _spawn
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ p.wait()
+
+
+ def _write_ledger(entries: list[dict]) -> None:
+ from hermes_cli import process_identity as pid_mod
+
+ path = pid_mod._ledger_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(entries), encoding="utf-8")
+
+
+ def _entry(proc: subprocess.Popen, purpose: str = "serve") -> dict:
+ import psutil
+
+ from hermes_cli import process_identity as pid_mod
+
+ return {
+ "install": pid_mod.install_id(None),
+ "pid": proc.pid,
+ "create_time": psutil.Process(proc.pid).create_time(),
+ "purpose": purpose,
+ "spawner_pid": os.getpid(),
+ "spawner_create": psutil.Process(os.getpid()).create_time(),
+ }
+
+
+ def test_live_supervised_serve_suppresses_cold_start(sleeper, monkeypatch, tmp_path):
+ from hermes_cli import gateway as hermes_gateway
+ from hermes_cli import gateway_windows
+ from hermes_cli import update_cmd
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ (tmp_path / ".hermes").mkdir()
+
+ serve = sleeper()
+ _write_ledger([_entry(serve)])
+
+ assert update_cmd._desktop_owns_gateway_lifecycle() is True
+
+ # Autostart artifact present + no gateway running: WITHOUT ownership the
+ # pause phase would plan a cold start; WITH it, no plan.
+ monkeypatch.setattr(hermes_gateway, "find_gateway_pids", lambda **_k: [])
+ monkeypatch.setattr(gateway_windows, "is_installed", lambda: True)
+ assert update_cmd._pause_windows_gateways_for_update() is None
+
+ # Dead serve → ownership drops → plan returns.
+ serve.kill()
+ serve.wait()
+ assert _wait_until(lambda: update_cmd._desktop_owns_gateway_lifecycle() is False)
+ token = update_cmd._pause_windows_gateways_for_update()
+ assert token is not None and token.get("cold_start_if_installed") is True
+
+
+ def test_holder_scan_fallback_respects_token_classifier(sleeper, monkeypatch, tmp_path):
+ from hermes_cli import update_cmd
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ (tmp_path / ".hermes").mkdir()
+ _write_ledger([]) # force the fallback rung
+
+ # Real process whose argv carries genuine serve shape, visible to psutil.
+ serve_like = sleeper("-m", "hermes_cli.main", "serve")
+ # Lookalike from the #90778 class — must NOT confer ownership.
+ kanban_like = sleeper("-m", "hermes_cli.main", "kanban", "--preserve-cache")
+
+ import psutil
+
+ # Snapshot both holder rows while both processes are alive. Building the
+ # kanban row later (after the serve kill) would re-read the dead serve pid,
+ # raise NoSuchProcess and hand the fallback an empty scan, which returns
+ # False without ever reaching the token classifier.
+ serve_row, kanban_row = (
+ (p.pid, psutil.Process(p.pid).name(), " ".join(psutil.Process(p.pid).cmdline()))
+ for p in (serve_like, kanban_like)
+ )
+ assert "--preserve-cache" in kanban_row[2]
+
+ monkeypatch.setattr(
+ "hermes_cli.main._detect_venv_python_processes", lambda: [serve_row, kanban_row]
+ )
+ # serve-shaped holder with a live parent (us) → owns
+ assert update_cmd._desktop_owns_gateway_lifecycle() is True
+
+ # Only the (still live) kanban lookalike left → classifier rejects → does not own
+ serve_like.kill()
+ serve_like.wait()
+ assert kanban_like.poll() is None
+ monkeypatch.setattr(
+ "hermes_cli.main._detect_venv_python_processes", lambda: [kanban_row]
+ )
+ assert update_cmd._desktop_owns_gateway_lifecycle() is False
diff --cc tests/hermes_cli/test_doctor.py
index f05ca868819,6379ba9ad3d..2a3337f410b
--- a/tests/hermes_cli/test_doctor.py
+++ b/tests/hermes_cli/test_doctor.py
@@@ -1433,109 -1373,137 +1433,179 @@@ class TestDoctorDeprecatedConfigAndEnv
assert doctor_config.collect_deprecated_env_vars(None) == []
-def test_macos_tcc_grant_check_is_silent_off_macos(monkeypatch, capsys, tmp_path):
- """Off macOS the TCC check prints nothing, even with a bundle present."""
- monkeypatch.setattr(doctor_platform, "_desktop_app_bundle", lambda: tmp_path / "Hermes.app")
- doctor_platform.check_macos_tcc_grants()
- assert capsys.readouterr().out == ""
+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_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_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 out
+
+def test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):
+ helper = TestDoctorMemoryProviderSection()
+
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: True)
+ monkeypatch.setattr(
+ "tools.browser_tool_lightpanda_fallback.lightpanda_engine_status",
+ lambda: (False, "cloud provider Browserbase is selected"),
+ )
+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
+ assert "browser.engine=lightpanda is shadowed" in out
+ assert "Browserbase" in out
+
+
+
+
+def test_run_doctor_warns_when_lightpanda_binary_missing(monkeypatch, tmp_path):
+ helper = TestDoctorMemoryProviderSection()
+
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: True)
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback.lightpanda_engine_status", lambda: (True, "Browser Use mode"))
+ monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: None)
+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
+ assert "Lightpanda selected but binary not found" in out
+
+
+def test_docker_daemon_probe_uses_version_not_info(monkeypatch):
+ """`docker info` needs the /info endpoint, which socket proxies commonly block, so doctor reported
+ "daemon not running" against a working DOCKER_HOST (#72927). `docker version` (/version) is what the
+ backend itself probes with."""
+ from hermes_cli import doctor_tools
+
+ calls: list = []
+ monkeypatch.setattr(doctor_tools, "find_docker", lambda: "/usr/bin/docker")
+ monkeypatch.setattr(doctor_tools, "_run_ok", lambda cmd, timeout, **kw: calls.append(cmd) or True)
+ monkeypatch.setattr(doctor_tools, "_require", lambda *a, **k: None)
+
+ doctor_tools._check_docker_backend("docker", False, [])
+
+ assert calls == [["/usr/bin/docker", "version"]]
+
+
+def test_doctor_reports_auxiliary_blocks_that_do_not_resolve(tmp_path, monkeypatch):
+ """A routed auxiliary.<task> block that the runtime resolver rejects is a doctor finding, not a
+ silent fall-back to the main model (#116055); a resolvable one is not flagged."""
+ import hermes_yaml as yaml
+ from hermes_cli import doctor_config
+
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+ cfg_file = tmp_path / "config.yaml"
+ cfg_file.write_text(yaml.safe_dump({"auxiliary": {
+ "background_review": {"provider": "no-such-provider", "model": "m"},
+ "compression": {"provider": "openai", "model": "gpt-x", "base_url": "https://gateway.example/v1", "api_key": "gw"},
+ }}))
+ issues = []
+ doctor_config._validate_auxiliary_config(cfg_file, issues)
+ assert len(issues) == 1 and "auxiliary.background_review" in issues[0] and "no-such-provider" in issues[0]
++
++
+ class TestMacOSTCCGrants:
+ """macOS TCC grant persistence check (#86385): a cdhash-pinned DR (pre-#73681
+ local builds) silently resets Screen Recording/Accessibility grants on every
+ rebuild while the Settings toggle stays ON."""
+
+ @staticmethod
+ def _darwin_bundle(monkeypatch, tmp_path, dr):
+ monkeypatch.setattr(doctor_platform, "_desktop_app_bundle", lambda: tmp_path / "Hermes.app")
+ if dr is not ...:
+ monkeypatch.setattr(doctor_platform, "_macos_desktop_dr", lambda app: dr)
+
+ def test_silent_without_desktop_bundle(self, monkeypatch, capsys):
+ monkeypatch.setattr(doctor_platform, "_desktop_app_bundle", lambda: None)
+ doctor_platform.check_macos_tcc_grants()
+ assert capsys.readouterr().out == ""
+
+ def test_warns_on_cdhash_pinned_dr(self, monkeypatch, capsys, tmp_path):
+ self._darwin_bundle(
+ monkeypatch, tmp_path,
+ 'designated => identifier "com.nousresearch.hermes" and cdhash H"97e692f3890f781fa0ad5ad6cb9d769cfaf42628"',
+ )
+ doctor_platform.check_macos_tcc_grants()
+ out = capsys.readouterr().out
+ assert "TCC grants will reset after every update" in out
+ assert "hermes update" in out
+ assert "signing identity is stable" not in out
+
+ def test_identifier_dr_is_stable_with_upgrade_hint_and_repair_info(self, monkeypatch, capsys, tmp_path):
+ self._darwin_bundle(monkeypatch, tmp_path, 'designated => identifier "com.nousresearch.hermes"')
+ doctor_platform.check_macos_tcc_grants()
+ out = capsys.readouterr().out
+ assert "TCC signing identity is stable" in out
+ assert "--setup-tcc-identity" in out
+ assert "tccutil reset ScreenCapture com.nousresearch.hermes" in out
+
+ def test_certificate_anchored_dr_is_stable_without_upgrade_hint(self, monkeypatch, capsys, tmp_path):
+ self._darwin_bundle(
+ monkeypatch, tmp_path,
+ 'designated => identifier "com.nousresearch.hermes" and certificate root = H"aabbcc"',
+ )
+ doctor_platform.check_macos_tcc_grants()
+ out = capsys.readouterr().out
+ assert "TCC signing identity is stable" in out
+ assert "--setup-tcc-identity" not in out
+ assert "tccutil reset ScreenCapture com.nousresearch.hermes" in out
+
+ @pytest.mark.parametrize("failure", ["none", "empty", "timeout", "no_codesign"])
+ def test_unreadable_dr_warns_and_never_claims_stable(self, monkeypatch, capsys, tmp_path, failure):
+ """codesign failing, hanging, missing or printing nothing degrades to a
+ warning; an empty DR must not false-positive as a stable identity."""
+ if failure in ("none", "empty"):
+ self._darwin_bundle(monkeypatch, tmp_path, None if failure == "none" else "")
+ else:
+ self._darwin_bundle(monkeypatch, tmp_path, ...)
+ if failure == "timeout":
+ monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/codesign")
+
+ def _timeout(*args, **kwargs):
+ raise subprocess.TimeoutExpired(cmd=["codesign"], timeout=15)
+
+ monkeypatch.setattr(subprocess, "run", _timeout)
+ else:
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ doctor_platform.check_macos_tcc_grants()
+ out = capsys.readouterr().out
+ assert "could not read code-signing requirement" in out
+ assert "stable" not in out
-
-
-def test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):
- helper = TestDoctorMemoryProviderSection()
-
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: True)
- monkeypatch.setattr(
- "tools.browser_tool_lightpanda_fallback.lightpanda_engine_status",
- lambda: (False, "cloud provider Browserbase is selected"),
- )
- out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
- assert "browser.engine=lightpanda is shadowed" in out
- assert "Browserbase" in out
-
-
-
-
-def test_run_doctor_warns_when_lightpanda_binary_missing(monkeypatch, tmp_path):
- helper = TestDoctorMemoryProviderSection()
-
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: True)
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback.lightpanda_engine_status", lambda: (True, "Browser Use mode"))
- monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: None)
- out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
- assert "Lightpanda selected but binary not found" in out
-
-
-def test_docker_daemon_probe_uses_version_not_info(monkeypatch):
- """`docker info` needs the /info endpoint, which socket proxies commonly block, so doctor reported
- "daemon not running" against a working DOCKER_HOST (#72927). `docker version` (/version) is what the
- backend itself probes with."""
- from hermes_cli import doctor_tools
-
- calls: list = []
- monkeypatch.setattr(doctor_tools, "find_docker", lambda: "/usr/bin/docker")
- monkeypatch.setattr(doctor_tools, "_run_ok", lambda cmd, timeout, **kw: calls.append(cmd) or True)
- monkeypatch.setattr(doctor_tools, "_require", lambda *a, **k: None)
-
- doctor_tools._check_docker_backend("docker", False, [])
-
- assert calls == [["/usr/bin/docker", "version"]]
-
-
-def test_doctor_reports_auxiliary_blocks_that_do_not_resolve(tmp_path, monkeypatch):
- """A routed auxiliary.<task> block that the runtime resolver rejects is a doctor finding, not a
- silent fall-back to the main model (#116055); a resolvable one is not flagged."""
- import yaml
- from hermes_cli import doctor_config
-
- monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
- cfg_file = tmp_path / "config.yaml"
- cfg_file.write_text(yaml.safe_dump({"auxiliary": {
- "background_review": {"provider": "no-such-provider", "model": "m"},
- "compression": {"provider": "openai", "model": "gpt-x", "base_url": "https://gateway.example/v1", "api_key": "gw"},
- }}))
- issues = []
- doctor_config._validate_auxiliary_config(cfg_file, issues)
- assert len(issues) == 1 and "auxiliary.background_review" in issues[0] and "no-such-provider" in issues[0]
diff --cc tests/hermes_cli/test_fast_command.py
index d6989ca3c5c,1fece97263c..4bf1b753901
--- a/tests/hermes_cli/test_fast_command.py
+++ b/tests/hermes_cli/test_fast_command.py
@@@ -197,8 -222,15 +206,8 @@@ class TestAnthropicFastMode(unittest.Te
assert model_supports_fast_mode("anthropic/claude-sonnet-4.6") is False
assert model_supports_fast_mode("anthropic/claude-opus-4-7") is False
-
-
-
-
-
-
-
def test_fast_command_hidden_for_anthropic_sonnet(self):
- """Sonnet doesn't support fast mode (Opus 4.8/5 only) — /fast must be hidden."""
+ """Sonnet doesn't support fast mode (Opus 4.8/5/5.5 only) — /fast must be hidden."""
cli_mod = _import_cli()
stub = SimpleNamespace(
provider="anthropic", requested_provider="anthropic",
diff --cc tests/hermes_cli/test_fleet_config_migration_windows_live.py
index 00000000000,d633f301a7b..56d8b7e73db
mode 000000,100644..100644
--- a/tests/hermes_cli/test_fleet_config_migration_windows_live.py
+++ b/tests/hermes_cli/test_fleet_config_migration_windows_live.py
@@@ -1,0 -1,51 +1,51 @@@
+ """LIVE Windows E2E for the fleet-wide config migration (wine2e lane).
+
+ Real profile homes on the Windows filesystem, real migration pipeline,
+ fresh-process semantics via HERMES_HOME env — mirrors the Linux live E2E.
+ """
+ import sys
+ from pathlib import Path
+
+ import pytest
-import yaml
++import hermes_yaml as yaml
+
+ WORKTREE = Path(__file__).resolve().parents[2]
+ sys.path.insert(0, str(WORKTREE))
+
-pytestmark = pytest.mark.windows_only
++pytestmark = pytest.mark.platforms("windows")
+
+
+ def test_fleet_config_migration_live_windows(tmp_path, monkeypatch):
+ active = tmp_path / "hermes-home"
+ profiles = active / "profiles"
+ for name, ver in [("research", 12), ("work", 25)]:
+ home = profiles / name
+ home.mkdir(parents=True)
+ (home / "config.yaml").write_text(
+ yaml.safe_dump({"_config_version": ver, "model": {"provider": "nous"}}),
+ encoding="utf-8",
+ )
+ active.mkdir(exist_ok=True)
+ (active / "config.yaml").write_text(
+ yaml.safe_dump({"_config_version": 12}), encoding="utf-8"
+ )
+ monkeypatch.setenv("HERMES_HOME", str(active))
+
+ import hermes_cli.update_cmd as update_cmd
+ from hermes_cli.config import DEFAULT_CONFIG
+
+ latest = int(DEFAULT_CONFIG["_config_version"])
+ migrated = update_cmd._migrate_sibling_profile_configs()
+
+ by_name = {m[0]: m for m in migrated}
+ assert set(by_name) == {"research", "work"}, migrated
+ assert by_name["research"][1] == 12 and by_name["research"][2] == latest
+
+ for name in ("research", "work"):
+ on_disk = yaml.safe_load((profiles / name / "config.yaml").read_text())
+ assert on_disk["_config_version"] == latest
+ assert on_disk["model"]["provider"] == "nous"
+
+ # active untouched; idempotent second run
+ assert yaml.safe_load((active / "config.yaml").read_text())["_config_version"] == 12
+ assert update_cmd._migrate_sibling_profile_configs() == []
diff --cc tests/hermes_cli/test_gateway.py
index b44e1c513ac,9f69e45f16b..8663aeccdcf
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@@ -520,7 -503,98 +520,98 @@@ class TestRestartWaitsForApiServerPort
class TestStopProfileGateway:
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_windows_stop_drains_marker_before_force_termination(self, monkeypatch):
+ """Windows must let the marker watcher run before escalating (#112750)."""
+ import hermes_cli.gateway_windows as gateway_windows
+ pid = 12345
+ calls = []
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda: pid)
+ monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
+ monkeypatch.setattr(
+ gateway_windows,
+ "_drain_gateway_pid",
+ lambda target, timeout: calls.append(("drain", target, timeout)) or True,
+ )
+ monkeypatch.setattr(
+ gateway_windows,
+ "_force_terminate_known_gateway_pids",
+ lambda pids: calls.append(("force", pids)),
+ )
+ monkeypatch.setattr(gateway.os, "kill", lambda *_: calls.append(("kill",)))
+ monkeypatch.setattr("gateway.status._pid_exists", lambda target: False)
+ monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)
+ monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
+
+ assert gateway.stop_profile_gateway() is True
+ assert calls == [("drain", pid, 7.0)]
+
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_windows_stop_force_terminates_only_after_drain_timeout(self, monkeypatch):
+ """A wedged Windows gateway still has a bounded force-stop fallback (#112750)."""
+ import hermes_cli.gateway_windows as gateway_windows
+
+ pid = 12345
+ calls = []
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda: pid)
+ monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
+ monkeypatch.setattr("gateway.status.get_process_start_time", lambda target: 100)
+ monkeypatch.setattr(
+ gateway_windows,
+ "_drain_gateway_pid",
+ lambda target, timeout: calls.append(("drain", target, timeout)) or False,
+ )
+ monkeypatch.setattr(
+ gateway_windows,
+ "_force_terminate_known_gateway_pids",
+ lambda pids: calls.append(("force", pids)),
+ )
+ monkeypatch.setattr(gateway.os, "kill", lambda *_: calls.append(("kill",)))
+ monkeypatch.setattr("gateway.status._pid_exists", lambda target: False)
+ monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)
+ monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
+
+ assert gateway.stop_profile_gateway() is True
+ assert calls == [("drain", pid, 7.0), ("force", {pid: 100})]
+
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_windows_stop_force_kill_carries_pre_drain_identity(self, monkeypatch):
+ """The post-drain taskkill must be guarded by the start time captured BEFORE the <=30 s drain:
+ a PID recycled during the wait shows a different start time, so ``terminate_pid``'s mismatch
+ refusal fires instead of killing an unrelated process. Reading it at kill time is a vacuous
+ self-comparison."""
+ import gateway.status as status
+ import hermes_cli.gateway_windows as gateway_windows
+
+ pid = 4242
+ calls = []
+ clock = {"now": 0.0}
+ alive = {"value": True}
+
+ monkeypatch.setattr(gateway_windows.time, "monotonic", lambda: clock["now"])
+ monkeypatch.setattr(
+ gateway_windows.time, "sleep", lambda _s: clock.__setitem__("now", clock["now"] + 10.0)
+ )
+ monkeypatch.setattr(gateway_windows, "_windows_stop_drain_timeout", lambda: 7.0)
+ monkeypatch.setattr(status, "get_running_pid", lambda: pid if alive["value"] else None)
+ monkeypatch.setattr(status, "write_planned_stop_marker", lambda target: None)
+ monkeypatch.setattr(status, "_pid_exists", lambda target: alive["value"])
+ # The original gateway (start time 100) exits during the drain and its PID is recycled (999).
+ monkeypatch.setattr(
+ status, "get_process_start_time", lambda target: 100 if clock["now"] < 7.0 else 999
+ )
+
+ def _terminate(target, force=False, expected_start_time=None):
+ calls.append((target, force, expected_start_time))
+ alive["value"] = False
+
+ monkeypatch.setattr(status, "terminate_pid", _terminate)
+ monkeypatch.setattr(status, "remove_pid_file", lambda: None)
+ monkeypatch.setattr(gateway, "_reap_unsupervised_gateway_orphans", lambda **_: False)
+
+ assert gateway.stop_profile_gateway() is True
+ assert calls == [(pid, True, 100)]
def test_stop_profile_gateway_keeps_pid_file_when_process_still_running(self, monkeypatch):
calls = {"kill": 0, "alive_probes": 0, "remove": 0, "reap_calls": 0}
@@@ -580,10 -654,179 +671,183 @@@
assert killed_pid in reap_extra_excludes[0]
+ class TestReapUnsupervisedGatewayOrphansMacOS:
+ """Tests that the orphan reaper excludes launchd-managed PIDs on macOS.
+
+ Regression guard: without the ``is_macos()`` exclusion of
+ ``_get_service_pids()``, the reaper would SIGTERM the launchd-supervised
+ gateway every time Hermes Desktop opens (``hermes serve`` calls
+ ``_reap_unsupervised_gateway_orphans`` during startup).
+ """
+
+ def test_macos_excludes_launchd_pid_from_kill(self, monkeypatch):
+ """A launchd-managed PID must not appear in the orphan kill list."""
+ launchd_pid = 52615
+
+ monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
+
+ # _get_service_pids returns the launchd-managed gateway PID.
+ # (accepts all_profiles: the reaper asks for the whole fleet, #74075)
+ monkeypatch.setattr(
+ gateway, "_get_service_pids", lambda all_profiles=False: {launchd_pid}
+ )
+ # No pidfile-recorded gateway in this scenario.
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
+
+ # find_gateway_pids returns the launchd PID plus a real orphan.
+ # The reaper should only kill the orphan, not the launchd PID.
+ orphan_pid = 99998
+ monkeypatch.setattr(
+ gateway,
+ "find_gateway_pids",
+ lambda exclude_pids=None: [p for p in [launchd_pid, orphan_pid] if p not in (exclude_pids or set())],
+ )
+
+ killed_pids = []
+ monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
+ monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", lambda pid: None)
+ monkeypatch.setattr("time.sleep", lambda _: None)
+ monkeypatch.setattr("time.monotonic", lambda: 1.0)
+
+ result = gateway._reap_unsupervised_gateway_orphans()
+
+ assert result is True # at least one orphan was reaped
+ killed = [pid for pid, _ in killed_pids]
+ assert orphan_pid in killed # the real orphan was killed
+ assert launchd_pid not in killed # the launchd PID was NOT killed
+
+
+ class TestReapUnsupervisedGatewayOrphansWindows:
+ """Tests that the orphan reaper spares the recorded gateway PID and its
+ supervision chain on Windows.
+
+ Regression guard: without the Windows exemption of the recorded healthy
+ gateway PID (and its parent chain), the reaper would SIGTERM/SIGKILL a
+ Scheduled-Task-supervised gateway every time Hermes Desktop opens
+ (``hermes serve`` calls ``_reap_unsupervised_gateway_orphans`` during
+ startup). The Scheduled-Task bootstrap's argv matches the gateway scan,
+ so it is reaped as an "orphan" — and when the bootstrap dies, the
+ detached gateway it spawned exits with it (#86098).
+ """
+
+ @staticmethod
+ def _install_fake_psutil(monkeypatch, chain):
+ """Install a fake psutil module exposing the given process chain."""
+ by_pid = {proc.pid: proc for proc in chain}
+ fake_psutil = SimpleNamespace(Process=lambda pid: by_pid[pid])
+ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
+
+ def test_windows_excludes_recorded_pid_and_bootstrap_from_kill(self, monkeypatch):
+ """The recorded gateway PID and its bootstrap parent must not be killed."""
+ recorded_pid = 52615 # detached gateway recorded in gateway.pid
+ bootstrap_pid = 52616 # Scheduled-Task bootstrap (argv matches scan)
+ orphan_pid = 99998 # a real orphan that should still be reaped
+
+ monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
+
+ # gateway.pid records the detached gateway; its parent is the
+ # Scheduled-Task bootstrap whose argv matches the gateway scan.
+ bootstrap = SimpleNamespace(pid=bootstrap_pid, parent=lambda: None)
+ recorded = SimpleNamespace(pid=recorded_pid, parent=lambda: bootstrap)
+ self._install_fake_psutil(monkeypatch, [recorded, bootstrap])
+
+ # get_running_pid() returns the recorded healthy gateway PID.
+ monkeypatch.setattr(
+ "gateway.status.get_running_pid", lambda cleanup_stale=True: recorded_pid
+ )
+
+ # find_gateway_pids returns the recorded PID, its bootstrap parent
+ # and a real orphan. The reaper should only kill the orphan.
+ monkeypatch.setattr(
+ gateway,
+ "find_gateway_pids",
+ lambda exclude_pids=None: [
+ p
+ for p in [recorded_pid, bootstrap_pid, orphan_pid]
+ if p not in (exclude_pids or set())
+ ],
+ )
+
+ killed_pids = []
+ marked_pids = []
+ monkeypatch.setattr(gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig)))
+ monkeypatch.setattr("gateway.status._pid_exists", lambda pid: False)
+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", marked_pids.append)
+ monkeypatch.setattr("time.sleep", lambda _: None)
+ monkeypatch.setattr("time.monotonic", lambda: 1.0)
+
+ result = gateway._reap_unsupervised_gateway_orphans()
+
+ assert result is True # at least one orphan was reaped
+ assert marked_pids == [orphan_pid] # the real orphan was asked to drain
+ assert killed_pids == [] # Windows SIGTERM must not TerminateProcess
+
+ def test_windows_raw_record_supplies_exclusion_when_validation_fails(
+ self, monkeypatch
+ ):
+ """A registration that fails liveness VALIDATION must still shield
+ the recorded PID from the sweep.
+
+ get_running_pid returns None whenever the record fails validation
+ (start-time mismatch, argv drift, lock hiccup) — regardless of
+ cleanup_stale, which only controls unlinking. The exclusion set is
+ therefore built from the RAW pidfile/lock records: a stale recorded
+ PID at worst spares one process, while a validation false-negative
+ would TerminateProcess a healthy standalone gateway (#87158).
+ """
+ recorded_pid = 52615
+
+ monkeypatch.setattr(gateway, "supports_systemd_services", lambda: False)
+
+ recorded = SimpleNamespace(pid=recorded_pid, parent=lambda: None)
+ self._install_fake_psutil(monkeypatch, [recorded])
+
+ # The raw record is present on disk; the validated probe rejects it.
+ monkeypatch.setattr(
+ "gateway.status._read_pid_record", lambda *a, **k: {"pid": recorded_pid}
+ )
+ monkeypatch.setattr(
+ "gateway.status._read_gateway_lock_record", lambda *a, **k: None
+ )
+ probe_kwargs = []
+
+ def failing_validation(*a, cleanup_stale=True, **k):
+ probe_kwargs.append(cleanup_stale)
+ return None
+
+ monkeypatch.setattr(
+ "gateway.status.get_running_pid", failing_validation
+ )
+ monkeypatch.setattr(
+ gateway,
+ "find_gateway_pids",
+ lambda exclude_pids=None: [
+ p for p in [recorded_pid] if p not in (exclude_pids or set())
+ ],
+ )
+
+ killed_pids = []
+ monkeypatch.setattr(
+ gateway.os, "kill", lambda pid, sig: killed_pids.append((pid, sig))
+ )
+
+ result = gateway._reap_unsupervised_gateway_orphans()
+
+ assert probe_kwargs == [False], (
+ "the fallback probe must still be non-destructive so the sweep "
+ f"never unlinks the record it just read, got {probe_kwargs}"
+ )
+ assert result is False
+ assert killed_pids == [] # the standalone gateway survived
+
+
+
+
+
+
class TestReaperCandidateIsSupervisorOwned:
"""Regression for the Windows pidfile-less supervisor-owned case (#83683).
diff --cc tests/hermes_cli/test_gateway_proc_fallback.py
index c55ffd9637b,8ce5f932555..54cedd7b38e
--- a/tests/hermes_cli/test_gateway_proc_fallback.py
+++ b/tests/hermes_cli/test_gateway_proc_fallback.py
@@@ -115,14 -114,128 +115,128 @@@ class TestProcFallback
mock_ps.assert_not_called() # /proc dir existed, so ps not called
+ class TestPsFallbackBsdCompat:
+ """The ps fallback must use flags BSD/macOS ps accepts (#73626, #74075).
+
+ ``ps -A eww`` fails on macOS (BSD ``e`` is not the procps flag), which
+ made gateway discovery silently return nothing whenever /proc is absent.
+ Linux-only like ``TestProcFallback``: the real host selects the POSIX arm
+ and only /proc's absence is faked, to force the ps rung.
+ """
+
+ def test_ps_fallback_uses_bsd_compatible_flags_and_columns(self):
+ with (
+ patch("os.path.isdir", side_effect=lambda p: p != "/proc"),
+ patch("hermes_cli.gateway._get_ancestor_pids", return_value=set()),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(returncode=1, stdout="", stderr="")
+ assert not gateway_mod._scan_gateway_pids(set())
+
+ ps_calls = [
+ c[0][0] for c in mock_run.call_args_list if c[0] and c[0][0] and c[0][0][0] == "ps"
+ ]
+ assert ps_calls, "ps was not invoked at all"
+ ps_call = ps_calls[0]
+ assert "-Aww" in ps_call and "eww" not in " ".join(ps_call), ps_call
+ assert "-o" in ps_call and "pid=,command=" in ps_call, ps_call
class TestGetServicePidsAllProfiles:
"""_get_service_pids(all_profiles=...) discovery across profiles."""
- @pytest.mark.macos_only
++ @pytest.mark.platforms("macos")
+ def test_default_scope_uses_current_profile_label(self):
+ """Without all_profiles, only the current profile's launchd agent is
+ located (per-label domain-explicit probe, #73627)."""
+ located = []
+ def _fake_locate(label):
+ located.append(label)
+ return ("gui/501", 123)
+ with (
+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False),
+ patch(
+ "hermes_cli.gateway.get_launchd_label",
+ return_value="ai.hermes.gateway.myprofile",
+ ),
+ patch(
+ "hermes_cli.gateway._locate_launchd_gateway_service",
+ side_effect=_fake_locate,
+ ),
+ patch("subprocess.run") as mock_run,
+ ):
+ pids = gateway_mod._get_service_pids()
+
+ assert pids == {123}
+ # Default scope: exactly the current profile's label, no fleet
+ # enumeration and no bare `launchctl list` scan.
+ assert located == ["ai.hermes.gateway.myprofile"]
+ launchctl_calls = [
+ c[0][0]
+ for c in mock_run.call_args_list
+ if c[0] and c[0][0] and c[0][0][0] == "launchctl"
+ ]
+ assert launchctl_calls == []
+
- @pytest.mark.macos_only
++ @pytest.mark.platforms("macos")
+ def test_all_profiles_enumerates_all_gateway_labels(self):
+ """With all_profiles=True, every install-derived gateway label is
+ located (#73627), and the bare ``launchctl list`` prefix scan still
+ widens the EXCLUDE set with unmapped ai.hermes.gateway* agents
+ (#74075 belt-and-suspenders)."""
+ located = []
+ label_pids = {
+ "ai.hermes.gateway": 123,
+ "ai.hermes.gateway-profile-b": 456,
+ }
+ def _fake_locate(label):
+ located.append(label)
+ pid = label_pids.get(label)
+ return ("gui/501", pid) if pid else (None, None)
+
+ with (
+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False),
+ patch(
+ "hermes_cli.gateway.get_launchd_label",
+ return_value="ai.hermes.gateway",
+ ),
+ patch(
+ "hermes_cli.gateway.launchd_gateway_labels_for_install",
+ return_value=["ai.hermes.gateway", "ai.hermes.gateway-profile-b"],
+ ),
+ patch(
+ "hermes_cli.gateway._locate_launchd_gateway_service",
+ side_effect=_fake_locate,
+ ),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(
+ returncode=0,
+ stdout=(
+ "999\t0\tai.hermes.gateway-unmapped\n"
+ "789\t0\tcom.apple.some.other.agent\n"
+ ),
+ stderr="",
+ )
+ pids = gateway_mod._get_service_pids(all_profiles=True)
+
+ # Label-derived fleet + prefix-scan stragglers; non-gateway excluded.
+ assert pids == {123, 456, 999}
+ assert 789 not in pids
+ assert sorted(located) == [
+ "ai.hermes.gateway",
+ "ai.hermes.gateway-profile-b",
+ ]
+ launchctl_calls = [
+ c[0][0]
+ for c in mock_run.call_args_list
+ if c[0] and c[0][0] and c[0][0][0] == "launchctl"
+ ]
+ assert launchctl_calls == [["launchctl", "list"]]
def test_all_profiles_preserves_systemd_behavior(self):
"""systemd scope is unaffected by the all_profiles switch — it already
diff --cc tests/hermes_cli/test_macos_fda_guidance.py
index 00000000000,fc470721cdf..9eb081ccdba
mode 000000,100644..100644
--- a/tests/hermes_cli/test_macos_fda_guidance.py
+++ b/tests/hermes_cli/test_macos_fda_guidance.py
@@@ -1,0 -1,90 +1,90 @@@
+ """macOS Full Disk Access onboarding guidance (issue #52010 follow-up).
+
+ One FDA grant silences every per-folder TCC prompt permanently. Doctor reports
+ the state and prints the one-switch setup; ``hermes setup`` surfaces the same
+ tip at onboarding. The probe reads the FDA-gated TCC db directory, which
+ returns EPERM (no dialog) without the grant; any other error is indeterminate
+ and must stay silent. The probe is gated on the real host, so the macOS
+ branches run on the macOS lane and the off-macOS silence runs on Linux.
+ """
+
+ import contextlib
+ import io
+ import os
+ import pathlib
+
+ import pytest
+
+ from hermes_cli import doctor_platform
+ from hermes_cli.setup_quick import _print_macos_fda_tip
+
+
+ def _capture(fn):
+ buf = io.StringIO()
+ with contextlib.redirect_stdout(buf):
+ fn()
+ return buf.getvalue()
+
+
+ @pytest.fixture
+ def home(tmp_path, monkeypatch):
+ monkeypatch.setattr(pathlib.Path, "home", classmethod(lambda cls: tmp_path))
+ return tmp_path
+
+
+ @pytest.fixture
+ def tcc_dir(home):
+ tcc = home / "Library" / "Application Support" / "com.apple.TCC"
+ tcc.mkdir(parents=True)
+ return tcc
+
+
+ @pytest.fixture
+ def fda_denied(tcc_dir, monkeypatch):
+ """The TCC dir exists but listing it fails with EPERM, exactly as without the grant."""
+ real_listdir = os.listdir
+
+ def _listdir(path="."):
+ if pathlib.Path(path) == tcc_dir:
+ raise PermissionError(13, "Operation not permitted", str(path))
+ return real_listdir(path)
+
+ monkeypatch.setattr(os, "listdir", _listdir)
+ return tcc_dir
+
+
+ def test_doctor_and_setup_are_silent_off_macos(tcc_dir):
+ assert _capture(doctor_platform.check_macos_full_disk_access) == ""
+ assert _capture(_print_macos_fda_tip) == ""
+
+
+ def test_doctor_reports_granted_without_guidance(tcc_dir):
+ out = _capture(doctor_platform.check_macos_full_disk_access)
+ assert "Full Disk Access granted" in out
+ assert "Privacy_AllFiles" not in out
+
+
+ def test_doctor_prints_one_switch_guidance_when_denied(fda_denied):
+ out = _capture(doctor_platform.check_macos_full_disk_access)
+ assert "Privacy_AllFiles" in out
+ assert "granted" not in out
+
+
+ def test_doctor_is_silent_when_probe_is_indeterminate(home):
+ """Missing TCC dir (FileNotFoundError, not EPERM) must not nag."""
+ assert _capture(doctor_platform.check_macos_full_disk_access) == ""
+
+
+ def test_setup_tip_is_silent_when_already_granted(tcc_dir):
+ assert _capture(_print_macos_fda_tip) == ""
+
+
+ def test_setup_tip_printed_when_denied(fda_denied):
+ out = _capture(_print_macos_fda_tip)
+ assert "Privacy_AllFiles" in out
diff --cc tests/hermes_cli/test_model_cache_parallel_prefetch.py
index 867e2806f5d,885ed635f4f..f5a80e61465
--- a/tests/hermes_cli/test_model_cache_parallel_prefetch.py
+++ b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
@@@ -184,6 -187,47 +184,46 @@@ class TestPrefetchProviderModelsParalle
_prefetch_provider_models_parallel([])
fetch.assert_not_called()
- # ---------------------------------------------------------------------------
- # Integration: prefetch is called from list_authenticated_providers
- # ---------------------------------------------------------------------------
+ def test_skips_ttl_expired_entries_the_serial_path_can_still_serve(self):
+ """A TTL-expired entry inside the stale-serve window is not prefetched.
+
+ ``cached_provider_model_ids`` returns such an entry from disk right
+ away and revalidates on a background thread, so blocking the picker
+ on a parallel fetch buys nothing. ``_PROVIDER_MODELS_STALE_SERVE_MAX``
+ is far longer than ``_PROVIDER_MODELS_CACHE_TTL``, so this is the
+ state every picker open a TTL after the previous one lands in.
+ """
+ import hermes_cli.models as models_mod
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ expired = time.time() - models_mod._PROVIDER_MODELS_CACHE_TTL - 60
+ cache = {"openrouter": {"fp": "fp", "at": expired, "models": ["m1"]}}
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids") as fetch:
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ fetch.assert_not_called()
+
+ def test_fetches_curated_fallback_rows_past_their_short_ttl(self):
+ """A curated-fallback row is served only for ``_PROVIDER_MODELS_FALLBACK_TTL``
+ and never through the stale window, so the serial call blocks on it and the
+ parallel prefetch must fetch it."""
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ cache = {"openrouter": {"fp": "fp", "at": time.time() - 7200, "models": ["m1"],
+ "fallback": True}}
+ fetched = []
+
+ def mock_fetch(slug, force_refresh=False):
+ fetched.append(slug)
+ return ["m1"]
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch), \
+ patch("hermes_cli.models.update_provider_cache_entry"):
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ assert fetched == ["openrouter"]
-
diff --cc tests/hermes_cli/test_personality_none.py
index 3c224902aaa,f10f0d21fcb..1ffa1753262
--- a/tests/hermes_cli/test_personality_none.py
+++ b/tests/hermes_cli/test_personality_none.py
@@@ -7,7 -7,8 +7,7 @@@ persistence flows exclusively through p
import os
import pytest
from unittest.mock import MagicMock, patch
--import yaml
-
++import hermes_yaml as yaml
# ── CLI tests ──────────────────────────────────────────────────────────────
@@@ -112,7 -114,7 +112,7 @@@ class TestGatewayPersonalityNone
"display": {"personality": "helpful"},
}
config_file = tmp_path / "config.yaml"
-- config_file.write_text(yaml.dump(config_data))
++ config_file.write_text(yaml.safe_dump(config_data))
p1, p2 = self._gateway_env(tmp_path)
with p1, p2:
@@@ -136,7 -138,7 +136,7 @@@
}
}
config_file = tmp_path / "config.yaml"
-- config_file.write_text(yaml.dump(config_data))
++ config_file.write_text(yaml.safe_dump(config_data))
p1, p2 = self._gateway_env(tmp_path)
with p1, p2:
diff --cc tests/hermes_cli/test_pet_toggle.py
index b9c14425017,b9c14425017..7ebc01e13ae
--- a/tests/hermes_cli/test_pet_toggle.py
+++ b/tests/hermes_cli/test_pet_toggle.py
@@@ -12,7 -12,7 +12,7 @@@ def test_pets_cli_quoted_false_disables
bool('false') is True — before the is_truthy_value fix, _has_active_pet
reported an active pet and /pet toggle DISABLED instead of enabling.
"""
-- import yaml
++ import hermes_yaml as yaml
from hermes_cli.pets import _has_active_pet, toggle_pet_display
diff --cc tests/hermes_cli/test_plan_reconciliation_windows_live.py
index 385eb4396d6,dce4b7e321c..51ff4bcc136
--- a/tests/hermes_cli/test_plan_reconciliation_windows_live.py
+++ b/tests/hermes_cli/test_plan_reconciliation_windows_live.py
@@@ -19,10 -21,29 +21,29 @@@ sys.path.insert(0, str(WORKTREE)
import pytest
- pytestmark = pytest.mark.platforms("windows") # live Windows E2E
+ # The stand-in wears a `gateway run` argv; the test spawns and reaps it itself.
-pytestmark = [pytest.mark.windows_only, pytest.mark.spawns_gateway_lookalike]
++pytestmark = [pytest.mark.platforms("windows"), pytest.mark.spawns_gateway_lookalike]
+
+
+ def _wait_until(predicate, timeout: float = 15.0, interval: float = 0.05) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(interval)
+ return bool(predicate())
+
+
+ def _argv_visible(pid: int, marker: str) -> bool:
+ """True once the process table shows *pid* with *marker* in its argv."""
+ import psutil
+
+ try:
+ return marker in " ".join(psutil.Process(pid).cmdline())
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ return False
- @pytest.mark.spawns_gateway_lookalike
def test_plan_reconciliation_live_windows(tmp_path, monkeypatch):
home = tmp_path / ".hermes"
home.mkdir()
diff --cc tests/hermes_cli/test_plugin_event_bus.py
index a34617d8507,a34617d8507..2e7719acc01
--- a/tests/hermes_cli/test_plugin_event_bus.py
+++ b/tests/hermes_cli/test_plugin_event_bus.py
@@@ -358,7 -358,7 +358,7 @@@ def test_recursion_cap_terminates(caplo
def test_manifest_parse_reads_emits_listens(tmp_path):
"""parse_manifest_file picks up optional emits/listens from plugin.yaml."""
-- import yaml
++ import hermes_yaml as yaml
plugin_dir = tmp_path / "myplug"
plugin_dir.mkdir()
@@@ -386,7 -386,7 +386,7 @@@
def test_plugins_show_includes_emits_listens(tmp_path, monkeypatch, capsys):
-- import yaml
++ import hermes_yaml as yaml
from hermes_cli import plugins_cmd
plugin_dir = tmp_path / "showplug"
diff --cc tests/hermes_cli/test_plugin_manifest_v2.py
index b29f92449cd,ebf91fb3779..e6ffff0769b
--- a/tests/hermes_cli/test_plugin_manifest_v2.py
+++ b/tests/hermes_cli/test_plugin_manifest_v2.py
@@@ -7,10 -7,9 +7,10 @@@ declare-only seam (surfaced, never inst
"""
import logging
+from types import SimpleNamespace
import pytest
--import yaml
++import hermes_yaml as yaml
from hermes_cli.plugins import (
PluginManager,
@@@ -27,7 -26,7 +27,7 @@@ def _write_plugin(base, name, manifest_
manifest = {"name": name, "version": "0.1.0", "description": f"test {name}"}
if manifest_extra:
manifest.update(manifest_extra)
-- (plugin_dir / "plugin.yaml").write_text(yaml.dump(manifest))
++ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump(manifest))
(plugin_dir / "__init__.py").write_text(
f"def register(ctx):\n {register_body}\n"
)
@@@ -526,7 -525,7 +526,7 @@@ class TestBundledKeyShadowing
_write_plugin(home / "plugins", "impostor_dir", manifest_extra={"name": "genuine"},
register_body="import sys; sys._shadow_probe = 'impostor'")
(home / "plugins" / "impostor_dir" / "plugin.yaml").write_text(
-- yaml.dump({"name": "genuine", "version": "0.1.0", "description": "impostor"}))
++ yaml.safe_dump({"name": "genuine", "version": "0.1.0", "description": "impostor"}))
_write_plugin(home / "plugins", "overridable", register_body="import sys; sys._override_probe = 'user'")
_enable(home, ["genuine", "overridable"])
import sys
diff --cc tests/hermes_cli/test_plugin_packs.py
index 004c23db7f6,004c23db7f6..69daa4450d8
--- a/tests/hermes_cli/test_plugin_packs.py
+++ b/tests/hermes_cli/test_plugin_packs.py
@@@ -10,7 -10,7 +10,7 @@@ import jso
from unittest import mock
import pytest
--import yaml
++import hermes_yaml as yaml
from hermes_cli.plugin_packs import (
PackError,
diff --cc tests/hermes_cli/test_profile_delete_service_name.py
index 00000000000,789c72a7321..bafcd606c77
mode 000000,100644..100644
--- a/tests/hermes_cli/test_profile_delete_service_name.py
+++ b/tests/hermes_cli/test_profile_delete_service_name.py
@@@ -1,0 -1,51 +1,51 @@@
+ """Deleting a profile from a multiplexed process removes THAT profile's service, never the host's.
+
+ A multi-profile dashboard/tui-gateway process has ``set_multiplex_active(True)`` and the launch
+ home pinned for routed-profile decisions. ``DELETE /api/profiles/<name>`` then runs
+ ``profiles._cleanup_gateway_service`` in that same process, which switches the home to the victim
+ to resolve ``get_service_name()``. If that switch were invisible to ``get_hermes_home()`` the name
+ would resolve to the launch home's bare ``hermes-gateway`` and the cleanup would disable, stop and
+ unlink the HOST multiplexer's own unit.
+ """
+ from __future__ import annotations
+
+ from pathlib import Path
+
+ import pytest
+
+ from agent.secret_scope import set_multiplex_active
+ from hermes_cli import profiles
+
+
+ @pytest.fixture
+ def two_homes(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ launch = tmp_path / ".hermes"
+ victim = launch / "profiles" / "victim"
+ victim.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
+ unit_dir = tmp_path / "xdg" / "systemd" / "user"
+ unit_dir.mkdir(parents=True)
+ host_unit = unit_dir / "hermes-gateway.service"
+ victim_unit = unit_dir / "hermes-gateway-victim.service"
+ host_unit.write_text("[Service]\n")
+ victim_unit.write_text("[Service]\n")
+ return launch, victim, host_unit, victim_unit
+
+
+ def test_delete_from_a_pinned_multiplexer_targets_the_victims_unit_only(two_homes, monkeypatch):
+ launch, victim, host_unit, victim_unit = two_homes
+ calls: list[list[str]] = []
+ monkeypatch.setattr(profiles.subprocess, "run", lambda cmd, **kw: calls.append(list(cmd)))
+ set_multiplex_active(True) # the dashboard has served a second profile: launch home pinned
+
+ profiles._cleanup_gateway_service("victim", victim)
+
+ assert not victim_unit.exists()
+ assert host_unit.exists(), "the host multiplexer's own unit must survive a profile delete"
+ assert ["systemctl", "--user", "disable", "hermes-gateway-victim"] in calls
+ assert not any(c[:3] == ["systemctl", "--user", "disable"] and c[3] == "hermes-gateway" for c in calls)
+ # The caller's process home is restored: the process still is the launch profile afterwards.
+ assert profiles.os.environ["HERMES_HOME"] == str(launch)
diff --cc tests/hermes_cli/test_provider_live_curated_merge.py
index 516a0bad897,00cb627fa7a..2a456072932
--- a/tests/hermes_cli/test_provider_live_curated_merge.py
+++ b/tests/hermes_cli/test_provider_live_curated_merge.py
@@@ -83,3 -85,64 +83,60 @@@ class TestGenericProviderLiveCuratedMer
):
zen_result = set(provider_model_ids("opencode-zen"))
assert {"a", "b", "c"} <= zen_result
+
+ def test_opencode_go_merge_does_not_resurrect_delisted_model(self):
+ """#95914 bug class, end-to-end through provider_model_ids with the REAL curated floor:
+ the Go relay (GET /zen/go/v1/models) delisted ox-alpha-free 2026-09-09 but may keep LISTING
+ it (#111749). Neither the live listing nor the curated floor may resurrect it, or the picker
+ keeps offering a model that now 401s."""
+ assert "opencode-go" in _LIVE_FIRST_PICKER_PROVIDERS
+ live = ["deepseek-v4-flash", "kimi-k3", "omen-alpha", "ox-alpha-free"]
+
+ with (
+ patch("providers.get_provider_profile", return_value=self._make_profile(live)),
+ patch(
+ "hermes_cli.auth.resolve_api_key_provider_credentials",
+ return_value={"api_key": "k", "base_url": ""},
+ ),
+ ):
+ result = provider_model_ids("opencode-go")
+
+ assert "ox-alpha-free" not in result
+ assert {"deepseek-v4-flash", "kimi-k3", "omen-alpha"} <= set(result)
+
+ def test_opencode_zen_merge_does_not_resurrect_retired_model(self):
+ """#115496 bug class, end-to-end through provider_model_ids with the REAL curated floor:
+ the Zen relay (GET /zen/v1/models) retired x-preview-f-free (the picker-facing id for Ox
+ Alpha) 2026-09-19. The live-first merge must not resurrect it from the curated floor
+ (models_catalog_static.py still lists it first), or the picker keeps offering a model that
+ now 401s (REVERT-PROOF: a stale floor re-adds it and this fails)."""
+ assert "opencode-zen" in _LIVE_FIRST_PICKER_PROVIDERS
+ live = ["kimi-k3", "gpt-5.6-sol", "claude-opus-5"] # current Zen relay (no x-preview-f-free)
+
+ with (
+ patch("providers.get_provider_profile", return_value=self._make_profile(live)),
+ patch(
+ "hermes_cli.auth.resolve_api_key_provider_credentials",
+ return_value={"api_key": "k", "base_url": ""},
+ ),
+ ):
+ result = provider_model_ids("opencode-zen")
+
+ assert "x-preview-f-free" not in result
+ assert {"kimi-k3", "gpt-5.6-sol", "claude-opus-5"} <= set(result)
+
+ def test_opencode_zen_offline_catalog_drops_retired_model(self):
+ """#115496 without a key: no live fetch, so provider_model_ids serves the curated floor merged
+ with models.dev — both still carry the retired x-preview-f-free. The final rows must not."""
+ with (
+ patch("providers.get_provider_profile", return_value=self._make_profile(None)),
+ patch(
+ "hermes_cli.auth.resolve_api_key_provider_credentials",
+ return_value={"api_key": "", "base_url": ""},
+ ),
+ patch("agent.models_dev.list_agentic_models", return_value=["x-preview-f-free", "kimi-k3"]),
+ ):
+ result = provider_model_ids("opencode-zen")
+
+ assert "x-preview-f-free" not in result
+ assert "kimi-k3" in result
-
-
-
-
diff --cc tests/hermes_cli/test_set_config_value.py
index b2984f8fa3a,b2984f8fa3a..a6ff5221dc9
--- a/tests/hermes_cli/test_set_config_value.py
+++ b/tests/hermes_cli/test_set_config_value.py
@@@ -6,7 -6,7 +6,7 @@@ import o
from unittest.mock import patch
import pytest
--import yaml
++import hermes_yaml as yaml
from hermes_cli.config import (
config_command,
@@@ -148,7 -148,7 +148,7 @@@ class TestConfigYamlRouting
):
set_config_value("terminal.docker_shared_container_key", "off")
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved["terminal"]["docker_shared_container_key"] == "off"
@@@ -202,7 -202,7 +202,7 @@@ class TestConfigGetUnset
args = argparse.Namespace(config_command="unset", key="terminal.backend")
config_command(args)
-- import yaml
++ import hermes_yaml as yaml
reloaded = yaml.safe_load(_read_config(_isolated_hermes_home)) or {}
assert reloaded == {}
assert "TERMINAL_ENV=" not in _read_env(_isolated_hermes_home)
@@@ -221,7 -221,7 +221,7 @@@
args = argparse.Namespace(config_command="unset", key="platforms.teams.extra.access_token")
config_command(args)
-- import yaml
++ import hermes_yaml as yaml
reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))
assert "access_token" not in reloaded["platforms"]["teams"]["extra"]
assert reloaded["platforms"]["teams"]["extra"]["tenant_id"] == "tenant"
@@@ -309,7 -309,7 +309,7 @@@ class TestListNavigation
set_config_value("custom_providers.0.api_key", "new-a")
-- import yaml
++ import hermes_yaml as yaml
reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))
# The list must still be a list
assert isinstance(reloaded["custom_providers"], list)
@@@ -337,7 -337,7 +337,7 @@@
set_config_value("custom_providers.0.api_key", "rotated")
-- import yaml
++ import hermes_yaml as yaml
reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))
entry = reloaded["custom_providers"][0]
assert entry["api_key"] == "rotated"
@@@ -362,7 -362,7 +362,7 @@@
# the canonical path.
set_config_value("telegram.allowlist.1.role", "admin")
-- import yaml
++ import hermes_yaml as yaml
reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))
allowlist = reloaded["telegram"]["allowlist"]
assert isinstance(allowlist, list)
@@@ -381,7 -381,7 +381,7 @@@ class TestStringTypedConfigValues
"""Values stay strings when DEFAULT_CONFIG declares the leaf as a string."""
set_config_value("approvals.mode", value)
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved["approvals"]["mode"] == value
assert isinstance(saved["approvals"]["mode"], str)
@@@ -395,7 -395,7 +395,7 @@@
):
set_config_value(key, value)
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
node = saved
for part in key.split("."):
@@@ -408,7 -408,7 +408,7 @@@
# (schema validation, #34067); coercion behavior is unchanged.
set_config_value("custom.enabled", "off", force=True)
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved["custom"]["enabled"] is False
@@@ -653,8 -653,8 +653,8 @@@ class TestMappingGuard
"""
def _write_config(self, tmp_path, data: dict):
-- import yaml as _yaml
-- (tmp_path / "config.yaml").write_text(_yaml.dump(data))
++ import hermes_yaml as _yaml
++ (tmp_path / "config.yaml").write_text(_yaml.safe_dump(data))
def test_bare_model_shorthand_preserves_siblings(self, _isolated_hermes_home):
"""hermes config set model <id> → model.default, siblings survive."""
@@@ -668,7 -668,7 +668,7 @@@
})
set_config_value("model", "claude-sonnet-4-20250514")
config_text = _read_config(_isolated_hermes_home)
-- import yaml as _yaml
++ import hermes_yaml as _yaml
parsed = _yaml.safe_load(config_text)
assert parsed["model"]["default"] == "claude-sonnet-4-20250514"
assert parsed["model"]["provider"] == "openai-api"
@@@ -702,7 -702,7 +702,7 @@@
}
})
set_config_value("terminal", "zsh", force=True)
-- import yaml as _yaml
++ import hermes_yaml as _yaml
parsed = _yaml.safe_load(_read_config(_isolated_hermes_home))
assert parsed["terminal"] == "zsh"
@@@ -715,7 -715,7 +715,7 @@@
}
})
set_config_value("model.default", "claude-opus-4")
-- import yaml as _yaml
++ import hermes_yaml as _yaml
parsed = _yaml.safe_load(_read_config(_isolated_hermes_home))
assert parsed["model"]["default"] == "claude-opus-4"
assert parsed["model"]["provider"] == "openai-api"
@@@ -730,7 -730,7 +730,7 @@@
}
})
set_config_value("model", "claude-opus-4", force=True)
-- import yaml as _yaml
++ import hermes_yaml as _yaml
parsed = _yaml.safe_load(_read_config(_isolated_hermes_home))
assert parsed["model"] == "claude-opus-4"
@@@ -740,7 -740,7 +740,7 @@@ class TestScalarModelSubKeyPreservation
def test_scalar_model_id_preserved_after_provider_write(self, _isolated_hermes_home):
"""Seed model: gpt-4o, then set model.provider → model.default must survive."""
-- import yaml
++ import hermes_yaml as yaml
set_config_value("model", "gpt-4o")
set_config_value("model.provider", "openai")
@@@ -753,7 -753,7 +753,7 @@@
def test_scalar_model_id_preserved_after_api_key_write(self, _isolated_hermes_home):
"""model.api_key must also preserve the existing scalar model id."""
-- import yaml
++ import hermes_yaml as yaml
set_config_value("model", "claude-sonnet")
# model.api_key is a sub-key (has a dot), so it stays in config.yaml
@@@ -815,7 -815,7 +815,7 @@@ class TestLiteralDotKeyEscaping
"""
def _write_config(self, tmp_path, data: dict):
-- import yaml as _yaml
++ import hermes_yaml as _yaml
(tmp_path / "config.yaml").write_text(_yaml.safe_dump(data, sort_keys=False))
def test_split_key_path_escaped_dot(self):
@@@ -845,7 -845,7 +845,7 @@@
'{"Wafer-ZDR": "required"}',
)
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
providers = saved["providers"]
# No bogus ``qwen3`` nesting was created; the existing entry was updated.
@@@ -874,7 -874,7 +874,7 @@@
)
config_command(args)
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
assert "qwen3.5-397b-wafer-non-zdr" not in saved["providers"]
assert saved["providers"]["openrouter"] == {"api_key": "or-keep"}
@@@ -896,7 -896,7 +896,7 @@@
)
config_command(args)
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
target = saved["providers"]["qwen3.5-397b-wafer-non-zdr"]
assert "extra_headers" not in target
@@@ -920,7 -920,7 +920,7 @@@
"""Nesting semantics for plain dotted keys are untouched."""
set_config_value("terminal.backend", "docker")
-- import yaml
++ import hermes_yaml as yaml
saved = yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved["terminal"]["backend"] == "docker"
@@@ -996,7 -996,7 +996,7 @@@ class TestContainerTypeRefusal
echoed it back."""
def _write_config(self, tmp_path, data: dict):
-- import yaml as _yaml
++ import hermes_yaml as _yaml
(tmp_path / "config.yaml").write_text(_yaml.safe_dump(data, sort_keys=False), encoding="utf-8")
def test_string_where_schema_wants_list_is_refused(self, _isolated_hermes_home, capsys):
@@@ -1022,7 -1022,7 +1022,7 @@@
# --force keeps its documented meaning: replace a whole mapping section.
set_config_value("model.aliases", "replaced", force=True)
-- import yaml as _yaml
++ import hermes_yaml as _yaml
saved = _yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved["custom_providers"] == [{"name": "ok", "base_url": "http://h/v1"}]
assert saved["model"] == {"default": "bar", "aliases": "replaced"}
@@@ -1036,7 -1036,7 +1036,7 @@@
with pytest.raises(SystemExit):
set_config_value(key, "notacontainer")
-- import yaml as _yaml
++ import hermes_yaml as _yaml
saved = _yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved == {"model": {"default": "m"}}
@@@ -1046,7 -1046,7 +1046,7 @@@
set_config_value("agent.disabled_toolsets", "web")
-- import yaml as _yaml
++ import hermes_yaml as _yaml
saved = _yaml.safe_load(_read_config(_isolated_hermes_home))
assert saved["agent"]["disabled_toolsets"] == ["web"]
diff --cc tests/hermes_cli/test_shim_fail_closed_windows_live.py
index 00000000000,982ccc45eea..c72587e3582
mode 000000,100644..100644
--- a/tests/hermes_cli/test_shim_fail_closed_windows_live.py
+++ b/tests/hermes_cli/test_shim_fail_closed_windows_live.py
@@@ -1,0 -1,185 +1,185 @@@
+ """LIVE Windows E2E for the fail-closed shim quarantine (#87331).
+
+ Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``
+ lane). Reproduces the REAL lock shape from the field report: a process
+ holding ``hermes.exe`` open WITHOUT FILE_SHARE_DELETE, exactly like a
+ running launcher — then proves the strict quarantine refuses before any
+ installer runs, and that the non-contended path still installs.
+
+ No mocks: real files, a real child process holding a real Windows handle,
+ the real rename attempt hitting the real sharing violation.
+ """
+
+ from __future__ import annotations
+
+ import os
+ import queue
+ import subprocess
+ import sys
+ import threading
+ import time
+ from pathlib import Path
+
+ import pytest
+ from hermes_cli import main_install_repair
+
-pytestmark = pytest.mark.windows_only
++pytestmark = pytest.mark.platforms("windows")
+
+ PROJECT_ROOT = Path(__file__).resolve().parents[2]
+
+
+ def _wait_until(predicate, timeout: float = 15.0, interval: float = 0.05) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(interval)
+ return bool(predicate())
+
+
+ def _readline(stream, timeout: float = 60.0) -> str:
+ """``stream.readline()`` bounded by *timeout* (a hung child fails, not hangs)."""
+ got: queue.Queue = queue.Queue()
+ threading.Thread(target=lambda: got.put(stream.readline()), daemon=True).start()
+ try:
+ return got.get(timeout=timeout)
+ except queue.Empty:
+ return ""
+
+
+ def _rename_round_trips(path: Path) -> bool:
+ """True once no handle blocks a rename of *path* (the holder is gone)."""
+ probe = path.with_name(path.name + ".probe")
+ try:
+ os.rename(path, probe)
+ except OSError:
+ return False
+ os.rename(probe, path)
+ return True
+
+ # Child that opens a file with GENERIC_READ and NO FILE_SHARE_DELETE —
+ # the exact sharing mode a running .exe image / desktop backend exhibits.
+ _HOLDER_CODE = r"""
+ import ctypes, sys, time
+ GENERIC_READ = 0x80000000
+ FILE_SHARE_READ = 0x1 # note: NO FILE_SHARE_DELETE
+ OPEN_EXISTING = 3
+ h = ctypes.windll.kernel32.CreateFileW(
+ sys.argv[1], GENERIC_READ, FILE_SHARE_READ, None, OPEN_EXISTING, 0, None
+ )
+ if h == -1 or h == 0xFFFFFFFF:
+ print("OPEN_FAILED", flush=True)
+ sys.exit(1)
+ print("HOLDING", flush=True)
+ time.sleep(120)
+ """
+
+
+ @pytest.fixture()
+ def held_shim(tmp_path: Path):
+ scripts = tmp_path / "venv" / "Scripts"
+ scripts.mkdir(parents=True)
+ shim = scripts / "hermes.exe"
+ shim.write_bytes(b"MZ fake shim")
+ (scripts / "hermes-gateway.exe").write_bytes(b"MZ fake shim")
+ holder = subprocess.Popen(
+ [sys.executable, "-c", _HOLDER_CODE, str(shim)],
+ stdout=subprocess.PIPE,
+ text=True,
+ )
+ line = _readline(holder.stdout).strip()
+ if line != "HOLDING":
+ holder.kill()
+ pytest.fail(f"lock-holder child failed: {line!r}")
+ yield scripts, shim
+ holder.kill()
+ holder.wait()
+
+
+ def test_locked_shim_really_cannot_be_renamed(held_shim):
+ """Premise check: the no-FILE_SHARE_DELETE handle blocks rename."""
+ _scripts, shim = held_shim
+ with pytest.raises(OSError):
+ os.rename(shim, shim.with_name("hermes.exe.old.premise"))
+
+
+ def test_strict_quarantine_refuses_against_real_lock(held_shim, monkeypatch):
+ import hermes_cli.main as cli_main
+ import hermes_cli.main_install_repair as hermes_cli_main_install_repair
+
+ scripts, _shim = held_shim
+ install_ran: list = []
+ monkeypatch.setattr(
+ cli_main,
+ "_run_install_with_heartbeat",
+ lambda cmd, env=None: install_ran.append(cmd),
+ )
+ monkeypatch.setattr(
+ hermes_cli_main_install_repair,
+ "_run_install_with_heartbeat",
+ lambda cmd, env=None: install_ran.append(cmd),
+ )
+
+ with pytest.raises(main_install_repair.ShimQuarantineError) as exc_info:
+ main_install_repair._run_quarantined_install(
+ ["would-be", "uv", "pip", "install"],
+ scripts_dir=scripts,
+ strict_quarantine=True,
+ )
+
+ assert install_ran == [], "installer ran against a contended venv"
+ assert "hermes.exe" in exc_info.value.failed_shims
+ # The unlocked sibling's rename was rolled back — venv untouched.
+ assert (scripts / "hermes-gateway.exe").exists()
+ assert not list(scripts.glob("*.old.*"))
+
+
+ def test_recovery_installer_refuses_against_real_lock(held_shim, monkeypatch):
+ import hermes_cli._install_repair as ir
+
+ scripts, _shim = held_shim
+ monkeypatch.setattr(ir, "_venv_scripts_dir", lambda root: scripts)
+ run_calls: list = []
+ monkeypatch.setattr(ir.subprocess, "run", lambda *a, **k: run_calls.append(a))
+
+ with pytest.raises(ir.ShimQuarantineError):
+ ir._run_install_cmd(["fake"], env=None, root=scripts.parent.parent)
+ assert run_calls == []
+
+
+ def test_release_then_strict_quarantine_succeeds(tmp_path, monkeypatch):
+ """After the holder exits, the same strict path proceeds normally."""
+ import hermes_cli.main as cli_main
+ import hermes_cli.main_install_repair as hermes_cli_main_install_repair
+
+ scripts = tmp_path / "venv" / "Scripts"
+ scripts.mkdir(parents=True)
+ (scripts / "hermes.exe").write_bytes(b"MZ fake shim")
+
+ holder = subprocess.Popen(
+ [sys.executable, "-c", _HOLDER_CODE, str(scripts / "hermes.exe")],
+ stdout=subprocess.PIPE,
+ text=True,
+ )
+ assert _readline(holder.stdout).strip() == "HOLDING"
+ holder.kill()
+ holder.wait()
+ # The handle is released when the kernel tears the (possibly trampolined)
+ # holder down, not when wait() returns.
+ assert _wait_until(lambda: _rename_round_trips(scripts / "hermes.exe")), "holder handle never released"
+
+ install_ran: list = []
+ monkeypatch.setattr(
+ cli_main,
+ "_run_install_with_heartbeat",
+ lambda cmd, env=None: install_ran.append(cmd),
+ )
+ monkeypatch.setattr(
+ hermes_cli_main_install_repair,
+ "_run_install_with_heartbeat",
+ lambda cmd, env=None: install_ran.append(cmd),
+ )
+ main_install_repair._run_quarantined_install(
+ ["fake"], scripts_dir=scripts, strict_quarantine=True
+ )
+ assert install_ran == [["fake"]]
diff --cc tests/hermes_cli/test_update_apply_shallow_count.py
index 5937df7acf1,3b7d08cc562..4dc19589ac1
--- a/tests/hermes_cli/test_update_apply_shallow_count.py
+++ b/tests/hermes_cli/test_update_apply_shallow_count.py
@@@ -4,45 -16,88 +16,87 @@@ import subproces
import pytest
- from hermes_cli import main, source_check, update_cmd
-
- SHA_A = "a" * 40
- SHA_B = "b" * 40
-
-
- @pytest.mark.parametrize("shallow,raw_count,api_count,expected", [
- (False, 7, None, 7),
- (True, 9980, 12, 12),
- (True, 9980, None, -1),
- (True, 3, 0, 0),
- (True, 0, None, 0),
- ], ids=["full", "shallow-api", "shallow-offline", "local-ahead", "equal-tips"])
- def test_apply_plan_counts_supplied_git_results(monkeypatch, tmp_path, shallow, raw_count, api_count, expected):
- monkeypatch.setattr(main, "PROJECT_ROOT", tmp_path)
- responses = {
- ("status", "--porcelain"): "",
- ("status", "--porcelain", "-z"): "",
- ("rev-list", "HEAD..origin/main", "--count"): str(raw_count),
- ("rev-parse", "--is-shallow-repository"): "true" if shallow else "false",
- ("rev-parse", "HEAD"): SHA_A,
- ("rev-parse", "origin/main"): SHA_B,
- }
-
- def git(cmd, **kwargs):
- assert cmd[0] == "git"
- return subprocess.CompletedProcess(cmd, 0, responses[tuple(cmd[1:])] + "\n", "")
-
- monkeypatch.setattr(subprocess, "run", git)
- compare = Mock(return_value=api_count)
- monkeypatch.setattr(source_check, "_github_compare_behind", compare)
-import hermes_cli.banner as banner
+ import hermes_cli.main as cli_main
-from hermes_cli import update_cmd
++from hermes_cli import source_check, update_cmd
+
+
+ def _git(cwd, *args):
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+ def _commit(repo, n):
+ (repo / "f.txt").write_text(f"{n}\n", encoding="utf-8")
+ _git(repo, "add", "f.txt")
+ _git(repo, "commit", "-q", "-m", f"c{n}")
+
+
+ @pytest.fixture
+ def origin(tmp_path, monkeypatch):
+ for key, value in {
+ "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "[email protected]",
+ "GIT_CONFIG_NOSYSTEM": "1",
+ }.items():
+ monkeypatch.setenv(key, value)
+ repo = tmp_path / "origin"
+ repo.mkdir()
+ _git(repo, "init", "-q", "-b", "main")
+ for n in range(1, 4):
+ _commit(repo, n)
+ return repo
+
+
+ def _checkout_behind(tmp_path, origin, monkeypatch, *, shallow):
+ """Clone *origin*, then land two new upstream commits and fetch them."""
+ clone = tmp_path / ("shallow" if shallow else "full")
+ depth = ["--depth", "1"] if shallow else []
+ _git(tmp_path, "clone", "-q", *depth, origin.as_uri(), str(clone))
+ for n in (4, 5):
+ _commit(origin, n)
+ _git(clone, "fetch", "-q", *depth, "origin", "main")
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", clone)
+ return clone
+
+
+ def _count(monkeypatch, *, api):
+ consulted = []
+
+ def fake_compare(head_sha, target_sha):
+ consulted.append((head_sha, target_sha))
+ return api
+
- monkeypatch.setattr(banner, "_github_compare_behind", fake_compare)
++ monkeypatch.setattr(source_check, "_github_compare_behind", fake_compare)
plan = update_cmd._prepare_checkout_for_update(
- ["git"], "main", "main", is_fork=False, assume_yes=False,
- gateway_mode=False, gw_input_fn=None, switch_branch=False,
- _windows_gateway_resume=None,
- )
- assert plan.commit_count == expected
- if shallow and raw_count:
- compare.assert_called_once_with(SHA_A, SHA_B)
- else:
- compare.assert_not_called()
+ ["git"], "main", "main", is_fork=False, assume_yes=True, gateway_mode=False,
+ gw_input_fn=input, switch_branch=False, _windows_gateway_resume=None)
+ return plan.commit_count, consulted
+
+
+ def test_full_clone_keeps_exact_count_without_the_api(tmp_path, origin, monkeypatch):
+ _checkout_behind(tmp_path, origin, monkeypatch, shallow=False)
+ count, consulted = _count(monkeypatch, api=999)
+ assert count == 2
+ assert consulted == []
+
+
+ def test_shallow_count_is_recovered_via_compare_api(tmp_path, origin, monkeypatch):
+ """FAIL-BEFORE: the shallow rev-list number was reported as the commit count."""
+ clone = _checkout_behind(tmp_path, origin, monkeypatch, shallow=True)
+ count, consulted = _count(monkeypatch, api=12)
+ assert count == 12
+ head = subprocess.run(["git", "rev-parse", "HEAD", "origin/main"], cwd=clone,
+ check=True, capture_output=True, text=True).stdout.split()
+ assert consulted == [tuple(head)]
+
+
+ def test_shallow_count_offline_is_unknown_not_bogus(tmp_path, origin, monkeypatch):
+ _checkout_behind(tmp_path, origin, monkeypatch, shallow=True)
+ count, _ = _count(monkeypatch, api=None)
+ assert count == -1
+
+
+ def test_shallow_local_ahead_is_up_to_date(tmp_path, origin, monkeypatch):
+ """compare says 0 behind (local is ahead): the apply path takes the up-to-date branch."""
+ _checkout_behind(tmp_path, origin, monkeypatch, shallow=True)
+ count, _ = _count(monkeypatch, api=0)
+ assert count == 0
diff --cc tests/hermes_cli/test_update_shim_self_lock.py
index 1b81a5d9fbb,021405d057c..537f8c1252c
--- a/tests/hermes_cli/test_update_shim_self_lock.py
+++ b/tests/hermes_cli/test_update_shim_self_lock.py
@@@ -6,11 -13,197 +6,12 @@@
from __future__ import annotations
-import os
-import sys
-import types
from pathlib import Path
-import pytest
-
-from hermes_cli import main as cli_main
from hermes_cli import main_install_repair
+from hermes_cli import main as cli_main
+ from hermes_constants import venv_bin_dir
-
-SHIM_NAMES = ["hermes.exe", "hermes-agent.exe", "hermes-acp.exe", "hermes-gateway.exe"]
-
-
-def venv(tmp_path, monkeypatch):
- """A project venv Scripts dir with a python.exe, wired into the shim matcher."""
- scripts = tmp_path / "venv" / "Scripts"
- scripts.mkdir(parents=True)
- (scripts / "python.exe").write_bytes(b"")
- # update_cmd reads these off hermes_cli.main (frozen ``_m()`` surface); the
- # install-repair helpers read their own module globals — patch both.
- for target in (cli_main, main_install_repair):
- monkeypatch.setattr(target, "_venv_scripts_dir", lambda: scripts)
- monkeypatch.setattr(sys, "argv", ["hermes", "update"])
- monkeypatch.delenv(cli_main._UPDATE_REEXEC_ENV, raising=False)
- _fake_psutil(monkeypatch, [])
- return scripts
-
-
-def _fake_psutil(monkeypatch, ancestor_exes: list[str]):
- """Stand in for psutil with a fixed self+ancestor executable chain."""
-
- class _Proc:
- def __init__(self, exe=None, pid=os.getpid()):
- self._exe, self.pid = exe, pid
-
- def exe(self):
- if self._exe is None:
- raise OSError("exe unavailable")
- return self._exe
-
- def parents(self):
- return [_Proc(exe, 1000 + i) for i, exe in enumerate(ancestor_exes)]
-
- monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(Process=_Proc))
-
-
-def _capture_popen(monkeypatch, raises: Exception | None = None):
- calls = []
-
- def fake_popen(cmd, env=None, **kwargs):
- if raises is not None:
- raise raises
- calls.append((list(cmd), dict(env or {}), kwargs))
- return object()
-
- monkeypatch.setattr(cli_main.subprocess, "Popen", fake_popen)
- return calls
-
-
-# ---------------------------------------------------------------------------
-# Shim detection
-# ---------------------------------------------------------------------------
-
-
[email protected]("shim_name", SHIM_NAMES)
-def test_detects_shim_as_argv0(venv, monkeypatch, shim_name):
- monkeypatch.setattr(sys, "argv", [str(venv / shim_name), "update"])
- assert main_install_repair._windows_shim_in_process_chain() == venv / shim_name
-
-
-def test_detects_shim_from_zipapp_main_py(venv, monkeypatch):
- """runpy/zipapp launches put ``<shim>\\__main__.py`` in argv[0]."""
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe" / "__main__.py")])
- assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"
-
-
-def test_detects_shim_in_ancestor_chain(venv, monkeypatch):
- """The launcher is usually a separate parent process, not argv[0]."""
- _fake_psutil(monkeypatch, [str(venv / "hermes.exe")])
- assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"
- # ...and it is that launcher's pid, not ours, a detached child must outwait (#101600).
- assert main_install_repair._windows_shim_holder_pid() == 1000
-
-
-def test_ignores_hermes_exe_outside_the_project_venv(venv, monkeypatch, tmp_path):
- """A shim from some other install must never trigger a re-exec."""
- other = tmp_path / "other" / "Scripts"
- other.mkdir(parents=True)
- monkeypatch.setattr(sys, "argv", [str(other / "hermes.exe"), "update"])
- _fake_psutil(monkeypatch, [str(other / "hermes.exe")])
- assert main_install_repair._windows_shim_in_process_chain() is None
-
-
-# ---------------------------------------------------------------------------
-# Re-exec hand-off
-# ---------------------------------------------------------------------------
-
-
-def test_reexec_runs_same_args_under_venv_python(venv, monkeypatch):
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update", "--yes"])
- calls = _capture_popen(monkeypatch)
- token = {"resume_needed": True, "profiles": {"default": 4}, "unmapped": []}
-
- assert cli_main._reexec_dependency_sync_off_windows_shim(token) is True
- cmd, env, kwargs = calls[0]
- assert cmd == [
- str(venv / "python.exe"), "-m", "hermes_cli.main", "update", "--yes",
- ]
- assert env[cli_main._UPDATE_REEXEC_ENV] == "1"
- # The parent exits, so a prompt in the child could never be answered.
- assert kwargs["stdin"] is cli_main.subprocess.DEVNULL
- # #101600: the child waits for THIS pid and resumes exactly the paused fleet; the parent's
- # copy is disarmed so it exits instead of relaunching gateways while it still holds the shim.
- from hermes_cli import update_handoff
- assert env[update_handoff.SHIM_PARENT_PID_ENV] == str(os.getpid())
- assert token["resume_needed"] is False
- monkeypatch.setenv(update_handoff.GATEWAY_RESUME_ENV, env[update_handoff.GATEWAY_RESUME_ENV])
- assert update_handoff.adopt_handed_off_gateway_resume() == {
- "resume_needed": True, "profiles": {"default": 4}, "unmapped": []}
- assert update_handoff.GATEWAY_RESUME_ENV not in os.environ
-
-
-def test_reexec_does_not_recurse(venv, monkeypatch):
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- monkeypatch.setenv(cli_main._UPDATE_REEXEC_ENV, "1")
- calls = _capture_popen(monkeypatch)
-
- assert cli_main._reexec_dependency_sync_off_windows_shim() is False
- assert calls == []
-
-
-def test_reexec_falls_through_when_spawn_fails(venv, monkeypatch):
- """A failed spawn keeps the sync in-process (it then fails closed on the lock)."""
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- _capture_popen(monkeypatch, raises=OSError("no exec"))
-
- assert cli_main._reexec_dependency_sync_off_windows_shim() is False
-
-
-# ---------------------------------------------------------------------------
-# Hand-off placement: the dependency-sync boundary
-# ---------------------------------------------------------------------------
-
-
-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 WITHOUT resuming the
- paused fleet here — the child owns the token (#101600)."""
- monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])
- monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])
- resumed = []
- monkeypatch.setattr(cli_main, "_resume_windows_gateways_after_update", resumed.append)
- calls = _capture_popen(monkeypatch)
-
- with pytest.raises(SystemExit) as excinfo:
- cli_main._abort_dependency_sync_if_self_locked({"resume_needed": True, "profiles": {}})
-
- assert excinfo.value.code == 0
- assert calls, "expected the dependency sync to be handed to the venv python"
- assert resumed == [], "the shim parent must exit at once, not relaunch gateways"
-
-
-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."""
- 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:
- cli_main._abort_dependency_sync_if_self_locked()
-
- assert excinfo.value.code == 2
- assert calls == [], "a native-module deferral must not also spawn a child"
-
-
-# ---------------------------------------------------------------------------
-# Reboot-deferred renames
-# ---------------------------------------------------------------------------
+import pytest
def test_pending_rename_filter_drops_only_our_shim_pairs():
diff --cc tests/hermes_cli/test_web_server.py
index 52de62a3479,790590e0313..4b95ec81577
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@@ -12,7 -12,7 +12,7 @@@ from pathlib import Pat
from unittest.mock import patch, MagicMock
import pytest
--import yaml
++import hermes_yaml as yaml
from hermes_cli.config import (
reload_env,
@@@ -2054,7 -2063,7 +2054,7 @@@ CONFIG_SCHEMA = ProviderConfigSchema
secret by the time Save sees it. Migrating it would duplicate the
user's secret into a second env var they never asked for.
"""
-- import yaml
++ import hermes_yaml as yaml
from hermes_cli.config import custom_endpoint_key_env, get_config_path, get_env_value
diff --cc tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
index e6bcdd4fc93,2d271755422..64fc4367961
--- a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
+++ b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py
@@@ -79,6 -91,119 +87,119 @@@ def test_orphaned_control_plane_does_no
process_identity, "ledger_entries", lambda **_k: [_live_serve_ledger_entry()]
)
monkeypatch.setattr(process_identity, "spawner_is_dead", lambda _e: True)
- monkeypatch.setattr(cli_main, "_detect_venv_python_processes", lambda: [])
+ monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: [])
assert update_cmd._desktop_owns_gateway_lifecycle() is False
+
+
+ def _running_beta_pause_fixture(monkeypatch, tmp_path):
+ """Windows update with ``beta`` (PID 777) running and the default profile home at ``tmp_path``."""
+ from types import SimpleNamespace
+ import hermes_cli.profiles as profiles_mod
+
+ homes = {"default": tmp_path, "beta": tmp_path / "profiles" / "beta"}
+ homes["beta"].mkdir(parents=True)
+ monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: str(tmp_path))
+ monkeypatch.setattr(update_cmd, "_desktop_owns_gateway_lifecycle", lambda: True)
+ monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)
+ beta = SimpleNamespace(pid=777, profile="beta")
+ monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({777: beta}, [], set(), [777]))
+ monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({"beta": 777}, [777], []))
+ monkeypatch.setattr(cli_main, "_venv_launcher_ancestors", lambda pids: [])
+ monkeypatch.setattr(cli_main, "_wait_for_windows_update_gateway_exit", lambda pids, timeout: set())
+ monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: "default")
+ monkeypatch.setattr(profiles_mod, "profiles_to_serve", lambda multiplex, **_kw: [(n, h) for n, h in homes.items() if n in ("default", "beta")])
+ monkeypatch.setattr(profiles_mod, "get_profile_dir", lambda name: homes[name])
+ # Resume side.
+ monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)
+ monkeypatch.setattr(hermes_gateway, "launch_detached_profile_gateway_restart", lambda p, o: True)
+ ready_probes: list = []
+ monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda *a, **k: ready_probes.append(k) or [4242])
+ homes["_ready_probes"] = ready_probes
+ return homes
+
+
+ def test_dead_attested_default_is_cold_started_beside_running_beta(monkeypatch, tmp_path, capsys):
+ """#110959: the all-or-nothing plan never ran while ``beta`` was alive, so a default gateway
+ that died after a ✓ stayed down after the update. Its dead attestation must become a per-profile
+ cold-start obligation on the token; resume spawns it under the default home and consumes only
+ that generation, while ``beta`` still goes through the ordinary relaunch."""
+ homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
+ gateway_windows._write_start_attestation([555], "direct spawn (PID 555)")
+ marker = tmp_path / "state" / "gateway.start-attestation.json"
+ generation = json.loads(marker.read_text(encoding="utf-8"))["generation"]
+
+ token = update_cmd._pause_windows_gateways_for_update()
+
+ assert token["profiles"] == {"beta": 777}
+ assert token["cold_start_profiles"] == {"default": generation}
+ assert marker.exists() # plan-time probe is read-only
+
+ spawned = []
+ monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda **k: spawned.append(k) or 4242)
+ update_cmd._resume_windows_gateways_after_update(token)
+
+ assert spawned == [{"home": homes["default"]}]
+ # Readiness is probed in the default profile's own home: live ``beta`` must not vouch for it.
+ assert {"home": homes["default"]} in homes["_ready_probes"]
+ # The authorizing generation is consumed and the NEW PID is attested in the same profile home,
+ # so a death after this CLI exits stays visible to the next update.
+ reattested = json.loads(marker.read_text(encoding="utf-8"))
+ assert (reattested["pids"], reattested["generation"] != generation) == ([4242], True)
+ assert "cold_start_profiles" not in token
+ assert token["relaunched_profiles"] == ["beta"]
+ assert token["resume_needed"] is False
+ out = capsys.readouterr().out
+ assert "Gateway profile default started via cold-start after update (PID: 4242)" in out
+
+
+ def test_every_dead_attested_profile_is_cold_started_when_nothing_runs(monkeypatch, tmp_path):
+ """Nothing running, active profile exited cleanly (plan → None), ``beta`` dead-attested: beta still
+ gets a token and a spawn. And when BOTH owe a spawn, the fleet-wide active cold-start runs FIRST —
+ a beta spawned earlier would satisfy its any-live-gateway guard and the active profile would stay down."""
+ homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
+ monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({}, [], set(), []))
+ monkeypatch.setattr(update_cmd_windows, "_windows_cold_start_plan", lambda: None)
+ gateway_windows._write_start_attestation([556], "direct spawn (PID 556)", home=homes["beta"])
+ beta_marker = homes["beta"] / "state" / "gateway.start-attestation.json"
+ beta_generation = json.loads(beta_marker.read_text(encoding="utf-8"))["generation"]
+
+ token = update_cmd._pause_windows_gateways_for_update()
+ assert token["cold_start_profiles"] == {"beta": beta_generation}
+ assert token["profiles"] == {}
+
+ order = []
+ monkeypatch.setattr(gateway_windows, "_spawn_detached", lambda **k: order.append(k.get("home")) or 4242)
+ monkeypatch.setattr(
+ cli_main, "_cold_start_windows_gateway_after_update", lambda token=None: order.append("active") or True)
+ token["cold_start_if_installed"] = True # both owe a spawn
+ update_cmd._resume_windows_gateways_after_update(token)
+ assert order == ["active", homes["beta"]]
+ assert json.loads(beta_marker.read_text(encoding="utf-8"))["generation"] != beta_generation
+ assert token["resume_needed"] is False
+
+
+ def test_service_supervised_running_profile_is_not_cold_started(monkeypatch, tmp_path):
+ """A profile whose gateway is alive under an SCM service is skipped by the socket pause, so it is
+ absent from ``token["profiles"]``; it must still count as RUNNING for the per-profile probe or its
+ live attestation reads as dead and resume spawns a second, unsupervised gateway beside the
+ restarted service."""
+ from types import SimpleNamespace
+
+ homes = _running_beta_pause_fixture(monkeypatch, tmp_path)
+ svc_proc = SimpleNamespace(pid=900, profile="beta", path=homes["beta"])
+ service = SimpleNamespace(name="HermesGw-beta", profile="beta", service_pid=800, gateway_pid=900,
+ descendant_identities=(), service_create_time=1.0, gateway_create_time=2.0)
+ monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({900: svc_proc}, [service], {900}, [900]))
+ monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({}, [], []))
+ monkeypatch.setattr(update_cmd, "_stop_windows_gateway_service", lambda *a, **k: None)
+ gateway_windows._write_start_attestation([900], "direct spawn (PID 900)", home=homes["beta"])
+
+ token = update_cmd._pause_windows_gateways_for_update()
+
+ assert token["services"] == ["HermesGw-beta"]
+ assert token["profiles"] == {}
+ assert "cold_start_profiles" not in token
diff --cc tests/hermes_state/test_delete_mode_read_busy_wait.py
index 00000000000,fa84c5bcff0..e4fba6ae2b5
mode 000000,100644..100644
--- a/tests/hermes_state/test_delete_mode_read_busy_wait.py
+++ b/tests/hermes_state/test_delete_mode_read_busy_wait.py
@@@ -1,0 -1,62 +1,62 @@@
+ """DELETE-journal readers wait out another process's commit instead of raising ``database is locked``.
+
+ Under rollback-journal mode a reader needs a SHARED lock that a sibling process's commit blocks for
+ the length of its journal+db fsyncs. Readers used to fail after the writer connection's 1 s busy
+ timeout, so the dashboard's /api/sessions returned 503 and ``hermes sessions list`` crashed while a
+ gateway was writing. The holder here is a separate process, as in production.
+ """
+
+ import subprocess
+ import sys
+
+ import pytest
-import yaml
++import hermes_yaml as yaml
+
+ from hermes_state import SessionDB
+
+ _HOLD_S = 2.0 # longer than the old 1 s read budget, well inside the new one
+
+ _HOLDER = """
+ import sqlite3, sys, time
+ conn = sqlite3.connect(sys.argv[1], isolation_level=None)
+ conn.execute("BEGIN EXCLUSIVE")
+ print("held", flush=True)
+ time.sleep(float(sys.argv[2]))
+ conn.execute("COMMIT")
+ """
+
+
+ @pytest.fixture()
+ def delete_mode_db(tmp_path, monkeypatch):
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text(yaml.safe_dump({"database": {"journal_mode": "delete"}}), encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ db = SessionDB(db_path=home / "state.db")
+ assert db._wal_active is False
+ assert db._conn.execute("PRAGMA journal_mode").fetchone()[0].lower() == "delete"
+ db.create_session("s1", source="cli")
+ db.append_message("s1", role="user", content="hello")
+ yield db
+ db.close()
+
+
+ @pytest.mark.parametrize("read_only", [True, False], ids=["read_only_handle", "writer_handle"])
+ def test_delete_mode_read_waits_for_other_process_commit(delete_mode_db, read_only):
+ holder = subprocess.Popen(
+ [sys.executable, "-c", _HOLDER, str(delete_mode_db.db_path), str(_HOLD_S)],
+ stdout=subprocess.PIPE, text=True,
+ )
+ try:
+ assert holder.stdout.readline().strip() == "held"
+ reader = SessionDB(db_path=delete_mode_db.db_path, read_only=True) if read_only else delete_mode_db
+ try:
+ assert [s["id"] for s in reader.list_sessions_rich(limit=10)] == ["s1"]
+ assert reader.session_count() == 1
+ finally:
+ if read_only:
+ reader.close()
+ finally:
+ assert holder.wait(timeout=30) == 0
+ # Writes keep their short busy timeout: they retry at application level with jitter.
+ assert delete_mode_db._conn.execute("PRAGMA busy_timeout").fetchone()[0] == 1000
diff --cc tests/plugins/memory/test_holographic_profile_db_path.py
index ae79e48df8b,ae79e48df8b..5542695d3ce
--- a/tests/plugins/memory/test_holographic_profile_db_path.py
+++ b/tests/plugins/memory/test_holographic_profile_db_path.py
@@@ -13,7 -13,7 +13,7 @@@ from pathlib import Pat
from unittest.mock import patch
import pytest
--import yaml
++import hermes_yaml as yaml
import hermes_cli.memory_setup as memory_setup
from hermes_cli.profiles import create_profile, rename_profile
diff --cc tests/plugins/test_security_guidance_plugin.py
index c52dbcbfc27,9b477dc9f29..a1542ace8ca
--- a/tests/plugins/test_security_guidance_plugin.py
+++ b/tests/plugins/test_security_guidance_plugin.py
@@@ -250,7 -261,7 +250,7 @@@ class TestPreToolCallHook
class TestPluginDiscovery:
def test_manifest_declares_registered_hooks(self):
"""Manifest metadata must use the field consumed by plugin discovery."""
-- import yaml
++ import hermes_yaml as yaml
plugin_dir = _repo_root() / "plugins" / "security-guidance"
manifest = yaml.safe_load(
diff --cc tests/pm/test_workspace.py
index 2ba9bae7547,00000000000..41d625a6f07
mode 100644,000000..100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@@ -1,116 -1,0 +1,146 @@@
+"""pm.workspace: the generated uv-workspace root for plugin deps.
+
+The workspace root is a pm-GENERATED project (never the committed
+pyproject.toml — sealed installs are read-only and member lists are
+machine-specific). Its pyproject = core's pyproject verbatim +
+``[tool.uv.workspace] members`` pointing at each snapshotted plugin.
+``uv lock`` unions core + plugin deps into ONE lock; conflict = loud refusal.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+import pm.workspace as ws
+from pm.environment import managed_environment
+from tests.pm.test_environment_build import locked_project # noqa: F401
+
+
+
+
+def layout(locked_project, tmp_path, monkeypatch):
+ core, uv, _ = locked_project
+ manifest = core / "pyproject.toml"
+ manifest.write_text(manifest.read_text().replace('[tool.uv.workspace]\nmembers=["member"]\n', ""))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (uv, Path(sys.executable)))
+ monkeypatch.setattr(ws.paths, "repo_root", lambda: core)
+ return tmp_path, core, core / "member", tmp_path / "store"
+
+
+
+
+def test_preparation_refuses_existing_workspace_without_mutating_it(layout):
+ from pm.package import InstallError
+
+ tmp, core, plug_a, _ = layout
+ root = tmp / "workspace"
+ environment = managed_environment(tmp / "env")
+ kwargs = dict(root=root, source=core, seed_lock=None,
+ environment=environment)
+ ws.lock_and_sync([plug_a], [], **kwargs)
+ before = {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()}
+ (plug_a / "pyproject.toml").write_text('changed after publication')
+ with pytest.raises(InstallError, match="fresh"):
+ ws.lock_and_sync([], [], **kwargs)
+ assert {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} == before
+
+
+def test_missing_explicit_seed_cannot_silently_resolve_new_versions(layout):
+ tmp, core, plug_a, _ = layout
+ with pytest.raises(FileNotFoundError):
+ ws.lock_and_sync([plug_a], [], root=tmp / "workspace", source=core,
+ seed_lock=tmp / "missing.lock", environment=managed_environment(tmp / "env"))
+ assert not (tmp / "env").exists()
+
+
++def test_core_quarantine_covers_core_packages_and_not_plugin_ones(layout, locked_project):
++ """Regression for #120076: Hermes's 14-day cutoff must not filter a plugin's own deps.
+
++ A global ``exclude-newer`` in the generated root made a catalog pin floored on a fresh
++ release unresolvable. The cutoff now travels per package: every registry package in
++ core's lock keeps it (or core's explicit exemption), plugin-only packages follow the
++ plugin's policy, and the rewritten root still locks and syncs.
++ """
++ import tomllib
++
++ tmp, core, plug_a, _ = layout
++ _, uv, env = locked_project
++ manifest = core / "pyproject.toml"
++ manifest.write_text(manifest.read_text().replace("[tool.uv]\n", '[tool.uv]\nexclude-newer="14 days"\n', 1)
++ + '[tool.uv.exclude-newer-package]\nBase_Dep = false\n')
++ subprocess.run([str(uv), "lock", "--python", sys.executable], cwd=core, env=env, check=True,
++ capture_output=True)
++ core_packages = {p["name"] for p in tomllib.loads((core / "uv.lock").read_text())["package"]
++ if "registry" in p.get("source", {})}
++ assert {"base-dep", "chosen-dep"} <= core_packages and "member-dep" not in core_packages
++
++ root = tmp / "workspace"
++ ws.lock_and_sync([plug_a], [], root=root, source=core, seed_lock=core / "uv.lock",
++ environment=managed_environment(tmp / "env"))
++
++ policy = tomllib.loads((root / "pyproject.toml").read_text())["tool"]["uv"]
++ assert "exclude-newer" not in policy
++ per_package = policy["exclude-newer-package"]
++ assert per_package == {name: False if name == "base-dep" else "14 days" for name in core_packages}
++ locked = {p["name"] for p in tomllib.loads((root / "uv.lock").read_text())["package"]}
++ assert "member-dep" in locked and "member-dep" not in per_package
+
+
+
+
+
+
+# --- classified failures + staging surface (FINAL-RUNTIME-CONTRACT) ---
+
+
+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(layout, monkeypatch):
+ from pm.package import InstallError
+
+ tmp, core, _, _ = layout
+ environment = managed_environment(tmp / "candidate")
+ monkeypatch.setattr(subprocess, "run", lambda cmd, **kwargs:
+ subprocess.CompletedProcess(cmd, 1, "", "Failed to download wheel"))
+ with pytest.raises(InstallError) as excinfo:
+ ws.lock_and_sync([], [], root=tmp / "workspace", source=core,
+ seed_lock=None, environment=environment, frozen=True)
+ assert not isinstance(excinfo.value, ws.ResolutionConflict)
+
+
+def test_staging_root_and_env_are_honored_without_live_mutation(layout, monkeypatch):
+ tmp, core, _, _ = layout
+ staging = tmp / "staging-ws"
+ monkeypatch.setenv("PM_WORKSPACE_TEST_SENTINEL", "live")
+ environment = managed_environment(tmp / "staging-venv", env={
+ "PATH": "/staged/bin", "PM_WORKSPACE_TEST_SENTINEL": "staged",
+ })
+ # The prepared environment is authoritative; workspace never discovers tools.
+ monkeypatch.setattr(shutil, "which", lambda *args, **kwargs: pytest.fail("PATH discovery"))
+ seen = []
+ def run(cmd, **kwargs):
+ seen.append((cmd, kwargs))
+ return subprocess.CompletedProcess(cmd, 0, "", "")
+ monkeypatch.setattr(subprocess, "run", run)
+ ws.lock_and_sync([], [], root=staging, source=core, seed_lock=None, environment=environment)
+ assert [cmd[1] for cmd, _ in seen] == ["lock", "sync"]
+ for cmd, kwargs in seen:
+ assert Path(cmd[0]) == environment.uv
+ assert Path(kwargs["cwd"]) == staging
+ assert kwargs["env"]["PM_WORKSPACE_TEST_SENTINEL"] == "staged"
+ assert kwargs["env"]["UV_CACHE_DIR"] == str(environment.cache)
+ assert kwargs["env"]["UV_PROJECT_ENVIRONMENT"] == str(environment.destination)
+ assert kwargs["env"]["UV_PYTHON"] == str(environment.python)
+ assert os.environ["PM_WORKSPACE_TEST_SENTINEL"] == "live"
diff --cc tests/skills/test_openclaw_migration.py
index 734727a2481,734727a2481..1ae919cff11
--- a/tests/skills/test_openclaw_migration.py
+++ b/tests/skills/test_openclaw_migration.py
@@@ -211,7 -211,7 +211,7 @@@ def test_readable_config_keeps_every_pr
migrator.migrate()
-- import yaml
++ import hermes_yaml as yaml
merged = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert merged["model"] == "hermes-4-405b"
diff --cc tests/test_fast_safe_load.py
index 765694f0172,765694f0172..c185c5ed516
--- a/tests/test_fast_safe_load.py
+++ b/tests/test_fast_safe_load.py
@@@ -8,7 -8,7 +8,7 @@@ any particular document
import io
--import yaml
++import hermes_yaml as yaml
from utils import fast_safe_load
diff --cc tests/test_hermes_constants.py
index f6e41166230,a32c8f54d6a..5b256b97c01
--- a/tests/test_hermes_constants.py
+++ b/tests/test_hermes_constants.py
@@@ -77,7 -86,17 +77,17 @@@ class TestGetDefaultHermesRoot
class TestGetHermesHome:
"""Tests for get_hermes_home() platform-aware fallback."""
+ def test_warn_once_latch_engages_on_first_check_even_without_warning(self, tmp_path, monkeypatch):
+ """Regression for #90065: the latch must engage on the first check even when there is
+ nothing to warn about, otherwise every get_hermes_home() call re-stats active_profile."""
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ monkeypatch.setattr(hermes_constants, "_profile_fallback_warned", False)
+ monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: tmp_path)
+
+ get_hermes_home()
+ assert hermes_constants._profile_fallback_warned is True
+
- @pytest.mark.windows_only
+ @pytest.mark.platforms("windows")
def test_windows_fallback_uses_localappdata(self, tmp_path, monkeypatch):
"""When HERMES_HOME is unset on Windows, use %LOCALAPPDATA%\\hermes."""
local_appdata = tmp_path / "LocalAppData"
diff --cc tests/test_hermes_logging.py
index 3740642eff3,333662d7980..cbb42ebf2b7
--- a/tests/test_hermes_logging.py
+++ b/tests/test_hermes_logging.py
@@@ -118,10 -124,47 +118,46 @@@ 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()
+ ).read_text(encoding="utf-8-sig")
+ default_log = hermes_home / "logs" / "agent.log"
+ assert not default_log.exists() or "profile-routed cron record" not in default_log.read_text(encoding="utf-8-sig")
+ @pytest.mark.parametrize("launch_redacts, routed_opt_out, routed_redacted", [
+ (False, None, True), # the launch profile opted out, the routed one did not
+ (True, "env", False), # the routed profile opted out in its own .env
+ ], ids=["launch-opt-out", "routed-env-opt-out"])
+ def test_routed_records_follow_their_own_profiles_redaction_policy(
+ self, hermes_home, tmp_path, monkeypatch, launch_redacts, routed_opt_out, routed_redacted):
+ """The listener thread formats every record after its profile scope is gone, so a routed profile's own
+ agent.log was redacted by the LAUNCH profile's policy: raw credentials if only the launch opted out."""
+ from agent import redact
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ monkeypatch.setattr(redact, "_REDACT_ENABLED", launch_redacts)
+ monkeypatch.setattr(redact, "_REDACT_ENABLED_BY_HOME", {})
+ routed = tmp_path / "profile-b"
+ routed.mkdir()
+ if routed_opt_out == "config":
+ (routed / "config.yaml").write_text("security:\n redact_secrets: false\n", encoding="utf-8")
+ elif routed_opt_out == "env":
+ (routed / ".env").write_text("HERMES_REDACT_SECRETS=false\n", encoding="utf-8")
+ hermes_logging.setup_logging(hermes_home=hermes_home)
+ assert hermes_logging.enable_profile_log_routing([hermes_home, routed]) is True
+ routed_secret = "sk-proj-ROUTEDPROFILE" + "b" * 24
+ launch_secret = "sk-proj-LAUNCHPROFILE" + "a" * 24
+
+ logger = logging.getLogger("gateway.redaction-routing-test")
+ token = set_hermes_home_override(routed)
+ try:
+ logger.warning("provider rejected key %s", routed_secret)
+ finally:
+ reset_hermes_home_override(token)
+ logger.warning("launch key %s", launch_secret)
+ hermes_logging.flush_log_queue()
+
+ assert (routed_secret not in (routed / "logs" / "agent.log").read_text()) is routed_redacted
+ assert (launch_secret not in (hermes_home / "logs" / "agent.log").read_text()) is launch_redacts
+
def test_release_profile_log_handlers_closes_only_deleted_profile(self, hermes_home, tmp_path):
"""Profile deletion releases its routed log files without disturbing another profile."""
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
diff --cc tests/tools/test_file_operations.py
index 3ed3936730d,530ee8af485..52693701963
--- a/tests/tools/test_file_operations.py
+++ b/tests/tools/test_file_operations.py
@@@ -768,3 -768,50 +768,50 @@@ class TestEscapeNativeToolArg
"""Multi-segment POSIX paths (/home/x, /tmp/y) are not drive paths."""
ops = self._ops(mock_env)
assert ops._escape_native_tool_arg("/tmp/workdir") == "'/tmp/workdir'"
+
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_rg_content_search_uses_native_form(self, mock_env):
+ """The call site, not just the helper: search must hand the native rg
+ binary C:/..., never the MSYS /c/... form (the live os-error-3 failure)."""
+ commands = []
+
+ def side_effect(command, **kwargs):
+ commands.append(command)
+ if "test -e" in command:
+ return {"output": "exists", "returncode": 0}
+ if "command -v" in command:
+ return {"output": "yes", "returncode": 0}
+ return {"output": "", "returncode": 0}
+
+ mock_env.execute.side_effect = side_effect
+ ops = self._ops(mock_env)
+ ops.search("needle", path=r"C:\Users\alice\project")
+ rg_cmds = [c for c in commands if "rg " in c or c.startswith("rg")]
+ assert rg_cmds, f"no rg command captured in: {commands}"
+ assert any("'C:/Users/alice/project'" in c for c in rg_cmds), rg_cmds
+ assert all("/c/Users" not in c for c in rg_cmds), rg_cmds
+
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_shell_linter_uses_native_form(self, mock_env):
+ """_check_lint must hand node/python/etc. the native C:/ path.
+
+ Regression for the double-prefix failure (#84303): node given the
+ MSYS /c/Users/... form resolves it as C:\\c\\Users\\... and every
+ .js write reports a phantom ENOENT lint error.
+ """
+ commands = []
+
+ def side_effect(command, **kwargs):
+ commands.append(command)
+ if "command -v" in command:
+ return {"output": "yes", "returncode": 0}
+ return {"output": "", "returncode": 0}
+
+ mock_env.execute.side_effect = side_effect
+ ops = self._ops(mock_env)
+ result = ops._check_lint(r"C:\Users\alice\app\main.js")
+ assert result.skipped is False
+ node_cmds = [c for c in commands if "node --check" in c]
+ assert node_cmds, f"no node command captured in: {commands}"
+ assert "'C:/Users/alice/app/main.js'" in node_cmds[0]
+ assert "/c/Users" not in node_cmds[0]
diff --cc tests/tui_gateway/test_cold_start_gil_stall.py
index 0e09d7e69b8,d101462cba5..3360e97cde8
--- a/tests/tui_gateway/test_cold_start_gil_stall.py
+++ b/tests/tui_gateway/test_cold_start_gil_stall.py
@@@ -66,6 -69,55 +66,52 @@@ class TestCopilotAuthSkipsGhCli
assert source == "gh auth token"
mock_cli.assert_called_once()
-
# ─── Fix 2: resolve_skin runs via to_thread in handle_ws ───────────────
+
+ def test_handle_ws_resolves_skin_off_the_loop_thread(monkeypatch):
+ """Driving the real handle_ws: resolve_skin runs on a worker thread, never the
+ event-loop thread, and its result still reaches the gateway.ready frame
+ (#60800 cold-start stall; #72720 salvage)."""
+ import asyncio
+ import json
+ import threading
+
+ from tui_gateway import server, ws as ws_mod
+
+ idents = {}
+ frames = []
+
+ def _resolve_skin():
+ idents["skin"] = threading.get_ident()
+ return {"palette": "wired"}
+
+ monkeypatch.setattr(server, "resolve_skin", _resolve_skin)
+ monkeypatch.setattr(server, "_ensure_skin_watcher", lambda: None)
+ monkeypatch.setattr(server, "register_live_transport", lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_start_backend_heartbeat_refresher", lambda: None)
+ monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", lambda: None, raising=False)
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)
+
+ class FakeWS:
+ async def accept(self):
+ idents["loop"] = threading.get_ident()
+
+ async def send_text(self, line):
+ frames.append(json.loads(line))
+
+ async def receive_text(self):
+ raise ws_mod._WebSocketDisconnect()
+
+ async def close(self):
+ pass
+
+ asyncio.run(ws_mod.handle_ws(FakeWS()))
+
+ assert idents["skin"] != idents["loop"], (
+ "resolve_skin ran on the event loop thread — the #60800 cold-start stall is back")
+ ready = [f for f in frames if f.get("params", {}).get("type") == "gateway.ready"]
+ assert ready and ready[0]["params"]["payload"]["skin"] == {"palette": "wired"}
+
+
# ─── Fix 3: _warm_gateway_module pre-imports heavy chains ──────────────
-
-
diff --cc tests/tui_gateway/test_tui_gateway_server.py
index b61c9d0dbd5,b3c95201b15..2d45a7b7b9b
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@@ -764,7 -764,7 +764,7 @@@ def test_session_context_explicit_cwd_f
def _write_profile_cfg(home: Path, cwd: str | None) -> Path:
-- import yaml
++ import hermes_yaml as yaml
home.mkdir(parents=True, exist_ok=True)
cfg = {"terminal": {"cwd": cwd}} if cwd is not None else {}
@@@ -8223,7 -8223,7 +8223,7 @@@ def test_config_set_yolo_stale_session_
def test_config_set_yolo_global_scope_writes_approvals_mode(tmp_path, monkeypatch):
"""Shift+click the desktop zap -> scope="global" flips persistent approvals.mode."""
-- import yaml
++ import hermes_yaml as yaml
cfg_path = tmp_path / "config.yaml"
cfg_path.write_text(yaml.safe_dump({"approvals": {"mode": "manual"}}))
@@@ -8254,7 -8254,7 +8254,7 @@@
def test_config_get_approval_mode_uses_smart_default_when_key_is_missing(
tmp_path, monkeypatch
):
-- import yaml
++ import hermes_yaml as yaml
monkeypatch.setattr(server, "_hermes_home", tmp_path)
# Point the canonical resolver (load_config → env HERMES_HOME) at the
@@@ -8274,7 -8274,7 +8274,7 @@@
def test_config_get_approval_mode_fails_safe_to_manual_for_invalid_explicit_value(
tmp_path, monkeypatch
):
-- import yaml
++ import hermes_yaml as yaml
monkeypatch.setattr(server, "_hermes_home", tmp_path)
# _load_approval_mode delegates to the canonical resolver in
@@@ -8293,7 -8293,7 +8293,7 @@@
def test_config_get_approval_mode_normalizes_yaml_off(tmp_path, monkeypatch):
-- import yaml
++ import hermes_yaml as yaml
monkeypatch.setattr(server, "_hermes_home", tmp_path)
# See fail-safe test above: the canonical resolver reads via
@@@ -8312,7 -8312,7 +8312,7 @@@
def test_config_set_approval_mode_persists_three_way_value_and_emits_live_status(
tmp_path, monkeypatch
):
-- import yaml
++ import hermes_yaml as yaml
monkeypatch.setattr(server, "_hermes_home", tmp_path)
# config.set writes via server._hermes_home, but the post-write
@@@ -8347,7 -8347,7 +8347,7 @@@ def test_pet_gallery_quoted_false_enabl
quoted YAML value kept the petdex mascot enabled against the operator's
explicit intent.
"""
-- import yaml
++ import hermes_yaml as yaml
monkeypatch.setattr(server, "_hermes_home", tmp_path)
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@@ -8426,7 -8426,7 +8426,7 @@@ def test_config_set_approval_mode_rejec
def test_config_set_yolo_global_scope_honors_explicit_value(tmp_path, monkeypatch):
"""An explicit value pins global approvals.mode regardless of prior state."""
-- import yaml
++ import hermes_yaml as yaml
cfg_path = tmp_path / "config.yaml"
cfg_path.write_text(yaml.safe_dump({"approvals": {"mode": "manual"}}))
@@@ -8668,7 -8668,7 +8668,7 @@@ def test_config_get_busy_survives_non_d
def test_config_set_statusbar_survives_non_dict_display(tmp_path, monkeypatch):
-- import yaml
++ import hermes_yaml as yaml
cfg_path = tmp_path / "config.yaml"
cfg_path.write_text(yaml.safe_dump({"display": "broken"}))
@@@ -8688,7 -8688,7 +8688,7 @@@
def test_config_set_details_mode_pins_all_sections(tmp_path, monkeypatch):
-- import yaml
++ import hermes_yaml as yaml
cfg_path = tmp_path / "config.yaml"
cfg_path.write_text(
@@@ -8718,7 -8718,7 +8718,7 @@@
def test_config_set_section_writes_per_section_override(tmp_path, monkeypatch):
-- import yaml
++ import hermes_yaml as yaml
cfg_path = tmp_path / "config.yaml"
monkeypatch.setattr(server, "_hermes_home", tmp_path)
@@@ -8737,7 -8737,7 +8737,7 @@@
def test_config_set_section_clears_override_on_empty_value(tmp_path, monkeypatch):
-- import yaml
++ import hermes_yaml as yaml
cfg_path = tmp_path / "config.yaml"
cfg_path.write_text(
@@@ -20675,7 -20729,7 +20729,7 @@@ def test_save_cfg_preserves_user_commen
assert "# provider rationale" in text
assert "# trailing skin note" in text
-- import yaml as _yaml
++ import hermes_yaml as _yaml
parsed = _yaml.safe_load(text)
assert parsed["display"]["skin"] == "mono"
diff --cc tools/registry.py
index 3d30b355fb4,5ffe255e1a5..57cffdc89aa
--- a/tools/registry.py
+++ b/tools/registry.py
@@@ -681,10 -684,9 +688,10 @@@ class ToolRegistry
owner = caller_owner or handler_owner
if scope is None and owner is not None:
scope = self._plugin_scope_of(owner)
+ scope = normalize_scope(scope)
with self._lock:
target = self._slot(scope, create=True)
- existing = (self._tools if scope is None else self._merged_tools(scope)).get(name)
+ existing = self._lookup(name, scope)
plugin_override_denied = (
owner is not None and not self._plugin_override_allowed(scope, owner))
shadows_global = (
diff --cc website/docs/developer-guide/plugins/index.md
index d2cfe86d36f,a9960bf59c5..2833d5e32dc
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@@ -387,6 -378,34 +387,34 @@@ When both exist the `pyproject.toml` wi
`HERMES_HOME/plugins/` survives `hermes update` and Desktop updates: the updater only rebuilds the
venv and the checkout, never the home directory.
+ ### Dependency security policy
+
+ Hermes quarantines **its own** dependencies: the checkout's `[tool.uv] exclude-newer = "14 days"`
+ keeps a freshly published release of any package Hermes itself depends on out of `hermes update`
+ and the built-in lazy installs for two weeks, so a hijacked upload is caught upstream before it
-reaches users. **That quarantine does not apply to your plugin's dependencies.** Plugin installs
-run outside Hermes's project policy (`uv pip install --no-config`, still under the core constraints
-file above), so a plugin can floor on a release published yesterday and install today — and the
-plugin's author, not Hermes, is responsible for what that pulls in.
++reaches users. **That quarantine does not apply to your plugin's dependencies.** When Hermes
++resolves your plugin into its environment, the cutoff stays on the packages Hermes itself locks
++and nowhere else, so a plugin can floor on a release published yesterday and install today — and the
++plugin's author, not Hermes, is responsible for what that pulls in. (A plugin that needs a newer
++version of a package Hermes itself depends on still waits out that package's window.)
+
+ Set your own policy and hold yourself to it. Strongly recommended:
+
+ - **Upper bounds on every dependency** — `>=floor,<next_major` for stable packages,
+ `>=0.29,<0.32` for pre-1.0 ones. A bare `>=X.Y` adopts every future release unreviewed.
+ - **Floor on the oldest API-compatible version**, not the release of the week. A floor on a
+ fresh wheel forces every installer onto it the day it appears; `>=old,!=broken,<next` keeps the
+ wide range and skips the one bad release.
+ - **Adopt a new-release quarantine of your own** — wait ~14 days before floors move to a new
+ release, and resolve with `uv --exclude-newer "14 days"` (or `UV_EXCLUDE_NEWER`) in your own CI so
- the lock you test is the one users get. Operators who want the same guard on plugin installs
- can set `UV_EXCLUDE_NEWER` in Hermes's environment; it applies to every install Hermes runs.
++ the lock you test is the one users get.
+ - **Pin your lock, review your bumps.** Treat a dependency bump as a code change: read the
+ upstream diff, then re-pin.
+
+ The plugin catalog review reads your dependency list at the pinned SHA (`plugin.yaml` or
+ `pyproject.toml`) and flags bare floors and missing bounds; an entry is not held for a floor that
+ is merely recent.
+
## Step 3: Write the tool schemas
Create `schemas.py` — this is what the LLM reads to decide when to call your tools: