The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): batch rollback undoes every file it wrote into an adopted dir
kshitijk4poor4638864a7438
diff --git a/tests/tools/test_skill_create_occupied_directory.py b/tests/tools/test_skill_create_occupied_directory.pyindex ec30c9947cf..c1dedef7ca5 100644--- a/tests/tools/test_skill_create_occupied_directory.py+++ b/tests/tools/test_skill_create_occupied_directory.py@@ -40,8 +40,8 @@ def test_occupied_directory_is_preserved_when_scan_blocks(tmp_path):data.write_bytes(b"keep me")result = _create_skill("new-skill", VALID_CONTENT)- # An EMPTY pre-existing directory (leftover of an earlier failed create) is a valid target,- # but a blocked scan removes only what create wrote and leaves the directory in place.+ # An EMPTY pre-existing directory (leftover of an earlier failed create) is a valid target;+ # a blocked scan removes what create wrote and the then-empty dir (rmdir, never rmtree).empty = tmp_path / "empty-skill"empty.mkdir()empty_result = _create_skill("empty-skill", VALID_CONTENT)@@ -67,8 +67,7 @@ def test_occupied_directory_is_preserved_when_scan_blocks(tmp_path):assert not (target / "SKILL.md").exists()assert empty_result["success"] is False- assert empty.is_dir()- assert not any(empty.iterdir())+ assert not empty.exists()assert fresh_result["success"] is Falseassert not (tmp_path / "fresh-skill").exists()diff --git a/tests/tools/test_skill_manage_batch.py b/tests/tools/test_skill_manage_batch.pyindex a676c99158b..719b8d91db7 100644--- a/tests/tools/test_skill_manage_batch.py+++ b/tests/tools/test_skill_manage_batch.py@@ -180,8 +180,8 @@ class TestSkillManageBatch(unittest.TestCase):def test_cross_skill_batch_and_rollback(self):"""Ops may target DIFFERENT skills; a late failure rolls backevery touched skill, including removing a batch-created one — but a dir- that pre-dated the batch (empty leftover create adopted) is never rmtree'd,- only the SKILL.md the batch wrote is undone."""+ that pre-dated the batch (empty leftover create adopted) is never rmtree'd:+ every file the BATCH wrote there is undone, anything else survives."""self._call("alpha", [{"action": "create", "content": SK.format(n="alpha")}])gamma = os.path.join(self.home, "skills", "gamma")os.mkdir(gamma) # empty pre-existing dir with no SKILL.md: create adopts it@@ -189,7 +189,8 @@ class TestSkillManageBatch(unittest.TestCase):def drop_file_before_failing_op(payload, **kw):if payload.get("action") == "write_file": # something lands mid-batch- open(os.path.join(gamma, "dropped.txt"), "w").write("keep me")+ with open(os.path.join(gamma, "dropped.txt"), "w", encoding="utf-8") as fh:+ fh.write("keep me")return real_from(payload, **kw)with patch.object(self.smt, "_skill_manage_from", side_effect=drop_file_before_failing_op):@@ -198,20 +199,38 @@ class TestSkillManageBatch(unittest.TestCase):"old_string": "Step 1.", "new_string": "Step A."},{"name": "beta", "action": "create", "content": SK.format(n="beta")},{"name": "gamma", "action": "create", "content": SK.format(n="gamma")},+ {"name": "gamma", "action": "write_file",+ "file_path": "references/a.md", "file_content": "a"},{"name": "beta", "action": "write_file","file_path": "bad/nope.md", "file_content": "x"},]))self.assertFalse(r["success"])- self.assertEqual(r["failed_index"], 3)+ self.assertEqual(r["failed_index"], 4)# alpha's patch undone; beta (batch-created) removed entirely.- content = open(os.path.join(self.home, "skills", "alpha", "SKILL.md")).read()+ with open(os.path.join(self.home, "skills", "alpha", "SKILL.md"), encoding="utf-8") as fh:+ content = fh.read()self.assertIn("Step 1.", content)self.assertNotIn("Step A.", content)self.assertFalse(os.path.exists(os.path.join(self.home, "skills", "beta")))- # gamma pre-existed: its SKILL.md is undone, the dir and the foreign file survive.+ # gamma pre-existed: SKILL.md and the batch's references/a.md are undone (with the+ # dir that held it); the dir and the foreign file survive.self.assertTrue(os.path.isdir(gamma))- self.assertFalse(os.path.exists(os.path.join(gamma, "SKILL.md")))- self.assertEqual(open(os.path.join(gamma, "dropped.txt")).read(), "keep me")+ with open(os.path.join(gamma, "dropped.txt"), encoding="utf-8") as fh:+ self.assertEqual(fh.read(), "keep me")+ self.assertEqual(os.listdir(gamma), ["dropped.txt"])+ # Without a foreign file the adopted dir is left as create found it (empty -> gone),+ # so a retry create is not refused as "occupied".+ delta = os.path.join(self.home, "skills", "delta")+ os.mkdir(delta)+ r = self._call("delta", [+ {"action": "create", "content": SK.format(n="delta")},+ {"action": "write_file", "file_path": "references/a.md", "file_content": "a"},+ {"action": "write_file", "file_path": "bad/nope.md", "file_content": "x"},+ ])+ self.assertFalse(r["success"])+ self.assertFalse(os.path.exists(delta))+ r = self._call("delta", [{"action": "create", "content": SK.format(n="delta")}])+ self.assertTrue(r["success"], r)def test_failed_restore_never_destroys_the_skill(self):"""Rollback used to rmtree the live skill directory BEFOREdiff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex 79f9543658a..fab23c532b9 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -134,7 +134,7 @@ def _validate_batch_ops(operations, default_name, tool_error):return names, None-def _snapshot_skills(names, snap_root, find_skill, create_targets=None):+def _snapshot_skills(names, snap_root, find_skill, create_targets):"""Copy every touched skill aside. Returns (snapshots, None) or (None, error_text).``create_targets`` maps a name with no skill yet to the dir its ``create`` op will use.@@ -150,12 +150,12 @@ def _snapshot_skills(names, snap_root, find_skill, create_targets=None):shutil.copytree(pre_dir, snap)except Exception as exc: # noqa: BLE001 — no snapshot, no atomicityreturn None, f"Could not snapshot '{nm}' for atomic batch: {exc}"- target = (create_targets or {}).get(nm) if pre is None else None+ target = create_targets.get(nm) if pre is None else Nonesnapshots[nm] = (pre_dir, snap, target is not None and target.is_dir())return snapshots, None-def _restore_snapshot(pre_dir, snap, post_dir, dir_pre_existed=False) -> None:+def _restore_snapshot(pre_dir, snap, post_dir, dir_pre_existed=False, written=()) -> None:post_exists = post_dir is not None and post_dir.is_dir()if snap is None:if not post_exists:@@ -163,10 +163,18 @@ def _restore_snapshot(pre_dir, snap, post_dir, dir_pre_existed=False) -> None:if not dir_pre_existed: # Batch created this skill: remove the partial result.shutil.rmtree(post_dir)return- # The dir predates the batch (adopted empty leftover): undo only the SKILL.md the batch- # wrote and drop the dir only if that leaves it empty — never anything foreign.- with suppress(OSError):- (post_dir / "SKILL.md").unlink()+ # The dir predates the batch (adopted empty leftover): unlink exactly the files the+ # batch wrote there, then rmdir() the now-empty dirs up to and including the skill dir.+ # rmdir() fails on anything left, so a file that landed out-of-band survives.+ for rel in ("SKILL.md", *written):+ target = post_dir / rel+ with suppress(OSError):+ target.unlink()+ for parent in target.parents:+ if parent == post_dir or not parent.is_relative_to(post_dir):+ break+ with suppress(OSError):+ parent.rmdir()with suppress(OSError):post_dir.rmdir()return@@ -188,13 +196,17 @@ def _restore_snapshot(pre_dir, snap, post_dir, dir_pre_existed=False) -> None:shutil.rmtree(aside, ignore_errors=True)-def _rollback(snapshots, find_skill):- """Restore every snapshot. Returns (note, failed)."""+def _rollback(snapshots, find_skill, results):+ """Restore every snapshot. ``results`` are the ops applied so far (their name/file_path+ tell an adopted dir's rollback which files were the batch's). Returns (note, failed)."""notes = []for nm, (pre_dir, snap, dir_pre_existed) in snapshots.items():+ written = [posixpath.normpath(r["file_path"].lstrip("/")) for r in results+ if r["name"] == nm and r["action"] == "write_file" and r["file_path"]]try:post = find_skill(nm)- _restore_snapshot(pre_dir, snap, Path(post["path"]) if post else None, dir_pre_existed)+ _restore_snapshot(pre_dir, snap, Path(post["path"]) if post else None,+ dir_pre_existed, written)except Exception as exc: # noqa: BLE001notes.append(f"ROLLBACK FAILED for '{nm}' ({exc})"+ (f"; snapshot preserved at '{snap}'" if snap is not None else ""))@@ -262,7 +274,7 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nonexcept Exception: # noqa: BLE001parsed = {"success": False, "error": "unparseable op result"}if not parsed.get("success"):- note, rollback_failed = _rollback(snapshots, _smt._find_skill)+ note, rollback_failed = _rollback(snapshots, _smt._find_skill, results)fail = { # key order is wire-visible"success": False,"error": (f"operations[{i}] ({op['action']} on '{names[i]}') failed: "diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex 00111e4ff07..af7dc12d71b 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -428,11 +428,10 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Anif existing := _find_skill(name):return _err(f"A skill named '{name}' already exists at {existing['path']}.")skill_dir = _resolve_skill_dir(name, category)- from hermes_constants import assert_named_profile_home_live- assert_named_profile_home_live(skill_dir)+ from hermes_constants import mkdir_under_hermes_home+ mkdir_under_hermes_home(skill_dir.parent)try:- skill_dir.mkdir(parents=True, exist_ok=False)- created_dir = True+ skill_dir.mkdir(exist_ok=False)except FileExistsError:# mkdir raised EEXIST for a file, symlink (live or dangling) or dir alike; only an EMPTY# real directory (leftover of an earlier create whose SKILL.md write failed) may be used.@@ -445,12 +444,10 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Anif not usable:return _err(f"Cannot create skill '{name}': {skill_dir} already exists (not an empty ""directory, or unreadable). Choose another name, or move/remove that path and retry.")- created_dir = Falseskill_md = skill_dir / "SKILL.md"if guard := _guarded_write(name, skill_dir, skill_md, "create", "SKILL.md", content):- if created_dir: # rmdir, not rmtree: an adopted leftover dir and anything foreign stay- with suppress(OSError):- skill_dir.rmdir()+ with suppress(OSError): # rmdir, not rmtree: only an empty dir goes, anything foreign stays+ skill_dir.rmdir()return guardroot = _skills_dir() # display relative under the profile dir; absolute under skills.create_dirdisplay = skill_dir.relative_to(root) if skill_dir.is_relative_to(root) else skill_dir