The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): bundle cache sees same-tick edits; save_bundle is atomic
Maciej Lisiewski946f73d09907
diff --git a/agent/skill_bundles.py b/agent/skill_bundles.pyindex 0bd3629f09a..d29b03b14ba 100644--- a/agent/skill_bundles.py+++ b/agent/skill_bundles.py@@ -8,6 +8,7 @@ skill share a slug, the bundle wins — slash dispatch checks bundles first, onfrom __future__ import annotations+import hashlibimport loggingimport osfrom pathlib import Path@@ -16,12 +17,13 @@ from typing import Any, Dict, List, Optional, Tupleimport hermes_yaml as yamlfrom hermes_constants import get_hermes_home+from utils import atomic_write_textfrom agent.skill_commands import command_snapshot, diff_command_snapshots, resolve_slash_key, slugify_skill_name as _slugifylogger = logging.getLogger(__name__)_bundles_cache: dict[str, dict[str, Any]] = {}-_bundles_cache_mtime: Optional[float] = None+_bundles_cache_mtime: Optional[tuple] = None # _bundles_sig() (content digests) of the cached scandef _bundles_dir() -> Path:@@ -35,15 +37,17 @@ def _iter_bundle_files() -> list[Path]:return [f for ext in ("*.yaml", "*.yml") for f in sorted(base.glob(ext))] if base.exists() else []-def _max_mtime(files: list[Path]) -> float:- """Highest mtime across the bundle files plus the dir itself (dir mtime catches deletions)."""- mtimes = []- for f in (_bundles_dir(), *files):+def _bundles_sig(files: list[Path]) -> tuple:+ """Sorted ``(path, content digest)`` of the bundle files. Content, not timestamps: a same-size+ rewrite within one coarse mtime/ctime tick, or under host/filesystem clock skew, still moves it.+ Bundles are a handful of small YAML files, so reading them per check is cheap."""+ entries = []+ for f in files:try:- mtimes.append(f.stat().st_mtime)+ entries.append((str(f), hashlib.sha256(f.read_bytes()).hexdigest()))except OSError:continue- return max(mtimes, default=0.0)+ return tuple(sorted(entries))def _load_bundle_file(path: Path) -> Optional[dict[str, Any]]:@@ -83,6 +87,8 @@ def scan_bundles() -> dict[str, dict[str, Any]]:"""Rebuild the ``"/slug"`` -> bundle info cache; duplicate slugs keep the first (alphabetical)."""global _bundles_cache, _bundles_cache_mtimefiles = _iter_bundle_files()+ # Stamp BEFORE parsing: a write landing mid-scan must leave the stamp stale, not match it.+ sig = _bundles_sig(files)out: dict[str, dict[str, Any]] = {}for f in files:info = _load_bundle_file(f)@@ -94,13 +100,13 @@ def scan_bundles() -> dict[str, dict[str, Any]]:continueout[key] = info_bundles_cache = out- _bundles_cache_mtime = _max_mtime(files)+ _bundles_cache_mtime = sigreturn outdef get_skill_bundles() -> dict[str, dict[str, Any]]:- """Current bundle mapping; rescans only when a bundle file or the dir mtime changed."""- current_mtime = _max_mtime(_iter_bundle_files())+ """Current bundle mapping; rescans only when the set of bundle files or their content changed."""+ current_mtime = _bundles_sig(_iter_bundle_files())if not _bundles_cache or _bundles_cache_mtime != current_mtime:scan_bundles()return _bundles_cache@@ -186,7 +192,8 @@ def save_bundle(name: str, skills: list[str], description: str = "", instructionpath.parent.mkdir(parents=True, exist_ok=True)payload: dict[str, Any] = {"name": name, "skills": cleaned_skills}payload.update({k: v for k, v in (("description", description), ("instruction", instruction)) if v})- path.write_text(yaml.safe_dump(payload, sort_keys=False, allow_unicode=True), encoding="utf-8")+ # Atomic: a gateway process scanning mid-write must never parse a truncated bundle.+ atomic_write_text(path, yaml.safe_dump(payload, sort_keys=False, allow_unicode=True), preserve_mode=True)scan_bundles()return pathdiff --git a/tests/agent/test_skill_bundles.py b/tests/agent/test_skill_bundles.pyindex e0e2330f442..f09e9fef4ab 100644--- a/tests/agent/test_skill_bundles.py+++ b/tests/agent/test_skill_bundles.py@@ -267,3 +267,92 @@ class TestListBundles:info_list = list_bundles()slugs = [b["slug"] for b in info_list]assert slugs == sorted(slugs)+++class TestBundleCacheRaces:+ """The gateway's cache must see edits another process (`hermes bundles`) makes in the same mtime tick."""++ T = 1_800_000_000_000_000_000++ def _pin(self, *paths):+ for p in paths:+ os.utime(p, ns=(self.T, self.T))++ def test_same_tick_new_bundle_is_seen(self, bundles_env):+ bundles_dir, _ = bundles_env+ alpha = _make_bundle_yaml(bundles_dir, "alpha", ["x"])+ self._pin(alpha, bundles_dir)+ assert sorted(get_skill_bundles()) == ["/alpha"]++ beta = _make_bundle_yaml(bundles_dir, "beta", ["y"])+ self._pin(beta, bundles_dir)+ assert sorted(get_skill_bundles()) == ["/alpha", "/beta"]++ def test_same_tick_edit_is_seen(self, bundles_env):+ bundles_dir, _ = bundles_env+ alpha = _make_bundle_yaml(bundles_dir, "alpha", ["x"])+ self._pin(alpha, bundles_dir)+ assert get_skill_bundles()["/alpha"]["skills"] == ["x"]++ _make_bundle_yaml(bundles_dir, "alpha", ["changed"])+ self._pin(alpha)+ assert get_skill_bundles()["/alpha"]["skills"] == ["changed"]++ def test_write_landing_during_scan_is_picked_up_next_call(self, bundles_env, monkeypatch):+ import agent.skill_bundles as mod++ bundles_dir, _ = bundles_env+ alpha = _make_bundle_yaml(bundles_dir, "alpha", ["x"])+ self._pin(alpha, bundles_dir)+ real_load = mod._load_bundle_file++ def load_then_concurrent_write(path):+ info = real_load(path)+ # Another process finishes its write after this scan parsed the old content.+ _make_bundle_yaml(bundles_dir, "alpha", ["after-parse"])+ self._pin(alpha)+ return info++ monkeypatch.setattr(mod, "_load_bundle_file", load_then_concurrent_write)+ assert get_skill_bundles()["/alpha"]["skills"] == ["x"]+ monkeypatch.setattr(mod, "_load_bundle_file", real_load)++ assert get_skill_bundles()["/alpha"]["skills"] == ["after-parse"]++ def test_same_size_in_place_rewrite_on_a_coarse_clock_is_seen(self, bundles_env, monkeypatch):+ """A filesystem whose timestamps did not tick between two writes (coarse mtime AND ctime):+ an in-place rewrite of the same size keeps every stat field, so only content can tell."""+ import pathlib+ from types import SimpleNamespace++ bundles_dir, _ = bundles_env+ alpha = _make_bundle_yaml(bundles_dir, "alpha", ["aa"])+ real_stat = pathlib.Path.stat++ def frozen_clock_stat(path, *args, **kwargs):+ st = real_stat(path, *args, **kwargs)+ return SimpleNamespace(st_mtime_ns=self.T, st_ctime_ns=self.T, st_size=st.st_size,+ st_ino=st.st_ino, st_mode=st.st_mode, st_mtime=self.T / 1e9)++ monkeypatch.setattr(pathlib.Path, "stat", frozen_clock_stat)+ assert get_skill_bundles()["/alpha"]["skills"] == ["aa"]++ alpha.write_text(alpha.read_text(encoding="utf-8").replace("aa", "bb"), encoding="utf-8")++ assert get_skill_bundles()["/alpha"]["skills"] == ["bb"]++ def test_overwrite_never_exposes_a_partial_file(self, bundles_env):+ import agent.skill_bundles as mod+ from tests.file_write_observer import observe_file_writes++ save_bundle("alpha", ["old-skill"])+ target = mod.bundle_path_for("alpha")+ seen = []++ # A reader at every write instant of the overwrite sees a whole bundle, old or new.+ with observe_file_writes(lambda: seen.append((mod._load_bundle_file(target) or {}).get("skills"))):+ save_bundle("alpha", ["new-skill"], overwrite=True)++ assert seen+ assert all(skills in (["old-skill"], ["new-skill"]) for skills in seen), seen+ assert get_bundle("alpha")["skills"] == ["new-skill"]diff --git a/tests/file_write_observer.py b/tests/file_write_observer.pynew file mode 100644index 00000000000..bc9ca4b4c5f--- /dev/null+++ b/tests/file_write_observer.py@@ -0,0 +1,45 @@+"""Run a "concurrent reader" at the exact instant a writer emits bytes (torn-read regression tests).++A file rewritten in place (``open(path, "w")`` / ``Path.write_text``) is empty from the truncating+open until the payload lands; another process that reads it then sees ``""``. Racing real threads+only hits that window probabilistically. This helper makes it deterministic: ``callback`` runs at+every Python-level ``write()`` on a file object in the current thread, i.e. while the writer is+mid-publication, so the callback can read the target exactly as a concurrent process would.++ from tests.file_write_observer import observe_file_writes++ seen = []+ with observe_file_writes(lambda: seen.append(target.read_text() if target.exists() else None)):+ writer()+ assert "" not in seen++An atomic writer (temp file + rename) only writes to its temp file, so the target still holds the+old bytes (or does not exist yet) at every observation.+"""++from __future__ import annotations++import io+import sys+from collections.abc import Callable, Iterator+from contextlib import contextmanager+++@contextmanager+def observe_file_writes(callback: Callable[[], None]) -> Iterator[None]:+ """Call ``callback()`` before every ``write``/``writelines`` on a file object in this thread."""++ def _profile(frame, event, arg):+ if event != "c_call":+ return+ if getattr(arg, "__name__", "") not in ("write", "writelines"):+ return+ if isinstance(getattr(arg, "__self__", None), io.IOBase):+ callback()++ previous = sys.getprofile()+ sys.setprofile(_profile)+ try:+ yield+ finally:+ sys.setprofile(previous)