#!/usr/bin/env python3 """Limpa output/runs/: remove execuções com falha ou canceladas e sucessos antigos, mantendo os N mais recentes por (configuração, perfil). Nunca remove a execução de last-success.json. Por padrão só MOSTRA o que removeria. Use --apply para apagar. Uso: python .claude/skills/cenaforge/scripts/clean_runs.py [--keep 2] [--apply] """ from __future__ import annotations import argparse import shutil from collections import defaultdict from _common import LAST_SUCCESS, RUNS_DIR, load_json, rel, utf8_stdout def main() -> int: utf8_stdout() ap = argparse.ArgumentParser(description="Limpa execuções antigas de output/runs/.") ap.add_argument("--keep", type=int, default=2, help="sucessos mantidos por configuração e perfil") ap.add_argument("--apply", action="store_true", help="apaga de fato (sem isto, só simula)") args = ap.parse_args() protected = load_json(LAST_SUCCESS).get("runDir") if LAST_SUCCESS.is_file() else None kept: dict[tuple, int] = defaultdict(int) remove: list[tuple] = [] for run in sorted((p for p in RUNS_DIR.glob("*") if p.is_dir()), reverse=True): if rel(run) == protected: continue report = run / "report.json" r = load_json(report) if report.is_file() else {} if r.get("status") != "success": remove.append((run, r.get("status", "sem report.json"))) continue key = (r.get("configSource"), r.get("profile")) kept[key] += 1 if kept[key] > args.keep: remove.append((run, "sucesso antigo")) if not remove: print("nada a remover") return 0 for run, why in remove: print(f"{'removido' if args.apply else 'removeria'}: {run.name} ({why})") if args.apply: shutil.rmtree(run) if not args.apply: print("(simulação; use --apply para apagar)") return 0 if __name__ == "__main__": raise SystemExit(main())