The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): doctor — warn_on_error ctx manager replaces try/except-warn wrappers; platform ladders/tcc text to data
Teknium16b46e593ae7
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex 1869e0dc4c6..785e84a39b4 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -30,6 +30,7 @@ load_hermes_dotenv(hermes_home=_env_path.parent, project_env=PROJECT_ROOT / ".enfrom hermes_cli.colors import Colors, colorfrom hermes_cli.doctor_report import ( # noqa: F401 (re-exported for doctor_live and tests)Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn, doctor_check,+ warn_on_error,)from hermes_cli.doctor_connectivity import ( # noqa: F401 (re-exported; tests import from hermes_cli.doctor)_build_apikey_providers_list, _has_healthy_oauth_fallback_for_apikey_provider, build_probes, run_probes,@@ -55,7 +56,7 @@ _PROVIDER_ENV_HINTS = (@doctor_check()def _check_auth_providers(should_fix: bool, f: Finding) -> None:"""Refresh-free OAuth status snapshot (doctor must never trigger a token refresh)."""- try:+ with warn_on_error("Auth provider status", "(could not check: {e})"):from hermes_cli.auth import get_nous_auth_status_local, get_codex_auth_status, get_minimax_oauth_auth_status_login_row("Nous Portal auth", get_nous_auth_status_local())# Native OAuth is Hermes' own device-code flow; the Codex CLI only imports existing ~/.codex/auth.json@@ -64,13 +65,9 @@ def _check_auth_providers(should_fix: bool, f: Finding) -> None:check_info("codex CLI not installed (optional — only required to import tokens from an existing Codex CLI login)")minimax_status = get_minimax_oauth_auth_status()_login_row("MiniMax OAuth", minimax_status, f"(logged in, region={minimax_status.get('region', 'global')})")- except Exception as e:- check_warn("Auth provider status", f"(could not check: {e})")- try: # xAI OAuth separately, so an import failure cannot disrupt the rows already printed above+ with warn_on_error(""): # xAI OAuth separately, so an import failure cannot disrupt the rows already printedfrom hermes_cli.auth import get_xai_oauth_auth_status_login_row("xAI OAuth", get_xai_oauth_auth_status() or {}, show_error=True)- except Exception:- passdef _login_row(label: str, status: dict, ok_detail: str = "(logged in)", show_error: bool = False) -> bool:@@ -168,9 +165,7 @@ def run_doctor(args):_section(title)total.merge(check(should_fix))# Opt-in live probes run AFTER all static checks (`--live`: real network calls; bounded + read-only).- try:+ with warn_on_error(""):from hermes_cli.doctor_live import maybe_run_live_checksmaybe_run_live_checks(args, total.manual_issues)- except Exception:- pass_print_summary(should_fix, total)diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex 1836a92a15a..5fad927840f 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -7,6 +7,7 @@ import osimport shutilfrom hermes_cli.doctor_report import (Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn, doctor_check,+ warn_on_error,)@@ -22,8 +23,7 @@ _DEPRECATED_CONFIG_KEYS: tuple[tuple[str, str, str], ...] = (("display", "tool_progress_overrides", "display.platforms"),("delegation", "max_async_children", "delegation.max_concurrent_children"),("compression", "summary_model", "auxiliary.compression"),- ("compression", "summary_provider", "auxiliary.compression"),- ("compression", "summary_base_url", "auxiliary.compression"),+ ("compression", "summary_provider", "auxiliary.compression"), ("compression", "summary_base_url", "auxiliary.compression"),)@@ -33,10 +33,8 @@ _DEPRECATED_CONFIG_KEYS: tuple[tuple[str, str, str], ...] = (_DEPRECATED_ENV_VARS: tuple[tuple[str, str], ...] = (("HERMES_TOOL_PROGRESS", "display.tool_progress in config.yaml — ignored/unsupported since config floor v12"),("HERMES_TOOL_PROGRESS_MODE", "display.tool_progress in config.yaml"),- ("TERMINAL_CWD", "terminal.cwd in config.yaml"),- ("MESSAGING_CWD", "terminal.cwd in config.yaml"),- ("QQ_HOME_CHANNEL", "QQBOT_HOME_CHANNEL"),- ("QQ_HOME_CHANNEL_NAME", "QQBOT_HOME_CHANNEL_NAME"),+ ("TERMINAL_CWD", "terminal.cwd in config.yaml"), ("MESSAGING_CWD", "terminal.cwd in config.yaml"),+ ("QQ_HOME_CHANNEL", "QQBOT_HOME_CHANNEL"), ("QQ_HOME_CHANNEL_NAME", "QQBOT_HOME_CHANNEL_NAME"),)@@ -44,11 +42,8 @@ def collect_deprecated_config_keys(raw_config: dict | None) -> list[tuple[str, s"""``(legacy_path, replacement)`` for deprecated keys in the on-disk YAML (empty containers still count)."""if not isinstance(raw_config, dict):return []- return [- (f"{section}.{key}", replacement)- for section, key, replacement in _DEPRECATED_CONFIG_KEYS- if isinstance(raw_config.get(section), dict) and key in raw_config[section]- ]+ return [(f"{section}.{key}", replacement) for section, key, replacement in _DEPRECATED_CONFIG_KEYS+ if isinstance(raw_config.get(section), dict) and key in raw_config[section]]def collect_deprecated_env_vars(env_map: dict | None) -> list[tuple[str, str]]:@@ -62,9 +57,8 @@ def collect_deprecated_env_vars(env_map: dict | None) -> list[tuple[str, str]]:def collect_relay_plugin_cutover_findings(raw_config: dict | None, env_map: dict | None) -> list[tuple[str, str]]:"""Return actionable findings for the removed Hermes Relay plugin."""- from hermes_cli.relay_plugin_cutover import (- LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV, configured_legacy_relay_env_vars, legacy_relay_plugin_keys,- )+ from hermes_cli.relay_plugin_cutover import (LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV,+ configured_legacy_relay_env_vars, legacy_relay_plugin_keys)findings: list[tuple[str, str]] = []plugins = raw_config.get("plugins") if isinstance(raw_config, dict) else Noneif isinstance(plugins, dict):@@ -104,15 +98,13 @@ def report_deprecated_config_and_env(raw_config: dict | None = None, env_map: didef managed_scope_check() -> None:"""Report the active managed scope (resolved dir + pinned key counts); silent when none. A HERMES_MANAGED_DIRoverride is surfaced too — a redirected scope is the documented foot-gun (docs/design/managed-scope.md §7)."""- try:+ managed_dir = None+ with warn_on_error(""): # diagnostics must never crashfrom hermes_cli import managed_scopemanaged_dir = managed_scope.get_managed_dir()- except Exception: # noqa: BLE001 — diagnostics must never crash- returnif managed_dir is None:return- n_cfg = len(managed_scope.managed_config_keys())- n_env = len(managed_scope.load_managed_env())+ n_cfg, n_env = len(managed_scope.managed_config_keys()), len(managed_scope.load_managed_env())check_ok(f"Managed scope active: {n_cfg} config key(s), {n_env} env key(s) pinned by {managed_dir}")if os.environ.get("HERMES_MANAGED_DIR", "").strip():check_info(f"managed dir set via HERMES_MANAGED_DIR={managed_dir}")@@ -125,14 +117,13 @@ def _check_mcp_security(should_fix: bool, f: Finding) -> None:from hermes_cli.mcp_security import validate_mcp_server_entryservers = load_config().get("mcp_servers") or {}suspicious = 0- if isinstance(servers, dict):- for name, entry in sorted(servers.items()):- issues_found = validate_mcp_server_entry(name, entry) if isinstance(entry, dict) else None- if not issues_found:- continue- suspicious += 1- check_warn(f"MCP server '{name}' has suspicious stdio command", "; ".join(issues_found))- f.manual_issues.append(f"Review/remove mcp_servers.{name} in config.yaml; rotate any credentials that may have been exposed.")+ for name, entry in sorted(servers.items()) if isinstance(servers, dict) else ():+ issues_found = validate_mcp_server_entry(name, entry) if isinstance(entry, dict) else None+ if not issues_found:+ continue+ suspicious += 1+ check_warn(f"MCP server '{name}' has suspicious stdio command", "; ".join(issues_found))+ f.manual_issues.append(f"Review/remove mcp_servers.{name} in config.yaml; rotate any credentials that may have been exposed.")if suspicious == 0:check_ok("No suspicious MCP stdio commands")@@ -160,10 +151,8 @@ def _check_env_file(should_fix: bool, f: Finding) -> None:env_path.parent.mkdir(parents=True, exist_ok=True)env_path.touch()# .env holds API keys — touch() obeys umask (commonly 0o022, world-readable); tighten explicitly.- try:+ with warn_on_error(""):os.chmod(str(env_path), 0o600)- except OSError:- passcheck_ok(f"Created empty {_DHH}/.env")check_info("Run 'hermes setup' to configure API keys")f.fixed += 1@@ -178,20 +167,14 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:known: set = set()resolve_auth = normalize = resolve_full = aliases = Nonecustom_providers: list = []- try:+ with warn_on_error(""):from hermes_cli.auth import PROVIDER_REGISTRY, resolve_provider as resolve_authknown = set(PROVIDER_REGISTRY.keys()) | {"openrouter", "custom", "auto", "moa"}- except Exception:- pass- try:+ with warn_on_error(""):from hermes_cli.config import get_compatible_custom_providersfrom hermes_cli.providers import custom_provider_aliases as aliases, normalize_provider as normalize, resolve_provider_full as resolve_full- try:+ with warn_on_error(""):custom_providers = get_compatible_custom_providers(cfg)- except Exception:- custom_providers = []- except Exception:- passuser_providers = cfg.get("providers")if isinstance(user_providers, dict):from hermes_cli.config import is_provider_enabled@@ -207,8 +190,8 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:# Vendor/model slugs are valid on aggregators and any custom provider; Fireworks' native IDs are slash-form# (accounts/fireworks/models/...) and DeepInfra's catalog is exclusively vendor/model._VENDOR_SLUG_PROVIDERS = {- "openrouter", "auto", "ai-gateway", "kilocode", "opencode-zen", "huggingface",- "lmstudio", "nous", "nvidia", "fireworks", "deepinfra",+ "openrouter", "auto", "ai-gateway", "kilocode", "opencode-zen", "huggingface", "lmstudio", "nous", "nvidia",+ "fireworks", "deepinfra",}@@ -268,14 +251,12 @@ def _validate_model_config(config_path, issues: list) -> None:"Either set model.provider to 'openrouter', or drop the vendor prefix.")if runtime_provider and runtime_provider not in ("auto", "custom"):from hermes_cli.doctor import _DHH- try:+ with warn_on_error(""):if not _provider_has_credentials(runtime_provider):_fail_and_issue(f"model.provider '{runtime_provider}' is set but no API key is configured","(check ~/.hermes/.env or run 'hermes setup')",f"No credentials found for provider '{runtime_provider}'. Run 'hermes setup' or set the provider's "f"API key in {_DHH}/.env, or switch providers with 'hermes config set model.provider <name>'", issues)- except Exception:- pass@doctor_check()@@ -285,10 +266,8 @@ def _check_config_file(should_fix: bool, f: Finding) -> None:config_path = HERMES_HOME / 'config.yaml'if config_path.exists():check_ok(f"{_DHH}/config.yaml exists")- try:+ with warn_on_error("Could not validate model/provider config"):_validate_model_config(config_path, f.issues)- except Exception as e:- check_warn("Could not validate model/provider config", f"({e})")elif (PROJECT_ROOT / 'cli-config.yaml').exists():check_ok("cli-config.yaml exists (in project directory)")elif should_fix:@@ -308,8 +287,8 @@ def _check_config_file(should_fix: bool, f: Finding) -> None:def _drift_config_version(f: Finding, should_fix: bool, config_path) -> None:from hermes_cli.config import check_config_version, migrate_configcurrent_ver, latest_ver = check_config_version()- if check_bool(current_ver >= latest_ver, f"Config version up to date (v{current_ver})",- (f"Config version outdated (v{current_ver} → v{latest_ver})", "(new settings available)")):+ outdated = (f"Config version outdated (v{current_ver} → v{latest_ver})", "(new settings available)")+ if check_bool(current_ver >= latest_ver, f"Config version up to date (v{current_ver})", outdated):returnif not should_fix:f.issues.append("Run 'hermes doctor --fix' or 'hermes setup' to migrate config")@@ -380,10 +359,9 @@ def _drift_deprecations(f: Finding, should_fix: bool, config_path) -> None:"""Warn-only deprecation sweep over the raw file + on-disk .env (process env would false-positive)."""from hermes_cli.config import load_env, read_user_config_rawraw = read_user_config_raw(config_path) if config_path is not None else {}- try:+ env = {}+ with warn_on_error(""):env = load_env()- except Exception:- env = {}report_deprecated_config_and_env(raw, env)@@ -402,11 +380,7 @@ def _drift_structure(f: Finding, should_fix: bool, config_path) -> None:_CONFIG_DRIFT_STEPS = (- _drift_config_version,- _drift_stale_root_keys,- _drift_max_iterations_ghost,- _drift_deprecations,- _drift_structure,+ _drift_config_version, _drift_stale_root_keys, _drift_max_iterations_ghost, _drift_deprecations, _drift_structure,)@@ -421,10 +395,8 @@ def _check_config_drift(should_fix: bool, f: Finding) -> None:if not config_path.exists():config_path = Nonefor step in _CONFIG_DRIFT_STEPS if config_path else (_drift_deprecations,):- try:+ with warn_on_error(""):step(f, should_fix, config_path)- except Exception:- pass@doctor_check("xAI retirement check skipped", "({e})")diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex 5d0cf3d04da..df4bc12ae75 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -12,6 +12,7 @@ from hermes_cli.colors import Colors, colorfrom hermes_cli.config import is_nix_install_method, recommended_update_command_for_methodfrom hermes_cli.doctor_report import (Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn, doctor_check,+ warn_on_error,)from hermes_constants import is_termux as _is_termux@@ -21,9 +22,7 @@ def _python_install_cmd() -> str:def _system_package_install_cmd(pkg: str) -> str:- if _is_termux():- return f"pkg install {pkg}"- return f"brew install {pkg}" if sys.platform == "darwin" else f"sudo apt install {pkg}"+ return f"{'pkg' if _is_termux() else 'brew' if sys.platform == 'darwin' else 'sudo apt'} install {pkg}"def _sqlite_upgrade_hint(install_method: str | None = None) -> str:@@ -31,10 +30,8 @@ def _sqlite_upgrade_hint(install_method: str | None = None) -> str:from hermes_cli.doctor import PROJECT_ROOT, detect_install_methodmethod = install_method or detect_install_method(PROJECT_ROOT)cmd = recommended_update_command_for_method(method)- if is_nix_install_method(method):- action = cmd # prose guidance, not a shell command- else:- action = {"docker": f"run `{cmd}`, then recreate all Hermes containers", "apt": f"run `{cmd}`"}.get(method, "run `hermes update`")+ action = cmd if is_nix_install_method(method) else { # nix: prose guidance, not a shell command+ "docker": f"run `{cmd}`, then recreate all Hermes containers", "apt": f"run `{cmd}`"}.get(method, "run `hermes update`")return f"({action}; fixed versions: 3.51.3+ / 3.50.7 / 3.44.6 — see https://sqlite.org/wal.html#walresetbug)"@@ -107,10 +104,11 @@ def _report_database_journal_modes(hermes_home: Path | None = None, version_infocontinuemode, error = _read_journal_mode(path)size = _format_db_size(path)- if error is not None and vulnerable:- check_warn(f"{name}: journal mode could not be read", f"({error}; cannot rule out WAL exposure)")- elif error is not None:- check_info(f"{name}: journal mode could not be read ({error})")+ if error is not None:+ if vulnerable:+ check_warn(f"{name}: journal mode could not be read", f"({error}; cannot rule out WAL exposure)")+ else:+ check_info(f"{name}: journal mode could not be read ({error})")elif mode == "wal" and vulnerable:exposed.append(name)check_warn(f"{name} is in WAL mode ({size})", "(exposed to the WAL-reset bug until SQLite is upgraded)")@@ -166,8 +164,8 @@ def _check_s6_supervision(issues: list[str]) -> None:_section("s6 Supervision")mgr = S6ServiceManager()for static in ("main-hermes", "dashboard"): # s6-rc symlinks under /run/service/, same s6-svstat probe- (check_ok if mgr.is_running(static) else check_info)(- f"{static}: up" if mgr.is_running(static) else f"{static}: down (expected if not enabled via env)")+ up = mgr.is_running(static)+ (check_ok if up else check_info)(f"{static}: up" if up else f"{static}: down (expected if not enabled via env)")profiles = mgr.list_profile_gateways()if not profiles:return check_info("No per-profile gateways registered yet — create one with `hermes profile create <name>`")@@ -186,19 +184,16 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -from agent.ssl_guard import verify_ca_bundle_with_fallbackfrom agent.errors import SSLConfigurationErrorexcept Exception as e:- check_warn("SSL certificate check skipped", str(e))- return+ return check_warn("SSL certificate check skipped", str(e))if issues is None:issues = []try:verify_ca_bundle_with_fallback()- check_ok("SSL CA certificate bundle is valid")- return+ return check_ok("SSL CA certificate bundle is valid")except SSLConfigurationError as e:first_error = str(e)except Exception as e:- check_warn("SSL certificate check skipped", str(e))- return+ return check_warn("SSL certificate check skipped", str(e))check_fail("SSL CA certificate bundle is broken", first_error)pip_cmd = f"{sys.executable} -m pip install --force-reinstall certifi"if not should_fix:@@ -212,9 +207,7 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -except Exception as exc:failure = ("certifi repair could not run pip", str(exc))if failure:- check_fail(*failure)- issues.append(f"Reinstall certifi manually: {pip_cmd}")- return+ return _fail_and_issue(*failure, f"Reinstall certifi manually: {pip_cmd}", issues)# Drop cached certifi modules so where() resolves the fresh install without a restart.import importlibfor mod_name in [m for m in sys.modules if m == "certifi" or m.startswith("certifi.")]:@@ -224,9 +217,9 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -verify_ca_bundle_with_fallback()check_ok("SSL CA certificate bundle repaired (certifi reinstalled)")except SSLConfigurationError as e:- check_fail("SSL CA certificate bundle still broken after reinstall", str(e))- issues.append("certifi reinstall did not restore the CA bundle — check for a custom CA env var "- "(SSL_CERT_FILE/REQUESTS_CA_BUNDLE) pointing at a missing file, or recreate the venv.")+ _fail_and_issue("SSL CA certificate bundle still broken after reinstall", str(e),+ "certifi reinstall did not restore the CA bundle — check for a custom CA env var "+ "(SSL_CERT_FILE/REQUESTS_CA_BUNDLE) pointing at a missing file, or recreate the venv.", issues)def _check_gateway_service_linger(issues: list[str]) -> None:@@ -235,19 +228,29 @@ def _check_gateway_service_linger(issues: list[str]) -> None:from hermes_cli.gateway import get_systemd_linger_status, get_systemd_unit_path, is_linuxfrom hermes_cli.service_manager import detect_service_managerexcept Exception as e:- check_warn("Gateway service linger", f"(could not import gateway helpers: {e})")- return+ return check_warn("Gateway service linger", f"(could not import gateway helpers: {e})")if not is_linux() or detect_service_manager() == "s6" or not get_systemd_unit_path().exists():return_section("Gateway Service")linger_enabled, linger_detail = get_systemd_linger_status()if linger_enabled is None:return check_warn("Could not verify systemd linger", f"({linger_detail})")- if not check_bool(linger_enabled, ("Systemd linger enabled", "(gateway service survives logout)"), ("Systemd linger disabled", "(gateway may stop after logout)")):+ if not check_bool(linger_enabled, ("Systemd linger enabled", "(gateway service survives logout)"),+ ("Systemd linger disabled", "(gateway may stop after logout)")):check_info("Run: sudo loginctl enable-linger $USER")issues.append("Enable linger for the gateway user service: sudo loginctl enable-linger $USER")+_TCC_CDHASH_DETAIL = (+ "the desktop bundle's designated requirement is cdhash-pinned (pre-#73681 build) — rebuilds invalidate "+ "all permission grants. Run `hermes update` to get the stable identifier-pinned signing identity, "+ "then re-grant permissions once.")+_TCC_STABLE_DETAIL = {+ True: "(certificate-anchored DR; grants survive rebuilds)",+ False: "(identifier-pinned DR; grants survive rebuilds — for the strongest anchor, see `hermes desktop --setup-tcc-identity`)",+}++def check_macos_tcc_grants() -> None:"""Check macOS TCC grant persistence for a locally-built desktop bundle; silent on non-macOS / no bundle.@@ -262,17 +265,11 @@ def check_macos_tcc_grants() -> None:returndr = _macos_desktop_dr(app)if not dr:- check_warn("macOS TCC grant check", "(could not read code-signing requirement of the desktop bundle)")- return+ return check_warn("macOS TCC grant check", "(could not read code-signing requirement of the desktop bundle)")if "cdhash" in dr.lower():- return check_warn("macOS TCC grants will reset after every update",- "the desktop bundle's designated requirement is cdhash-pinned (pre-#73681 build) — rebuilds invalidate "- "all permission grants. Run `hermes update` to get the stable identifier-pinned signing identity, "- "then re-grant permissions once.")- check_ok("macOS TCC signing identity is stable",- # --setup-tcc-identity or notarized build: strongest anchor- "(certificate-anchored DR; grants survive rebuilds)" if "certificate" in dr.lower() else- "(identifier-pinned DR; grants survive rebuilds — for the strongest anchor, see `hermes desktop --setup-tcc-identity`)")+ return check_warn("macOS TCC grants will reset after every update", _TCC_CDHASH_DETAIL)+ # --setup-tcc-identity or notarized build (certificate-anchored) is the strongest anchor.+ check_ok("macOS TCC signing identity is stable", _TCC_STABLE_DETAIL["certificate" in dr.lower()])check_info("If macOS still re-prompts for permissions (toggle shows ON): the stored grant is stale — run ""`tccutil reset ScreenCapture com.nousresearch.hermes` (repeat per affected service), toggle it ON in ""System Settings, then fully quit & relaunch Hermes once.")@@ -302,7 +299,7 @@ def _macos_desktop_dr(app: Path) -> str | None:def check_macos_tcc_anchor(should_fix: bool = False) -> None:"""Report (and with --fix install) the dylib-complete TCC anchor; silent on non-macOS / non-uv interpreters.Never raises. Install is gated by the module's pre-install boot probe, so ``--fix`` cannot brick the CLI."""- try:+ with warn_on_error("macOS TCC anchor check failed"):from hermes_cli import macos_tcc_anchor as tccstatus, detail = tcc.tcc_anchor_state()if status == "skip":@@ -313,8 +310,6 @@ def check_macos_tcc_anchor(should_fix: bool = False) -> None:if anchored is not None:return check_ok("macOS TCC anchor installed", f"({anchored})")check_warn("macOS TCC anchor missing" if status == "missing" else "macOS TCC anchor stale", f"({detail})")- except Exception as e:- check_warn("macOS TCC anchor check failed", f"({e})")def check_macos_full_disk_access() -> None:@@ -325,18 +320,17 @@ def check_macos_full_disk_access() -> None:"""if sys.platform != "darwin":return- tcc_dir = Path.home() / "Library" / "Application Support" / "com.apple.TCC"try:- os.listdir(tcc_dir)- except OSError as e:- if not isinstance(e, PermissionError):- return+ os.listdir(Path.home() / "Library" / "Application Support" / "com.apple.TCC")+ except PermissionError:check_info("One switch silences all macOS folder prompts: grant your terminal app Full Disk Access and Hermes ""will never trip per-folder dialogs (Desktop/Downloads/Documents/...) again. Open: System Settings → ""Privacy & Security → Full Disk Access — or run:\n"" open \"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles\"\n"" then enable your terminal (and Hermes.app if you use Desktop), and restart them once. ""With Hermes' stable signing identities the grant survives every update.")+ except OSError:+ pass # missing dir / other error: indeterminate, stay silentelse:check_ok("macOS Full Disk Access granted", "(no per-folder permission prompts will occur)")@@ -350,12 +344,12 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:if not fresh_hits:return check_ok("No active security advisories")for hit in fresh_hits:- check_fail(f"{hit.advisory.title}", f"({hit.package}=={hit.installed_version})")- for line in full_remediation_text(hit): # indented under the header as one section+ # Fail row + remediation text indented under it as one section; also into the summary action list.+ _fail_and_issue(f"{hit.advisory.title}", f"({hit.package}=={hit.installed_version})",+ f"Resolve security advisory {hit.advisory.id}: uninstall {hit.package}=={hit.installed_version} "+ f"and rotate credentials, then run `hermes doctor --ack {hit.advisory.id}`.", f.manual_issues)+ for line in full_remediation_text(hit):print(f" {color(line, Colors.YELLOW)}" if line else "")- # Also into the action list so the summary block surfaces it.- f.manual_issues.append(f"Resolve security advisory {hit.advisory.id}: uninstall {hit.package}=={hit.installed_version} "- f"and rotate credentials, then run `hermes doctor --ack {hit.advisory.id}`.")acked_ids = get_acked_ids() # acked-but-still-installed stays visiblefor h in all_hits:if h.advisory.id in acked_ids:@@ -366,30 +360,22 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:def _check_python_environment(should_fix: bool, f: Finding) -> None:"""Interpreter, linked SQLite, venv, macOS TCC anchors/FDA/grants, version-file drift."""v, label = sys.version_info, f"Python {'.'.join(map(str, sys.version_info[:3]))}"- if v >= (3, 10):- check_ok(label)- if v < (3, 11):- check_warn("Python 3.11+ recommended for RL Training tools (tinker requires >= 3.11)")- elif v >= (3, 8):- check_warn(label, "(3.10+ recommended)")- else:+ if v < (3, 8):_fail_and_issue(label, "(3.10+ required)", "Upgrade Python to 3.10+", f.issues)+ elif check_bool(v >= (3, 10), label, (label, "(3.10+ recommended)")) and v < (3, 11):+ check_warn("Python 3.11+ recommended for RL Training tools (tinker requires >= 3.11)")# Linked SQLite: version + source id matter independently of the Python minor (uv's# python-build-standalone can keep a vulnerable SQLite across upgrades).- try:+ with warn_on_error("SQLite version probe failed: {e}", ""):import sqlite3from hermes_state import is_sqlite_wal_reset_vulnerable, sqlite_source_idsrc = sqlite_source_id()- if is_sqlite_wal_reset_vulnerable():- # Warn-only: Hermes already refuses WAL on fresh DBs and runtime repair is best-effort.- check_warn(f"SQLite {sqlite3.sqlite_version} (WAL-reset bug)", _sqlite_upgrade_hint())- else:- check_ok(f"SQLite {sqlite3.sqlite_version}")+ # Warn-only: Hermes already refuses WAL on fresh DBs and runtime repair is best-effort.+ check_bool(not is_sqlite_wal_reset_vulnerable(), f"SQLite {sqlite3.sqlite_version}",+ (f"SQLite {sqlite3.sqlite_version} (WAL-reset bug)", _sqlite_upgrade_hint()))if src:check_info(f"SQLite source id: {(src[:48] + '…') if len(src) > 48 else src}")_report_database_journal_modes()- except Exception as e:- check_warn(f"SQLite version probe failed: {e}")check_bool(sys.prefix != sys.base_prefix, "Virtual environment active", ("Not in virtual environment", "(recommended)"))check_macos_tcc_anchor(should_fix=should_fix)check_macos_full_disk_access()@@ -443,10 +429,8 @@ def _check_command_installation(should_fix: bool, f: Finding) -> None:check_ok(f"Venv entry point exists ({venv_bin.relative_to(PROJECT_ROOT)})")# Expected command link directory (mirrors install.sh logic).prefix = os.environ.get("PREFIX", "")- if prefix and (os.environ.get("TERMUX_VERSION") or "com.termux/files/usr" in prefix):- link_dir, display = Path(prefix) / "bin", "$PREFIX/bin"- else:- link_dir, display = Path.home() / ".local" / "bin", "~/.local/bin"+ termux = prefix and (os.environ.get("TERMUX_VERSION") or "com.termux/files/usr" in prefix)+ link_dir, display = (Path(prefix) / "bin", "$PREFIX/bin") if termux else (Path.home() / ".local" / "bin", "~/.local/bin")link = link_dir / "hermes"if link.is_symlink():target, expected = link.resolve(), venv_bin.resolve()diff --git a/hermes_cli/doctor_report.py b/hermes_cli/doctor_report.pyindex 410258aaace..fc258dd4f9c 100644--- a/hermes_cli/doctor_report.py+++ b/hermes_cli/doctor_report.py@@ -3,6 +3,7 @@from __future__ import annotationsimport functools+from contextlib import contextmanagerfrom dataclasses import dataclass, fieldfrom hermes_cli.colors import Colors, color@@ -39,6 +40,17 @@ def _fail_and_issue(text: str, detail: str, fix: str, issues: list[str]) -> Noneissues.append(fix)+@contextmanager+def warn_on_error(text: str, detail: str = "({e})", report=check_warn):+ """Best-effort block: an exception prints ``report(text.format(e=e), detail.format(e=e))`` (nothing when+ *text* is ``""``) instead of propagating. ``{e}`` in either string is the exception."""+ try:+ yield+ except Exception as e:+ if text:+ report(text.format(e=e), detail.format(e=e))++@dataclassclass Finding:"""What one doctor check contributed: auto-fixable issues, manual-only issues, fixes applied."""@@ -57,20 +69,17 @@ def doctor_check(on_error: str | None = None, detail: str = ""):"""Turn ``fn(should_fix, f: Finding)`` into a ``(should_fix) -> Finding`` doctor check.*on_error* None: exceptions propagate (as they always did for that check). Otherwise the check is- best-effort: a crash prints ``check_warn(on_error.format(e=e), detail.format(e=e))`` (nothing for- ``""``) and the partial Finding is still returned, so issues recorded before the crash survive.- """+ best-effort via :func:`warn_on_error` (``""`` = silent) and the partial Finding is still returned,+ so issues recorded before the crash survive."""def deco(fn):@functools.wraps(fn)def check(should_fix: bool) -> Finding:f = Finding()- try:+ if on_error is None:fn(should_fix, f)- except Exception as e:- if on_error is None:- raise- if on_error:- check_warn(on_error.format(e=e), detail.format(e=e))+ else:+ with warn_on_error(on_error, detail):+ fn(should_fix, f)return freturn checkreturn deco