Skip to content

The agent that grows with you

fix(skills): render per-op diffs for staged batch skill writes

finn763b46f182f8b31
diff --git a/tests/tools/test_skill_pending_diff_batch.py b/tests/tools/test_skill_pending_diff_batch.py
new file mode 100644
index 00000000000..c5a823b2c53
--- /dev/null
+++ b/tests/tools/test_skill_pending_diff_batch.py
@@ -0,0 +1,122 @@
+"""Batch pending diff for /skills diff <id> (#123315).
+
+Writes staged through ``skill_manage`` ``operations[]`` are ``batch`` records;
+without a batch case ``skill_pending_diff`` falls through to ``(batch on '')``
+and the review-before-approve affordance never shows a diff.
+"""
+import importlib
+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: Probe skill for pending-diff tests.\n---\n"
+ "# Probe\nStep 1.\n"
+)
+
+
+class TestSkillPendingDiffBatch(unittest.TestCase):
+ def setUp(self):
+ self.home = tempfile.mkdtemp(prefix="skdiff_t_")
+ os.environ["HERMES_HOME"] = self.home
+ os.makedirs(os.path.join(self.home, "skills", "probe"), exist_ok=True)
+ with open(os.path.join(self.home, "skills", "probe", "SKILL.md"), "w",
+ encoding="utf-8") as f:
+ f.write(SK.format(n="probe"))
+ # Re-import against the temp home (skill lookup caches SKILLS_DIR).
+ import tools.skill_manager_tool as smt
+ importlib.reload(smt)
+ import tools.write_approval as wa
+ importlib.reload(wa)
+ self.wa = wa
+
+ def tearDown(self):
+ shutil.rmtree(self.home, ignore_errors=True)
+
+ def _batch_record(self):
+ return {
+ "id": "abc123",
+ "summary": "batch(2 ops: create, patch) on newprobe, probe",
+ "payload": {
+ "action": "batch",
+ "operations": [
+ {"action": "create", "name": "newprobe",
+ "content": SK.format(n="newprobe")},
+ {"action": "patch", "name": "probe",
+ "old_string": "Step 1.", "new_string": "Step ONE."},
+ ],
+ },
+ }
+
+ def test_batch_diff_renders_per_op_content(self):
+ out = self.wa.skill_pending_diff(self._batch_record())
+ self.assertNotIn("(batch on", out)
+ # create op shows the full new content
+ self.assertIn("Step 1.", out)
+ # patch op shows a unified diff against the on-disk skill
+ self.assertIn("-Step 1.", out)
+ self.assertIn("+Step ONE.", out)
+
+ def test_single_op_paths_unchanged(self):
+ create = self.wa.skill_pending_diff(
+ {"payload": {"action": "create", "name": "newprobe",
+ "content": SK.format(n="newprobe")}})
+ self.assertEqual(create, SK.format(n="newprobe"))
+ patch = self.wa.skill_pending_diff(
+ {"payload": {"action": "patch", "name": "probe",
+ "old_string": "Step 1.", "new_string": "Step ONE."}})
+ self.assertIn("-Step 1.", patch)
+ self.assertIn("+Step ONE.", patch)
+
+ def test_batch_op_diffs_against_earlier_ops_not_disk(self):
+ """A batch that creates a skill and then patches it: the patch must diff against the
+ content the create op staged, not the (absent) on-disk copy — otherwise the review
+ renders the literal '(patch ...)' fallback for the very case batches are used for."""
+ rec = {"id": "def456", "payload": {"action": "batch", "operations": [
+ {"action": "create", "name": "newprobe",
+ "content": SK.format(n="newprobe")},
+ {"action": "patch", "name": "newprobe",
+ "old_string": "Step 1.", "new_string": "Step ONE."},
+ {"action": "write_file", "name": "newprobe",
+ "file_path": "ref.md", "file_content": "x\n"},
+ {"action": "patch", "name": "newprobe", "file_path": "ref.md",
+ "old_string": "x", "new_string": "y"},
+ ]}}
+ out = self.wa.skill_pending_diff(rec)
+ self.assertNotIn("(patch", out)
+ self.assertIn("-Step 1.", out)
+ self.assertIn("+Step ONE.", out)
+ # write_file labels its own file, and the following patch diffs against its content
+ self.assertIn("a/ref.md", out)
+ self.assertIn("-x", out)
+ self.assertIn("+y", out)
+
+ def test_batch_numbering_ignores_non_dict_ops(self):
+ rec = {"id": "ghi789", "payload": {"action": "batch", "operations": [
+ "not-an-op",
+ {"action": "create", "name": "newprobe",
+ "content": SK.format(n="newprobe")},
+ ]}}
+ out = self.wa.skill_pending_diff(rec)
+ self.assertIn("## op 1/1:", out)
+ self.assertNotIn("/2:", out)
+
+ def test_diff_subcommand_end_to_end(self):
+ from hermes_cli.write_approval_commands import handle_pending_subcommand
+ rec = self.wa.stage_write(
+ self.wa.SKILLS, self._batch_record()["payload"],
+ summary="batch(2 ops) on newprobe, probe", origin="foreground")
+ out = handle_pending_subcommand(self.wa.SKILLS, ["diff", rec["id"]])
+ self.assertIsNotNone(out)
+ assert out is not None
+ self.assertIn(rec["id"], out)
+ self.assertNotIn("(batch on", out)
+ self.assertIn("+Step ONE.", out)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/write_approval.py b/tools/write_approval.py
index 0ba8306295f..289c2f84e9f 100644
--- a/tools/write_approval.py
+++ b/tools/write_approval.py
@@ -252,12 +252,35 @@ def _find_skill_path(name: str) -> Optional[Path]:
return found["path"] if found else None
-def skill_pending_diff(record: Dict[str, Any]) -> str:
- """Full content (create) or unified diff vs. the on-disk skill (edit/patch/write_file),
- rendered by /skills diff <id> on surfaces that can show it."""
+def _staged_base(name: str, target_label: str, staged: Optional[Dict[str, Dict[str, str]]]) -> str:
+ """What an op diffs against: the content earlier ops of the same batch left in this file,
+ else the on-disk copy (empty for a file that does not exist yet)."""
+ files = (staged or {}).get(name)
+ if files and target_label in files:
+ return files[target_label]
+ skill_dir = _find_skill_path(name)
+ if not skill_dir:
+ return ""
+ with suppress(Exception):
+ p = skill_dir / target_label
+ if p.exists():
+ return p.read_text(encoding="utf-8-sig")
+ return ""
+
+
+def skill_pending_diff(
+ record: Dict[str, Any], staged: Optional[Dict[str, Dict[str, str]]] = None
+) -> str:
+ """Full content (create) or unified diff vs. the base file (edit/patch/write_file),
+ rendered by /skills diff <id> on surfaces that can show it. ``staged`` carries the file
+ contents the earlier ops of a batch left behind, so op *i* diffs against ops 1..*i-1* and
+ disk is read only for files no earlier op touched. A staged batch renders each op's diff
+ under its gist header (single-op path below is unchanged)."""
payload = record.get("payload", {})
action = payload.get("action", "")
name = payload.get("name", "")
+ if action == "batch":
+ return _batch_pending_diff(payload)
if action == "create":
return payload.get("content") or ""
if action not in {"edit", "patch", "write_file"}:
@@ -265,14 +288,8 @@ def skill_pending_diff(record: Dict[str, Any]) -> str:
"delete": f"delete skill '{name}'"}.get(action, f"({action} on '{name}')")
# patch/write_file target a file inside the skill; edit always targets SKILL.md.
- target_label, current = "SKILL.md", ""
- skill_dir = _find_skill_path(name)
- if skill_dir:
- if action != "edit":
- target_label = payload.get("file_path") or "SKILL.md"
- with suppress(Exception):
- p = skill_dir / target_label
- current = p.read_text(encoding="utf-8-sig") if p.exists() else ""
+ target_label = "SKILL.md" if action == "edit" else (payload.get("file_path") or "SKILL.md")
+ current = _staged_base(name, target_label, staged)
if action == "patch":
old_s, new_s = payload.get("old_string") or "", payload.get("new_string") or ""
@@ -282,3 +299,46 @@ def skill_pending_diff(record: Dict[str, Any]) -> str:
diff = difflib.unified_diff(current.splitlines(keepends=True), new.splitlines(keepends=True),
fromfile=f"a/{target_label}", tofile=f"b/{target_label}")
return "".join(diff) or "(no textual change)"
+
+
+def _fold_staged(staged: Dict[str, Dict[str, str]], action: str, name: str,
+ op: Dict[str, Any]) -> None:
+ """Record what one op leaves in the staged view the next op diffs against."""
+ if not name:
+ return
+ if action == "delete":
+ staged.pop(name, None)
+ return
+ label = "SKILL.md" if action == "edit" else (op.get("file_path") or "SKILL.md")
+ files = staged.setdefault(name, {})
+ if action in {"create", "edit"}:
+ files["SKILL.md"] = op.get("content") or ""
+ elif action == "write_file":
+ files[label] = op.get("file_content") or ""
+ elif action == "patch":
+ files[label] = _staged_base(name, label, staged).replace(
+ op.get("old_string") or "", op.get("new_string") or "")
+ elif action == "remove_file":
+ files.pop(label, None)
+
+
+def _batch_pending_diff(payload: Dict[str, Any]) -> str:
+ """Per-op diffs for a staged ``batch`` payload (skill_manage operations[]). Ops apply in
+ order, so each op reuses the single-op path above with the earlier ops' staged content as
+ its base (disk only for files no earlier op touched) — a patch to a skill an earlier op
+ created shows a real diff, which is the case this renderer exists for."""
+ ops = [op for op in (payload.get("operations") or []) if isinstance(op, dict)]
+ total = len(ops)
+ staged: Dict[str, Dict[str, str]] = {}
+ parts = []
+ for i, op in enumerate(ops):
+ op_action, op_name = op.get("action", ""), op.get("name") or ""
+ gist = skill_gist(op_action, op_name, content=op.get("content") or "",
+ file_path=op.get("file_path") or "",
+ old_string=op.get("old_string") or "",
+ new_string=op.get("new_string") or "")
+ diff = skill_pending_diff({"payload": {**op, "name": op_name}}, staged)
+ parts.append(f"## op {i + 1}/{total}: {gist}\n\n{diff}")
+ _fold_staged(staged, op_action, op_name, op)
+ return "\n\n".join(parts) or "(empty batch)"
+