Skip to content

The agent that grows with you

refactor(tools): skills_sync shares _iter_skill_mds; plugin/bundled-ops guard collapses and docstring compaction

Tekniuma150766f5809
diff --git a/tools/skills_sync.py b/tools/skills_sync.py
index 655385fdb2a..1a49452e4b3 100644
--- a/tools/skills_sync.py
+++ b/tools/skills_sync.py
@@ -78,15 +78,19 @@ def _get_optional_dir() -> Path:
return get_optional_skills_dir(Path(__file__).parent.parent / "optional-skills")
-def _iter_active_skill_mds(sort: bool = False) -> Iterator[Path]:
- """Yield every non-excluded SKILL.md in the user's skills tree."""
- root = _skills_dir()
+def _iter_skill_mds(root: Path, sort: bool = False) -> Iterator[Path]:
+ """Yield every non-excluded SKILL.md under ``root`` (nothing when it does not exist)."""
found = root.rglob("SKILL.md") if root.exists() else iter(())
for skill_md in sorted(found) if sort else found:
if not is_excluded_skill_path(skill_md):
yield skill_md
+def _iter_active_skill_mds(sort: bool = False) -> Iterator[Path]:
+ """Yield every non-excluded SKILL.md in the user's skills tree."""
+ return _iter_skill_mds(_skills_dir(), sort)
+
+
def _build_external_skill_index() -> Set[str]:
"""Names (directory and frontmatter) of every skill provided by external_dirs,
so sync_skills never shadows an externally-delegated skill."""
@@ -94,9 +98,8 @@ def _build_external_skill_index() -> Set[str]:
_external_dirs_cache_clear() # so a config edit (or a test patch) is seen
external_names: Set[str] = set()
for ext_dir in get_external_skills_dirs():
- for skill_md in ext_dir.rglob("SKILL.md"):
- if not is_excluded_skill_path(skill_md):
- external_names.update({skill_md.parent.name, _read_skill_name(skill_md, "")})
+ for skill_md in _iter_skill_mds(ext_dir):
+ external_names.update({skill_md.parent.name, _read_skill_name(skill_md, "")})
external_names.discard("")
return external_names
@@ -119,9 +122,9 @@ def _read_suppressed_names() -> set:
def _write_manifest(entries: Dict[str, str]):
"""Atomic v2 write, preserving an existing file's mode/owner (not mkstemp's 0600)."""
_manifest_file().parent.mkdir(parents=True, exist_ok=True)
- data = "\n".join(f"{name}:{hash_val}" for name, hash_val in sorted(entries.items())) + "\n"
try:
- atomic_write_text(_manifest_file(), data, tmp_prefix=".bundled_manifest_", preserve_mode=True)
+ atomic_write_text(_manifest_file(), "".join(f"{n}:{h}\n" for n, h in sorted(entries.items())),
+ tmp_prefix=".bundled_manifest_", preserve_mode=True)
except Exception as e:
logger.debug("Failed to write skills manifest %s: %s", _manifest_file(), e, exc_info=True)
@@ -145,13 +148,11 @@ def _compute_relative_dest(skill_dir: Path, bundled_dir: Path) -> Path:
def _dir_hash(directory: Path) -> str:
"""MD5 over relative paths + contents of every file in a directory."""
hasher = hashlib.md5()
- try:
+ with suppress(OSError):
for fpath in sorted(directory.rglob("*")):
if fpath.is_file():
hasher.update(str(fpath.relative_to(directory)).encode("utf-8"))
hasher.update(fpath.read_bytes())
- except OSError:
- pass
return hasher.hexdigest()
@@ -208,7 +209,6 @@ def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Opt
@dataclass
class _SyncState:
"""Mutable accumulator threaded through one sync_skills() run."""
-
manifest: Dict[str, str]
quiet: bool
skipped: int = 0
@@ -309,8 +309,7 @@ def _update_existing_skill(st: _SyncState, skill_name: str, skill_src: Path, des
st.skipped += 1
return
user_hash = _dir_hash(dest)
- if not origin_hash:
- # v1 migration: baseline from the user's copy (can't tell user-edit from upstream change).
+ if not origin_hash: # v1 migration: baseline from the user's copy (can't tell edit from upstream change)
st.manifest[skill_name] = user_hash
st.skipped += 1
return
@@ -330,8 +329,8 @@ def _update_existing_skill(st: _SyncState, skill_name: str, skill_src: Path, des
def _seed_category_descriptions(bundled_dir: Path, only_dirs: Optional[Set[Path]]) -> None:
- """Copy category DESCRIPTION.md files not already present; ``only_dirs``
- restricts seeding to the essential skills' categories on opted-out profiles."""
+ """Copy category DESCRIPTION.md files not already present; ``only_dirs`` restricts
+ seeding to the essential skills' categories on opted-out profiles."""
for desc_md in bundled_dir.rglob("DESCRIPTION.md"):
dest_desc = _skills_dir() / desc_md.relative_to(bundled_dir)
if (only_dirs is not None and dest_desc.parent not in only_dirs) or dest_desc.exists():
@@ -415,7 +414,6 @@ def _rmtree_writable(path: Path) -> None:
with suppress(OSError):
os.chmod(p, stat.S_IRWXU)
func(fpath)
-
shutil.rmtree(path, onerror=_on_error)
diff --git a/tools/skills_sync_bundled_ops.py b/tools/skills_sync_bundled_ops.py
index e1d82386dd3..2a48c26d6bb 100644
--- a/tools/skills_sync_bundled_ops.py
+++ b/tools/skills_sync_bundled_ops.py
@@ -1,8 +1,5 @@
"""Bundled-skill maintenance ops: reset, diff, list-modified, opt-out, remove-pristine.
-
-Profile-scoped paths and patchable helpers (``_get_bundled_dir``, ``sync_skills``, ...)
-are resolved through ``_ss()`` at call time so monkeypatching ``tools.skills_sync`` works.
-"""
+Profile-scoped paths and patchable helpers resolve through ``_ss()`` at call time."""
from pathlib import Path
from typing import List, Optional, Tuple
@@ -11,27 +8,24 @@ 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_user_modified_bundled_skills`` so they never drift."""
+ """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 so they never drift."""
return bool(origin_hash) and user_hash != origin_hash
def _bundled_state():
- """``(skills_sync, manifest, bundled_dir, {skill_name: bundled_src})`` — the shared
- preamble of every maintenance op."""
+ """``(skills_sync, manifest, bundled_dir, {skill_name: bundled_src})`` — shared op preamble."""
ss = _ss()
bundled_dir = ss._get_bundled_dir()
return ss, ss._read_manifest(), bundled_dir, dict(ss._discover_bundled_skills(bundled_dir))
def reset_bundled_skill(name: str, restore: bool = False) -> dict:
- """Reset a bundled skill's manifest tracking so future syncs work normally.
-
- An edited bundled skill stays ``user_modified`` forever because the manifest holds
- the OLD origin hash; clearing the entry breaks that loop. ``restore`` also deletes
- the user's copy so the next sync re-copies bundled. Returns ``{ok, action, message,
- synced}``; action is manifest_cleared / restored / not_in_manifest / bundled_missing / not_reset."""
+ """Reset a bundled skill's manifest tracking so future syncs work normally. An edited bundled
+ skill stays ``user_modified`` forever because the manifest holds the OLD origin hash; clearing
+ the entry breaks that loop. ``restore`` also deletes the user's copy so the next sync re-copies
+ bundled. Returns ``{ok, action, message, synced}``; action is manifest_cleared / restored /
+ not_in_manifest / bundled_missing / not_reset."""
ss, manifest, bundled_dir, bundled_by_name = _bundled_state()
in_manifest = name in manifest
is_bundled = name in bundled_by_name
@@ -71,8 +65,8 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
def list_user_modified_bundled_skills() -> List[dict]:
- """Bundled skills ``hermes update`` keeps because the user edited them (same test
- the sync loop uses). Name-sorted ``{"name", "dest", "bundled_src"}`` dicts."""
+ """Bundled skills ``hermes update`` keeps because the user edited them (same test the sync
+ loop uses). Name-sorted ``{"name", "dest", "bundled_src"}`` dicts."""
ss = _ss()
if not (manifest := ss._read_manifest()):
return []
@@ -98,9 +92,9 @@ def _read_for_diff(path: Path) -> Tuple[Optional[bytes], Optional[str]]:
def diff_bundled_skill(name: str) -> dict:
- """Diff a user's copy of a bundled skill against stock. Returns ``{ok, name, found,
- modified, message, diffs}``; each diff is ``{"path", "status", "diff"}`` with status
- modified / added (only in user copy) / removed (only in bundled) / binary."""
+ """Diff a user's copy of a bundled skill against stock. Returns ``{ok, name, found, modified,
+ message, diffs}``; each diff is ``{"path", "status", "diff"}`` with status modified / added
+ (only in user copy) / removed (only in bundled) / binary."""
import difflib
ss, _, bundled_dir, bundled_by_name = _bundled_state()
@@ -119,19 +113,20 @@ def diff_bundled_skill(name: str) -> dict:
for rel in sorted(user_files | stock_files):
if rel not in stock_files:
diffs.append({"path": rel, "status": "added", "diff": f"+ only in your copy: {rel}"})
- elif rel not in user_files:
+ continue
+ if rel not in user_files:
diffs.append({"path": rel, "status": "removed", "diff": f"- only in stock: {rel}"})
- else:
- user_bytes, user_text = _read_for_diff(dest / rel)
- stock_bytes, stock_text = _read_for_diff(bundled_src / rel)
- if user_text is None or stock_text is None: # a binary side: report only if bytes differ
- if user_bytes != stock_bytes:
- diffs.append({"path": rel, "status": "binary", "diff": "<binary file differs>"})
- elif user_text != stock_text:
- text = "".join(difflib.unified_diff(
- stock_text.splitlines(keepends=True), user_text.splitlines(keepends=True),
- fromfile=f"stock/{rel}", tofile=f"yours/{rel}"))
- diffs.append({"path": rel, "status": "modified", "diff": text})
+ continue
+ user_bytes, user_text = _read_for_diff(dest / rel)
+ stock_bytes, stock_text = _read_for_diff(bundled_src / rel)
+ if user_text is None or stock_text is None: # a binary side: report only if bytes differ
+ if user_bytes != stock_bytes:
+ diffs.append({"path": rel, "status": "binary", "diff": "<binary file differs>"})
+ elif user_text != stock_text:
+ text = "".join(difflib.unified_diff(
+ stock_text.splitlines(keepends=True), user_text.splitlines(keepends=True),
+ fromfile=f"stock/{rel}", tofile=f"yours/{rel}"))
+ diffs.append({"path": rel, "status": "modified", "diff": text})
message = (f"'{name}' differs from the stock version in {len(diffs)} file(s)." if diffs
else f"'{name}' matches the stock version.")
return {"ok": True, "name": name, "found": True, "modified": bool(diffs), "diffs": diffs, "message": message}
@@ -145,9 +140,8 @@ _OPT_OUT_MESSAGES = { # (enabled, changed) -> message
def set_bundled_skills_opt_out(enabled: bool) -> dict:
- """Toggle the .no-bundled-skills marker (the on-disk half of ``hermes skills
- opt-out`` / ``opt-in``); removing present skills is ``remove_pristine_bundled_skills``.
- Returns ``{ok, changed, marker, message}``."""
+ """Toggle the .no-bundled-skills marker (on-disk half of ``hermes skills opt-out`` / ``opt-in``;
+ removing present skills is ``remove_pristine_bundled_skills``). ``{ok, changed, marker, message}``."""
ss = _ss()
marker = ss._hermes_home() / ss.NO_BUNDLED_SKILLS_MARKER
existed = marker.exists()
@@ -168,10 +162,10 @@ def set_bundled_skills_opt_out(enabled: bool) -> dict:
def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:
- """Delete bundled skills that are manifest-tracked (genuinely bundled), still in the
- bundled source (hash-comparable) AND byte-identical to the origin hash; everything
- else lands in ``skipped``. Removed skills lose their manifest entry so a later
- opt-in re-seed treats them as new. Returns ``{ok, removed, skipped: [{name, reason}], dry_run, message}``."""
+ """Delete bundled skills that are manifest-tracked, still in the bundled source AND
+ byte-identical to the origin hash; everything else lands in ``skipped``. Removed skills lose
+ their manifest entry so a later opt-in re-seed treats them as new.
+ Returns ``{ok, removed, skipped: [{name, reason}], dry_run, message}``."""
ss, manifest, bundled_dir, bundled_by_name = _bundled_state()
removed: List[str] = []
skipped: List[dict] = []
@@ -199,6 +193,5 @@ def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:
if not dry_run and removed:
ss._write_manifest(manifest)
verb = "Would remove" if dry_run else "Removed"
- return {
- "ok": True, "removed": removed, "skipped": skipped, "dry_run": dry_run,
- "message": f"{verb} {len(removed)} pristine bundled skill(s); kept {len(skipped)}."}
+ return {"ok": True, "removed": removed, "skipped": skipped, "dry_run": dry_run,
+ "message": f"{verb} {len(removed)} pristine bundled skill(s); kept {len(skipped)}."}
diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.py
index 9d4401cc42e..c1075127c1a 100644
--- a/tools/skills_sync_optional.py
+++ b/tools/skills_sync_optional.py
@@ -1,8 +1,5 @@
-"""Official optional-skill provenance: hub-lock backfill and restore.
-
-Profile-scoped paths and patchable helpers are resolved through ``_ss()`` at call
-time so tests and multi-profile runtimes patching ``tools.skills_sync`` keep working.
-"""
+"""Official optional-skill provenance: hub-lock backfill and restore. Profile-scoped paths
+and patchable helpers resolve through ``_ss()`` at call time (``tools.skills_sync`` patches work)."""
import json
import logging
@@ -68,8 +65,9 @@ def _read_hub_install_paths() -> Set[str]:
def _iter_optional_skills(optional_dir: Path, *, root_relative: bool) -> Iterator[Tuple[Path, Path, str]]:
"""Yield ``(skill_md, src, install_path)`` for every safe official optional skill."""
for skill_md in sorted(optional_dir.rglob("SKILL.md")):
- if (is_excluded_skill_path(skill_md.relative_to(optional_dir), root=optional_dir) if root_relative
- else is_excluded_skill_path(skill_md)):
+ excluded = (is_excluded_skill_path(skill_md.relative_to(optional_dir), root=optional_dir)
+ if root_relative else is_excluded_skill_path(skill_md))
+ if excluded:
continue
try:
yield skill_md, skill_md.parent, _safe_rel_install_path(skill_md.parent, optional_dir)
@@ -93,8 +91,7 @@ def _move_to_restore_backup(path: Path, backup_root: Path) -> str:
"""Move an existing skill directory into a restore backup, preserving rel path."""
ss = _ss()
rel = path.relative_to(ss._skills_dir())
- target = backup_root / rel
- suffix = 0
+ target, suffix = backup_root / rel, 0
while target.exists():
suffix += 1
target = (backup_root / rel).with_name(f"{rel.name}-{suffix}")
diff --git a/tools/skills_tool_dedup.py b/tools/skills_tool_dedup.py
index b8589d43882..5de13b17d46 100644
--- a/tools/skills_tool_dedup.py
+++ b/tools/skills_tool_dedup.py
@@ -1,10 +1,7 @@
-"""skill_view repeat-view dedup registry.
-
-Per-task cache of (skill name, file_path) -> (skill file mtime+size). A repeat
-view of an UNCHANGED file returns a short stub — the earlier tool result already
-carries the content verbatim. Cleared on context compression via
+"""skill_view repeat-view dedup registry: per-task cache of (skill name, file_path) ->
+(skill file mtime+size). A repeat view of an UNCHANGED file returns a short stub — the earlier
+tool result already carries the content verbatim. Cleared on context compression via
``reset_skill_view_dedup()`` because the original content is summarized away.
-Every name is re-imported into ``tools.skills_tool``; state lives only here.
"""
import json
@@ -76,10 +73,9 @@ def _check_skill_view_dedup(task_id, name, file_path) -> str | None:
cache.pop(key, None)
return None
return json.dumps({
- "success": True, "status": "unchanged", "name": rec_name,
- "file": file_path or "SKILL.md", "dedup": True,
- "content_returned": False, "message": _SKILL_VIEW_DEDUP_MESSAGE,
- }, ensure_ascii=False)
+ "success": True, "status": "unchanged", "name": rec_name, "file": file_path or "SKILL.md",
+ "dedup": True, "content_returned": False, "message": _SKILL_VIEW_DEDUP_MESSAGE},
+ ensure_ascii=False)
return None
diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.py
index 826a56013f3..c246e260972 100644
--- a/tools/skills_tool_plugin.py
+++ b/tools/skills_tool_plugin.py
@@ -1,8 +1,7 @@
-"""Plugin-provided skill serving for ``skill_view`` (``plugin:skill`` names) plus
-the JSON / file-serving helpers shared with the local-skill path.
+"""Plugin-provided skill serving for ``skill_view`` (``plugin:skill`` names) plus the
+JSON / file-serving helpers shared with the local-skill path.
-Every name is re-imported by ``tools.skills_tool``. Helpers tests patch on the
-origin module (``_is_skill_disabled``, ``_parse_frontmatter``,
+Helpers tests patch on the origin module (``_is_skill_disabled``, ``_parse_frontmatter``,
``skill_matches_platform``) are looked up lazily via ``tools.skills_tool``.
"""
@@ -16,12 +15,9 @@ from tools.skills_tool_setup import SkillReadinessStatus
logger = logging.getLogger("tools.skills_tool")
-# Anthropic-recommended limits for progressive disclosure efficiency
-MAX_NAME_LENGTH = 64
+MAX_NAME_LENGTH = 64 # Anthropic-recommended progressive-disclosure limits
MAX_DESCRIPTION_LENGTH = 1024
-
-# Prompt injection detection — shared by local-skill and plugin-skill paths.
-_INJECTION_PATTERNS: list = [
+_INJECTION_PATTERNS: list = [ # shared by local-skill and plugin-skill paths
"ignore previous instructions", "ignore all previous", "you are now",
"disregard your", "forget your instructions", "new instructions:",
"system prompt:", "<system>", "]]>"]
@@ -44,9 +40,9 @@ def _read_skill_text(path: Path) -> str:
def _truncate_description(description: str) -> str:
- if len(description) > MAX_DESCRIPTION_LENGTH:
- return description[: MAX_DESCRIPTION_LENGTH - 3] + "..."
- return description
+ if len(description) <= MAX_DESCRIPTION_LENGTH:
+ return description
+ return description[: MAX_DESCRIPTION_LENGTH - 3] + "..."
def _safe_frontmatter(path: Path | None = None, *, content: str | None = None) -> Dict[str, Any]:
@@ -59,29 +55,26 @@ def _safe_frontmatter(path: Path | None = None, *, content: str | None = None) -
def _available_skill_files(skill_dir: Path) -> Dict[str, List[str]]:
- """Non-SKILL.md files grouped by support dir (+ "other" for known source
- extensions at other locations); empty groups dropped."""
+ """Non-SKILL.md files grouped by support dir (+ "other" for known source extensions
+ elsewhere); empty groups dropped."""
groups: Dict[str, List[str]] = {}
for f in skill_dir.rglob("*"):
if not f.is_file() or f.name == "SKILL.md":
continue
rel = str(f.relative_to(skill_dir))
top = rel.split("/", 1)[0] if "/" in rel else None
- if top in _SUPPORT_DIRS:
- groups.setdefault(top, []).append(rel)
- elif f.suffix in _SKILL_FILE_EXTS:
- groups.setdefault("other", []).append(rel)
+ if top in _SUPPORT_DIRS or f.suffix in _SKILL_FILE_EXTS:
+ groups.setdefault(top if top in _SUPPORT_DIRS else "other", []).append(rel)
return {k: groups[k] for k in (*_SUPPORT_DIRS, "other") if k in groups}
def _serve_skill_file(
skill_root: Path, file_path: str, label: str, *, hint: str | None = None,
list_available: bool = False, read_error_prefix: bool = False, mark_read: bool = False) -> str:
- """Serve one linked file from a skill directory as a skill_view JSON result.
-
- ``hint`` decorates traversal/containment errors and ``list_available`` adds the
- available-files listing on not-found (local skills); ``read_error_prefix`` wraps
- non-decode read errors (plugin) instead of propagating to the caller's handler."""
+ """Serve one linked file from a skill directory as a skill_view JSON result. ``hint``
+ decorates traversal/containment errors; ``list_available`` adds the available-files listing
+ on not-found (local); ``read_error_prefix`` wraps non-decode read errors (plugin) instead
+ of propagating to the caller's handler."""
from tools.path_security import has_traversal_component, validate_within_dir
extra = {"hint": hint} if hint else {}
if has_traversal_component(file_path):
@@ -91,12 +84,9 @@ def _serve_skill_file(
return _fail(path_error, **extra)
# is_file(), not exists(): a bare directory must take the not-found branch.
if not target.is_file():
- not_found = f"File '{file_path}' not found in skill '{label}'."
- if list_available:
- return _fail(
- not_found, available_files=_available_skill_files(skill_root),
- hint="Use one of the available file paths listed above")
- return _fail(not_found)
+ listing = {"available_files": _available_skill_files(skill_root),
+ "hint": "Use one of the available file paths listed above"} if list_available else {}
+ return _fail(f"File '{file_path}' not found in skill '{label}'.", **listing)
try:
content = _read_skill_text(target)
except UnicodeDecodeError:
@@ -160,22 +150,17 @@ def _serve_plugin_skill(
if any(p in content.lower() for p in _INJECTION_PATTERNS):
logger.warning(
"Plugin skill '%s:%s' contains patterns that may indicate prompt injection", namespace, bare)
- try: # bundle-context banner: sibling skills of the same plugin
+ banner = ""
+ with suppress(Exception): # bundle-context banner: sibling skills of the same plugin
siblings = [s for s in get_plugin_manager().list_plugin_skills(namespace) if s != bare]
- banner = f"[Bundle context: This skill is part of the '{namespace}' plugin."
- if siblings:
- banner += (
- f"\nSibling skills: {', '.join(siblings)}.\n"
- f"Use qualified form to invoke siblings (e.g. {namespace}:{siblings[0]}).")
- banner += "]\n\n"
- except Exception:
- banner = ""
+ banner = f"[Bundle context: This skill is part of the '{namespace}' plugin." + (
+ f"\nSibling skills: {', '.join(siblings)}.\n"
+ f"Use qualified form to invoke siblings (e.g. {namespace}:{siblings[0]})." if siblings else ""
+ ) + "]\n\n"
rendered_content = content if not preprocess else _preprocess_skill(
content, skill_md.parent, session_id, "Could not preprocess plugin skill %s:%s", namespace, bare)
return _json({
- "success": True,
- "name": qualified_name,
- "content": f"{banner}{rendered_content}" if banner else rendered_content,
+ "success": True, "name": qualified_name, "content": banner + rendered_content,
"description": _truncate_description(str(parsed_frontmatter.get("description", ""))),
"linked_files": _plugin_skill_linked_files(skill_md.parent),
"readiness_status": SkillReadinessStatus.AVAILABLE.value})
@@ -185,12 +170,8 @@ def _plugin_skill_linked_files(skill_root: Path) -> Dict[str, List[str]] | None:
from tools.path_security import validate_within_dir
linked: Dict[str, List[str]] = {}
for category in _SUPPORT_DIRS:
- base = skill_root / category
- if not base.is_dir():
- continue
files = [
- str(path.relative_to(skill_root))
- for path in sorted(base.rglob("*"))
+ str(path.relative_to(skill_root)) for path in sorted((skill_root / category).rglob("*"))
if path.is_file() and validate_within_dir(path, skill_root) is None]
if files:
linked[category] = files