The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli): one special-file filter for every profile copytree
kshitijk4poor1d8af13e4dde
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 6066beee1ea..e5fa6d4483c 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -72,6 +72,27 @@ _PLACEHOLDER_ENV = ()+def _non_exportable_entries(directory: str, contents: list) -> set:+ """Entries under *directory* that must never be copied out of a profile: bytecode caches,+ ``*.sock``/``*.tmp`` names, and anything that is not a regular file, directory, or symlink.+ :func:`shutil.copytree` cannot copy special files, so a single live Unix socket without a+ ``.sock`` name (or a FIFO, or a device node) would abort the whole export or clone with+ ``[Errno 6] No such device or address``. Symlinks survive — copytree recreates them."""+ ignored: set = set()+ for entry in contents:+ if entry == "__pycache__" or entry.endswith((".sock", ".tmp", ".pyc", ".pyo")):+ ignored.add(entry)+ continue+ try:+ mode = os.lstat(os.path.join(directory, entry)).st_mode+ except OSError:+ ignored.add(entry) # vanished mid-walk — copytree would fail on it anyway+ continue+ if not (stat.S_ISREG(mode) or stat.S_ISDIR(mode) or stat.S_ISLNK(mode)):+ ignored.add(entry)+ return ignored++def _clone_all_copytree_ignore(source_dir: Path):"""copytree ignore for --clone-all: history artifacts for any source, infrastructureonly when the source is the default profile (see the two exclude sets above)."""@@ -87,13 +108,9 @@ def _clone_all_copytree_ignore(source_dir: Path):# resolve() can fail on odd FS layouts (broken symlinks, missing parents).# Fail open — better to over-copy than silently drop user data.at_root = False- # A live source profile carries gateway/agent-browser sockets that copytree- # cannot copy; _non_exportable_entries drops them (and __pycache__/*.sock/*.tmp).ignored = _non_exportable_entries(directory, names)- ignored.update(- entry for entry in names- if entry.endswith((".pyc", ".pyo")) or (at_root and entry in root_exclude)- )+ if at_root:+ ignored.update(root_exclude & set(names))return ignoredreturn _ignore@@ -824,7 +841,10 @@ def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path]) -> Non_clone_file(source_dir, profile_dir, relpath)source_skills = source_dir / "skills"if source_skills.is_dir():- shutil.copytree(source_skills, profile_dir / "skills", symlinks=True, dirs_exist_ok=True)+ shutil.copytree(+ source_skills, profile_dir / "skills", symlinks=True, dirs_exist_ok=True,+ ignore=_non_exportable_entries,+ )for relpath in _CLONE_SUBDIR_FILES:_clone_file(source_dir, profile_dir, relpath)@@ -1520,27 +1540,6 @@ def get_profile_export_path(name: str, *, timestamp: Optional[str] = None) -> Pareturn export_dir / f"{canon}-{stamp}.tar.gz"-def _non_exportable_entries(directory: str, contents: list) -> set:- """Entries under *directory* that must never reach an export archive: ``__pycache__``,- ``*.sock``/``*.tmp`` names, and anything that is not a regular file, directory, or symlink.- :func:`shutil.copytree` cannot copy special files, so a single live Unix socket without a- ``.sock`` name (or a FIFO, or a device node) would abort the whole export with- ``[Errno 6] No such device or address``. Symlinks survive — copytree recreates them."""- ignored: set = set()- for entry in contents:- if entry == "__pycache__" or entry.endswith((".sock", ".tmp")):- ignored.add(entry)- continue- try:- mode = os.lstat(os.path.join(directory, entry)).st_mode- except OSError:- ignored.add(entry) # vanished mid-walk — copytree would fail on it anyway- continue- if not (stat.S_ISREG(mode) or stat.S_ISDIR(mode) or stat.S_ISLNK(mode)):- ignored.add(entry)- return ignored--def _default_export_ignore(root_dir: Path):"""copytree ignore for the default-profile export: root-level allow-list(``_DEFAULT_EXPORT_INCLUDE_ROOT``) plus universal exclusions. Surviving text files are@@ -1622,10 +1621,7 @@ def export_profile(name: str, output_path: str, extra_files: Optional[Dict[str,# The default profile IS ~/.hermes (dir name ".hermes"), so both paths stage a filtered# copy under a temp dir named after the canonical id: root allow-list for default,- # credential exclusion for named profiles. The universal exclusions apply to both:- # profiles accumulate Unix sockets in normal operation (e.g. an agent-browser control- # socket under ``home/.agent-browser/``), and a single one aborts copytree — and with- # it the whole export.+ # credential exclusion for named profiles.def _ignore_credentials(directory: str, contents: list) -> set:ignored = _non_exportable_entries(directory, contents)ignored.update(_EXPORT_CREDENTIAL_FILES & set(contents))diff --git a/tests/hermes_cli/test_profile_export_special_files.py b/tests/hermes_cli/test_profile_export_special_files.pyindex 524c117c158..d1c7618ae71 100644--- a/tests/hermes_cli/test_profile_export_special_files.py+++ b/tests/hermes_cli/test_profile_export_special_files.py@@ -29,21 +29,16 @@ def _patch_named_profile(monkeypatch, profiles_root, profile_dir):monkeypatch.setattr("hermes_cli.profiles.validate_profile_name", lambda n: None)-def _bind_unix_socket(path):+def _bind_unix_socket(monkeypatch, path):"""Bind an AF_UNIX socket at *path*.Binds via a cwd-relative name so pytest's long tmp paths stay under the~104-byte ``sun_path`` limit on macOS. The filesystem entry outlives theclose — exactly the stale-socket state a real profile ends up with."""- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- cwd = os.getcwd()- os.chdir(path.parent)- try:+ monkeypatch.chdir(path.parent)+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:sock.bind(path.name)- finally:- os.chdir(cwd)- sock.close()def test_named_profile_export_survives_unix_socket(tmp_path, monkeypatch):@@ -58,8 +53,8 @@ def test_named_profile_export_survives_unix_socket(tmp_path, monkeypatch):# One socket the *.sock suffix rule catches, one only lstat can catch,# and a FIFO — none of them may fail or enter the export.- _bind_unix_socket(browser_dir / "dev-12345.sock")- _bind_unix_socket(browser_dir / "control")+ _bind_unix_socket(monkeypatch, browser_dir / "dev-12345.sock")+ _bind_unix_socket(monkeypatch, browser_dir / "control")os.mkfifo(browser_dir / "events")_patch_named_profile(monkeypatch, profiles_root, profile_dir)@@ -83,7 +78,7 @@ def test_default_profile_export_survives_unix_socket(tmp_path, monkeypatch):(profile_dir / "config.yaml").write_text("model: gpt-4\n")(sessions_dir / "log.jsonl").write_text("{}\n")- _bind_unix_socket(sessions_dir / "ipc")+ _bind_unix_socket(monkeypatch, sessions_dir / "ipc")_patch_named_profile(monkeypatch, tmp_path / "profiles", profile_dir)diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.pyindex 389385a48e6..b5cbb279aab 100644--- a/tests/hermes_cli/test_profiles.py+++ b/tests/hermes_cli/test_profiles.py@@ -201,7 +201,6 @@ class TestCreateProfile:assert (profile_dir / ".env").read_text().strip() == "KEY=val"assert (profile_dir / "SOUL.md").read_text() == "Be helpful."- @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="special files need a POSIX filesystem")def test_clone_all_does_not_copy_cron_jobs(self, profile_env):# Cron jobs are scheduled work bound to the source profile + origin channel; a clone# that inherits jobs.json fires every job twice (two gateways, same job ids).@@ -210,8 +209,19 @@ class TestCreateProfile:(default_home / "cron").mkdir()(default_home / "cron" / "jobs.json").write_text(json.dumps({"jobs": [{"id": "abc123def456"}]}))(default_home / "cron" / "output").mkdir()++ profile_dir = create_profile("coder", clone_all=True, no_alias=True)++ assert (profile_dir / "cron").is_dir()+ assert not any((profile_dir / "cron").iterdir())+ assert yaml.safe_load((profile_dir / "config.yaml").read_text())["model"] == "test"++ @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="special files need a POSIX filesystem")+ def test_clone_all_skips_special_files(self, profile_env):# A live source profile holds special files copytree cannot copy (e.g. a suffixless# agent-browser control socket); one of them must not abort the whole clone.+ default_home = profile_env / ".hermes"+ (default_home / "config.yaml").write_text("model: test")browser_dir = default_home / "home" / ".agent-browser"browser_dir.mkdir(parents=True)(browser_dir / "state.json").write_text("{}")@@ -219,9 +229,6 @@ class TestCreateProfile:profile_dir = create_profile("coder", clone_all=True, no_alias=True)- assert (profile_dir / "cron").is_dir()- assert not any((profile_dir / "cron").iterdir())- assert yaml.safe_load((profile_dir / "config.yaml").read_text())["model"] == "test"assert (profile_dir / "home" / ".agent-browser" / "state.json").is_file()assert not (profile_dir / "home" / ".agent-browser" / "control").exists()