diff --git a/hermes_cli/curator.py b/hermes_cli/curator.py index 96a53f35af..c6bdf6d01c 100644 --- a/hermes_cli/curator.py +++ b/hermes_cli/curator.py @@ -653,7 +653,9 @@ def _cmd_purge(args) -> int: purged = 0 for p in sorted(candidates): - before = skill_ledger.capture_before(p) + before = skill_ledger.capture_before( + p, complete_package=True, skill=p.name + ) try: shutil.rmtree(p) except OSError as e: diff --git a/tests/tools/test_skill_ledger.py b/tests/tools/test_skill_ledger.py index 0fd748403b..7243c480ad 100644 --- a/tests/tools/test_skill_ledger.py +++ b/tests/tools/test_skill_ledger.py @@ -365,3 +365,196 @@ def test_user_actor_override(ledger_env): skill_ledger.reset_ledger_actor(tok) entry = skill_ledger.get_entry(entry_id) assert entry["actor"] == "user" + + +# --------------------------------------------------------------------------- +# Package-completeness fill from the newest curator backup (issue #96962) +# --------------------------------------------------------------------------- + + +def _write_skills_tarball(home: Path, files: dict, stamp: str = "2026-08-01T00-00-00Z"): + """Write a curator-shaped ``skills.tar.gz`` under *home* (arcnames are + relative to skills/, exactly like agent.curator_backup.snapshot_skills).""" + import io + import tarfile + + snap = home / "skills" / ".curator_backups" / stamp + snap.mkdir(parents=True, exist_ok=True) + tar_path = snap / "skills.tar.gz" + with tarfile.open(tar_path, "w:gz") as tf: + for rel, content in files.items(): + data = content.encode("utf-8") if isinstance(content, str) else content + info = tarfile.TarInfo(name=rel) + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + return tar_path + + +def test_delete_after_rehome_ledgers_full_package_from_backup(ledger_env): + """The incident shape (#96962): consolidation re-homes references/ out of + the tree, then deletes. The delete entry must still capture the support + file from the newest curator backup, and rollback must restore both.""" + from tools import skill_ledger + from tools.skill_manager_tool import skill_manage + + assert _create()["success"] is True + extra = ledger_env["skills"] / "my-skill" / "references" / "extra.md" + wrote = json.loads(skill_manage( + action="write_file", + name="my-skill", + file_path="references/extra.md", + file_content="roadmap body", + )) + assert wrote["success"] is True + + # The pre-curator-run snapshot, taken while the package was whole. + skill_md = ledger_env["skills"] / "my-skill" / "SKILL.md" + _write_skills_tarball( + ledger_env["home"], + { + "my-skill/SKILL.md": skill_md.read_text(encoding="utf-8"), + "my-skill/references/extra.md": "roadmap body", + }, + ) + + # Re-home: the support file leaves the tree before the delete. + extra.unlink() + extra.parent.rmdir() + + deleted = json.loads(skill_manage(action="delete", name="my-skill")) + assert deleted["success"] is True + + delete_entry = [ + r for r in skill_ledger.list_entries(skill="my-skill") + if r["action"] == "delete" + ][0] + before_names = {Path(i["path"]).name for i in delete_entry["before"]} + assert "SKILL.md" in before_names + assert "extra.md" in before_names, ( + "delete ledger captured only SKILL.md after the support files were " + "re-homed — rollback would restore a hollow skill (#96962)" + ) + + ok, msg = skill_ledger.rollback_entry(delete_entry["id"]) + assert ok is True, msg + assert skill_md.is_file() + assert extra.is_file() + assert extra.read_text(encoding="utf-8") == "roadmap body" + + +def test_rollback_historical_hollow_entry_restores_full_package(ledger_env): + """Entries recorded BEFORE this fix (files: 1) still restore the whole + package: rollback-time fill from the newest curator backup.""" + from tools import skill_ledger + + skill_dir = ledger_env["skills"] / "my-skill" + skill_dir.mkdir() + skill_md = skill_dir / "SKILL.md" + skill_md.write_text(VALID_SKILL_CONTENT, encoding="utf-8") + _write_skills_tarball( + ledger_env["home"], + { + "my-skill/SKILL.md": VALID_SKILL_CONTENT, + "my-skill/references/roadmap.md": "week 1", + }, + ) + # The mutation that made the entry: package gone, only SKILL.md captured. + skill_md.unlink() + skill_dir.rmdir() + + entry_id = skill_ledger.append_entry( + "delete", + "my-skill", + before=[{"path": str(skill_md), "sha256": skill_ledger._store_blob( + VALID_SKILL_CONTENT.encode("utf-8") + )}], + after=[], + ) + assert entry_id is not None + + ok, msg = skill_ledger.rollback_entry(entry_id) + assert ok is True, msg + roadmap = skill_dir / "references" / "roadmap.md" + assert skill_md.is_file() + assert roadmap.is_file(), "hollow rollback: support file not restored" + assert roadmap.read_text(encoding="utf-8") == "week 1" + + +def test_delete_rollback_without_backup_still_works(ledger_env): + """No curator backup present: the fill degrades to the old behavior and + must not break the plain delete -> rollback round trip.""" + from tools import skill_ledger + from tools.skill_manager_tool import skill_manage + + assert _create()["success"] is True + skill_md = ledger_env["skills"] / "my-skill" / "SKILL.md" + + deleted = json.loads(skill_manage(action="delete", name="my-skill")) + assert deleted["success"] is True + delete_entry = [ + r for r in skill_ledger.list_entries(skill="my-skill") + if r["action"] == "delete" + ][0] + assert {Path(i["path"]).name for i in delete_entry["before"]} == {"SKILL.md"} + + ok, msg = skill_ledger.rollback_entry(delete_entry["id"]) + assert ok is True, msg + assert skill_md.read_text(encoding="utf-8") == VALID_SKILL_CONTENT + + +def test_backup_fill_does_not_clobber_disk_hash(ledger_env): + """Disk state wins: a live SKILL.md that differs from the backup copy is + captured with the LIVE hash; the backup only fills missing paths.""" + from tools import skill_ledger + + skill_dir = ledger_env["skills"] / "my-skill" + skill_dir.mkdir() + skill_md = skill_dir / "SKILL.md" + live = VALID_SKILL_CONTENT.replace("Original body.", "Live body.") + skill_md.write_text(live, encoding="utf-8") + _write_skills_tarball( + ledger_env["home"], + { + "my-skill/SKILL.md": VALID_SKILL_CONTENT, + "my-skill/references/extra.md": "from tar", + }, + ) + + captured = skill_ledger.snapshot_paths(skill_dir, complete_package=True) + by_name = {Path(i["path"]).name: i["sha256"] for i in captured} + live_hash = skill_ledger._store_blob(live.encode("utf-8")) + tar_hash = skill_ledger._store_blob(VALID_SKILL_CONTENT.encode("utf-8")) + assert by_name["SKILL.md"] == live_hash, "disk hash must win over backup" + assert by_name["SKILL.md"] != tar_hash + assert by_name["extra.md"] == skill_ledger._store_blob(b"from tar") + + +def test_backup_fill_ignores_tar_path_traversal(ledger_env): + """Fill runs AND malicious members are rejected: a legitimate missing + file is restored while members escaping the package prefix (absolute, + ..) are never filled. Both assertions matter — the positive one keeps + this test honest (a silently inert fill would pass a negatives-only + check), the negative one pins the traversal defense.""" + from tools import skill_ledger + + skill_dir = ledger_env["skills"] / "my-skill" + skill_dir.mkdir() + (skill_dir / "SKILL.md").write_text(VALID_SKILL_CONTENT, encoding="utf-8") + _write_skills_tarball( + ledger_env["home"], + { + "my-skill/SKILL.md": VALID_SKILL_CONTENT, + "my-skill/references/legit.md": "legit body", + "../evil.md": "nope", + "my-skill/../outside.md": "nope", + }, + ) + + captured = skill_ledger.snapshot_paths(skill_dir, complete_package=True) + paths = [i["path"] for i in captured] + # The legitimate missing file WAS filled — proof the fill is live. + assert any(p.endswith("references/legit.md") for p in paths), ( + "package fill did not restore the missing support file" + ) + # Malicious members are not. + assert not any(p.endswith("evil.md") or p.endswith("outside.md") for p in paths) diff --git a/tools/skill_ledger.py b/tools/skill_ledger.py index bff84f0b56..348e2ed1a9 100644 --- a/tools/skill_ledger.py +++ b/tools/skill_ledger.py @@ -31,6 +31,8 @@ import hashlib import json import logging import os +import re +import tarfile import uuid from datetime import datetime, timezone from pathlib import Path @@ -43,6 +45,18 @@ logger = logging.getLogger(__name__) ACTOR_CURATOR = "curator" ACTOR_AGENT = "agent" ACTOR_USER = "user" + +# Snapshot-id shape used by agent.curator_backup (kept in sync by the +# test suite; duplicated here so the ledger can read the newest +# skills.tar.gz without importing the backup stack). +_BACKUP_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z(-\d{2})?$") +# ".archive/-YYYYMMDDHHMMSS" collision suffix added by archive_skill. +_ARCHIVE_TS_SUFFIX_RE = re.compile(r"^(.+)-\d{14}$") +# Actions whose rollback must restore a COMPLETE skill package. These are +# the actions where a hollow before-capture (support files re-homed out of +# the tree first) makes `hermes curator rollback` restore a shell of a +# skill instead of the package (issue #96962). +_PACKAGE_RESTORE_ACTIONS = frozenset({"delete", "archive", "purge"}) _VALID_ACTORS = {ACTOR_CURATOR, ACTOR_AGENT, ACTOR_USER} # Explicit actor override for call sites that know who they are acting for: @@ -135,11 +149,22 @@ def read_blob(sha256: str) -> Optional[bytes]: return None -def snapshot_paths(root: Optional[Path]) -> List[Dict[str, str]]: +def snapshot_paths( + root: Optional[Path], + *, + complete_package: bool = False, +) -> List[Dict[str, str]]: """Capture {path, sha256} for every file under *root* (recursively), storing each file's content as a blob. Empty list when root is None or doesn't exist. Raises on I/O failure — callers decide whether that is - fatal (rollback safety capture) or swallowed (telemetry hooks).""" + fatal (rollback safety capture) or swallowed (telemetry hooks). + + ``complete_package=True`` unions in files from the newest curator + ``skills.tar.gz`` for this skill (issue #96962). Consolidation re-homes + ``references/`` / ``scripts/`` out of the tree before the + delete/archive, so a disk-only capture ledgers ``files: 1`` and + rollback would restore a hollow skill. Disk hashes win over the + backup copy.""" if root is None: return [] root = Path(root) @@ -148,11 +173,210 @@ def snapshot_paths(root: Optional[Path]) -> List[Dict[str, str]]: elif root.is_dir(): files = sorted(p for p in root.rglob("*") if p.is_file()) else: - return [] + files = [] + if not complete_package: + return [] out: List[Dict[str, str]] = [] for f in files: data = f.read_bytes() out.append({"path": str(f), "sha256": _store_blob(data)}) + if complete_package: + out = fill_snapshot_from_curator_backup(root, out) + return out + + +# --------------------------------------------------------------------------- +# Package-completeness fill from the newest curator backup (issue #96962) +# --------------------------------------------------------------------------- + +def _skills_dir() -> Path: + return get_hermes_home() / "skills" + + +def _package_rel(root: Path) -> Optional[str]: + """Relative POSIX path of a skill directory under ``skills/``, or None + when *root* is not inside the local skills dir. Backup / hub metadata + roots are excluded — they are never a skill package.""" + try: + rel = Path(os.path.normpath(str(root))).relative_to( + Path(os.path.normpath(str(_skills_dir()))) + ) + except ValueError: + return None + posix = rel.as_posix().strip("/") + if not posix: + return None + top = posix.split("/", 1)[0] + if top in {".curator_backups", ".hub", ".archive"}: + return None + return posix + + +def _strip_archive_timestamp(name: str) -> str: + match = _ARCHIVE_TS_SUFFIX_RE.match(name) + return match.group(1) if match else name + + +def package_prefixes( + root: Optional[Path] = None, + skill: Optional[str] = None, + before: Optional[List[Dict[str, str]]] = None, +) -> List[str]: + """Tar member prefixes that belong to this skill's package. + + Every spelling the package may carry: its live location under + ``skills/``, the bare skill name, the name minus an archive collision + suffix, and — for rollback-time fills where *root* is gone — the + package parent recorded in the before-state SKILL.md paths.""" + found: List[str] = [] + + def add(prefix: Optional[str]) -> None: + if not prefix: + return + prefix = prefix.strip("/") + if prefix and prefix not in found: + found.append(prefix) + + if root is not None: + add(_package_rel(Path(root))) + for item in before or []: + path = Path(str(item.get("path", ""))) + if path.name == "SKILL.md": + add(_package_rel(path.parent)) + if skill: + add(skill) + add(_strip_archive_timestamp(skill)) + return found + + +def _latest_skills_tarball() -> Optional[Path]: + """Newest ``skills.tar.gz`` under ``skills/.curator_backups/``.""" + backups = _skills_dir() / ".curator_backups" + if not backups.is_dir(): + return None + candidates: List[Path] = [] + try: + children = list(backups.iterdir()) + except OSError: + return None + for child in children: + if not child.is_dir() or not _BACKUP_ID_RE.match(child.name): + continue + archive = child / "skills.tar.gz" + if archive.is_file(): + candidates.append(archive) + if not candidates: + return None + # Parent dirs sort lexicographically == chronologically for the id shape. + candidates.sort(key=lambda p: p.parent.name, reverse=True) + return candidates[0] + + +def _read_package_files_from_latest_backup(prefixes: List[str]) -> Dict[str, bytes]: + """``{posix-relpath: bytes}`` for files under *prefixes* in the newest + snapshot. Malicious member names (absolute, ``..`` traversal) are + rejected.""" + if not prefixes: + return {} + archive = _latest_skills_tarball() + if archive is None: + return {} + prefixed = tuple(p if p.endswith("/") else p + "/" for p in prefixes) + exact = set(prefixes) + out: Dict[str, bytes] = {} + try: + with tarfile.open(archive, "r:gz") as tf: + for member in tf.getmembers(): + if not member.isfile(): + continue + name = member.name.replace("\\", "/").lstrip("./") + if not name or name.startswith("/") or ".." in Path(name).parts: + continue + if name not in exact and not name.startswith(prefixed): + continue + extracted = tf.extractfile(member) + if extracted is None: + continue + out[name] = extracted.read() + except (OSError, tarfile.TarError) as exc: + logger.debug("skill_ledger: could not read curator backup package: %s", exc) + return {} + return out + + +def fill_snapshot_from_curator_backup( + root: Optional[Path], + existing: Optional[List[Dict[str, str]]] = None, + *, + skill: Optional[str] = None, +) -> List[Dict[str, str]]: + """Union missing skill-package files from the newest curator snapshot. + + Completeness fill, not a gate: failures are swallowed and the existing + capture is returned unchanged. Disk/already-ledgered hashes win — the + backup only fills paths ABSENT from *existing*. + + Filled files are addressed where the rollback must restore them: under + *root* itself when it is known (delete/archive/purge all restore to the + captured location — for purge that is ``.archive//``, NOT the + live tree), else under the live skills dir. Backup members carry a + leading package-dir segment (arcname = top-level dir name); it is + stripped when *root* already names the package. Every fill target must + stay under ``skills/`` and HERMES_HOME. + """ + out = list(existing or []) + prefixes = package_prefixes(root, skill, out) + if not prefixes: + return out + try: + extra = _read_package_files_from_latest_backup(prefixes) + except Exception as exc: + logger.debug("skill_ledger: backup package fill failed: %s", exc) + return out + if not extra: + return out + skills = _skills_dir() + dest_root = Path(root) if root is not None else None + pkg_name = ( + _strip_archive_timestamp(dest_root.name) if dest_root is not None else None + ) + have = set() + for item in out: + path = Path(str(item.get("path", ""))) + try: + have.add( + Path(os.path.normpath(str(path))) + .relative_to(Path(os.path.normpath(str(skills)))) + .as_posix() + ) + except ValueError: + continue + for rel, data in extra.items(): + parts = rel.split("/") + if dest_root is not None and parts and parts[0] in (pkg_name, dest_root.name): + parts = parts[1:] + if not parts: + continue + base = dest_root if dest_root is not None else skills + dest = base.joinpath(*parts) + if not _is_within(skills, dest) or not _is_within(get_hermes_home(), dest): + continue + try: + rel_key = ( + Path(os.path.normpath(str(dest))) + .relative_to(Path(os.path.normpath(str(skills)))) + .as_posix() + ) + except ValueError: + continue + if rel_key in have: + continue + try: + out.append({"path": str(dest), "sha256": _store_blob(data)}) + except Exception as exc: + logger.debug("skill_ledger: backup blob store failed for %s: %s", rel, exc) + continue + have.add(rel_key) return out @@ -204,12 +428,21 @@ def record_mutation( ) -> Optional[str]: """One-stop hook for mutation call sites: capture after-state from *after_root* (pre-captured *before* list, or capture from *before_root*) - and append. NEVER raises and never blocks the mutation.""" + and append. NEVER raises and never blocks the mutation. + + Package-destroying actions (delete/archive/purge) always capture a + COMPLETE package: re-homed support files are filled in from the newest + curator backup so a rollback never restores a hollow skill (#96962).""" if not ledger_enabled(): return None try: + _complete = action in _PACKAGE_RESTORE_ACTIONS if before is None: - before = snapshot_paths(before_root) + before = snapshot_paths(before_root, complete_package=_complete) + elif _complete: + before = fill_snapshot_from_curator_backup( + before_root, before, skill=skill + ) after = snapshot_paths(after_root) return append_entry( action, skill, before=before, after=after, actor=actor, evidence=evidence @@ -219,13 +452,25 @@ def record_mutation( return None -def capture_before(root: Optional[Path]) -> Optional[List[Dict[str, str]]]: +def capture_before( + root: Optional[Path], + *, + complete_package: bool = False, + skill: Optional[str] = None, +) -> Optional[List[Dict[str, str]]]: """Best-effort pre-mutation capture. Returns None on failure or when the - ledger is disabled (callers pass the result straight to record_mutation).""" + ledger is disabled (callers pass the result straight to record_mutation). + + ``complete_package=True`` fills support files from the newest curator + backup — required for delete/archive/purge captures, where consolidation + may have re-homed the support files out of the tree first (#96962).""" if not ledger_enabled(): return None try: - return snapshot_paths(root) + captured = snapshot_paths(root) + if complete_package: + captured = fill_snapshot_from_curator_backup(root, captured, skill=skill) + return captured except Exception as e: logger.warning("skill_ledger: before-capture failed (%s) — mutation unaffected", e) return None @@ -314,8 +559,28 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]: if path_err: return False, f"refusing rollback: {path_err}" - before = entry.get("before") or [] - after = entry.get("after") or [] + before = list(entry.get("before") or []) + after = list(entry.get("after") or []) + + # Historical hollow entries (#96962): a delete/archive/purge captured + # only what was left after consolidation re-homed the support files + # (``files: 1`` = SKILL.md). Fill the before-state from the newest + # curator backup so the rollback restores the complete package, not a + # shell. Disk hashes already in the entry win; this only adds missing + # paths. The filled set is re-validated against HERMES_HOME below. + if entry.get("action") in _PACKAGE_RESTORE_ACTIONS: + skill_root: Optional[Path] = None + for item in before: + p = Path(str(item.get("path", ""))) + if p.name == "SKILL.md": + skill_root = p.parent + break + before = fill_snapshot_from_curator_backup( + skill_root, 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}" # Pre-check every blob we need so we never fail mid-restore. for item in before: diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py index d5c2fb7ec8..058b21f390 100644 --- a/tools/skill_manager_tool.py +++ b/tools/skill_manager_tool.py @@ -1954,7 +1954,15 @@ def skill_manage( from tools import skill_ledger as _ledger _pre = _find_skill(name) _ledger_before_dir = _pre["path"] if _pre else None - _ledger_before = _ledger.capture_before(_ledger_before_dir) + # delete destroys the whole package; consolidation may have re-homed + # support files out of the tree first, so complete the capture from + # the newest curator backup or rollback restores a hollow skill + # (#96962). Other actions capture disk state only. + _ledger_before = _ledger.capture_before( + _ledger_before_dir, + complete_package=(action == "delete"), + skill=name, + ) except Exception: pass diff --git a/tools/skill_usage.py b/tools/skill_usage.py index 2bd076388e..aa7e616daa 100644 --- a/tools/skill_usage.py +++ b/tools/skill_usage.py @@ -1115,10 +1115,15 @@ def archive_skill(skill_name: str) -> Tuple[bool, str]: dest = archive_root / f"{skill_dir.name}-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}" # Audit ledger pre-capture (best-effort; never blocks the archive). + # complete_package: consolidation may have re-homed support files out of + # the tree first, so a disk-only capture can come back hollow; the fill + # from the newest curator backup keeps rollback restorable (#96962). _ledger_before = None try: from tools import skill_ledger as _ledger - _ledger_before = _ledger.capture_before(skill_dir) + _ledger_before = _ledger.capture_before( + skill_dir, complete_package=True, skill=skill_name + ) except Exception: _ledger = None # type: ignore[assignment]