Skip to content

The agent that grows with you

refactor(tools): bundled-ops/sync guard folds (reset messages, read_for_diff, orphan recovery)

Teknium9197b7926fcd
diff --git a/tools/skills_sync.py b/tools/skills_sync.py
index fae2d1354e7..275ea16668d 100644
--- a/tools/skills_sync.py
+++ b/tools/skills_sync.py
@@ -188,8 +188,7 @@ def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Opt
continue
if rel in st.hub_paths: # the hub owns its install paths
continue
- if _dir_hash(candidate) != origin_hash:
- # Moving a customized copy would edit the user's work; warn so they migrate deliberately.
+ if _dir_hash(candidate) != origin_hash: # moving a customized copy would edit user work
st.say(
f" ⚠ {skill_name}: upstream moved this skill to {_rel_skills_posix(dest)}, but your "
f"modified copy at {rel} was kept — it will not receive updates. "
@@ -230,13 +229,12 @@ def _recover_orphan_backup(dest: Path) -> None:
"""If an interrupted update left the user's only copy in ``dest.bak`` with dest gone, move it
back so the skill isn't misread as user-deleted."""
orphan = dest.with_suffix(".bak")
- if not orphan.exists() or dest.exists():
- return
- try:
- _move_dir(orphan, dest)
- logger.info("Recovered orphaned skill backup: %s", orphan)
- except OSError:
- logger.warning("Could not recover orphaned skill backup %s", orphan, exc_info=True)
+ if orphan.exists() and not dest.exists():
+ try:
+ _move_dir(orphan, dest)
+ logger.info("Recovered orphaned skill backup: %s", orphan)
+ except OSError:
+ logger.warning("Could not recover orphaned skill backup %s", orphan, exc_info=True)
def _defer_to_external(st: _SyncState, skill_name: str, dest: Path, bundled_hash: str) -> None:
@@ -349,7 +347,6 @@ def sync_skills(quiet: bool = False) -> dict:
if not bundled_dir.exists():
return {"copied": [], "updated": [], "skipped": 0, "user_modified": [], "cleaned": [],
"suppressed": [], "total_bundled": 0, "optional_provenance_backfilled": []}
-
_skills_dir().mkdir(parents=True, exist_ok=True)
bundled_skills = _discover_bundled_skills(bundled_dir)
if essential_only:
diff --git a/tools/skills_sync_bundled_ops.py b/tools/skills_sync_bundled_ops.py
index 2a48c26d6bb..930f7077011 100644
--- a/tools/skills_sync_bundled_ops.py
+++ b/tools/skills_sync_bundled_ops.py
@@ -36,10 +36,8 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
if not in_manifest and not is_bundled:
return _fail("not_in_manifest", f"'{name}' is not a tracked bundled skill. Nothing to reset. "
f"(Hub-installed skills use `hermes skills uninstall`.)")
- # Delete the user's copy BEFORE touching the manifest so a failed rmtree can't
- # leave the skill in a manifest-less limbo.
deleted_user_copy = False
- if restore:
+ if restore: # delete the user's copy BEFORE the manifest so a failed rmtree can't strand it
if not is_bundled:
return _fail("bundled_missing", f"'{name}' has no bundled source — manifest entry preserved "
f"but cannot restore from bundled (skill was removed upstream).")
@@ -57,10 +55,10 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
if not restore:
action, message = "manifest_cleared", (f"Cleared manifest entry for '{name}'. Future `hermes update` runs "
f"will re-baseline against your current copy and accept upstream changes.")
- elif deleted_user_copy:
- action, message = "restored", f"Restored '{name}' from bundled source."
else:
- action, message = "restored", f"Restored '{name}' (no prior user copy, re-copied from bundled)."
+ action = "restored"
+ message = (f"Restored '{name}' from bundled source." if deleted_user_copy
+ else f"Restored '{name}' (no prior user copy, re-copied from bundled).")
return {"ok": True, "action": action, "message": message, "synced": synced}
@@ -84,9 +82,10 @@ def _read_for_diff(path: Path) -> Tuple[Optional[bytes], Optional[str]]:
"""``(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"))
except OSError:
return None, None
+ try:
+ return data, (None if b"\x00" in data else data.decode("utf-8"))
except UnicodeDecodeError:
return data, None
diff --git a/tools/skills_sync_optional.py b/tools/skills_sync_optional.py
index c1075127c1a..2dd60ca5dc5 100644
--- a/tools/skills_sync_optional.py
+++ b/tools/skills_sync_optional.py
@@ -56,18 +56,16 @@ def _hub_lock_entries(data: Optional[dict]) -> List[dict]:
def _read_hub_install_paths() -> Set[str]:
- """Hub-lock install paths as POSIX strings. Hub-installed skills are owned by the
- hub: rename recovery must not move them even when content matches a bundled
- origin hash, or the lock's ``install_path`` dangles."""
+ """Hub-lock install paths as POSIX strings. Hub-installed skills are owned by the hub: rename
+ recovery must not move them even when content matches a bundled origin hash (dangling lock)."""
return {str(e["install_path"]).strip("/") for e in _hub_lock_entries(_load_hub_lock()) if e.get("install_path")}
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")):
- 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:
+ if (is_excluded_skill_path(skill_md.relative_to(optional_dir), root=optional_dir)
+ if root_relative else is_excluded_skill_path(skill_md)):
continue
try:
yield skill_md, skill_md.parent, _safe_rel_install_path(skill_md.parent, optional_dir)
@@ -119,8 +117,8 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
for folder_name, install_path, src in targets if restore else []:
dest = ss._skills_dir() / Path(*install_path.split("/"))
canonical_ok = dest.exists() and ss._dir_hash(dest) == ss._dir_hash(src)
- # Active copies by frontmatter name or folder slug — the curator may have moved
- # the skill into another category; ``dest`` itself is handled below.
+ # Active copies by frontmatter name or folder slug (the curator may have moved the skill
+ # into another category); ``dest`` itself is handled below.
names = {folder_name, ss._read_skill_name(src / "SKILL.md", folder_name)}
for md in ss._iter_active_skill_mds(sort=True):
match = md.parent
diff --git a/tools/skills_tool.py b/tools/skills_tool.py
index ce135b2ea7a..c1fb829b8d3 100644
--- a/tools/skills_tool.py
+++ b/tools/skills_tool.py
@@ -206,8 +206,7 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:
return [dict(s) for s in cached[2]]
skills = []
seen_names: set = set()
- # Project dirs iterate through the quarantine chokepoint (scan-time injection gate).
- for scan_dir in dirs_to_scan:
+ for scan_dir in dirs_to_scan: # project dirs go through the quarantine chokepoint
_iter = iter_project_skill_files if scan_dir in project_dirs else lambda d: iter_skill_index_files(d, "SKILL.md")
for skill_md in _iter(scan_dir):
if any(part in _EXCLUDED_SKILL_DIRS for part in skill_md.parts):
@@ -221,9 +220,8 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:
continue
description = 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)
+ 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)})
@@ -231,8 +229,8 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:
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)
- # 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.
+ # 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]
@@ -291,8 +289,8 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess):
except Exception as exc:
logger.debug("Failed pruning inactive memory-provider skills: %s", exc)
plugin_skill_md = pm.find_plugin_skill(name)
- # Memory providers load through plugins.memory, not the general PluginManager: load
- # the namespaced provider once so its collector can forward its skills into the registry.
+ # Memory providers load through plugins.memory, not the general PluginManager: load the
+ # namespaced provider once so its collector can forward its skills into the registry.
if plugin_skill_md is None and namespace == active_memory_provider:
try:
from plugins.memory import load_memory_provider
diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.py
index c246e260972..f0b2a7bbd26 100644
--- a/tools/skills_tool_plugin.py
+++ b/tools/skills_tool_plugin.py
@@ -91,20 +91,17 @@ def _serve_skill_file(
content = _read_skill_text(target)
except UnicodeDecodeError:
return _json({
- "success": True, "name": label, "file": file_path,
- "content": f"[Binary file: {target.name}, size: {target.stat().st_size} bytes]",
- "is_binary": True})
+ "success": True, "name": label, "file": file_path, "is_binary": True,
+ "content": f"[Binary file: {target.name}, size: {target.stat().st_size} bytes]"})
except Exception as exc:
if not read_error_prefix:
raise
return _fail(f"Failed to read '{file_path}': {exc}")
if mark_read:
_mark_background_review_read(target)
- return _json({
+ return _json({ # _source_path: internal, feeds the repeat-view dedup fingerprint
"success": True, "name": label, "file": file_path, "content": content,
- "file_type": target.suffix,
- # Internal: absolute source path for the repeat-view dedup fingerprint.
- "_source_path": str(target)})
+ "file_type": target.suffix, "_source_path": str(target)})
def _mark_background_review_read(path: Path) -> None:
@@ -142,9 +139,8 @@ def _serve_plugin_skill(
if _st._is_skill_disabled(qualified_name):
return _fail(f"Skill '{qualified_name}' is disabled.")
if not _st.skill_matches_platform(parsed_frontmatter):
- return _fail(
- f"Skill '{qualified_name}' is not supported on this platform.",
- readiness_status=SkillReadinessStatus.UNSUPPORTED.value)
+ return _fail(f"Skill '{qualified_name}' is not supported on this platform.",
+ readiness_status=SkillReadinessStatus.UNSUPPORTED.value)
if file_path:
return _serve_skill_file(skill_md.parent, file_path, qualified_name, read_error_prefix=True)
if any(p in content.lower() for p in _INJECTION_PATTERNS):