From e1a85406b6f021d41908873c1ef070a0df1bb5df Mon Sep 17 00:00:00 2001 From: graysonzeng <916028390@qq.com> Date: Sat, 11 Apr 2026 16:23:23 +0800 Subject: [PATCH] fix(skills): follow symlinks with cycle guard across all skill discovery paths --- agent/skill_commands.py | 6 ++--- agent/skill_utils.py | 37 +++++++++++++++++++++++++----- gateway/run.py | 8 +++---- hermes_cli/profiles.py | 7 ++---- tests/agent/test_skill_commands.py | 29 +++++++++++++++++++++++ tools/skill_manager_tool.py | 4 ++-- tools/skills_tool.py | 14 +++++------ 7 files changed, 75 insertions(+), 30 deletions(-) diff --git a/agent/skill_commands.py b/agent/skill_commands.py index 1f000eefed2a1..c1cef3ae9503c 100644 --- a/agent/skill_commands.py +++ b/agent/skill_commands.py @@ -207,7 +207,7 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]: _skill_commands = {} try: from tools.skills_tool import SKILLS_DIR, _parse_frontmatter, skill_matches_platform, _get_disabled_skill_names - from agent.skill_utils import get_external_skills_dirs + from agent.skill_utils import get_external_skills_dirs, walk_skill_files disabled = _get_disabled_skill_names() seen_names: set = set() @@ -218,9 +218,7 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]: dirs_to_scan.extend(get_external_skills_dirs()) for scan_dir in dirs_to_scan: - for skill_md in scan_dir.rglob("SKILL.md"): - if any(part in ('.git', '.github', '.hub') for part in skill_md.parts): - continue + for skill_md in walk_skill_files(scan_dir, "SKILL.md"): try: content = skill_md.read_text(encoding='utf-8') frontmatter, body = _parse_frontmatter(content) diff --git a/agent/skill_utils.py b/agent/skill_utils.py index ba606b358d0c6..0470438fde5ed 100644 --- a/agent/skill_utils.py +++ b/agent/skill_utils.py @@ -429,15 +429,40 @@ def extract_skill_description(frontmatter: Dict[str, Any]) -> str: # ── File iteration ──────────────────────────────────────────────────────── -def iter_skill_index_files(skills_dir: Path, filename: str): - """Walk skills_dir yielding sorted paths matching *filename*. +def walk_skill_files(base_dir: Path, filename: str) -> List[Path]: + """Walk *base_dir* returning sorted paths matching *filename*. + + Follows symlinked directories so that skills installed via ``ln -s`` + are discovered. Uses ``(st_dev, st_ino)`` to detect directory cycles + and avoid infinite recursion. Excludes ``.git``, ``.github``, ``.hub`` directories. """ - matches = [] - for root, dirs, files in os.walk(skills_dir): + results: List[Path] = [] + seen_real: set = set() + for root, dirs, files in os.walk(base_dir, followlinks=True): + # Cycle guard: skip directories we have already traversed + try: + st = os.stat(root) + ident = (st.st_dev, st.st_ino) + except OSError: + dirs[:] = [] + continue + if ident in seen_real: + dirs[:] = [] + continue + seen_real.add(ident) dirs[:] = [d for d in dirs if d not in EXCLUDED_SKILL_DIRS] if filename in files: - matches.append(Path(root) / filename) - for path in sorted(matches, key=lambda p: str(p.relative_to(skills_dir))): + results.append(Path(root) / filename) + return sorted(results, key=lambda p: str(p)) + + +def iter_skill_index_files(skills_dir: Path, filename: str): + """Walk skills_dir yielding sorted paths matching *filename*. + + Excludes ``.git``, ``.github``, ``.hub`` directories. + Follows symlinks with cycle detection (delegates to :func:`walk_skill_files`). + """ + for path in walk_skill_files(skills_dir, filename): yield path diff --git a/gateway/run.py b/gateway/run.py index 2f15361c6aa46..f3502d1404b88 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -377,16 +377,14 @@ def _check_unavailable_skill(command_name: str) -> str | None: normalized = command_name.lower().replace("_", "-") try: from tools.skills_tool import _get_disabled_skill_names - from agent.skill_utils import get_all_skills_dirs + from agent.skill_utils import get_all_skills_dirs, walk_skill_files disabled = _get_disabled_skill_names() # Check disabled skills across all dirs (local + external) for skills_dir in get_all_skills_dirs(): if not skills_dir.exists(): continue - for skill_md in skills_dir.rglob("SKILL.md"): - if any(part in ('.git', '.github', '.hub') for part in skill_md.parts): - continue + for skill_md in walk_skill_files(skills_dir, "SKILL.md"): name = skill_md.parent.name.lower().replace("_", "-") if name == normalized and name in disabled: return ( @@ -399,7 +397,7 @@ def _check_unavailable_skill(command_name: str) -> str | None: repo_root = Path(__file__).resolve().parent.parent optional_dir = get_optional_skills_dir(repo_root / "optional-skills") if optional_dir.exists(): - for skill_md in optional_dir.rglob("SKILL.md"): + for skill_md in walk_skill_files(optional_dir, "SKILL.md"): name = skill_md.parent.name.lower().replace("_", "-") if name == normalized: # Build install path: official// diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py index 6735ff0f047cb..7f6d538ec4a01 100644 --- a/hermes_cli/profiles.py +++ b/hermes_cli/profiles.py @@ -321,11 +321,8 @@ def _count_skills(profile_dir: Path) -> int: skills_dir = profile_dir / "skills" if not skills_dir.is_dir(): return 0 - count = 0 - for md in skills_dir.rglob("SKILL.md"): - if "/.hub/" not in str(md) and "/.git/" not in str(md): - count += 1 - return count + from agent.skill_utils import walk_skill_files + return len(walk_skill_files(skills_dir, "SKILL.md")) # --------------------------------------------------------------------------- diff --git a/tests/agent/test_skill_commands.py b/tests/agent/test_skill_commands.py index 57ac7d6b58fff..0749e336f919a 100644 --- a/tests/agent/test_skill_commands.py +++ b/tests/agent/test_skill_commands.py @@ -46,6 +46,35 @@ def test_finds_skills(self, tmp_path): assert "/my-skill" in result assert result["/my-skill"]["name"] == "my-skill" + def test_finds_symlinked_skill(self, tmp_path): + """Skills installed via symlink should be discovered.""" + real_dir = tmp_path / "real" / "linked-skill" + real_dir.mkdir(parents=True) + (real_dir / "SKILL.md").write_text( + "---\nname: linked-skill\ndescription: A symlinked skill.\n---\n\nBody.\n" + ) + skills_dir = tmp_path / "skills" + skills_dir.mkdir() + (skills_dir / "linked-skill").symlink_to(real_dir, target_is_directory=True) + with patch("tools.skills_tool.SKILLS_DIR", skills_dir): + result = scan_skill_commands() + assert "/linked-skill" in result + assert result["/linked-skill"]["name"] == "linked-skill" + + def test_symlink_cycle_does_not_hang(self, tmp_path): + """A symlink cycle inside the skills dir must not cause infinite recursion.""" + skill_dir = tmp_path / "cyclic-skill" + skill_dir.mkdir() + (skill_dir / "SKILL.md").write_text( + "---\nname: cyclic-skill\ndescription: Has a cycle.\n---\n\nBody.\n" + ) + # Create a directory symlink that points back to the skills root + (skill_dir / "loop").symlink_to(tmp_path, target_is_directory=True) + with patch("tools.skills_tool.SKILLS_DIR", tmp_path): + result = scan_skill_commands() + # Should still find the skill without hanging + assert "/cyclic-skill" in result + def test_empty_dir(self, tmp_path): with patch("tools.skills_tool.SKILLS_DIR", tmp_path): result = scan_skill_commands() diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py index 2273d75fa6f17..de9c9bec0cc66 100644 --- a/tools/skill_manager_tool.py +++ b/tools/skill_manager_tool.py @@ -204,11 +204,11 @@ def _find_skill(name: str) -> Optional[Dict[str, Any]]: external dirs configured via skills.external_dirs. Returns {"path": Path} or None. """ - from agent.skill_utils import get_all_skills_dirs + from agent.skill_utils import get_all_skills_dirs, walk_skill_files for skills_dir in get_all_skills_dirs(): if not skills_dir.exists(): continue - for skill_md in skills_dir.rglob("SKILL.md"): + for skill_md in walk_skill_files(skills_dir, "SKILL.md"): if skill_md.parent.name == name: return {"path": skill_md.parent} return None diff --git a/tools/skills_tool.py b/tools/skills_tool.py index 085ed0055094d..3c0b380c9e874 100644 --- a/tools/skills_tool.py +++ b/tools/skills_tool.py @@ -529,7 +529,7 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]: Returns: List of skill metadata dicts (name, description, category). """ - from agent.skill_utils import get_external_skills_dirs + from agent.skill_utils import get_external_skills_dirs, walk_skill_files skills = [] seen_names: set = set() @@ -544,9 +544,7 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]: dirs_to_scan.extend(get_external_skills_dirs()) for scan_dir in dirs_to_scan: - for skill_md in scan_dir.rglob("SKILL.md"): - if any(part in _EXCLUDED_SKILL_DIRS for part in skill_md.parts): - continue + for skill_md in walk_skill_files(scan_dir, "SKILL.md"): skill_dir = skill_md.parent @@ -671,12 +669,11 @@ def skills_categories(verbose: bool = False, task_id: str = None) -> str: ensure_ascii=False, ) + from agent.skill_utils import walk_skill_files as _walk category_dirs = {} category_counts: Dict[str, int] = {} for scan_dir in all_dirs: - for skill_md in scan_dir.rglob("SKILL.md"): - if any(part in _EXCLUDED_SKILL_DIRS for part in skill_md.parts): - continue + for skill_md in _walk(scan_dir, "SKILL.md"): try: frontmatter, _ = _parse_frontmatter( @@ -832,8 +829,9 @@ def skill_view(name: str, file_path: str = None, task_id: str = None) -> str: # Search by directory name across all dirs if not skill_md: + from agent.skill_utils import walk_skill_files as _walk for search_dir in all_dirs: - for found_skill_md in search_dir.rglob("SKILL.md"): + for found_skill_md in _walk(search_dir, "SKILL.md"): if found_skill_md.parent.name == name: skill_dir = found_skill_md.parent skill_md = found_skill_md