The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): list and prompt index advertise only names skill_view loads
yu-xin-ca24d7382d3d1
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex b4335920939..f8f5ff85e71 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -1206,8 +1206,9 @@ def drain_truncation_warnings() -> list:_SKILLS_PROMPT_CACHE_MAX = 32_SKILLS_PROMPT_CACHE: OrderedDict[tuple, str] = OrderedDict()_SKILLS_PROMPT_CACHE_LOCK = threading.Lock()-# v2 added org provenance fields (org_id/org_author); older snapshots are rebuilt.-_SKILLS_SNAPSHOT_VERSION = 3+# v2 added org provenance fields (org_id/org_author); v4 adds ``rel`` (SKILL.md path relative to its root) for+# duplicate-name resolution. Older snapshots are rebuilt.+_SKILLS_SNAPSHOT_VERSION = 4def _skills_prompt_snapshot_path() -> Path:@@ -1287,6 +1288,7 @@ def _build_snapshot_entry(skill_file: Path, skills_dir: Path, frontmatter: dict,platforms = [platforms] if isinstance(platforms, str) else platformsentry = {"skill_name": skill_name, "category": category, "frontmatter_name": str(frontmatter.get("name", skill_name)),+ "rel": skill_file.relative_to(skills_dir).as_posix(),"description": description, "platforms": [str(p).strip() for p in platforms if str(p).strip()],"conditions": extract_skill_conditions(frontmatter),"requires_apps": _requires_apps_list(frontmatter),@@ -1362,7 +1364,8 @@ def build_skills_system_prompt() -> str:"""Compact skill index for the system prompt.- External dirs (``skills.external_dirs``) are read-only and lose name collisions to local skills.+ Same-named skills resolve like skill_view: project > local > create_dir > external_dirs, and a+ same-tier duplicate is listed under its exact relative path (``agent.skill_utils.resolve_skill_catalog``).``compact_categories`` (coding posture) demotes categories to a names-only line — nothing is ever hidden.``skills_dir_override`` makes home resolution EXPLICIT: a build thread that never bound the HERMES_HOMEContextVar would otherwise leak the default profile's skills into a bot's prompt.@@ -1405,46 +1408,44 @@ def _read_category_descriptions(root: Path, log_fmt: str) -> dict[str, str]:return found-def _collect_extra_skills(- root: Path, skill_files, hides, claimed: set[str], skills_by_category: dict[str, list[tuple[str, str]]],- *, desc_prefix: str, log_fmt: str,-) -> None:- """Add visible skills from a project/external dir; names already in *claimed* are skipped."""+def _scan_extra_root(root: Path, skill_files, tier: int, log_fmt: str) -> list[tuple[dict, bool]]:+ """``(entry tagged with tier/root, is_compatible)`` for every skill under a project/create_dir/external root."""+ rows = []for skill_file in skill_files:try:is_compatible, frontmatter, desc = _parse_skill_file(skill_file)- entry = _build_snapshot_entry(skill_file, root, frontmatter, desc) if is_compatible else None- fm_name = entry["frontmatter_name"] if entry else ""- if not entry or fm_name in claimed or hides(fm_name, entry["skill_name"], extract_skill_conditions(frontmatter)):- continue- claimed.add(fm_name)- skills_by_category.setdefault(entry["category"], []).append((fm_name, f"{desc_prefix}{entry['description']}".strip()))+ rows.append(({**_build_snapshot_entry(skill_file, root, frontmatter, desc), "tier": tier, "root": root}, is_compatible))except Exception as e:logger.debug(log_fmt, skill_file, e)+ return rowsdef _label_visible_entries(visible_entries: list[dict], skills_by_category: dict[str, list[tuple[str, str]]]) -> None:- """Org labeling + FAIL-LOUD collisions: a personal/org name clash flags BOTH- entries (neither silently wins) and skill_view refuses the bare name."""+ """Index rows under each entry's ``load_name`` (what skill_view accepts); org labeling + FAIL-LOUD+ collisions: a personal/org name clash flags every loadable side with the exact path to load."""+ from agent.skill_utils import TIER_PROJECTname_owners: dict[str, set[str]] = {}for entry in visible_entries:- name_owners.setdefault(_entry_name(entry), set()).add("org" if entry.get("org_id") else "personal")- for entry in visible_entries:- fm, desc, org_id = _entry_name(entry), entry.get("description", ""), entry.get("org_id")+ name_owners.setdefault(entry["name"], set()).add("org" if entry.get("org_id") else "personal")+ for entry in (e for e in visible_entries if e["load_name"]):+ desc, org_id = entry.get("description", ""), entry.get("org_id")if org_id:author = entry.get("org_author") or ""desc = f"[org-shared{': by ' + author if author else ''}] {desc}".strip()+ elif entry["tier"] == TIER_PROJECT:+ desc = f"[project] {desc}".strip()category = f"org:{org_id}" if org_id else (entry.get("category") or "general")- if len(name_owners[fm]) > 1:- desc = f"[name collision — also exists {'personally' if org_id else 'in your org'}; load via category path] {desc}".strip()- skills_by_category.setdefault(category, []).append((fm, desc))+ if len(name_owners[entry["name"]]) > 1:+ desc = f"[name collision — also exists {'personally' if org_id else 'in your org'}; load by this exact path] {desc}".strip()+ skills_by_category.setdefault(category, []).append((entry["load_name"], desc))def _render_skills_index(skills_by_category: dict[str, list[tuple[str, str]]], category_descriptions: dict[str, str],- compact_categories: "frozenset[str] | None", available_tools: "set[str] | None",+ compact_categories: "frozenset[str] | None", available_tools: "set[str] | None", unloadable: "list[str]" = (),) -> str:- """Render the ## Skills block; "" when there is nothing to list."""+ """Render the ## Skills block; "" when there is nothing to list. *unloadable* names (different skills+ sharing a name AND path in one tier) get a rename note instead of a row skill_view would refuse."""if not skills_by_category:return ""# Demoted categories collapse to one names-only line. NEVER drop entries — agent-created skills are the@@ -1455,6 +1456,9 @@ def _render_skills_index("context, so their descriptions are omitted — the skills work ""normally and load with skill_view(name) as usual.)") if demoted else ""+ if unloadable:+ hidden_note += (f"\n(A copy of {', '.join(unloadable)} is not listed: it shares both its name and its path "+ "with a different skill in the same skills directory, so skill_view cannot load it — rename one.)")# Don't name web_search when the session has no web tools (dangling reference)._basic_tools = "terminal" if available_tools is not None and "web_search" not in available_tools else "web_search or terminal"index_lines = []@@ -1550,20 +1554,28 @@ def _build_skills_system_prompt_inner(for skill_file in iter_skill_index_files(skills_dir, "SKILL.md"):is_compatible, frontmatter, desc = _parse_skill_file(skill_file)candidates.append((_build_snapshot_entry(skill_file, skills_dir, frontmatter, desc), is_compatible))- visible_entries: list[dict] = [- entry for entry, is_compatible in candidates- if is_compatible and not hides(_entry_name(entry), entry.get("skill_name") or "", entry.get("conditions") or {})- ]-- # Project-local skills (highest precedence) shadow same-named profile-local skills; tagged [project].- project_names: set[str] = set()- if project_dirs:- from agent.skill_utils import iter_project_skill_files- for proj_dir in (d for d in project_dirs if d.exists()):- _collect_extra_skills(proj_dir, iter_project_skill_files(proj_dir), hides, project_names, skills_by_category,- desc_prefix="[project] ", log_fmt="Error reading project skill %s: %s")- # Drop shadowed entries BEFORE org labeling so collision flags don't fire on intentional overrides.- _label_visible_entries([e for e in visible_entries if _entry_name(e) not in project_names], skills_by_category)+ # Every tier is resolved together, exactly as skill_view resolves names (agent.skill_utils precedence:+ # project > local > create_dir > external_dirs; same-tier duplicates listed by exact path). Hidden and+ # incompatible copies still take part — skill_view sees them too.+ from agent.skill_utils import (+ TIER_CREATE_DIR, TIER_EXTERNAL, TIER_LOCAL, TIER_PROJECT, get_skill_create_dir, iter_project_skill_files,+ resolve_skill_catalog)+ rows: list[tuple[dict, bool]] = []+ for proj_dir in (d for d in project_dirs if d.exists()):+ rows += _scan_extra_root(proj_dir, iter_project_skill_files(proj_dir), TIER_PROJECT, "Error reading project skill %s: %s")+ rows += [({**entry, "tier": TIER_LOCAL, "root": skills_dir}, ok) for entry, ok in candidates]+ create_dir = get_skill_create_dir()+ for ext_dir in (d for d in external_dirs if d.exists()):+ tier = TIER_CREATE_DIR if ext_dir == create_dir else TIER_EXTERNAL+ rows += _scan_extra_root(ext_dir, iter_skill_index_files(ext_dir, "SKILL.md"), tier, "Error reading external skill %s: %s")+ for cat, cat_desc in _read_category_descriptions(ext_dir, "Could not read external skill description %s: %s").items():+ category_descriptions.setdefault(cat, cat_desc)+ resolved = resolve_skill_catalog([+ {**entry, "name": _entry_name(entry), "path": entry["root"] / entry["rel"],+ "visible": ok and not hides(_entry_name(entry), entry.get("skill_name") or "", entry.get("conditions") or {})}+ for entry, ok in rows])+ visible_entries = [e for e in resolved if e["visible"] and e["status"] != "shadowed"]+ _label_visible_entries(visible_entries, skills_by_category)if snapshot is None: # persist for fast cold-start reuse (best-effort)category_descriptions.update(_read_category_descriptions(skills_dir, "Could not read skill description %s: %s"))try:@@ -1574,15 +1586,8 @@ def _build_skills_system_prompt_inner(except Exception as e:logger.debug("Could not write skills prompt snapshot: %s", e)- # External skill directories: scanned directly (read-only, small); names already indexed are skipped.- seen_skill_names: set[str] = {name for cat in skills_by_category.values() for name, _ in cat}- for ext_dir in (d for d in external_dirs if d.exists()):- _collect_extra_skills(ext_dir, iter_skill_index_files(ext_dir, "SKILL.md"), hides, seen_skill_names,- skills_by_category, desc_prefix="", log_fmt="Error reading external skill %s: %s")- for cat, cat_desc in _read_category_descriptions(ext_dir, "Could not read external skill description %s: %s").items():- category_descriptions.setdefault(cat, cat_desc)-- result = _render_skills_index(skills_by_category, category_descriptions, compact_categories, available_tools)+ unloadable = sorted({e["name"] for e in visible_entries if not e["load_name"]})+ result = _render_skills_index(skills_by_category, category_descriptions, compact_categories, available_tools, unloadable)with _SKILLS_PROMPT_CACHE_LOCK:_SKILLS_PROMPT_CACHE[cache_key] = result_SKILLS_PROMPT_CACHE.move_to_end(cache_key)diff --git a/agent/skill_utils.py b/agent/skill_utils.pyindex 3ddd21235dd..e4c4666c831 100644--- a/agent/skill_utils.py+++ b/agent/skill_utils.py@@ -420,6 +420,7 @@ def display_skill_create_dir() -> str:# skills.external_dirs. Inside ONE tier two different skills sharing a name stay ambiguous — refused,# never guessed (59da8ec4e) — while identical copies under one root resolve to the shallowest.TIER_PROJECT, TIER_LOCAL, TIER_CREATE_DIR, TIER_EXTERNAL = range(4)+_WARNED_SHADOWS: Set[str] = set()def get_skill_search_roots(local: Optional[Path] = None, *, include_project: bool = True) -> List[Tuple[int, Path]]:@@ -468,6 +469,43 @@ def pick_skill_candidate(candidates) -> Tuple[Optional[int], List[int]]:return (contenders[0] if len(contenders) == 1 else None), contenders+def resolve_skill_catalog(entries: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """Copies of scanned skills (each with ``name``, ``tier``, ``root`` and ``path`` = its SKILL.md)+ annotated with what skill_view() resolves, using its aliases (declared name, directory name, path+ relative to the root) and :func:`pick_skill_candidate`. Adds ``relative_path`` and ``status``:+ ``unique`` (``load_name`` = name), ``ambiguous`` (``load_name`` = the exact relative path, or None+ when even that is shared) or ``shadowed`` (a higher tier owns the name: hidden, warned once)."""+ out = [dict(e) for e in entries]+ owners: Dict[str, List[int]] = {}+ for i, e in enumerate(out):+ skill_dir = Path(e["path"]).parent+ e["relative_path"] = skill_dir.relative_to(e["root"]).as_posix()+ for alias in {str(e["name"]), skill_dir.name, e["relative_path"]}:+ owners.setdefault(alias, []).append(i)+ winner: Dict[str, Optional[int]] = {}+ for alias, idxs in owners.items():+ won, _ = pick_skill_candidate([+ (out[j]["tier"], str(out[j]["root"]), (False, len(PurePath(out[j]["relative_path"]).parts) + 1),+ out[j]["path"]) for j in idxs])+ winner[alias] = None if won is None else idxs[won]+ for i, e in enumerate(out):+ name, rel = str(e["name"]), e["relative_path"]+ higher = [j for j in owners[name] if out[j]["tier"] < e["tier"]]+ if higher or winner[name] not in (None, i): # lower tier, or an identical same-root copy+ e.update(status="shadowed", load_name=None)+ # A symlink view or byte-identical copy of the winner hides nothing worth a warning.+ if (higher and str(e["path"]) not in _WARNED_SHADOWS+ and not any(provably_same_skill([e["path"], out[j]["path"]]) for j in higher)):+ _WARNED_SHADOWS.add(str(e["path"]))+ logger.warning("Skill '%s' at %s is shadowed by a higher-precedence copy "+ "(project > local > create_dir > external_dirs)", name, e["path"])+ elif winner[name] == i:+ e.update(status="unique", load_name=name)+ else:+ e.update(status="ambiguous", load_name=rel if winner[rel] == i else None)+ return out++# Project-local skills (<root>/.hermes/skills, <root>/.agents/skills; root = nearest# .git ancestor) are a prompt-injection vector if auto-sourced from any clone, so# they load only when the root is in ``skills.trusted_project_dirs``; then theydiff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.pyindex 48493328c4e..18c83954e67 100644--- a/hermes_cli/skills_hub.py+++ b/hermes_cli/skills_hub.py@@ -820,14 +820,16 @@ def do_list(source_filter: str = "all", enabled_only: bool = False,profile's config — ``-p`` swaps HERMES_HOME at process start, so no profile flag here."""from tools.skills_hub import HubLockFile, ensure_hub_dirsfrom tools.skills_sync import _read_manifest- from tools.skills_tool import _find_all_skills- from agent.skill_utils import get_disabled_skill_names+ from tools.skills_tool import _skill_catalog+ from agent.skill_utils import TIER_CREATE_DIR, TIER_EXTERNAL, TIER_PROJECT, get_disabled_skill_namesfrom agent.skill_commands import skill_command_collision_notec = console or _consoleensure_hub_dirs()hub_installed = {e["name"]: e for e in HubLockFile().list_installed()}builtin_names = set(_read_manifest())- all_skills = _find_all_skills(skip_disabled=True) # include disabled ones to annotate status+ # Rows are what skill_view loads: shadowed copies hidden, same-tier duplicates under their exact path.+ all_skills = [{**s, "name": s["load_name"]} for s in _skill_catalog(skip_disabled=True) if s["load_name"]]+ root_labels = {TIER_PROJECT: "project", TIER_CREATE_DIR: "create_dir", TIER_EXTERNAL: "external"}disabled_names = get_disabled_skill_names()table = _table(("Name", {"style": "bold cyan"}), "Category", "Source", "Trust", "Status",@@ -843,6 +845,7 @@ def do_list(source_filter: str = "all", enabled_only: bool = False,trust = hub_entry.get("trust_level", "community")else:source_type = source_display = trust = "builtin" if name in builtin_names else "local"+ source_display = root_labels.get(skill["tier"], source_display)is_enabled = name not in disabled_namesif source_filter not in ("all", source_type) or (enabled_only and not is_enabled):continuediff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 598388f904d..16da6810c75 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -179,10 +179,11 @@ def _skill_search_dirs() -> Tuple[List[Tuple[int, Path]], Path]:return roots, active_skills_dir-def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:- """All skills (name, description, category) across project/local/create_dir/external dirs,- first-wins by name; cached per session. ``skip_disabled=True`` ignores disabled state (config UI)."""- from agent.skill_utils import TIER_PROJECT, iter_project_skill_files, iter_skill_index_files+def _skill_catalog(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:+ """Every scanned skill resolved by ``agent.skill_utils.resolve_skill_catalog`` (status /+ load_name / tier / path), visible ones only; cached per session. Resolution runs over ALL+ files first — skill_view ignores platform/disabled gates when collecting candidates."""+ from agent.skill_utils import TIER_PROJECT, iter_project_skill_files, iter_skill_index_files, resolve_skill_catalogcache_key = "with_disabled" if skip_disabled else "filtered"disabled = set() if skip_disabled else _get_disabled_skill_names()roots, _ = _skill_search_dirs()@@ -193,8 +194,7 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:# Shallow copies: callers mutate the returned dicts (web_server annotates# s["enabled"]/s["usage"]); handing out cached objects would poison the cache.return [dict(s) for s in cached[2]]- skills = []- seen_names: set = set()+ scanned = []for tier, scan_dir in roots: # project dirs go through the quarantine chokepoint_iter = iter_project_skill_files if tier == TIER_PROJECT else lambda d: iter_skill_index_files(d, "SKILL.md")for skill_md in _iter(scan_dir):@@ -202,28 +202,36 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:continuetry:frontmatter, body = _parse_frontmatter(_read_skill_text(skill_md)[:4000])- if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter) or not skill_matches_apps(frontmatter):- continue- name = frontmatter.get("name", skill_md.parent.name)[:MAX_NAME_LENGTH]- if name in seen_names or name in disabled:- continuedescription = frontmatter.get("description", "")if not description: # first non-heading body line (a null value stays null)description = next((ln for ln in map(str.strip, body.strip().split("\n"))if ln and not ln.startswith("#")), description)- seen_names.add(name)- skills.append({"name": name, "description": _truncate_description(description),- "category": _get_category_from_path(skill_md)})+ scanned.append({+ "name": frontmatter.get("name", skill_md.parent.name)[:MAX_NAME_LENGTH],+ "description": _truncate_description(description),+ "category": _get_category_from_path(skill_md), "tier": tier, "root": scan_dir,+ "path": skill_md, "visible": bool(skill_matches_platform(frontmatter)+ and skill_matches_environment(frontmatter)+ and skill_matches_apps(frontmatter))})except (UnicodeDecodeError, PermissionError) as e:logger.debug("Failed to read skill file %s: %s", skill_md, e)except Exception as e:logger.debug("Skipping skill at %s: failed to parse: %s", skill_md, e, exc_info=True)+ skills = [s for s in resolve_skill_catalog(scanned) if s.pop("visible") and s["name"] not in disabled]# Keyed by the signature computed BEFORE the scan: a write racing the scan changes the# signature, so the next call re-scans instead of serving a torn result._SKILLS_CACHE[cache_key] = (signature, now, skills)return [dict(s) for s in skills]+def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:+ """Loadable skills (name, description, category): ``name`` is what skill_view() accepts —+ the declared name, or the exact relative path for a same-tier duplicate. Shadowed and+ unloadable copies are left out. ``skip_disabled=True`` ignores disabled state (config UI)."""+ return [{"name": s["load_name"], "description": s["description"], "category": s["category"]}+ for s in _skill_catalog(skip_disabled=skip_disabled) if s["load_name"]]++def _sort_skills(skills: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Keep every skill listing path ordered the same way."""return sorted(skills, key=lambda s: (s.get("category") or "", s["name"]))