The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): serialize skill mutations
KoNit-K0b8b000ce914
diff --git a/tests/tools/test_skill_manager_tool.py b/tests/tools/test_skill_manager_tool.pyindex 87caa16e8c5..d7d326d04b9 100644--- a/tests/tools/test_skill_manager_tool.py+++ b/tests/tools/test_skill_manager_tool.py@@ -1,6 +1,7 @@"""Tests for tools/skill_manager_tool.py — skill creation, editing, and deletion."""import json+import threadingfrom contextlib import contextmanagerfrom contextvars import copy_contextfrom pathlib import Path@@ -311,6 +312,116 @@ word wordassert outside_file.read_text() == "old text here"+class TestSkillMutationLock:+ @pytest.mark.parametrize("file_path", [None, "references/concurrent.md"])+ def test_concurrent_patches_keep_both_updates(self, tmp_path, file_path):+ """The second patch cannot read stale content while the first writes."""+ first_entered = threading.Event()+ second_entered = threading.Event()+ release_first = threading.Event()+ call_lock = threading.Lock()+ calls = 0+ results = []++ from tools.fuzzy_match import fuzzy_find_and_replace as real_replace++ def delayed_replace(*args, **kwargs):+ nonlocal calls+ with call_lock:+ calls += 1+ call = calls+ if call == 1:+ first_entered.set()+ assert release_first.wait(timeout=2)+ else:+ second_entered.set()+ return real_replace(*args, **kwargs)++ def run_patch(old, new):+ results.append(json.loads(skill_manage(+ action="patch", name="my-skill", old_string=old, new_string=new,+ file_path=file_path,+ )))++ with _skill_dir(tmp_path):+ _create_skill("my-skill", VALID_SKILL_CONTENT)+ if file_path:+ _write_file("my-skill", file_path, "FIRST\nSECOND\n")+ first_old, first_new = "FIRST", "FIRST_UPDATED"+ second_old, second_new = "SECOND", "SECOND_UPDATED"+ else:+ first_old, first_new = "# Test Skill", "# Test Skill Updated"+ second_old, second_new = "Step 1:", "Step 1 Updated:"+ with patch("tools.fuzzy_match.fuzzy_find_and_replace", side_effect=delayed_replace):+ first = threading.Thread(target=run_patch, args=(first_old, first_new))+ second = threading.Thread(target=run_patch, args=(second_old, second_new))+ first.start()+ assert first_entered.wait(timeout=2)+ second.start()+ assert not second_entered.wait(timeout=0.15), "second writer entered before first committed"+ release_first.set()+ first.join(timeout=2)+ second.join(timeout=2)++ target = tmp_path / "my-skill" / (file_path or "SKILL.md")+ content = target.read_text()++ assert all(result["success"] for result in results)+ assert first_new in content+ assert second_new in content++ @pytest.mark.parametrize(("action", "handler", "kwargs"), [+ ("edit", "_edit_skill", {"content": VALID_SKILL_CONTENT_2}),+ ("write_file", "_write_file", {"file_path": "references/concurrent.md", "file_content": "new"}),+ ("remove_file", "_remove_file", {"file_path": "references/concurrent.md"}),+ ])+ def test_mutation_lock_covers_edit_and_supporting_file_actions(self, tmp_path, action, handler, kwargs):+ """Every public mutation action holds the same per-skill lock."""+ first_entered = threading.Event()+ second_entered = threading.Event()+ release_first = threading.Event()+ entered_lock = threading.Lock()+ entered = 0+ results = []++ def delayed_handler(*_args, **_kwargs):+ nonlocal entered+ with entered_lock:+ entered += 1+ ordinal = entered+ if ordinal == 1:+ first_entered.set()+ assert release_first.wait(timeout=2)+ else:+ second_entered.set()+ return {"success": True, "message": "mutated"}++ def mutate():+ results.append(json.loads(skill_manage(action=action, name="my-skill", **kwargs)))++ with _skill_dir(tmp_path), patch(f"tools.skill_manager_tool.{handler}", side_effect=delayed_handler):+ _create_skill("my-skill", VALID_SKILL_CONTENT)+ first = threading.Thread(target=mutate)+ second = threading.Thread(target=mutate)+ first.start()+ assert first_entered.wait(timeout=2)+ second.start()+ assert not second_entered.wait(timeout=0.15), "second writer entered before first committed"+ release_first.set()+ first.join(timeout=2)+ second.join(timeout=2)++ assert all(result["success"] for result in results)++ def test_public_delete_does_not_strand_a_category_lock_directory(self, tmp_path):+ with _skill_dir(tmp_path):+ _create_skill("my-skill", VALID_SKILL_CONTENT, category="devops")+ result = json.loads(skill_manage(action="delete", name="my-skill"))++ assert result["success"] is True+ assert not (tmp_path / "devops").exists()++class TestDeleteSkill:def test_delete_cleans_empty_category_dir(self, tmp_path):with _skill_dir(tmp_path):diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex 9f38adff284..b9a6b041af9 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -144,10 +144,21 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nonstaged = _smt._run_write_gate(_staging)if staged is not None:return staged- snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))+ # Hold every target's lock from the snapshot through either commit or+ # rollback. Individual operations re-enter these locks through+ # skill_manage(), but the outer fence is what keeps a concurrent writer+ # from landing between this batch's snapshot and its final operation.+ mutation_locks = _smt._skill_mutation_locks(names)+ mutation_locks.__enter__()+ try:+ snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))+ except BaseException as exc:+ mutation_locks.__exit__(type(exc), exc, exc.__traceback__)+ raisesnapshots, snap_err = _snapshot_skills(names, snap_root, _smt._find_skill)if snap_err is not None:shutil.rmtree(snap_root, ignore_errors=True)+ mutation_locks.__exit__(None, None, None)return tool_error(snap_err, success=False)# Single-op path with the gate bypassed (the batch already cleared/staged it).results = []@@ -183,6 +194,7 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nonlogger.warning("skill_manage batch rollback failed, snapshots kept at %s", snap_root)else:shutil.rmtree(snap_root, ignore_errors=True)+ mutation_locks.__exit__(None, None, None)# utf-8-sig + errors="replace": SKILL.md files are user-authored and sometimes carry a Notepad BOM or# stray non-UTF-8 bytes. Pinning UTF-8 with replacement keeps skill_view deterministic across platforms# — falling back to the machine locale (cp1252/GBK) would make the same skill render differently perdiff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex 00a7ce8c0bf..428b12805bf 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -8,8 +8,9 @@ existing skills (bundled, hub, user) are modified in place. Layout:"""import contextvars as _ctxvars+import hashlibimport json-from contextlib import suppress+from contextlib import ExitStack, contextmanager, suppressimport loggingimport reimport shutil@@ -37,6 +38,23 @@ from tools.skills_guard import scan_skill, should_allow_install, format_scan_replogger = logging.getLogger(__name__)+# Advisory locks serialize the complete skill mutation transaction across+# processes. ``fcntl`` is unavailable on Windows, where ``msvcrt`` provides+# the equivalent byte-range lock instead.+try:+ import fcntl+except ImportError: # pragma: no cover - Windows fallback+ fcntl = None+try:+ import msvcrt+except ImportError: # pragma: no cover - POSIX+ msvcrt = None+++_held_skill_mutation_locks: "_ctxvars.ContextVar[frozenset[str]]" = _ctxvars.ContextVar(+ "held_skill_mutation_locks", default=frozenset())++def _guard_agent_created_enabled() -> bool:"""skills.guard_agent_created (default False): opt-in — terminal() runs the same code ungated."""try:@@ -80,6 +98,75 @@ def _skills_dir() -> Path:return configured if configured != _SKILLS_DIR_AT_IMPORT else get_hermes_home() / "skills"+def _skill_mutation_lock_path(name: str) -> Path:+ """Return a stable per-skill lock path without placing it in the skill.++ The lock must survive a delete/recreate cycle: a lock file inside the+ skill directory could be unlinked while another writer still holds it.+ Lock files stay under the active Hermes home rather than a category+ directory, so deleting the last categorized skill still removes that now+ empty category.+ """+ existing = _find_skill(name)+ skill_dir = Path(existing["path"]) if existing else _resolve_skill_dir(name)+ try:+ identity = str(skill_dir.resolve())+ except OSError:+ identity = str(skill_dir.absolute())+ digest = hashlib.sha256(identity.encode("utf-8")).hexdigest()+ return _skills_dir() / ".skill_manage_locks" / f"{digest}.lock"+++@contextmanager+def _skill_mutation_lock(name: str):+ """Serialize one skill's read-transform-validate-write window.++ Locking is intentionally advisory and fail-open only where neither+ platform primitive exists, preserving the tool's existing portability on+ unsupported platforms. The Windows lock file contains one byte because+ ``msvcrt.locking`` cannot lock an empty range.+ """+ lock_path = _skill_mutation_lock_path(name)+ lock_key = str(lock_path)+ held = _held_skill_mutation_locks.get()+ if lock_key in held:+ yield+ return+ if fcntl is None and msvcrt is None: # pragma: no cover - unsupported platform+ yield+ return+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ if msvcrt is not None and (not lock_path.exists() or lock_path.stat().st_size == 0):+ lock_path.write_text(" ", encoding="utf-8")+ with open(lock_path, "r+" if msvcrt is not None else "a+", encoding="utf-8") as handle:+ if fcntl is not None:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)+ else: # pragma: no cover - Windows fallback+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)+ token = _held_skill_mutation_locks.set(held | {lock_key})+ try:+ yield+ finally:+ _held_skill_mutation_locks.reset(token)+ with suppress(OSError, IOError):+ if fcntl is not None:+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ else: # pragma: no cover - Windows fallback+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+++@contextmanager+def _skill_mutation_locks(names):+ """Acquire several skill locks in path order for an atomic batch."""+ lock_names = sorted(dict.fromkeys(names), key=lambda name: str(_skill_mutation_lock_path(name)))+ with ExitStack() as stack:+ for name in lock_names:+ stack.enter_context(_skill_mutation_lock(name))+ yield++MAX_NAME_LENGTH = 64MAX_DESCRIPTION_LENGTH = 1024MAX_SKILL_CONTENT_CHARS = 100_000 # ~36k tokens at 2.75 chars/token@@ -758,29 +845,33 @@ def skill_manage(absorbed_into=absorbed_into)if (gate_result := _apply_skill_write_gate(action, name, **args)) is not None:return gate_result- # Ledger pre-capture: telemetry, not a gate — failures must NEVER block the mutation. delete- # destroys the whole package (consolidation may have re-homed support files first), so- # complete it from the newest curator backup or a restore is hollow.- # Audit ledger (tracker #79686 P3): capture the pre-mutation state of the skill directory so every- # mutation — any actor — lands in the append-only JSONL ledger with before/after blobs.- _ledger_before = None- with suppress(Exception):- from tools import skill_ledger as _ledger- _pre = _find_skill(name)- _ledger_before = _ledger.capture_before(- _pre["path"] if _pre else None, complete_package=(action == "delete"), skill=name)for arg, missing, message in _REQUIRED_ARGS.get(action, ()):if missing(args[arg]):return tool_error(message, success=False)- handler = _ACTION_HANDLERS.get(action, lambda a: _err(- f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file"))- result = handler({"name": name, **args})- if isinstance(result, str):- return result # tool_error JSON for argument-shape problems (patch)- if result.get("success"):- _record_success(- action, name, result, file_path=file_path, absorbed_into=absorbed_into,- task_id=task_id, session_id=session_id, ledger_before=_ledger_before)+ # A mutation is read-modify-write even when its action eventually delegates+ # to a helper: guards, ledger capture, patch matching, validation, rollback,+ # and the atomic replacement all belong to the same ownership window.+ with _skill_mutation_lock(name):+ # Ledger pre-capture: telemetry, not a gate — failures must NEVER block the mutation. delete+ # destroys the whole package (consolidation may have re-homed support files first), so+ # complete it from the newest curator backup or a restore is hollow.+ # Audit ledger (tracker #79686 P3): capture the pre-mutation state of the skill directory so every+ # mutation — any actor — lands in the append-only JSONL ledger with before/after blobs.+ _ledger_before = None+ with suppress(Exception):+ from tools import skill_ledger as _ledger+ _pre = _find_skill(name)+ _ledger_before = _ledger.capture_before(+ _pre["path"] if _pre else None, complete_package=(action == "delete"), skill=name)+ handler = _ACTION_HANDLERS.get(action, lambda a: _err(+ f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file"))+ result = handler({"name": name, **args})+ if isinstance(result, str):+ return result # tool_error JSON for argument-shape problems (patch)+ if result.get("success"):+ _record_success(+ action, name, result, file_path=file_path, absorbed_into=absorbed_into,+ task_id=task_id, session_id=session_id, ledger_before=_ledger_before)return json.dumps(result, ensure_ascii=False)