The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): unify skill_manage guard/ledger boilerplate; compact batch + ledger helpers
Tekniumd9d25c89ba99
diff --git a/tools/skill_ledger.py b/tools/skill_ledger.pyindex 6509db56397..ffe617b7ee8 100644--- a/tools/skill_ledger.py+++ b/tools/skill_ledger.py@@ -3,10 +3,9 @@Every skill mutation (any actor) appends one JSONL entry to``~/.hermes/skills/.curator_ledger.jsonl`` with before/after file manifests whosecontents are stored content-addressed (sha256-deduped) under-``~/.hermes/.curator_backups/blobs/``. JSONL, not the state DB: durable,-human-greppable, survives DB resets. The ledger is TELEMETRY, NOT A GATE: every-public write path swallows and logs. The one exception is ``rollback_entry``,-which FAILS CLOSED when its own pre-rollback safety capture fails.+``~/.hermes/.curator_backups/blobs/``. JSONL, not the state DB: durable, greppable,+survives DB resets. TELEMETRY, NOT A GATE: every public write path swallows and+logs — except ``rollback_entry``, which FAILS CLOSED when its safety capture fails."""from __future__ import annotations@@ -28,14 +27,12 @@ from hermes_constants import get_hermes_homelogger = logging.getLogger(__name__)-# Snapshot-id shape used by agent.curator_backup (duplicated so the ledger can-# read the newest skills.tar.gz without importing the backup stack).+# Snapshot-id shape of agent.curator_backup (duplicated to avoid importing the backup stack)._BACKUP_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z(-\d{2})?$")# ".archive/<name>-YYYYMMDDHHMMSS" collision suffix added by archive_skill._ARCHIVE_TS_SUFFIX_RE = re.compile(r"^(.+)-\d{14}$")-# Actions whose rollback must restore a COMPLETE package: consolidation may-# have re-homed support files out of the tree first, so a disk-only capture-# would make rollback restore a hollow skill.+# Rollback of these must restore a COMPLETE package: consolidation may have re-homed+# support files first, so a disk-only capture would restore a hollow skill._PACKAGE_RESTORE_ACTIONS = frozenset({"delete", "archive", "purge"})_VALID_ACTORS = {"curator", "agent", "user"}_NON_PACKAGE_TOPS = {".curator_backups", ".hub", ".archive"}@@ -96,17 +93,13 @@ def _rel_posix(path: Path | str, root: Path) -> Optional[str]:"""POSIX path of ``path`` relative to ``root`` (both normalized), or None when outside."""try:return _norm(path).relative_to(_norm(root)).as_posix()- except ValueError:+ except (ValueError, TypeError):return Nonedef _is_within(root: Path, path: Path) -> bool:"""True when *path* (normalized, no symlink resolution) sits under *root*."""- try:- root_r, path_r = _norm(root), _norm(path)- return path_r == root_r or root_r in path_r.parents- except Exception:- return False+ return _rel_posix(path, root) is not Nonedef _store_blob(data: bytes) -> str:@@ -150,9 +143,7 @@ def snapshot_paths(root: Optional[Path], *, complete_package: bool = False) -> Lelse:return []out = [{"path": str(f), "sha256": _store_blob(f.read_bytes())} for f in files]- if complete_package:- out = fill_snapshot_from_curator_backup(root, out)- return out+ return fill_snapshot_from_curator_backup(root, out) if complete_package else outdef _package_rel(root: Path) -> Optional[str]:@@ -208,9 +199,7 @@ def _latest_skills_tarball() -> Optional[Path]:def _read_package_files_from_latest_backup(prefixes: List[str]) -> Dict[str, bytes]:"""``{posix-relpath: bytes}`` under *prefixes* in the newest snapshot; maliciousmember names (absolute, ``..`` traversal) are rejected."""- if not prefixes:- return {}- archive = _latest_skills_tarball()+ archive = _latest_skills_tarball() if prefixes else Noneif archive is None:return {}prefixed = tuple(p if p.endswith("/") else p + "/" for p in prefixes)@@ -219,12 +208,10 @@ def _read_package_files_from_latest_backup(prefixes: List[str]) -> Dict[str, byttry:with tarfile.open(archive, "r:gz") as tf:for member in tf.getmembers():- if not member.isfile():- continuename = member.name.replace("\\", "/").lstrip("./")- if not name or name.startswith("/") or ".." in Path(name).parts:- continue- if name not in exact and not name.startswith(prefixed):+ if (not member.isfile() or not name or name.startswith("/")+ or ".." in Path(name).parts+ or (name not in exact and not name.startswith(prefixed))):continueextracted = tf.extractfile(member)if extracted is not None:@@ -293,14 +280,10 @@ def append_entry(return Nonetry:entry = {- "id": uuid.uuid4().hex[:12],- "ts": datetime.now(timezone.utc).isoformat(),+ "id": uuid.uuid4().hex[:12], "ts": datetime.now(timezone.utc).isoformat(),"actor": actor if actor in _VALID_ACTORS else derive_actor(),- "action": action,- "skill": skill,- "evidence": evidence or {},- "before": before or [],- "after": after or []}+ "action": action, "skill": skill, "evidence": evidence or {},+ "before": before or [], "after": after or []}path = ledger_path()path.parent.mkdir(parents=True, exist_ok=True)with open(path, "a", encoding="utf-8") as fh:@@ -327,9 +310,8 @@ def record_mutation(before = snapshot_paths(before_root, complete_package=_complete)elif _complete:before = fill_snapshot_from_curator_backup(before_root, before, skill=skill)- after = snapshot_paths(after_root)- return append_entry(- action, skill, before=before, after=after, actor=actor, evidence=evidence)+ return append_entry(action, skill, before=before, after=snapshot_paths(after_root),+ actor=actor, evidence=evidence)except Exception as e:logger.warning("skill_ledger: record_mutation failed (%s) — mutation unaffected", e)return None@@ -361,20 +343,16 @@ def list_entries(skill: Optional[str] = None, limit: Optional[int] = None) -> Litry:with open(path, "r", encoding="utf-8") as fh:for line in fh:- try:+ with suppress(json.JSONDecodeError):row = json.loads(line) if line.strip() else None- except json.JSONDecodeError:- continue- if isinstance(row, dict):- rows.append(row)+ if isinstance(row, dict):+ rows.append(row)except OSError:return []if skill:rows = [r for r in rows if r.get("skill") == skill]rows.reverse()- if limit is not None and limit >= 0:- rows = rows[:limit]- return rows+ return rows[:limit] if limit is not None and limit >= 0 else rowsdef get_entry(entry_id: str) -> Optional[Dict[str, Any]]:@@ -403,14 +381,11 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:entry = get_entry(entry_id)if entry is None:return False, f"no ledger entry with id '{entry_id}'"-- path_err = _validate_entry_paths(entry)- if path_err:+ if path_err := _validate_entry_paths(entry):return False, f"refusing rollback: {path_err}"before = list(entry.get("before") or [])after = list(entry.get("after") or [])-# Historical hollow delete/archive/purge entries (SKILL.md only): fill from the# newest curator backup so the complete package is restored. Entry hashes win;# only missing paths are added, and the filled set is re-validated.@@ -418,10 +393,8 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:before = fill_snapshot_from_curator_backup(next(iter(_skill_md_parents(before)), None), before,skill=str(entry.get("skill") or "") or None)- path_err = _validate_entry_paths({**entry, "before": before, "after": after})- if path_err:+ if path_err := _validate_entry_paths({**entry, "before": before, "after": after}):return False, f"refusing rollback: {path_err}"-# Pre-check every blob we need so we never fail mid-restore.for item in before:if read_blob(str(item.get("sha256", ""))) is None:@@ -431,11 +404,8 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:# Safety entry: CURRENT state of every touched path, so the rollback itself is undoable.touched = {str(i["path"]) for i in before + after if i.get("path")}try:- safety_before: List[Dict[str, str]] = []- for p in sorted(touched):- fp = Path(p)- if fp.is_file():- safety_before.append({"path": p, "sha256": _store_blob(fp.read_bytes())})+ safety_before = [{"path": p, "sha256": _store_blob(Path(p).read_bytes())}+ for p in sorted(touched) if Path(p).is_file()]safety_id = append_entry("pre-rollback", entry.get("skill", "?"), before=safety_before, after=safety_before,evidence={"rollback_target": entry_id})@@ -456,10 +426,9 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:for item in after:p = str(item.get("path", ""))if p and p not in before_paths:- fp = Path(p)try:- if fp.is_file():- fp.unlink()+ if Path(p).is_file():+ Path(p).unlink()removed += 1except OSError as e:logger.warning("skill_ledger: could not remove %s during rollback: %s", p, e)diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex 5d1e863239c..c0a2f4eb8cb 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -19,24 +19,23 @@ def _validate_batch_ops(operations, default_name, tool_error):"""Shape checks with no side effects. Returns (names, None) or (None, error_json)."""from tools.skill_manager_guards import _background_review_preflight+ def fail(i, msg):+ return None, tool_error(f"operations[{i}]{msg}", success=False)+names = []for i, op in enumerate(operations):if not isinstance(op, dict) or not op.get("action"):- return None, tool_error(f"operations[{i}] needs an 'action'.", success=False)+ return fail(i, " needs an 'action'.")act = op["action"]if act not in _BATCH_OP_ACTIONS:- return None, tool_error(- f"operations[{i}]: unknown action '{act}'. Batchable: "- f"{', '.join(sorted(_BATCH_OP_ACTIONS))}; delete must be sole.",- success=False)+ return fail(i, f": unknown action '{act}'. Batchable: "+ f"{', '.join(sorted(_BATCH_OP_ACTIONS))}; delete must be sole.")nm = op.get("name") or default_nameif not nm:- return None, tool_error(f"operations[{i}] needs a 'name' (the skill it targets).", success=False)+ return fail(i, " needs a 'name' (the skill it targets).")names.append(nm)if act == "create" and nm in names[:-1]:- return None, tool_error(- f"operations[{i}]: create for '{nm}' must precede that skill's other ops.",- success=False)+ return fail(i, f": create for '{nm}' must precede that skill's other ops.")preflight = _background_review_preflight(act, nm)if preflight is not None:return None, json.dumps(preflight, ensure_ascii=False)@@ -46,22 +45,18 @@ def _validate_batch_ops(operations, default_name, tool_error):# Additive patches are always legal. Paths are normalized against spelling variants.touched_files = set()for i, op in enumerate(operations):- act = op["action"]- nm = names[i]+ act, nm = op["action"], names[i]# create and full-rewrite patch (content) always hit SKILL.md.full_rewrite = act == "patch" and bool(op.get("content"))fp = (op.get("file_path") or "").strip()target = ("SKILL.md" if (act == "create" or full_rewrite or not fp)else posixpath.normpath(fp.lstrip("/")))key = (nm, target)- destructive = act in ("create", "write_file", "remove_file") or full_rewrite- if destructive and key in touched_files:- return None, tool_error(- f"operations[{i}]: {act} on '{target}' of skill '{nm}' — an earlier op in this "- f"batch already touched that file, and this op would silently discard its work. "- f"One destructive op (write_file/remove_file/full rewrite) per file per batch; put "- f"it first, or fold the change in. Patch chains are fine.",- success=False)+ if (act in ("create", "write_file", "remove_file") or full_rewrite) and key in touched_files:+ return fail(i, f": {act} on '{target}' of skill '{nm}' — an earlier op in this "+ f"batch already touched that file, and this op would silently discard its work. "+ f"One destructive op (write_file/remove_file/full rewrite) per file per batch; put "+ f"it first, or fold the change in. Patch chains are fine.")touched_files.add(key)return names, None@@ -84,26 +79,27 @@ def _snapshot_skills(names, snap_root, find_skill):def _restore_snapshot(pre_dir, snap, post_dir) -> None:- if snap is not None:- if post_dir is not None and post_dir.is_dir():- # Move the broken state aside and delete it only after the snapshot is- # back, so a failed copytree (disk full, locked file) can't mean total loss.- aside = post_dir.with_name(post_dir.name + ".rollback-broken")- shutil.rmtree(aside, ignore_errors=True)- post_dir.rename(aside)- try:- shutil.copytree(snap, pre_dir)- except Exception:- # Restore failed: put the half-applied state back rather than nothing.- shutil.rmtree(pre_dir, ignore_errors=True)- aside.rename(pre_dir)- raise- shutil.rmtree(aside, ignore_errors=True)- else:- shutil.copytree(snap, pre_dir)- elif post_dir is not None and post_dir.is_dir():- # Batch created this skill: remove the partial result.- shutil.rmtree(post_dir)+ post_exists = post_dir is not None and post_dir.is_dir()+ if snap is None:+ if post_exists: # Batch created this skill: remove the partial result.+ shutil.rmtree(post_dir)+ return+ if not post_exists:+ shutil.copytree(snap, pre_dir)+ return+ # Move the broken state aside and delete it only after the snapshot is+ # back, so a failed copytree (disk full, locked file) can't mean total loss.+ aside = post_dir.with_name(post_dir.name + ".rollback-broken")+ shutil.rmtree(aside, ignore_errors=True)+ post_dir.rename(aside)+ try:+ shutil.copytree(snap, pre_dir)+ except Exception:+ # Restore failed: put the half-applied state back rather than nothing.+ shutil.rmtree(pre_dir, ignore_errors=True)+ aside.rename(pre_dir)+ raise+ shutil.rmtree(aside, ignore_errors=True)def _rollback(snapshots, find_skill):@@ -114,9 +110,8 @@ def _rollback(snapshots, find_skill):post = find_skill(nm)_restore_snapshot(pre_dir, snap, Path(post["path"]) if post else None)except Exception as exc: # noqa: BLE001- notes.append(- f"ROLLBACK FAILED for '{nm}' ({exc}); snapshot preserved at '{snap}'"- if snap is not None else f"ROLLBACK FAILED for '{nm}' ({exc})")+ notes.append(f"ROLLBACK FAILED for '{nm}' ({exc})"+ + (f"; snapshot preserved at '{snap}'" if snap is not None else ""))return ("; ".join(notes) if notes else "all touched skills rolled back"), bool(notes)@@ -136,10 +131,8 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nonreturn tool_error(f"operations is capped at {_BATCH_MAX_OPS} ops per call.", success=False)if any(isinstance(op, dict) and op.get("action") == "delete" for op in operations):if len(operations) != 1:- return tool_error(- "delete must be the SOLE op in its call — it doesn't "- "compose with other ops' rollback.",- success=False)+ return tool_error("delete must be the SOLE op in its call — it doesn't "+ "compose with other ops' rollback.", success=False)op = operations[0]nm = op.get("name") or default_nameif not nm:diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.pyindex ad616e82537..41e8a02b396 100644--- a/tools/skill_manager_guards.py+++ b/tools/skill_manager_guards.py@@ -8,6 +8,7 @@ reached lazily through ``tools.skill_manager_tool`` so test patches keep workingimport contextvars as _ctxvarsimport loggingimport threading+from contextlib import suppressfrom pathlib import Pathfrom typing import Any, Dict, Optional@@ -77,22 +78,28 @@ def _reset_background_review_read_marks() -> None:_background_review_read_paths.set(_BackgroundReviewReadMarks())-def _containing_skills_root(skill_path: Path) -> Path:- """Skills root (local or external_dirs) containing ``skill_path``; local dir if none match."""+def _resolved_roots(skill_path: Path):+ """``(resolved skill_path, [(root, resolved_root), ...])`` over every skills root+ whose resolve() succeeds; an unresolvable skill_path is used as-is."""from agent.skill_utils import get_all_skills_dirs- from tools import skill_manager_tool as _smttry:resolved = skill_path.resolve()except OSError:resolved = skill_path+ roots = []for root in get_all_skills_dirs():- try:- if resolved.is_relative_to(root.resolve()):- return root- except OSError:- continue- return _smt._skills_dir()+ with suppress(OSError):+ roots.append((root, root.resolve()))+ return resolved, roots+++def _containing_skills_root(skill_path: Path) -> Path:+ """Skills root (local or external_dirs) containing ``skill_path``; local dir if none match."""+ from tools import skill_manager_tool as _smt++ resolved, roots = _resolved_roots(skill_path)+ return next((root for root, r in roots if resolved.is_relative_to(r)), _smt._skills_dir())def _is_path_redirect(path: Path) -> bool:@@ -108,22 +115,16 @@ def _validate_delete_target(skill_dir: Path) -> Optional[str]:"""Last-line guard before ``shutil.rmtree(skill_dir)``: even a poisoned treemust never delete (1) a path outside every known skills root, (2) a skillsroot itself, or (3) a symlink/junction (rmtree would follow it)."""- from agent.skill_utils import get_all_skills_dirs-if _is_path_redirect(skill_dir):return (f"Refusing to delete '{skill_dir}': the skill directory is a "f"symlink/junction. Remove the link target manually if intended.")try:- resolved = skill_dir.resolve()+ skill_dir.resolve()except OSError as exc:return f"Refusing to delete '{skill_dir}': could not resolve path ({exc})."-- for root in get_all_skills_dirs():- try:- root = root.resolve()- except OSError:- continue+ resolved, roots = _resolved_roots(skill_dir)+ for _root, root in roots:if resolved == root:return (f"Refusing to delete '{skill_dir}': resolves to the skills root "@@ -135,6 +136,16 @@ def _validate_delete_target(skill_dir: Path) -> Optional[str]:f"known skills root.")+def _is_pinned(name: str, what: str) -> Optional[bool]:+ """skill_usage pinned flag; None (logged at debug) when the record is unreadable."""+ try:+ from tools import skill_usage+ return bool(skill_usage.get_record(name).get("pinned"))+ except Exception:+ logger.debug("%s lookup failed for %s", what, name, exc_info=True)+ return None++def _pinned_guard(name: str) -> Optional[str]:"""Refusal message if *name* is pinned or essential, else None.@@ -150,15 +161,11 @@ def _pinned_guard(name: str) -> Optional[str]:f"cannot be deleted. Patches and edits are still allowed.")except Exception:logger.debug("essential-guard lookup failed for %s", name, exc_info=True)- try:- from tools import skill_usage- if skill_usage.get_record(name).get("pinned"):- return (- f"Skill '{name}' is pinned and cannot be deleted by skill_manage. Ask the user to "- f"run `hermes curator unpin {name}` if they want to delete it. Patches and edits "- f"are allowed on pinned skills; only deletion is blocked.")- except Exception:- logger.debug("pinned-guard lookup failed for %s", name, exc_info=True)+ if _is_pinned(name, "pinned-guard"):+ return (+ f"Skill '{name}' is pinned and cannot be deleted by skill_manage. Ask the user to "+ f"run `hermes curator unpin {name}` if they want to delete it. Patches and edits "+ f"are allowed on pinned skills; only deletion is blocked.")return None@@ -170,22 +177,17 @@ def _background_review_write_guard(agents it is also blocked on pinned/external/bundled/hub skills."""if not _is_background_review():return None-- try:- from tools import skill_usage- if skill_usage.get_record(name).get("pinned"):- return _refusal(- f"Refusing background curator {action} for pinned skill '{name}': pinned skills "- f"are off-limits to autonomous maintenance. Ask the user to run `hermes curator "- f"unpin {name}` if they want it changed.")- except Exception:- logger.debug("pinned skill guard lookup failed for %s", name, exc_info=True)-+ refuse = f"Refusing background curator {action} for"+ if _is_pinned(name, "pinned skill guard"):+ return _refusal(+ f"{refuse} pinned skill '{name}': pinned skills "+ f"are off-limits to autonomous maintenance. Ask the user to run `hermes curator "+ f"unpin {name}` if they want it changed.")try:from agent.skill_utils import is_external_skill_pathif is_external_skill_path(skill_dir):return _refusal(- f"Refusing background curator {action} for skill '{name}': "+ f"{refuse} skill '{name}': ""the skill lives in skills.external_dirs, which are ""externally owned and read-only to autonomous curation.")except Exception:@@ -198,8 +200,7 @@ def _background_review_write_guard((skill_usage.is_hub_installed, "hub-installed"),(skill_usage.is_bundled, "bundled")):if predicate(name):- return _refusal(- f"Refusing background curator {action} for {label} skill '{name}'.")+ return _refusal(f"{refuse} {label} skill '{name}'.")# Not curator-managed (no `created_by: "agent"`) => user-owned. A MISSING# record and an explicit `created_by: null` must resolve IDENTICALLY (keying# on presence made the policy depend on the guard's own side effect: the@@ -209,13 +210,13 @@ def _background_review_write_guard(_detail = (f"created_by={usage_rec.get('created_by')!r}" if isinstance(usage_rec, dict)else "no usage record")return _refusal(- f"Refusing background curator {action} for skill '{name}': the skill is not "+ f"{refuse} skill '{name}': the skill is not "f"curator-managed ({_detail}). User-owned skills are off-limits to autonomous "f"curation. Run `hermes curator adopt {name}` to opt it in.")except Exception:logger.warning("owned skill guard lookup failed for %s", name, exc_info=True)return _refusal(- f"Refusing background curator {action} for skill '{name}': agent ownership could not "+ f"{refuse} skill '{name}': agent ownership could not "f"be verified because the provenance record is unavailable or unreadable.")return None@@ -249,31 +250,31 @@ def _curator_consolidation_delete_guard(via ``absorbed_into=<umbrella>`` (existence validated in ``_delete_skill``).The deterministic inactivity prune never calls ``skill_manage``, so a baredelete here can only be the LLM pass pruning without evidence: refuse it."""- if not _is_background_review():- return None- if isinstance(absorbed_into, str) and absorbed_into.strip():+ if not _is_background_review() or (isinstance(absorbed_into, str) and absorbed_into.strip()):return Nonereturn _refusal(f"Refusing background curator delete of skill '{name}': the consolidation pass may only "f"archive a skill it has absorbed into an umbrella. Pass absorbed_into=<umbrella> (the "f"umbrella must already exist) to record a verified consolidation. Pruning a skill with no "f"forwarding target is not permitted here — the deterministic inactivity prune handles "- f"staleness archival "- "separately. Keeping '{name}' active.".format(name=name),+ f"staleness archival separately. Keeping '{name}' active.",_fail_closed=True)+def _is_org_mirror(skill_path: Path) -> bool:+ from agent.skill_utils import is_org_mirror_path+ from tools import skill_manager_tool as _smt+ return is_org_mirror_path(skill_path, _smt._skills_dir())++def _maybe_auto_propose_org_edit(name: str, skill_path: Path) -> Optional[str]:"""Submit an org-skill edit upstream when `sync.org_auto_propose` is on.Returns a note for the tool result or None; never raises (the edit isalready saved locally and can be proposed later)."""- from tools import skill_manager_tool as _smt-try:- from agent.skill_utils import is_org_mirror_pathfrom tools import skills_sync_client as ssc- if not is_org_mirror_path(skill_path, _smt._skills_dir()):+ if not _is_org_mirror(skill_path):return Noneif not ssc.sync_org_auto_propose():return (@@ -302,12 +303,8 @@ def _org_mirror_write_guard(name: str, skill_path: Path, action: str) -> Optionacomes back, and removing for everyone is an admin action."""if action not in {"delete", "remove_file"}:return None- from tools import skill_manager_tool as _smt-try:- from agent.skill_utils import is_org_mirror_path-- if is_org_mirror_path(skill_path, _smt._skills_dir()):+ if _is_org_mirror(skill_path):return _refusal(f"Cannot {action} '{name}' locally: it is shared by your organisation, so a local "f"delete would just come back on the next sync. Ask an org admin to remove it for "diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex b72acaa9d6e..e1c45f3f496 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -34,7 +34,7 @@ from tools.skill_manager_guards import ( # noqa: F401 — re-exported for calle_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)+ mark_background_review_skill_read, _refusal as _err)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@@ -104,10 +104,6 @@ def _display_create_dir() -> str:return f"{display_hermes_home()}/skills/"-def _err(message: str) -> Dict[str, Any]:- return {"success": False, "error": message}--# --- Validation helpers -------------------------------------------------------def _validate_name(name: str) -> Optional[str]:@@ -157,10 +153,9 @@ def _validate_frontmatter(content: str, *, new_skill: bool = False) -> Optional[return f"YAML frontmatter parse error: {e}"if not isinstance(parsed, dict):return "Frontmatter must be a YAML mapping (key: value pairs)."- if "name" not in parsed:- return "Frontmatter must include 'name' field."- if "description" not in parsed:- return "Frontmatter must include 'description' field."+ for field in ("name", "description"):+ if field not in parsed:+ return f"Frontmatter must include '{field}' field."desc = str(parsed["description"])if len(desc) > MAX_DESCRIPTION_LENGTH:return f"Description exceeds {MAX_DESCRIPTION_LENGTH} characters."@@ -199,9 +194,7 @@ def _resolve_skill_dir(name: str, category: str = None) -> Path:base = _skills_dir()try:from agent.skill_utils import get_skill_create_dir- create_dir = get_skill_create_dir()- if create_dir is not None:- base = create_dir+ base = get_skill_create_dir() or baseexcept Exception:logger.debug("skills.create_dir lookup failed", exc_info=True)return base / category / name if category else base / name@@ -267,14 +260,12 @@ def _find_skill_in_other_profiles(name: str) -> List[Tuple[str, Path]]:if profiles_root.is_dir():candidates += [(e.name, e / "skills") for e in profiles_root.iterdir() if e.is_dir()]for profile_name, skills_dir in candidates:- try:+ with suppress(OSError, RuntimeError):if skills_dir.resolve() == active_dir or not skills_dir.is_dir():continuehit = next((d for d in _iter_skill_dirs(skills_dir) if d.name == name), None)if hit is not None:matches.append((profile_name, hit)) # one match per profile is enough- except (OSError, RuntimeError):- continuereturn matches@@ -325,28 +316,22 @@ def _resolve_supporting_file(skill_dir: Path, file_path: str):-> ``(target, None)`` | ``(None, error_dict)``."""from tools.path_security import validate_within_dir- err = _validate_file_path(file_path)- if err:- return None, _err(err)- target = skill_dir / file_path- err = validate_within_dir(target, skill_dir)- if err:- return None, _err(err)- return target, None+ target = skill_dir / (file_path or "")+ err = _validate_file_path(file_path) or validate_within_dir(target, skill_dir)+ return (None, _err(err)) if err else (target, None)-def _locate_for_write(name: str, action: str, not_found_suffix: str = ""):- """Find the skill and run the org-mirror + background-review write guards- -> ``(skill_dir, None)`` | ``(None, error_dict)``."""+def _locate_for_write(name: str, action: str, not_found_suffix: str = "", *,+ org_guard: bool = True):+ """Find the skill and run the org-mirror (unless ``org_guard=False``) ++ 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))skill_dir = existing["path"]- guard = (_org_mirror_write_guard(name, skill_dir, action)+ guard = ((org_guard and _org_mirror_write_guard(name, skill_dir, action))or _background_review_write_guard(name, skill_dir, action))- if guard:- return None, guard- return skill_dir, None+ return (None, guard) if guard else (skill_dir, None)def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label: str,@@ -356,8 +341,7 @@ def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label:Returns an error dict or None."""original = Noneif target.exists():- read_guard = _background_review_read_before_write_guard(name, target, action, label)- if read_guard:+ if read_guard := _background_review_read_before_write_guard(name, target, action, label):return read_guardoriginal = target.read_text(encoding="utf-8")target.parent.mkdir(parents=True, exist_ok=True)@@ -373,8 +357,7 @@ def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label:def _attach_org_note(result: Dict[str, Any], name: str, skill_dir: Path) -> None:- org_note = _maybe_auto_propose_org_edit(name, skill_dir)- if org_note:+ if org_note := _maybe_auto_propose_org_edit(name, skill_dir):result["org_sharing"] = org_noteresult["message"] = f"{result['message']} {org_note}"@@ -403,6 +386,10 @@ def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None:"— fix them with skill_manage(action='patch') to match Hermes skill standards.")+def _clip(text: str, n: int, ellipsis: str) -> str:+ return text[:n] + (ellipsis if len(text) > n else "")++# --- Core actions -------------------------------------------------------------def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Any]:@@ -410,8 +397,7 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Anor _validate_frontmatter(content, new_skill=True) or _validate_content_size(content))if err:return _err(err)- existing = _find_skill(name)- if existing:+ if existing := _find_skill(name):return _err(f"A skill named '{name}' already exists at {existing['path']}.")skill_dir = _resolve_skill_dir(name, category)@@ -427,8 +413,7 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Andisplay = skill_dir.relative_to(root) if skill_dir.is_relative_to(root) else skill_dirresult = {"success": True, "message": f"Skill '{name}' created.", "path": str(display),- "skill_md": str(skill_md), "_change": {"description": _description_preview(content)},- }+ "skill_md": str(skill_md), "_change": {"description": _description_preview(content)}}if category:result["category"] = categoryresult["hint"] = (@@ -442,15 +427,12 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Andef _edit_skill(name: str, content: str) -> Dict[str, Any]:"""Replace the SKILL.md of any existing skill (full rewrite)."""- err = _validate_frontmatter(content) or _validate_content_size(content)- if err:+ if err := _validate_frontmatter(content) or _validate_content_size(content):return _err(err)skill_dir, guard = _locate_for_write(name, "edit")- if guard:- return guard# SKILL.md always exists here (_find_skill requires it), so a blocked scan restores it.- guard = _guarded_write(name, skill_dir, skill_dir / "SKILL.md", "edit", "SKILL.md", content)- if guard:+ if guard := guard or _guarded_write(+ name, skill_dir, skill_dir / "SKILL.md", "edit", "SKILL.md", content):return guardresult = {"success": True, "message": f"Skill '{name}' updated (full rewrite).",@@ -480,7 +462,6 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = Nskill_dir, guard = _locate_for_write(name, "patch")if guard:return guard-if file_path:target, err = _resolve_supporting_file(skill_dir, file_path)if err:@@ -490,8 +471,7 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = Nif 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:+ if read_guard := _background_review_read_before_write_guard(name, target, "patch", target_label):return read_guardcontent = target.read_text(encoding="utf-8")@@ -504,24 +484,18 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = Nwith suppress(Exception):from tools.fuzzy_match import format_no_match_hintmatch_error += format_no_match_hint(match_error, match_count, old_string, content)- return _err(match_error) | {"file_preview": content[:500] + ("..." if len(content) > 500 else "")}+ return _err(match_error) | {"file_preview": _clip(content, 500, "...")}- err = _validate_content_size(new_content, label=target_label)- if err:+ if err := _validate_content_size(new_content, label=target_label):return _err(err)- if not file_path:- err = _validate_frontmatter(new_content)- if err:- return _err(f"Patch would break SKILL.md structure: {err}")-- guard = _guarded_write(name, skill_dir, target, "patch", target_label, new_content)- if guard:+ if not file_path and (err := _validate_frontmatter(new_content)):+ return _err(f"Patch would break SKILL.md structure: {err}")+ if guard := _guarded_write(name, skill_dir, target, "patch", target_label, new_content):return guardresult = {"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": _clip(old_string, 200, "…"), "new": _clip(new_string, 200, "…")}}_attach_org_note(result, name, skill_dir)return result@@ -531,13 +505,9 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Aexplicit prune; "<skill>" = absorbed into that umbrella, which must exist ondisk (validated here so the model can't claim a nonexistent umbrella)."""skill_dir, guard = _locate_for_write(name, "delete")- if guard:+ if guard := guard or _curator_consolidation_delete_guard(name, absorbed_into):return guard- fail_closed = _curator_consolidation_delete_guard(name, absorbed_into)- if fail_closed:- return fail_closed- pinned_err = _pinned_guard(name)- if pinned_err:+ if pinned_err := _pinned_guard(name):return _err(pinned_err)absorbed_target = absorbed_into.strip() if isinstance(absorbed_into, str) else ""@@ -549,8 +519,7 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Af"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:+ if unsafe := _validate_delete_target(skill_dir): # defense-in-depth before rmtreereturn _err(unsafe)# Curator consolidations must be RECOVERABLE (`hermes curator restore`): archive@@ -580,8 +549,7 @@ def _rmdir_if_empty(parent: Path, stop: Path) -> None:def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:"""Add or overwrite a supporting file within any skill directory."""- err = _validate_file_path(file_path)- if err:+ if err := _validate_file_path(file_path):return _err(err)if not file_content and file_content != "":return _err("file_content is required.")@@ -589,18 +557,14 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:if content_bytes > MAX_SKILL_FILE_BYTES: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:+ if err := _validate_content_size(file_content, label=file_path):return _err(err)skill_dir, guard = _locate_for_write(name, "write_file", " Create it first with action='create'.")if guard:return guardtarget, err = _resolve_supporting_file(skill_dir, file_path)- if err:- return err- guard = _guarded_write(name, skill_dir, target, "write_file", file_path, file_content)- if guard:+ if guard := err or _guarded_write(name, skill_dir, target, "write_file", file_path, file_content):return guardresult = {"success": True, "message": f"File '{file_path}' written to skill '{name}'.","path": str(target)}@@ -610,14 +574,9 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:def _remove_file(name: str, file_path: str) -> Dict[str, Any]:"""Remove a supporting file from any skill directory."""- err = _validate_file_path(file_path)- if err:+ if err := _validate_file_path(file_path):return _err(err)- existing = _find_skill(name)- if not existing:- return _err(_skill_not_found_error(name))- skill_dir = existing["path"]- guard = _background_review_write_guard(name, skill_dir, "remove_file")+ skill_dir, guard = _locate_for_write(name, "remove_file", org_guard=False)if guard:return guardtarget, err = _resolve_supporting_file(skill_dir, file_path)@@ -630,8 +589,7 @@ def _remove_file(name: str, file_path: str) -> Dict[str, Any]: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:+ if read_guard := _background_review_read_before_write_guard(name, target, "remove_file", file_path):return read_guardtarget.unlink()