Skip to content

The agent that grows with you

fix(curator): tarball skips regeneratable dirs; `ledger --compact` garbage-collects blobs

teknium14fc3e9be85b8
diff --git a/agent/curator_backup.py b/agent/curator_backup.py
index 5fb2a7acd3f..f0ff46c8d87 100644
--- a/agent/curator_backup.py
+++ b/agent/curator_backup.py
@@ -40,6 +40,17 @@ DEFAULT_KEEP = 2
# skills held the CLI prompt for 6 minutes).
_EXCLUDE_TOP_LEVEL = {".curator_backups", ".hub", ".locks", ".git", ".archive", ".curator_ledger.jsonl"}
+
+def _excluded_member(ti: tarfile.TarInfo) -> bool:
+ """Skip excluded names anywhere in the path, plus regeneratable DIRECTORIES (venv, node_modules,
+ caches — a 1.3 GB torch venv inside one skill made every snapshot 349 MB, #107539). Directory
+ parts only: a plain file that happens to be called ``venv`` is skill content."""
+ from tools.skill_ledger import TRANSIENT_DIRS
+
+ parts = Path(ti.name).parts
+ dir_parts = parts if ti.isdir() else parts[:-1]
+ return any(p in _EXCLUDE_TOP_LEVEL for p in parts) or any(p in TRANSIENT_DIRS for p in dir_parts)
+
# Snapshot id: UTC ISO with colons replaced by dashes (Windows-safe filename); optional ``-NN`` suffix for same-second snapshots.
_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z(-\d{2})?$")
@@ -163,9 +174,9 @@ def snapshot_skills(reason: str = "manual", *, protect_ids: Optional[Set[str]] =
with tarfile.open(archive, "w:gz", compresslevel=6) as tf:
for entry in sorted(skills.iterdir()):
if entry.name not in _EXCLUDE_TOP_LEVEL:
- # arcname relative to skills/ so extraction drops back in cleanly; the filter excludes nested _EXCLUDE_TOP_LEVEL paths too.
+ # arcname relative to skills/ so extraction drops back in cleanly; the filter excludes nested paths too.
tf.add(str(entry), arcname=entry.name, recursive=True,
- filter=lambda ti: None if any(p in _EXCLUDE_TOP_LEVEL for p in Path(ti.name).parts) else ti)
+ filter=lambda ti: None if _excluded_member(ti) else ti)
# Cron capture is additive and never fails the snapshot; the manifest records whether it happened so rollback can say "no cron data".
_write_manifest(dest, reason, archive, _count_skill_files(skills), _backup_cron_jobs_into(dest))
except (OSError, tarfile.TarError) as e:
@@ -327,15 +338,19 @@ def _restore_excluded_subtrees(staged: Path, skills: Path) -> None:
(submodule / worktree ``gitdir:`` pointer) — both are moved. Best-effort and conditional: an entry is carried only when
its parent skill dir was restored and nothing sits at the target. If the target snapshot predates the skill, the entry
is dropped with the staging dir rather than left orphaned; the safety snapshot excludes these paths too, so not undoable."""
+ from tools.skill_ledger import TRANSIENT_DIRS
+
for dirpath, dirnames, filenames in os.walk(staged):
- for src in [Path(dirpath) / n for n in (*dirnames, *filenames) if n in _EXCLUDE_TOP_LEVEL]:
+ carried = [Path(dirpath) / n for n in filenames if n in _EXCLUDE_TOP_LEVEL]
+ carried += [Path(dirpath) / n for n in dirnames if n in _EXCLUDE_TOP_LEVEL or n in TRANSIENT_DIRS]
+ for src in carried:
dest = skills / src.relative_to(staged)
if dest.parent.is_dir() and not dest.exists():
try:
shutil.move(str(src), str(dest))
except OSError as e:
logger.debug("Could not restore excluded entry %s: %s", src, e)
- dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_TOP_LEVEL]
+ dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_TOP_LEVEL and d not in TRANSIENT_DIRS]
def _unstage(moved: List[Tuple[Path, Path]]) -> List[str]:
diff --git a/hermes_cli/curator.py b/hermes_cli/curator.py
index c2f9745104c..e7b43aaf670 100644
--- a/hermes_cli/curator.py
+++ b/hermes_cli/curator.py
@@ -389,7 +389,9 @@ def _cmd_ledger(args) -> int:
from tools import skill_ledger
if getattr(args, "compact", False):
entries, before, after = skill_ledger.compact_ledger()
- print(f"curator: ledger compacted — {entries} entries, {before / 2**20:.1f} MB → {after / 2**20:.1f} MB")
+ blobs, freed = skill_ledger.gc_blobs()
+ print(f"curator: ledger compacted — {entries} entries, {before / 2**20:.1f} MB → {after / 2**20:.1f} MB; "
+ f"{blobs} unreferenced blob(s) removed ({freed / 2**20:.1f} MB)")
return 0
rows = skill_ledger.list_entries(
skill=getattr(args, "skill", None), limit=getattr(args, "limit", None) or 20)
diff --git a/tests/agent/test_curator_backup.py b/tests/agent/test_curator_backup.py
index 98100082b7f..53f29186b0f 100644
--- a/tests/agent/test_curator_backup.py
+++ b/tests/agent/test_curator_backup.py
@@ -548,6 +548,30 @@ def test_snapshot_and_rollback_leave_ledger_and_archive_alone(backup_env):
assert (skills / ".archive" / "pruned-later" / "SKILL.md").exists()
+def test_snapshot_skips_nested_venv_and_rollback_carries_it_back(backup_env):
+ """A regeneratable dir inside a skill (venv, node_modules) is never tarred — one torch venv made
+ every snapshot 349 MB (#107539) — and rollback moves the live copy back rather than dropping it.
+ A plain FILE named ``venv`` is skill content and stays in."""
+ cb, skills = backup_env["cb"], backup_env["skills"]
+ _write_skill(skills, "alpha", body="v1")
+ (skills / "alpha" / "venv" / "lib").mkdir(parents=True)
+ (skills / "alpha" / "venv" / "lib" / "big.so").write_bytes(b"x" * 4096)
+ (skills / "alpha" / "scripts").mkdir()
+ (skills / "alpha" / "scripts" / "venv").write_text("#!/bin/sh\n", encoding="utf-8")
+
+ snap_dir = cb.snapshot_skills(reason="snap-v1")
+ with tarfile.open(snap_dir / "skills.tar.gz", "r:gz") as tf:
+ members = set(tf.getnames())
+ assert "alpha/scripts/venv" in members
+ assert not any(n.startswith("alpha/venv") for n in members), members
+
+ _write_skill(skills, "alpha", body="v2")
+ ok, msg, _ = cb.rollback(snap_dir.name)
+ assert ok, msg
+ assert "v1" in (skills / "alpha" / "SKILL.md").read_text(encoding="utf-8")
+ assert (skills / "alpha" / "venv" / "lib" / "big.so").exists(), "live venv carried back after rollback"
+
+
def test_rollback_preserves_top_level_git(backup_env):
"""Rollback must preserve repository .git metadata untouched in the skills root."""
cb = backup_env["cb"]
diff --git a/tests/tools/test_skill_ledger_delta.py b/tests/tools/test_skill_ledger_delta.py
index bb59ab2c49e..ebd52c889f6 100644
--- a/tests/tools/test_skill_ledger_delta.py
+++ b/tests/tools/test_skill_ledger_delta.py
@@ -70,3 +70,25 @@ def test_compact_rewrites_legacy_full_manifests_in_place(ledger_home):
assert {Path(i["path"]).name for i in by_id["abc123"]["before"]} == {"SKILL.md"}
assert len(by_id["def456"]["before"]) == 50, "pre-rollback safety entries keep their full capture"
assert "not json" in path.read_text(encoding="utf-8")
+
+
+def test_gc_blobs_removes_only_unreferenced(ledger_home):
+ """The blob store was write-only (#107539): after compaction, blobs no entry references are
+ deleted; every referenced blob survives so any entry can still roll back."""
+ from tools import skill_ledger
+ skills = ledger_home / "skills"
+ kept = _manifest(skills, "s", **{"SKILL.md": "v1"})
+ skill_ledger.append_entry("create", "s", before=[], after=kept, actor="agent")
+ orphan = skill_ledger._store_blob(b"never referenced by any entry")
+ assert (skill_ledger.blobs_dir() / orphan).exists()
+
+ deleted, freed = skill_ledger.gc_blobs()
+ assert (deleted, freed) == (1, len(b"never referenced by any entry"))
+ assert not (skill_ledger.blobs_dir() / orphan).exists()
+ assert skill_ledger.read_blob(kept[0]["sha256"]) == b"v1"
+
+ # A malformed line might hold references we cannot read: the sweep refuses rather than guesses.
+ with open(skill_ledger.ledger_path(), "a", encoding="utf-8") as fh:
+ fh.write("{broken\n")
+ skill_ledger._store_blob(b"orphan two")
+ assert skill_ledger.gc_blobs() == (0, 0)
diff --git a/tools/skill_ledger.py b/tools/skill_ledger.py
index 812aba0717c..eeceba5395e 100644
--- a/tools/skill_ledger.py
+++ b/tools/skill_ledger.py
@@ -299,7 +299,8 @@ def append_entry(
def compact_ledger() -> Tuple[int, int, int]:
"""Rewrite the ledger with every entry's unchanged paths dropped (see ``_delta``); ids, order and
rollback semantics are preserved. Returns ``(entries, bytes_before, bytes_after)``. Atomic: the
- new file replaces the old only once fully written. Malformed lines are kept verbatim."""
+ new file replaces the old only once fully written. Malformed lines are kept verbatim. Follow with
+ ``gc_blobs()``: dropped references leave blobs nothing can restore."""
path = ledger_path()
try:
raw = path.read_bytes()
@@ -326,6 +327,41 @@ def compact_ledger() -> Tuple[int, int, int]:
return kept, len(raw), len(data)
+def gc_blobs() -> Tuple[int, int]:
+ """Delete blobs no ledger entry references; returns ``(deleted, bytes_freed)``. The store was
+ write-only: on one install 98.9% of 47k blobs (1.18 GB) were unreachable after a venv walk
+ (#107539). Malformed ledger lines abort the sweep (nothing deleted) — an unreadable entry
+ may still hold references."""
+ blobs = blobs_dir()
+ if not blobs.is_dir():
+ return 0, 0
+ referenced: set = set()
+ try:
+ lines = ledger_path().read_text(encoding="utf-8").splitlines()
+ except OSError:
+ lines = []
+ for line in lines:
+ if not line.strip():
+ continue
+ try:
+ row = json.loads(line)
+ except json.JSONDecodeError:
+ return 0, 0
+ for item in (row.get("before") or []) + (row.get("after") or []):
+ referenced.add(str(item.get("sha256", "")))
+ deleted = freed = 0
+ for blob in blobs.iterdir():
+ if blob.is_file() and blob.name not in referenced:
+ try:
+ size = blob.stat().st_size
+ blob.unlink()
+ except OSError:
+ continue
+ deleted += 1
+ freed += size
+ return deleted, freed
+
+
def record_mutation(
action: str, skill: str, before_root: Optional[Path] = None,
before: Optional[List[Dict[str, str]]] = None, after_root: Optional[Path] = None,