The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(backup): restore import members atomically so a failed import can't erase config
briandevanse88c9f0ef29c
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex e5c201d49e6..4a69bb667f9 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -13,6 +13,7 @@ import loggingimport osimport shutilimport sqlite3+import statimport sysimport tempfileimport threading@@ -24,6 +25,7 @@ from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom hermes_constants import get_default_hermes_root, get_hermes_home, display_hermes_home+from utils import atomic_replace# Shared formatter; the private alias is kept because claw.py and the backup# tests import ``_format_size`` from this module.@@ -849,6 +851,93 @@ def _detect_prefix(zf: zipfile.ZipFile) -> str:return ""+def _default_new_file_mode() -> Optional[int]:+ """Return the mode ``open(path, "wb")`` gives a file it has to create.++ ``tempfile.mkstemp`` always creates at 0600, so staging an import through a+ temp file would tighten every *newly created* file to owner-only — the same+ hazard ``utils._restore_file_mode`` documents for Docker/NAS volume mounts+ that rely on broader permissions. The umask can only be read by setting it,+ so this is resolved once per import rather than once per member. The probe+ installs a *restrictive* mask rather than 0 so that anything another thread+ creates inside the two-syscall window is owner-only, never world-writable.+ Returns ``None`` if the umask cannot be read, in which case the caller+ leaves mkstemp's mode alone.+ """+ try:+ current = os.umask(0o077)+ os.umask(current)+ except OSError:+ return None+ return 0o666 & ~current+++def _extract_member_atomically(+ zf: zipfile.ZipFile,+ member: str,+ target: Path,+ new_file_mode: Optional[int] = None,+) -> None:+ """Restore one zip member onto *target* with no truncation window.++ ``open(target, "wb")`` truncates the user's existing file to zero *before*+ any replacement bytes exist. A Ctrl-C, an ENOSPC, a corrupt member, or a+ crash between the truncate and the write therefore leaves that file empty+ with nothing behind it — during ``hermes import``, which is the+ disaster-recovery path a user reaches for *because* they already lost+ something. Staging into the target's own directory and publishing with a+ rename means the target only ever moves from its old contents to the+ complete new contents.++ ``atomic_replace`` rather than a bare ``os.replace``: it resolves a+ symlinked target first, so a deployment that links ``config.yaml`` into a+ dotfiles repo keeps the link instead of having it silently swapped for a+ regular file (GitHub #16743), and it falls back to copy/fsync/unlink on+ ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.++ Permission bits are carried across the replace so routing through mkstemp+ does not change the mode the caller would otherwise have produced. The+ temp file is removed on any failure so a partial import leaves no residue.+ """+ mode = new_file_mode+ try:+ mode = stat.S_IMODE(target.stat().st_mode)+ except OSError:+ # Target does not exist (or cannot be stat'd) — keep the create-mode.+ pass++ # Truncate the stem: mkstemp adds ~16 characters, and a member already near+ # NAME_MAX would otherwise fail here on a write that used to succeed.+ fd, tmp_name = tempfile.mkstemp(+ dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial"+ )+ try:+ with os.fdopen(fd, "wb") as dst:+ if mode is not None and hasattr(os, "fchmod"):+ # Apply before the replace so the target never transits through+ # mkstemp's 0600. fchmod is Unix-only; Windows uses the+ # post-replace chmod below.+ os.fchmod(dst.fileno(), mode)+ # Stream instead of ``src.read()``: a multi-gigabyte state.db member+ # must not be held in memory in one piece.+ with zf.open(member) as src:+ shutil.copyfileobj(src, dst)+ dst.flush()+ os.fsync(dst.fileno())+ real_path = atomic_replace(tmp_name, target)+ if mode is not None and not hasattr(os, "fchmod"):+ try:+ os.chmod(real_path, mode)+ except OSError:+ pass+ except BaseException:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ raise++def run_import(args) -> None:"""Restore a Hermes backup from a zip file."""zip_path = Path(args.zipfile).expanduser().resolve()@@ -907,6 +996,9 @@ def run_import(args) -> None:restored_external = 0skipped_runtime: list[str] = []home_dir = Path.home().resolve()+ # Resolved once: every member is published via a temp file, and mkstemp+ # would otherwise create newly restored files as 0600.+ new_file_mode = _default_new_file_mode()t0 = time.monotonic()for member in members:@@ -926,8 +1018,7 @@ def run_import(args) -> None:continuetry:target.parent.mkdir(parents=True, exist_ok=True)- with zf.open(member) as src, open(target, "wb") as dst:- dst.write(src.read())+ _extract_member_atomically(zf, member, target, new_file_mode)# External provider configs commonly hold credentials.if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:try:@@ -972,8 +1063,7 @@ def run_import(args) -> None:try:target.parent.mkdir(parents=True, exist_ok=True)- with zf.open(member) as src, open(target, "wb") as dst:- dst.write(src.read())+ _extract_member_atomically(zf, member, target, new_file_mode)if target.name in _SECRET_FILE_NAMES:os.chmod(target, 0o600)restored += 1diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex 31784abf641..8645ce077af 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -652,6 +652,189 @@ class TestImportEdgeCases:assert (hermes_home / "sessions" / "s0599.json").exists()+class _ExplodingMember:+ """Zip member whose stream dies mid-restore (ENOSPC / corrupt member).++ Both the pre-fix ``dst.write(src.read())`` and the atomic+ ``shutil.copyfileobj`` path pull bytes through ``read()``, so injecting+ here exercises whichever implementation is in the tree.+ """++ def __enter__(self):+ return self++ def __exit__(self, *exc_info):+ return False++ def read(self, *args):+ raise OSError(28, "No space left on device")++ def close(self):+ pass+++def _break_member(monkeypatch, failing_member: str) -> None:+ """Make ``ZipFile.open`` hand back a dying stream for one member only."""+ real_open = zipfile.ZipFile.open++ def _patched(self, name, *args, **kwargs):+ filename = name.filename if isinstance(name, zipfile.ZipInfo) else name+ if filename == failing_member:+ return _ExplodingMember()+ return real_open(self, name, *args, **kwargs)++ monkeypatch.setattr(zipfile.ZipFile, "open", _patched)+++class TestImportAtomicWrites:+ """`hermes import` must never leave a user's file truncated.++ The pre-fix code did ``open(target, "wb")`` then ``dst.write(src.read())``,+ which zeroes the existing file *before* any replacement bytes exist. These+ tests pin the invariant for both restore branches: the HERMES_HOME branch+ and the ``_external/`` branch that writes into third-party configs under+ the user's home.+ """++ def _zip(self, zip_path: Path, files: dict) -> None:+ with zipfile.ZipFile(zip_path, "w") as zf:+ for name, content in files.items():+ zf.writestr(name, content)++ def test_failed_member_leaves_existing_file_intact(self, tmp_path, monkeypatch):+ """A dying member must not destroy the file it was replacing."""+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ original = "model: original\napi_key: keep-me\n"+ (hermes_home / "config.yaml").write_text(original)+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ zip_path = tmp_path / "backup.zip"+ self._zip(zip_path, {"config.yaml": "model: replacement\n", "state.db": ""})+ _break_member(monkeypatch, "config.yaml")++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ # Pre-fix this file is 0 bytes: the truncate landed, the write did not.+ assert (hermes_home / "config.yaml").read_text() == original+ # And the aborted write must not litter the directory it staged in.+ assert list(hermes_home.glob(".config.yaml.*")) == []++ def test_failed_external_member_leaves_existing_file_intact(self, tmp_path, monkeypatch):+ """Same invariant on the `_external/` branch, which writes outside HERMES_HOME."""+ dst_home = tmp_path / "dst"+ dst_home.mkdir()+ hermes_home = dst_home / ".hermes"+ hermes_home.mkdir()+ honcho = dst_home / ".honcho"+ honcho.mkdir()+ original = '{"peer":"original"}'+ (honcho / "config.json").write_text(original)++ zip_path = tmp_path / "backup.zip"+ self._zip(zip_path, {+ "config.yaml": "model: {}\n",+ "_external/.honcho/config.json": '{"peer":"replacement"}',+ })++ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: dst_home)+ _break_member(monkeypatch, "_external/.honcho/config.json")++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ assert (honcho / "config.json").read_text() == original+ assert list(honcho.glob(".config.json.*")) == []++ @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks")+ def test_symlinked_target_keeps_its_symlink(self, tmp_path, monkeypatch):+ """A symlinked target is written through, not replaced by a regular file.++ Guards the atomic rewrite against a naive ``os.replace``, which would+ detach dotfiles-managed deployments (GitHub #16743). ``atomic_replace``+ resolves the link first.+ """+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ store = hermes_home / "store"+ store.mkdir()+ real = store / "config.yaml"+ real.write_text("model: original\n")+ link = hermes_home / "config.yaml"+ link.symlink_to(real)++ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ zip_path = tmp_path / "backup.zip"+ self._zip(zip_path, {"config.yaml": "model: restored\n", "state.db": ""})++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ assert link.is_symlink(), "import replaced the symlink with a regular file"+ assert real.read_text() == "model: restored\n"++ @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks")+ def test_symlinked_external_target_keeps_its_symlink(self, tmp_path, monkeypatch):+ """Same guard on the `_external/` branch — the realistic dotfiles case."""+ dst_home = tmp_path / "dst"+ dst_home.mkdir()+ hermes_home = dst_home / ".hermes"+ hermes_home.mkdir()+ dotfiles = dst_home / "dotfiles"+ dotfiles.mkdir()+ real = dotfiles / "honcho.json"+ real.write_text('{"peer":"original"}')+ honcho = dst_home / ".honcho"+ honcho.mkdir()+ link = honcho / "config.json"+ link.symlink_to(real)++ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: dst_home)++ zip_path = tmp_path / "backup.zip"+ self._zip(zip_path, {+ "config.yaml": "model: {}\n",+ "_external/.honcho/config.json": '{"peer":"restored"}',+ })++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ assert link.is_symlink(), "import replaced the symlink with a regular file"+ assert real.read_text() == '{"peer":"restored"}'++ @pytest.mark.skipif(os.name != "posix", reason="POSIX file modes")+ def test_restore_preserves_existing_file_mode(self, tmp_path, monkeypatch):+ """Staging through mkstemp must not silently tighten restored files to 0600.++ ``tempfile.mkstemp`` creates at 0600; the mode of the file being+ replaced has to survive the publish, or Docker/NAS installs that rely+ on broader permissions break on restore.+ """+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ target = hermes_home / "config.yaml"+ target.write_text("model: original\n")+ os.chmod(target, 0o644)+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ zip_path = tmp_path / "backup.zip"+ self._zip(zip_path, {"config.yaml": "model: restored\n", "state.db": ""})++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ assert target.read_text() == "model: restored\n"+ assert (target.stat().st_mode & 0o777) == 0o644++# ---------------------------------------------------------------------------# Profile restoration tests# ---------------------------------------------------------------------------