Skip to content

The agent that grows with you

fix(profiles): tombstone deleted named profiles so logging cannot resurrect them

EndeavorYen7e3452245471
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 5475d4289f3..1e482d16f41 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -958,17 +958,13 @@ def ensure_hermes_home():
home = get_hermes_home()
key = str(home)
+ # Named profiles must be created explicitly (e.g. ``hermes profile create``).
+ # Check tombstones before the memo so a stale empty shell cannot skip
+ # the deleted-profile guard.
+ from hermes_constants import assert_named_profile_home_live
+ assert_named_profile_home_live(home)
if key in _HERMES_HOME_ENSURED and home.is_dir():
return
- # Named profiles must be created explicitly (e.g. ``hermes profile create``).
- # If a stale process keeps running after the profile was renamed/deleted,
- # silently mkdir-ing the old HERMES_HOME would resurrect an empty skeleton
- # and make the deleted profile reappear in Desktop/profile lists.
- if home.parent.name == "profiles" and not home.exists():
- raise FileNotFoundError(
- f"Named profile home does not exist: {home}. "
- "Create the profile explicitly before using it."
- )
if is_managed():
old_umask = os.umask(0o007)
try:
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index d5a4fa4e293..d439f57b270 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -34,6 +34,11 @@ from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Dict, List, Optional, Tuple
from agent.skill_utils import is_excluded_skill_path
+from hermes_constants import (
+ clear_named_profile_deleted,
+ mark_named_profile_deleted,
+ named_profile_is_deleted,
+)
logger = logging.getLogger(__name__)
@@ -1022,6 +1027,8 @@ def list_profiles() -> List[ProfileInfo]:
continue # already added as the built-in default above
if not _PROFILE_ID_RE.match(name):
continue
+ if named_profile_is_deleted(entry):
+ continue
model, provider = _read_config_model(entry)
alias_name = alias_map.get(normalize_profile_name(name))
if alias_name:
@@ -1107,6 +1114,8 @@ def profiles_to_serve(
continue # default is the built-in entry already added above
if not _PROFILE_ID_RE.match(name):
continue
+ if named_profile_is_deleted(entry):
+ continue
if allowed is not None and name not in allowed:
continue
serve.append((name, entry))
@@ -1173,8 +1182,11 @@ def create_profile(
)
profile_dir = get_profile_dir(canon)
+ if profile_dir.exists() and named_profile_is_deleted(profile_dir):
+ shutil.rmtree(profile_dir)
if profile_dir.exists():
raise FileExistsError(f"Profile '{canon}' already exists at {profile_dir}")
+ clear_named_profile_deleted(profile_dir)
# Resolve clone source
source_dir = None
@@ -1703,6 +1715,10 @@ def delete_profile(name: str, yes: bool = False) -> Path:
# guard — resurrected the deleted tree.
_stop_profile_backends(canon, profile_dir)
+ # Tombstone before rmtree so a stale serve/logging mkdir cannot relist
+ # this name as a live profile.
+ mark_named_profile_deleted(profile_dir)
+
# 2c. Release this process's holographic memory-store connections into
# the profile. The Desktop's *main* serve process opens memory_store.db
# for every known profile and is deliberately not stopped above, so on
diff --git a/hermes_constants.py b/hermes_constants.py
index 34cc6f8e87b..c70e251fb00 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -227,6 +227,62 @@ def get_default_hermes_root() -> Path:
return result
+# Named-profile deletion must survive stale mkdir from live serve/logging.
+# The marker lives beside the profile dir, not inside it, so rmtree cannot
+# erase the fact that the profile was deleted.
+_DELETED_PROFILES_DIR = ".deleted"
+
+
+def named_profile_home(path: str | Path) -> Path | None:
+ """Return ``<root>/profiles/<name>`` when *path* is that home or under it."""
+ current = Path(path)
+ for candidate in (current, *current.parents):
+ if candidate.parent.name == "profiles" and not candidate.name.startswith("."):
+ return candidate
+ return None
+
+
+def profile_tombstone_path(profile_home: Path) -> Path:
+ return profile_home.parent / _DELETED_PROFILES_DIR / profile_home.name
+
+
+def named_profile_is_deleted(profile_home: str | Path) -> bool:
+ return profile_tombstone_path(Path(profile_home)).exists()
+
+
+def mark_named_profile_deleted(profile_home: str | Path) -> None:
+ marker = profile_tombstone_path(Path(profile_home))
+ marker.parent.mkdir(parents=True, exist_ok=True)
+ marker.write_text("deleted\n", encoding="utf-8")
+
+
+def clear_named_profile_deleted(profile_home: str | Path) -> None:
+ profile_tombstone_path(Path(profile_home)).unlink(missing_ok=True)
+
+
+def assert_named_profile_home_live(path: str | Path) -> None:
+ """Refuse missing or tombstoned named profile homes.
+
+ Default ``HERMES_HOME`` (not under ``profiles/``) is unchanged.
+ """
+ home = named_profile_home(path)
+ if home is None:
+ return
+ if named_profile_is_deleted(home) or not home.exists():
+ raise FileNotFoundError(
+ f"Named profile home does not exist: {home}. "
+ "Create the profile explicitly before using it."
+ )
+
+
+def mkdir_under_hermes_home(path: str | Path) -> Path:
+ """Create *path*, but never materialize a deleted/missing named profile."""
+ target = Path(path)
+ assert_named_profile_home_live(target)
+ target.mkdir(parents=True, exist_ok=True)
+ return target
+
+
def get_optional_skills_dir(default: Path | None = None) -> Path:
"""Return the optional-skills directory, honoring package-manager wrappers.
diff --git a/hermes_logging.py b/hermes_logging.py
index d371af25aaf..7c81afd57dd 100644
--- a/hermes_logging.py
+++ b/hermes_logging.py
@@ -301,8 +301,8 @@ def setup_logging(
"""
global _logging_initialized
home = hermes_home or get_hermes_home()
- log_dir = home / "logs"
- log_dir.mkdir(parents=True, exist_ok=True)
+ from hermes_constants import mkdir_under_hermes_home
+ log_dir = mkdir_under_hermes_home(home / "logs")
# Read config defaults (best-effort — config may not be loaded yet).
cfg_level, cfg_max_size, cfg_backup = _read_logging_config()
@@ -745,7 +745,8 @@ def _add_rotating_handler(
):
return # already attached
- path.parent.mkdir(parents=True, exist_ok=True)
+ from hermes_constants import mkdir_under_hermes_home
+ mkdir_under_hermes_home(path.parent)
handler = _ManagedRotatingFileHandler(
str(path), maxBytes=max_bytes, backupCount=backup_count,
encoding="utf-8",
diff --git a/tests/hermes_cli/test_deleted_profile_tombstone.py b/tests/hermes_cli/test_deleted_profile_tombstone.py
new file mode 100644
index 00000000000..b30bd15dd1f
--- /dev/null
+++ b/tests/hermes_cli/test_deleted_profile_tombstone.py
@@ -0,0 +1,95 @@
+"""Deleted named profiles must stay gone until explicitly recreated.
+
+A live serve/logging process can mkdir ``profiles/<name>/logs`` after
+``hermes profile delete`` removes the tree. That empty shell then
+reappears in ``hermes profile list`` and Desktop Bot Mode. These tests
+lock the tombstone + no-mkdir contract without depending on Desktop.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from hermes_cli.config import ensure_hermes_home
+from hermes_cli.profiles import (
+ create_profile,
+ delete_profile,
+ list_profiles,
+ profiles_to_serve,
+)
+from hermes_logging import setup_logging
+
+
+def profile_env(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ default_home = tmp_path / ".hermes"
+ default_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(default_home))
+ return tmp_path
+
+
+def _named_homes(tmp_path: Path) -> list[str]:
+ return [info.name for info in list_profiles() if not info.is_default]
+
+
+class TestDeletedProfileTombstone:
+ def test_delete_then_logging_setup_does_not_recreate_home(self, profile_env, monkeypatch):
+ profile_dir = create_profile("worker", no_alias=True, no_skills=True)
+ with patch("hermes_cli.profiles._cleanup_gateway_service"), patch(
+ "hermes_cli.profiles._stop_profile_backends"
+ ):
+ delete_profile("worker", yes=True)
+
+ assert not profile_dir.exists()
+ assert "worker" not in _named_homes(profile_env)
+
+ monkeypatch.setenv("HERMES_HOME", str(profile_dir))
+ with pytest.raises(FileNotFoundError, match="Named profile home does not exist"):
+ setup_logging(hermes_home=profile_dir, force=True)
+
+ assert not profile_dir.exists()
+ monkeypatch.setenv("HERMES_HOME", str(profile_env / ".hermes"))
+ assert "worker" not in _named_homes(profile_env)
+
+ def test_empty_shell_after_delete_is_not_listed_or_served(self, profile_env):
+ profile_dir = create_profile("worker", no_alias=True, no_skills=True)
+ with patch("hermes_cli.profiles._cleanup_gateway_service"), patch(
+ "hermes_cli.profiles._stop_profile_backends"
+ ):
+ delete_profile("worker", yes=True)
+
+ # Simulate a stale mkdir that only rebuilds the directory itself.
+ profile_dir.mkdir(parents=True)
+ (profile_dir / "state.db").write_bytes(b"")
+
+ assert "worker" not in _named_homes(profile_env)
+ served = [name for name, _ in profiles_to_serve(True)]
+ assert "worker" not in served
+
+ def test_tombstoned_home_is_not_bootstrapped(self, profile_env, monkeypatch):
+ profile_dir = create_profile("worker", no_alias=True, no_skills=True)
+ with patch("hermes_cli.profiles._cleanup_gateway_service"), patch(
+ "hermes_cli.profiles._stop_profile_backends"
+ ):
+ delete_profile("worker", yes=True)
+ profile_dir.mkdir(parents=True)
+
+ monkeypatch.setenv("HERMES_HOME", str(profile_dir))
+ with pytest.raises(FileNotFoundError, match="Named profile home does not exist"):
+ ensure_hermes_home()
+ assert not (profile_dir / "sessions").exists()
+
+ def test_create_after_delete_clears_tombstone(self, profile_env):
+ create_profile("worker", no_alias=True, no_skills=True)
+ with patch("hermes_cli.profiles._cleanup_gateway_service"), patch(
+ "hermes_cli.profiles._stop_profile_backends"
+ ):
+ delete_profile("worker", yes=True)
+
+ recreated = create_profile("worker", no_alias=True, no_skills=True)
+ assert recreated.is_dir()
+ assert "worker" in _named_homes(profile_env)