The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): doctor — compact module docstrings/comments, banner loop, drop in-function blanks
Teknium52552aed6e53
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex 1633e1b93ea..4ad707b8eb0 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -1,13 +1,11 @@"""``hermes doctor`` — diagnose (and with --fix, repair) a Hermes install.-``run_doctor`` walks ``DOCTOR_CHECKS`` in order; each check prints its own-rows and returns a ``Finding``. Check bodies live in the ``doctor_*`` sibling-modules and are re-exported here so ``hermes_cli.doctor.<name>`` stays the-stable import/monkeypatch surface.+``run_doctor`` walks ``DOCTOR_CHECKS`` in order; each check prints its own rows and returns a ``Finding``.+Check bodies live in the ``doctor_*`` siblings and are re-exported here so ``hermes_cli.doctor.<name>``+stays the stable import/monkeypatch surface."""-# stdlib modules stay bound here: tests patch doctor.shutil.which / doctor.subprocess.run /-# doctor.importlib.util.find_spec / doctor.Path.home / doctor.sys.platform / doctor.os.listdir.+# stdlib modules stay bound here: tests patch doctor.shutil.which / .subprocess.run / .importlib.util.find_spec / .Path.home / .sys.platform / .os.listdir.import osimport sysimport subprocess # noqa: F401@@ -19,7 +17,7 @@ from hermes_cli.config import ( # noqa: F401 (detect_install_method: tests patdetect_install_method, get_env_path, get_hermes_home, get_project_root,)from hermes_cli.env_loader import load_hermes_dotenv-from hermes_constants import display_hermes_home+from hermes_constants import display_hermes_home, is_termux as _is_termux # noqa: F401 (tests call doctor._is_termux)PROJECT_ROOT = get_project_root()HERMES_HOME = get_hermes_home()@@ -71,8 +69,6 @@ _PROVIDER_ENV_HINTS = ("TOKENPLAN_API_KEY",)--from hermes_constants import is_termux as _is_termux # noqa: F401 (tests call doctor._is_termux)from hermes_cli.sizefmt import format_bytes as _human_bytes # noqa: F401 (tests import doctor._human_bytes)@@ -87,17 +83,15 @@ def _check_auth_providers(should_fix: bool) -> Finding:if not _login_row("OpenAI Codex auth", codex_status):if codex_status.get("error"):check_info(codex_status["error"])- # Native OAuth uses Hermes' own device-code flow — the Codex CLI is only needed to import- # existing tokens from ~/.codex/auth.json. Attach the hint to the Codex auth row so it- # doesn't read as remediation for whichever provider happens to print next.+ # Native OAuth uses Hermes' own device-code flow — the Codex CLI only imports existing tokens from+ # ~/.codex/auth.json. Hint sits under the Codex row so it doesn't read as another provider's remedy.if not _safe_which("codex"):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})")- # xAI OAuth — separate try/except so an import failure here cannot- # disrupt the already-printed Nous/Codex/MiniMax rows above.+ # xAI OAuth — separate try/except so an import failure cannot disrupt the already-printed rows above.try:from hermes_cli.auth import get_xai_oauth_auth_statusxai_oauth_status = get_xai_oauth_auth_status() or {}@@ -197,15 +191,15 @@ def _print_summary(should_fix: bool, total: Finding) -> None:def run_doctor(args):"""Run diagnostic checks."""should_fix = getattr(args, 'fix', False)- ack_target = getattr(args, 'ack', None)# Doctor runs from the interactive CLI, so CLI-gated tool checks (e.g. cronjob) see the same context.os.environ.setdefault("HERMES_INTERACTIVE", "1")- if ack_target:- return _ack_advisory(ack_target)+ if getattr(args, 'ack', None):+ return _ack_advisory(args.ack)print()- print(color("┌─────────────────────────────────────────────────────────┐", Colors.CYAN))- print(color("│ 🩺 Hermes Doctor │", Colors.CYAN))- print(color("└─────────────────────────────────────────────────────────┘", Colors.CYAN))+ for line in ("┌─────────────────────────────────────────────────────────┐",+ "│ 🩺 Hermes Doctor │",+ "└─────────────────────────────────────────────────────────┘"):+ print(color(line, Colors.CYAN))total = Finding()for title, check in DOCTOR_CHECKS:if title:diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.pyindex cf9e3192612..09efb1e1348 100644--- a/hermes_cli/doctor_config.py+++ b/hermes_cli/doctor_config.py@@ -1,8 +1,5 @@"""Configuration-file checks for hermes doctor: .env, config.yaml validation, drift, deprecations.--Split out of ``hermes_cli/doctor.py``; every moved name is re-imported there, so-``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching) as before.-"""+Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching)."""from __future__ import annotations@@ -19,10 +16,9 @@ def _has_provider_env_config(content: str) -> bool:return any(key in content for key in _PROVIDER_ENV_HINTS)-# Deprecated / legacy config keys still read for back-compat. Doctor surfaces them as non-failing-# warnings with the modern replacement — it does not auto-migrate (migrations live in config.py).+# Legacy config keys still read for back-compat: warn-only with the modern replacement, never auto-migrated+# (migrations live in config.py). (section, key, replacement)_DEPRECATED_CONFIG_KEYS: tuple[tuple[str, str, str], ...] = (- # (section, key, replacement)("display", "tool_progress_overrides", "display.platforms"),("delegation", "max_async_children", "delegation.max_concurrent_children"),("compression", "summary_model", "auxiliary.compression"),@@ -31,11 +27,10 @@ _DEPRECATED_CONFIG_KEYS: tuple[tuple[str, str, str], ...] = ()-# Deprecated env vars (checked in the .env file, not process env, so config→env-# bridges like terminal.cwd → TERMINAL_CWD do not false-positive).+# Deprecated env vars (checked in the .env FILE, not process env, so config→env bridges like terminal.cwd →+# TERMINAL_CWD do not false-positive). HERMES_TOOL_PROGRESS is silently ignored since the v12 config floor+# removed its only consumer; HERMES_TOOL_PROGRESS_MODE is still read by the gateway as a back-compat fallback._DEPRECATED_ENV_VARS: tuple[tuple[str, str], ...] = (- # HERMES_TOOL_PROGRESS is silently ignored since the v12 config floor removed its only consumer;- # HERMES_TOOL_PROGRESS_MODE is still read by the gateway as a back-compat fallback.("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"),@@ -75,11 +70,9 @@ def collect_relay_plugin_cutover_findings(raw_config: dict | None, env_map: dictif isinstance(plugins, dict):findings += [(f"plugins.enabled: {key}", f"remove it and configure {RELAY_PLUGINS_CONFIG_ENV}")for key in legacy_relay_plugin_keys(plugins.get("enabled"))]-effective_env = dict(env_map or {})- # Fall through to process-level env ONLY when no explicit env_map was given: run_doctor passes- # None and wants live-process vars included, but callers (and tests) handing in an explicit map- # describe a complete environment — merging os.environ on top breaks hermeticity.+ # Fall through to process env ONLY when no explicit env_map was given: run_doctor passes None and wants+ # live-process vars, but an explicit map describes a complete environment (merging os.environ breaks hermeticity).if env_map is None:for name in (*LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV):if name not in effective_env and os.environ.get(name) is not None:@@ -99,7 +92,6 @@ def report_deprecated_config_and_env(raw_config: dict | None = None, env_map: diif not findings:check_ok("No deprecated config keys or env vars")return findings-for legacy, replacement in deprecated:check_warn(f"Deprecated: {legacy}", f"(use {replacement} instead)")check_info(f"Replace {legacy} → {replacement} (warn-only; not auto-migrated here)")@@ -153,8 +145,7 @@ def _check_env_file(should_fix: bool) -> Finding:env_path = HERMES_HOME / '.env'if env_path.exists():check_ok(f"{_DHH}/.env file exists")- # Prefer UTF-8 (.env is written as UTF-8 elsewhere); latin-1 fallback for Windows- # Notepad/cp1252 files — matches hermes_cli.env_loader._load_dotenv_with_fallback.+ # UTF-8 first; latin-1 fallback for Windows Notepad/cp1252 files (matches env_loader._load_dotenv_with_fallback).try:content = env_path.read_text(encoding="utf-8")except UnicodeDecodeError:@@ -206,7 +197,6 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:custom_providers = []except Exception:pass-user_providers = cfg.get("providers")if isinstance(user_providers, dict):from hermes_cli.config import is_provider_enabled@@ -219,8 +209,8 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:return known, custom_providers, resolve_auth, normalize, resolve_full-# Vendor/model slugs are valid on aggregator-style providers and on any custom provider. Fireworks'-# native IDs are slash-form (accounts/fireworks/models/...); DeepInfra's catalog is exclusively vendor/model.+# 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",@@ -249,7 +239,6 @@ def _validate_model_config(config_path, issues: list) -> None:provider_raw = (model_section.get("provider") or "").strip()provider = provider_raw.lower()default_model = (model_section.get("default") or model_section.get("model") or "").strip()-known_providers, custom_providers, resolve_auth, normalize, resolve_full = _known_provider_ids(cfg)valid_provider_ids = set(known_providers)accept = {provider} if provider else set()@@ -258,7 +247,6 @@ def _validate_model_config(config_path, issues: list) -> None:valid_provider_ids.add(normalize(known_provider))except Exception:continue-runtime_provider = catalog_provider = providerif provider and provider not in {"auto", "custom"}:if resolve_auth is not None:@@ -272,7 +260,6 @@ def _validate_model_config(config_path, issues: list) -> None:catalog_provider = provider_def.id if provider_def is not None else Noneif catalog_provider is not None:accept.add(catalog_provider)-if provider and provider != "auto" and (catalog_provider is None or (known_providers and not (accept & valid_provider_ids))):known_list = ", ".join(sorted(known_providers)) if known_providers else "(unavailable)"_fail_and_issue(@@ -281,7 +268,6 @@ def _validate_model_config(config_path, issues: list) -> None:f"Fix: run 'hermes config set model.provider <valid_provider>'",issues,)-policy_id = str(runtime_provider or catalog_provider or "").strip().lower()accepts_vendor_slug = policy_id in _VENDOR_SLUG_PROVIDERS or policy_id == "custom" or policy_id.startswith("custom:")if default_model and "/" in default_model and policy_id and not accepts_vendor_slug:@@ -289,7 +275,6 @@ def _validate_model_config(config_path, issues: list) -> None:"(vendor-prefixed slugs belong to aggregators like openrouter)")issues.append(f"model.default '{default_model}' is vendor-prefixed but model.provider is '{provider_raw}'. ""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 _DHHtry:diff --git a/hermes_cli/doctor_connectivity.py b/hermes_cli/doctor_connectivity.pyindex 1c1295d8e47..78b974afe41 100644--- a/hermes_cli/doctor_connectivity.py+++ b/hermes_cli/doctor_connectivity.py@@ -48,7 +48,6 @@ def _has_healthy_oauth_fallback_for_apikey_provider(provider_label: str) -> boolreturn Falsetry:from hermes_cli import auth-return bool((getattr(auth, getter)() or {}).get("logged_in"))except Exception:return False@@ -107,8 +106,7 @@ def _build_apikey_providers_list() -> list:continueif {_normalize_provider(a) for a in (_pp.name, *(_pp.aliases or ()))} & _dedicated_canonical:continue- # Separate API-key vars from base-URL override vars — the health-check loop sends the- # first found value as Authorization: Bearer, so a URL string must never be picked.+ # Key vars vs base-URL vars: the first found value goes out as Authorization: Bearer, never a URL._is_url = lambda v: v.endswith("_BASE_URL") or v.endswith("_URL") # noqa: E731_key_vars = tuple(v for v in _pp.env_vars if not _is_url(v))if not _key_vars:@@ -167,9 +165,8 @@ def _probe_anthropic() -> ProbeResult:headers["x-api-key"] = keyurl = "https://api.anthropic.com/v1/models"r = httpx.get(url, headers=headers, timeout=10)- # Reactive recovery: OAuth subscriptions without 1M context reject with 400 "long context beta- # is not yet available for this subscription". Retry once with that beta stripped so doctor- # doesn't falsely report Anthropic as unreachable.+ # OAuth subscriptions without 1M context reject with 400 "long context beta is not yet available";+ # retry once with that beta stripped so doctor doesn't falsely report Anthropic as unreachable.if is_oauth and r.status_code == 400 and "long context beta" in r.text.lower() and "not yet available" in r.text.lower():headers["anthropic-beta"] = ",".join([b for b in _COMMON_BETAS if b != _CONTEXT_1M_BETA] + list(_OAUTH_ONLY_BETAS))r = httpx.get(url, headers=headers, timeout=10)@@ -208,8 +205,7 @@ def _apikey_request(key: str, base_env, default_url) -> tuple:# Kimi Code keys (sk-kimi-) → api.kimi.com/coding/v1 (OpenAI-compat surface exposing /models).if not base and key.startswith("sk-kimi-"):base = "https://api.kimi.com/coding/v1"- # Anthropic-compat endpoints (/anthropic, api.kimi.com/coding with no /v1) don't support- # /models — rewrite to the OpenAI-compat /v1 surface for health checks.+ # Anthropic-compat endpoints (/anthropic, api.kimi.com/coding sans /v1) lack /models — use the OpenAI-compat /v1 surface.if base and base.rstrip("/").endswith("/anthropic"):from agent.auxiliary_client import _to_openai_base_urlbase = _to_openai_base_url(base)@@ -274,14 +270,12 @@ def _probe_azure_entra() -> ProbeResult:return _skip(name)except Exception:return _skip(name)-try:from agent.azure_identity_adapter import (EntraIdentityConfig, SCOPE_AI_AZURE_DEFAULT, describe_active_credential, has_azure_identity_installed,)except Exception as exc:return _row(name, "warn", f"(adapter import failed: {exc})", [f"Azure Foundry adapter import failed: {exc}"], label=label)-if not has_azure_identity_installed():return _row(name, "warn", "(azure-identity not installed)", [f"Install azure-identity: {sys.executable} -m pip install azure-identity"], label=label)entra_cfg = model_cfg.get("entra") or {}@@ -315,9 +309,8 @@ def run_probes(probes: list) -> list:Probes are independent HTTP calls (series cost ~5s wall, 2s of it boto3's IMDS lookup);parallel collapses the section to roughly the slowest single probe without changing the output."""- # Disable boto3's EC2 instance-metadata probe (169.254.169.254, multi-second timeout off-EC2).- # Set on the parent thread before submitting so the env mutation never races a worker;- # has_aws_credentials() already gates on real env creds, so IMDS is never legitimate for doctor.+ # Disable boto3's EC2 instance-metadata probe (169.254.169.254, multi-second timeout off-EC2). Set on the+ # parent thread before submitting so it never races a worker; has_aws_credentials() already gates on real creds._imds_prev = os.environ.get("AWS_EC2_METADATA_DISABLED")os.environ["AWS_EC2_METADATA_DISABLED"] = "true"try:diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.pyindex 42e55342107..6bf7322b3bc 100644--- a/hermes_cli/doctor_platform.py+++ b/hermes_cli/doctor_platform.py@@ -1,7 +1,5 @@"""Host-platform checks for hermes doctor: interpreter, SQLite, certificates, macOS TCC, gateway supervision, command install.--Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching).-"""+Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching)."""from __future__ import annotations@@ -43,7 +41,6 @@ def _sqlite_upgrade_hint(install_method: str | None = None) -> str:def _hermes_database_paths(hermes_home: Path) -> list[tuple[str, Path]]:"""(display name, path) pairs for Hermes-managed SQLite databases: backup.py's per-profile store list + per-board kanban.db."""from hermes_cli.backup import _QUICK_STATE_FILES-entries = [(name, hermes_home / name) for name in _QUICK_STATE_FILES if name.endswith(".db")]for board_db in sorted((hermes_home / "kanban" / "boards").glob("*/kanban.db")):entries.append((str(board_db.relative_to(hermes_home)), board_db))@@ -75,7 +72,6 @@ def _read_journal_mode(db_path: Path) -> tuple[str | None, str | None]:``run_doctor`` in-process with live ``SessionDB`` connections — the helper refuses then (unreadable)."""from hermes_cli.sqlite_safe_read import has_live_connection, read_header_bytes_preopen-header = read_header_bytes_preopen(db_path, length=20)if header is None:return None, "database is open in this process" if has_live_connection(db_path) else _unreadable_reason(db_path)@@ -89,7 +85,6 @@ def _read_journal_mode(db_path: Path) -> tuple[str | None, str | None]:def _format_db_size(db_path: Path) -> str:from hermes_cli.backup import _format_size # backup.py owns size formatting-try:return _format_size(db_path.stat().st_size)except OSError:@@ -100,7 +95,6 @@ def _report_database_journal_modes(hermes_home: Path | None = None, version_info"""List each database's journal mode; warn on WAL under a vulnerable SQLite."""from hermes_cli.doctor import HERMES_HOMEfrom hermes_state import _wal_reset_repair_hint, is_sqlite_wal_reset_vulnerable-vulnerable = is_sqlite_wal_reset_vulnerable(version_info)try:databases = _hermes_database_paths(hermes_home if hermes_home is not None else HERMES_HOME)@@ -174,13 +168,11 @@ def _check_s6_supervision(issues: list[str]) -> None:returnif detect_service_manager() != "s6":return-_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)")-profiles = mgr.list_profile_gateways()if not profiles:return check_info("No per-profile gateways registered yet — create one with `hermes profile create <name>`")@@ -212,13 +204,11 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -except Exception as e:check_warn("SSL certificate check skipped", str(e))return-check_fail("SSL CA certificate bundle is broken", first_error)pip_cmd = f"{sys.executable} -m pip install --force-reinstall certifi"if not should_fix:issues.append(f"Repair the CA bundle: run `hermes doctor --fix`, or `{pip_cmd}`")return-print(" → Repairing: force-reinstalling certifi...")try:result = subprocess.run([sys.executable, "-m", "pip", "install", "--force-reinstall", "certifi"],@@ -230,13 +220,11 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -check_fail(*failure)issues.append(f"Reinstall certifi manually: {pip_cmd}")return-# 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.")]:sys.modules.pop(mod_name, None)importlib.invalidate_caches()-try:verify_ca_bundle_with_fallback()check_ok("SSL CA certificate bundle repaired (certifi reinstalled)")@@ -256,7 +244,6 @@ def _check_gateway_service_linger(issues: list[str]) -> None:returnif 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 True:@@ -325,7 +312,6 @@ def check_macos_tcc_anchor(should_fix: bool = False) -> None:Never raises. Install is gated by the module's pre-install boot probe, so ``--fix`` cannot brick the CLI."""try:from hermes_cli import macos_tcc_anchor as tcc-status, detail = tcc.tcc_anchor_state()if status == "skip":return@@ -403,13 +389,11 @@ def _check_python_environment(should_fix: bool) -> Finding:check_warn(label, "(3.10+ recommended)")else:_fail_and_issue(label, "(3.10+ required)", "Upgrade Python to 3.10+", f.issues)-# Linked SQLite: version + source id matter independently of the Python minor (uv's# python-build-standalone can keep a vulnerable SQLite across upgrades).try:import sqlite3from hermes_state import is_sqlite_wal_reset_vulnerable, sqlite_source_id-src = sqlite_source_id()if is_sqlite_wal_reset_vulnerable():# Warn-only: Hermes already refuses WAL on fresh DBs and runtime repair is best-effort.@@ -421,7 +405,6 @@ def _check_python_environment(should_fix: bool) -> Finding:_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()@@ -478,13 +461,11 @@ def _check_command_installation(should_fix: bool) -> Finding:else:link_dir, display = Path.home() / ".local" / "bin", "~/.local/bin"link = link_dir / "hermes"-if venv_bin is None:check_warn("Venv entry point not found", "(hermes not in venv/bin/ or .venv/bin/ — reinstall with pip install -e '.[all]')")f.manual_issues.append(f"Reinstall entry point: cd {PROJECT_ROOT} && source venv/bin/activate && pip install -e '.[all]'")return fcheck_ok(f"Venv entry point exists ({venv_bin.relative_to(PROJECT_ROOT)})")-if link.is_symlink():target, expected = link.resolve(), venv_bin.resolve()if target == expected:diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.pyindex 9f1ded812bc..97c1eaa9339 100644--- a/hermes_cli/doctor_state.py+++ b/hermes_cli/doctor_state.py@@ -1,8 +1,5 @@"""HERMES_HOME state checks for hermes doctor: directories, memory files, state.db health, skills hub, memory provider, profiles.--Split out of ``hermes_cli/doctor.py``; every moved name is re-imported there, so-``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching) as before.-"""+Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching)."""from __future__ import annotations@@ -44,8 +41,7 @@ def _doctor_memory_config(hermes_home: Path | None = None) -> dict:return {}-# state.db size threshold (advisory only — deliberately a module constant, not config:-# doctor warnings are guidance, not policy).+# state.db size threshold — advisory only; deliberately a module constant, not config (doctor warnings are guidance, not policy).STATE_DB_SIZE_WARN_BYTES = 1 * 1024 * 1024 * 1024 # 1 GiB logical size@@ -87,19 +83,15 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:lines.append(("warn", f"state.db FTS repair is blocked after {deferral.get('attempts') or '?'} deferral(s) "f"by PID(s) {deferral.get('holder_pids') or [] or 'unknown'}","(stop the listed processes, then run 'hermes sessions optimize-storage' with the gateway stopped)"))-- # Advisory: oversized database. Suggest auto_prune, and — when the v23 FTS rebuild is pending OR- # the DB still carries the legacy inline trigram layout (fts_storage_version marker absent) —- # the offline optimize-storage pass that migrates/compacts the FTS indexes.+ # Oversized DB: suggest auto_prune, plus the offline optimize-storage pass when the v23 FTS rebuild is+ # pending OR the DB still carries the legacy inline trigram layout (fts_storage_version marker absent).if logical is not None and logical > STATE_DB_SIZE_WARN_BYTES:detail = "consider enabling sessions.auto_prune in config.yaml to bound growth"legacy_trigram = fts is not None and fts.get("messages_fts_trigram") and stats.get("fts_storage_version") is Noneif stats.get("fts_rebuild_pending") or legacy_trigram:detail += "; run 'hermes sessions optimize-storage' offline (with the gateway stopped) to compact FTS storage"lines.append(("warn", f"state.db is large ({_human_bytes(logical)})", f"({detail})"))-- # WAL runaway is deliberately NOT warned here: the WAL check later in the state.db section already- # warns above 50 MB and offers a checkpoint via --fix; a second warning would only duplicate it.+ # WAL runaway is deliberately NOT warned here: _state_db_wal already warns above 50 MB and offers --fix.return lines@@ -114,16 +106,12 @@ def _check_directory_structure(should_fix: bool) -> Finding:f = Finding()hermes_home = HERMES_HOMEensure_dir(f, should_fix, hermes_home, f"{_DHH} directory exists", f"Created {_DHH} directory", f"{_DHH} not found")-_memory_enabled, _user_profile_enabled = _memory_store_flags(hermes_home)memory_on = _memory_enabled or _user_profile_enabled-- # Expected subdirectories. The built-in file store does not create or consume memories/ when- # both targets are disabled, so stale migration files are not an active diagnostic surface.+ # The built-in file store neither creates nor consumes memories/ when both targets are disabled.for subdir_name in ["cron", "sessions", "logs", "skills"] + (["memories"] if memory_on else []):ensure_dir(f, should_fix, hermes_home / subdir_name, f"{_DHH}/{subdir_name}/ exists",f"Created {_DHH}/{subdir_name}/", f"{_DHH}/{subdir_name}/ not found")-# SOUL.md persona filesoul_path = hermes_home / "SOUL.md"if soul_path.exists():@@ -141,9 +129,8 @@ def _check_directory_structure(should_fix: bool) -> Finding:"You are Hermes, a helpful AI assistant.\n", encoding="utf-8")check_ok(f"Created {_DHH}/SOUL.md with basic template")f.fixed += 1-- # Check only enabled built-in stores. External providers are additive, but users can explicitly- # disable either legacy file target; stale migration files must not read as active memory usage.+ # Only enabled built-in stores: users can disable either legacy file target, and stale migration files+ # must not read as active memory usage.memories_dir = hermes_home / "memories"if not memory_on:check_info("Built-in memory files disabled by config")@@ -212,8 +199,8 @@ def _state_db_health(f: Finding, should_fix: bool, state_db_path: Path, _DHH: st"""Session count + FTS write-health probe; malformed-schema path when even COUNT(*) fails."""try:check_ok(f"{_DHH}/state.db exists ({_session_count(state_db_path)} sessions)")- # `SELECT COUNT(*)` succeeds even when the FTS index is corrupt and every message write- # fails through the triggers; _db_opens_cleanly drives a rolled-back write to surface that.+ # COUNT(*) succeeds even when the FTS index is corrupt and every write fails through the triggers;+ # _db_opens_cleanly drives a rolled-back write to surface that.from hermes_state import _db_opens_cleanly_write_reason = _db_opens_cleanly(state_db_path)if _write_reason is not None:@@ -224,8 +211,8 @@ def _state_db_health(f: Finding, should_fix: bool, state_db_path: Path, _DHH: stif not is_malformed_db_error(e):check_warn(f"{_DHH}/state.db exists but has issues: {e}")return- # sqlite_master itself is malformed (e.g. duplicate messages_fts): every statement fails- # before it runs, so this is NOT a plain FTS rebuild — repair sqlite_master in place (backup first).+ # sqlite_master itself is malformed (e.g. duplicate messages_fts): every statement fails before it runs,+ # so this is NOT a plain FTS rebuild — repair sqlite_master in place (backup first).check_warn(f"{_DHH}/state.db schema is malformed (sessions hidden until repaired)", f"({e})")_repair_state_db(f, should_fix, state_db_path, "schema")@@ -314,7 +301,6 @@ def _check_skills_hub(should_fix: bool) -> Finding:q_count = sum(1 for d in quarantine.iterdir() if d.is_dir()) if quarantine.exists() else 0if q_count > 0:check_warn(f"{q_count} skill(s) in quarantine", "(pending review)")-from hermes_cli.config import get_env_valueif get_env_value("GITHUB_TOKEN") or get_env_value("GH_TOKEN"):check_ok("GitHub token configured (authenticated API access)")@@ -423,7 +409,6 @@ def _check_profiles(should_fix: bool, f: Finding) -> None:if not (wrapper_dir / p.name).exists():parts.append("no alias")check_ok(f" {p.name}: {', '.join(parts) if parts else 'configured'}")-# Orphan wrappersif wrapper_dir.is_dir():for wrapper in wrapper_dir.iterdir():diff --git a/hermes_cli/doctor_tools.py b/hermes_cli/doctor_tools.pyindex 051c5d0ffb4..930758225a8 100644--- a/hermes_cli/doctor_tools.py+++ b/hermes_cli/doctor_tools.py@@ -1,7 +1,5 @@"""External-tool checks for hermes doctor: terminal backends, git/rg, Node + agent-browser, npm audit, tool availability.--Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching).-"""+Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching)."""from __future__ import annotations@@ -111,7 +109,6 @@ def _enabled_cli_toolsets_for_doctor() -> set[str] | None:try:from hermes_cli.config import load_configfrom hermes_cli.tools_config import _get_platform_tools-return {str(toolset) for toolset in _get_platform_tools(load_config() or {}, "cli")}except Exception:return None@@ -197,7 +194,6 @@ def _check_vercel_backend(issues: list[str]) -> None:_require(importlib.util.find_spec("vercel") is not None, ("vercel SDK", "(installed)"),("vercel SDK not installed", "(pip install 'hermes-agent[vercel]')"),"Install the Vercel optional dependency: pip install 'hermes-agent[vercel]'", issues)-auth_status = describe_vercel_auth()if auth_status.ok:check_ok("Vercel auth", f"({auth_status.label})")@@ -239,8 +235,8 @@ def _check_terminal_backend(should_fix: bool) -> Finding:running_in_container = _is_container()except Exception:running_in_container = False- # Inside our container docker-in-docker isn't set up, so the local backend is the intended one: skip the- # noisy "docker not found" warning. An explicit TERMINAL_ENV=docker (mounted docker.sock) still gets checked.+ # In our container docker-in-docker isn't set up, so local is intended: skip the noisy "docker not found"+ # warning. An explicit TERMINAL_ENV=docker (mounted docker.sock) still gets checked.if running_in_container and terminal_env != "docker":check_info("Running inside a container — using local terminal backend (docker-in-docker is not configured by default)")terminal_env = "local"@@ -263,7 +259,6 @@ def _check_agent_browser(should_fix: bool) -> bool:resolved = _find_agent_browser(validate=False)except Exception:resolved = None-if resolved and _is_npx_agent_browser_sentinel(resolved):check_ok("agent-browser", "(resolves via npx on first use)")if should_fix:@@ -426,9 +421,7 @@ def _check_tool_availability(should_fix: bool, f: Finding) -> None:from hermes_cli.doctor import PROJECT_ROOT, _doctor_web_capability_rowssys.path.insert(0, str(PROJECT_ROOT))from model_tools import check_tool_availability, TOOLSET_REQUIREMENTS-available, unavailable = _apply_doctor_tool_availability_overrides(*check_tool_availability())-# Web is split into search/extract readiness rows so an explicitly# selected but unconfigured backend cannot look healthy.web_rows = []@@ -437,7 +430,6 @@ def _check_tool_availability(should_fix: bool, f: Finding) -> None:if web_rows:available = [tid for tid in available if tid != "web"]unavailable = [item for item in unavailable if item.get("name") != "web"]-for tid in available:check_ok(TOOLSET_REQUIREMENTS.get(tid, {}).get("name", tid), _doctor_tool_availability_detail(tid))for status, label, detail in web_rows:@@ -445,7 +437,6 @@ def _check_tool_availability(should_fix: bool, f: Finding) -> None:for item in unavailable:env_vars = item.get("missing_vars") or item.get("env_vars") or []check_warn(item["name"], f"(missing {', '.join(env_vars)})" if env_vars else "(system dependency not met)")-# Only toolsets enabled for the CLI count toward the summary; default-off or# disabled toolsets may warn above but must not pollute it.api_disabled = _missing_api_key_toolsets_for_summary(unavailable)diff --git a/hermes_cli/dump.py b/hermes_cli/dump.pyindex cf18dc33fe3..91c9bfd49c4 100644--- a/hermes_cli/dump.py+++ b/hermes_cli/dump.py@@ -229,7 +229,6 @@ def _openai_version() -> str:def run_dump(args):"""Output a compact, copy-pasteable setup summary."""show_keys = getattr(args, "show_keys", False)-# Load env from .env file so key checks workload_hermes_dotenv(hermes_home=get_env_path().parent, project_env=get_project_root() / ".env")project_root = get_project_root()@@ -245,7 +244,6 @@ def run_dump(args):except Exception:profile = "(default)"openai_ver = _openai_version()-lines = ["--- hermes dump ---",f"version: {_version_line(project_root)}",@@ -261,7 +259,6 @@ def run_dump(args):"api_keys:",*_api_key_lines(show_keys),]-toolsets = config.get("toolsets", ["hermes-cli"])platforms = [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]lines += [@@ -275,7 +272,6 @@ def run_dump(args):f" cron_jobs: {_cron_summary(hermes_home)}",f" skills: {_count_skills(hermes_home)}",]-overrides = _config_overrides(config)if overrides:lines += ["", "config_overrides:"] + [f" {key}: {val}" for key, val in overrides.items()]