Skip to content

The agent that grows with you

fix(skills): exclude generated runtime caches from bundled ownership hashes

Xipong25a80b3bb6c1
diff --git a/tests/tools/test_skills_runtime_cache.py b/tests/tools/test_skills_runtime_cache.py
new file mode 100644
index 00000000000..dc4dce8f0cc
--- /dev/null
+++ b/tests/tools/test_skills_runtime_cache.py
@@ -0,0 +1,161 @@
+"""Runtime caches must not take ownership of updater-managed skill packages."""
+
+import hashlib
+import py_compile
+
+import pytest
+
+from tools import skills_sync as ss
+from tools.skills_sync_bundled_ops import diff_bundled_skill, list_user_modified_bundled_skills
+from tools.skills_sync_optional import _skill_file_list
+
+
+def _legacy_hash(directory):
+ digest = hashlib.md5()
+ for path in sorted(directory.rglob("*")):
+ if path.is_file():
+ digest.update(str(path.relative_to(directory)).encode("utf-8"))
+ digest.update(path.read_bytes())
+ return digest.hexdigest()
+
+
+def _write(root, rel, text):
+ target = root / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text, encoding="utf-8")
+ return target
+
+
+def skill_tree(tmp_path, monkeypatch):
+ base = tmp_path / "profile"
+ bundled = base / "bundled"
+ src = bundled / "coding" / "demo"
+ _write(src, "SKILL.md", "---\nname: demo\n---\n# Demo\n")
+ _write(src, "scripts/helper.py", "ANSWER = 1\n")
+ skills = base / "skills"
+ monkeypatch.setattr(ss, "HERMES_HOME", base)
+ monkeypatch.setattr(ss, "SKILLS_DIR", skills)
+ monkeypatch.setattr(ss, "MANIFEST_FILE", skills / ".bundled_manifest")
+ monkeypatch.setattr(ss, "_get_bundled_dir", lambda: bundled)
+ monkeypatch.setattr(ss, "_get_optional_dir", lambda: base / "no-optional")
+ monkeypatch.setattr(ss, "_build_external_skill_index", set)
+ monkeypatch.setattr(ss, "_read_suppressed_names", set)
+ assert ss.sync_skills(quiet=True)["copied"] == ["demo"]
+ return src, skills / "coding" / "demo"
+
+
+def test_real_python_compilation_does_not_freeze_update(skill_tree):
+ src, dest = skill_tree
+ origin = ss._read_manifest()["demo"]
+ py_compile.compile(str(dest / "scripts/helper.py"), doraise=True)
+ assert list((dest / "scripts/__pycache__").glob("*.pyc"))
+ assert ss._dir_hash(dest) == origin
+ assert list_user_modified_bundled_skills() == []
+ assert diff_bundled_skill("demo")["diffs"] == []
+ _write(src, "scripts/helper.py", "ANSWER = 2\n")
+ result = ss.sync_skills(quiet=True)
+ assert result["updated"] == ["demo"]
+ assert (dest / "scripts/helper.py").read_text() == "ANSWER = 2\n"
+ assert ss._read_manifest()["demo"] == ss._dir_hash(src)
+
+
[email protected]("cache_path", [
+ "scripts/__pycache__/helper.cpython-311.pyc",
+ ".pytest_cache/v/cache/nodeids",
+ "scripts/.mypy_cache/3.11/helper.data.json",
+ "scripts/.ruff_cache/0.15.0/abc",
+ "scripts/helper.pyc", "scripts/helper.pyo",
+])
+def test_runtime_cache_is_not_hash_or_diff_content(skill_tree, cache_path):
+ src, dest = skill_tree
+ _write(dest, cache_path, "generated")
+ assert ss._dir_hash(dest) == ss._dir_hash(src)
+ assert cache_path not in _skill_file_list(dest)
+ assert diff_bundled_skill("demo")["modified"] is False
+
+
[email protected]("edited_path", ["SKILL.md", "scripts/helper.py", "references/notes.md", "cache/data.json", "scripts/bytecode_only.pyc"])
+def test_genuine_edits_next_to_cache_are_preserved(skill_tree, edited_path):
+ src, dest = skill_tree
+ _write(dest, "scripts/__pycache__/helper.cpython-311.pyc", "generated")
+ _write(dest, edited_path, "user-owned content")
+ _write(src, "references/new-upstream.md", "new upstream documentation")
+ assert [entry["name"] for entry in list_user_modified_bundled_skills()] == ["demo"]
+ result = ss.sync_skills(quiet=True)
+ assert result["user_modified"] == ["demo"]
+ assert (dest / edited_path).read_text() == "user-owned content"
+ assert not (dest / "references/new-upstream.md").exists()
+
+
+def test_source_cache_is_neither_seeded_nor_recorded(skill_tree):
+ src, dest = skill_tree
+ _write(src, "scripts/__pycache__/helper.cpython-311.pyc", "source generated")
+ _write(src, "SKILL.md", "---\nname: demo\n---\n# Changed upstream\n")
+ assert ss.sync_skills(quiet=True)["updated"] == ["demo"]
+ assert not (dest / "scripts/__pycache__").exists()
+ ss._rmtree_writable(dest)
+ ss._write_manifest({})
+ assert ss.sync_skills(quiet=True)["copied"] == ["demo"]
+ assert not (dest / "scripts/__pycache__").exists()
+
+
+def test_legacy_cache_hash_migrates_only_with_matching_origin(skill_tree):
+ src, dest = skill_tree
+ _write(dest, "scripts/__pycache__/helper.cpython-311.pyc", "legacy generated")
+ ss._write_manifest({"demo": _legacy_hash(dest)})
+ assert list_user_modified_bundled_skills() == []
+ _write(src, "scripts/helper.py", "ANSWER = 2\n")
+ assert ss.sync_skills(quiet=True)["updated"] == ["demo"]
+ assert ss._read_manifest()["demo"] == ss._dir_hash(src)
+
+
+def test_legacy_hash_mismatch_never_rebaselines_user_edits(skill_tree):
+ src, dest = skill_tree
+ cache = _write(dest, "scripts/__pycache__/helper.cpython-311.pyc", "legacy generated")
+ origin = _legacy_hash(dest)
+ ss._write_manifest({"demo": origin})
+ cache.unlink()
+ _write(dest, "scripts/helper.py", "user edit\n")
+ _write(src, "scripts/helper.py", "upstream edit\n")
+ assert ss.sync_skills(quiet=True)["user_modified"] == ["demo"]
+ assert ss._read_manifest()["demo"] == origin
+ assert (dest / "scripts/helper.py").read_text() == "user edit\n"
+
+
+def test_clean_manifest_hash_is_backwards_compatible(skill_tree):
+ src, dest = skill_tree
+ assert ss._dir_hash(src) == _legacy_hash(src)
+ assert ss._dir_hash(dest) == _legacy_hash(dest)
+
+
+def test_runtime_cache_does_not_hide_dotfile_edit(skill_tree):
+ src, dest = skill_tree
+ _write(dest, ".settings.json", "user settings")
+ _write(dest, ".pytest_cache/v/cache/nodeids", "[]")
+ assert ss._dir_hash(dest) != ss._dir_hash(src)
+ assert ".settings.json" in _skill_file_list(dest)
+ assert [e["path"] for e in diff_bundled_skill("demo")["diffs"]] == [".settings.json"]
+
+
+def test_legacy_cache_origin_allows_rename_without_freezing(skill_tree):
+ src, dest = skill_tree
+ _write(dest, "scripts/__pycache__/helper.cpython-311.pyc", "legacy generated")
+ ss._write_manifest({"demo": _legacy_hash(dest)})
+ new_src = src.parent.parent / "recategorized" / "demo"
+ new_src.parent.mkdir(parents=True)
+ src.rename(new_src)
+ _write(new_src, "scripts/helper.py", "ANSWER = 3\n")
+ result = ss.sync_skills(quiet=True)
+ assert result["updated"] == ["demo"]
+ assert not dest.exists()
+ assert (ss._skills_dir() / "recategorized/demo/scripts/helper.py").read_text() == "ANSWER = 3\n"
+
+
+def test_hash_filter_is_skill_relative(tmp_path):
+ # A Python environment/install prefix can itself contain a cache name.
+ src = tmp_path / "__pycache__" / "demo"
+ _write(src, "SKILL.md", "real skill content")
+ _write(src, "scripts/helper.py", "ANSWER = 1\n")
+ assert ss._dir_hash(src) == _legacy_hash(src)
+ assert set(_skill_file_list(src)) == {"SKILL.md", "scripts/helper.py"}
diff --git a/tools/skills_sync.py b/tools/skills_sync.py
index 322167e5ade..ca774820be5 100644
--- a/tools/skills_sync.py
+++ b/tools/skills_sync.py
@@ -25,8 +25,9 @@ for _stream in (sys.stdout, sys.stderr):
from hermes_constants import get_bundled_skills_dir, get_hermes_home, get_optional_skills_dir
from agent.skill_utils import ESSENTIAL_SKILLS, is_excluded_skill_path
from tools.skill_usage import _read_skill_name, read_suppressed_names
-from tools.skills_sync_bundled_ops import _is_tracked_user_modification
-from tools.skills_sync_optional import _backfill_optional_provenance, _read_hub_install_paths
+from tools.skills_sync_optional import (
+ _backfill_optional_provenance, _ignore_runtime_cache, _is_runtime_cache, _read_hub_install_paths,
+)
from utils import atomic_write_text
logger = logging.getLogger(__name__)
@@ -150,17 +151,34 @@ def _compute_relative_dest(skill_dir: Path, bundled_dir: Path) -> Path:
return _skills_dir() / skill_dir.relative_to(bundled_dir)
-def _dir_hash(directory: Path) -> str:
- """MD5 over relative paths + contents of every file in a directory."""
+def _dir_hash(directory: Path, *, include_runtime_cache: bool = False) -> str:
+ """MD5 of package paths/content, excluding generated runtime state.
+
+ The legacy option is only for proving an exact pre-filter origin match.
+ Keep the original path encoding so clean existing manifests remain valid.
+ """
hasher = hashlib.md5()
with suppress(OSError):
for fpath in sorted(directory.rglob("*")):
- if fpath.is_file():
+ if (include_runtime_cache or not _is_runtime_cache(fpath, directory)) and fpath.is_file():
hasher.update(str(fpath.relative_to(directory)).encode("utf-8"))
hasher.update(fpath.read_bytes())
return hasher.hexdigest()
+def _matches_origin_hash(directory: Path, origin_hash: str, user_hash: Optional[str] = None) -> bool:
+ """Prove unchanged package ownership against a clean OR exact legacy hash.
+
+ Never re-baseline a differing package merely because it contains a cache:
+ if legacy cached bytes changed/disappeared, the old origin cannot be proven.
+ A genuinely edited package must remain protected in that case.
+ """
+ if not origin_hash:
+ return False
+ current = _dir_hash(directory) if user_hash is None else user_hash
+ return current == origin_hash or _dir_hash(directory, include_runtime_cache=True) == origin_hash
+
+
def _move_dir(src: Path, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(src), str(dest))
@@ -168,7 +186,7 @@ def _move_dir(src: Path, dest: Path) -> None:
def _copy_dir(src: Path, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
- shutil.copytree(src, dest)
+ shutil.copytree(src, dest, ignore=_ignore_runtime_cache)
def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Optional[str]:
@@ -192,7 +210,7 @@ def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Opt
continue
if rel in st.hub_paths: # the hub owns its install paths
continue
- if _dir_hash(candidate) != origin_hash: # moving a customized copy would edit user work
+ if not _matches_origin_hash(candidate, origin_hash): # moving a customized copy would edit user work
st.say(
f" ⚠ {skill_name}: upstream moved this skill to {_rel_skills_posix(dest)}, but your "
f"modified copy at {rel} was kept — it will not receive updates. "
@@ -284,7 +302,7 @@ def _replace_skill_dir(skill_src: Path, dest: Path) -> None:
_rmtree_writable(backup)
shutil.move(str(dest), str(backup))
try:
- shutil.copytree(skill_src, dest)
+ shutil.copytree(skill_src, dest, ignore=_ignore_runtime_cache)
except OSError:
if backup.exists(): # clear a partially-written dest so it can't shadow/block the restore
if dest.exists():
@@ -313,7 +331,7 @@ def _update_existing_skill(st: _SyncState, skill_name: str, skill_src: Path, des
st.manifest[skill_name] = user_hash
st.skipped += 1
return
- if _is_tracked_user_modification(origin_hash, user_hash):
+ if not _matches_origin_hash(dest, origin_hash, user_hash):
st.user_modified.append(skill_name)
st.say(f" ~ {skill_name} (user-modified, skipping)")
return
diff --git a/tools/skills_sync_bundled_ops.py b/tools/skills_sync_bundled_ops.py
index fe63ec96ec6..5f66e12025d 100644
--- a/tools/skills_sync_bundled_ops.py
+++ b/tools/skills_sync_bundled_ops.py
@@ -7,12 +7,6 @@ from typing import List, Optional, Tuple
from tools.skills_sync_optional import _skill_file_list, _ss
-def _is_tracked_user_modification(origin_hash: str, user_hash: str) -> bool:
- """User modification ``hermes update`` keeps: a recorded origin hash (un-baselined v1 entries
- don't count) AND differing content. Shared by the sync loop and list-modified (no drift)."""
- return bool(origin_hash) and user_hash != origin_hash
-
-
def _bundled_state():
"""``(skills_sync, manifest, bundled_dir, {skill_name: bundled_src})`` — shared op preamble."""
ss = _ss()
@@ -75,7 +69,7 @@ def list_user_modified_bundled_skills() -> List[dict]:
for skill_name, skill_dir in ss._discover_bundled_skills(bundled_dir):
origin_hash = manifest.get(skill_name, "") # empty = untracked/un-baselined v1: next sync handles it
dest = ss._compute_relative_dest(skill_dir, bundled_dir)
- if origin_hash and dest.exists() and _is_tracked_user_modification(origin_hash, ss._dir_hash(dest)):
+ if origin_hash and dest.exists() and not ss._matches_origin_hash(dest, origin_hash):
modified.append({"name": skill_name, "dest": dest, "bundled_src": skill_dir})
return sorted(modified, key=lambda e: e["name"])
@@ -180,7 +174,7 @@ def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:
if not dry_run: # already gone from disk; forget the stale manifest entry
manifest.pop(name, None)
continue
- if ss._dir_hash(dest) != origin_hash:
+ if not ss._matches_origin_hash(dest, origin_hash):
skipped.append({"name": name, "reason": "user-modified (kept)"})
continue
if not dry_run:
diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.py
index 20bcf969363..313de12c880 100644
--- a/tools/skills_sync_optional.py
+++ b/tools/skills_sync_optional.py
@@ -38,9 +38,36 @@ def _safe_rel_install_path(path: Path, base: Path) -> str:
return "/".join(parts)
+# Only generated runtime state, never generic cache/ or arbitrary dotfiles. This
+# is updater ownership, not the security scanner's content-integrity policy.
+_RUNTIME_CACHE_DIRS = frozenset({"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"})
+
+
+def _is_runtime_cache(path: Path, skill_dir: Path) -> bool:
+ """Whether a skill-relative path is disposable Python/tool runtime state.
+
+ Install prefixes may themselves contain a cache directory name. Legacy
+ sibling bytecode is ignored only alongside its source; source-less .pyc
+ files can be deliberately shipped or user-owned content.
+ """
+ relative = path.relative_to(skill_dir)
+ if any(part in _RUNTIME_CACHE_DIRS for part in relative.parts[:-1]):
+ return True
+ if path.name in _RUNTIME_CACHE_DIRS and path.is_dir():
+ return True
+ return path.suffix in {".pyc", ".pyo"} and path.with_suffix(".py").is_file()
+
+
+def _ignore_runtime_cache(directory: str, names: List[str]) -> List[str]:
+ """copytree callback: don't seed generated caches into managed packages."""
+ root = Path(directory)
+ return [name for name in names if _is_runtime_cache(root / name, root)]
+
+
def _skill_file_list(skill_dir: Path) -> List[str]:
- """List files inside a skill directory in lock-file format."""
- return [f.relative_to(skill_dir).as_posix() for f in sorted(skill_dir.rglob("*")) if f.is_file()]
+ """List package files for provenance/diff, excluding generated runtime caches."""
+ return [f.relative_to(skill_dir).as_posix() for f in sorted(skill_dir.rglob("*"))
+ if not _is_runtime_cache(f, skill_dir) and f.is_file()]
def _load_hub_lock() -> Optional[dict]: