skill_manager_guards.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. """Write/delete guards for ``skill_manage``. Every guard returns ``None`` when the
  2. operation may proceed, else a refusal (error dict or message). Origin-owned state
  3. (``_find_skill``, ``_skills_dir``) is reached lazily via ``tools.skill_manager_tool``
  4. so test patches keep working."""
  5. import contextvars as _ctxvars
  6. import logging
  7. import threading
  8. from contextlib import suppress
  9. from pathlib import Path
  10. from typing import Any, Dict, Optional
  11. logger = logging.getLogger("tools.skill_manager_tool")
  12. def _refusal(message: str, **extra: Any) -> dict[str, Any]:
  13. return {"success": False, "error": message, **extra}
  14. def _is_background_review() -> bool:
  15. """True inside the autonomous curator review fork; False on any lookup failure."""
  16. try:
  17. from tools.skill_provenance import is_background_review
  18. return bool(is_background_review())
  19. except Exception:
  20. return False
  21. def _resolved_str(path: Path) -> str:
  22. with suppress(Exception):
  23. return str(path.resolve())
  24. return str(path)
  25. class _BackgroundReviewReadMarks:
  26. """Read marks shared by copied tool contexts within one review run."""
  27. def __init__(self) -> None:
  28. self._lock = threading.Lock()
  29. self._paths: set[str] = set()
  30. def add(self, path: str) -> None:
  31. with self._lock:
  32. self._paths.add(path)
  33. def contains(self, path: str) -> bool:
  34. with self._lock:
  35. return path in self._paths
  36. _background_review_read_paths: _ctxvars.ContextVar[Optional[_BackgroundReviewReadMarks]] = (
  37. _ctxvars.ContextVar("background_review_read_paths", default=None))
  38. def mark_background_review_skill_read(path: Path) -> None:
  39. """Record that the active background-review fork has read a skill file. The fork must not
  40. patch content it only inferred from the transcript: skill_view/read_file call this, and
  41. the write guards require the mark."""
  42. if not _is_background_review():
  43. return
  44. if (marks := _background_review_read_paths.get()) is None:
  45. _background_review_read_paths.set(marks := _BackgroundReviewReadMarks())
  46. marks.add(_resolved_str(path))
  47. def _background_review_has_read(path: Path) -> bool:
  48. marks = _background_review_read_paths.get()
  49. return marks is not None and marks.contains(_resolved_str(path))
  50. def _reset_background_review_read_marks() -> None:
  51. """Start a fresh, isolated read set for the current review context."""
  52. _background_review_read_paths.set(_BackgroundReviewReadMarks())
  53. def _resolved_roots(skill_path: Path):
  54. """``(resolved skill_path, [(root, resolved_root), ...])`` over every resolvable skills root."""
  55. from agent.skill_utils import get_all_skills_dirs
  56. try:
  57. resolved = skill_path.resolve()
  58. except OSError:
  59. resolved = skill_path
  60. roots = []
  61. for root in get_all_skills_dirs():
  62. with suppress(OSError):
  63. roots.append((root, root.resolve()))
  64. return resolved, roots
  65. def _containing_skills_root(skill_path: Path) -> Path:
  66. """Skills root (local or external_dirs) containing ``skill_path``; local dir if none match."""
  67. from tools import skill_manager_tool as _smt
  68. resolved, roots = _resolved_roots(skill_path)
  69. return next((root for root, r in roots if resolved.is_relative_to(r)), _smt._skills_dir())
  70. def _is_path_redirect(path: Path) -> bool:
  71. """Symlink or (Windows 3.12+) junction — either lets a poisoned tree redirect rmtree outside."""
  72. try:
  73. return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())
  74. except OSError:
  75. return False
  76. def _validate_delete_target(skill_dir: Path) -> Optional[str]:
  77. """Last-line guard before rmtree: even a poisoned tree must never delete (1) a path outside
  78. every known skills root, (2) a skills root itself, (3) a symlink/junction (rmtree follows it).
  79. ``_find_skill`` already restricts ``skill_dir`` to a real ``SKILL.md`` parent discovered by walking the
  80. skills roots, so the agent cannot inject an arbitrary path the way Kilo Code's HTTP endpoint could
  81. (their issue 11227: a built-in-skill sentinel resolved to the server cwd and a recursive delete wiped
  82. the user's entire working directory). This is the matching defense-in-depth for our agent-facing
  83. ``skill_manage`` delete path: even if discovery or a poisoned tree hands us a bad directory, never
  84. recursively delete See #11227.
  85. """
  86. if _is_path_redirect(skill_dir):
  87. return (f"Refusing to delete '{skill_dir}': the skill directory is a "
  88. f"symlink/junction. Remove the link target manually if intended.")
  89. try:
  90. skill_dir.resolve()
  91. except OSError as exc:
  92. return f"Refusing to delete '{skill_dir}': could not resolve path ({exc})."
  93. resolved, roots = _resolved_roots(skill_dir)
  94. for _root, root in roots:
  95. if resolved == root:
  96. return (f"Refusing to delete '{skill_dir}': resolves to the skills root "
  97. f"itself, which would remove every installed skill.")
  98. if resolved.is_relative_to(root):
  99. return None
  100. return f"Refusing to delete '{skill_dir}': path does not resolve inside any known skills root."
  101. def _is_pinned(name: str, what: str) -> Optional[bool]:
  102. """skill_usage pinned flag; None (logged at debug) when the record is unreadable."""
  103. try:
  104. from tools import skill_usage
  105. return bool(skill_usage.get_record(name).get("pinned"))
  106. except Exception:
  107. logger.debug("%s lookup failed for %s", what, name, exc_info=True)
  108. return None
  109. def _pinned_guard(name: str) -> Optional[str]:
  110. """Refusal message if *name* is pinned or essential, else None. Pin only guards DELETION;
  111. patches/edits stay allowed. ESSENTIAL_SKILLS are permanently pinned (the system prompt
  112. references them). Best-effort: an unreadable sidecar lets the delete through."""
  113. try:
  114. from agent.skill_utils import ESSENTIAL_SKILLS
  115. if name in ESSENTIAL_SKILLS:
  116. return (
  117. f"Skill '{name}' is essential to Hermes (the agent's own "
  118. f"operating manual referenced by the system prompt) and "
  119. f"cannot be deleted. Patches and edits are still allowed.")
  120. except Exception:
  121. logger.debug("essential-guard lookup failed for %s", name, exc_info=True)
  122. if _is_pinned(name, "pinned-guard"):
  123. return (
  124. f"Skill '{name}' is pinned and cannot be deleted by skill_manage. Ask the user to "
  125. f"run `hermes curator unpin {name}` if they want to delete it. Patches and edits "
  126. f"are allowed on pinned skills; only deletion is blocked.")
  127. return None
  128. def _background_review_delete_guard(name: str, skill_dir: Path) -> Optional[dict[str, Any]]:
  129. """Refuse autonomous deletes of anything but curator-owned sediment. Content writes are not
  130. gated by ownership: the review fork exists to improve every skill it learns from, and every
  131. write is ledgered and reversible, while an archive removes a skill the user relies on."""
  132. if not _is_background_review():
  133. return None
  134. refuse = "Refusing background curator delete for"
  135. if _is_pinned(name, "pinned skill guard"):
  136. return _refusal(
  137. f"{refuse} pinned skill '{name}': pinned skills "
  138. f"are off-limits to autonomous maintenance. Ask the user to run `hermes curator "
  139. f"unpin {name}` if they want it changed.")
  140. try:
  141. from agent.skill_utils import is_external_skill_path
  142. if is_external_skill_path(skill_dir):
  143. return _refusal(
  144. f"{refuse} skill '{name}': the skill lives in skills.external_dirs, which are "
  145. f"externally owned and read-only to autonomous curation.")
  146. except Exception:
  147. logger.debug("external skill guard lookup failed for %s", name, exc_info=True)
  148. try:
  149. from tools import skill_usage
  150. for predicate, label in (
  151. (skill_usage.is_protected_builtin, "protected built-in"),
  152. (skill_usage.is_hub_installed, "hub-installed"),
  153. (skill_usage.is_bundled, "bundled")):
  154. if predicate(name):
  155. return _refusal(f"{refuse} {label} skill '{name}'.")
  156. # Not curator-managed (no `created_by: "agent"`) => user-owned, never archived
  157. # autonomously. A MISSING record and `created_by: null` must resolve identically:
  158. # keying on presence let the guard's own bookkeeping flip the verdict (#67140).
  159. usage_rec = skill_usage.load_usage().get(name)
  160. if not skill_usage._is_curator_managed_record(usage_rec):
  161. _detail = (f"created_by={usage_rec.get('created_by')!r}" if isinstance(usage_rec, dict)
  162. else "no usage record")
  163. return _refusal(
  164. f"{refuse} skill '{name}': the skill is not "
  165. f"curator-managed ({_detail}). Only curator-managed skills may be archived "
  166. f"autonomously. Run `hermes curator adopt {name}` to opt it in.")
  167. except Exception:
  168. logger.warning("owned skill guard lookup failed for %s", name, exc_info=True)
  169. return _refusal(
  170. f"{refuse} skill '{name}': agent ownership could not "
  171. f"be verified because the provenance record is unavailable or unreadable.")
  172. return None
  173. def _background_review_read_before_write_guard(
  174. name: str, target: Path, action: str, file_label: str) -> Optional[dict[str, Any]]:
  175. """Require review forks to load the exact target before mutating it."""
  176. if not _is_background_review() or _background_review_has_read(target):
  177. return None
  178. return _refusal(
  179. f"Refusing background curator {action} for skill '{name}': the current {file_label} "
  180. f"content has not been loaded in this review turn. Call skill_view(name) for SKILL.md, or "
  181. f"skill_view(name, file_path=...) for a supporting file, then retry the write using the "
  182. f"content just returned.",
  183. _read_before_write_required=True)
  184. def _locked_guard(name: str, action: str) -> Optional[dict[str, Any]]:
  185. """Refuse every mutating ``skill_manage`` action on a skill the user locked (``hermes curator
  186. lock`` / the Desktop lock switch), whoever asks: foreground turns, the background review and the
  187. curator pass alike. ``create`` is exempt (the collision check already refuses a name that resolves
  188. anywhere). An unreadable sidecar fails CLOSED for the autonomous passes (silently relaxing a
  189. lock is the failure this exists to prevent) and open for normal turns, so one corrupt file does
  190. not freeze every skill edit. Keyed by directory name, so the bare, ``cat/name`` and
  191. frontmatter-name forms all resolve to the same record."""
  192. if action == "create" or not name:
  193. return None
  194. try:
  195. from tools import skill_manager_tool as _smt
  196. from tools import skill_usage
  197. candidates = {name, Path(name).name}
  198. if existing := _smt._find_skill(name):
  199. candidates.add(existing["path"].name)
  200. locked = next((c for c in candidates if skill_usage.is_locked(c)), None)
  201. except Exception:
  202. logger.warning("locked skill guard lookup failed for %s", name, exc_info=True)
  203. if not _is_background_review():
  204. return None # a corrupt sidecar must not freeze every skill edit in normal turns
  205. return _refusal(
  206. f"Refusing {action} for skill '{name}': its lock state could not be verified because the "
  207. f"skills/.usage.json sidecar is unreadable. Leave the skill alone and tell the user; they "
  208. f"can repair the sidecar or run `hermes curator unlock {name}`.", _locked=True)
  209. if locked:
  210. from tools.skill_lock import skill_refusal
  211. return _refusal(f"Refusing {action}: {skill_refusal(locked)}", _locked=True)
  212. return None
  213. def _background_review_preflight(action: str, name: str) -> Optional[dict[str, Any]]:
  214. """Guards that run on the bare action/name before any handler, for the single-op AND the
  215. batch path: the content lock (every mutating action) and the ownership delete guard."""
  216. if (locked := _locked_guard(name, action)) is not None:
  217. return locked
  218. if action != "delete":
  219. return None
  220. from tools import skill_manager_tool as _smt
  221. existing = _smt._find_skill(name)
  222. return _background_review_delete_guard(name, existing["path"]) if existing else None
  223. def _curator_consolidation_delete_guard(
  224. name: str, absorbed_into: Optional[str]) -> Optional[dict[str, Any]]:
  225. """Fail closed on unverified deletes during the curator consolidation pass. The fork's only
  226. legitimate delete is a consolidation declared via ``absorbed_into=<umbrella>`` (existence
  227. validated in ``_delete_skill``); the deterministic inactivity prune never calls skill_manage,
  228. so a bare delete here can only be the LLM pass pruning without evidence.
  229. A delete with no forwarding target — ``absorbed_into`` omitted (``None``) or empty (``""``) — is the
  230. fail-open behavior reported in #29912: the consolidation pass archived whole clusters of active skills
  231. with zero verified consolidations (``consolidated_this_run == 0``), leaving active automations pointing
  232. at names that no longer resolve. Refuse it; keep the skill active.
  233. """
  234. if not _is_background_review() or (isinstance(absorbed_into, str) and absorbed_into.strip()):
  235. return None
  236. return _refusal(
  237. f"Refusing background curator delete of skill '{name}': the consolidation pass may only "
  238. f"archive a skill it has absorbed into an umbrella. Pass absorbed_into=<umbrella> (the "
  239. f"umbrella must already exist) to record a verified consolidation. Pruning a skill with no "
  240. f"forwarding target is not permitted here — the deterministic inactivity prune handles "
  241. f"staleness archival separately. Keeping '{name}' active.",
  242. _fail_closed=True)