Skip to content

The agent that grows with you

refactor(tools): skill ledger/batch — inline one-use helpers, drop section banners

Tekniumce992963a27c
diff --git a/tools/skill_ledger.py b/tools/skill_ledger.py
index 7307df4a899..6509db56397 100644
--- a/tools/skill_ledger.py
+++ b/tools/skill_ledger.py
@@ -109,8 +109,6 @@ def _is_within(root: Path, path: Path) -> bool:
return False
-# --- Blob store (content-addressed, deduped) ---------------------------------
-
def _store_blob(data: bytes) -> str:
"""Write *data* keyed by sha256 (existing blob left alone). Returns the hash."""
digest = hashlib.sha256(data).hexdigest()
@@ -157,8 +155,6 @@ def snapshot_paths(root: Optional[Path], *, complete_package: bool = False) -> L
return out
-# --- Package-completeness fill from the newest curator backup -----------------
-
def _package_rel(root: Path) -> Optional[str]:
"""Relative POSIX path of a skill dir under ``skills/``; None when outside it
or under backup/hub/archive metadata roots (never a package)."""
@@ -173,12 +169,9 @@ def _strip_archive_timestamp(name: str) -> str:
return match.group(1) if match else name
-def _skill_md_parent(items: Optional[List[Dict[str, str]]]) -> Optional[Path]:
- for item in items or []:
- path = Path(str(item.get("path", "")))
- if path.name == "SKILL.md":
- return path.parent
- return None
+def _skill_md_parents(items: Optional[List[Dict[str, str]]]) -> List[Path]:
+ paths = [Path(str(item.get("path", ""))) for item in items or []]
+ return [p.parent for p in paths if p.name == "SKILL.md"]
def package_prefixes(
@@ -188,10 +181,7 @@ def package_prefixes(
the package parent from the before-state SKILL.md path (rollback fills where
*root* is gone), the bare skill name, and the name minus an archive suffix."""
candidates = [_package_rel(Path(root)) if root is not None else None]
- for item in before or []:
- path = Path(str(item.get("path", "")))
- if path.name == "SKILL.md":
- candidates.append(_package_rel(path.parent))
+ candidates += [_package_rel(p) for p in _skill_md_parents(before)]
candidates += [skill, _strip_archive_timestamp(skill) if skill else None]
found: List[str] = []
for prefix in candidates:
@@ -294,8 +284,6 @@ def fill_snapshot_from_curator_backup(
return out
-# --- Append + read ------------------------------------------------------------
-
def append_entry(
action: str, skill: str, before: Optional[List[Dict[str, str]]] = None,
after: Optional[List[Dict[str, str]]] = None, actor: Optional[str] = None,
@@ -395,8 +383,6 @@ def get_entry(entry_id: str) -> Optional[Dict[str, Any]]:
return next((row for row in list_entries() if row.get("id") == entry_id), None)
-# --- Single-edit rollback -----------------------------------------------------
-
def _validate_entry_paths(entry: Dict[str, Any]) -> Optional[str]:
"""Every entry path must be under HERMES_HOME — a hand-edited ledger must not
become a write-anywhere primitive."""
@@ -430,7 +416,8 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:
# only missing paths are added, and the filled set is re-validated.
if entry.get("action") in _PACKAGE_RESTORE_ACTIONS:
before = fill_snapshot_from_curator_backup(
- _skill_md_parent(before), before, skill=str(entry.get("skill") or "") or None)
+ 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:
return False, f"refusing rollback: {path_err}"
@@ -461,15 +448,11 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:
# Restore: write every before-file, remove files the mutation created.
before_paths = {str(i["path"]) for i in before}
- restored = 0
- removed = 0
for item in before:
fp = Path(str(item["path"]))
- data = read_blob(str(item["sha256"]))
- assert data is not None # pre-checked above
fp.parent.mkdir(parents=True, exist_ok=True)
- fp.write_bytes(data)
- restored += 1
+ fp.write_bytes(read_blob(str(item["sha256"]))) # pre-checked above
+ restored, removed = len(before), 0
for item in after:
p = str(item.get("path", ""))
if p and p not in before_paths:
diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.py
index 92ad073119a..5d1e863239c 100644
--- a/tools/skill_manager_batch.py
+++ b/tools/skill_manager_batch.py
@@ -15,11 +15,6 @@ _BATCH_OP_ACTIONS = {"create", "patch", "write_file", "remove_file"}
_BATCH_MAX_OPS = 20
-def _norm_target(op) -> str:
- fp = (op.get("file_path") or "").strip()
- return posixpath.normpath(fp.lstrip("/")) if fp else "SKILL.md"
-
-
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
@@ -55,7 +50,9 @@ def _validate_batch_ops(operations, default_name, tool_error):
nm = names[i]
# create and full-rewrite patch (content) always hit SKILL.md.
full_rewrite = act == "patch" and bool(op.get("content"))
- target = "SKILL.md" if (act == "create" or full_rewrite) else _norm_target(op)
+ 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:
@@ -69,19 +66,6 @@ def _validate_batch_ops(operations, default_name, tool_error):
return names, None
-def _stage_batch_if_gated(operations, names):
- """Approval gate for the WHOLE batch as one pending write."""
- from tools.skill_manager_tool import _run_write_gate
-
- def _staging(wa):
- acts = ", ".join(op["action"] for op in operations)
- skills = ", ".join(sorted(set(names)))
- gist = f"batch({len(operations)} ops: {acts}) on {skills}"
- return {"action": "batch", "operations": operations}, gist
-
- return _run_write_gate(_staging)
-
-
def _snapshot_skills(names, snap_root, find_skill):
"""Copy every touched skill aside. Returns (snapshots, None) or (None, error_text)."""
snapshots = {} # skill name -> (pre_dir or None, snapshot_dir or None)
@@ -169,7 +153,13 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Non
return err
if not _smt._skill_gate_bypass.get():
- staged = _stage_batch_if_gated(operations, names)
+ # Approval gate for the WHOLE batch as one pending write.
+ def _staging(wa):
+ acts = ", ".join(op["action"] for op in operations)
+ gist = f"batch({len(operations)} ops: {acts}) on {', '.join(sorted(set(names)))}"
+ return {"action": "batch", "operations": operations}, gist
+
+ staged = _smt._run_write_gate(_staging)
if staged is not None:
return staged
diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.py
index 97712603b81..ad616e82537 100644
--- a/tools/skill_manager_guards.py
+++ b/tools/skill_manager_guards.py
@@ -34,8 +34,6 @@ def _resolved_str(path: Path) -> str:
return str(path)
-# --- Background-review read marks --------------------------------------------
-
class _BackgroundReviewReadMarks:
"""Read marks shared by copied tool contexts within one review run."""
@@ -79,8 +77,6 @@ def _reset_background_review_read_marks() -> None:
_background_review_read_paths.set(_BackgroundReviewReadMarks())
-# --- Delete-target safety -----------------------------------------------------
-
def _containing_skills_root(skill_path: Path) -> Path:
"""Skills root (local or external_dirs) containing ``skill_path``; local dir if none match."""
from agent.skill_utils import get_all_skills_dirs
@@ -139,8 +135,6 @@ def _validate_delete_target(skill_dir: Path) -> Optional[str]:
f"known skills root.")
-# --- Ownership / provenance guards --------------------------------------------
-
def _pinned_guard(name: str) -> Optional[str]:
"""Refusal message if *name* is pinned or essential, else None.
@@ -269,8 +263,6 @@ def _curator_consolidation_delete_guard(
_fail_closed=True)
-# --- Org-mirror handling ------------------------------------------------------
-
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 is
diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py
index b385560b311..fa056453828 100644
--- a/tools/skill_manager_tool.py
+++ b/tools/skill_manager_tool.py
@@ -92,6 +92,7 @@ MAX_SKILL_FILE_BYTES = 1_048_576 # 1 MiB per supporting file
VALID_NAME_RE = re.compile(r'^[a-z0-9][a-z0-9._-]*$') # filesystem-safe, URL-friendly
ALLOWED_SUBDIRS = {"references", "templates", "scripts", "assets"} # for write_file/remove_file
_FRONTMATTER_END_RE = re.compile(r'\n---\s*\n')
+_NAME_RULE = "Use lowercase letters, numbers, hyphens, dots, and underscores."
def _display_create_dir() -> str:
@@ -115,8 +116,7 @@ def _validate_name(name: str) -> Optional[str]:
if len(name) > MAX_NAME_LENGTH:
return f"Skill name exceeds {MAX_NAME_LENGTH} characters."
if not VALID_NAME_RE.match(name):
- return (f"Invalid skill name '{name}'. Use lowercase letters, numbers, "
- f"hyphens, dots, and underscores. Must start with a letter or digit.")
+ return f"Invalid skill name '{name}'. {_NAME_RULE} Must start with a letter or digit."
return None
@@ -128,8 +128,8 @@ def _validate_category(category: Optional[str]) -> Optional[str]:
category = category.strip()
if not category:
return None
- invalid = (f"Invalid category '{category}'. Use lowercase letters, numbers, "
- "hyphens, dots, and underscores. Categories must be a single directory name.")
+ invalid = (f"Invalid category '{category}'. {_NAME_RULE} "
+ "Categories must be a single directory name.")
if "/" in category or "\\" in category:
return invalid
if len(category) > MAX_NAME_LENGTH:
@@ -627,7 +627,6 @@ def _remove_file(name: str, file_path: str) -> Dict[str, Any]:
guard = _background_review_write_guard(name, skill_dir, "remove_file")
if guard:
return guard
-
target, err = _resolve_supporting_file(skill_dir, file_path)
if err:
return err
@@ -720,7 +719,7 @@ def apply_skill_pending(payload: Dict[str, Any]) -> str:
# Debounce state for the sync push hook: a burst of skill_manage writes
# collapses into one push after a quiet window, on a daemon timer.
_sync_push_timer = None
-_sync_push_lock = None
+_sync_push_lock = threading.Lock()
_SYNC_PUSH_DEBOUNCE_S = 5.0
@@ -728,7 +727,7 @@ def _maybe_debounced_sync_push(skill_name: str) -> None:
"""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
+ global _sync_push_timer
try:
from tools.skill_usage import is_sync_enabled
if not is_sync_enabled(skill_name):
@@ -736,9 +735,6 @@ def _maybe_debounced_sync_push(skill_name: str) -> None:
except Exception:
return
- if _sync_push_lock is None:
- _sync_push_lock = threading.Lock()
-
def _fire():
with suppress(Exception):
from tools.skills_sync_client import maybe_push_skills