Skip to content

The agent that grows with you

fix(skills): batch rollback never rmtree()s a dir that pre-dated the batch

kshitijk4poorfb4dbf77fcb9
diff --git a/tests/tools/test_skill_manage_batch.py b/tests/tools/test_skill_manage_batch.py
index 714096fd86c..252b9b8c8f4 100644
--- a/tests/tools/test_skill_manage_batch.py
+++ b/tests/tools/test_skill_manage_batch.py
@@ -170,22 +170,40 @@ class TestSkillManageBatch(unittest.TestCase):
def test_cross_skill_batch_and_rollback(self):
"""Ops may target DIFFERENT skills; a late failure rolls back
- every touched skill, including removing a batch-created one."""
+ every 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."""
self._call("alpha", [{"action": "create", "content": SK.format(n="alpha")}])
- r = json.loads(self.smt.skill_manage(action="", name="", operations=[
- {"name": "alpha", "action": "patch",
- "old_string": "Step 1.", "new_string": "Step A."},
- {"name": "beta", "action": "create", "content": SK.format(n="beta")},
- {"name": "beta", "action": "write_file",
- "file_path": "bad/nope.md", "file_content": "x"},
- ]))
+ gamma = os.path.join(self.home, "skills", "gamma")
+ os.mkdir(gamma) # empty pre-existing dir with no SKILL.md: create adopts it
+ real_from = self.smt._skill_manage_from
+
+ 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")
+ return real_from(payload, **kw)
+
+ from unittest.mock import patch as _patch
+ with _patch.object(self.smt, "_skill_manage_from", side_effect=drop_file_before_failing_op):
+ r = json.loads(self.smt.skill_manage(action="", name="", operations=[
+ {"name": "alpha", "action": "patch",
+ "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": "beta", "action": "write_file",
+ "file_path": "bad/nope.md", "file_content": "x"},
+ ]))
self.assertFalse(r["success"])
- self.assertEqual(r["failed_index"], 2)
+ self.assertEqual(r["failed_index"], 3)
# alpha's patch undone; beta (batch-created) removed entirely.
content = open(os.path.join(self.home, "skills", "alpha", "SKILL.md")).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.
+ 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")
def test_failed_restore_never_destroys_the_skill(self):
"""Rollback used to rmtree the live skill directory BEFORE
diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.py
index f64b2080a87..1e36f0ca52d 100644
--- a/tools/skill_manager_batch.py
+++ b/tools/skill_manager_batch.py
@@ -2,6 +2,7 @@
(``skill_manage``/``_find_skill``/``_skill_gate_bypass``) is reached lazily
through ``tools.skill_manager_tool`` so that module owns it."""
+from contextlib import suppress
import json
import logging
import posixpath
@@ -128,9 +129,13 @@ def _validate_batch_ops(operations, default_name, tool_error):
return names, None
-def _snapshot_skills(names, snap_root, find_skill):
- """Copy every touched skill aside. Returns (snapshots, None) or (None, error_text)."""
- snapshots = {} # skill name -> (pre_dir or None, snapshot_dir or None)
+def _snapshot_skills(names, snap_root, find_skill, create_targets=None):
+ """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.
+ An EMPTY pre-existing dir there has no SKILL.md to snapshot, yet create adopts it (see
+ ``_create_skill``): record that it pre-dated the batch so rollback never rmtree()s it."""
+ snapshots = {} # skill name -> (pre_dir or None, snapshot_dir or None, dir_pre_existed)
for nm in dict.fromkeys(names): # ordered unique
pre = find_skill(nm)
pre_dir = Path(pre["path"]) if pre else None
@@ -140,15 +145,25 @@ def _snapshot_skills(names, snap_root, find_skill):
shutil.copytree(pre_dir, snap)
except Exception as exc: # noqa: BLE001 — no snapshot, no atomicity
return None, f"Could not snapshot '{nm}' for atomic batch: {exc}"
- snapshots[nm] = (pre_dir, snap)
+ target = (create_targets or {}).get(nm) if pre is None else None
+ snapshots[nm] = (pre_dir, snap, target is not None and target.is_dir())
return snapshots, None
-def _restore_snapshot(pre_dir, snap, post_dir) -> None:
+def _restore_snapshot(pre_dir, snap, post_dir, dir_pre_existed=False) -> None:
post_exists = post_dir is not None and post_dir.is_dir()
if snap is None:
- if post_exists: # Batch created this skill: remove the partial result.
+ if not post_exists:
+ return
+ 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()
+ with suppress(OSError):
+ post_dir.rmdir()
return
if not post_exists:
shutil.copytree(snap, pre_dir)
@@ -171,10 +186,10 @@ def _restore_snapshot(pre_dir, snap, post_dir) -> None:
def _rollback(snapshots, find_skill):
"""Restore every snapshot. Returns (note, failed)."""
notes = []
- for nm, (pre_dir, snap) in snapshots.items():
+ for nm, (pre_dir, snap, dir_pre_existed) in snapshots.items():
try:
post = find_skill(nm)
- _restore_snapshot(pre_dir, snap, Path(post["path"]) if post else None)
+ _restore_snapshot(pre_dir, snap, Path(post["path"]) if post else None, dir_pre_existed)
except Exception as exc: # noqa: BLE001
notes.append(f"ROLLBACK FAILED for '{nm}' ({exc})"
+ (f"; snapshot preserved at '{snap}'" if snap is not None else ""))
@@ -223,7 +238,9 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Non
# between the snapshot and a rollback would be silently reverted.
with _smt._skill_mutation_locks(names):
snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))
- snapshots, snap_err = _snapshot_skills(names, snap_root, _smt._find_skill)
+ create_targets = {names[i]: _smt._resolve_skill_dir(names[i], op.get("category"))
+ for i, op in enumerate(operations) if op.get("action") == "create"}
+ snapshots, snap_err = _snapshot_skills(names, snap_root, _smt._find_skill, create_targets)
if snap_err is not None:
shutil.rmtree(snap_root, ignore_errors=True)
return tool_error(snap_err, success=False)