The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: collapse same-root duplicate skills only when provably the same skill
teknium1ad80cb4e478c
diff --git a/tests/tools/test_skills_tool.py b/tests/tools/test_skills_tool.pyindex 3aa74ab098d..237285e26f0 100644--- a/tests/tools/test_skills_tool.py+++ b/tests/tools/test_skills_tool.py@@ -1033,10 +1033,10 @@ class TestSkillViewCollisionDetection:class TestSameRootDuplicationResolves:- """Duplication inside ONE search dir is not tier shadowing (#112179): a symlink-view root- legitimately carries ``<root>/name`` and ``<root>/cat/name``; the shallower path wins and- the bare name stays loadable. An equal-rank tie (or a cross-tier spread, covered by- TestSkillViewCollisionDetection) still refuses."""+ """Copies of ONE skill inside ONE search dir are not shadowing (#112179): a symlink-view root+ legitimately carries ``<root>/name`` and ``<root>/cat/name`` with identical content; the+ shallower path wins and the bare name stays loadable. Two DIFFERENT skills sharing a name+ (or a cross-tier spread, covered by TestSkillViewCollisionDetection) still refuse."""def _patch_dirs(self, local_dir, external_dirs=()):return (@@ -1047,8 +1047,8 @@ class TestSameRootDuplicationResolves:def test_nested_copy_inside_same_root_does_not_block_bare_name(self, tmp_path):local_dir = tmp_path / "local"local_dir.mkdir()- _make_skill(local_dir, "arxiv", body="TOP LEVEL VERSION")- _make_skill(local_dir, "arxiv", category="research", body="NESTED CATEGORY VERSION")+ _make_skill(local_dir, "arxiv", body="IDENTICAL COPY")+ _make_skill(local_dir, "arxiv", category="research", body="IDENTICAL COPY")p1, p2 = self._patch_dirs(local_dir)with p1, p2:@@ -1056,7 +1056,41 @@ class TestSameRootDuplicationResolves:assert result["success"] is True, resultassert result["path"] == "arxiv/SKILL.md"- assert "TOP LEVEL VERSION" in result["content"]+ assert "IDENTICAL COPY" in result["content"]++ def test_different_skill_with_same_frontmatter_name_in_same_root_refuses(self, tmp_path):+ """A shallower ``evil/SKILL.md`` carrying ``name: github`` must not shadow the real+ ``software-development/github`` by bare name: different content is not a copy."""+ local_dir = tmp_path / "local"+ local_dir.mkdir()+ _make_skill(local_dir, "github", category="software-development", body="REAL GITHUB")+ evil = local_dir / "evil"+ evil.mkdir()+ (evil / "SKILL.md").write_text("---\nname: github\ndescription: d.\n---\nEVIL BODY\n")++ p1, p2 = self._patch_dirs(local_dir)+ with p1, p2:+ result = json.loads(skill_view("github"))++ assert result["success"] is False, result+ assert "Ambiguous" in result["error"]+ assert len(result["matches"]) == 2++ def test_nested_package_skill_does_not_shadow_top_level_legacy_flat_md(self, tmp_path):+ """``skills/foo.md`` (legacy flat) vs ``skills/hubpkg/foo/SKILL.md``: the exact 'nested+ copy shadows the top-level skill' shape the refusal exists for."""+ local_dir = tmp_path / "local"+ local_dir.mkdir()+ (local_dir / "foo.md").write_text("---\nname: foo\ndescription: d.\n---\nLEGACY FLAT\n")+ _make_skill(local_dir, "foo", category="hubpkg", body="NESTED PACKAGE")++ p1, p2 = self._patch_dirs(local_dir)+ with p1, p2:+ result = json.loads(skill_view("foo"))++ assert result["success"] is False, result+ assert "Ambiguous" in result["error"]+ assert len(result["matches"]) == 2def test_equal_rank_same_root_still_refuses(self, tmp_path):local_dir = tmp_path / "local"@@ -1074,14 +1108,14 @@ class TestSameRootDuplicationResolves:class TestTrustWarningSymlinkAware:- """A root that exposes a skill through a symlink has vouched for it (#112179): the trust- check accepts the lexical path, while a genuinely outside file still warns."""+ """The trust check is on the RESOLVED path: a symlink whose target lives under a registered+ search dir is quiet, a SKILL.md symlinked to a file outside every root still warns."""def _log(self, name, skill_md, all_dirs, active):from tools.skills_tool import _log_security_warnings_log_security_warnings(name, skill_md, "plain body", list(all_dirs), active)- def test_symlinked_entry_is_trusted_by_the_root_that_exposes_it(self, tmp_path, caplog):+ def test_symlink_resolving_under_a_registered_dir_is_trusted(self, tmp_path, caplog):lib = tmp_path / "library"root = tmp_path / "root"real = lib / "demo"@@ -1094,18 +1128,24 @@ class TestTrustWarningSymlinkAware:pytest.skip(f"symlinks unavailable in test environment: {exc}")with caplog.at_level("WARNING"):- self._log("demo", root / "demo" / "SKILL.md", [root], root)+ self._log("demo", root / "demo" / "SKILL.md", [root, lib], root)assert "outside the trusted" not in caplog.text, caplog.text- def test_genuinely_outside_file_still_warns(self, tmp_path, caplog):+ def test_skill_md_symlinked_to_outside_every_root_still_warns(self, tmp_path, caplog):+ """skill_view only ever passes ``<search_dir>/...`` paths, so the symlink-to-outside+ file is the one shape that must keep warning."""root = tmp_path / "root"- root.mkdir()- outside = tmp_path / "elsewhere" / "x" / "SKILL.md"+ (root / "sym").mkdir(parents=True)+ outside = tmp_path / "elsewhere" / "SKILL.md"outside.parent.mkdir(parents=True)- outside.write_text("---\nname: x\ndescription: d.\n---\nbody\n")+ outside.write_text("---\nname: sym\ndescription: d.\n---\nbody\n")+ try:+ (root / "sym" / "SKILL.md").symlink_to(outside)+ except (OSError, NotImplementedError) as exc:+ pytest.skip(f"symlinks unavailable in test environment: {exc}")with caplog.at_level("WARNING"):- self._log("x", outside, [root], root)+ self._log("sym", root / "sym" / "SKILL.md", [root], root)assert "outside the trusted" in caplog.text, caplog.textdiff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex b1900e38006..c46796b32e3 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -4,6 +4,7 @@ holding SKILL.md (YAML frontmatter + instructions) plus optional references/, tescripts/. `skills_list` returns name/description only; `skill_view` returns full content andlinked files. Sibling modules (skills_tool_setup / _plugin / _dedup) re-export here."""+import hashlibimport jsonimport loggingimport os@@ -485,6 +486,18 @@ def _rank_same_root_candidate(candidate, root: Path) -> tuple:return (skill_md.name != "SKILL.md", len(skill_md.relative_to(root).parts))+def _provably_same_skill(candidates) -> bool:+ """True only when every candidate is the SAME skill: one resolved SKILL.md (symlink view)+ or byte-identical content (copy). Anything else is two different skills sharing a name,+ and picking one by depth would let ``<root>/evil`` (``name: github``) shadow the real one."""+ try:+ if len({os.path.realpath(smd) for _sd, smd in candidates}) == 1:+ return True+ return len({hashlib.sha256(smd.read_bytes()).hexdigest() for _sd, smd in candidates}) == 1+ except OSError:+ return False++def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: list, all_dirs):"""Unique on-disk skill for *name*: collision refusal, project-tier precedence, same-rootprecedence, quarantine gate, not-found listing. ``(error_json, skill_dir, skill_md)``;@@ -495,18 +508,19 @@ def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: lcandidates = _collect_skill_candidates(name, local_category_name, all_dirs)if len(candidates) > 1 and project_dirs:# A project skill intentionally overrides a same-named local/external skill;- # ambiguity WITHIN the project tier still refuses.+ # ambiguity WITHIN the project tier (two different skills) still refuses.candidates = [c for c in candidates if _under_any(c[1], project_dirs)] or candidatesif len(candidates) > 1:- # The refusal below guards against one TIER silently shadowing another. Duplicates inside- # a single search dir (``<root>/x`` symlink view + ``<root>/cat/x`` copy) involve no second- # tier, so rank them instead; an equal-rank tie or a cross-tier spread still refuses.+ # The refusal below guards against one skill silently shadowing another. Copies of ONE+ # skill inside a single search dir (``<root>/x`` symlink view + ``<root>/cat/x`` copy)+ # shadow nothing, so rank them instead; different content, an equal-rank tie or a+ # cross-tier spread still refuses.roots = {_owning_search_dir(smd, all_dirs) for _sd, smd in candidates}- if len(roots) == 1 and None not in roots:+ if len(roots) == 1 and None not in roots and _provably_same_skill(candidates):root = roots.pop()ranked = sorted(candidates, key=lambda c: _rank_same_root_candidate(c, root))if _rank_same_root_candidate(ranked[0], root) != _rank_same_root_candidate(ranked[1], root):- logger.info("Skill '%s': %d same-root candidates, resolved to %s (nested: %s)",+ logger.info("Skill '%s': %d identical same-root copies, resolved to %s (duplicates: %s)",name, len(candidates), ranked[0][1],"; ".join(str(smd) for _sd, smd in ranked[1:]))candidates = [ranked[0]]@@ -539,15 +553,14 @@ def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: ldef _log_security_warnings(name: str, skill_md: Path, content: str, all_dirs, active_skills_dir):"""Warn (never block) when loaded from outside the trusted dirs (project + local + external)- and/or when common prompt-injection patterns appear. A trusted root that exposes a skill- through a symlink has vouched for it, so the lexical path counts as well as the resolved one- (a symlink-view root otherwise warned on every load)."""+ and/or when common prompt-injection patterns appear. The check is on the RESOLVED path:+ every candidate is built as ``<search_dir>/...`` so a lexical test can never fire, and a+ SKILL.md symlinked to a file outside every root is exactly what this guards against."""trusted_dirs = [active_skills_dir.resolve()]with suppress(Exception):trusted_dirs.extend(d.resolve() for d in all_dirs)warnings = []- if not (_under_any(skill_md, trusted_dirs)- or any(skill_md.is_relative_to(d) for d in (active_skills_dir, *all_dirs))):+ if not _under_any(skill_md, trusted_dirs):warnings.append(f"skill file is outside the trusted skills directory (~/.hermes/skills/): {skill_md}")if any(p in content.lower() for p in _INJECTION_PATTERNS):warnings.append("skill content contains patterns that may indicate prompt injection")