Skip to content

The agent that grows with you

fix(backup): import into the active HERMES_HOME instead of the root home

Konstantin Khlopkovaea2daee293c
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index e7751f92afe..9a63f4d0464 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -24,7 +24,12 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional
-from hermes_constants import get_default_hermes_root, get_hermes_home, display_hermes_home
+from hermes_constants import (
+ _get_platform_default_hermes_home,
+ get_default_hermes_root,
+ get_hermes_home,
+ display_hermes_home,
+)
from utils import (
_preserve_file_mode,
_preserve_file_owner,
@@ -1230,7 +1235,12 @@ def run_import(args) -> None:
print(f"Error: Not a valid zip file: {zip_path}")
sys.exit(1)
- hermes_root = get_default_hermes_root()
+ # The restore target must be the home the command operates under — the
+ # same path printed as "Target:" via display_hermes_home(). Resolving
+ # through get_default_hermes_root() instead maps a profile home
+ # (<root>/profiles/<name>) back to <root>, silently retargeting the
+ # restore at the live root while the profile directory stays empty.
+ hermes_root = get_hermes_home()
with zipfile.ZipFile(zip_path, "r") as zf:
# Validate
@@ -1442,15 +1452,33 @@ def run_import(args) -> None:
# platform-less gateway is a supported mode, so this is safe even
# for backups with no messaging config). Best-effort and prompt-free;
# failures print a manual fallback and never fail the import.
- try:
- from hermes_cli.gateway import ensure_gateway_service, _is_service_running
+ native_default = _get_platform_default_hermes_home()
+ default_has_install = any(
+ (native_default / marker).exists()
+ for marker in ("config.yaml", ".env", "state.db")
+ )
+ # A restore into a sandbox or profile home must not silently install
+ # a second gateway pointed at it — on the default service name that
+ # would shadow or hijack the machine's primary install. Only revive
+ # the service automatically when the restore landed in the default
+ # home, or when no other install exists on this machine.
+ if hermes_root != native_default and default_has_install:
+ print(
+ "\nRestored into a non-default home; leaving the gateway service "
+ "alone to avoid clashing with the install at "
+ f"{native_default}."
+ )
+ print("To start a gateway for this home, run: hermes gateway install")
+ else:
+ try:
+ 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")
+ 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("Done. Your Hermes configuration has been restored.")
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index e78cfb57f42..3a3b5620b7c 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -1852,5 +1852,133 @@ class TestMemoryProviderExternalPaths:
assert not (hermes_home / "_external").exists()
+# ---------------------------------------------------------------------------
+# run_import: HERMES_HOME override handling (issue #99839)
+# ---------------------------------------------------------------------------
+
+
+class TestImportHonorsHermesHomeOverride:
+ """`hermes import` must restore into the home the command runs under.
+
+ Resolving the target through get_default_hermes_root() maps a profile
+ home (<root>/profiles/<name>) back to <root>: the import then overwrites
+ the live root's config.yaml while the profile directory stays empty —
+ exactly what "Target:" printed it would NOT do.
+ """
+
+ def _make_backup_zip(self, tmp_path):
+ import zipfile
+
+ src_root = tmp_path / "src-home"
+ src_root.mkdir()
+ (src_root / "config.yaml").write_text("model:\n provider: anthropic\n")
+ (src_root / ".env").write_text("ANTHROPIC_API_KEY=sk-test\n")
+ zip_path = tmp_path / "backup.zip"
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ zf.write(src_root / "config.yaml", "config.yaml")
+ zf.write(src_root / ".env", ".env")
+ return zip_path
+
+ def test_import_targets_named_profile_home(self, tmp_path, monkeypatch):
+ """HERMES_HOME=<root>/profiles/<name> must restore INTO the profile,
+ not into <root> (which would clobber the live root config)."""
+ root = tmp_path / "hermes-root"
+ profile = root / "profiles" / "coder"
+ profile.mkdir(parents=True)
+ # Live root config that must survive untouched.
+ (root / "config.yaml").write_text("model:\n provider: openai\n")
+
+ monkeypatch.setenv("HERMES_HOME", str(profile))
+ from hermes_constants import get_hermes_home
+
+ assert get_hermes_home() == profile
+
+ zip_path = self._make_backup_zip(tmp_path)
+ import argparse
+ from hermes_cli.backup import run_import
+
+ args = argparse.Namespace(zipfile=str(zip_path), force=True)
+ run_import(args)
+
+ assert (profile / "config.yaml").read_text() == (
+ "model:\n provider: anthropic\n"
+ )
+ assert (root / "config.yaml").read_text() == "model:\n provider: openai\n"
+
+ def test_import_skips_gateway_install_for_non_default_home(
+ self, tmp_path, monkeypatch
+ ):
+ """A restore into a sandbox must not silently start a second gateway
+ pointed at it — the profile/sandbox gateway would shadow the default
+ service installed by the primary install."""
+ native_default = tmp_path / "native-default"
+ sandbox = tmp_path / "sandbox-home"
+ sandbox.mkdir(parents=True)
+ # Live default install markers.
+ native_default.mkdir()
+ (native_default / "config.yaml").write_text("model:\n provider: openai\n")
+
+ monkeypatch.setenv("HERMES_HOME", str(sandbox))
+
+ import argparse
+
+ import hermes_constants
+ from hermes_cli import backup as backup_mod
+
+ monkeypatch.setattr(
+ backup_mod,
+ "_get_platform_default_hermes_home",
+ lambda: native_default,
+ )
+
+ calls = []
+ monkeypatch.setattr(
+ "hermes_cli.gateway.ensure_gateway_service",
+ lambda *a, **kw: calls.append(kw),
+ )
+ monkeypatch.setattr(
+ "hermes_cli.gateway._is_service_running",
+ lambda: False,
+ )
+
+ zip_path = self._make_backup_zip(tmp_path)
+ args = argparse.Namespace(zipfile=str(zip_path), force=True)
+ backup_mod.run_import(args)
+
+ assert calls == [], "gateway must not be auto-installed for a sandbox restore"
+
+ def test_import_installs_gateway_when_default_home_is_target(
+ self, tmp_path, monkeypatch
+ ):
+ """Restoring into the default home keeps the auto-install behavior."""
+ native_default = tmp_path / "native-default"
+ native_default.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(native_default))
+
+ import argparse
+
+ from hermes_cli import backup as backup_mod
+
+ monkeypatch.setattr(
+ backup_mod,
+ "_get_platform_default_hermes_home",
+ lambda: native_default,
+ )
+
+ calls = []
+ monkeypatch.setattr(
+ "hermes_cli.gateway.ensure_gateway_service",
+ lambda *a, **kw: calls.append(kw),
+ )
+ monkeypatch.setattr(
+ "hermes_cli.gateway._is_service_running",
+ lambda: False,
+ )
+
+ zip_path = self._make_backup_zip(tmp_path)
+ args = argparse.Namespace(zipfile=str(zip_path), force=True)
+ backup_mod.run_import(args)
+
+ assert calls and calls[0].get("context") == "import"