The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): skill_manage — dispatch default for unknown action, simpler ledger read, squeeze body blanks
Teknium370c6a245671
diff --git a/tools/skill_ledger.py b/tools/skill_ledger.pyindex 8b4512ee4f2..637f26f2e22 100644--- a/tools/skill_ledger.py+++ b/tools/skill_ledger.py@@ -320,19 +320,16 @@ def capture_before(def list_entries(skill: Optional[str] = None, limit: Optional[int] = None) -> List[Dict[str, Any]]:"""Read the ledger, newest first. Malformed lines are skipped."""- path = ledger_path()- if not path.exists():- return []- rows: List[Dict[str, Any]] = []try:- with open(path, "r", encoding="utf-8") as fh:- for line in fh:- with suppress(json.JSONDecodeError):- row = json.loads(line) if line.strip() else None- if isinstance(row, dict):- rows.append(row)- except OSError:+ lines = ledger_path().read_text(encoding="utf-8").splitlines()+ except OSError: # missing or unreadable ledger == emptyreturn []+ rows: List[Dict[str, Any]] = []+ for line in lines:+ with suppress(json.JSONDecodeError):+ row = json.loads(line) if line.strip() else None+ if isinstance(row, dict):+ rows.append(row)if skill:rows = [r for r in rows if r.get("skill") == skill]rows.reverse()@@ -366,7 +363,6 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:return False, f"no ledger entry with id '{entry_id}'"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@@ -383,7 +379,6 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:if read_blob(str(item.get("sha256", ""))) is None:return False, (f"missing blob {item.get('sha256')} for {item.get('path')}; ""rollback aborted, nothing was changed")-# 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:@@ -398,7 +393,6 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:if safety_id is None:return False, ("pre-rollback safety capture failed (ledger disabled or ""unwritable); rollback aborted and current skills were not changed")-# Restore: write every before-file, remove files the mutation created.before_paths = {str(i["path"]) for i in before}for item in before:@@ -415,7 +409,6 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:removed += 1except OSError as e:logger.warning("skill_ledger: could not remove %s during rollback: %s", p, e)-append_entry("rollback", entry.get("skill", "?"), before=safety_before, after=before,evidence={"rollback_target": entry_id, "restored": restored, "removed": removed})diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex b23bc50c015..c5fe07118bb 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -18,10 +18,8 @@ _BATCH_MAX_OPS = 20def _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"):@@ -39,7 +37,6 @@ def _validate_batch_ops(operations, default_name, tool_error):preflight = _background_review_preflight(act, nm)if preflight is not None:return None, json.dumps(preflight, ensure_ascii=False)-# Clobber guard: a DESTRUCTIVE op (create/write_file/remove_file/full rewrite) on# a file an earlier op touched would SILENTLY discard its work — reject it.# Additive patches are always legal. Paths are normalized against spelling variants.@@ -67,9 +64,8 @@ def _snapshot_skills(names, snap_root, find_skill):for nm in dict.fromkeys(names): # ordered uniquepre = find_skill(nm)pre_dir = Path(pre["path"]) if pre else None- snap = None- if pre_dir is not None and pre_dir.is_dir():- snap = snap_root / nm+ snap = snap_root / nm if pre_dir is not None and pre_dir.is_dir() else None+ if snap is not None:try:shutil.copytree(pre_dir, snap)except Exception as exc: # noqa: BLE001 — no snapshot, no atomicity@@ -124,7 +120,6 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nontop-level ``name`` fallback (staged replay)."""from tools import skill_manager_tool as _smtfrom tools.registry import tool_error-if not isinstance(operations, list) or not operations:return tool_error("operations must be a non-empty array.", success=False)if len(operations) > _BATCH_MAX_OPS:@@ -138,28 +133,23 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nonreturn tool_error("operations[0] (delete) needs a 'name'.", success=False)return _smt.skill_manage(action="delete", name=nm, task_id=task_id, session_id=session_id,absorbed_into=operations[0].get("absorbed_into"))-names, err = _validate_batch_ops(operations, default_name, tool_error)if err is not None:return err-if not _smt._skill_gate_bypass.get():# 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-snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))snapshots, snap_err = _snapshot_skills(names, snap_root, _smt._find_skill)if snap_err is not None:shutil.rmtree(snap_root, ignore_errors=True)return tool_error(snap_err, success=False)-# Single-op path with the gate bypassed (the batch already cleared/staged it).results = []rollback_failed = False@@ -194,7 +184,6 @@ def _skill_manage_batch(operations, default_name: str = None, task_id: str = Nonlogger.warning("skill_manage batch rollback failed, snapshots kept at %s", snap_root)else:shutil.rmtree(snap_root, ignore_errors=True)-return json.dumps({"success": True, "operations_applied": len(results), "results": results},ensure_ascii=False)diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.pyindex d7de879d3a6..3b4d913a1b3 100644--- a/tools/skill_manager_guards.py+++ b/tools/skill_manager_guards.py@@ -78,7 +78,6 @@ def _reset_background_review_read_marks() -> None:def _resolved_roots(skill_path: Path):"""``(resolved skill_path, [(root, resolved_root), ...])`` over every resolvable skills root."""from agent.skill_utils import get_all_skills_dirs-try:resolved = skill_path.resolve()except OSError:@@ -93,7 +92,6 @@ def _resolved_roots(skill_path: Path):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())@@ -173,12 +171,10 @@ def _background_review_write_guard(from agent.skill_utils import is_external_skill_pathif is_external_skill_path(skill_dir):return _refusal(- f"{refuse} skill '{name}': "- "the skill lives in skills.external_dirs, which are "- "externally owned and read-only to autonomous curation.")+ f"{refuse} skill '{name}': the skill lives in skills.external_dirs, which are "+ f"externally owned and read-only to autonomous curation.")except Exception:logger.debug("external skill guard lookup failed for %s", name, exc_info=True)-try:from tools import skill_usagefor predicate, label in (@@ -256,7 +252,6 @@ def _maybe_auto_propose_org_edit(name: str, skill_path: Path) -> Optional[str]:the tool result or None; never raises (the edit is saved locally and can be proposed later)."""try:from tools import skills_sync_client as ssc-if not _is_org_mirror(skill_path):return Noneif not ssc.sync_org_auto_propose():diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex 2cb78edf312..a0e42bfb294 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -206,7 +206,6 @@ def _find_skill(name: str) -> Optional[Dict[str, Any]]:categorized relative path (``mlops/axolotl``) — the two forms skill_view resolves. Thecategorized form matches RELATIVE to the local root only (relative_to raises for external dirs)."""from agent.skill_utils import get_all_skills_dirs-local_root = Noneif "/" in name or "\\" in name:try:@@ -216,7 +215,6 @@ def _find_skill(name: str) -> Optional[Dict[str, Any]]:"skills dir resolve failed; categorized lookups fall back to the unresolved path",exc_info=True)local_root = _skills_dir()-for skills_dir in get_all_skills_dirs():if not skills_dir.exists():continue@@ -281,7 +279,6 @@ def _skill_not_found_error(name: str, suffix: str = "") -> str:def _validate_file_path(file_path: str) -> Optional[str]:"""Validate a write_file/remove_file path: under an allowed subdir, no escape."""from tools.path_security import has_traversal_component-if not file_path:return "file_path is required."parts = Path(file_path).parts@@ -303,7 +300,6 @@ def _resolve_supporting_file(skill_dir: Path, file_path: str):"""Validate ``file_path`` and resolve it inside ``skill_dir``-> ``(target, None)`` | ``(None, error_dict)``."""from tools.path_security import validate_within_dir-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)@@ -363,7 +359,7 @@ def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None:from tools.skill_linter import lint_skill # local import: optional pathfindings = lint_skill(skill_md)except Exception:- return+ findings = Noneif not findings:returnresult["lint_warnings"] = [@@ -386,7 +382,6 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Anreturn _err(err)if existing := _find_skill(name):return _err(f"A skill named '{name}' already exists at {existing['path']}.")-skill_dir = _resolve_skill_dir(name, category)skill_dir.mkdir(parents=True, exist_ok=True)skill_md = skill_dir / "SKILL.md"@@ -394,7 +389,6 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Anif scan_error := _security_scan_skill(skill_dir):shutil.rmtree(skill_dir, ignore_errors=True)return _err(scan_error)-root = _skills_dir()# Relative when under the profile dir; absolute when created under skills.create_dir.display = skill_dir.relative_to(root) if skill_dir.is_relative_to(root) else skill_dir@@ -456,7 +450,6 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = Nreturn _err(f"File not found: {target.relative_to(skill_dir)}")if read_guard := _background_review_read_before_write_guard(name, target, "patch", target_label):return read_guard-content = target.read_text(encoding="utf-8")# Same fuzzy engine as the file patch tool (whitespace/indent/escape normalization,# block anchors) so minor formatting mismatches don't fail.@@ -468,7 +461,6 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = Nfrom 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": _clip(content, 500, "...")}-if err := _validate_content_size(new_content, label=target_label):return _err(err)if not file_path and (err := _validate_frontmatter(new_content)):@@ -491,7 +483,6 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Areturn guardif pinned_err := _pinned_guard(name):return _err(pinned_err)-absorbed_target = absorbed_into.strip() if isinstance(absorbed_into, str) else ""if absorbed_target:if absorbed_target == name:@@ -499,7 +490,6 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Aif 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.")-skills_root = _containing_skills_root(skill_dir)if unsafe := _validate_delete_target(skill_dir): # defense-in-depth before rmtreereturn _err(unsafe)@@ -517,7 +507,6 @@ def _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Areturn {"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 rootreturn {"success": True, "message": f"Skill '{name}' deleted.{absorbed_note}"}@@ -540,7 +529,6 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:f"bytes / 1 MiB). Consider splitting into smaller files.")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 guard@@ -572,7 +560,6 @@ def _remove_file(name: str, file_path: str) -> Dict[str, Any]:"available_files": available if available else None}if read_guard := _background_review_read_before_write_guard(name, target, "remove_file", file_path):return read_guard-target.unlink()_rmdir_if_empty(target.parent, skill_dir)return {"success": True, "message": f"File '{file_path}' removed from skill '{name}'."}@@ -608,14 +595,12 @@ def _apply_skill_write_gate(action, name, **payload_kwargs):"""Flat-shape gate: stage the full kwargs so approval can replay them; bypassed during replay."""if action not in _ACTION_HANDLERS or _skill_gate_bypass.get():return None-def _staging(wa):payload = {"action": action, "name": name,**{k: v for k, v in payload_kwargs.items() if v is not None}}gist_kw = {k: payload_kwargs.get(k) or ""for k in ("content", "file_path", "old_string", "new_string")}return payload, wa.skill_gist(action, name, **gist_kw)-return _run_write_gate(_staging)@@ -656,12 +641,10 @@ def _maybe_debounced_sync_push(skill_name: str) -> None:returnexcept Exception:return-def _fire():with suppress(Exception):from tools.skills_sync_client import maybe_push_skillsmaybe_push_skills(message=f"sync: {skill_name}")-with _sync_push_lock:if _sync_push_timer is not None:_sync_push_timer.cancel() # only sets an Event; never raises@@ -750,7 +733,6 @@ def skill_manage(operations, default_name=name or None, task_id=task_id, session_id=session_id)if (preflight := _background_review_preflight(action, name)) is not None:return json.dumps(preflight, ensure_ascii=False)-# 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,@@ -758,7 +740,6 @@ def skill_manage(absorbed_into=absorbed_into)if (gate_result := _apply_skill_write_gate(action, name, **args)) is not None:return gate_result-# Ledger pre-capture: telemetry, not a gate — failures must NEVER block the mutation. delete# destroys the whole package (consolidation may have re-homed support files first), so# complete it from the newest curator backup or a restore is hollow.@@ -768,18 +749,14 @@ def skill_manage(_pre = _find_skill(name)_ledger_before = _ledger.capture_before(_pre["path"] if _pre else None, complete_package=(action == "delete"), skill=name)-- handler = _ACTION_HANDLERS.get(action)- if handler is None:- result = _err(f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file")- else:- for arg, missing, message in _REQUIRED_ARGS.get(action, ()):- if missing(args[arg]):- return tool_error(message, success=False)- result = handler({"name": name, **args})- if isinstance(result, str):- return result # tool_error JSON for argument-shape problems (patch)-+ for arg, missing, message in _REQUIRED_ARGS.get(action, ()):+ if missing(args[arg]):+ return tool_error(message, success=False)+ handler = _ACTION_HANDLERS.get(action, lambda a: _err(+ f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file"))+ result = handler({"name": name, **args})+ if isinstance(result, str):+ return result # tool_error JSON for argument-shape problems (patch)if result.get("success"):_record_success(action, name, result, file_path=file_path, absorbed_into=absorbed_into,