Skip to content

The agent that grows with you

refactor(tools): skill_manager_tool — unify guarded writes, compact docstrings

Teknium9832b0800dc4
diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py
index 0e64b992c6a..32f2c64c8f0 100644
--- a/tools/skill_manager_tool.py
+++ b/tools/skill_manager_tool.py
@@ -1,13 +1,11 @@
#!/usr/bin/env python3
-"""
-Skill Manager Tool -- Agent-Managed Skill Creation & Editing
-
-Lets the agent create, patch, and delete skills — its procedural memory
-(narrow, actionable "how to do X"), as opposed to MEMORY.md/USER.md (broad,
-declarative). New skills land in ~/.hermes/skills/ (or ``skills.create_dir``);
-existing skills (bundled, hub-installed, user-created) are modified in place.
-Layout: ``<skills>/[category/]<skill>/SKILL.md`` plus optional
-``references/ templates/ scripts/ assets/`` subdirs.
+"""Skill Manager Tool — agent-managed skill creation & editing.
+
+Skills are the agent's procedural memory (narrow "how to do X"), as opposed to
+MEMORY.md/USER.md (broad, declarative). New skills land in ~/.hermes/skills/
+(or ``skills.create_dir``); existing skills (bundled, hub, user) are modified in
+place. Layout: ``<skills>/[category/]<skill>/SKILL.md`` + optional
+``references/ templates/ scripts/ assets/``.
"""
import contextvars as _ctxvars
@@ -30,33 +28,23 @@ from agent.skill_utils import (
parse_frontmatter as _parse_frontmatter,
SKILL_PROMPT_DESC_LIMIT)
from tools.skill_manager_guards import ( # noqa: F401 — re-exported for callers/tests
- _BackgroundReviewReadMarks,
- _background_review_has_read,
- _background_review_preflight,
- _background_review_read_before_write_guard,
- _background_review_read_paths,
- _background_review_write_guard,
- _containing_skills_root,
- _curator_consolidation_delete_guard,
- _is_path_redirect,
- _maybe_auto_propose_org_edit,
- _org_mirror_write_guard,
- _pinned_guard,
- _reset_background_review_read_marks,
- _validate_delete_target,
- _is_background_review,
- mark_background_review_skill_read)
-from tools.skill_manager_batch import ( # noqa: F401
- _BATCH_MAX_OPS, _BATCH_OP_ACTIONS, _skill_manage_batch,
+ _BackgroundReviewReadMarks, _background_review_has_read, _background_review_preflight,
+ _background_review_read_before_write_guard, _background_review_read_paths,
+ _background_review_write_guard, _containing_skills_root, _curator_consolidation_delete_guard,
+ _is_path_redirect, _maybe_auto_propose_org_edit, _org_mirror_write_guard, _pinned_guard,
+ _reset_background_review_read_marks, _validate_delete_target, _is_background_review,
+ mark_background_review_skill_read,
)
+from tools.skill_manager_batch import ( # noqa: F401
+ _BATCH_MAX_OPS, _BATCH_OP_ACTIONS, _skill_manage_batch)
from tools.skills_guard import scan_skill, should_allow_install, format_scan_report
logger = logging.getLogger(__name__)
def _guard_agent_created_enabled() -> bool:
- """skills.guard_agent_created (default False): the agent can already run
- the same code via terminal() ungated, so the scan is opt-in belt-and-suspenders."""
+ """skills.guard_agent_created (default False): the agent can already run the same
+ code via terminal() ungated, so the scan is opt-in belt-and-suspenders."""
try:
from hermes_cli.config import load_config
return is_truthy_value(
@@ -66,12 +54,9 @@ def _guard_agent_created_enabled() -> bool:
def _security_scan_skill(skill_dir: Path) -> Optional[str]:
- """Scan a skill directory after write. Returns error string if blocked, else None.
-
- No-op when skills.guard_agent_created is disabled (the default). An "ask"
- verdict means dangerous findings for an agent-created skill — surfaced as
- an error so the agent can retry with the flagged content removed.
- """
+ """Post-write scan; error string if blocked, else None. No-op unless
+ skills.guard_agent_created. An "ask" verdict (dangerous findings) is surfaced
+ as an error so the agent can retry with the flagged content removed."""
if not _guard_agent_created_enabled():
return None
try:
@@ -93,16 +78,11 @@ _SKILLS_DIR_AT_IMPORT = SKILLS_DIR
def _skills_dir() -> Path:
- """Active profile's skills directory at call time.
-
- Long-lived multi-profile runtimes import this module once and later bind a
- different profile per session. Honor an explicitly patched module-level
- ``SKILLS_DIR`` (tests), otherwise resolve from the live HERMES_HOME.
- """
+ """Active profile's skills dir at call time: multi-profile runtimes import once
+ and bind a different profile per session. An explicitly patched module-level
+ ``SKILLS_DIR`` (tests) wins, otherwise resolve from the live HERMES_HOME."""
configured = Path(SKILLS_DIR)
- if configured != _SKILLS_DIR_AT_IMPORT:
- return configured
- return get_hermes_home() / "skills"
+ return configured if configured != _SKILLS_DIR_AT_IMPORT else get_hermes_home() / "skills"
MAX_NAME_LENGTH = 64
@@ -115,8 +95,7 @@ _FRONTMATTER_END_RE = re.compile(r'\n---\s*\n')
def _display_create_dir() -> str:
- """Display string for the skill-creation directory (schema/instruction text);
- follows ``skills.create_dir`` when configured."""
+ """Skill-creation dir for schema/instruction text; follows ``skills.create_dir``."""
try:
from agent.skill_utils import display_skill_create_dir
return display_skill_create_dir()
@@ -131,7 +110,6 @@ def _err(message: str) -> Dict[str, Any]:
# --- Validation helpers -------------------------------------------------------
def _validate_name(name: str) -> Optional[str]:
- """Validate a skill name. Returns error message or None if valid."""
if not name:
return "Skill name is required."
if len(name) > MAX_NAME_LENGTH:
@@ -143,7 +121,6 @@ def _validate_name(name: str) -> Optional[str]:
def _validate_category(category: Optional[str]) -> Optional[str]:
- """Validate an optional category name used as a single directory segment."""
if category is None:
return None
if not isinstance(category, str):
@@ -161,12 +138,11 @@ def _validate_category(category: Optional[str]) -> Optional[str]:
def _validate_frontmatter(content: str, *, new_skill: bool = False) -> Optional[str]:
- """Validate SKILL.md frontmatter (name + description) and a non-empty body.
+ """Validate frontmatter (name + description) and a non-empty body.
- ``new_skill`` (create path only) also enforces the SKILL_PROMPT_DESC_LIMIT
- budget so new skills never lose routing signal to index truncation; edit
- and patch skip it so existing over-limit skills remain maintainable.
- """
+ ``new_skill`` (create only) also enforces SKILL_PROMPT_DESC_LIMIT so new skills
+ never lose routing signal to index truncation; edit/patch skip it so existing
+ over-limit skills remain maintainable."""
if not content.strip():
return "Content cannot be empty."
content = content.lstrip("\ufeff") # tolerate a Windows UTF-8 BOM
@@ -191,28 +167,26 @@ def _validate_frontmatter(content: str, *, new_skill: bool = False) -> Optional[
if new_skill and len(desc.strip().strip("'\"")) > SKILL_PROMPT_DESC_LIMIT:
return (
f"Description is {len(desc.strip())} chars — new skills must fit the "
- f"{SKILL_PROMPT_DESC_LIMIT}-char system-prompt budget (one sentence, "
- f"trigger first, ends with a period). The skill index truncates "
- f"longer descriptions to {SKILL_PROMPT_DESC_LIMIT - 3} chars + '...', "
- f"destroying the routing signal. Move detail into the skill body.")
+ f"{SKILL_PROMPT_DESC_LIMIT}-char system-prompt budget (one sentence, trigger first, "
+ f"ends with a period). The skill index truncates longer descriptions to "
+ f"{SKILL_PROMPT_DESC_LIMIT - 3} chars + '...', destroying the routing signal. "
+ f"Move detail into the skill body.")
if not content[end_match.end() + 3:].strip():
return "SKILL.md must have content after the frontmatter (instructions, procedures, etc.)."
return None
def _validate_content_size(content: str, label: str = "SKILL.md") -> Optional[str]:
- """Error message when content exceeds the agent-write character limit, else None."""
if len(content) > MAX_SKILL_CONTENT_CHARS:
return (
- f"{label} content is {len(content):,} characters "
- f"(limit: {MAX_SKILL_CONTENT_CHARS:,}). "
- f"Consider splitting into a smaller SKILL.md with supporting files "
- f"in references/ or templates/.")
+ f"{label} content is {len(content):,} characters (limit: {MAX_SKILL_CONTENT_CHARS:,}). "
+ f"Consider splitting into a smaller SKILL.md with supporting files in references/ "
+ f"or templates/.")
return None
def _description_preview(content: str) -> str:
- """First 120 chars of the frontmatter description (verbose notifications); '' on any failure."""
+ """First 120 chars of the frontmatter description; '' on any failure."""
try:
fm_end = _FRONTMATTER_END_RE.search(content[3:])
if fm_end:
@@ -224,8 +198,7 @@ def _description_preview(content: str) -> str:
def _resolve_skill_dir(name: str, category: str = None) -> Path:
- """Directory for a new skill; honors ``skills.create_dir`` (e.g. a shared
- fleet directory) and falls back to the profile-local skills dir."""
+ """New-skill dir; honors ``skills.create_dir`` (e.g. a shared fleet dir)."""
base = _skills_dir()
try:
from agent.skill_utils import get_skill_create_dir
@@ -238,26 +211,23 @@ def _resolve_skill_dir(name: str, category: str = None) -> Path:
def _iter_skill_dirs(root: Path):
- """Yield every non-excluded skill directory (parent of a SKILL.md) under ``root``."""
from agent.skill_utils import is_excluded_skill_path
-
for skill_md in root.rglob("SKILL.md"):
if not is_excluded_skill_path(skill_md):
yield skill_md.parent
def _find_skill(name: str) -> Optional[Dict[str, Any]]:
- """Find a skill by name across the local skills dir then skills.external_dirs.
+ """Find a skill across the local skills dir then skills.external_dirs.
- Accepts the bare directory name (``axolotl``) and the categorized relative
- path (``mlops/axolotl``) — the two forms skill_view resolves. Bare lookups
- compare the skill's own dir name so category-nested skills still match.
- Returns ``{"path": Path}`` or None.
- """
+ Accepts the bare dir name (``axolotl``) and the categorized relative path
+ (``mlops/axolotl``) — the two forms skill_view resolves. Bare lookups compare
+ the skill's own dir name so category-nested skills still match.
+ Returns ``{"path": Path}`` or None."""
from agent.skill_utils import get_all_skills_dirs
- # The categorized form matches the skill dir RELATIVE to the local root
- # (never external dirs — relative_to raises there).
+ # The categorized form matches RELATIVE to the local root only (relative_to
+ # raises for external dirs).
local_root = None
if "/" in name or "\\" in name:
try:
@@ -285,8 +255,8 @@ def _find_skill(name: str) -> Optional[Dict[str, Any]]:
def _find_skill_in_other_profiles(name: str) -> List[Tuple[str, Path]]:
- """``(profile_name, skill_dir)`` pairs for OTHER profiles holding ``name``;
- lets the "not found" error explain a wrong-profile mistake. Fail-quiet."""
+ """``(profile, skill_dir)`` pairs for OTHER profiles holding ``name`` (so the
+ not-found error can explain a wrong-profile mistake). Fail-quiet."""
matches: List[Tuple[str, Path]] = []
try:
from hermes_constants import get_default_hermes_root
@@ -320,8 +290,7 @@ def _find_skill_in_other_profiles(name: str) -> List[Tuple[str, Path]]:
def _skill_not_found_error(name: str, suffix: str = "") -> str:
- """"Skill not found" error naming other profiles that hold the skill;
- ``suffix`` is appended after the hint."""
+ """Not-found error naming other profiles that hold the skill, plus ``suffix``."""
from agent.file_safety import _resolve_active_profile_name
active = _resolve_active_profile_name()
base = f"Skill '{name}' not found in active profile '{active}'."
@@ -330,16 +299,15 @@ def _skill_not_found_error(name: str, suffix: str = "") -> str:
if len(others) == 1:
other_profile, other_path = others[0]
base += (
- f" A skill by that name exists in profile "
- f"'{other_profile}' ({other_path}). To edit it, switch "
- f"profiles (`hermes -p {other_profile}`) or edit the file "
- f"directly (file tools / terminal).")
+ f" A skill by that name exists in profile '{other_profile}' ({other_path}). To edit "
+ f"it, switch profiles (`hermes -p {other_profile}`) or edit the file directly "
+ f"(file tools / terminal).")
elif others:
names = ", ".join(f"'{p}'" for p, _ in others)
base += (
- f" Skills by that name exist in other profiles: {names}. "
- f"Switch profiles (`hermes -p <name>`) to edit there, or "
- f"edit the files directly (file tools / terminal).")
+ f" Skills by that name exist in other profiles: {names}. Switch profiles "
+ f"(`hermes -p <name>`) to edit there, or edit the files directly "
+ f"(file tools / terminal).")
else:
base += " Use skills_list() to see available skills."
return base + suffix
@@ -352,8 +320,7 @@ def _validate_file_path(file_path: str) -> Optional[str]:
if not file_path:
return "file_path is required."
normalized = Path(file_path)
- # Traversal is checked before any allow-listing so the SKILL.md exception
- # can never be reached by a traversal-laden path.
+ # Traversal first, so the SKILL.md exception is unreachable by a traversal-laden path.
if has_traversal_component(file_path):
return "Path traversal ('..') is not allowed."
# SKILL.md lives at the skill root; accept 'SKILL.md' and '<skill>/SKILL.md'.
@@ -368,8 +335,8 @@ def _validate_file_path(file_path: str) -> Optional[str]:
def _resolve_supporting_file(skill_dir: Path, file_path: str):
- """Validate ``file_path`` and resolve it inside ``skill_dir``.
- Returns (target, None) or (None, error_dict)."""
+ """Validate ``file_path`` and resolve it inside ``skill_dir``
+ -> ``(target, None)`` | ``(None, error_dict)``."""
from tools.path_security import validate_within_dir
err = _validate_file_path(file_path)
@@ -383,8 +350,8 @@ def _resolve_supporting_file(skill_dir: Path, file_path: str):
def _locate_for_write(name: str, action: str, not_found_suffix: str = ""):
- """Find the skill and run the org-mirror + background-review write guards.
- Returns ``(skill_dir, None)`` or ``(None, error_dict)``."""
+ """Find the skill and run the org-mirror + background-review write guards
+ -> ``(skill_dir, None)`` | ``(None, error_dict)``."""
existing = _find_skill(name)
if not existing:
return None, _err(_skill_not_found_error(name, not_found_suffix))
@@ -396,18 +363,27 @@ def _locate_for_write(name: str, action: str, not_found_suffix: str = ""):
return skill_dir, None
-def _write_scanned(target: Path, content: str, skill_dir: Path,
- original: Optional[str]) -> Optional[str]:
- """Atomically write ``content``, then security-scan the skill; on block,
- restore ``original`` (or unlink a newly created file) and return the error."""
+def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label: str,
+ content: str) -> Optional[Dict[str, Any]]:
+ """Read-before-write guard (existing targets only), atomic write, then the
+ security scan; a blocked scan restores the original (or unlinks a new file).
+ Returns an error dict or None."""
+ original = None
+ if target.exists():
+ read_guard = _background_review_read_before_write_guard(name, target, action, label)
+ if read_guard:
+ return read_guard
+ original = target.read_text(encoding="utf-8")
+ target.parent.mkdir(parents=True, exist_ok=True)
atomic_write_text(target, content, preserve_mode=True, create_mode=0o644)
scan_error = _security_scan_skill(skill_dir)
- if scan_error:
- if original is not None:
- atomic_write_text(target, original, preserve_mode=True)
- else:
- target.unlink(missing_ok=True)
- return scan_error
+ if not scan_error:
+ return None
+ if original is not None:
+ atomic_write_text(target, original, preserve_mode=True)
+ else:
+ target.unlink(missing_ok=True)
+ return _err(scan_error)
def _attach_org_note(result: Dict[str, Any], name: str, skill_dir: Path) -> None:
@@ -418,18 +394,15 @@ def _attach_org_note(result: Dict[str, Any], name: str, skill_dir: Path) -> None
def _add_description_prompt_preview(result: Dict[str, Any], content: str) -> None:
- """Append a system_prompt_preview field when the description will be truncated."""
fm, _ = _parse_frontmatter(content)
if is_skill_description_truncated_for_prompt(fm):
result["system_prompt_preview"] = (
- f"System prompt will show: \"{extract_skill_description(fm)}\" — "
- f"keep the trigger self-contained in the first "
- f"{SKILL_PROMPT_DESC_LIMIT - 3} chars.")
+ f"System prompt will show: \"{extract_skill_description(fm)}\" — keep the trigger "
+ f"self-contained in the first {SKILL_PROMPT_DESC_LIMIT - 3} chars.")
def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None:
- """Attach ADVISORY skill-authoring-convention findings (never a hard block;
- hard rejects already ran in _validate_frontmatter)."""
+ """Attach ADVISORY authoring findings (hard rejects already ran in _validate_frontmatter)."""
try:
from tools.skill_linter import lint_skill # local import: optional path
findings = lint_skill(skill_md)
@@ -440,20 +413,15 @@ def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None:
result["lint_warnings"] = [
{"severity": f.severity, "rule": f.rule, "message": f.message} for f in findings]
result["lint_hint"] = (
- "The skill was created. These are advisory authoring-convention "
- "findings (not blockers) — fix them with skill_manage(action='patch') "
- "to match Hermes skill standards.")
+ "The skill was created. These are advisory authoring-convention findings (not blockers) "
+ "— fix them with skill_manage(action='patch') to match Hermes skill standards.")
# --- Core actions -------------------------------------------------------------
def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Any]:
- """Create a new user skill with SKILL.md content."""
- err = (
- _validate_name(name)
- or _validate_category(category)
- or _validate_frontmatter(content, new_skill=True)
- or _validate_content_size(content))
+ err = (_validate_name(name) or _validate_category(category)
+ or _validate_frontmatter(content, new_skill=True) or _validate_content_size(content))
if err:
return _err(err)
existing = _find_skill(name)
@@ -474,11 +442,9 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, An
except ValueError:
_display_path = str(skill_dir) # created under skills.create_dir
result = {
- "success": True,
- "message": f"Skill '{name}' created.",
- "path": _display_path,
- "skill_md": str(skill_md),
- "_change": {"description": _description_preview(content)}}
+ "success": True, "message": f"Skill '{name}' created.", "path": _display_path,
+ "skill_md": str(skill_md), "_change": {"description": _description_preview(content)},
+ }
if category:
result["category"] = category
result["hint"] = (
@@ -498,22 +464,14 @@ def _edit_skill(name: str, content: str) -> Dict[str, Any]:
skill_dir, guard = _locate_for_write(name, "edit")
if guard:
return guard
- skill_md = skill_dir / "SKILL.md"
- read_guard = _background_review_read_before_write_guard(name, skill_md, "edit", "SKILL.md")
- if read_guard:
- return read_guard
-
# SKILL.md always exists here (_find_skill requires it), so a blocked scan restores it.
- original_content = skill_md.read_text(encoding="utf-8") if skill_md.exists() else None
- scan_error = _write_scanned(skill_md, content, skill_dir, original_content)
- if scan_error:
- return _err(scan_error)
-
+ guard = _guarded_write(name, skill_dir, skill_dir / "SKILL.md", "edit", "SKILL.md", content)
+ if guard:
+ return guard
result = {
- "success": True,
- "message": f"Skill '{name}' updated (full rewrite).",
- "path": str(skill_dir),
- "_change": {"description": _description_preview(content)}}
+ "success": True, "message": f"Skill '{name}' updated (full rewrite).",
+ "path": str(skill_dir), "_change": {"description": _description_preview(content)},
+ }
_attach_org_note(result, name, skill_dir)
_add_description_prompt_preview(result, content)
return result
@@ -521,17 +479,17 @@ def _edit_skill(name: str, content: str) -> Dict[str, Any]:
def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = None,
replace_all: bool = False) -> Dict[str, Any]:
- """Targeted find-and-replace within SKILL.md (default) or a supporting file.
- Requires a unique match unless replace_all is True."""
+ """Targeted find-and-replace within SKILL.md (default) or a supporting file;
+ requires a unique match unless replace_all."""
if not old_string:
# A bare "required" error is a dead end: the model retries blindly and
# often escapes to action='write_file', clobbering the whole file.
return _err(
"old_string is required for 'patch' and must be the EXACT text currently in the "
"file. Read the target file first (read_file on the skill's SKILL.md, or the file "
- "named by file_path) and copy the snippet verbatim, then retry 'patch'. "
- "Do NOT fall back to action='write_file' — that rewrites the entire file and "
- "destroys unrelated content.")
+ "named by file_path) and copy the snippet verbatim, then retry 'patch'. Do NOT fall "
+ "back to action='write_file' — that rewrites the entire file and destroys unrelated "
+ "content.")
if new_string is None:
return _err("new_string is required for 'patch'. Use an empty string to delete matched text.")
# No old_string == new_string guard here: fuzzy_find_and_replace rejects
@@ -549,7 +507,6 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = N
target = skill_dir / "SKILL.md"
if not target.exists():
return _err(f"File not found: {target.relative_to(skill_dir)}")
-
target_label = file_path or "SKILL.md"
read_guard = _background_review_read_before_write_guard(name, target, "patch", target_label)
if read_guard:
@@ -559,7 +516,6 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = N
# Same fuzzy engine as the file patch tool (whitespace/indent/escape
# normalization, block anchors) so minor formatting mismatches don't fail.
from tools.fuzzy_match import fuzzy_find_and_replace
-
new_content, match_count, _strategy, match_error = fuzzy_find_and_replace(
content, old_string, new_string, replace_all)
if match_error:
@@ -578,28 +534,23 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = N
if err:
return _err(f"Patch would break SKILL.md structure: {err}")
- scan_error = _write_scanned(target, new_content, skill_dir, content)
- if scan_error:
- return _err(scan_error)
-
+ guard = _guarded_write(name, skill_dir, target, "patch", target_label, new_content)
+ if guard:
+ return guard
result = {
"success": True,
"message": f"Patched {target_label} in skill '{name}' ({match_count} replacement{'s' if match_count > 1 else ''}).",
- "_change": {
- "old": old_string[:200] + ("…" if len(old_string) > 200 else ""),
- "new": new_string[:200] + ("…" if len(new_string) > 200 else "")}}
+ "_change": {"old": old_string[:200] + ("…" if len(old_string) > 200 else ""),
+ "new": new_string[:200] + ("…" if len(new_string) > 200 else "")},
+ }
_attach_org_note(result, name, skill_dir)
return result
def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Any]:
- """Delete a skill.
-
- ``absorbed_into``: ``None`` = undeclared (legacy path, accepted);
- ``""`` = explicit prune with no forwarding target; ``"<skill>"`` = content
- absorbed into that umbrella, which must exist on disk (validated here so
- the model can't claim a nonexistent umbrella).
- """
+ """Delete a skill. ``absorbed_into``: None = undeclared (legacy, accepted); "" =
+ explicit prune; "<skill>" = absorbed into that umbrella, which must exist on
+ disk (validated here so the model can't claim a nonexistent umbrella)."""
skill_dir, guard = _locate_for_write(name, "delete")
if guard:
return guard
@@ -616,18 +567,16 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, A
if absorbed_target == name:
return _err(f"absorbed_into='{absorbed_target}' cannot equal the skill being deleted.")
if not _find_skill(absorbed_target):
- return _err(
- f"absorbed_into='{absorbed_target}' does not exist. "
- f"Create or patch the umbrella skill first, then retry the delete.")
+ return _err(f"absorbed_into='{absorbed_target}' does not exist. "
+ f"Create or patch the umbrella skill first, then retry the delete.")
skills_root = _containing_skills_root(skill_dir)
unsafe = _validate_delete_target(skill_dir) # defense-in-depth before rmtree
if unsafe:
return _err(unsafe)
- # During the curator consolidation pass a verified consolidation must be
- # RECOVERABLE (`hermes curator restore`), so route through the archive
- # primitive instead of rmtree. Foreground deletes keep hard-delete semantics.
+ # Curator consolidations must be RECOVERABLE (`hermes curator restore`): archive
+ # instead of rmtree. Foreground deletes keep hard-delete semantics.
absorbed_note = f" Content absorbed into '{absorbed_target}'." if is_consolidation else ""
if _is_background_review():
try:
@@ -637,10 +586,9 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, A
return _err(f"failed to archive '{name}': {e}")
if not ok:
return _err(archive_msg)
- return {
- "success": True,
- "message": f"Skill '{name}' archived ({archive_msg}).{absorbed_note}",
- "_archived": True}
+ return {"success": True,
+ "message": f"Skill '{name}' archived ({archive_msg}).{absorbed_note}",
+ "_archived": True}
shutil.rmtree(skill_dir)
_rmdir_if_empty(skill_dir.parent, skills_root) # empty category dir, never the root
@@ -661,10 +609,8 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:
return _err("file_content is required.")
content_bytes = len(file_content.encode("utf-8"))
if content_bytes > MAX_SKILL_FILE_BYTES:
- return _err(
- f"File content is {content_bytes:,} bytes "
- f"(limit: {MAX_SKILL_FILE_BYTES:,} bytes / 1 MiB). "
- f"Consider splitting into smaller files.")
+ return _err(f"File content is {content_bytes:,} bytes (limit: {MAX_SKILL_FILE_BYTES:,} "
+ f"bytes / 1 MiB). Consider splitting into smaller files.")
err = _validate_content_size(file_content, label=file_path)
if err:
return _err(err)
@@ -675,20 +621,11 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:
target, err = _resolve_supporting_file(skill_dir, file_path)
if err:
return err
- if target.exists():
- read_guard = _background_review_read_before_write_guard(name, target, "write_file", file_path)
- if read_guard:
- return read_guard
- target.parent.mkdir(parents=True, exist_ok=True)
- original_content = target.read_text(encoding="utf-8") if target.exists() else None
- scan_error = _write_scanned(target, file_content, skill_dir, original_content)
- if scan_error:
- return _err(scan_error)
-
- result = {
- "success": True,
- "message": f"File '{file_path}' written to skill '{name}'.",
- "path": str(target)}
+ guard = _guarded_write(name, skill_dir, target, "write_file", file_path, file_content)
+ if guard:
+ return guard
+ result = {"success": True, "message": f"File '{file_path}' written to skill '{name}'.",
+ "path": str(target)}
_attach_org_note(result, name, skill_dir)
return result
@@ -711,15 +648,11 @@ def _remove_file(name: str, file_path: str) -> Dict[str, Any]:
return err
if not target.exists():
available = [
- str(f.relative_to(skill_dir))
- for subdir in ALLOWED_SUBDIRS
+ str(f.relative_to(skill_dir)) for subdir in ALLOWED_SUBDIRS
if (skill_dir / subdir).exists()
- for f in (skill_dir / subdir).rglob("*")
- if f.is_file()]
- return {
- "success": False,
- "error": f"File '{file_path}' not found in skill '{name}'.",
- "available_files": available if available else None}
+ for f in (skill_dir / subdir).rglob("*") if f.is_file()]
+ return {"success": False, "error": f"File '{file_path}' not found in skill '{name}'.",
+ "available_files": available if available else None}
read_guard = _background_review_read_before_write_guard(name, target, "remove_file", file_path)
if read_guard:
return read_guard
@@ -740,10 +673,9 @@ _GATED_ACTIONS = {"create", "edit", "patch", "delete", "write_file", "remove_fil
def _run_write_gate(build_staging):
- """Shared write-gate evaluation. Returns None to proceed, or a JSON tool
- result when blocked/staged. ``build_staging(wa)`` -> (payload, gist) is
- only called when the decision is to stage. Fails open if write_approval
- cannot be imported."""
+ """Shared write gate: None to proceed, else a JSON tool result (blocked/staged).
+ ``build_staging(wa) -> (payload, gist)`` runs only when staging. Fails open
+ if write_approval cannot be imported."""
try:
from tools import write_approval as wa
except Exception:
@@ -755,15 +687,13 @@ def _run_write_gate(build_staging):
return tool_error(decision.message, success=False)
payload, gist = build_staging(wa)
record = wa.stage_write(wa.SKILLS, payload, summary=gist, origin=wa.current_origin())
- return json.dumps(
- {"success": True, "staged": True, "pending_id": record["id"],
- "gist": gist, "message": decision.message},
- ensure_ascii=False)
+ return json.dumps({"success": True, "staged": True, "pending_id": record["id"],
+ "gist": gist, "message": decision.message}, ensure_ascii=False)
def _apply_skill_write_gate(action, name, **payload_kwargs):
- """Flat-shape write gate: stage the full skill_manage kwargs so approval can
- replay them. Bypassed during approved-pending replay."""
+ """Flat-shape gate: stage the full kwargs so approval can replay them;
+ bypassed during approved-pending replay."""
if action not in _GATED_ACTIONS or _skill_gate_bypass.get():
return None
@@ -771,8 +701,7 @@ def _apply_skill_write_gate(action, name, **payload_kwargs):
payload = {"action": action, "name": name}
payload.update({k: v for k, v in payload_kwargs.items() if v is not None})
gist = wa.skill_gist(
- action, name,
- content=payload_kwargs.get("content") or "",
+ action, name, content=payload_kwargs.get("content") or "",
file_path=payload_kwargs.get("file_path") or "",
old_string=payload_kwargs.get("old_string") or "",
new_string=payload_kwargs.get("new_string") or "")
@@ -787,16 +716,13 @@ _FLAT_OP_KEYS = ("content", "category", "file_path", "file_content", "old_string
def _skill_manage_from(payload: Dict[str, Any], **extra) -> str:
"""Call ``skill_manage`` with the flat-shape fields taken from ``payload``."""
return skill_manage(
- action=payload.get("action", ""),
- name=payload.get("name", ""),
+ action=payload.get("action", ""), name=payload.get("name", ""),
replace_all=payload.get("replace_all", False),
- **{k: payload.get(k) for k in _FLAT_OP_KEYS},
- **extra)
+ **{k: payload.get(k) for k in _FLAT_OP_KEYS}, **extra)
def apply_skill_pending(payload: Dict[str, Any]) -> str:
- """Replay a staged skill write, bypassing the gate. Returns the tool result
- JSON string. Called by the /skills approve handler."""
+ """Replay a staged skill write, bypassing the gate (the /skills approve handler)."""
token = _skill_gate_bypass.set(True)
try:
return _skill_manage_from(
@@ -814,12 +740,9 @@ _SYNC_PUSH_DEBOUNCE_S = 5.0
def _maybe_debounced_sync_push(skill_name: str) -> None:
- """Schedule a debounced best-effort sync push after a skill write.
-
- Fast-path: skills not opted into sync do nothing (no auth, no network).
- The push runs via ``skills_sync_client.maybe_push_skills`` which enforces
- the access gate and swallows errors. Never blocks the caller.
- """
+ """Debounced best-effort sync push after a skill write; never blocks the caller.
+ Skills not opted into sync do nothing (no auth, no network); the push itself
+ (``skills_sync_client.maybe_push_skills``) enforces the access gate."""
global _sync_push_timer, _sync_push_lock
try:
from tools.skill_usage import is_sync_enabled
@@ -863,10 +786,8 @@ def _act_patch(a):
# Two shapes: old_string/new_string = targeted replacement;
# content (alone) = full SKILL.md rewrite (absorbs the old 'edit').
if a["content"] and (a["old_string"] or a["new_string"] is not None):
- return tool_error(
- "Pass EITHER content (full SKILL.md rewrite) OR "
- "old_string/new_string (targeted replacement), not both.",
- success=False)
+ return tool_error("Pass EITHER content (full SKILL.md rewrite) OR "
+ "old_string/new_string (targeted replacement), not both.", success=False)
if a["content"]:
return _edit_skill(a["name"], a["content"])
# Targeted-replacement validation lives in _patch_skill so the public
@@ -901,8 +822,8 @@ _ACTION_HANDLERS = {
def _record_success(action, name, result, *, file_path, absorbed_into, task_id,
session_id, ledger_before) -> None:
- """Post-mutation side effects, all best-effort (never break the tool):
- audit ledger, prompt-cache clear, curator telemetry, debounced sync push."""
+ """Best-effort post-mutation side effects (never break the tool): audit ledger,
+ prompt-cache clear, curator telemetry, debounced sync push."""
try:
from tools import skill_ledger as _ledger
_post = _find_skill(name)
@@ -916,10 +837,8 @@ def _record_success(action, name, result, *, file_path, absorbed_into, task_id,
if file_path:
_evidence["file_path"] = file_path
_ledger.record_mutation(
- action, name,
- before=ledger_before if ledger_before is not None else [],
- after_root=_post["path"] if _post else None,
- evidence=_evidence)
+ action, name, before=ledger_before if ledger_before is not None else [],
+ after_root=_post["path"] if _post else None, evidence=_evidence)
except Exception:
pass
try:
@@ -927,10 +846,9 @@ def _record_success(action, name, result, *, file_path, absorbed_into, task_id,
clear_skills_system_prompt_cache(clear_snapshot=True)
except Exception:
pass
- # Curator telemetry: only the background review fork marks a skill as
- # agent-created — foreground creates are user-directed and belong to the
- # user. A recoverable curator archive keeps its record as STATE_ARCHIVED
- # (so `hermes curator status`/`restore` see it); only a hard delete forgets.
+ # Curator telemetry: only the background review fork marks a skill agent-created
+ # (foreground creates belong to the user). A recoverable curator archive keeps its
+ # record as STATE_ARCHIVED (`hermes curator status`/`restore`); only a hard delete forgets.
try:
from tools.skill_usage import bump_patch, forget, record_created
from tools.skill_provenance import is_background_review
@@ -943,9 +861,8 @@ def _record_success(action, name, result, *, file_path, absorbed_into, task_id,
forget(name)
except Exception:
pass
- # Sync push only runs AFTER the write gate passed (staged writes returned
- # early), so un-reviewed content is never pushed. Inert unless the access
- # gate is open, a sync URL is configured, and the skill is opted in.
+ # Runs only AFTER the write gate passed (staged writes returned early), so
+ # un-reviewed content is never pushed.
try:
_maybe_debounced_sync_push(name)
except Exception:
@@ -957,12 +874,8 @@ def skill_manage(
file_content: str = None, old_string: str = None, new_string: str = None,
replace_all: bool = False, absorbed_into: str = None, task_id: str = None,
session_id: str = None, operations=None) -> str:
- """Manage user-created skills; dispatches to the action handler.
-
- ``operations``: batch shape — a list of {action, ...} dicts applied
- atomically (see _skill_manage_batch). When set, the flat single-op fields
- are ignored and ``action`` may be omitted/'batch'. Returns a JSON string.
- """
+ """Dispatch to the action handler; returns a JSON string. ``operations`` (batch
+ shape, applied atomically by _skill_manage_batch) overrides the flat fields."""
if operations is not None:
return _skill_manage_batch(
operations, default_name=name or None, task_id=task_id, session_id=session_id)
@@ -970,9 +883,8 @@ def skill_manage(
if preflight is not None:
return json.dumps(preflight, ensure_ascii=False)
- # Approval gate: when on, stages the write for review (skills are too large
- # to review inline, so they always stage regardless of origin); bypassed
- # when replaying an already-approved staged write.
+ # Approval gate: skills are too large to review inline, so they always stage
+ # regardless of origin; bypassed when replaying an approved staged write.
args = dict(
content=content, category=category, file_path=file_path,
file_content=file_content, old_string=old_string, new_string=new_string,
@@ -981,10 +893,9 @@ def skill_manage(
if gate_result is not None:
return gate_result
- # Audit ledger: capture pre-mutation state. Telemetry, not a gate — failures
- # must NEVER block the mutation. delete destroys the whole package and
- # consolidation may have re-homed support files first, so complete the
- # capture from the newest curator backup or a restore is hollow.
+ # Audit ledger pre-capture: telemetry, not a gate — failures must NEVER block the
+ # mutation. delete destroys the whole package (and consolidation may have re-homed
+ # support files first), so complete it from the newest curator backup or a restore is hollow.
_ledger_before = None
try:
from tools import skill_ledger as _ledger