The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: anchor checkout detection to the export path, not cwd
kshitijk4poor26fb8f60e613
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex a48f6e0e916..250949c94dd 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -477,14 +477,14 @@ class CLICommandsMixin:parts = parts[:idx] + parts[idx + 2:]name = parts[0] if parts else (get_active_profile_name() or "default")- if not output:- output = str(get_profile_export_path(name))try:+ if not output:+ output = str(get_profile_export_path(name))result = export_profile(name, output)print(f" ✓ Exported '{name}' to {result}")print(" Share it: the other user runs /import or `hermes profile import <archive>`.")- except (ValueError, FileNotFoundError) as e:+ except (ValueError, FileNotFoundError, OSError) as e:print(f" Error: {e}")def _handle_import_command(self, command: str):diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 5a346222f2a..3e0c866b746 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -11479,11 +11479,11 @@ def cmd_profile(args):from hermes_cli.profiles import export_profile, get_profile_export_pathname = args.profile_name- output = args.output or str(get_profile_export_path(name))try:+ output = args.output or str(get_profile_export_path(name))result_path = export_profile(name, output)print(f"✓ Exported '{name}' to {result_path}")- except (ValueError, FileNotFoundError) as e:+ except (ValueError, FileNotFoundError, OSError) as e:print(f"Error: {e}")sys.exit(1)diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 574047965a3..5f06358d338 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -2115,45 +2115,51 @@ def get_active_profile_name() -> str:# Export / Import# ----------------------------------------------------------------------------def _profile_export_directory() -> Path:- """Choose an export directory that cannot become source-tree input."""- export_dir = _get_default_hermes_home() / "profile-exports"+def _inside_git_checkout(path: Path) -> bool:+ """Return True when *path* lies inside a Git checkout.++ Walks the path's OWN resolved ancestry for a ``.git`` marker (a directory+ for normal clones, a file for worktrees/submodules). Anchoring on the+ candidate path — not on ``Path.cwd()`` — keeps the safety proof valid when+ ``HERMES_HOME`` points inside a checkout but the process runs from+ somewhere else entirely (cron, a service manager, an absolute-path+ invocation). On resolution failure we conservatively report True so the+ caller falls through to a provably safe candidate.+ """try:- cwd = Path.cwd().resolve()+ resolved = path.resolve()except OSError:- return export_dir-- checkout_root = next(- (- candidate- for candidate in (cwd, *cwd.parents)- if (candidate / ".git").exists()- ),- None,+ return True+ return any(+ (candidate / ".git").exists() for candidate in (resolved, *resolved.parents))- if checkout_root is None:- return export_dir- try:- export_dir.resolve().relative_to(checkout_root.resolve())- except ValueError:++def _profile_export_directory() -> Path:+ """Choose an export directory that cannot become source-tree input."""+ import tempfile++ export_dir = _get_default_hermes_home() / "profile-exports"+ if not _inside_git_checkout(export_dir):return export_dir# A custom deployment may point HERMES_HOME at its source checkout. Do# not put the automatic archive under that tree; use a sibling store and# fall back to the OS temp directory only for the unusual case where the- # user's home itself is the checkout.- candidates = [+ # user's home itself is a checkout (e.g. a dotfiles repo).+ candidates = (Path.home() / ".hermes-profile-exports",- ]- import tempfile-- candidates.append(Path(tempfile.gettempdir()) / "hermes-profile-exports")+ Path(tempfile.gettempdir()) / "hermes-profile-exports",+ )for candidate in candidates:- try:- candidate.resolve().relative_to(checkout_root.resolve())- except ValueError:+ if not _inside_git_checkout(candidate):return candidate+ logger.warning(+ "Every managed export destination resolves inside a Git checkout; "+ "falling back to %s. Pass an explicit output path to avoid staging "+ "profile archives in a source tree.",+ export_dir,+ )return export_dirdiff --git a/tests/hermes_cli/test_profile_export_default_path.py b/tests/hermes_cli/test_profile_export_default_path.pyindex d06da310590..baf09c54891 100644--- a/tests/hermes_cli/test_profile_export_default_path.py+++ b/tests/hermes_cli/test_profile_export_default_path.py@@ -2,27 +2,35 @@from __future__ import annotations+import importlibfrom argparse import Namespacefrom pathlib import Pathimport pytest-from hermes_cli import profiles-from hermes_cli.cli_commands_mixin import CLICommandsMixin-from hermes_cli.main import cmd_profile-from hermes_cli.profiles import get_profile_export_path++def profiles():+ """Resolve the live profiles module at call time.++ Sibling test files reload ``hermes_cli.profiles`` / ``hermes_cli.main``;+ a top-level ``from hermes_cli.profiles import ...`` here would bind the+ pre-reload function objects and silently divorce this file's monkeypatches+ from the code under test when the whole directory runs as one sweep.+ """+ return importlib.import_module("hermes_cli.profiles")def test_default_export_path_is_managed_and_outside_named_profiles(- tmp_path, monkeypatch+ tmp_path, monkeypatch, profiles):default_home = tmp_path / ".hermes"default_home.mkdir()- monkeypatch.setattr(- "hermes_cli.profiles._get_default_hermes_home", lambda: default_home- )+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)- result = get_profile_export_path("Research-Bot", timestamp="20260823-120000")+ result = profiles.get_profile_export_path(+ "Research-Bot", timestamp="20260823-120000"+ )assert (result@@ -33,39 +41,81 @@ def test_default_export_path_is_managed_and_outside_named_profiles(def test_custom_hermes_home_inside_a_checkout_uses_a_sibling_store(- tmp_path, monkeypatch+ tmp_path, monkeypatch, profiles):checkout = tmp_path / "checkout"checkout.mkdir()(checkout / ".git").write_text("gitdir: ../git\n", encoding="utf-8")monkeypatch.chdir(checkout)monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")- monkeypatch.setattr(- "hermes_cli.profiles._get_default_hermes_home", lambda: checkout- )+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: checkout)++ result = profiles.get_profile_export_path("default", timestamp="20260823-120000")++ assert not result.resolve().is_relative_to(checkout.resolve())+++def test_checkout_detection_does_not_depend_on_cwd(tmp_path, monkeypatch, profiles):+ """HERMES_HOME inside a checkout must be detected even when cwd is elsewhere.++ Regression for the cwd-anchored bypass: cron/service-manager invocations+ run from outside the checkout, and the original heuristic walked+ ``Path.cwd()`` — letting the export land inside the source tree again.+ """+ checkout = tmp_path / "checkout"+ checkout.mkdir()+ (checkout / ".git").write_text("gitdir: ../git\n", encoding="utf-8")+ hermes_home = checkout / "data_home"+ hermes_home.mkdir()+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ monkeypatch.chdir(elsewhere) # cwd has no .git ancestor inside tmp_path+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: hermes_home)- result = get_profile_export_path("default", timestamp="20260823-120000")+ result = profiles.get_profile_export_path("default", timestamp="20260823-120000")assert not result.resolve().is_relative_to(checkout.resolve())+def test_cli_export_rejects_bad_profile_name_without_traceback(+ tmp_path, monkeypatch, capsys, profiles+):+ """A bad name must print a clean error — the helper raises before export."""+ main_mod = importlib.import_module("hermes_cli.main")+ default_home = tmp_path / ".hermes"+ default_home.mkdir()+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)++ with pytest.raises(SystemExit):+ main_mod.cmd_profile(+ Namespace(+ profile_action="export",+ profile_name="bad//name",+ output=None,+ )+ )++ out = capsys.readouterr().out+ assert "Error:" in out++def test_cli_export_default_does_not_write_into_the_current_checkout(- tmp_path, monkeypatch, capsys+ tmp_path, monkeypatch, capsys, profiles):+ main_mod = importlib.import_module("hermes_cli.main")default_home = tmp_path / ".hermes"default_home.mkdir()(default_home / "config.yaml").write_text("model: test\n", encoding="utf-8")checkout = tmp_path / "checkout"checkout.mkdir()monkeypatch.chdir(checkout)- monkeypatch.setattr(- "hermes_cli.profiles._get_default_hermes_home", lambda: default_home- )+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: default_home)- cmd_profile(+ main_mod.cmd_profile(Namespace(profile_action="export",profile_name="default",@@ -80,12 +130,13 @@ def test_cli_export_default_does_not_write_into_the_current_checkout(assert str(exported[0]) in capsys.readouterr().out-def test_slash_export_uses_the_same_managed_destination(tmp_path, monkeypatch):+def test_slash_export_uses_the_same_managed_destination(+ tmp_path, monkeypatch, profiles+):+ mixin_mod = importlib.import_module("hermes_cli.cli_commands_mixin")default_home = tmp_path / ".hermes"default_home.mkdir()- monkeypatch.setattr(- "hermes_cli.profiles._get_default_hermes_home", lambda: default_home- )+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)monkeypatch.setattr(profiles, "get_active_profile_name", lambda: "default")calls = []monkeypatch.setattr(@@ -94,7 +145,7 @@ def test_slash_export_uses_the_same_managed_destination(tmp_path, monkeypatch):lambda name, output: calls.append((name, output)) or output,)- CLICommandsMixin()._handle_export_command("/export")+ mixin_mod.CLICommandsMixin()._handle_export_command("/export")assert len(calls) == 1assert calls[0][0] == "default"@@ -104,10 +155,11 @@ def test_slash_export_uses_the_same_managed_destination(tmp_path, monkeypatch):@pytest.mark.asyncioasync def test_profile_export_api_uses_the_shared_managed_destination(- tmp_path, monkeypatch+ tmp_path, monkeypatch, profiles):from hermes_cli.web_models import ProfileExport- from hermes_cli.web_routers.profiles import export_profile_endpoint++ router_mod = importlib.import_module("hermes_cli.web_routers.profiles")managed = tmp_path / "profile-exports" / "default-20260823-120000.tar.gz"monkeypatch.setattr(profiles, "get_profile_export_path", lambda name: managed)@@ -117,6 +169,6 @@ async def test_profile_export_api_uses_the_shared_managed_destination(lambda name, output, extra_files=None: output,)- result = await export_profile_endpoint("default", ProfileExport())+ result = await router_mod.export_profile_endpoint("default", ProfileExport())assert result == {"ok": True, "archive": str(managed)}diff --git a/website/docs/user-guide/profile-distributions.md b/website/docs/user-guide/profile-distributions.mdindex 4cf8a295b04..718b799d205 100644--- a/website/docs/user-guide/profile-distributions.md+++ b/website/docs/user-guide/profile-distributions.md@@ -633,8 +633,10 @@ Without `-o`, the CLI and TUI place the archive in Hermes's managed`profile-exports/` directory under the default Hermes home, not in the currentworking directory. This keeps routine exports out of source checkouts andprevents a generated profile snapshot from being mistaken for a repository-source file. An explicit `-o` path is still honored when you intentionally-choose where to save the archive.+source file. If the Hermes home itself lives inside a Git checkout (some+Docker/custom deployments), the archive goes to `~/.hermes-profile-exports/`+instead — never into the checkout. An explicit `-o` path is still honored+when you intentionally choose where to save the archive.Or from a shell, same machinery: