The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): skills_sync ops share _bundled_state preamble; collapse (OSError, IOError) and chmod guards
Teknium12bc8781c09b
diff --git a/tools/skills_sync.py b/tools/skills_sync.pyindex 02e8553ad23..3d2b27666d5 100644--- a/tools/skills_sync.py+++ b/tools/skills_sync.py@@ -14,6 +14,7 @@ import osimport shutilimport statimport sys+from contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Dict, Iterator, List, Optional, Set, Tuple@@ -87,10 +88,7 @@ def _iter_active_skill_mds(sort: bool = False) -> Iterator[Path]: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."""- try:- from agent.skill_utils import get_external_skills_dirs, _external_dirs_cache_clear- except ImportError:- return set()+ from agent.skill_utils import get_external_skills_dirs, _external_dirs_cache_clear_external_dirs_cache_clear() # so a config edit (or a test patch) is seenexternal_names: Set[str] = set()@@ -103,18 +101,13 @@ def _build_external_skill_index() -> Set[str]:def _read_manifest() -> Dict[str, str]:- """Read the manifest as ``{skill_name: origin_hash}``; v1 plain-name lines get an- empty hash, which triggers migration on the next sync."""+ """``{skill_name: origin_hash}``; v1 plain-name lines get an empty hash (migrates next sync)."""try:lines = _manifest_file().read_text(encoding="utf-8").splitlines() if _manifest_file().exists() else []- except (OSError, IOError):+ except OSError:return {}- result = {}- for line in map(str.strip, lines):- if line:- name, _, hash_val = line.partition(":")- result[name.strip()] = hash_val.strip()- return result+ pairs = (line.partition(":") for line in map(str.strip, lines) if line)+ return {name.strip(): hash_val.strip() for name, _, hash_val in pairs}def _read_suppressed_names() -> set:@@ -123,8 +116,7 @@ def _read_suppressed_names() -> set:def _write_manifest(entries: Dict[str, str]):- """Write the manifest atomically in v2 format, preserving an existing file's- permission bits/owner instead of resetting them to mkstemp's 0600."""+ """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:@@ -146,8 +138,7 @@ def _discover_bundled_skills(bundled_dir: Path) -> List[Tuple[str, Path]]:def _compute_relative_dest(skill_dir: Path, bundled_dir: Path) -> Path:- """Destination in the skills dir preserving category structure- (bundled/skills/mlops/axolotl -> ~/.hermes/skills/mlops/axolotl)."""+ """Destination preserving category structure (bundled/mlops/axolotl -> skills/mlops/axolotl)."""return _skills_dir() / skill_dir.relative_to(bundled_dir)@@ -159,7 +150,7 @@ def _dir_hash(directory: Path) -> str:if fpath.is_file():hasher.update(str(fpath.relative_to(directory)).encode("utf-8"))hasher.update(fpath.read_bytes())- except (OSError, IOError):+ except OSError:passreturn hasher.hexdigest()@@ -216,7 +207,7 @@ def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Optcontinuetry:_move_dir(candidate, dest)- except (OSError, IOError):+ except OSError:logger.warning("Could not relocate renamed skill %s -> %s", candidate, dest, exc_info=True)return Nonelogger.info("Relocated renamed bundled skill: %s -> %s", candidate, dest)@@ -256,7 +247,7 @@ def _recover_orphan_backup(dest: Path) -> None:try:_move_dir(orphan, dest)logger.info("Recovered orphaned skill backup: %s", orphan)- except (OSError, IOError):+ except OSError:logger.warning("Could not recover orphaned skill backup %s", orphan, exc_info=True)@@ -293,7 +284,7 @@ def _install_new_skill(st: _SyncState, skill_name: str, skill_src: Path, dest: Pst.copied.append(skill_name)st.manifest[skill_name] = bundled_hashst.say(f" + {skill_name}")- except (OSError, IOError) as e:+ except OSError as e:st.say(f" ! Failed to copy {skill_name}: {e}") # not in manifest — next sync retries@@ -306,19 +297,19 @@ def _replace_skill_dir(skill_src: Path, dest: Path) -> None:shutil.move(str(dest), str(backup))try:shutil.copytree(skill_src, dest)- except (OSError, IOError):+ except OSError:# Clear a partially-written dest so it can't shadow or block the restore.if backup.exists() and dest.exists():try:_rmtree_writable(dest)- except (OSError, IOError):+ except OSError:logger.warning("Could not clear partial copy %s during restore", dest, exc_info=True)if backup.exists() and not dest.exists():shutil.move(str(backup), str(dest))raisetry:_rmtree_writable(backup)- except (OSError, IOError):+ except OSError:logger.debug("Could not remove backup %s", backup, exc_info=True)@@ -341,7 +332,7 @@ def _update_existing_skill(st: _SyncState, skill_name: str, skill_src: Path, des# bundled changed and the user copy is pristine -> updatetry:_replace_skill_dir(skill_src, dest)- except (OSError, IOError) as e:+ except OSError as e:st.say(f" ! Failed to update {skill_name}: {e}")returnst.manifest[skill_name] = bundled_hash@@ -359,7 +350,7 @@ def _seed_category_descriptions(bundled_dir: Path, only_dirs: Optional[Set[Path]try:dest_desc.parent.mkdir(parents=True, exist_ok=True)shutil.copy2(desc_md, dest_desc)- except (OSError, IOError) as e:+ except OSError as e:logger.debug("Could not copy %s: %s", desc_md, e)@@ -411,11 +402,9 @@ def sync_skills(quiet: bool = False) -> dict:cleaned = [] if essential_only else sorted(set(st.manifest) - {name for name, _ in bundled_skills})for name in cleaned:del st.manifest[name]-_seed_category_descriptions(bundled_dir,- {_compute_relative_dest(src, bundled_dir).parent for _, src in bundled_skills} if essential_only else None,- )+ {_compute_relative_dest(src, bundled_dir).parent for _, src in bundled_skills} if essential_only else None)_write_manifest(st.manifest)return {@@ -440,10 +429,8 @@ def _rmtree_writable(path: Path) -> None:def _on_error(func, fpath, exc_info):for p in (os.path.dirname(fpath), fpath):- try:+ with suppress(OSError):os.chmod(p, stat.S_IRWXU)- except OSError:- passfunc(fpath)shutil.rmtree(path, onerror=_on_error)@@ -463,12 +450,11 @@ if __name__ == "__main__":print("Syncing bundled skills into ~/.hermes/skills/ ...")result = sync_skills(quiet=False)parts = [f"{len(result['copied'])} new", f"{len(result['updated'])} updated", f"{result['skipped']} unchanged"]- names = result["user_modified"]- if names:+ if names := result["user_modified"]:shown = ", ".join(names[:5]) + (f", +{len(names) - 5} more" if len(names) > 5 else "")parts.append(f"{len(names)} user-modified (kept): {shown}")if result["cleaned"]:parts.append(f"{len(result['cleaned'])} cleaned from manifest")- if result.get("optional_provenance_backfilled"):- parts.append(f"{len(result['optional_provenance_backfilled'])} official optional backfilled")+ if backfilled := result.get("optional_provenance_backfilled"):+ parts.append(f"{len(backfilled)} official optional backfilled")print(f"\nDone: {', '.join(parts)}. {result['total_bundled']} total bundled.")diff --git a/tools/skills_sync_bundled_ops.py b/tools/skills_sync_bundled_ops.pyindex 7d8cc778221..1f30e18e739 100644--- a/tools/skills_sync_bundled_ops.py+++ b/tools/skills_sync_bundled_ops.py@@ -17,8 +17,12 @@ def _is_tracked_user_modification(origin_hash: str, user_hash: str) -> bool:return bool(origin_hash) and user_hash != origin_hash-def _bundled_by_name(bundled_dir: Path) -> dict:- return dict(_ss()._discover_bundled_skills(bundled_dir))+def _bundled_state():+ """``(skills_sync, manifest, bundled_dir, {skill_name: bundled_src})`` — the shared+ preamble of every maintenance op."""+ 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:@@ -28,10 +32,7 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:the OLD origin hash; clearing the entry breaks that loop. ``restore`` also deletesthe 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 = _ss()- manifest = ss._read_manifest()- bundled_dir = ss._get_bundled_dir()- bundled_by_name = _bundled_by_name(bundled_dir)+ ss, manifest, bundled_dir, bundled_by_name = _bundled_state()in_manifest = name in manifestis_bundled = name in bundled_by_name@@ -53,7 +54,7 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:if dest.exists():try:ss._rmtree_writable(dest)- except (OSError, IOError) as e:+ except OSError as e:return _fail("not_reset", f"Could not delete user copy at {dest}: {e}. "f"Manifest entry preserved — nothing was changed.")deleted_user_copy = True@@ -91,8 +92,7 @@ def list_user_modified_bundled_skills() -> List[dict]:def _read_for_diff(path: Path) -> Tuple[Optional[bytes], Optional[str]]:- """Read a file once for diffing: ``(raw_bytes, text)`` with ``text=None`` for- binary content, ``(None, None)`` if unreadable."""+ """``(raw_bytes, text)`` for diffing; ``text=None`` for binary, ``(None, None)`` if unreadable."""try:data = path.read_bytes()return data, (None if b"\x00" in data else data.decode("utf-8"))@@ -108,13 +108,12 @@ def diff_bundled_skill(name: str) -> dict:modified / added (only in user copy) / removed (only in bundled) / binary."""import difflib- ss = _ss()+ ss, _, bundled_dir, bundled_by_name = _bundled_state()def _fail(found: bool, message: str) -> dict:return {"ok": False, "name": name, "found": found, "modified": False, "diffs": [], "message": message}- bundled_dir = ss._get_bundled_dir()- bundled_src = _bundled_by_name(bundled_dir).get(name)+ bundled_src = bundled_by_name.get(name)if bundled_src is None:return _fail(False, f"'{name}' is not a tracked bundled skill (no stock version to "f"diff against). Hub-installed skills use `hermes skills inspect`.")@@ -133,8 +132,7 @@ def diff_bundled_skill(name: str) -> dict: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:- # At least one side is binary — report only if the bytes differ.+ if user_text is None or stock_text is None: # a binary side: report only if bytes differif user_bytes != stock_bytes:diffs.append({"path": rel, "status": "binary", "diff": "<binary file differs>"})elif user_text != stock_text:@@ -183,11 +181,7 @@ def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:bundled source (hash-comparable) AND byte-identical to the origin hash; everythingelse lands in ``skipped``. Removed skills lose their manifest entry so a lateropt-in re-seed treats them as new. Returns ``{ok, removed, skipped: [{name, reason}], dry_run, message}``."""- ss = _ss()- manifest = ss._read_manifest()- bundled_dir = ss._get_bundled_dir()- bundled_by_name = _bundled_by_name(bundled_dir)-+ ss, manifest, bundled_dir, bundled_by_name = _bundled_state()removed: List[str] = []skipped: List[dict] = []for name, origin_hash in sorted(manifest.items()):@@ -206,7 +200,7 @@ def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:if not dry_run:try:ss._rmtree_writable(dest)- except (OSError, IOError) as e:+ except OSError as e:skipped.append({"name": name, "reason": f"delete failed: {e}"})continuemanifest.pop(name, None)diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.pyindex 93d9de09d7d..c3758258846 100644--- a/tools/skills_sync_optional.py+++ b/tools/skills_sync_optional.py@@ -17,14 +17,15 @@ logger = logging.getLogger("tools.skills_sync")def _ss():+ """Live ``tools.skills_sync`` module (imported lazily: it re-exports this module)."""from tools import skills_syncreturn skills_syncdef _content_hash(directory: Path) -> str:- """Same hash style the skills hub lock uses; hashing is provenance metadata- only, so fall back to the local MD5 if guard deps are unavailable."""+ """Hub-lock hash style; provenance metadata only, so fall back to the local MD5+ if guard deps are unavailable."""try:from tools.skills_guard import content_hash@@ -34,7 +35,7 @@ def _content_hash(directory: Path) -> str:def _safe_rel_install_path(path: Path, base: Path) -> str:- """Return a normalized relative POSIX path, rejecting traversal/absolute paths."""+ """Normalized relative POSIX path; rejects traversal/absolute paths."""posix = path.relative_to(base).as_posix()pure = PurePosixPath(posix)parts = [part for part in pure.parts if part not in {"", "."}]@@ -80,11 +81,8 @@ def _write_hub_lock(lock_path: Path, data: dict) -> None: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 root_relative:- excluded = is_excluded_skill_path(skill_md.relative_to(optional_dir), root=optional_dir)- else:- excluded = is_excluded_skill_path(skill_md)- if excluded:+ if (is_excluded_skill_path(skill_md.relative_to(optional_dir), root=optional_dir) if root_relative+ else is_excluded_skill_path(skill_md)):continuetry:yield skill_md, skill_md.parent, _safe_rel_install_path(skill_md.parent, optional_dir)@@ -109,13 +107,14 @@ def _optional_skill_index() -> Dict[str, Tuple[str, str, Path]]:def _move_to_restore_backup(path: Path, backup_root: Path) -> str:"""Move an existing skill directory into a restore backup, preserving rel path."""- rel = path.relative_to(_ss()._skills_dir())+ ss = _ss()+ rel = path.relative_to(ss._skills_dir())target = backup_root / relsuffix = 0while target.exists():suffix += 1target = (backup_root / rel).with_name(f"{rel.name}-{suffix}")- _ss()._move_dir(path, target)+ ss._move_dir(path, target)return rel.as_posix()@@ -136,19 +135,14 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dictonly backfills exact-match provenance; ``restore=True`` also backs up matchingactive copies and copies the official source into its canonical path."""ss = _ss()-- def _fail(message: str) -> dict:- return {"ok": False, "message": message, "restored": [], "backfilled": [], "backed_up": []}-index = _optional_skill_index()- if not index:- return _fail("No official optional skills directory found.")- if name in {"all", "*"}:+ if index and name in {"all", "*"}:targets = sorted(set(index.values()), key=lambda item: item[1])elif name in index:targets = [index[name]]else:- return _fail(f"Official optional skill not found: {name}")+ message = f"Official optional skill not found: {name}" if index else "No official optional skills directory found."+ return {"ok": False, "message": message, "restored": [], "backfilled": [], "backed_up": []}restored: List[str] = []backed_up: List[str] = []