skills_sync.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/env python3
  2. """Skills Sync -- manifest-based seeding and updating of bundled skills. Copies repo skills/ into
  3. ~/.hermes/skills/, tracking each synced skill's origin hash in .bundled_manifest (v2 "name:hash"
  4. lines; v1 plain names auto-migrate). NEW skills are copied and recorded; EXISTING skills update
  5. only when bundled changed AND the user copy still matches the origin hash (else user-customized
  6. -> SKIP); user-DELETED skills are not re-added; upstream-REMOVED ones leave the manifest once no active or
  7. archived copy remains (the entry is that copy's only built-in provenance record)."""
  8. import hashlib
  9. import logging
  10. import os
  11. import shutil
  12. import stat
  13. import sys
  14. from contextlib import suppress
  15. from dataclasses import dataclass, field
  16. from pathlib import Path
  17. from typing import Dict, Iterator, List, Optional, Set, Tuple
  18. # Force UTF-8 stdout/stderr: GBK-style Windows locales can't encode the glyphs
  19. # printed here (✓ ↑ →), and install.ps1 parses this script's stdout as UTF-8.
  20. for _stream in (sys.stdout, sys.stderr):
  21. if hasattr(_stream, "reconfigure"):
  22. with suppress(ValueError, TypeError):
  23. _stream.reconfigure(encoding="utf-8", errors="replace")
  24. from hermes_constants import get_bundled_skills_dir, get_hermes_home, get_optional_skills_dir
  25. from agent.skill_utils import ESSENTIAL_SKILLS, is_excluded_skill_path
  26. from tools.skill_usage import read_skill_name
  27. from tools.skills_sync_optional import (
  28. _backfill_optional_provenance, _ignore_runtime_cache, _is_runtime_cache, _read_hub_install_paths,
  29. )
  30. from utils import atomic_write_text
  31. logger = logging.getLogger(__name__)
  32. HERMES_HOME = get_hermes_home()
  33. SKILLS_DIR = HERMES_HOME / "skills"
  34. MANIFEST_FILE = SKILLS_DIR / ".bundled_manifest"
  35. # Import-time snapshots backing the call-time accessors: long-lived multi-profile runtimes
  36. # retarget HERMES_HOME after import, and frozen constants would resolve (and for
  37. # reset_bundled_skill() DELETE) against the wrong profile. Accessors honor an explicitly
  38. # patched module global and otherwise re-resolve on every call.
  39. # Same bug class and same fix as skills_tool (f8723c478) and skill_manager_tool (c6a3d412d): long-lived
  40. # multi-profile runtimes (Dashboard console, TUI/Desktop backend, cron, kanban workers) import this module
  41. # once under the launch HERMES_HOME and later scope requests to a different profile via
  42. # set_hermes_home_override(). See #65828.
  43. _HERMES_HOME_AT_IMPORT = HERMES_HOME
  44. _SKILLS_DIR_AT_IMPORT = SKILLS_DIR
  45. _MANIFEST_FILE_AT_IMPORT = MANIFEST_FILE
  46. def _live(configured, at_import: Path, fallback) -> Path:
  47. """The patched module global if it changed since import, else the live value."""
  48. return Path(configured) if Path(configured) != at_import else fallback()
  49. def _hermes_home() -> Path:
  50. return _live(HERMES_HOME, _HERMES_HOME_AT_IMPORT, get_hermes_home)
  51. def _skills_dir() -> Path:
  52. return _live(SKILLS_DIR, _SKILLS_DIR_AT_IMPORT, lambda: _hermes_home() / "skills")
  53. def _manifest_file() -> Path:
  54. return _live(MANIFEST_FILE, _MANIFEST_FILE_AT_IMPORT, lambda: _skills_dir() / ".bundled_manifest")
  55. # Written by `hermes profile create --no-skills` / installer `--no-skills`: sync seeds only
  56. # essential skills. Mirrors hermes_cli.profiles.NO_BUNDLED_SKILLS_MARKER (no CLI import here).
  57. NO_BUNDLED_SKILLS_MARKER = ".no-bundled-skills"
  58. def _get_bundled_dir() -> Path: # HERMES_BUNDLED_SKILLS env first, then repo-relative
  59. return get_bundled_skills_dir(Path(__file__).parent.parent / "skills")
  60. def _get_optional_dir() -> Path:
  61. return get_optional_skills_dir(Path(__file__).parent.parent / "optional-skills")
  62. def _rel_skills_posix(path: Path) -> str:
  63. return path.relative_to(_skills_dir()).as_posix()
  64. def _iter_skill_mds(root: Path, sort: bool = False) -> Iterator[Path]:
  65. """Yield every non-excluded SKILL.md under ``root`` (nothing when it does not exist)."""
  66. found = root.rglob("SKILL.md") if root.exists() else iter(())
  67. for skill_md in sorted(found) if sort else found:
  68. if not is_excluded_skill_path(skill_md):
  69. yield skill_md
  70. def _iter_active_skill_mds(sort: bool = False) -> Iterator[Path]:
  71. """Yield every non-excluded SKILL.md in the user's skills tree."""
  72. return _iter_skill_mds(_skills_dir(), sort)
  73. def _build_external_skill_index() -> set[str]:
  74. """Names (directory and frontmatter) of every skill provided by external_dirs,
  75. so sync_skills never shadows an externally-delegated skill."""
  76. from agent.skill_utils import get_external_skills_dirs, _external_dirs_cache_clear
  77. _external_dirs_cache_clear() # so a config edit (or a test patch) is seen
  78. external_names: set[str] = set()
  79. for ext_dir in get_external_skills_dirs():
  80. for skill_md in _iter_skill_mds(ext_dir):
  81. external_names.update({skill_md.parent.name, read_skill_name(skill_md, "")})
  82. external_names.discard("")
  83. return external_names
  84. def _read_manifest() -> dict[str, str]:
  85. """``{skill_name: origin_hash}``; v1 plain-name lines get an empty hash (migrates next sync)."""
  86. try:
  87. result = {}
  88. for line in _manifest_file().read_text(encoding="utf-8-sig").splitlines():
  89. line = line.strip()
  90. if not line:
  91. continue
  92. if ":" in line:
  93. # v2 format: name:hash
  94. name, _, hash_val = line.partition(":")
  95. result[name.strip()] = hash_val.strip()
  96. else:
  97. # v1 format: plain name — empty hash triggers migration
  98. result[line] = ""
  99. return result
  100. except OSError:
  101. return {}
  102. def _read_suppressed_names() -> set:
  103. """Built-in skills the curator pruned — must NOT be re-seeded on sync.
  104. Delegates to ``tools.skill_usage`` (single source of truth) and falls back
  105. to reading ``~/.hermes/skills/.curator_suppressed`` directly if that import
  106. is unavailable in a packaged/update context.
  107. """
  108. try:
  109. from tools.skill_usage import read_suppressed_names
  110. return read_suppressed_names()
  111. except Exception:
  112. path = _skills_dir() / ".curator_suppressed"
  113. if not path.exists():
  114. return set()
  115. names = set()
  116. try:
  117. for line in path.read_text(encoding="utf-8-sig").splitlines():
  118. line = line.strip()
  119. if line and not line.startswith("#"):
  120. names.add(line)
  121. except OSError:
  122. pass
  123. return names
  124. def _write_manifest(entries: dict[str, str]):
  125. """Atomic v2 write, preserving an existing file's mode/owner (not mkstemp's 0600)."""
  126. from hermes_constants import mkdir_under_hermes_home
  127. mkdir_under_hermes_home(_manifest_file().parent)
  128. try:
  129. data = "".join(f"{n}:{h}\n" for n, h in sorted(entries.items()))
  130. atomic_write_text(_manifest_file(), data, tmp_prefix=".bundled_manifest_", preserve_mode=True)
  131. except Exception as e:
  132. logger.debug("Failed to write skills manifest %s: %s", _manifest_file(), e, exc_info=True)
  133. def _discover_bundled_skills(bundled_dir: Path) -> list[tuple[str, Path]]:
  134. """``(skill_name, skill_dir)`` per SKILL.md under the bundled dir. Exclusions are evaluated
  135. relative to the bundled tree: the install prefix itself may contain ``venv``/``site-packages``
  136. (which once made wheel installs discover zero skills)."""
  137. if not bundled_dir.exists():
  138. return []
  139. return [
  140. (read_skill_name(md, md.parent.name), md.parent)
  141. for md in bundled_dir.rglob("SKILL.md")
  142. if not is_excluded_skill_path(md.relative_to(bundled_dir), root=bundled_dir)]
  143. def _compute_relative_dest(skill_dir: Path, bundled_dir: Path) -> Path:
  144. """Destination preserving category structure (bundled/mlops/axolotl -> skills/mlops/axolotl)."""
  145. return _skills_dir() / skill_dir.relative_to(bundled_dir)
  146. def dir_hash(directory: Path, *, include_runtime_cache: bool = False) -> str:
  147. """MD5 of package paths/content, excluding generated runtime state.
  148. The legacy option is only for proving an exact pre-filter origin match.
  149. Keep the original path encoding so clean existing manifests remain valid.
  150. """
  151. hasher = hashlib.md5()
  152. with suppress(OSError):
  153. for fpath in sorted(directory.rglob("*")):
  154. if (include_runtime_cache or not _is_runtime_cache(fpath, directory)) and fpath.is_file():
  155. hasher.update(str(fpath.relative_to(directory)).encode("utf-8"))
  156. hasher.update(fpath.read_bytes())
  157. return hasher.hexdigest()
  158. def _matches_origin_hash(directory: Path, origin_hash: str, user_hash: Optional[str] = None) -> bool:
  159. """Prove unchanged package ownership against a clean OR exact legacy hash.
  160. Never re-baseline a differing package merely because it contains a cache:
  161. if legacy cached bytes changed/disappeared, the old origin cannot be proven.
  162. A genuinely edited package must remain protected in that case.
  163. """
  164. if not origin_hash:
  165. return False
  166. current = dir_hash(directory) if user_hash is None else user_hash
  167. return current == origin_hash or dir_hash(directory, include_runtime_cache=True) == origin_hash
  168. def _move_dir(src: Path, dest: Path) -> None:
  169. dest.parent.mkdir(parents=True, exist_ok=True)
  170. shutil.move(str(src), str(dest))
  171. def _copy_dir(src: Path, dest: Path) -> None:
  172. dest.parent.mkdir(parents=True, exist_ok=True)
  173. shutil.copytree(src, dest, ignore=_ignore_runtime_cache)
  174. def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Optional[str]:
  175. """Move a bundled skill's stale copy to its new canonical path after an upstream RENAME /
  176. RECATEGORIZATION (else it is misread as user-deleted and stranded forever). Only a copy
  177. byte-identical to the origin hash — proof *we* placed it — moves. Returns rel source path."""
  178. origin_hash = st.manifest.get(skill_name, "")
  179. if not origin_hash:
  180. return None
  181. if st.active_index is None: # by frontmatter name
  182. st.active_index = {}
  183. for md in _iter_active_skill_mds():
  184. st.active_index.setdefault(read_skill_name(md, md.parent.name), []).append(md.parent)
  185. st.hub_paths = _read_hub_install_paths()
  186. for candidate in st.active_index.get(skill_name, []):
  187. if candidate == dest or not candidate.is_dir():
  188. continue
  189. try:
  190. rel = _rel_skills_posix(candidate)
  191. except ValueError:
  192. continue
  193. if rel in st.hub_paths: # the hub owns its install paths
  194. continue
  195. if not _matches_origin_hash(candidate, origin_hash): # moving a customized copy would edit user work
  196. st.say(
  197. f" ⚠ {skill_name}: upstream moved this skill to {_rel_skills_posix(dest)}, but your "
  198. f"modified copy at {rel} was kept — it will not receive updates. "
  199. f"Run `hermes skills reset {skill_name} --restore` to move to the new location.")
  200. continue
  201. try:
  202. _move_dir(candidate, dest)
  203. except OSError:
  204. logger.warning("Could not relocate renamed skill %s -> %s", candidate, dest, exc_info=True)
  205. return None
  206. logger.info("Relocated renamed bundled skill: %s -> %s", candidate, dest)
  207. st.say(f" → {skill_name} (moved {rel} → {_rel_skills_posix(dest)})")
  208. return rel
  209. return None
  210. @dataclass
  211. class _SyncState:
  212. """Mutable accumulator threaded through one sync_skills() run."""
  213. manifest: dict[str, str]
  214. quiet: bool
  215. skipped: int = 0
  216. copied: list[str] = field(default_factory=list)
  217. updated: list[str] = field(default_factory=list)
  218. user_modified: list[str] = field(default_factory=list)
  219. suppressed: list[str] = field(default_factory=list)
  220. relocated: list[str] = field(default_factory=list)
  221. shadowed_by_external: list[str] = field(default_factory=list)
  222. active_index: Optional[dict[str, list[Path]]] = None # rename-recovery indexes are expensive on
  223. hub_paths: set[str] = field(default_factory=set) # bind mounts: built lazily, only when needed
  224. def say(self, msg: str) -> None:
  225. if not self.quiet:
  226. print(msg)
  227. def _recover_orphan_backup(dest: Path) -> None:
  228. """If an interrupted update left the user's only copy in ``dest.bak`` with dest gone, move it
  229. back so the skill isn't misread as user-deleted."""
  230. orphan = dest.with_suffix(".bak")
  231. if orphan.exists() and not dest.exists():
  232. try:
  233. _move_dir(orphan, dest)
  234. logger.info("Recovered orphaned skill backup: %s", orphan)
  235. except OSError:
  236. logger.warning("Could not recover orphaned skill backup %s", orphan, exc_info=True)
  237. def _defer_to_external(st: _SyncState, skill_name: str, dest: Path, bundled_hash: str) -> None:
  238. """An external_dirs source provides this skill; a local copy would be a name collision the
  239. loader refuses. Defer for ALL manifest states; remove a stale local shadow from an earlier
  240. sync only when byte-identical (a user's own skill differs)."""
  241. st.shadowed_by_external.append(skill_name)
  242. st.skipped += 1
  243. st.say(f" ⇢ {skill_name} (deferred to external_dirs, not written to local tree)")
  244. if dest.exists() and dir_hash(dest) == bundled_hash:
  245. _rmtree_writable(dest)
  246. st.say(f" ✓ removed stale shadow of {skill_name}")
  247. st.manifest.pop(skill_name, None)
  248. def _install_new_skill(st: _SyncState, skill_name: str, skill_src: Path, dest: Path, bundled_hash: str) -> None:
  249. """Handle a skill never offered before (not in manifest)."""
  250. try:
  251. if dest.exists():
  252. # Never overwrite a same-named user skill. Baseline the manifest only when
  253. # byte-identical: a differing copy's bundled_hash reads as "user-modified" forever.
  254. st.skipped += 1
  255. if dir_hash(dest) == bundled_hash:
  256. st.manifest[skill_name] = bundled_hash
  257. else:
  258. st.say(
  259. f" ⚠ {skill_name}: bundled version shipped but you already have a local skill "
  260. f"by this name — yours was kept. Run `hermes skills reset {skill_name}` to "
  261. f"replace it with the bundled version.")
  262. else:
  263. _copy_dir(skill_src, dest)
  264. st.copied.append(skill_name)
  265. st.manifest[skill_name] = bundled_hash
  266. st.say(f" + {skill_name}")
  267. except OSError as e:
  268. st.say(f" ! Failed to copy {skill_name}: {e}") # not in manifest — next sync retries
  269. def _replace_skill_dir(skill_src: Path, dest: Path) -> None:
  270. """Replace ``dest`` with a fresh copy of ``skill_src`` via a .bak sibling; restore on failure."""
  271. backup = dest.with_suffix(".bak")
  272. if backup.exists(): # a stale .bak would make shutil.move() nest dest INSIDE it
  273. _rmtree_writable(backup)
  274. shutil.move(str(dest), str(backup))
  275. try:
  276. shutil.copytree(skill_src, dest, ignore=_ignore_runtime_cache)
  277. except OSError:
  278. if backup.exists(): # clear a partially-written dest so it can't shadow/block the restore
  279. if dest.exists():
  280. try:
  281. _rmtree_writable(dest)
  282. except OSError:
  283. logger.warning("Could not clear partial copy %s during restore", dest,
  284. exc_info=True)
  285. if not dest.exists():
  286. shutil.move(str(backup), str(dest))
  287. raise
  288. try:
  289. _rmtree_writable(backup)
  290. except OSError:
  291. logger.debug("Could not remove backup %s", backup, exc_info=True)
  292. def _update_existing_skill(st: _SyncState, skill_name: str, skill_src: Path, dest: Path, bundled_hash: str) -> None:
  293. """Handle a skill that is in the manifest AND on disk."""
  294. origin_hash = st.manifest.get(skill_name, "")
  295. if origin_hash and bundled_hash == origin_hash: # bundled unchanged: skip without hashing the user copy
  296. st.skipped += 1
  297. return
  298. user_hash = dir_hash(dest)
  299. if not origin_hash: # v1 migration: baseline from user's copy (can't tell edit from upstream)
  300. st.manifest[skill_name] = user_hash
  301. st.skipped += 1
  302. return
  303. if not _matches_origin_hash(dest, origin_hash, user_hash):
  304. st.user_modified.append(skill_name)
  305. st.say(f" ~ {skill_name} (user-modified, skipping)")
  306. return
  307. # bundled changed and the user copy is pristine -> update
  308. try:
  309. _replace_skill_dir(skill_src, dest)
  310. except OSError as e:
  311. st.say(f" ! Failed to update {skill_name}: {e}")
  312. return
  313. st.manifest[skill_name] = bundled_hash
  314. st.updated.append(skill_name)
  315. st.say(f" ↑ {skill_name} (updated)")
  316. def _seed_category_descriptions(bundled_dir: Path, only_dirs: Optional[set[Path]]) -> None:
  317. """Copy category DESCRIPTION.md files not already present; ``only_dirs`` restricts
  318. seeding to the essential skills' categories on opted-out profiles."""
  319. for desc_md in bundled_dir.rglob("DESCRIPTION.md"):
  320. dest_desc = _skills_dir() / desc_md.relative_to(bundled_dir)
  321. if (only_dirs is not None and dest_desc.parent not in only_dirs) or dest_desc.exists():
  322. continue
  323. try:
  324. dest_desc.parent.mkdir(parents=True, exist_ok=True)
  325. shutil.copy2(desc_md, dest_desc)
  326. except OSError as e:
  327. logger.debug("Could not copy %s: %s", desc_md, e)
  328. def sync_skills(quiet: bool = False) -> dict:
  329. """Sync bundled skills into ~/.hermes/skills/ using the manifest; returns the per-category
  330. result dict. Opted-out profiles seed ONLY ESSENTIAL_SKILLS (the system prompt always
  331. points at ``hermes-agent``)."""
  332. essential_only = (_hermes_home() / NO_BUNDLED_SKILLS_MARKER).exists()
  333. if essential_only and not quiet:
  334. print(" (profile opted out of bundled skills via .no-bundled-skills — seeding essential skills only)")
  335. bundled_dir = _get_bundled_dir()
  336. if not bundled_dir.exists():
  337. return {"copied": [], "updated": [], "skipped": 0, "user_modified": [], "cleaned": [],
  338. "suppressed": [], "total_bundled": 0, "optional_provenance_backfilled": []}
  339. _skills_dir().mkdir(parents=True, exist_ok=True)
  340. bundled_skills = _discover_bundled_skills(bundled_dir)
  341. if essential_only:
  342. bundled_skills = [(name, src) for name, src in bundled_skills if name in ESSENTIAL_SKILLS]
  343. suppressed = _read_suppressed_names()
  344. external_index = _build_external_skill_index()
  345. st = _SyncState(manifest=_read_manifest(), quiet=quiet)
  346. for skill_name, skill_src in bundled_skills:
  347. # Curator-pruned built-ins must not resurrect on every update; essentials are exempt.
  348. if skill_name in suppressed and skill_name not in ESSENTIAL_SKILLS:
  349. st.suppressed.append(skill_name)
  350. continue
  351. dest = _compute_relative_dest(skill_src, bundled_dir)
  352. bundled_hash = dir_hash(skill_src)
  353. # Recoveries run BEFORE classification so a missing dest isn't misread as user-deleted.
  354. _recover_orphan_backup(dest)
  355. if not dest.exists() and skill_name in st.manifest and _recover_renamed_skill(st, skill_name, dest):
  356. st.relocated.append(skill_name)
  357. if skill_name in external_index:
  358. _defer_to_external(st, skill_name, dest, bundled_hash)
  359. elif skill_name not in st.manifest:
  360. _install_new_skill(st, skill_name, skill_src, dest, bundled_hash)
  361. elif dest.exists():
  362. _update_existing_skill(st, skill_name, skill_src, dest, bundled_hash)
  363. else:
  364. st.skipped += 1 # in manifest but not on disk — user deleted it
  365. # Clean manifest entries for skills removed upstream once no copy is left. A dropped built-in still
  366. # on disk (active or archived) keeps its entry: it is the only provenance record, and without it the
  367. # copy reads as agent-authored ("Learned", editable) (#95415). Skipped when opted out: bundled_skills
  368. # is only the essential set there, so cleaning would drop tracking for everything else.
  369. removed = [] if essential_only else sorted(set(st.manifest) - {name for name, _ in bundled_skills})
  370. present = set()
  371. if removed: # curator archive is flat: directory name == skill name
  372. archive = _skills_dir() / ".archive"
  373. present = {read_skill_name(md, md.parent.name) for md in _iter_active_skill_mds()} | (
  374. {p.name for p in archive.iterdir() if p.is_dir()} if archive.is_dir() else set())
  375. cleaned = [name for name in removed if name not in present]
  376. for name in cleaned:
  377. del st.manifest[name]
  378. _seed_category_descriptions(
  379. bundled_dir,
  380. {_compute_relative_dest(src, bundled_dir).parent for _, src in bundled_skills} if essential_only else None)
  381. _write_manifest(st.manifest)
  382. return {
  383. "copied": st.copied, "updated": st.updated, "skipped": st.skipped, "user_modified": st.user_modified,
  384. "cleaned": cleaned, "suppressed": st.suppressed, "relocated": st.relocated,
  385. "total_bundled": len(bundled_skills),
  386. "optional_provenance_backfilled": _backfill_optional_provenance(quiet=quiet),
  387. "shadowed_by_external": st.shadowed_by_external,
  388. "skipped_opt_out": essential_only} # lets callers report "opted out", not a normal sync
  389. def _rmtree_writable(path: Path) -> None:
  390. """rmtree that first makes read-only entries writable (Nix/deb/rpm keep r-x dirs; unlinking
  391. a child needs a writable parent, so chmod both). Scope guard: refuses anything not a STRICT
  392. child of the active skills root (bad join / missing HERMES_HOME / malicious manifest entry).
  393. Handles immutable package sources (Nix store, deb/rpm installs) that preserve read-only permissions on
  394. copied files *and* directories (``r-xr-xr-x``). Removing a child requires write permission on its parent
  395. directory, so the retry handler makes the failing path **and its parent** writable before re-attempting.
  396. See #34860, #34972.
  397. """
  398. target = Path(path).resolve()
  399. skills_root = _skills_dir().resolve()
  400. if skills_root not in target.parents:
  401. raise ValueError(f"refusing to rmtree {target!r}: not strictly under {skills_root!r} (scope guard — see #48200)")
  402. def _on_error(func, fpath, exc_info):
  403. for p in (os.path.dirname(fpath), fpath):
  404. with suppress(OSError):
  405. os.chmod(p, stat.S_IRWXU)
  406. func(fpath)
  407. shutil.rmtree(path, onerror=_on_error)
  408. if __name__ == "__main__":
  409. print("Syncing bundled skills into ~/.hermes/skills/ ...")
  410. result = sync_skills(quiet=False)
  411. parts = [f"{len(result['copied'])} new", f"{len(result['updated'])} updated", f"{result['skipped']} unchanged"]
  412. if names := result["user_modified"]:
  413. shown = ", ".join(names[:5]) + (f", +{len(names) - 5} more" if len(names) > 5 else "")
  414. parts.append(f"{len(names)} user-modified (kept): {shown}")
  415. if result["cleaned"]:
  416. parts.append(f"{len(result['cleaned'])} cleaned from manifest")
  417. if backfilled := result.get("optional_provenance_backfilled"):
  418. parts.append(f"{len(backfilled)} official optional backfilled")
  419. print(f"\nDone: {', '.join(parts)}. {result['total_bundled']} total bundled.")