The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): validate keep once, and reject negative /snapshot prune counts
kshitijk4poordb3f9482e601
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 99c120df5e4..66ad325be78 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -591,8 +591,6 @@ def run_backup(args) -> bool: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``."""- if getattr(args, "keep", 0) < 0:- raise ValueError("--keep must be non-negative (0 keeps everything)")hermes_root = get_default_hermes_root()if not hermes_root.is_dir():diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 4006e6363b1..abd1a5bca0d 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -872,10 +872,11 @@ class CLICommandsMixin:from hermes_cli.backup import prune_quick_snapshotskeep = 20if len(parts) > 2:- try:- keep = int(parts[2])- except ValueError:+ # isdecimal() also rejects "-1": a negative keep would slice away the+ # newest snapshots instead of the oldest.+ if not parts[2].isdecimal():return print(f" {_t('snapshot.usage_prune')}")+ keep = int(parts[2])deleted = prune_quick_snapshots(keep=keep)print(f" {_t('snapshot.pruned', deleted=deleted, keep=keep)}")diff --git a/hermes_cli/subcommands/backup.py b/hermes_cli/subcommands/backup.pyindex 402c5343f2d..ea317bd8d6e 100644--- a/hermes_cli/subcommands/backup.py+++ b/hermes_cli/subcommands/backup.py@@ -7,10 +7,10 @@ from typing import Callabledef _non_negative_keep(value: str) -> int:- keep = int(value)- if keep < 0:- raise ArgumentTypeError("--keep must be non-negative (0 keeps everything)")- return keep+ # The one --keep validation: cmd_backup -> run_backup is the only caller.+ if not value.isdecimal():+ raise ArgumentTypeError("must be a non-negative integer (0 keeps everything)")+ return int(value)def build_backup_parser(subparsers, *, cmd_backup: Callable) -> None:diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex 89113839456..6917fa0dbbe 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -916,6 +916,27 @@ class TestValidation:class TestBackupEdgeCases:+ def test_negative_keep_is_rejected_by_backup_parser_and_snapshot_prune(self, capsys):+ """A negative keep slices away the NEWEST archives/snapshots, so both the+ ``backup --keep`` parser and ``/snapshot prune N`` refuse it."""+ import argparse+ from hermes_cli.cli_commands_mixin import CLICommandsMixin+ from hermes_cli.subcommands.backup import build_backup_parser++ parser = argparse.ArgumentParser()+ build_backup_parser(parser.add_subparsers(dest="command"), cmd_backup=lambda args: None)+ for bad in ("-1", "x"):+ with pytest.raises(SystemExit) as exc:+ parser.parse_args(["backup", "--keep", bad])+ assert exc.value.code == 2+ assert [parser.parse_args(["backup", *a]).keep for a in (["--keep", "0"], ["-k", "1"], [])] == [0, 1, 3]++ with patch("hermes_cli.backup.prune_quick_snapshots") as prune:+ CLICommandsMixin._snapshot_prune(object(), ["/snapshot", "prune", "-1"])+ prune.assert_not_called()+ CLICommandsMixin._snapshot_prune(object(), ["/snapshot", "prune", "2"])+ prune.assert_called_once_with(keep=2)+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: acron/systemd timer must never see a partial archive as success (#101096)."""diff --git a/tests/hermes_cli/test_backup_retention_validation.py b/tests/hermes_cli/test_backup_retention_validation.pydeleted file mode 100644index f5ee0c50156..00000000000--- a/tests/hermes_cli/test_backup_retention_validation.py+++ /dev/null@@ -1,42 +0,0 @@-"""Invalid full-backup retention must never delete a recovery archive."""--import argparse-import zipfile--import pytest---def test_full_backup_refuses_negative_retention_before_touching_archives(tmp_path, monkeypatch):- from hermes_cli.backup import run_backup-- home = tmp_path / "home"- home.mkdir()- (home / "config.yaml").write_text("memory:\n provider: null\n", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))- output = tmp_path / "exports"- output.mkdir()- archive = output / "hermes-backup-2000-01-01-000000.zip"- with zipfile.ZipFile(archive, "w") as zf:- zf.writestr("config.yaml", "previous recovery settings")- original = archive.read_bytes()-- with pytest.raises(ValueError, match="keep"):- run_backup(argparse.Namespace(output=str(output), keep=-1))-- assert list(output.iterdir()) == [archive]- assert archive.read_bytes() == original---def test_backup_parser_rejects_negative_retention_and_preserves_supported_values():- from hermes_cli.subcommands.backup import build_backup_parser-- parser = argparse.ArgumentParser()- build_backup_parser(parser.add_subparsers(dest="command"), cmd_backup=lambda args: None)-- with pytest.raises(SystemExit) as exc:- parser.parse_args(["backup", "--keep", "-1"])- assert exc.value.code == 2- assert parser.parse_args(["backup", "--keep", "0"]).keep == 0- assert parser.parse_args(["backup", "--keep", "1"]).keep == 1- assert parser.parse_args(["backup"]).keep == 3