The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): backup/banner — fold section headers, merge adjacent prints, flatten _restore_member closure
Teknium76683a8bded4
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 586f1c06b74..b6001fec235 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -28,9 +28,7 @@ from hermes_cli.sizefmt import format_bytes as _format_sizelogger = logging.getLogger(__name__)-# ----------------------------------------------------------------------------# Exclusion rules-# ---------------------------------------------------------------------------+# --- Exclusion rules ---# Where ``hermes backup --quick`` / ``/snapshot`` / the pre-update safety net write state# snapshots (see ``create_quick_snapshot``); defined here because the exclusion set needs it.@@ -59,16 +57,9 @@ _EXCLUDED_DIRS = {# Login Data — a credential store that must NOT enter an archive. Regenerated on next launch."browser-profile",# Python dependency trees (plugin / MCP-server venvs) — regenerated by reinstalling.- ".venv",- "venv",- "site-packages",+ ".venv", "venv", "site-packages",# Tool / build caches — all regeneratable.- ".cache",- ".tox",- ".nox",- ".pytest_cache",- ".mypy_cache",- ".ruff_cache",+ ".cache", ".tox", ".nox", ".pytest_cache", ".mypy_cache", ".ruff_cache",}# Hermes-managed runtime downloads (GGUF models, llama.cpp runtimes, managed Node): all@@ -140,7 +131,6 @@ def _backup_operation_lock(hermes_home: Path, timeout_seconds: float = 0.25):try:if os.name == "nt":import msvcrt-if lock_path.stat().st_size == 0:handle.write(b" ")handle.flush()@@ -152,7 +142,6 @@ def _backup_operation_lock(hermes_home: Path, timeout_seconds: float = 0.25):lock_flag, unlock_flag = msvcrt.LK_NBLCK, msvcrt.LK_UNLCKelse:import fcntl-def _lock_op(flag: int) -> None:fcntl.flock(handle.fileno(), flag)@@ -206,7 +195,6 @@ def _collect_memory_provider_external_paths() -> List[Path]:"""try:from plugins.memory import _get_active_memory_provider, load_memory_provider-active = _get_active_memory_provider()provider = load_memory_provider(active) if active else Noneexcept Exception:@@ -238,9 +226,9 @@ def _iter_external_files(base: Path) -> List[Path]:"""Regular files under *base* (a file or a directory), skipping symlinks, caches, and pyc."""if base.is_file() and not base.is_symlink():return [base]- files: List[Path] = []if not base.is_dir():- return files+ return []+ files: List[Path] = []for dirpath, dirnames, filenames in os.walk(base, followlinks=False):dp = Path(dirpath)dirnames[:] = [d for d in dirnames if d not in _EXCLUDED_DIRS]@@ -299,9 +287,7 @@ def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optionalyield fpath, rel-# ----------------------------------------------------------------------------# SQLite safe copy-# ---------------------------------------------------------------------------+# --- SQLite safe copy ---def _close_quietly(conn: Optional[sqlite3.Connection]) -> None:if conn is not None:@@ -372,7 +358,6 @@ def is_zeroed_sqlite_file(path: Path, *, probe_bytes: int = 100, force: bool = Fexcept OSError:return Falsefrom hermes_cli.sqlite_safe_read import has_live_connection, read_header_bytes_preopen-if not force and has_live_connection(path):return False@@ -381,9 +366,7 @@ def is_zeroed_sqlite_file(path: Path, *, probe_bytes: int = 100, force: bool = Freturn head is not None and not head.startswith(b"SQLite format 3") and not any(head)-# ----------------------------------------------------------------------------# SQLite integrity verification-# ---------------------------------------------------------------------------+# --- SQLite integrity verification ---_SQLITE_HEADER = b"SQLite format 3\0"@@ -423,7 +406,6 @@ def verify_sqlite_integrity(# process's POSIX locks — see hermes_cli.sqlite_safe_read); verification targets# snapshots and backup artifacts, which are offline by construction.from hermes_cli.sqlite_safe_read import read_header_bytes_preopen-head = read_header_bytes_preopen(path, length=len(_SQLITE_HEADER))if head is None:return _done("cannot read header", size=size)@@ -534,7 +516,6 @@ def _unlink_move_restore_db(src: Path, dst: Path) -> bool:connection to *dst* is live and holds the connection-lifecycle lock across the whole swap."""from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access-try:holders = _foreign_db_holder_pids(dst)if holders:@@ -622,13 +603,7 @@ def _print_capped(header: str, lines: List[str], indent: str) -> None:print(f"{indent}... and {len(lines) - 10} more")-def _print_skipped_warnings(errors: List[str]) -> None:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")---# ----------------------------------------------------------------------------# Backup-# ---------------------------------------------------------------------------+# --- Backup ---def _resolve_backup_output_path(output: Optional[str]) -> Path:"""Turn ``--output`` (file, directory, or None) into a ``.zip`` path whose parent exists.@@ -769,14 +744,12 @@ def _run_backup_locked(args, hermes_root: Path) -> None:print("\n".join(f" {d}/" for d in sorted(skipped_dirs)))if errors:- _print_skipped_warnings(errors)+ _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")else:print(f"\nRestore with: hermes import {out_path.name}")-# ----------------------------------------------------------------------------# Import-# ---------------------------------------------------------------------------+# --- Import ---def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:"""Check that a zip looks like a Hermes backup."""@@ -869,10 +842,8 @@ def _confirm_import_overwrite(hermes_root: Path) -> bool:"""Prompt before importing over an existing installation; True when import may proceed."""if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):return True- print()- print("Warning: Target directory already has Hermes configuration.")- print("Importing will overwrite existing files with backup contents.")- print()+ print("\nWarning: Target directory already has Hermes configuration.\n"+ "Importing will overwrite existing files with backup contents.\n")try:answer = input("Continue? [y/N] ").strip().lower()except (EOFError, KeyboardInterrupt):@@ -897,26 +868,6 @@ def _import_members(# create newly restored files as 0600.new_file_mode = _default_new_file_mode()- def _restore_member(- member: str, rel: str, target: Path, root: Path, tighten: bool, *, strict_chmod: bool) -> bool:- """Publish one member under *root*; False when blocked or failed (recorded in errors)."""- if not _is_within(target, root):- errors.append(f"{rel}: path traversal blocked")- return False- try:- target.parent.mkdir(parents=True, exist_ok=True)- _extract_member_atomically(zf, member, target, new_file_mode)- if tighten:- try:- os.chmod(target, 0o600)- except OSError:- if strict_chmod:- raise- except (PermissionError, OSError) as exc:- errors.append(f"{rel}: {exc}")- return False- return True-for member in members:# ``_external/`` members restore to their original home-relative location (e.g.# ~/.honcho/config.json), NOT under HERMES_HOME. Provider configs commonly hold@@ -940,9 +891,23 @@ def _import_members(if not rel:continue- if _restore_member(member, member if external else rel, target, root, tighten, strict_chmod=not external):- restored += 1- restored_external += external+ label = member if external else rel+ if not _is_within(target, root):+ errors.append(f"{label}: path traversal blocked")+ else:+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ _extract_member_atomically(zf, member, target, new_file_mode)+ if tighten:+ try:+ os.chmod(target, 0o600)+ except OSError:+ if not external: # external provider configs are tightened best-effort only+ raise+ restored += 1+ restored_external += external+ except (PermissionError, OSError) as exc:+ errors.append(f"{label}: {exc}")if restored % 500 == 0:print(f" {restored}/{file_count} files ...")@@ -1003,7 +968,7 @@ def run_import(args) -> None:f"their original location(s) outside {display_hermes_home()}.")if errors:- _print_skipped_warnings(errors)+ _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")if skipped_runtime:_print_capped(@@ -1015,8 +980,8 @@ def run_import(args) -> None:print()if not (hermes_root / "hermes-agent").is_dir():- print("Note: The hermes-agent codebase was not included in the backup.")- print(" If this is a fresh install, run: hermes update")+ print("Note: The hermes-agent codebase was not included in the backup.\n"+ " If this is a fresh install, run: hermes update")if restored_profiles:print("\nTo re-enable gateway services for profiles:")@@ -1055,14 +1020,14 @@ def _restore_profile_wrappers(hermes_root: Path) -> List[str]:if skipped:print(f" Profile aliases skipped: {', '.join(skipped)}")if not _is_wrapper_dir_in_path():- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.")- print(' Add to your shell config (~/.bashrc or ~/.zshrc):')- print(' export PATH="$HOME/.local/bin:$PATH"')+ print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"+ " Add to your shell config (~/.bashrc or ~/.zshrc):\n"+ ' export PATH="$HOME/.local/bin:$PATH"')except ImportError:# hermes_cli.profiles might not be available (fresh install)if any(profiles_dir.iterdir()):- print("\n Profiles detected but aliases could not be created.")- print(" Run: hermes profile list (after installing hermes)")+ print("\n Profiles detected but aliases could not be created.\n"+ " Run: hermes profile list (after installing hermes)")return [n for n, _ in restored_profiles]@@ -1087,18 +1052,14 @@ def _revive_gateway_after_import(hermes_root: Path) -> None:returntry:from hermes_cli.gateway import ensure_gateway_service, _is_service_running-if not _is_service_running():print()ensure_gateway_service(context="import")except Exception:- print("\nStart the gateway to activate cron jobs and messaging:")- print(" hermes gateway install")+ print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")-# ----------------------------------------------------------------------------# Quick state snapshots (used by /snapshot slash command and hermes backup --quick)-# ---------------------------------------------------------------------------+# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---# Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is# regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR@@ -1254,8 +1215,8 @@ def _create_quick_snapshot_locked(if failed_dbs:# The update path used to log-and-continue with exit 0, so a missing state.db backup# looked like a successful pre-update snapshot (#68474). Surface it on stdout.- print(" ⚠ CRITICAL: could not snapshot DB file(s): " + ", ".join(failed_dbs))- print(f" ⚠ If sessions disappear after update, check {root} and run: hermes snapshot list")+ print(f" ⚠ CRITICAL: could not snapshot DB file(s): {', '.join(failed_dbs)}\n"+ f" ⚠ If sessions disappear after update, check {root} and run: hermes snapshot list")logger.error("Quick snapshot failed to capture DB file(s): %s", ", ".join(failed_dbs))if not manifest:@@ -1450,7 +1411,6 @@ def _sibling_profile_homes(invoking_home: Path) -> list[tuple[str, Path]]:homes: list[tuple[str, Path]] = []try:from hermes_cli.profiles import _get_default_hermes_home, _get_profiles_root, _PROFILE_ID_RE-invoking = invoking_home.resolve()default_home = _get_default_hermes_home()if default_home.is_dir() and default_home.resolve() != invoking:@@ -1506,7 +1466,6 @@ def _read_raw_yaml_dict(path: Path) -> Optional[Dict[str, Any]]:return Nonetry:import yaml-with open(path, "r", encoding="utf-8") as f:data = yaml.safe_load(f)except Exception:@@ -1573,7 +1532,6 @@ def restore_config_model_settings_if_rewritten(try:from utils import atomic_yaml_write-atomic_yaml_write(live_path, live)except (OSError, PermissionError) as exc:logger.error("config.yaml model settings were rewritten during update but auto-restore failed: %s", exc)@@ -1664,9 +1622,7 @@ def run_quick_backup(args) -> None:print("No state files found to snapshot.")-# ----------------------------------------------------------------------------# Shared full-zip backup helper-# ---------------------------------------------------------------------------+# --- Shared full-zip backup helper ---def _write_full_zip_backup(out_path: Path, hermes_root: Path) -> Optional[Path]:"""Write a full zip snapshot of ``hermes_root`` to ``out_path`` while holding the backup slot.@@ -1690,47 +1646,38 @@ def _write_full_zip_backup_locked(out_path: Path, hermes_root: Path) -> Optionalexcept OSError as exc:logger.warning("Full-zip backup: walk failed: %s", exc)return None-if not files_to_add:return None-logger.info("automatic backup phase=scan status=complete duration_ms=%.1f files=%d",(time.monotonic() - scan_started) * 1000, len(files_to_add))- archive_started = time.monotonic()-def _db_failure(rel_path: Path) -> None:logger.warning("Full-zip backup aborted: SQLite snapshot failed for %s", rel_path)raise _SQLiteSnapshotError(str(rel_path))+ archive_started = time.monotonic()try:with _atomic_output_path(out_path) as archive_path, zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zf:_write_zip_entries(- zf, files_to_add, out_path,- on_db_failure=_db_failure,+ zf, files_to_add, out_path, on_db_failure=_db_failure, track_bytes=False,on_error=lambda rel, exc: logger.debug("Skipping %s in zip backup: %s", rel, exc),on_progress=lambda i: logger.info(- "automatic backup phase=archive status=progress completed=%d total=%d", i, len(files_to_add)- ),- track_bytes=False)+ "automatic backup phase=archive status=progress completed=%d total=%d", i, len(files_to_add)))except (OSError, _SQLiteSnapshotError) as exc:- logger.warning("Full-zip backup: zip write failed: %s", exc)# ``_atomic_output_path`` already removed the hidden partial. Do not unlink ``out_path``:# it may be a previous valid backup that the atomic publisher deliberately preserved.+ logger.warning("Full-zip backup: zip write failed: %s", exc)return None-logger.info("automatic backup phase=archive status=complete duration_ms=%.1f files=%d bytes=%d",(time.monotonic() - archive_started) * 1000, len(files_to_add), out_path.stat().st_size)return out_path-# ----------------------------------------------------------------------------# Pre-update / pre-migration auto-backups-# ---------------------------------------------------------------------------+# --- Pre-update / pre-migration auto-backups ---_PRE_UPDATE_BACKUPS_DIR = "backups"_PRE_UPDATE_PREFIX = "pre-update-"diff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex 1a18edb3ce0..47777ddadf9 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -53,9 +53,7 @@ def _skin_color(key: str, fallback: str) -> str:return _quiet(lambda: _active_skin().get_color(key, fallback), fallback)-# =========================================================================-# ASCII Art & Branding-# =========================================================================+# === ASCII Art & Branding ===from hermes_cli import __version__ as VERSION, __release_date__ as RELEASE_DATE@@ -82,9 +80,7 @@ HERMES_CADUCEUS = """[#CD7F32]⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⠀⣀⣀[#B8860B]⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⠈⣡⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀[/][#B8860B]⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀[/]"""-# =========================================================================-# Skills scanning-# =========================================================================+# === Skills scanning ===# Per-process caches: ``None`` until computed, then a 1-tuple ``(value,)`` so a computed ``None``# is distinguishable from "not yet computed". Reset by assigning ``None`` (tests, ``hermes skills``).@@ -129,9 +125,7 @@ def get_available_skills() -> Dict[str, List[str]]:return {} if result is _UNCACHED else result-# =========================================================================-# Update check-# =========================================================================+# === Update check ===_UPDATE_CHECK_CACHE_SECONDS = 6 * 3600 # avoid repeated git fetches@@ -180,7 +174,6 @@ def _git_run(kwargs: dict = {}if network:from hermes_cli._subprocess_compat import noninteractive_git_env-kwargs = {"stdin": subprocess.DEVNULL, "env": noninteractive_git_env()}try:return subprocess.run(@@ -227,7 +220,6 @@ def _github_compare_behind(current_rev: str, target_rev: str) -> Optional[int]:def _fetch():import urllib.request-# api.github.com 403s requests without a User-Agent.req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json", "User-Agent": "hermes-cli-update-check"})@@ -300,7 +292,6 @@ def _check_via_local_git(repo_dir: Path) -> Optional[int]:# removes the lock. This passive check is also the main tmp_pack GENERATOR on flaky lines,# so it must be the janitor too (#93732).from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs-clear_stale_git_locks(repo_dir)clear_stale_tmp_packs(repo_dir)@@ -463,9 +454,7 @@ def format_banner_version_label() -> str:return f"{base} · upstream {upstream} · local {local} (+{ahead} carried {_plural(ahead, 'commit')})"-# =========================================================================-# Non-blocking update check-# =========================================================================+# === Non-blocking update check ===_update_result: Optional[int] = None_update_check_done = threading.Event()@@ -548,9 +537,7 @@ def _defer_update_notice(console: "Console", max_wait: float = 30.0) -> None:_daemon("update-notice", _wait_and_print) # never break the session over an update notice-# =========================================================================-# Welcome banner-# =========================================================================+# === Welcome banner ===def _plural(n: int, word: str) -> str:return word if n == 1 else f"{word}s"@@ -578,9 +565,7 @@ def _short_label(name: str) -> str:return name[:25] + "..." if len(name) > 28 else name-# =========================================================================-# Banner snapshot — warm-launch fast path-# =========================================================================+# === Banner snapshot — warm-launch fast path ===# The tool panel needs the full tool registry (~0.5-0.9s cold, the largest chunk of time-to-# banner). The list is a pure function of (config.yaml, .env, code checkout, enabled toolsets),# so the rendered inputs are snapshotted to disk and replayed when the fingerprint matches. The@@ -597,7 +582,6 @@ def _banner_snapshot_path() -> Path:def banner_snapshot_fingerprint() -> Optional[str]:"""Fingerprint the inputs the banner tool panel depends on."""import hashlib-def _inputs():from hermes_cli.config import get_config_pathreturn (get_config_path(), get_hermes_home() / ".env")@@ -673,7 +657,6 @@ def compute_toolset_availability(enabled_toolsets: List[str] = None) -> Dict[strSplit out so the result can be snapshotted and replayed without importing ``model_tools``."""from model_tools import check_tool_availability, TOOLSET_REQUIREMENTS-enabled_toolsets = enabled_toolsets or []_, unavailable_toolsets = check_tool_availability(quiet=True)# The availability check walks the GLOBAL registry, so it includes toolsets outside this@@ -749,7 +732,6 @@ def _moa_aggregator_label(preset_name: str) -> str:"""Short aggregator-model label for a MoA preset ("" when the preset has none)."""from hermes_cli.config import load_configfrom hermes_cli.moa_config import normalize_moa_config-preset = normalize_moa_config(load_config().get("moa") or {}).get("presets", {}).get(preset_name)model = str(((preset or {}).get("aggregator") or {}).get("model") or "")return model.split("/")[-1]@@ -867,15 +849,11 @@ def _banner_skill_lines(skills_by_category: Dict[str, List[str]], skills_enabledreturn lines-def build_welcome_banner(console: "Console", model: str, cwd: str,- tools: List[dict] = None,- enabled_toolsets: List[str] = None,- session_id: str = None,- get_toolset_for_tool=None,- context_length: int = None,- provider: str = None,- availability: Dict[str, Any] = None,- skills_by_category: Dict[str, List[str]] = None):+def build_welcome_banner(+ console: "Console", model: str, cwd: str, tools: List[dict] = None, enabled_toolsets: List[str] = None,+ session_id: str = None, get_toolset_for_tool=None, context_length: int = None, provider: str = None,+ availability: Dict[str, Any] = None, skills_by_category: Dict[str, List[str]] = None,+):"""Build and print a welcome banner with caduceus on left and info on right.When ``provider == "moa"``, ``model`` is a MoA preset name and the aggregator is rendered.@@ -886,7 +864,6 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,from rich.table import Tableif get_toolset_for_tool is None:from model_tools import get_toolset_for_tool-tools = tools or []enabled_toolsets = enabled_toolsets or []