Skip to content

The agent that grows with you

refactor(skills): trim same-root duplicate resolution to its minimal shape

teknium12d34f62fbbdf
diff --git a/tests/tools/test_skills_tool.py b/tests/tools/test_skills_tool.py
index 67280e36d9f..3aa74ab098d 100644
--- a/tests/tools/test_skills_tool.py
+++ b/tests/tools/test_skills_tool.py
@@ -1033,23 +1033,15 @@ class TestSkillViewCollisionDetection:
class TestSameRootDuplicationResolves:
- """Duplication inside ONE search dir is not tier shadowing.
-
- A root may legitimately carry both ``<root>/name`` and a categorized or legacy copy
- (``<root>/research/name``, ``<root>/notes/name.md``). Before this, every such name was
- UNLOADABLE by its bare name (measured: 106 names in one root), which silently emptied
- every skill bundle declaring them. Resolution is deterministic — a real SKILL.md beats a
- legacy flat ``<name>.md``, then the shallower path wins — and it is logged, not silent.
- A true ambiguity (equal rank, or candidates spanning two tiers) still refuses.
- """
+ """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."""
def _patch_dirs(self, local_dir, external_dirs=()):
return (
patch("tools.skills_tool.SKILLS_DIR", local_dir),
- patch(
- "agent.skill_utils.get_external_skills_dirs",
- return_value=list(external_dirs),
- ),
+ patch("agent.skill_utils.get_external_skills_dirs", return_value=list(external_dirs)),
)
def test_nested_copy_inside_same_root_does_not_block_bare_name(self, tmp_path):
@@ -1066,22 +1058,6 @@ class TestSameRootDuplicationResolves:
assert result["path"] == "arxiv/SKILL.md"
assert "TOP LEVEL VERSION" in result["content"]
- def test_legacy_flat_md_never_shadows_real_skill(self, tmp_path):
- local_dir = tmp_path / "local"
- local_dir.mkdir()
- _make_skill(local_dir, "context-compression", body="REAL SKILL")
- legacy = local_dir / "research" / "llm-wiki" / "concepts" / "context-compression.md"
- legacy.parent.mkdir(parents=True, exist_ok=True)
- legacy.write_text("# concept note, not a skill\n")
-
- p1, p2 = self._patch_dirs(local_dir)
- with p1, p2:
- result = json.loads(skill_view("context-compression"))
-
- assert result["success"] is True, result
- assert result["path"] == "context-compression/SKILL.md"
- assert "REAL SKILL" in result["content"]
-
def test_equal_rank_same_root_still_refuses(self, tmp_path):
local_dir = tmp_path / "local"
local_dir.mkdir()
@@ -1098,24 +1074,24 @@ class TestSameRootDuplicationResolves:
class TestTrustWarningSymlinkAware:
- """Trust must be decided by the path that EXPOSED a skill as well as its real location.
-
- Regression: the local skills root is largely a symlink view of the library, so resolving
- the path first made EVERY load warn "outside the trusted skills directory" (measured ~2k
- warnings in one bundle-heavy session) and buried the real injection-pattern signal.
- """
+ """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."""
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):
- lib = tmp_path / "library"; lib.mkdir()
- root = tmp_path / "root"; root.mkdir()
+ lib = tmp_path / "library"
+ root = tmp_path / "root"
real = lib / "demo"
- real.mkdir()
+ real.mkdir(parents=True)
+ root.mkdir()
(real / "SKILL.md").write_text("---\nname: demo\ndescription: d.\n---\nbody\n")
- (root / "demo").symlink_to(real)
+ try:
+ (root / "demo").symlink_to(real, target_is_directory=True)
+ except (OSError, NotImplementedError) as exc:
+ pytest.skip(f"symlinks unavailable in test environment: {exc}")
with caplog.at_level("WARNING"):
self._log("demo", root / "demo" / "SKILL.md", [root], root)
@@ -1123,7 +1099,8 @@ class TestTrustWarningSymlinkAware:
assert "outside the trusted" not in caplog.text, caplog.text
def test_genuinely_outside_file_still_warns(self, tmp_path, caplog):
- root = tmp_path / "root"; root.mkdir()
+ root = tmp_path / "root"
+ root.mkdir()
outside = tmp_path / "elsewhere" / "x" / "SKILL.md"
outside.parent.mkdir(parents=True)
outside.write_text("---\nname: x\ndescription: d.\n---\nbody\n")
diff --git a/tools/skills_tool.py b/tools/skills_tool.py
index 1c00ceca70e..b1900e38006 100644
--- a/tools/skills_tool.py
+++ b/tools/skills_tool.py
@@ -473,31 +473,16 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict
def _owning_search_dir(skill_md: Path, all_dirs) -> Optional[Path]:
- """The most specific search dir containing *skill_md*, compared **lexically**.
+ """Most specific search dir containing *skill_md*, compared lexically: a symlinked entry
+ belongs to the root that exposes it, not to the root its target lives in."""
+ owners = [Path(d) for d in all_dirs if skill_md.is_relative_to(d)]
+ return max(owners, key=lambda d: len(d.parts), default=None)
- Symlinks are deliberately NOT followed: a skill entry exposed by a root via symlink
- belongs to that root (that is what decides same-root duplication vs cross-tier
- shadowing), even though the file it points at lives elsewhere.
- """
- best: Optional[Path] = None
- for search_dir in all_dirs:
- with suppress(Exception):
- if skill_md.is_relative_to(search_dir) and (
- best is None or len(Path(search_dir).parts) > len(Path(best).parts)
- ):
- best = Path(search_dir)
- return best
-
-def _rank_same_root_candidate(candidate, root: Optional[Path]) -> tuple:
- """Deterministic rank for same-root duplicates: a real SKILL.md beats a legacy flat
- ``<name>.md`` (a support note must never shadow a skill), then shallower path wins."""
+def _rank_same_root_candidate(candidate, root: Path) -> tuple:
+ """Real SKILL.md beats a legacy flat ``<name>.md``, then the shallower path wins."""
_skill_dir, skill_md = candidate
- is_flat = 0 if skill_md.name == "SKILL.md" else 1
- with suppress(Exception):
- if root is not None:
- return (is_flat, len(skill_md.relative_to(root).parts))
- return (is_flat, len(skill_md.parts))
+ return (skill_md.name != "SKILL.md", len(skill_md.relative_to(root).parts))
def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: list, all_dirs):
@@ -513,27 +498,17 @@ def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: l
# ambiguity WITHIN the project tier still refuses.
candidates = [c for c in candidates if _under_any(c[1], project_dirs)] or candidates
if len(candidates) > 1:
- # Same-root duplication is NOT the shadowing bug class this guard exists for: when one
- # search dir carries both ``<root>/arxiv`` and a category/legacy copy of it
- # (``<root>/research/arxiv``, ``<root>/.../arxiv.md``), no second tier is involved, so
- # there is nothing that could be silently shadowed — refusing would only make the skill
- # unloadable by its bare name (measured: 106 such names in one root, breaking every
- # bundle that declares them). Resolve deterministically, log it, and keep refusing a TRUE
- # ambiguity (equal rank, or candidates spanning two tiers — the local-vs-external case).
+ # 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.
roots = {_owning_search_dir(smd, all_dirs) for _sd, smd in candidates}
- if len(roots) == 1 and next(iter(roots)) is not None:
- # Non-None guard: every candidate is built from a search dir today, so an
- # all-None set should be unreachable — but if it ever happens the "same root"
- # claim would be unfounded and the tie-break could silently cross tiers,
- # which is exactly what the refusal below exists to prevent.
- root = next(iter(roots))
+ if len(roots) == 1 and None not in roots:
+ 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)",
- name, len(candidates), ranked[0][1],
- "; ".join(str(smd) for _sd, smd in ranked[1:]),
- )
+ logger.info("Skill '%s': %d same-root candidates, resolved to %s (nested: %s)",
+ name, len(candidates), ranked[0][1],
+ "; ".join(str(smd) for _sd, smd in ranked[1:]))
candidates = [ranked[0]]
if len(candidates) > 1:
paths = [str(smd) for _, smd in candidates]
@@ -564,25 +539,15 @@ def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: l
def _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.
-
- Trust is decided on the path that EXPOSED the skill as well as on its real location. A root
- that deliberately exposes a skill through a symlink (the local skills dir is largely a symlink
- view of the library) has vouched for it; resolving first made every such skill warn —
- measured ~2k spurious warnings per bundle-heavy session, which buries the real signal. The
- injection-pattern check below is independent and still runs.
- """
+ 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)."""
trusted_dirs = [active_skills_dir.resolve()]
with suppress(Exception):
trusted_dirs.extend(d.resolve() for d in all_dirs)
-
- def _exposed_under(path: Path, dirs) -> bool:
- with suppress(Exception):
- return any(path.is_relative_to(Path(d)) for d in dirs)
- return False
-
warnings = []
- if not (_under_any(skill_md, trusted_dirs) or _exposed_under(skill_md, [active_skills_dir, *all_dirs])):
+ if not (_under_any(skill_md, trusted_dirs)
+ or any(skill_md.is_relative_to(d) for d in (active_skills_dir, *all_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")