doctor_config.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. """Configuration-file checks for hermes doctor: .env, config.yaml validation, drift, deprecations.
  2. Split out of ``hermes_cli/doctor.py``."""
  3. from __future__ import annotations
  4. import os
  5. from hermes_cli.doctor_report import (
  6. Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn, doctor_check,
  7. warn_on_error,
  8. )
  9. def _has_provider_env_config(content: str) -> bool:
  10. """Return True when ~/.hermes/.env contains provider auth/base URL settings."""
  11. from hermes_cli.doctor import _PROVIDER_ENV_HINTS
  12. return any(key in content for key in _PROVIDER_ENV_HINTS)
  13. # Legacy config keys still read for back-compat: warn-only with the modern replacement, never auto-migrated
  14. # (migrations live in config.py). (section, key, replacement)
  15. _DEPRECATED_CONFIG_KEYS: tuple[tuple[str, str, str], ...] = (
  16. ("display", "tool_progress_overrides", "display.platforms"),
  17. ("delegation", "max_async_children", "delegation.max_concurrent_children"),
  18. ("compression", "summary_model", "auxiliary.compression"),
  19. ("compression", "summary_provider", "auxiliary.compression"), ("compression", "summary_base_url", "auxiliary.compression"),
  20. )
  21. # Deprecated env vars (checked in the .env FILE, not process env, so config→env bridges like terminal.cwd →
  22. # TERMINAL_CWD do not false-positive). HERMES_TOOL_PROGRESS is silently ignored since the v12 config floor
  23. # removed its only consumer; HERMES_TOOL_PROGRESS_MODE is still read by the gateway as a back-compat fallback.
  24. _DEPRECATED_ENV_VARS: tuple[tuple[str, str], ...] = (
  25. ("HERMES_TOOL_PROGRESS", "display.tool_progress in config.yaml — ignored/unsupported since config floor v12"),
  26. ("HERMES_TOOL_PROGRESS_MODE", "display.tool_progress in config.yaml"),
  27. ("TERMINAL_CWD", "terminal.cwd in config.yaml"), ("MESSAGING_CWD", "terminal.cwd in config.yaml"),
  28. ("QQ_HOME_CHANNEL", "QQBOT_HOME_CHANNEL"), ("QQ_HOME_CHANNEL_NAME", "QQBOT_HOME_CHANNEL_NAME"),
  29. )
  30. def collect_deprecated_config_keys(raw_config: dict | None) -> list[tuple[str, str]]:
  31. """``(legacy_path, replacement)`` for deprecated keys in the on-disk YAML (empty containers still count)."""
  32. if not isinstance(raw_config, dict):
  33. return []
  34. return [(f"{section}.{key}", replacement) for section, key, replacement in _DEPRECATED_CONFIG_KEYS
  35. if isinstance(raw_config.get(section), dict) and key in raw_config[section]]
  36. def collect_deprecated_env_vars(env_map: dict | None) -> list[tuple[str, str]]:
  37. """``(legacy_env, replacement)`` for deprecated vars in *env_map* (the on-disk ``.env``, not ``os.environ``,
  38. so bridged runtime vars do not false-positive)."""
  39. if not isinstance(env_map, dict):
  40. return []
  41. return [(name, replacement) for name, replacement in _DEPRECATED_ENV_VARS
  42. if env_map.get(name) is not None and str(env_map[name]).strip() != ""]
  43. def collect_relay_plugin_cutover_findings(raw_config: dict | None, env_map: dict | None) -> list[tuple[str, str]]:
  44. """Return actionable findings for the removed Hermes Relay plugin."""
  45. from hermes_cli.relay_plugin_cutover import (LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV,
  46. configured_legacy_relay_env_vars, legacy_relay_plugin_keys)
  47. findings: list[tuple[str, str]] = []
  48. plugins = raw_config.get("plugins") if isinstance(raw_config, dict) else None
  49. if isinstance(plugins, dict):
  50. findings += [(f"plugins.enabled: {key}", "remove it and configure a standard user or system Relay plugins.toml; "
  51. f"use {RELAY_PLUGINS_CONFIG_ENV} for an explicit user-file override")
  52. for key in legacy_relay_plugin_keys(plugins.get("enabled"))]
  53. effective_env = dict(env_map or {})
  54. # Fall through to process env ONLY when no explicit env_map was given: run_doctor passes None and wants
  55. # live-process vars, but an explicit map describes a complete environment (merging os.environ breaks hermeticity).
  56. if env_map is None:
  57. for name in (*LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV):
  58. if name not in effective_env and os.environ.get(name) is not None:
  59. effective_env[name] = os.environ[name]
  60. if not str(effective_env.get(RELAY_PLUGINS_CONFIG_ENV, "")).strip():
  61. findings += [(name, f"run `hermes migrate relay` to generate relay-plugins.toml and set {RELAY_PLUGINS_CONFIG_ENV}; "
  62. "this legacy variable is now ignored and does not configure an exporter")
  63. for name in configured_legacy_relay_env_vars(effective_env)]
  64. return findings
  65. def report_deprecated_config_and_env(raw_config: dict | None = None, env_map: dict | None = None) -> list[tuple[str, str]]:
  66. """Emit non-failing doctor warnings for deprecated config keys and env vars; returns the findings reported.
  67. Does not mutate config/env and does not append to the blocking ``issues`` list."""
  68. deprecated = collect_deprecated_config_keys(raw_config) + collect_deprecated_env_vars(env_map)
  69. relay_cutover = collect_relay_plugin_cutover_findings(raw_config, env_map)
  70. findings = deprecated + relay_cutover
  71. if not findings:
  72. check_ok("No deprecated config keys or env vars")
  73. return findings
  74. for legacy, replacement in deprecated:
  75. check_warn(f"Deprecated: {legacy}", f"(use {replacement} instead)")
  76. check_info(f"Replace {legacy} → {replacement} (warn-only; not auto-migrated here)")
  77. for legacy, replacement in relay_cutover:
  78. check_warn(f"Breaking Relay migration: {legacy}", f"({replacement})")
  79. check_info(f"Migrate {legacy}: {replacement}")
  80. return findings
  81. @doctor_check("Relay plugin check failed: {e}")
  82. def _check_relay_plugins(should_fix: bool, f: Finding) -> None:
  83. """Name the plugins.toml files Relay applies to Hermes, including ones outside the Hermes home."""
  84. from agent.relay_runtime import resolve_plugin_sources
  85. try:
  86. sources = resolve_plugin_sources()
  87. except ModuleNotFoundError as exc:
  88. if exc.name != "nemo_relay":
  89. raise
  90. check_ok("NeMo Relay is not available on this platform")
  91. return
  92. except Exception as exc:
  93. check_warn("Relay plugin configuration could not be read", "(Hermes runs without Relay plugins)")
  94. _relay_info_lines(cause for cause in (exc, exc.__cause__) if cause is not None)
  95. f.manual_issues.append("Fix the Relay plugin configuration shown under NeMo Relay Plugins.")
  96. return
  97. if not sources.config_paths:
  98. check_ok("No Relay plugin files found")
  99. return
  100. if sources.errors:
  101. check_warn("Relay will reject this plugin configuration", "(Hermes runs without Relay plugins)")
  102. f.manual_issues.append("Fix the Relay plugin configuration shown under NeMo Relay Plugins.")
  103. else:
  104. # Validation cannot load dynamic plugins, so Relay reports what it cannot confirm as a warning.
  105. report = check_warn if sources.warnings else check_ok
  106. if sources.enabled:
  107. report("Relay plugins enabled", "(applies to every profile a Hermes process hosts)")
  108. else:
  109. report("Relay plugin files found, nothing enabled")
  110. _relay_info_lines((*sources.config_paths, *sources.errors, *sources.warnings))
  111. def _relay_info_lines(lines) -> None:
  112. """Print Relay paths and messages as doctor detail rows, keeping multi-line parser errors indented."""
  113. for line in lines:
  114. check_info("\n ".join(part for part in str(line).strip().splitlines() if part.strip()))
  115. def managed_scope_check() -> None:
  116. """Report the active managed scope (resolved dir + pinned key counts); silent when none. A HERMES_MANAGED_DIR
  117. override is surfaced too — a redirected scope is the documented foot-gun (docs/design/managed-scope.md §7)."""
  118. managed_dir = None
  119. with warn_on_error(""): # diagnostics must never crash
  120. from hermes_cli import managed_scope
  121. managed_dir = managed_scope.get_managed_dir()
  122. if managed_dir is None:
  123. return
  124. n_cfg, n_env = len(managed_scope.managed_config_keys()), len(managed_scope.load_managed_env())
  125. check_ok(f"Managed scope active: {n_cfg} config key(s), {n_env} env key(s) pinned by {managed_dir}")
  126. if os.environ.get("HERMES_MANAGED_DIR", "").strip():
  127. check_info(f"managed dir set via HERMES_MANAGED_DIR={managed_dir}")
  128. @doctor_check("MCP security check failed: {e}")
  129. def _check_mcp_security(should_fix: bool, f: Finding) -> None:
  130. """Flag mcp_servers entries with suspicious stdio commands."""
  131. from hermes_cli.config import load_config
  132. from hermes_cli.mcp_security import validate_mcp_server_entry
  133. servers = load_config().get("mcp_servers") or {}
  134. suspicious = 0
  135. for name, entry in sorted(servers.items()) if isinstance(servers, dict) else ():
  136. issues_found = validate_mcp_server_entry(name, entry) if isinstance(entry, dict) else None
  137. if not issues_found:
  138. continue
  139. suspicious += 1
  140. check_warn(f"MCP server '{name}' has suspicious stdio command", "; ".join(issues_found))
  141. f.manual_issues.append(f"Review/remove mcp_servers.{name} in config.yaml; rotate any credentials that may have been exposed.")
  142. if suspicious == 0:
  143. check_ok("No suspicious MCP stdio commands")
  144. @doctor_check()
  145. def _check_env_file(should_fix: bool, f: Finding) -> None:
  146. """Managed scope plus ~/.hermes/.env presence and provider credentials."""
  147. from hermes_cli.doctor import HERMES_HOME, PROJECT_ROOT, _DHH
  148. managed_scope_check()
  149. env_path = HERMES_HOME / '.env'
  150. if env_path.exists():
  151. check_ok(f"{_DHH}/.env file exists")
  152. # UTF-8 first; latin-1 fallback for Windows Notepad/cp1252 files (matches env_loader._load_dotenv_with_fallback).
  153. try:
  154. content = env_path.read_text(encoding="utf-8-sig")
  155. except UnicodeDecodeError:
  156. content = env_path.read_text(encoding="latin-1")
  157. if not check_bool(_has_provider_env_config(content), "API key or custom endpoint configured", f"No API key found in {_DHH}/.env"):
  158. f.issues.append("Run 'hermes setup' to configure API keys")
  159. elif (PROJECT_ROOT / '.env').exists(): # project root as fallback
  160. check_ok(".env file exists (in project directory)")
  161. else:
  162. check_fail(f"{_DHH}/.env file missing")
  163. if should_fix:
  164. env_path.parent.mkdir(parents=True, exist_ok=True)
  165. env_path.touch()
  166. # .env holds API keys — touch() obeys umask (commonly 0o022, world-readable); tighten explicitly.
  167. with warn_on_error(""):
  168. os.chmod(str(env_path), 0o600)
  169. check_ok(f"Created empty {_DHH}/.env")
  170. check_info("Run 'hermes setup' to configure API keys")
  171. f.fixed += 1
  172. else:
  173. check_info("Run 'hermes setup' to create one")
  174. f.issues.append("Run 'hermes setup' to create .env")
  175. def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:
  176. """Return (known ids, custom providers, resolve_auth, normalize, resolve_full); any import failure leaves
  177. the matching resolver as None so validation degrades to "unavailable" rather than crashing doctor."""
  178. known: set = set()
  179. resolve_auth = normalize = resolve_full = aliases = None
  180. custom_providers: list = []
  181. with warn_on_error(""):
  182. from hermes_cli.auth import PROVIDER_REGISTRY, resolve_provider as resolve_auth
  183. known = set(PROVIDER_REGISTRY.keys()) | {"openrouter", "custom", "auto", "moa"}
  184. with warn_on_error(""):
  185. from hermes_cli.config import get_compatible_custom_providers
  186. from hermes_cli.providers import custom_provider_aliases as aliases, normalize_provider as normalize, resolve_provider_full as resolve_full
  187. with warn_on_error(""):
  188. custom_providers = get_compatible_custom_providers(cfg)
  189. user_providers = cfg.get("providers")
  190. if isinstance(user_providers, dict):
  191. from hermes_cli.config import is_provider_enabled
  192. known.update(str(name).strip().lower() for name, prov_cfg in user_providers.items()
  193. if str(name).strip() and is_provider_enabled(prov_cfg))
  194. for entry in custom_providers if aliases is not None else ():
  195. name = str(entry.get("name") or "").strip() if isinstance(entry, dict) else ""
  196. if name:
  197. known.update(aliases(name, str(entry.get("provider_key") or "").strip()))
  198. return known, custom_providers, resolve_auth, normalize, resolve_full
  199. # Vendor/model slugs are valid on aggregators and any custom provider; Fireworks' native IDs are slash-form
  200. # (accounts/fireworks/models/...) and DeepInfra's catalog is exclusively vendor/model.
  201. _VENDOR_SLUG_PROVIDERS = {
  202. "openrouter", "auto", "ai-gateway", "kilocode", "opencode-zen", "huggingface", "lmstudio", "nous", "nvidia",
  203. "fireworks", "deepinfra",
  204. }
  205. def _provider_has_credentials(runtime_provider: str) -> bool:
  206. """Only API-key providers in PROVIDER_REGISTRY are checked — OAuth/SDK/custom providers have their own
  207. checks elsewhere, and get_auth_status() returns a bare {logged_in: False} for anything it doesn't dispatch."""
  208. if runtime_provider == "openrouter":
  209. from hermes_cli.config import get_env_value
  210. return any(str(get_env_value(k) or "").strip() for k in ("OPENROUTER_API_KEY", "OPENAI_API_KEY"))
  211. from hermes_cli.auth import PROVIDER_REGISTRY, get_auth_status
  212. pconfig = PROVIDER_REGISTRY.get(runtime_provider)
  213. if pconfig and getattr(pconfig, "auth_type", "") == "api_key":
  214. status = get_auth_status(runtime_provider) or {}
  215. return bool(status.get("configured") or status.get("logged_in") or status.get("api_key"))
  216. return True
  217. def _validate_model_config(config_path, issues: list) -> None:
  218. """Validate model.provider / model.default against the provider registry (raw file)."""
  219. # Detect stale root-level model keys (known bug source — PR #4329)
  220. from hermes_cli.config import read_user_config_raw
  221. cfg = read_user_config_raw(config_path)
  222. model_section = cfg.get("model") or {}
  223. provider_raw = (model_section.get("provider") or "").strip()
  224. provider = provider_raw.lower()
  225. default_model = (model_section.get("default") or model_section.get("model") or "").strip()
  226. known_providers, custom_providers, resolve_auth, normalize, resolve_full = _known_provider_ids(cfg)
  227. valid_provider_ids = set(known_providers)
  228. accept = {provider} if provider else set()
  229. for known_provider in known_providers if normalize is not None else ():
  230. try:
  231. valid_provider_ids.add(normalize(known_provider))
  232. except Exception:
  233. continue
  234. runtime_provider = catalog_provider = provider
  235. if provider and provider not in {"auto", "custom"}:
  236. if resolve_auth is not None:
  237. try:
  238. runtime_provider = resolve_auth(provider)
  239. accept.add(runtime_provider)
  240. except Exception:
  241. runtime_provider = provider
  242. if resolve_full is not None:
  243. provider_def = resolve_full(provider, cfg.get("providers"), custom_providers)
  244. catalog_provider = provider_def.id if provider_def is not None else None
  245. accept.update({catalog_provider} - {None})
  246. if provider and provider != "auto" and (catalog_provider is None or (known_providers and not (accept & valid_provider_ids))):
  247. known_list = ", ".join(sorted(known_providers)) if known_providers else "(unavailable)"
  248. _fail_and_issue(f"model.provider '{provider_raw}' is not a recognised provider", f"(known: {known_list})",
  249. f"model.provider '{provider_raw}' is unknown. Valid providers: {known_list}. "
  250. f"Fix: run 'hermes config set model.provider <valid_provider>'", issues)
  251. policy_id = str(runtime_provider or catalog_provider or "").strip().lower()
  252. accepts_vendor_slug = policy_id in _VENDOR_SLUG_PROVIDERS or policy_id == "custom" or policy_id.startswith("custom:")
  253. # openai-api pointed at a non-OpenAI endpoint (local router, proxy) is an aggregator in all but name:
  254. # the router owns the model namespace, so vendor/model slugs are the correct IDs there.
  255. model_base_url = str(model_section.get("base_url") or "").strip()
  256. if policy_id == "openai-api" and model_base_url:
  257. from utils import base_url_host_matches
  258. accepts_vendor_slug = accepts_vendor_slug or not base_url_host_matches(model_base_url, "api.openai.com")
  259. if default_model and "/" in default_model and policy_id and not accepts_vendor_slug:
  260. check_warn(f"model.default '{default_model}' uses a vendor/model slug but provider is '{provider_raw}'",
  261. "(vendor-prefixed slugs belong to aggregators like openrouter)")
  262. issues.append(f"model.default '{default_model}' is vendor-prefixed but model.provider is '{provider_raw}'. "
  263. "Either set model.provider to 'openrouter', or drop the vendor prefix.")
  264. if runtime_provider and runtime_provider not in ("auto", "custom"):
  265. from hermes_cli.doctor import _DHH
  266. with warn_on_error(""):
  267. if not _provider_has_credentials(runtime_provider):
  268. _fail_and_issue(f"model.provider '{runtime_provider}' is set but no API key is configured",
  269. f"(add it to {_DHH}/.env or run 'hermes setup')",
  270. f"No credentials found for provider '{runtime_provider}'. Run 'hermes setup' or set the provider's "
  271. f"API key in {_DHH}/.env, or switch providers with 'hermes config set model.provider <name>'", issues)
  272. def _validate_auxiliary_config(config_path, issues: list) -> None:
  273. """Resolve every routed ``auxiliary.<task>`` block through the real entry point the tasks use and report
  274. the ones that fail — an unresolvable block otherwise silently runs the task on the main model (#116055)."""
  275. from hermes_cli.config import read_user_config_raw
  276. from hermes_cli.left_core_migration import provider_install_hint
  277. from hermes_cli.runtime_provider import resolve_runtime_provider
  278. from utils import base_url_hostname
  279. aux = read_user_config_raw(config_path).get("auxiliary")
  280. routed = {name: block for name, block in (aux.items() if isinstance(aux, dict) else ())
  281. if isinstance(block, dict) and str(block.get("provider") or "").strip().lower() not in ("", "auto")}
  282. ok = []
  283. for task, block in sorted(routed.items()):
  284. provider, model, base_url, api_key = (str(block.get(k) or "").strip() or None for k in ("provider", "model", "base_url", "api_key"))
  285. try:
  286. runtime = resolve_runtime_provider(requested=provider, target_model=model, explicit_api_key=api_key, explicit_base_url=base_url)
  287. except Exception as exc:
  288. reason, moved = str(exc).splitlines()[0], provider_install_hint(provider or "")
  289. _fail_and_issue(f"auxiliary.{task}.provider '{provider}' does not resolve", f"({reason})",
  290. f"auxiliary.{task}.provider '{provider}' cannot be resolved ({reason}); the task silently runs "
  291. f"on the main model. " + (moved or f"Fix the provider name/credentials in auxiliary.{task}."),
  292. issues)
  293. continue
  294. if not runtime.get("api_key") and not runtime.get("command"):
  295. check_warn(f"auxiliary.{task}.provider '{provider}' resolved without credentials", f"({runtime.get('provider')} @ {runtime.get('base_url')})")
  296. continue
  297. ok.append(f"{task}→{runtime.get('provider')}@{base_url_hostname(str(runtime.get('base_url') or '')) or '?'}")
  298. if ok:
  299. check_ok("auxiliary task routing resolves: " + ", ".join(ok))
  300. @doctor_check()
  301. def _check_config_file(should_fix: bool, f: Finding) -> None:
  302. """config.yaml presence (project cli-config.yaml as fallback); model/provider validation."""
  303. from hermes_cli.config_backend import config_exists, get_config_backend
  304. from hermes_cli.doctor import HERMES_HOME, PROJECT_ROOT, _DHH
  305. config_path = HERMES_HOME / 'config.yaml'
  306. backend = get_config_backend()
  307. if not backend.supports_file_tooling() and not _check_config_backend(backend, HERMES_HOME, f):
  308. return
  309. if config_exists(config_path):
  310. if backend.supports_file_tooling():
  311. check_ok(f"{_DHH}/config.yaml exists")
  312. with warn_on_error("Could not validate model/provider config"):
  313. _validate_model_config(config_path, f.issues)
  314. with warn_on_error("Could not validate auxiliary task routing"):
  315. _validate_auxiliary_config(config_path, f.issues)
  316. elif (PROJECT_ROOT / 'cli-config.yaml').exists():
  317. check_ok("cli-config.yaml exists (in project directory)")
  318. elif should_fix:
  319. from hermes_cli.config import seed_config_file
  320. from_template = seed_config_file(config_path, PROJECT_ROOT / 'cli-config.yaml.example')
  321. check_ok(f"Created {_DHH}/config.yaml from {'cli-config.yaml.example' if from_template else 'defaults'}")
  322. f.fixed += 1
  323. else:
  324. check_warn("config.yaml not found", "(using defaults)")
  325. def _check_config_backend(backend, home, f: Finding) -> bool:
  326. """A backend without a config file (§4.7): report where config comes from instead of the file
  327. checks, plus the backend's own warnings (remote mode flags an ignored managed config.yaml, D18)."""
  328. try:
  329. backend.read_user_doc(home)
  330. check_ok(f"Config backend: {backend.describe(home)}")
  331. except SystemExit as exc: # ConfigBackendUnavailable: the plane cannot serve this profile
  332. check_fail(f"Config backend {backend.name!r} unavailable", str(exc.code or ""))
  333. f.issues.append(f"Config backend {backend.name!r} cannot serve config for {home}")
  334. return False
  335. for warning, hint, issue in backend.doctor_warnings(home):
  336. check_warn(warning, hint)
  337. f.issues.append(issue)
  338. return True
  339. def _drift_config_version(f: Finding, should_fix: bool, config_path) -> None:
  340. from hermes_cli.config import check_config_version, migrate_config
  341. current_ver, latest_ver = check_config_version()
  342. outdated = (f"Config version outdated (v{current_ver} → v{latest_ver})", "(new settings available)")
  343. if check_bool(current_ver >= latest_ver, f"Config version up to date (v{current_ver})", outdated):
  344. return
  345. if not should_fix:
  346. f.issues.append("Run 'hermes doctor --fix' or 'hermes setup' to migrate config")
  347. return
  348. try:
  349. migrate_config(interactive=False, quiet=False)
  350. check_ok("Config migrated to latest version")
  351. f.fixed += 1
  352. except Exception as mig_err:
  353. check_warn(f"Auto-migration failed: {mig_err}")
  354. f.issues.append("Run 'hermes setup' to migrate config")
  355. def _drift_stale_root_keys(f: Finding, should_fix: bool, config_path) -> None:
  356. """Root-level ``provider``/``base_url`` belong under ``model:`` (raw-file diagnostic)."""
  357. from hermes_cli.config import atomic_config_replace, read_user_config_raw
  358. raw_config = read_user_config_raw(config_path)
  359. stale_root_keys = [k for k in ("provider", "base_url") if k in raw_config and isinstance(raw_config[k], str)]
  360. if not stale_root_keys:
  361. return
  362. check_warn(f"Stale root-level config keys: {', '.join(stale_root_keys)}", "(should be under 'model:' section)")
  363. if not should_fix:
  364. f.issues.append("Stale root-level provider/base_url in config.yaml — run 'hermes doctor --fix'")
  365. return
  366. # Coerce scalar/None ``model:`` into a dict before mutation (setdefault would hand back a scalar).
  367. raw_model = raw_config.get("model")
  368. if not isinstance(raw_model, dict):
  369. raw_model = raw_config["model"] = {"default": raw_model.strip()} if isinstance(raw_model, str) and raw_model.strip() else {}
  370. for k in stale_root_keys:
  371. value = raw_config.pop(k)
  372. if not raw_model.get(k):
  373. raw_model[k] = value
  374. atomic_config_replace(config_path, raw_config)
  375. check_ok("Migrated stale root-level keys into model section")
  376. f.fixed += 1
  377. def _drift_max_iterations_ghost(f: Finding, should_fix: bool, config_path) -> None:
  378. """A stale HERMES_MAX_ITERATIONS in .env shadows agent.max_turns in config.yaml.
  379. The setup wizard used to dual-write the budget. The gateway bridge derives HERMES_MAX_ITERATIONS from
  380. agent.max_turns, but if it bails on an earlier config-parse error the .env value silently wins. Read the
  381. .env FILE (load_env), not get_env_value/os.environ, which the bridge may have overridden already.
  382. """
  383. from hermes_cli.doctor import _DHH
  384. # Detect stale HERMES_MAX_ITERATIONS ghost in .env shadowing agent.max_turns in config.yaml (issue
  385. # #17534). The setup wizard used to dual-write the iteration budget to both stores; users who later edit
  386. # only config.yaml are left with a .env ghost. The gateway bridge normally derives HERMES_MAX_ITERATIONS
  387. # from agent.max_turns at startup, but if that bridge bails (any earlier config-parse error), the stale
  388. # .env value silently wins and the agent runs at the wrong budget — e.g. config says 400 but the
  389. # activity line reads N/90.
  390. from hermes_cli.config import load_env, read_user_config_raw, remove_env_value
  391. raw_config = read_user_config_raw(config_path)
  392. agent_cfg = raw_config.get("agent")
  393. cfg_max_turns = agent_cfg.get("max_turns") if isinstance(agent_cfg, dict) else None
  394. if cfg_max_turns is None:
  395. cfg_max_turns = raw_config.get("max_turns") # legacy root-level key counts too
  396. env_ghost = load_env().get("HERMES_MAX_ITERATIONS")
  397. if cfg_max_turns is None or env_ghost is None or str(cfg_max_turns).strip() == str(env_ghost).strip():
  398. return
  399. check_warn(f"HERMES_MAX_ITERATIONS={env_ghost} in .env shadows agent.max_turns={cfg_max_turns} in config.yaml",
  400. "(stale ghost from an earlier `hermes setup` run)")
  401. if not should_fix:
  402. f.issues.append("Stale HERMES_MAX_ITERATIONS in .env shadows config.yaml — run 'hermes doctor --fix'")
  403. elif remove_env_value("HERMES_MAX_ITERATIONS"):
  404. check_ok(f"Removed stale HERMES_MAX_ITERATIONS from .env (config.yaml agent.max_turns={cfg_max_turns} is now authoritative)")
  405. f.fixed += 1
  406. else:
  407. check_warn("Could not remove HERMES_MAX_ITERATIONS from .env")
  408. f.manual_issues.append(f"Manually delete the HERMES_MAX_ITERATIONS line from {_DHH}/.env — config.yaml agent.max_turns is authoritative.")
  409. def _drift_deprecations(f: Finding, should_fix: bool, config_path) -> None:
  410. """Warn-only deprecation sweep over the raw file + on-disk .env (process env would false-positive)."""
  411. from hermes_cli.config import load_env, read_user_config_raw
  412. raw = read_user_config_raw(config_path) if config_path is not None else {}
  413. env = {}
  414. with warn_on_error(""):
  415. env = load_env()
  416. report_deprecated_config_and_env(raw, env)
  417. def _drift_structure(f: Finding, should_fix: bool, config_path) -> None:
  418. """Structural validation (malformed custom_providers, etc.)."""
  419. from hermes_cli.config import validate_config_structure
  420. config_issues = validate_config_structure()
  421. if not config_issues:
  422. return
  423. _section("Config Structure")
  424. for ci in config_issues:
  425. (check_fail if ci.severity == "error" else check_warn)(ci.message)
  426. for hint_line in ci.hint.splitlines():
  427. check_info(hint_line)
  428. f.issues.append(ci.message)
  429. def _endpoint_url(entry: dict) -> str:
  430. """Comparable endpoint URL of a legacy list entry (``base_url``/``url``) or a ``providers:`` entry (``api``)."""
  431. url = entry.get("api") or entry.get("base_url") or entry.get("url") or ""
  432. return str(url).strip().rstrip("/").lower()
  433. def _drift_legacy_custom_providers(f: Finding, should_fix: bool, config_path) -> None:
  434. """Legacy ``custom_providers`` list entries with no ``providers:`` twin (raw-file diagnostic).
  435. The v11→v12 migration (config_migrations._migrate_to_12) moves the list into ``providers:`` ONCE, at
  436. the version bump; an entry hand-written afterwards lives on in the retired list store (dual-read by the
  437. picker and the Custom Endpoints page) instead of the ``providers:`` map every other surface edits.
  438. """
  439. from hermes_cli.config import read_user_config_raw
  440. raw_config = read_user_config_raw(config_path)
  441. legacy = raw_config.get("custom_providers")
  442. if not isinstance(legacy, list):
  443. return
  444. providers = raw_config.get("providers")
  445. twins = {_endpoint_url(e) for e in (providers.values() if isinstance(providers, dict) else ()) if isinstance(e, dict)}
  446. for entry in legacy:
  447. if not isinstance(entry, dict) or not _endpoint_url(entry) or _endpoint_url(entry) in twins:
  448. continue
  449. label = str(entry.get("name") or "").strip() or _endpoint_url(entry)
  450. check_warn(f"Legacy custom_providers entry '{label}' has no providers: twin",
  451. "(still read from the retired list store; every other surface edits providers:)")
  452. f.manual_issues.append(
  453. f"Move custom_providers entry '{label}' into config.yaml providers: as `providers.<key>.api: "
  454. f"{_endpoint_url(entry)}` and delete it from the list — the v12 list migration ran once and does not re-fire")
  455. _CONFIG_DRIFT_STEPS = (
  456. _drift_config_version, _drift_stale_root_keys, _drift_max_iterations_ghost, _drift_deprecations, _drift_structure,
  457. _drift_legacy_custom_providers,
  458. )
  459. def _check_channel_record_hygiene() -> None:
  460. """Stale per-install channel records (``update.installs.<sha16>``).
  461. Same report-don't-delete posture as the state sweep. Three shapes
  462. (hermes_cli.update_channel.stale_channel_records): a record whose path
  463. holds a DIFFERENT install now (``replaced``), a record whose path is
  464. gone (``missing``), and a record no live install-state folder claims
  465. (``unclaimed``). Keep-on-doubt: doctor names the config key, the user
  466. removes it.
  467. """
  468. try:
  469. from hermes_cli.config import load_config
  470. from hermes_cli.update_channel import stale_channel_records
  471. stale = stale_channel_records(load_config() or {})
  472. except Exception as exc:
  473. check_warn("Channel-record hygiene unreadable", f"({exc})")
  474. return
  475. if not stale:
  476. return
  477. for sha16, record, reason in stale:
  478. recorded = record.get("path") or "<no path>"
  479. if reason == "replaced":
  480. detail = f"(the install at {recorded} is a different install now — stale channel entry)"
  481. elif reason == "missing":
  482. detail = f"(nothing at {recorded} — safe to remove update.installs.{sha16})"
  483. else: # unclaimed
  484. detail = f"(no live install claims {sha16} — safe to remove update.installs.{sha16})"
  485. check_warn(f"Stale channel record: {sha16}", detail)
  486. @doctor_check()
  487. def _check_config_drift(should_fix: bool, f: Finding) -> None:
  488. """Config version, stale root keys, HERMES_MAX_ITERATIONS ghost, deprecations, structure.
  489. Each step is independent and best-effort: a failure in one never hides the next.
  490. """
  491. from hermes_cli.config_backend import config_exists
  492. from hermes_cli.doctor import HERMES_HOME
  493. config_path = HERMES_HOME / 'config.yaml'
  494. if not config_exists(config_path):
  495. config_path = None
  496. for step in _CONFIG_DRIFT_STEPS if config_path else (_drift_deprecations,):
  497. with warn_on_error(""):
  498. step(f, should_fix, config_path)
  499. # Stale per-install update-channel records (update.installs.<sha16>):
  500. # report-don't-delete, same posture as the state sweep.
  501. _check_channel_record_hygiene()
  502. @doctor_check("xAI retirement check skipped", "({e})")
  503. def _check_xai_retirement(should_fix: bool, f: Finding) -> None:
  504. from hermes_cli.config import load_config
  505. from hermes_cli.xai_retirement import MIGRATION_GUIDE_URL, find_retired_xai_refs, format_issue
  506. retired_refs = find_retired_xai_refs(load_config())
  507. if not retired_refs:
  508. check_ok("No retired xAI models in config")
  509. return
  510. for ref in retired_refs:
  511. check_warn(format_issue(ref))
  512. check_info(f"Migration guide: {MIGRATION_GUIDE_URL}")
  513. f.manual_issues.append(f"Update {len(retired_refs)} retired xAI model reference(s) in config.yaml — see {MIGRATION_GUIDE_URL}")
  514. @doctor_check("Session reset check skipped", "({e})")
  515. def _check_retired_session_reset(should_fix: bool, f: Finding) -> None:
  516. from hermes_cli.config_effective import load_user_config_effective
  517. from hermes_cli.session_reset_retirement import format_notice, reset_plugin_enabled, retired_reset_policy
  518. found = retired_reset_policy(load_user_config_effective())
  519. if found is None:
  520. check_ok("No idle/daily session_reset policy configured")
  521. elif reset_plugin_enabled():
  522. check_ok(f"{found[0]}.mode: {found[1]} is applied by the session reset plugin")
  523. else:
  524. check_warn(format_notice(*found))
  525. f.manual_issues.append(format_notice(*found))