Skip to content

The agent that grows with you

fix(curator): retain staging after failed rollback recovery

liuzikaiie8e56bc8422a
diff --git a/agent/curator_backup.py b/agent/curator_backup.py
index 5403c87214f..565f2e2ba34 100644
--- a/agent/curator_backup.py
+++ b/agent/curator_backup.py
@@ -332,14 +332,16 @@ def _remove_entry(entry: Path) -> None:
entry.unlink()
-def _restore_excluded_subtrees(staged: Path, skills: Path) -> None:
+def _restore_excluded_subtrees(staged: Path, skills: Path) -> List[str]:
"""Move excluded entries (nested ``.git``/``.hub``/...) from *staged* back under *skills* after a successful extract.
Snapshots never contain these, so the staged copy of the live tree is the only source. ``.git`` may be a dir or a file
(submodule / worktree ``gitdir:`` pointer) — both are moved. Best-effort and conditional: an entry is carried only when
its parent skill dir was restored and nothing sits at the target. If the target snapshot predates the skill, the entry
- is dropped with the staging dir rather than left orphaned; the safety snapshot excludes these paths too, so not undoable."""
+ is dropped with the staging dir rather than left orphaned; the safety snapshot excludes these paths too, so not undoable.
+ Returns entries whose move failed, so their only surviving copies stay staged for recovery."""
from tools.skill_ledger import TRANSIENT_DIRS
+ failed: List[str] = []
for dirpath, dirnames, filenames in os.walk(staged):
carried = [Path(dirpath) / n for n in filenames if n in _EXCLUDE_TOP_LEVEL]
carried += [Path(dirpath) / n for n in dirnames if n in _EXCLUDE_TOP_LEVEL or n in TRANSIENT_DIRS]
@@ -349,8 +351,10 @@ def _restore_excluded_subtrees(staged: Path, skills: Path) -> None:
try:
shutil.move(str(src), str(dest))
except OSError as e:
+ failed.append(str(src.relative_to(staged)))
logger.debug("Could not restore excluded entry %s: %s", src, e)
dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_TOP_LEVEL and d not in TRANSIENT_DIRS]
+ return failed
def _unstage(moved: List[Tuple[Path, Path]]) -> List[str]:
@@ -418,7 +422,10 @@ def rollback(backup_id: Optional[str] = None) -> Tuple[bool, str, Optional[Path]
shutil.move(str(entry), str(staged / entry.name))
moved.append((entry, staged / entry.name))
except OSError as e:
- _unstage(moved)
+ unrestored = _unstage(moved)
+ if unrestored:
+ return (False, f"failed to stage current skills: {e} - could not restore "
+ f"{', '.join(sorted(unrestored))}; staged copies kept at {staged}", None)
shutil.rmtree(staged, ignore_errors=True)
return (False, f"failed to stage current skills: {e}", None)
@@ -447,7 +454,10 @@ def rollback(backup_id: Optional[str] = None) -> Tuple[bool, str, Optional[Path]
# Snapshots never contain excluded subtrees (nested ``.git``, ``.hub``, ...), so carry them over from the staged live tree
# (top-level ``.git`` is never staged). Then staging is done; the undo handle is the safety snapshot.
- _restore_excluded_subtrees(staged, skills)
+ unrestored = _restore_excluded_subtrees(staged, skills)
+ if unrestored:
+ return (False, "snapshot extracted but could not restore excluded entries "
+ f"{', '.join(sorted(unrestored))}; staged copies kept at {staged}", None)
shutil.rmtree(staged, ignore_errors=True)
# Cron reconciliation failures don't fail the rollback — the skills tree (the main guarantee) is already restored.
diff --git a/tests/agent/test_curator_rollback_staging.py b/tests/agent/test_curator_rollback_staging.py
new file mode 100644
index 00000000000..83e587431a9
--- /dev/null
+++ b/tests/agent/test_curator_rollback_staging.py
@@ -0,0 +1,95 @@
+"""Failed recovery must retain the staged files omitted from safety snapshots."""
+
+from pathlib import Path
+
+import pytest
+
+
[email protected]("failure", ["staging", "carry"])
[email protected]("metadata_kind", ["directory", "pointer"])
+def test_failed_rollback_keeps_unrestored_metadata(
+ tmp_path, monkeypatch, failure, metadata_kind
+):
+ home = tmp_path / "home"
+ skills = home / "skills"
+ skills.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ from agent import curator_backup as curator
+
+ for name in ("alpha", "beta"):
+ skill = skills / name
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(
+ f"# {name}\nSnapshot content\n", encoding="utf-8"
+ )
+ target = curator.snapshot_skills()
+ assert target is not None
+ expected = {}
+ for name in ("alpha", "beta"):
+ skill = skills / name
+ metadata = skill / ".git"
+ if metadata_kind == "directory":
+ metadata.mkdir()
+ metadata /= "local-history"
+ expected[name] = f"unpublished metadata for {name}".encode()
+ metadata.write_bytes(expected[name])
+ (skill / "SKILL.md").write_text("Current content\n", encoding="utf-8")
+
+ real_move = curator.shutil.move
+ staged_names = []
+
+ def fail_move(source, destination, *args, **kwargs):
+ source, destination = Path(source), Path(destination)
+ if failure == "carry" and source.name == ".git":
+ raise PermissionError("injected metadata move failure")
+ if failure == "staging":
+ if source.parent == skills:
+ if staged_names:
+ raise PermissionError("injected staging failure")
+ result = real_move(source, destination, *args, **kwargs)
+ staged_names.append(source.name)
+ return result
+ if source.parent.name.startswith(".rollback-staging-"):
+ raise PermissionError("injected recovery move failure")
+ return real_move(source, destination, *args, **kwargs)
+
+ monkeypatch.setattr(curator.shutil, "move", fail_move)
+ ok, message, restored = curator.rollback(target.name)
+
+ assert not ok
+ assert restored is None
+ staging = list((skills / ".curator_backups").glob(".rollback-staging-*"))
+ assert len(staging) == 1
+ assert str(staging[0]) in message
+ for name, content in expected.items():
+ relative = Path(name) / ".git"
+ if metadata_kind == "directory":
+ relative /= "local-history"
+ copies = [root / relative for root in (skills, staging[0])]
+ assert any(path.is_file() and path.read_bytes() == content for path in copies)
+
+
+def test_successful_rollback_restores_metadata_and_removes_staging(
+ tmp_path, monkeypatch
+):
+ home = tmp_path / "home"
+ skill = home / "skills" / "alpha"
+ skill.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ from agent import curator_backup as curator
+
+ instructions = skill / "SKILL.md"
+ instructions.write_text("Snapshot content\n", encoding="utf-8")
+ target = curator.snapshot_skills()
+ assert target is not None
+ instructions.write_text("Current content\n", encoding="utf-8")
+ (skill / ".git").write_text("gitdir: /local/worktree\n", encoding="utf-8")
+
+ ok, _message, restored = curator.rollback(target.name)
+
+ assert ok and restored == target
+ assert instructions.read_text(encoding="utf-8-sig") == "Snapshot content\n"
+ assert (skill / ".git").read_text(
+ encoding="utf-8-sig"
+ ) == "gitdir: /local/worktree\n"
+ assert not list((skill.parent / ".curator_backups").glob(".rollback-staging-*"))