Skip to content

The agent that grows with you

fix(skills): hub lock.json and taps.json updates are atomic and locked

Maciej Lisiewskie622147e6aa9
diff --git a/tests/tools/test_skills_hub_lock_file.py b/tests/tools/test_skills_hub_lock_file.py
new file mode 100644
index 00000000000..ca8446af841
--- /dev/null
+++ b/tests/tools/test_skills_hub_lock_file.py
@@ -0,0 +1,87 @@
+"""skills/.hub/lock.json and taps.json survive concurrent writers from different processes.
+
+The desktop/TUI skill install RPC and the CLI ``hermes skills install/uninstall`` rewrite the same
+lock.json from different processes. An in-place rewrite left it empty between truncate and write
+(a torn read: the next ``record_install`` loaded ``EMPTY``); an unlocked load → mutate → save let
+the last writer put back the snapshot it loaded, dropping the provenance of every skill another
+process recorded meanwhile.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+from tests.file_write_observer import observe_file_writes
+from tools.skills_hub import HubLockFile, TapsManager
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_WRITES_PER_PROCESS = 150
+
+_WRITER = textwrap.dedent("""
+ import sys, time
+ from pathlib import Path
+ from tools.skills_hub import HubLockFile, TapsManager
+
+ hub, tag, count, go = Path(sys.argv[1]), sys.argv[2], int(sys.argv[3]), Path(sys.argv[4])
+ while not go.exists():
+ time.sleep(0.001)
+ lock, taps = HubLockFile(hub / "lock.json"), TapsManager(hub / "taps.json")
+ for i in range(count):
+ name = f"{tag}-{i}"
+ lock.record_install(
+ name=name, source="github", identifier=f"o/r/{name}", trust_level="community",
+ scan_verdict="safe", skill_hash="sha256:0", install_path=name, files=["SKILL.md"],
+ )
+ taps.add(f"o/{name}")
+""")
+
+
+def _seed(lock: HubLockFile, names: list[str]) -> None:
+ lock.save({"version": 1, "installed": {
+ name: {"source": "github", "identifier": f"o/r/{name}", "install_path": name, "files": ["SKILL.md"]}
+ for name in names
+ }})
+
+
+def test_concurrent_processes_keep_every_install_and_tap(tmp_path):
+ hub = tmp_path / "skills" / ".hub"
+ hub.mkdir(parents=True)
+ go = tmp_path / "go"
+ writers = [
+ subprocess.Popen(
+ [sys.executable, "-c", _WRITER, str(hub), tag, str(_WRITES_PER_PROCESS), str(go)],
+ cwd=_REPO_ROOT, stderr=subprocess.PIPE, text=True,
+ )
+ for tag in ("cli", "desktop")
+ ]
+ go.touch()
+ for writer in writers:
+ _, stderr = writer.communicate(timeout=120)
+ assert writer.returncode == 0, stderr
+
+ expected = sorted(f"{tag}-{i}" for tag in ("cli", "desktop") for i in range(_WRITES_PER_PROCESS))
+ assert sorted(HubLockFile(hub / "lock.json").load()["installed"]) == expected
+ assert sorted(t["repo"] for t in TapsManager(hub / "taps.json").load()) == [f"o/{name}" for name in expected]
+
+
+def test_reader_mid_save_sees_complete_hub_state(tmp_path):
+ lock_path = tmp_path / "lock.json"
+ taps_path = tmp_path / "taps.json"
+ lock = HubLockFile(lock_path)
+ taps = TapsManager(taps_path)
+ _seed(lock, ["alpha", "beta"])
+ taps.save([{"repo": "o/one", "path": "skills/"}])
+ seen = []
+
+ with observe_file_writes(lambda: seen.append((sorted(HubLockFile(lock_path).load()["installed"]),
+ [t["repo"] for t in TapsManager(taps_path).load()]))):
+ lock.record_uninstall("beta")
+ taps.add("o/two")
+
+ assert seen
+ assert all(installed and repos for installed, repos in seen), seen
+ assert sorted(lock.load()["installed"]) == ["alpha"]
+ assert [t["repo"] for t in taps.load()] == ["o/one", "o/two"]
diff --git a/tools/skills_hub.py b/tools/skills_hub.py
index b4787fb268b..6f1dff8ad04 100644
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@ -13,12 +13,13 @@ Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command.
import json
import logging
+import threading
import time
from contextvars import ContextVar
from contextlib import ExitStack, contextmanager
from datetime import datetime, timezone, UTC
from pathlib import Path
-from typing import Any, Dict, Iterator, List, Optional
+from typing import Any, Callable, Dict, Iterator, List, Optional
from urllib.parse import urljoin
import httpx
@@ -28,6 +29,7 @@ from tools.url_safety import is_safe_url
from tools.url_safety import create_ssrf_safe_client
from tools.website_policy import check_website_access
from tools.skills_hub_models import _normalize_lock_install_path, _validate_skill_name
+from utils import atomic_write_text
logger = logging.getLogger(__name__)
@@ -277,6 +279,7 @@ class _JsonStateFile:
EMPTY: dict = {}
DEFAULT_PATH: Any = None
+ _LOCK_HOLDER: threading.local
def __init__(self, path: Optional[Path] = None):
self.path = path if path is not None else type(self).DEFAULT_PATH()
@@ -289,7 +292,31 @@ class _JsonStateFile:
def _write(self, data: dict, **dumps_kwargs) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
- self.path.write_text(json.dumps(data, indent=2, **dumps_kwargs) + "\n", encoding="utf-8")
+ # Temp + rename: another process (CLI vs desktop install) reading mid-write would see an
+ # empty file, load EMPTY and save a lock that drops every other installed skill.
+ atomic_write_text(self.path, json.dumps(data, indent=2, **dumps_kwargs) + "\n", preserve_mode=True)
+
+ def _update(self, mutate: Callable[[dict], bool], **dumps_kwargs) -> bool:
+ """Re-read, ``mutate`` and save under a cross-process lock; the file is rewritten only
+ when ``mutate`` returns True. The CLI and desktop rewrite the same file, and a save from a
+ snapshot loaded outside the lock drops whatever the other process recorded meanwhile.
+
+ An unusable lock (no flock on the filesystem, a wedged holder) degrades to an unlocked
+ update rather than failing the install that triggered it."""
+ from hermes_cli.auth import _file_lock
+ with ExitStack() as stack:
+ try:
+ stack.enter_context(_file_lock(
+ self.path.with_name(self.path.name + ".lock"), type(self)._LOCK_HOLDER, 10.0,
+ f"Timed out waiting for the skills hub state lock ({self.path})",
+ ))
+ except (OSError, TimeoutError):
+ logger.warning("Updating %s without its lock", self.path, exc_info=True)
+ data = self._read()
+ changed = mutate(data)
+ if changed:
+ self._write(data, **dumps_kwargs)
+ return changed
class HubLockFile(_JsonStateFile):
@@ -297,6 +324,7 @@ class HubLockFile(_JsonStateFile):
EMPTY = {"version": 1, "installed": {}}
DEFAULT_PATH = staticmethod(_lock_file)
+ _LOCK_HOLDER = threading.local()
def load(self) -> dict:
return self._read()
@@ -321,27 +349,32 @@ class HubLockFile(_JsonStateFile):
# entry is the precondition for the uninstall_skill rmtree-escape.
safe_name = _validate_skill_name(name)
safe_install_path = _normalize_lock_install_path(install_path, safe_name)
- data = self.load()
- now = datetime.now(UTC).isoformat()
- data["installed"][safe_name] = {
- "source": source,
- "identifier": identifier,
- "trust_level": trust_level,
- "scan_verdict": scan_verdict,
- "content_hash": skill_hash,
- "install_path": safe_install_path,
- "files": files,
- "metadata": metadata or {},
- "scan_provenance": scan_provenance or {},
- "installed_at": now,
- "updated_at": now,
- }
- self.save(data)
+
+ def record(data: dict) -> bool:
+ now = datetime.now(UTC).isoformat()
+ data.setdefault("installed", {})[safe_name] = {
+ "source": source,
+ "identifier": identifier,
+ "trust_level": trust_level,
+ "scan_verdict": scan_verdict,
+ "content_hash": skill_hash,
+ "install_path": safe_install_path,
+ "files": files,
+ "metadata": metadata or {},
+ "scan_provenance": scan_provenance or {},
+ "installed_at": now,
+ "updated_at": now,
+ }
+ return True
+
+ self._update(record, ensure_ascii=False)
def record_uninstall(self, name: str) -> None:
- data = self.load()
- data["installed"].pop(name, None)
- self.save(data)
+ def forget(data: dict) -> bool:
+ data.setdefault("installed", {}).pop(name, None)
+ return True
+
+ self._update(forget, ensure_ascii=False)
def get_installed(self, name: str) -> Optional[dict]:
return self.load()["installed"].get(name)
@@ -355,6 +388,7 @@ class TapsManager(_JsonStateFile):
EMPTY = {"taps": []}
DEFAULT_PATH = staticmethod(_taps_file)
+ _LOCK_HOLDER = threading.local()
def load(self) -> list[dict]:
return self._read().get("taps", [])
@@ -364,21 +398,24 @@ class TapsManager(_JsonStateFile):
def add(self, repo: str, path: str = "skills/") -> bool:
"""Add a tap. Returns False if already exists."""
- taps = self.load()
- if any(t["repo"] == repo for t in taps):
- return False
- taps.append({"repo": repo, "path": path})
- self.save(taps)
- return True
+ def append(data: dict) -> bool:
+ taps = data.setdefault("taps", [])
+ if any(t["repo"] == repo for t in taps):
+ return False
+ taps.append({"repo": repo, "path": path})
+ return True
+
+ return self._update(append)
def remove(self, repo: str) -> bool:
"""Remove a tap by repo name. Returns False if not found."""
- taps = self.load()
- new_taps = [t for t in taps if t["repo"] != repo]
- if len(new_taps) == len(taps):
- return False
- self.save(new_taps)
- return True
+ def drop(data: dict) -> bool:
+ taps = data.get("taps", [])
+ kept = [t for t in taps if t["repo"] != repo]
+ data["taps"] = kept
+ return len(kept) != len(taps)
+
+ return self._update(drop)
list_taps = load