Skip to content

The agent that grows with you

refactor(hermes_cli): doctor — symlink verb merge, run_dump single list, drift/linger/version early returns

Teknium6e1fc36ce091
diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.py
index 93c10aa6daa..1836a92a15a 100644
--- a/hermes_cli/doctor_config.py
+++ b/hermes_cli/doctor_config.py
@@ -185,11 +185,7 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:
pass
try:
from hermes_cli.config import get_compatible_custom_providers
- from hermes_cli.providers import (
- custom_provider_aliases as aliases,
- normalize_provider as normalize,
- resolve_provider_full as resolve_full,
- )
+ from hermes_cli.providers import custom_provider_aliases as aliases, normalize_provider as normalize, resolve_provider_full as resolve_full
try:
custom_providers = get_compatible_custom_providers(cfg)
except Exception:
@@ -257,16 +253,12 @@ def _validate_model_config(config_path, issues: list) -> None:
if resolve_full is not None:
provider_def = resolve_full(provider, cfg.get("providers"), custom_providers)
catalog_provider = provider_def.id if provider_def is not None else None
- if catalog_provider is not None:
- accept.add(catalog_provider)
+ accept.update({catalog_provider} - {None})
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(
- f"model.provider '{provider_raw}' is not a recognised provider", f"(known: {known_list})",
- f"model.provider '{provider_raw}' is unknown. Valid providers: {known_list}. "
- f"Fix: run 'hermes config set model.provider <valid_provider>'",
- issues,
- )
+ _fail_and_issue(f"model.provider '{provider_raw}' is not a recognised provider", f"(known: {known_list})",
+ f"model.provider '{provider_raw}' is unknown. Valid providers: {known_list}. "
+ 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:
@@ -278,14 +270,10 @@ def _validate_model_config(config_path, issues: list) -> None:
from hermes_cli.doctor import _DHH
try:
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}'. "
- f"Run 'hermes setup' or set the provider's API key in {_DHH}/.env, "
- f"or switch providers with 'hermes config set model.provider <name>'",
- issues,
- )
+ _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
@@ -348,15 +336,12 @@ def _drift_stale_root_keys(f: Finding, should_fix: bool, config_path) -> None:
return
# Coerce scalar/None ``model:`` into a dict before mutation (setdefault would hand back a scalar).
raw_model = raw_config.get("model")
- if isinstance(raw_model, dict):
- model_section = raw_model
- else:
- model_section = {"default": raw_model.strip()} if isinstance(raw_model, str) and raw_model.strip() else {}
- raw_config["model"] = model_section
+ if not isinstance(raw_model, dict):
+ raw_model = raw_config["model"] = {"default": raw_model.strip()} if isinstance(raw_model, str) and raw_model.strip() else {}
for k in stale_root_keys:
value = raw_config.pop(k)
- if not model_section.get(k):
- model_section[k] = value
+ if not raw_model.get(k):
+ raw_model[k] = value
atomic_config_write(config_path, raw_config)
check_ok("Migrated stale root-level keys into model section")
f.fixed += 1
@@ -374,8 +359,8 @@ def _drift_max_iterations_ghost(f: Finding, should_fix: bool, config_path) -> No
raw_config = read_user_config_raw(config_path)
agent_cfg = raw_config.get("agent")
cfg_max_turns = agent_cfg.get("max_turns") if isinstance(agent_cfg, dict) else None
- if cfg_max_turns is None: # legacy root-level key counts too
- cfg_max_turns = raw_config.get("max_turns")
+ if cfg_max_turns is None:
+ cfg_max_turns = raw_config.get("max_turns") # legacy root-level key counts too
env_ghost = load_env().get("HERMES_MAX_ITERATIONS")
if cfg_max_turns is None or env_ghost is None or str(cfg_max_turns).strip() == str(env_ghost).strip():
return
diff --git a/hermes_cli/doctor_connectivity.py b/hermes_cli/doctor_connectivity.py
index 6f9f2d2299c..27ad855a0e7 100644
--- a/hermes_cli/doctor_connectivity.py
+++ b/hermes_cli/doctor_connectivity.py
@@ -167,9 +167,7 @@ def _probe_anthropic() -> ProbeResult:
r = httpx.get(url, headers=headers, timeout=10)
except Exception as e:
return _row(name, "warn", f"({e})")
- if r.status_code == 200:
- return _row(name, "ok")
- return _row(name, "fail", "(invalid API key)") if r.status_code == 401 else _row(name, "warn", "(couldn't verify)")
+ return _row(name, *{200: ("ok",), 401: ("fail", "(invalid API key)")}.get(r.status_code, ("warn", "(couldn't verify)")))
def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_health_check) -> ProbeResult:
@@ -187,11 +185,9 @@ def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_heal
r = httpx.get("https://dashscope.aliyuncs.com/compatible-mode/v1/models", headers=headers, timeout=10)
except Exception as e:
return _row(pname, "warn", f"({e})", label=label)
- if r.status_code == 200:
- return _row(pname, "ok", label=label)
if r.status_code == 401:
return _row(pname, "fail", "(invalid API key)", [f"Check {env_vars[0]} in .env"], label=label)
- return _row(pname, "warn", f"(HTTP {r.status_code})", label=label)
+ return _row(pname, "ok", label=label) if r.status_code == 200 else _row(pname, "warn", f"(HTTP {r.status_code})", label=label)
def _apikey_request(key: str, base_env, default_url) -> tuple:
diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.py
index f9463d4f2c3..5d0cf3d04da 100644
--- a/hermes_cli/doctor_platform.py
+++ b/hermes_cli/doctor_platform.py
@@ -149,12 +149,9 @@ def _check_version_consistency(issues: list[str]) -> None:
if pyproject_version is None:
return
if pyproject_version == init_version:
- check_ok("Version files consistent", f"({init_version})")
- else:
- _fail_and_issue("Version mismatch between source files",
- f"(pyproject.toml {pyproject_version} != hermes_cli/__init__.py {init_version})",
- "Re-sync version files (e.g. run 'hermes update', or set "
- "hermes_cli/__init__.py __version__ to match pyproject.toml)", issues)
+ return check_ok("Version files consistent", f"({init_version})")
+ _fail_and_issue("Version mismatch between source files", f"(pyproject.toml {pyproject_version} != hermes_cli/__init__.py {init_version})",
+ "Re-sync version files (e.g. run 'hermes update', or set hermes_cli/__init__.py __version__ to match pyproject.toml)", issues)
def _check_s6_supervision(issues: list[str]) -> None:
@@ -244,14 +241,11 @@ def _check_gateway_service_linger(issues: list[str]) -> None:
return
_section("Gateway Service")
linger_enabled, linger_detail = get_systemd_linger_status()
- if linger_enabled is True:
- check_ok("Systemd linger enabled", "(gateway service survives logout)")
- elif linger_enabled is False:
- check_warn("Systemd linger disabled", "(gateway may stop after logout)")
+ 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)")):
check_info("Run: sudo loginctl enable-linger $USER")
issues.append("Enable linger for the gateway user service: sudo loginctl enable-linger $USER")
- else:
- check_warn("Could not verify systemd linger", f"({linger_detail})")
def check_macos_tcc_grants() -> None:
@@ -354,8 +348,7 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:
all_hits = detect_compromised()
fresh_hits = filter_unacked(all_hits)
if not fresh_hits:
- check_ok("No active security advisories")
- return
+ 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
@@ -444,6 +437,10 @@ def _check_command_installation(should_fix: bool, f: Finding) -> None:
return
_section("Command Installation")
venv_bin = next((c for c in (PROJECT_ROOT / n / "bin" / "hermes" for n in ("venv", ".venv")) if c.exists()), None)
+ 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]')")
+ return f.manual_issues.append(f"Reinstall entry point: cd {PROJECT_ROOT} && source venv/bin/activate && pip install -e '.[all]'")
+ 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):
@@ -451,37 +448,26 @@ def _check_command_installation(should_fix: bool, f: Finding) -> None:
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
- check_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:
- check_ok(f"{display}/hermes → correct target")
- return
+ return check_ok(f"{display}/hermes → correct target")
check_warn(f"{display}/hermes points to wrong target", f"(→ {target}, expected → {expected})")
if not should_fix:
- f.issues.append(f"Broken symlink at {display}/hermes — run 'hermes doctor --fix'")
- return
+ return f.issues.append(f"Broken symlink at {display}/hermes — run 'hermes doctor --fix'")
link.unlink()
- _link_venv(f, link, venv_bin, f"Fixed symlink: {display}/hermes → {venv_bin}")
+ verb = "Fixed"
elif link.exists(): # regular file (wrapper script), not a symlink
- check_ok(f"{display}/hermes exists (non-symlink)")
+ return check_ok(f"{display}/hermes exists (non-symlink)")
else:
check_fail(f"{display}/hermes not found", "(hermes command may not work outside the venv)")
if not should_fix:
- f.issues.append(f"Missing {display}/hermes symlink — run 'hermes doctor --fix'")
- return
+ return f.issues.append(f"Missing {display}/hermes symlink — run 'hermes doctor --fix'")
link_dir.mkdir(parents=True, exist_ok=True)
- _link_venv(f, link, venv_bin, f"Created symlink: {display}/hermes → {venv_bin}")
- if str(link_dir) not in os.environ.get("PATH", "").split(os.pathsep):
- check_warn(f"{display} is not on your PATH", "(add it to your shell config: export PATH=\"$HOME/.local/bin:$PATH\")")
- f.manual_issues.append(f"Add {display} to your PATH")
-
-
-def _link_venv(f: Finding, link: Path, venv_bin: Path, msg: str) -> None:
+ verb = "Created"
link.symlink_to(venv_bin)
- check_ok(msg)
+ check_ok(f"{verb} symlink: {display}/hermes → {venv_bin}")
f.fixed += 1
+ if verb == "Created" and str(link_dir) not in os.environ.get("PATH", "").split(os.pathsep):
+ check_warn(f"{display} is not on your PATH", "(add it to your shell config: export PATH=\"$HOME/.local/bin:$PATH\")")
+ f.manual_issues.append(f"Add {display} to your PATH")
diff --git a/hermes_cli/doctor_report.py b/hermes_cli/doctor_report.py
index efa53500529..410258aaace 100644
--- a/hermes_cli/doctor_report.py
+++ b/hermes_cli/doctor_report.py
@@ -9,9 +9,7 @@ from hermes_cli.colors import Colors, color
def _mark(glyph: str, col: str):
- def check(text: str, detail: str = ""):
- print(f" {color(glyph, col)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
- return check
+ return lambda text, detail="": print(f" {color(glyph, col)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
check_ok, check_warn, check_fail = _mark("✓", Colors.GREEN), _mark("⚠", Colors.YELLOW), _mark("✗", Colors.RED)
@@ -66,12 +64,11 @@ def doctor_check(on_error: str | None = None, detail: str = ""):
@functools.wraps(fn)
def check(should_fix: bool) -> Finding:
f = Finding()
- if on_error is None:
- fn(should_fix, f)
- return f
try:
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))
return f
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index ad2c1c380c2..7bb46b7a15d 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -107,7 +107,7 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
hermes_home = HERMES_HOME
ensure_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
+ memory_on = bool(_memory_enabled or _user_profile_enabled)
# 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",
@@ -115,9 +115,9 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
# SOUL.md persona file
soul_path = hermes_home / "SOUL.md"
if soul_path.exists():
- content = soul_path.read_text(encoding="utf-8").strip()
# Template comments only (no real content)?
- if any(l.strip() and not l.strip().startswith(("<!--", "-->", "#")) for l in content.splitlines()):
+ lines = soul_path.read_text(encoding="utf-8").strip().splitlines()
+ if any(l.strip() and not l.strip().startswith(("<!--", "-->", "#")) for l in lines):
check_ok(f"{_DHH}/SOUL.md exists (persona configured)")
else:
check_info(f"{_DHH}/SOUL.md exists but is empty — edit it to customize personality")
@@ -142,11 +142,10 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
f.fixed += 1
else:
check_ok(f"{_DHH}/memories/ directory exists")
- for enabled, fname in ((_memory_enabled, "MEMORY.md"), (_user_profile_enabled, "USER.md")):
- mem_file = memories_dir / fname
- if enabled and mem_file.exists():
- check_ok(f"{fname} exists ({len(mem_file.read_text(encoding='utf-8').strip())} chars)")
- elif enabled:
+ for fname in [n for on, n in ((_memory_enabled, "MEMORY.md"), (_user_profile_enabled, "USER.md")) if on]:
+ if (memories_dir / fname).exists():
+ check_ok(f"{fname} exists ({len((memories_dir / fname).read_text(encoding='utf-8').strip())} chars)")
+ else:
check_info(f"{fname} not created yet (will be created when the agent first writes a memory)")
@@ -182,8 +181,7 @@ def _repair_state_db(f: Finding, should_fix: bool, state_db_path: Path, kind: st
report = repair_state_db_schema(state_db_path)
if not report.get("repaired"):
check_warn(not_fixed_label, f"({report.get('error')}; backup: {report.get('backup_path')})")
- f.issues.append(failed_issue)
- return
+ return f.issues.append(failed_issue)
if "{count}" in ok_label:
try:
ok_label = ok_label.format(count=_session_count(state_db_path))
@@ -283,10 +281,7 @@ def _gh_authenticated() -> bool:
def _check_skills_hub(should_fix: bool, f: Finding) -> None:
from hermes_cli.doctor import HERMES_HOME, _DHH
hub_dir = HERMES_HOME / "skills" / ".hub"
- if not hub_dir.exists():
- check_warn("Skills Hub directory not initialized", "(run: hermes skills list)")
- else:
- check_ok("Skills Hub directory exists")
+ if check_bool(hub_dir.exists(), "Skills Hub directory exists", ("Skills Hub directory not initialized", "(run: hermes skills list)")):
lock_file = hub_dir / "lock.json"
if lock_file.exists():
try:
diff --git a/hermes_cli/dump.py b/hermes_cli/dump.py
index 28cc68eb4c5..bc4b058bfd9 100644
--- a/hermes_cli/dump.py
+++ b/hermes_cli/dump.py
@@ -224,8 +224,7 @@ def run_dump(args):
show_keys = getattr(args, "show_keys", False)
# Load env from .env file so key checks work
load_hermes_dotenv(hermes_home=get_env_path().parent, project_env=get_project_root() / ".env")
- project_root = get_project_root()
- hermes_home = get_hermes_home()
+ project_root, hermes_home = get_project_root(), get_hermes_home()
try:
config = load_config()
except Exception:
@@ -236,27 +235,21 @@ def run_dump(args):
profile = get_active_profile_name() or "(default)"
except Exception:
profile = "(default)"
- openai_ver = _openai_version()
+ toolsets = config.get("toolsets", ["hermes-cli"])
+ platforms = [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]
lines = [
"--- hermes dump ---",
f"version: {_version_line(project_root)}",
f"os: {platform.system()} {platform.release()} {platform.machine()}",
f"python: {sys.version.split()[0]}",
- f"openai_sdk: {openai_ver}",
+ f"openai_sdk: {_openai_version()}",
f"profile: {profile}",
f"hermes_home: {display_hermes_home()}",
f"model: {model}",
f"provider: {provider}",
f"terminal: {_effective_terminal_backend(config)}",
- "",
- "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 += [
- "",
- "features:",
+ "", "api_keys:", *_api_key_lines(show_keys),
+ "", "features:",
f" toolsets: {', '.join(toolsets) if toolsets else '(default)'}",
f" mcp_servers: {len(config.get('mcp', {}).get('servers', {}))}",
f" memory_provider: {config.get('memory', {}).get('provider', '') or 'built-in'}",
@@ -268,5 +261,4 @@ def run_dump(args):
overrides = _config_overrides(config)
if overrides:
lines += ["", "config_overrides:"] + [f" {key}: {val}" for key, val in overrides.items()]
- lines.append("--- end dump ---")
- print("\n".join(lines))
+ print("\n".join(lines + ["--- end dump ---"]))