Skip to content

The agent that grows with you

feat(skill_manage): operations[] is the call — each op names its skill; atomic with cross-skill rollback (#97295)

Teknium72874b067512
diff --git a/tests/tools/test_skill_manage_batch.py b/tests/tools/test_skill_manage_batch.py
new file mode 100644
index 00000000000..b6e782b7960
--- /dev/null
+++ b/tests/tools/test_skill_manage_batch.py
@@ -0,0 +1,223 @@
+"""skill_manage operations[] batch (#95681 arc, maintainer-approved).
+
+Memory-tool pattern: several ops on ONE skill, atomically — create + N
+supporting files, or SKILL.md + the script it references, in one call.
+Any failure rolls the skill directory back to its pre-batch state.
+"""
+import json
+import os
+import shutil
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
+
+SK = (
+ "---\nname: {n}\ndescription: Use when probing batch ops. Behavior.\n---\n"
+ "# Probe\nStep 1.\n"
+)
+
+
+class TestSkillManageBatch(unittest.TestCase):
+ def setUp(self):
+ self.home = tempfile.mkdtemp(prefix="skmbatch_t_")
+ os.environ["HERMES_HOME"] = self.home
+ os.environ["HERMES_YOLO_MODE"] = "1"
+ os.makedirs(os.path.join(self.home, "skills"), exist_ok=True)
+ # Re-import against the temp home (module caches SKILLS_DIR).
+ import importlib
+
+ import tools.skill_manager_tool as smt
+ importlib.reload(smt)
+ self.smt = smt
+
+ def tearDown(self):
+ shutil.rmtree(self.home, ignore_errors=True)
+
+ def _call(self, name, ops):
+ # Inject the per-op name (tests were written per-skill; the
+ # interface is name-per-op, maintainer-directed).
+ for op in ops:
+ op.setdefault("name", name)
+ return json.loads(self.smt.skill_manage(action="", name="", operations=ops))
+
+ def test_create_plus_files_atomic(self):
+ r = self._call("probe", [
+ {"action": "create", "content": SK.format(n="probe")},
+ {"action": "write_file", "file_path": "references/a.md", "file_content": "a"},
+ {"action": "write_file", "file_path": "scripts/r.py", "file_content": "pass"},
+ ])
+ self.assertTrue(r["success"], r)
+ self.assertEqual(r["operations_applied"], 3)
+ base = os.path.join(self.home, "skills", "probe")
+ for rel in ("SKILL.md", "references/a.md", "scripts/r.py"):
+ self.assertTrue(os.path.exists(os.path.join(base, rel)), rel)
+
+ def test_midbatch_failure_rolls_back_existing_skill(self):
+ self._call("probe", [{"action": "create", "content": SK.format(n="probe")}])
+ r = self._call("probe", [
+ {"action": "patch", "old_string": "Step 1.", "new_string": "Step ONE."},
+ {"action": "write_file", "file_path": "bad/nope.md", "file_content": "x"},
+ ])
+ self.assertFalse(r["success"])
+ self.assertEqual(r["failed_index"], 1)
+ content = open(os.path.join(self.home, "skills", "probe", "SKILL.md")).read()
+ self.assertIn("Step 1.", content) # patch undone
+ self.assertNotIn("Step ONE.", content)
+
+ def test_failed_create_batch_removes_partial_skill(self):
+ r = self._call("fresh", [
+ {"action": "create", "content": SK.format(n="fresh")},
+ {"action": "write_file", "file_path": "../escape.md", "file_content": "x"},
+ ])
+ self.assertFalse(r["success"])
+ self.assertFalse(os.path.exists(os.path.join(self.home, "skills", "fresh")))
+
+ def test_validation_rules(self):
+ # delete as SOLE op routes to the real delete (works)
+ self._call("probe", [{"action": "create", "content": SK.format(n="probe")}])
+ r = self._call("probe", [{"action": "delete"}])
+ self.assertTrue(r["success"], r)
+ self.assertFalse(os.path.exists(os.path.join(self.home, "skills", "probe")))
+ # delete mixed with other ops rejected
+ self._call("probe", [{"action": "create", "content": SK.format(n="probe")}])
+ r = self._call("probe", [
+ {"action": "patch", "old_string": "Step 1.", "new_string": "X."},
+ {"action": "delete"},
+ ])
+ self.assertFalse(r["success"])
+ self.assertIn("SOLE", r["error"])
+ # create must be first
+ r = self._call("x", [
+ {"action": "write_file", "file_path": "references/a.md", "file_content": "a"},
+ {"action": "create", "content": SK.format(n="x")},
+ ])
+ self.assertFalse(r["success"])
+ # empty / capped
+ r = self._call("x", [])
+ self.assertFalse(r["success"])
+ r = self._call("x", [{"action": "patch"}] * 21)
+ self.assertFalse(r["success"])
+ self.assertIn("capped", r["error"])
+
+ def test_intra_batch_conflict_guard(self):
+ """Same-file double writes and post-edit full rewrites are always
+ a confused plan under last-wins sequencing — rejected BEFORE any
+ side effect. Patch chains and rewrite-first stay legal."""
+ self._call("probe", [{"action": "create", "content": SK.format(n="probe")}])
+ # destructive op on an already-touched file: rejected — double
+ # write, write+remove, patch-then-write, patch-then-remove, and a
+ # path-spelling variant of the same file.
+ self._call("probe", [{"action": "write_file",
+ "file_path": "references/c.md", "file_content": "seed"}])
+ for ops in (
+ [{"action": "write_file", "file_path": "references/a.md", "file_content": "1"},
+ {"action": "write_file", "file_path": "references/a.md", "file_content": "2"}],
+ [{"action": "write_file", "file_path": "references/b.md", "file_content": "x"},
+ {"action": "remove_file", "file_path": "references/b.md"}],
+ [{"action": "patch", "file_path": "references/c.md",
+ "old_string": "seed", "new_string": "edited"},
+ {"action": "write_file", "file_path": "references/c.md", "file_content": "CLOB"}],
+ [{"action": "patch", "file_path": "references/c.md",
+ "old_string": "seed", "new_string": "edited"},
+ {"action": "remove_file", "file_path": "references/c.md"}],
+ [{"action": "write_file", "file_path": "references/d.md", "file_content": "1"},
+ {"action": "write_file", "file_path": "./references//d.md", "file_content": "2"}],
+ ):
+ r = self._call("probe", ops)
+ self.assertFalse(r["success"], ops)
+ self.assertIn("discard", r["error"])
+ # ...and rejected pre-effect: c.md still holds its seed text.
+ c_md = os.path.join(self.home, "skills", "probe", "references", "c.md")
+ self.assertEqual(open(c_md).read(), "seed")
+ # write-then-patch on one supporting file stays legal (additive).
+ r = self._call("probe", [
+ {"action": "write_file", "file_path": "references/e.md", "file_content": "base"},
+ {"action": "patch", "file_path": "references/e.md",
+ "old_string": "base", "new_string": "base+"},
+ ])
+ self.assertTrue(r["success"], r)
+ # patch then full rewrite: rejected; rewrite-first: allowed
+ r = self._call("probe", [
+ {"action": "patch", "old_string": "Step 1.", "new_string": "P."},
+ {"action": "patch", "content": SK.format(n="probe")},
+ ])
+ self.assertFalse(r["success"])
+ self.assertIn("rewrite", r["error"])
+ r = self._call("probe", [
+ {"action": "patch", "content": SK.format(n="probe").replace("Step 1.", "F.")},
+ {"action": "patch", "old_string": "F.", "new_string": "G."},
+ ])
+ self.assertTrue(r["success"], r)
+ # patch chains stay legal
+ r = self._call("probe", [
+ {"action": "patch", "old_string": "G.", "new_string": "H."},
+ {"action": "patch", "old_string": "H.", "new_string": "I."},
+ ])
+ self.assertTrue(r["success"], r)
+
+ def test_cross_skill_batch_and_rollback(self):
+ """Ops may target DIFFERENT skills; a late failure rolls back
+ every touched skill, including removing a batch-created one."""
+ self._call("alpha", [{"action": "create", "content": SK.format(n="alpha")}])
+ r = json.loads(self.smt.skill_manage(action="", name="", operations=[
+ {"name": "alpha", "action": "patch",
+ "old_string": "Step 1.", "new_string": "Step A."},
+ {"name": "beta", "action": "create", "content": SK.format(n="beta")},
+ {"name": "beta", "action": "write_file",
+ "file_path": "bad/nope.md", "file_content": "x"},
+ ]))
+ self.assertFalse(r["success"])
+ self.assertEqual(r["failed_index"], 2)
+ # alpha's patch undone; beta (batch-created) removed entirely.
+ content = open(os.path.join(self.home, "skills", "alpha", "SKILL.md")).read()
+ self.assertIn("Step 1.", content)
+ self.assertNotIn("Step A.", content)
+ self.assertFalse(os.path.exists(os.path.join(self.home, "skills", "beta")))
+
+ def test_single_op_path_unchanged(self):
+ self._call("probe", [{"action": "create", "content": SK.format(n="probe")}])
+ raw = self.smt.skill_manage(
+ action="patch", name="probe",
+ old_string="Step 1.", new_string="Step 1 (single).",
+ )
+ self.assertTrue(json.loads(raw)["success"])
+
+ def test_batch_stages_as_one_pending_write_when_gated(self):
+ """Approval gate: the whole batch stages as ONE pending record, and
+ apply_skill_pending replays it (operations key round-trips)."""
+ from unittest.mock import patch as _patch
+
+ class _Decision:
+ allow = False
+ blocked = False
+ message = "staged for review"
+
+ staged = {}
+
+ def fake_stage_write(area, payload, summary=None, origin=None):
+ staged.update(payload=payload, summary=summary)
+ return {"id": "pend_1"}
+
+ import tools.write_approval as wa
+
+ with _patch.object(wa, "evaluate_gate", return_value=_Decision()), \
+ _patch.object(wa, "stage_write", side_effect=fake_stage_write):
+ r = self._call("probe", [
+ {"action": "create", "content": SK.format(n="probe")},
+ {"action": "write_file", "file_path": "references/a.md",
+ "file_content": "a"},
+ ])
+ self.assertTrue(r.get("staged"), r)
+ self.assertEqual(staged["payload"]["action"], "batch")
+ self.assertEqual(len(staged["payload"]["operations"]), 2)
+ self.assertIn("2 ops", staged["summary"])
+ # Replay applies the batch (gate bypassed inside).
+ out = json.loads(self.smt.apply_skill_pending(staged["payload"]))
+ self.assertTrue(out["success"], out)
+ self.assertEqual(out["operations_applied"], 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/tools/test_skill_manage_schema_diet.py b/tests/tools/test_skill_manage_schema_diet.py
index 0d78cb21b17..7bdab0ad220 100644
--- a/tests/tools/test_skill_manage_schema_diet.py
+++ b/tests/tools/test_skill_manage_schema_diet.py
@@ -15,8 +15,22 @@ from tools.skill_manager_tool import SKILL_MANAGE_SCHEMA
class TestSkillManageSchemaDiet(unittest.TestCase):
- def test_patch_args_defer_to_patch_tool(self):
+ def _op_props(self):
+ return SKILL_MANAGE_SCHEMA["parameters"]["properties"]["operations"]["items"]["properties"]
+
+ def test_single_call_shape(self):
+ """Maintainer-directed: operations[] IS the interface — each op
+ names its skill; a single edit is a list of one. Flat fields are
+ handler-only compat."""
props = SKILL_MANAGE_SCHEMA["parameters"]["properties"]
+ self.assertEqual(sorted(props), ["operations"])
+ self.assertEqual(SKILL_MANAGE_SCHEMA["parameters"]["required"], ["operations"])
+ items = SKILL_MANAGE_SCHEMA["parameters"]["properties"]["operations"]["items"]
+ self.assertEqual(items["required"], ["name", "action"])
+ self.assertIn("delete", self._op_props()["action"]["enum"])
+
+ def test_patch_args_defer_to_patch_tool(self):
+ props = self._op_props()
self.assertIn("patch tool", props["old_string"]["description"])
# The uniqueness/context curriculum lives in the patch tool's schema,
# not here.
@@ -24,7 +38,7 @@ class TestSkillManageSchemaDiet(unittest.TestCase):
self.assertNotIn("surrounding context", props["old_string"]["description"])
def test_file_path_states_relative_shape(self):
- desc = SKILL_MANAGE_SCHEMA["parameters"]["properties"]["file_path"]["description"]
+ desc = self._op_props()["file_path"]["description"]
self.assertIn("RELATIVE", desc)
self.assertIn("references/api.md", desc)
self.assertIn("never absolute", desc)
@@ -42,13 +56,14 @@ class TestSkillManageSchemaDiet(unittest.TestCase):
self.assertIn("skill_view()", desc)
self.assertNotIn("numbered steps", desc)
# Stale action vocabulary must not return.
- self.assertNotIn("edit", SKILL_MANAGE_SCHEMA["parameters"]["properties"]["name"]["description"])
+ self.assertNotIn("edit", self._op_props()["name"]["description"])
def test_content_keeps_pre_irreversibility_warning(self):
"""The REPLACES-whole-file warning is pre-irreversibility guidance:
an error can't teach after a successful full rewrite, so it must
- stay schema-side (maintainer call)."""
- desc = SKILL_MANAGE_SCHEMA["parameters"]["properties"]["content"]["description"]
+ stay schema-side (maintainer call). Lives in the description now
+ (op fields stay terse)."""
+ desc = SKILL_MANAGE_SCHEMA["description"]
self.assertIn("REPLACES", desc)
self.assertIn("skill_view()", desc)
diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py
index ba3159a9fc3..d28d178b1a0 100644
--- a/tools/skill_manager_tool.py
+++ b/tools/skill_manager_tool.py
@@ -1518,11 +1518,237 @@ def apply_skill_pending(payload: Dict[str, Any]) -> str:
new_string=payload.get("new_string"),
replace_all=payload.get("replace_all", False),
absorbed_into=payload.get("absorbed_into"),
+ operations=payload.get("operations"),
)
finally:
_skill_gate_bypass.reset(token)
+_BATCH_OP_ACTIONS = {"create", "patch", "write_file", "remove_file"}
+_BATCH_MAX_OPS = 20
+
+
+def _skill_manage_batch(
+ operations,
+ default_name: str = None,
+ task_id: str = None,
+ session_id: str = None,
+) -> str:
+ """Apply a sequence of operations atomically (memory-tool pattern).
+
+ Each op carries its own ``name`` (skill) and ``action``; a single edit
+ is a list of one. Every skill the batch touches is snapshotted before
+ any op runs; any failure rolls ALL touched skills back to their
+ pre-batch state (skills the batch created are removed).
+
+ Rules:
+ - ``delete`` only as the SOLE op of the call (its recoverable-archive
+ path doesn't compose with rollback) — routed to the single-op
+ handler, preserving absorbed_into/archive semantics;
+ - ``create`` for a skill must precede that skill's other ops;
+ - same-file clobber guard (below) rejects silently-lost work.
+
+ ``default_name``: legacy top-level ``name`` fallback for ops that omit
+ their own (staged-replay / back-compat path).
+ """
+ import shutil
+ import tempfile
+
+ # --- validate shape up front (no side effects before this passes) ---
+ 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:
+ return tool_error(f"operations is capped at {_BATCH_MAX_OPS} ops per call.", success=False)
+ # delete: sole-op only; route through the normal single-op path so the
+ # gate, archive, ledger, and curator absorbed_into semantics all apply.
+ 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,
+ )
+ op = operations[0]
+ nm = op.get("name") or default_name
+ if not nm:
+ return tool_error("operations[0] (delete) needs a 'name'.", success=False)
+ return skill_manage(
+ action="delete",
+ name=nm,
+ absorbed_into=op.get("absorbed_into"),
+ task_id=task_id,
+ session_id=session_id,
+ )
+ names = []
+ for i, op in enumerate(operations):
+ if not isinstance(op, dict) or not op.get("action"):
+ return tool_error(f"operations[{i}] needs an 'action'.", success=False)
+ act = op["action"]
+ if act not in _BATCH_OP_ACTIONS:
+ return tool_error(
+ f"operations[{i}]: unknown action '{act}'. "
+ f"Batchable: {', '.join(sorted(_BATCH_OP_ACTIONS))}; "
+ "delete must be sole.",
+ success=False,
+ )
+ nm = op.get("name") or default_name
+ if not nm:
+ return tool_error(f"operations[{i}] needs a 'name' (the skill it targets).", success=False)
+ names.append(nm)
+ if act == "create" and nm in names[:-1]:
+ return tool_error(
+ f"operations[{i}]: create for '{nm}' must precede that "
+ "skill's other ops.",
+ success=False,
+ )
+ preflight = _background_review_preflight(act, nm)
+ if preflight is not None:
+ return json.dumps(preflight, ensure_ascii=False)
+
+ # --- intra-batch conflict guard: sequential last-wins semantics make
+ # these SILENTLY succeed while discarding earlier ops' work — always a
+ # confused plan, never intentional. Rule: a DESTRUCTIVE op (write_file,
+ # remove_file, full SKILL.md rewrite) on a file some earlier op in the
+ # batch already touched is rejected; ADDITIVE patches are always legal,
+ # so patch CHAINS (each op building on the previous text) and
+ # write-then-patch both stay allowed. Paths are normalized so spelling
+ # variants ('./references/x.md', 'references//x.md') can't slip past. ---
+ import posixpath
+
+ def _norm_target(op) -> str:
+ fp = (op.get("file_path") or "").strip()
+ if not fp:
+ return "SKILL.md"
+ return posixpath.normpath(fp.lstrip("/"))
+
+ touched_files = set() # (skill, normalized path) touched by ANY earlier op
+ for i, op in enumerate(operations):
+ act = op["action"]
+ nm = names[i]
+ # create and full-rewrite patch (content) always hit SKILL.md —
+ # _edit_skill ignores file_path on the rewrite shape.
+ full_rewrite = act == "patch" and bool(op.get("content"))
+ target = "SKILL.md" if (act == "create" or full_rewrite) else _norm_target(op)
+ key = (nm, target)
+ destructive = act in ("create", "write_file", "remove_file") or full_rewrite
+ if destructive and key in touched_files:
+ return tool_error(
+ f"operations[{i}]: {act} on '{target}' of skill '{nm}' — an "
+ "earlier op in this batch already touched that file, and this "
+ "op would silently discard its work. One destructive op "
+ "(write_file/remove_file/full rewrite) per file per batch; "
+ "put it first, or fold the change in. Patch chains are fine.",
+ success=False,
+ )
+ touched_files.add(key)
+
+ # --- approval gate: stage the WHOLE batch as one pending write ---
+ if not _skill_gate_bypass.get():
+ try:
+ from tools import write_approval as wa
+ except Exception:
+ wa = None # fail open, matching _apply_skill_write_gate
+ if wa is not None:
+ decision = wa.evaluate_gate(wa.SKILLS)
+ if decision.blocked:
+ return tool_error(decision.message, success=False)
+ if not decision.allow:
+ payload = {"action": "batch", "operations": operations}
+ acts = ", ".join(op["action"] for op in operations)
+ skills = ", ".join(sorted(set(names)))
+ gist = f"batch({len(operations)} ops: {acts}) on {skills}"
+ 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,
+ )
+
+ # --- snapshot every touched skill for rollback ---
+ snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))
+ snapshots = {} # skill name -> (pre_dir or None, snapshot_dir or None)
+ for nm in dict.fromkeys(names): # ordered unique
+ pre = _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
+ try:
+ shutil.copytree(pre_dir, snap)
+ except Exception as exc: # noqa: BLE001 — no snapshot, no atomicity
+ shutil.rmtree(snap_root, ignore_errors=True)
+ return tool_error(f"Could not snapshot '{nm}' for atomic batch: {exc}", success=False)
+ snapshots[nm] = (pre_dir, snap)
+
+ def _rollback() -> str:
+ notes = []
+ for nm, (pre_dir, snap) in snapshots.items():
+ try:
+ post = _find_skill(nm)
+ post_dir = Path(post["path"]) if post else None
+ if snap is not None:
+ if post_dir is not None and post_dir.is_dir():
+ shutil.rmtree(post_dir)
+ 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)
+ except Exception as exc: # noqa: BLE001
+ notes.append(f"ROLLBACK FAILED for '{nm}' ({exc})")
+ return "; ".join(notes) if notes else "all touched skills rolled back"
+
+ # --- execute ops through the normal single-op path (gate bypassed:
+ # the batch already cleared/staged it above; ledger + telemetry
+ # fire per-op, which is the audit granularity we want) ---
+ results = []
+ token = _skill_gate_bypass.set(True)
+ try:
+ for i, op in enumerate(operations):
+ raw = skill_manage(
+ action=op["action"],
+ name=names[i],
+ content=op.get("content"),
+ category=op.get("category"),
+ file_path=op.get("file_path"),
+ file_content=op.get("file_content"),
+ old_string=op.get("old_string"),
+ new_string=op.get("new_string"),
+ replace_all=op.get("replace_all", False),
+ task_id=task_id,
+ session_id=session_id,
+ )
+ try:
+ parsed = json.loads(raw)
+ except Exception: # noqa: BLE001
+ parsed = {"success": False, "error": "unparseable op result"}
+ if not parsed.get("success"):
+ note = _rollback()
+ return json.dumps(
+ {"success": False,
+ "error": (
+ f"operations[{i}] ({op['action']} on '{names[i]}') failed: "
+ f"{parsed.get('error', 'unknown error')} — batch aborted, {note}."
+ ),
+ "failed_index": i,
+ "completed_before_failure": i},
+ ensure_ascii=False,
+ )
+ results.append({"name": names[i], "action": op["action"],
+ "file_path": op.get("file_path"),
+ "success": True})
+ finally:
+ _skill_gate_bypass.reset(token)
+ shutil.rmtree(snap_root, ignore_errors=True)
+
+ return json.dumps(
+ {"success": True, "operations_applied": len(results),
+ "results": results},
+ ensure_ascii=False,
+ )
+
+
# Debounce state for the sync push hook. A burst of skill_manage writes
# (e.g. create + several write_file calls) collapses into a single push after
# a short quiet window, on a daemon timer so the agent write never blocks.
@@ -1586,12 +1812,22 @@ def skill_manage(
absorbed_into: str = None,
task_id: str = None,
session_id: str = None,
+ operations=None,
) -> str:
"""
Manage user-created skills. Dispatches to the appropriate action handler.
+ ``operations``: batch shape — a list of {action, ...} dicts applied to
+ ONE skill atomically (see _skill_manage_batch). When set, the flat
+ single-op fields are ignored and ``action`` may be omitted/'batch'.
+
Returns JSON string with results.
"""
+ if operations is not None:
+ return _skill_manage_batch(
+ operations, default_name=name or None,
+ task_id=task_id, session_id=session_id,
+ )
preflight = _background_review_preflight(action, name)
if preflight is not None:
return json.dumps(preflight, ensure_ascii=False)
@@ -1760,91 +1996,100 @@ def skill_manage(
SKILL_MANAGE_SCHEMA = {
"name": "skill_manage",
+ # ONE call shape (memory-tool pattern, maintainer-directed): the call
+ # IS an operations array — each op names its skill and action; a
+ # single edit is a list of one. The legacy flat shape (top-level
+ # action/name/content/...) is still ACCEPTED by the handler for old
+ # transcripts and staged-write replay, but no longer advertised.
"description": (
"Create, update, or delete skills — your procedural memory for "
- f"recurring task types. Actions: create (lands in {display_hermes_home()}/skills/), "
- "patch (targeted old_string/new_string fix — preferred), delete, "
- "write_file/remove_file (supporting files). Existing skills are "
- "modified wherever they live. Keep the description's first 57 chars "
- "a self-contained trigger: 'Use when <trigger>. <one-line "
- "behavior>.' — skill_view() shows full format conventions."
+ "recurring task types. The call is an operations array (a single "
+ "edit is a list of one); it applies atomically — any failure rolls "
+ "every touched skill back. Ops: create (full SKILL.md; lands in "
+ f"{display_hermes_home()}/skills/; must precede that skill's other "
+ "ops), patch (targeted old_string/new_string fix — preferred; "
+ "content alone REPLACES the whole file, read it via skill_view() "
+ "first), write_file/remove_file (supporting files), delete (sole "
+ "op only). Existing skills are modified wherever they live. Keep "
+ "the description's first 57 chars a self-contained trigger: 'Use "
+ "when <trigger>. <one-line behavior>.' — skill_view() shows "
+ "format conventions."
),
"parameters": {
"type": "object",
"properties": {
- "action": {
- "type": "string",
- "enum": ["create", "patch", "delete", "write_file", "remove_file"],
- "description": "The action to perform."
- },
- "name": {
- "type": "string",
- "description": (
- "Skill name (lowercase, hyphens/underscores, max 64 "
- "chars); an existing skill's name for every action "
- "except create."
- )
- },
- "content": {
- "type": "string",
- "description": (
- "Full SKILL.md content (YAML frontmatter + markdown "
- "body). Required for 'create'. On 'patch' (without "
- "old_string) it REPLACES the whole file — read it via "
- "skill_view() first."
- )
- },
- # patch args: same fuzzy-matching semantics as the `patch` tool
- # (uniqueness unless replace_all, context-for-uniqueness advice
- # lives there) — teach only the skill-specific facts here.
- "old_string": {
- "type": "string",
- "description": (
- "Text to find (for 'patch'; same matching semantics as "
- "the patch tool)."
- )
- },
- "new_string": {
- "type": "string",
- "description": (
- "Replacement text (for 'patch'); empty string deletes "
- "the match."
- )
- },
- "replace_all": {
- "type": "boolean",
- "description": "For 'patch': replace all occurrences (default: false)."
- },
- "category": {
- "type": "string",
- "description": (
- "Optional category subdirectory for 'create' (e.g. "
- "'devops', 'mlops')."
- )
- },
- "file_path": {
- "type": "string",
- "description": (
- "Path RELATIVE to the skill's own directory, e.g. "
- "'references/api.md' — no leading slash, never absolute. "
- "write_file/remove_file: required; first segment must be "
- "references/, templates/, scripts/, or assets/. patch: "
- "optional (default SKILL.md)."
- )
- },
- "file_content": {
- "type": "string",
- "description": "Content for write_file."
+ "operations": {
+ "type": "array",
+ "description": "Ordered ops; each names its target skill.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": (
+ "Skill name (lowercase, hyphens/underscores, "
+ "max 64 chars); an existing skill's name "
+ "unless creating."
+ )
+ },
+ "action": {
+ "type": "string",
+ "enum": ["create", "patch", "delete", "write_file", "remove_file"]
+ },
+ "content": {
+ "type": "string",
+ "description": (
+ "Full SKILL.md text (YAML frontmatter + "
+ "markdown body) for create, or a full "
+ "rewrite on patch."
+ )
+ },
+ "category": {
+ "type": "string",
+ "description": "Optional category subdir for create (e.g. 'devops')."
+ },
+ # patch args: same fuzzy-matching semantics as the
+ # `patch` tool — teach only skill-specific facts here.
+ "old_string": {
+ "type": "string",
+ "description": "Text to find (patch; same matching semantics as the patch tool)."
+ },
+ "new_string": {
+ "type": "string",
+ "description": "Replacement (patch); empty string deletes the match."
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": "patch: replace all occurrences (default false)."
+ },
+ "file_path": {
+ "type": "string",
+ "description": (
+ "Path RELATIVE to the skill's own directory, "
+ "e.g. 'references/api.md' — no leading slash, "
+ "never absolute. write_file/remove_file: "
+ "required; first segment references/, "
+ "templates/, scripts/, or assets/. patch: "
+ "optional (default SKILL.md)."
+ )
+ },
+ "file_content": {
+ "type": "string",
+ "description": "Content for write_file."
+ }
+ },
+ "required": ["name", "action"]
+ }
},
- # NOTE: the handler also accepts `absorbed_into` on delete — the
- # curator's consolidation pass declares merge-vs-prune intent with
- # it. Deliberately NOT advertised in this schema: only curator
- # sessions need it, the curator's own prompt documents it, and the
- # curator-context delete guard's error re-teaches it on omission
- # (_curator_consolidation_delete_guard). Keeping it out saves
- # ~100 tokens on every call of every other session.
+ # NOTE: the handler also accepts the legacy flat single-op shape
+ # (top-level action/name/content/old_string/new_string/
+ # replace_all/category/file_path/file_content) — old transcripts
+ # and staged-write replay depend on it — plus `absorbed_into` on
+ # delete ops (curator-only vocabulary; the curator's prompt
+ # documents it and the delete guard's error re-teaches it).
+ # None are advertised.
},
- "required": ["action", "name"],
+ "required": ["operations"],
},
}
@@ -1867,6 +2112,7 @@ registry.register(
new_string=args.get("new_string"),
replace_all=args.get("replace_all", False),
absorbed_into=args.get("absorbed_into"),
+ operations=args.get("operations"),
task_id=kw.get("task_id"),
session_id=kw.get("session_id")),
emoji="📝",