The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): skill_manage advertises one shape per action; a misfiled text slot fails before any op applies
teknium175a0649a180d
diff --git a/tests/tools/test_skill_manage_schema_diet.py b/tests/tools/test_skill_manage_schema_diet.pyindex 7bdab0ad220..b26a333a72a 100644--- a/tests/tools/test_skill_manage_schema_diet.py+++ b/tests/tools/test_skill_manage_schema_diet.py@@ -15,22 +15,29 @@ from tools.skill_manager_tool import SKILL_MANAGE_SCHEMAclass TestSkillManageSchemaDiet(unittest.TestCase):- def _op_props(self):- return SKILL_MANAGE_SCHEMA["parameters"]["properties"]["operations"]["items"]["properties"]+ def _branches(self):+ return SKILL_MANAGE_SCHEMA["parameters"]["properties"]["operations"]["items"]["anyOf"]++ def _op_props(self, action):+ """Merged properties of every branch advertising ``action``."""+ return {k: v for b in self._branches() if b["properties"]["action"]["enum"] == [action]+ for k, v in b["properties"].items()}def test_single_call_shape(self):"""Maintainer-directed: operations[] IS the interface — each opnames its skill; a single edit is a list of one. Flat fields are- handler-only compat."""+ handler-only compat. Every per-action branch is a flat op object+ (memory-tool pattern), not a nested sub-object."""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"])+ for branch in self._branches():+ self.assertEqual(branch["required"][:2], ["name", "action"])+ self.assertTrue(all(p["type"] != "object" for p in branch["properties"].values()))+ self.assertTrue(self._op_props("delete"))def test_patch_args_defer_to_patch_tool(self):- props = self._op_props()+ props = self._op_props("patch")self.assertIn("patch tool", props["old_string"]["description"])# The uniqueness/context curriculum lives in the patch tool's schema,# not here.@@ -38,7 +45,7 @@ class TestSkillManageSchemaDiet(unittest.TestCase):self.assertNotIn("surrounding context", props["old_string"]["description"])def test_file_path_states_relative_shape(self):- desc = self._op_props()["file_path"]["description"]+ desc = self._op_props("write_file")["file_path"]["description"]self.assertIn("RELATIVE", desc)self.assertIn("references/api.md", desc)self.assertIn("never absolute", desc)@@ -56,7 +63,7 @@ class TestSkillManageSchemaDiet(unittest.TestCase):self.assertIn("skill_view()", desc)self.assertNotIn("numbered steps", desc)# Stale action vocabulary must not return.- self.assertNotIn("edit", self._op_props()["name"]["description"])+ self.assertFalse(self._op_props("edit"))def test_content_keeps_pre_irreversibility_warning(self):"""The REPLACES-whole-file warning is pre-irreversibility guidance:@@ -70,3 +77,39 @@ class TestSkillManageSchemaDiet(unittest.TestCase):if __name__ == "__main__":unittest.main()+++def _fits(op, branch):+ """Plain-Python reading of one per-action branch (required + enum + additionalProperties:+ false) so the test does not need a JSON-Schema validator."""+ props = branch["properties"]+ return (set(branch["required"]) <= set(op) and set(op) <= set(props)+ and op.get("action") in props["action"]["enum"])+++class TestSkillManagePerActionShapes(unittest.TestCase):+ """#112677 — the four text slots (content / new_string / file_content / file_path) must+ not be siblings in one flat object: a create op carrying write_file's file_content+ validated against the advertised schema, so a grammar-constrained 27B model kept+ emitting it and every batch rolled back."""++ def _matches(self, op):+ return [b for b in SKILL_MANAGE_SCHEMA["parameters"]["properties"]["operations"]["items"]["anyOf"]+ if _fits(op, b)]++ def test_another_actions_text_slot_fits_no_branch(self):+ for op in ({"name": "s", "action": "create", "file_content": "# x"},+ {"name": "s", "action": "create", "new_string": "# x"},+ {"name": "s", "action": "write_file", "file_path": "references/a.md", "content": "x"},+ {"name": "s", "action": "patch", "file_content": "x"}):+ self.assertEqual(self._matches(op), [], op)++ def test_every_documented_call_shape_fits_exactly_one_branch(self):+ for op in ({"name": "s", "action": "create", "content": "# x", "category": "devops"},+ {"name": "s", "action": "patch", "old_string": "a", "new_string": "b",+ "file_path": "references/a.md", "replace_all": True},+ {"name": "s", "action": "patch", "content": "# whole file"},+ {"name": "s", "action": "write_file", "file_path": "references/a.md", "file_content": "x"},+ {"name": "s", "action": "remove_file", "file_path": "references/a.md"},+ {"name": "s", "action": "delete"}):+ self.assertEqual(len(self._matches(op)), 1, op)diff --git a/tests/tools/test_skill_manager_tool.py b/tests/tools/test_skill_manager_tool.pyindex d19995c3970..01ca0ce9564 100644--- a/tests/tools/test_skill_manager_tool.py+++ b/tests/tools/test_skill_manager_tool.py@@ -498,20 +498,37 @@ class TestSkillManageDispatcher:destination):"""#112677 — a batch op whose SKILL.md text sits in another action's key must be toldWHICH key it used and where to move it; the bare "X is required" error made a local- model replay the identical payload until the tool-loop guardrail tripped. The batch- still rolls back (atomicity unchanged), and a plain missing-content op gets no note."""+ model replay the identical payload until the tool-loop guardrail tripped. The misfiled+ op is rejected before any sibling is applied (no rollback needed), and a plain+ missing-content op gets no note."""with _skill_dir(tmp_path):_create_skill("my-skill", VALID_SKILL_CONTENT)- result = json.loads(skill_manage(action="", name="",- operations=[{"name": "my-skill", **op}]))+ result = json.loads(skill_manage(action="", name="", operations=[+ {"name": "sibling", "action": "create", "content": VALID_SKILL_CONTENT},+ {"name": "my-skill", **op}]))bare = json.loads(skill_manage(action="", name="",operations=[{"name": "other", "action": "create"}]))+ sibling_created = _find_skill("sibling") is not Noneassert result["success"] is False+ assert "operations[1]" in result["error"]assert f"'{stray_key}'" in result["error"] and destination in result["error"]- assert "rolled back" in result["error"]+ assert "rolled back" not in result["error"] and not sibling_createdassert bare["success"] is False and "file_content" not in bare["error"]+ def test_unmatched_old_string_with_stray_key_is_not_steered_to_a_rewrite(self, tmp_path):+ """#112677 — the misplaced-text note belongs to argument-shape misses only. A patch whose+ real problem is an unmatched old_string used to get "move that text to ... 'content'+ (full rewrite)" appended, steering the model toward the whole-file rewrite the patch+ error itself warns against."""+ with _skill_dir(tmp_path):+ _create_skill("my-skill", VALID_SKILL_CONTENT)+ result = json.loads(skill_manage(action="patch", name="my-skill", old_string="NOT IN FILE",+ new_string="x", file_content="stray"))++ assert result["success"] is False+ assert "move that text" not in result["error"]+def test_write_file_given_content_names_the_reverse_misplacement(self, tmp_path):"""#112677 — the reverse direction: create's `content` sent to write_file. Checked on thelegacy flat call shape so both entry points share the one hint chokepoint."""diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pyindex 2096d0ba1af..a7dd15a12d3 100644--- a/tools/skill_manager_batch.py+++ b/tools/skill_manager_batch.py@@ -14,6 +14,63 @@ logger = logging.getLogger("tools.skill_manager_tool")_BATCH_OP_ACTIONS = {"create", "patch", "write_file", "remove_file"}_BATCH_MAX_OPS = 20+# --- Per-op argument shape (checked before any effect) ---------------------------------+# action -> (arg, is_missing, error) checks run before the handler.+_MISSING, _IS_NONE = (lambda v: not v), (lambda v: v is None)+_REQUIRED_ARGS = {+ "create": [("content", _MISSING,+ "content is required for 'create'. Provide the full SKILL.md text (frontmatter + body).")],+ "edit": [("content", _MISSING,+ "content is required for a full rewrite. Provide the full updated SKILL.md text.")],+ "write_file": [+ ("file_path", _MISSING, "file_path is required for 'write_file'. Example: 'references/api-guide.md'"),+ ("file_content", _IS_NONE, "file_content is required for 'write_file'.")],+ "remove_file": [("file_path", _MISSING, "file_path is required for 'remove_file'.")]}+# A bare "required" error is a dead end: the model retries blindly and often escapes to+# action='write_file', clobbering the whole file.+_PATCH_NEEDS_OLD_STRING = (+ "old_string is required for 'patch' and must be the EXACT text currently in the file. "+ "Read the target file first (read_file on the skill's SKILL.md, or the file named by "+ "file_path) and copy the snippet verbatim, then retry 'patch'. Do NOT fall back to "+ "action='write_file' — that rewrites the entire file and destroys unrelated content.")+# Text-slot keys a model confuses: key -> the action that reads it. A 27B model that just+# used write_file's file_content re-emits it on create/patch and then replays the identical+# payload when the error only says the right key is "required" — the hint has to name where+# the text actually landed so the retry can move it.+_TEXT_SLOT_OWNER = {"content": "create (and a full-rewrite patch)",+ "new_string": "a targeted patch (with old_string)",+ "file_content": "write_file"}+# action -> (text slots it reads, where misfiled text belongs)+_TEXT_SLOT_FOR = {+ "create": (("content",), "'content'"),+ "edit": (("content",), "'content'"),+ "patch": (("content", "new_string"), "old_string/new_string (targeted) or 'content' (full rewrite, last resort)"),+ "write_file": (("file_content",), "'file_content'")}+++def _misplaced_text_hint(action: str, args: dict) -> str:+ """Sentence naming the text-slot key(s) this op carries that ``action`` never reads, or ''."""+ if action not in _TEXT_SLOT_FOR:+ return "" # delete/remove_file/unknown: no text slot, so no destination to point at+ reads, destination = _TEXT_SLOT_FOR[action]+ stray = [k for k in _TEXT_SLOT_OWNER if k not in reads and args.get(k) is not None]+ if not stray:+ return ""+ carried = " and ".join(f"'{k}' (that key is for {_TEXT_SLOT_OWNER[k]})" for k in stray)+ return f" Note: this op carries {carried} — move that text to {destination}."+++def _op_shape_error(action: str, args: dict):+ """Argument-shape error text for one op, or None. Only shape misses carry the misplaced-text+ hint: a patch whose real problem is an unmatched old_string must not be steered to a full+ rewrite. Pure function so the batch can reject a misfiled op BEFORE any sibling is applied."""+ for arg, missing, message in _REQUIRED_ARGS.get(action, ()):+ if missing(args.get(arg)):+ return message + _misplaced_text_hint(action, args)+ if action == "patch" and not args.get("old_string") and not args.get("content"):+ return _PATCH_NEEDS_OLD_STRING + _misplaced_text_hint(action, args)+ return None+def _validate_batch_ops(operations, default_name, tool_error):"""Shape checks with no side effects. Returns (names, None) or (None, error_json)."""@@ -31,6 +88,10 @@ def _validate_batch_ops(operations, default_name, tool_error):nm = op.get("name") or default_nameif not nm:return fail(i, " needs a 'name' (the skill it targets).")+ # Reject a misfiled op here, before any sibling is applied: a runtime failure on+ # op[1] would first apply op[0] and then roll the whole batch back.+ if (shape_err := _op_shape_error(act, op)) is not None:+ return fail(i, f" ({act} on '{nm}'): {shape_err}")names.append(nm)if act == "create" and nm in names[:-1]:return fail(i, f": create for '{nm}' must precede that skill's other ops.")diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex 05829ec93d5..cb741d7ec32 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -32,7 +32,7 @@ from tools.skill_manager_guards import (_background_review_preflight, _background_review_read_before_write_guard, _background_review_write_guard,_containing_skills_root, _curator_consolidation_delete_guard, _maybe_auto_propose_org_edit,_org_mirror_write_guard, _pinned_guard, _validate_delete_target, _is_background_review, _refusal as _err)-from tools.skill_manager_batch import _skill_manage_batch+from tools.skill_manager_batch import _PATCH_NEEDS_OLD_STRING, _op_shape_error, _skill_manage_batchfrom tools.skills_guard import scan_skill, should_allow_install, format_scan_reportlogger = logging.getLogger(__name__)@@ -460,13 +460,7 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = Nreplace_all: bool = False) -> Dict[str, Any]:"""Targeted find-and-replace in SKILL.md (default) or a supporting file; unique match unless replace_all."""if not old_string:- # A bare "required" error is a dead end: the model retries blindly and often- # escapes to action='write_file', clobbering the whole file.- return _err(- "old_string is required for 'patch' and must be the EXACT text currently in the file. "- "Read the target file first (read_file on the skill's SKILL.md, or the file named by "- "file_path) and copy the snippet verbatim, then retry 'patch'. Do NOT fall back to "- "action='write_file' — that rewrites the entire file and destroys unrelated content.")+ return _err(_PATCH_NEEDS_OLD_STRING)if new_string is None:return _err("new_string is required for 'patch'. Use an empty string to delete matched text.")# No old_string == new_string guard here: fuzzy_find_and_replace rejects that with a@@ -713,42 +707,6 @@ _ACTION_HANDLERS = {"delete": lambda a: _delete_skill(a["name"], absorbed_into=a["absorbed_into"]),"write_file": lambda a: _write_file(a["name"], a["file_path"], a["file_content"]),"remove_file": lambda a: _remove_file(a["name"], a["file_path"])}-# action -> (arg, is_missing, error) argument-shape checks run before the handler.-_MISSING, _IS_NONE = (lambda v: not v), (lambda v: v is None)-_REQUIRED_ARGS = {- "create": [("content", _MISSING,- "content is required for 'create'. Provide the full SKILL.md text (frontmatter + body).")],- "edit": [("content", _MISSING,- "content is required for a full rewrite. Provide the full updated SKILL.md text.")],- "write_file": [- ("file_path", _MISSING, "file_path is required for 'write_file'. Example: 'references/api-guide.md'"),- ("file_content", _IS_NONE, "file_content is required for 'write_file'.")],- "remove_file": [("file_path", _MISSING, "file_path is required for 'remove_file'.")]}-# Text-slot keys a model confuses (the schema is one flat object): key -> the action that reads it.-# A 27B model that just used write_file's file_content re-emits it on create/patch and then-# replays the identical payload when the error only says the right key is "required" — the-# hint has to name where the text actually landed so the retry can move it.-_TEXT_SLOT_OWNER = {"content": "create (and a full-rewrite patch)",- "new_string": "a targeted patch (with old_string)",- "file_content": "write_file"}-# action -> (text slots it reads, where misfiled text belongs)-_TEXT_SLOT_FOR = {- "create": (("content",), "'content'"),- "edit": (("content",), "'content'"),- "patch": (("content", "new_string"), "old_string/new_string (targeted) or 'content' (full rewrite, last resort)"),- "write_file": (("file_content",), "'file_content'")}---def _misplaced_text_hint(action: str, args: Dict[str, Any]) -> str:- """Sentence naming the text-slot key(s) this op carries that ``action`` never reads, or ''."""- if action not in _TEXT_SLOT_FOR:- return "" # delete/remove_file/unknown: no text slot, so no destination to point at- reads, destination = _TEXT_SLOT_FOR[action]- stray = [k for k in _TEXT_SLOT_OWNER if k not in reads and args.get(k) is not None]- if not stray:- return ""- carried = " and ".join(f"'{k}' (that key is for {_TEXT_SLOT_OWNER[k]})" for k in stray)- return f" Note: this op carries {carried} — move that text to {destination}."def _record_success(action, name, result, *, file_path, absorbed_into, task_id,@@ -810,9 +768,8 @@ def skill_manage(absorbed_into=absorbed_into)if (gate_result := _apply_skill_write_gate(action, name, **args)) is not None:return gate_result- for arg, missing, message in _REQUIRED_ARGS.get(action, ()):- if missing(args[arg]):- return tool_error(message + _misplaced_text_hint(action, args), success=False)+ if (shape_err := _op_shape_error(action, args)) is not None:+ return tool_error(shape_err, success=False)# Validate before the lock is keyed on the name, so a rejected name never touches .locks/# (create takes a bare name; the other actions also accept ``category/name``).if (name_err := _validate_name(name if action == "create" or not name else Path(name).name)) is not None:@@ -837,8 +794,6 @@ def skill_manage(result = handler({"name": name, **args})if isinstance(result, str):return result # tool_error JSON for argument-shape problems (patch)- if not result.get("success") and (hint := _misplaced_text_hint(action, args)):- result["error"] = result.get("error", "") + hintif result.get("success"):_record_success(action, name, result, file_path=file_path, absorbed_into=absorbed_into,@@ -874,6 +829,27 @@ def _skill_manage_schema_overrides() -> dict:return {"description": _skill_manage_description(_display_create_dir())}+_NAME = {"type": "string"}+_OLD_STRING = {"type": "string",+ "description": "Text to find (same matching semantics as the patch tool)."}+_NEW_STRING = {"type": "string", "description": "Replacement; empty string deletes the match."}+_FILE_PATH = {+ "type": "string",+ "description": (+ "Path RELATIVE to the skill's own directory, e.g. 'references/api.md' — no leading "+ "slash, never absolute; first segment references/, templates/, scripts/, or assets/."+ ),+} # stated once (write_file); patch/remove_file point at it+++def _op_schema(action: str, props: dict, required: tuple) -> dict:+ """One self-contained per-action op shape. ``additionalProperties: false`` is what lets a+ grammar-constrained backend refuse another action's text slot outright."""+ return {"type": "object", "additionalProperties": False,+ "properties": {"name": _NAME, "action": {"type": "string", "enum": [action]}, **props},+ "required": ["name", "action", *required]}++SKILL_MANAGE_SCHEMA = {"name": "skill_manage",# ONE advertised call shape (memory-tool pattern): the call IS an operations@@ -885,66 +861,40 @@ SKILL_MANAGE_SCHEMA = {"properties": {"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"]- }+ "description": (+ "Ordered ops; each names its target skill (lowercase, hyphens/underscores, "+ "max 64 chars). Each action is its own shape; another action's text slot is invalid."+ ),+ # Per-action branches, not one flat union: with one object holding content /+ # new_string / file_content side by side, a 27B model that just used write_file+ # kept emitting file_content on create and the whole batch rolled back (#112677).+ "items": {"anyOf": [+ _op_schema("create", {+ "content": {"type": "string",+ "description": "Full SKILL.md text (YAML frontmatter + markdown body)."},+ "category": {"type": "string",+ "description": "Optional category subdir (e.g. 'devops')."},+ }, ("content",)),+ _op_schema("patch", {+ "old_string": _OLD_STRING, "new_string": _NEW_STRING,+ "replace_all": {"type": "boolean",+ "description": "Replace all occurrences (default false)."},+ "file_path": {"type": "string",+ "description": "Optional supporting file (write_file's shape); default SKILL.md."},+ }, ("old_string", "new_string")),+ _op_schema("patch", {+ "content": {"type": "string",+ "description": "Full SKILL.md rewrite (REPLACES the whole file; last resort)."},+ }, ("content",)),+ _op_schema("write_file", {+ "file_path": _FILE_PATH,+ "file_content": {"type": "string", "description": "Full text of the supporting file."},+ }, ("file_path", "file_content")),+ _op_schema("remove_file", {+ "file_path": {"type": "string", "description": "Supporting file (write_file's shape)."},+ }, ("file_path",)),+ _op_schema("delete", {}, ()),+ ]},},# Also accepted, never advertised: the legacy flat single-op fields, and# `absorbed_into` on delete ops (curator-only vocabulary; the curator'sdiff --git a/website/docs/user-guide/features/skills.md b/website/docs/user-guide/features/skills.mdindex fd4fc32b569..c9924206cc8 100644--- a/website/docs/user-guide/features/skills.md+++ b/website/docs/user-guide/features/skills.md@@ -652,13 +652,20 @@ than 60 reference files). They warn; they never block a write.|--------|---------|------------|| `create` | New skill from scratch | `name`, `content` (full SKILL.md), optional `category` || `patch` | Targeted fixes (preferred) | `name`, `old_string`, `new_string` |-| `edit` | Major structural rewrites | `name`, `content` (full SKILL.md replacement) |+| `patch` with `content` | Major structural rewrites (replaces the whole SKILL.md; `edit` is the legacy alias) | `name`, `content` || `delete` | Remove a skill entirely | `name` || `write_file` | Add/update supporting files | `name`, `file_path`, `file_content` || `remove_file` | Remove a supporting file | `name`, `file_path` |+Each action is advertised as its own shape: the text slot belongs to one action only+(`content` → create / full rewrite, `new_string` → targeted patch, `file_content` →+write_file). An op that carries another action's slot — e.g. `file_content` on a+`create` — is invalid against the tool schema (grammar-constrained local backends never+emit it) and, if it arrives anyway, is rejected **before any op in the batch is+applied**, with an error naming the key the text sits in and where to move it.+:::tip-The `patch` action is preferred for updates — it's more token-efficient than `edit` because only the changed text appears in the tool call.+The targeted `patch` is preferred for updates — it's more token-efficient than a full rewrite because only the changed text appears in the tool call.:::### Gating agent skill writes (`skills.write_approval`)