Skip to content

The agent that grows with you

fix(backup): exit non-zero when a full backup is incomplete

leomcamiloccb3d968cedc
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 2b3fe560136..a5918f18a7d 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -663,8 +663,14 @@ def _collect_external_entries() -> tuple[list[tuple[Path, str]], list[str]]:
return external_to_add, skipped_external
-def run_backup(args) -> None:
- """Create a zip backup of the Hermes home directory."""
+def run_backup(args) -> bool:
+ """Create a zip backup of the Hermes home directory.
+
+ True when every selected file landed in the archive (or there was nothing to back up); False
+ when the zip was written but is incomplete — it is kept so the rest can still be restored, and
+ the caller turns False into exit status 1 so a cron/systemd timer never publishes a "successful"
+ archive that is missing state.db. Hard failures keep raising ``SystemExit``.
+ """
hermes_root = get_default_hermes_root()
if not hermes_root.is_dir():
@@ -673,13 +679,13 @@ def run_backup(args) -> None:
try:
with _backup_operation_lock(hermes_root):
- _run_backup_locked(args, hermes_root)
+ return _run_backup_locked(args, hermes_root)
except BackupInProgressError as exc:
print(f"Error: {exc}")
raise SystemExit(2) from exc
-def _run_backup_locked(args, hermes_root: Path) -> None:
+def _run_backup_locked(args, hermes_root: Path) -> bool:
"""Write a full backup while the cross-process backup slot is held."""
out_path = _resolve_backup_output_path(args.output)
scan_started = time.monotonic()
@@ -691,7 +697,7 @@ def _run_backup_locked(args, hermes_root: Path) -> None:
if not files_to_add and not external_to_add:
logger.info("backup phase=scan status=empty duration_ms=%.1f", (time.monotonic() - scan_started) * 1000)
print("No files to back up.")
- return
+ return True
file_count = len(files_to_add) + len(external_to_add)
logger.info("backup phase=scan status=complete duration_ms=%.1f files=%d",
@@ -736,7 +742,8 @@ def _run_backup_locked(args, hermes_root: Path) -> None:
if skipped_dirs:
print("\n Excluded directories:\n" + "\n".join(f" {d}/" for d in sorted(skipped_dirs)))
if errors:
- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")
+ _print_capped(f"\n Archive kept, but {len(errors)} file(s) could not be added (exit status 1):",
+ errors, " ")
else:
print(f"\nRestore with: hermes import {out_path.name}")
keep = getattr(args, "keep", 0) # 0 / absent: never prune (non-CLI callers)
@@ -744,6 +751,7 @@ def _run_backup_locked(args, hermes_root: Path) -> None:
pruned = _prune_prefixed_zips(out_path.parent, _RUN_BACKUP_PREFIX, keep, "backup")
if pruned:
print(f" Pruned {pruned} older {_RUN_BACKUP_PREFIX}*.zip (keeping {keep}).")
+ return not errors
# --- Import ---
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 36d83e206f0..3eee4d8c5b5 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2224,7 +2224,10 @@ def cmd_backup(args):
"""Back up Hermes home directory to a zip file."""
from hermes_cli import backup
- (backup.run_quick_backup if getattr(args, "quick", False) else backup.run_backup)(args)
+ if getattr(args, "quick", False):
+ backup.run_quick_backup(args)
+ elif backup.run_backup(args) is False:
+ raise SystemExit(1) # archive written but incomplete: never shell-success for a timer
def _print_version_info(*, check_updates: bool = True) -> None:
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 5b438e953fb..b22f68a5f63 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -736,6 +736,32 @@ class TestValidation:
class TestBackupEdgeCases:
+ def test_incomplete_archive_is_kept_but_reported_as_failure(self, tmp_path, monkeypatch, capsys):
+ """A file that cannot be read is skipped, the zip still lands, and the CLI exits 1: a
+ cron/systemd timer must never see a partial archive as success (#101096)."""
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ _make_hermes_tree(hermes_home)
+ unreadable = hermes_home / "skills" / "locked.md"
+ unreadable.write_text("secret\n")
+ unreadable.chmod(0)
+ if os.access(unreadable, os.R_OK):
+ pytest.skip("running as root: chmod 0 does not make the file unreadable")
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ out_zip = tmp_path / "out.zip"
+
+ from hermes_cli.backup import run_backup
+ from hermes_cli.main import cmd_backup
+
+ assert run_backup(Namespace(output=str(out_zip))) is False
+ assert out_zip.exists()
+ assert "Backup incomplete" in capsys.readouterr().out
+ with pytest.raises(SystemExit) as exc:
+ cmd_backup(Namespace(output=str(tmp_path / "out2.zip"), quick=False))
+ assert exc.value.code == 1
+ unreadable.chmod(0o600)
+ assert run_backup(Namespace(output=str(tmp_path / "out4.zip"))) is True
def test_empty_hermes_home(self, tmp_path, monkeypatch):
"""Backup handles empty hermes home (no files to back up)."""
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index 4aa9fb5ed31..992de4694cc 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1039,6 +1039,8 @@ Create a zip archive of your Hermes configuration, skills, sessions, and data. T
The backup uses SQLite's `backup()` API for safe copying, so it works correctly even when Hermes is running (WAL-mode safe).
+**Exit status:** `0` only when every selected file landed in the archive. If some files could not be added (`Backup incomplete: …`), the zip is kept so the rest can still be restored, but the command exits `1` — a cron or systemd timer will not report a partial archive as success. `2` means another backup was already running.
+
**What's excluded from the zip:**
- `*.db-wal`, `*.db-shm`, `*.db-journal` — SQLite's WAL / shared-memory / journal sidecars. The `*.db` file already got a consistent snapshot via `sqlite3.backup()`; shipping the live sidecars alongside it would let a restore see a half-committed state.