The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): route the skill_manage lock through the existing skill_usage lock helper
teknium1273986f88ff3
diff --git a/tests/tools/test_skill_manager_tool.py b/tests/tools/test_skill_manager_tool.pyindex d7d326d04b9..3fa02e9a32e 100644--- a/tests/tools/test_skill_manager_tool.py+++ b/tests/tools/test_skill_manager_tool.py@@ -313,9 +313,9 @@ word wordclass 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."""+ def test_concurrent_patches_keep_both_updates(self, tmp_path):+ """Two writers patching the same SKILL.md serialize on the per-skill lock (#111578):+ the second cannot read stale content while the first is between read and write."""first_entered = threading.Event()second_entered = threading.Event()release_first = threading.Event()@@ -339,22 +339,13 @@ class TestSkillMutationLock: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,- )))+ action="patch", name="my-skill", old_string=old, new_string=new)))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 = threading.Thread(target=run_patch, args=("# Test Skill", "# Test Skill Updated"))+ second = threading.Thread(target=run_patch, args=("Step 1:", "Step 1 Updated:"))first.start()assert first_entered.wait(timeout=2)second.start()@@ -362,64 +353,11 @@ class TestSkillMutationLock: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)+ content = (tmp_path / "my-skill" / "SKILL.md").read_text()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()+ assert "# Test Skill Updated" in content+ assert "Step 1 Updated:" in contentclass TestDeleteSkill:diff --git a/tests/tools/test_skill_usage.py b/tests/tools/test_skill_usage.pyindex d7267fa7f8e..9b65f27de75 100644--- a/tests/tools/test_skill_usage.py+++ b/tests/tools/test_skill_usage.py@@ -571,3 +571,29 @@ def test_foreground_create_stamps_learn_provenance_not_agent(skills_home):skill_usage.record_created("agent-skill", agent_created=True)assert skill_usage.get_record("agent-skill")["created_by"] == "agent"assert skill_usage.is_curator_managed("agent-skill")+++def test_skill_file_lock_is_reentrant_in_thread_and_exclusive_across_threads(tmp_path):+ """A nested acquire of the same lock path in one thread must not deadlock (an atomic+ skill_manage batch holds every target lock while its per-op calls re-acquire them), while a+ second thread still waits until the outer holder releases.+ """+ import threading+ from tools.skill_usage import skill_file_lock++ lock_path = tmp_path / ".locks" / "demo.lock"+ entered = threading.Event()+ other_done = threading.Event()++ def other():+ with skill_file_lock(lock_path):+ other_done.set()++ t = threading.Thread(target=other)+ with skill_file_lock(lock_path):+ with skill_file_lock(lock_path): # re-entrant: returns immediately+ entered.set()+ t.start()+ assert not other_done.wait(timeout=0.2), "second thread acquired a held lock"+ t.join(timeout=2)+ assert entered.is_set() and other_done.is_set()diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex b9a6b041af9..2096d0ba1af 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -144,57 +144,49 @@ 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- # 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:+ # Every target's lock is held from the snapshot through commit or rollback; the per-op+ # skill_manage() calls re-enter them. Without the outer fence a concurrent writer landing+ # between the snapshot and a rollback would be silently reverted.+ with _smt._skill_mutation_locks(names):snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))- except BaseException as exc:- mutation_locks.__exit__(type(exc), exc, exc.__traceback__)- raise- snapshots, 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 = []- rollback_failed = False- token = _smt._skill_gate_bypass.set(True)- try:- for i, op in enumerate(operations):- raw = _smt._skill_manage_from({**op, "name": names[i], "operations": None},- task_id=task_id, session_id=session_id)- try:- parsed = json.loads(raw)- except Exception: # noqa: BLE001- parsed = {"success": False, "error": "unparseable op result"}- if not parsed.get("success"):- note, rollback_failed = _rollback(snapshots, _smt._find_skill)- fail = { # key order is wire-visible- "success": False,- "error": (f"operations[{i}] ({op['action']} on '{names[i]}') failed: "- f"{parsed.get('error', 'unknown error')} — batch aborted, {note}."),- "failed_index": i, "completed_before_failure": i}- # Carry the failing op's teaching payload (patch's file_preview /- # fuzzy-match hints) through — without it the model recovers blind.- for k, v in parsed.items():- if k not in ("success", "error") and v is not None:- fail.setdefault(k, v)- return json.dumps(fail, ensure_ascii=False)- results.append({"name": names[i], "action": op["action"],- "file_path": op.get("file_path"), "success": True})- finally:- _smt._skill_gate_bypass.reset(token)- if rollback_failed:- # Keep the snapshots so the operator can still recover by hand.- logger.warning("skill_manage batch rollback failed, snapshots kept at %s", snap_root)- else:+ snapshots, 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 = []+ rollback_failed = False+ token = _smt._skill_gate_bypass.set(True)+ try:+ for i, op in enumerate(operations):+ raw = _smt._skill_manage_from({**op, "name": names[i], "operations": None},+ task_id=task_id, session_id=session_id)+ try:+ parsed = json.loads(raw)+ except Exception: # noqa: BLE001+ parsed = {"success": False, "error": "unparseable op result"}+ if not parsed.get("success"):+ note, rollback_failed = _rollback(snapshots, _smt._find_skill)+ fail = { # key order is wire-visible+ "success": False,+ "error": (f"operations[{i}] ({op['action']} on '{names[i]}') failed: "+ f"{parsed.get('error', 'unknown error')} — batch aborted, {note}."),+ "failed_index": i, "completed_before_failure": i}+ # Carry the failing op's teaching payload (patch's file_preview /+ # fuzzy-match hints) through — without it the model recovers blind.+ for k, v in parsed.items():+ if k not in ("success", "error") and v is not None:+ fail.setdefault(k, v)+ return json.dumps(fail, ensure_ascii=False)+ results.append({"name": names[i], "action": op["action"],+ "file_path": op.get("file_path"), "success": True})+ finally:+ _smt._skill_gate_bypass.reset(token)+ if rollback_failed:+ # Keep the snapshots so the operator can still recover by hand.+ logger.warning("skill_manage batch rollback failed, snapshots kept at %s", snap_root)+ else:+ shutil.rmtree(snap_root, ignore_errors=True)# 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 428b12805bf..29c027e08e5 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -8,9 +8,8 @@ existing skills (bundled, hub, user) are modified in place. Layout:"""import contextvars as _ctxvars-import hashlibimport json-from contextlib import ExitStack, contextmanager, suppress+from contextlib import ExitStack, suppressimport loggingimport reimport shutil@@ -38,23 +37,6 @@ 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:@@ -98,73 +80,28 @@ 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.- """+def _skill_lock_path(name: str) -> Path:+ """Per-skill lock file under ``<skills>/.locks/`` (same idiom as the usage ledger's+ ``.usage.json.lock``), never inside the skill dir so delete/recreate cannot unlink it under a+ waiting writer. Keyed by the resolved skill dir so ``foo`` and ``category/foo`` share one lock."""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"+ return _skills_dir() / ".locks" / f"{skill_dir.name}.lock"-@contextmanagerdef _skill_mutation_lock(name: str):- """Serialize one skill's read-transform-validate-write window.+ """Exclusive lock held across one skill's whole read-modify-write; thread-re-entrant."""+ from tools.skill_usage import skill_file_lock+ return skill_file_lock(_skill_lock_path(name))+- 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)---@contextmanagerdef _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+ """Every lock of an atomic batch, acquired in one stable path order (deadlock-free across batches)."""+ from tools.skill_usage import skill_file_lock+ stack = ExitStack()+ for lock_path in sorted({_skill_lock_path(n) for n in names}):+ stack.enter_context(skill_file_lock(lock_path))+ return stackMAX_NAME_LENGTH = 64diff --git a/tools/skill_usage.py b/tools/skill_usage.pyindex 3066d2ac873..1d317d386d2 100644--- a/tools/skill_usage.py+++ b/tools/skill_usage.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport jsonimport logging+import threadingfrom contextlib import contextmanager, suppressfrom datetime import datetime, timezonefrom pathlib import Path@@ -61,25 +62,40 @@ def _flock(fd, lock: bool) -> None:msvcrt.locking(fd.fileno(), msvcrt.LK_LOCK if lock else msvcrt.LK_UNLCK, 1)+_held_locks = threading.local() # per thread: flock is NOT re-entrant across separate fds++@contextmanager-def _usage_file_lock():- """Serialize .usage.json read-modify-write cycles across processes."""- lock_path = _usage_file().with_suffix(".json.lock")- lock_path.parent.mkdir(parents=True, exist_ok=True)- if fcntl is None and msvcrt is None:+def skill_file_lock(lock_path: Path):+ """Exclusive cross-process lock on ``lock_path`` held across a read-modify-write cycle.+ Re-entrant within one thread (a nested acquire of the same path just runs); a no-op+ where neither fcntl nor msvcrt exists."""+ lock_path = Path(lock_path)+ held = getattr(_held_locks, "paths", None)+ if held is None:+ held = _held_locks.paths = set()+ if (fcntl is None and msvcrt is None) or lock_path in held:yieldreturn+ lock_path.parent.mkdir(parents=True, exist_ok=True)if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):lock_path.write_text(" ", encoding="utf-8") # msvcrt needs a non-empty byte range to lockwith open(lock_path, "r+" if msvcrt else "a+", encoding="utf-8") as fd:_flock(fd, True)+ held.add(lock_path)try:yieldfinally:+ held.discard(lock_path)with suppress(OSError, IOError):_flock(fd, False)+def _usage_file_lock():+ """Serialize .usage.json read-modify-write cycles across processes."""+ return skill_file_lock(_usage_file().with_suffix(".json.lock"))++def _read_lines(path: Path, fail_log: str) -> List[str]:"""Stripped, non-empty lines of a small metadata file ([] if missing/unreadable)."""if not path.exists():