The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(curator): restore the real skills tree when a rollback extract dies part-way
MaxFreedomPollard65e9ece96498
diff --git a/agent/curator_backup.py b/agent/curator_backup.pyindex ca0cc763625..8a65825464e 100644--- a/agent/curator_backup.py+++ b/agent/curator_backup.py@@ -541,6 +541,33 @@ def _restore_cron_skill_links(snapshot_dir: Path) -> Dict[str, Any]:+def _unstage(moved: List[Tuple[Path, Path]]) -> List[str]:+ """Move staged entries back to their original paths.++ ``shutil.move`` moves *into* an existing destination directory rather than+ replacing it, so a partially-completed extract leaves debris that would+ otherwise bury the user's real skill one level deeper+ (``skills/foo/foo/``) while the tree still looks populated. Clear whatever+ the failed extract created at each original path first. The staged copy is+ authoritative, and the pre-rollback safety snapshot is the undo handle for+ the extract's own output.++ Returns the names that could not be restored, so the caller can report an+ incomplete recovery instead of claiming the state was restored.+ """+ failed: List[str] = []+ for orig, dest in moved:+ try:+ if orig.is_dir() and not orig.is_symlink():+ shutil.rmtree(orig)+ elif orig.exists() or orig.is_symlink():+ orig.unlink()+ shutil.move(str(dest), str(orig))+ except OSError:+ failed.append(orig.name)+ return failed++def rollback(backup_id: Optional[str] = None) -> Tuple[bool, str, Optional[Path]]:"""Restore ``~/.hermes/skills/`` from a snapshot.@@ -609,11 +636,7 @@ def rollback(backup_id: Optional[str] = None) -> Tuple[bool, str, Optional[Path]moved.append((entry, dest))except OSError as e:# Best-effort rollback of the move- for orig, dest in moved:- try:- shutil.move(str(dest), str(orig))- except OSError:- pass+ _unstage(moved)try:shutil.rmtree(staged, ignore_errors=True)except OSError:@@ -638,12 +661,30 @@ def rollback(backup_id: Optional[str] = None) -> Tuple[bool, str, Optional[Path]# Python < 3.12 — no filter kwargtf.extractall(str(skills))except (OSError, tarfile.TarError) as e:- # Best-effort recover: move staged contents back- for orig, dest in moved:+ # Best-effort recover. A partial extract can leave entries the+ # original tree never had, so drop those first, otherwise the+ # "restored" tree is the user's skills plus a slice of the snapshot.+ staged_names = {orig.name for orig, _ in moved}+ for entry in list(skills.iterdir()):+ if entry.name in _EXCLUDE_TOP_LEVEL or entry.name in staged_names:+ continuetry:- shutil.move(str(dest), str(orig))+ if entry.is_dir() and not entry.is_symlink():+ shutil.rmtree(entry)+ else:+ entry.unlink()except OSError:pass+ unrestored = _unstage(moved)+ if unrestored:+ # Do not claim a clean restore we did not achieve, and keep the+ # staging dir so the entries can be recovered by hand.+ return (+ False,+ f"snapshot extract failed: {e} - could not restore "+ f"{', '.join(sorted(unrestored))}; staged copies kept at {staged}",+ None,+ )try:shutil.rmtree(staged, ignore_errors=True)except OSError:diff --git a/tests/agent/test_curator_backup.py b/tests/agent/test_curator_backup.pyindex 04256478dd0..a20d80a3b11 100644--- a/tests/agent/test_curator_backup.py+++ b/tests/agent/test_curator_backup.py@@ -392,3 +392,69 @@ def _three_ordered_snapshots(cb, skills, monkeypatch):+# ---------------------------------------------------------------------------+# A failed extract must leave the skills tree exactly as it was found+# ---------------------------------------------------------------------------++def test_rollback_recovers_cleanly_from_a_partial_extract(backup_env, monkeypatch):+ """An extract that dies part-way must restore the original tree exactly.++ ``shutil.move`` moves *into* an existing directory rather than replacing+ it, so debris from a half-finished extract buried the user's own skill one+ level deeper (``skills/alpha/alpha/``) while rollback still reported+ "state restored".+ """+ cb = backup_env["cb"]+ skills = backup_env["skills"]++ _write_skill(skills, "alpha", body="snapshot copy")+ assert cb.snapshot_skills(reason="before") is not None++ # Diverge from the snapshot so a real restore would be observable.+ _write_skill(skills, "alpha", body="current copy")+ _write_skill(skills, "beta", body="current only")++ real_open = tarfile.open++ class _DiesMidExtract:+ """Writes part of the archive, then fails like a full disk would."""++ def __init__(self, inner):+ self._inner = inner++ def getmembers(self):+ return self._inner.getmembers()++ def extractall(self, path, *args, **kwargs):+ partial = Path(path) / "alpha"+ partial.mkdir(parents=True, exist_ok=True)+ (partial / "SKILL.md").write_text("half written", encoding="utf-8")+ (Path(path) / "gamma").mkdir(parents=True, exist_ok=True)+ raise OSError(28, "No space left on device")++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self._inner.close()+ return False++ def _open(name, mode="r", *args, **kwargs):+ # Only the rollback's read is intercepted; the pre-rollback safety+ # snapshot opens for write and must keep working.+ handle = real_open(name, mode, *args, **kwargs)+ return _DiesMidExtract(handle) if mode.startswith("r") else handle++ monkeypatch.setattr(cb.tarfile, "open", _open)++ ok, msg, _ = cb.rollback()+ assert not ok++ assert not (skills / "alpha" / "alpha").exists(), \+ "staged skill was nested, not restored"+ present = sorted(+ p.name for p in skills.iterdir() if p.name not in cb._EXCLUDE_TOP_LEVEL+ )+ assert present == ["alpha", "beta"], f"tree not restored: {present}"+ assert "current copy" in (skills / "alpha" / "SKILL.md").read_text(encoding="utf-8")+ assert "current only" in (skills / "beta" / "SKILL.md").read_text(encoding="utf-8")