|
| 1 | +"""`hermes checkpoints` CLI subcommand. |
| 2 | +
|
| 3 | +Gives users direct visibility and control over the filesystem checkpoint |
| 4 | +store at ``~/.hermes/checkpoints/``. Actions: |
| 5 | +
|
| 6 | + hermes checkpoints # same as `status` |
| 7 | + hermes checkpoints status # total size, project count, breakdown |
| 8 | + hermes checkpoints list # per-project checkpoint counts + workdir |
| 9 | + hermes checkpoints prune [opts] # force a sweep (ignores the 24h marker) |
| 10 | + hermes checkpoints clear [-f] # nuke the entire base (asks first) |
| 11 | + hermes checkpoints clear-legacy # delete just the legacy-* archives |
| 12 | +
|
| 13 | +Examples:: |
| 14 | +
|
| 15 | + hermes checkpoints |
| 16 | + hermes checkpoints prune --retention-days 3 --max-size-mb 200 |
| 17 | + hermes checkpoints clear -f |
| 18 | +
|
| 19 | +None of these require the agent to be running. Safe to call any time. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import argparse |
| 25 | +import time |
| 26 | +from datetime import datetime |
| 27 | +from pathlib import Path |
| 28 | +from typing import Any, Dict |
| 29 | + |
| 30 | + |
| 31 | +def _fmt_bytes(n: int) -> str: |
| 32 | + units = ("B", "KB", "MB", "GB", "TB") |
| 33 | + size = float(n or 0) |
| 34 | + for unit in units: |
| 35 | + if size < 1024 or unit == units[-1]: |
| 36 | + if unit == "B": |
| 37 | + return f"{int(size)} {unit}" |
| 38 | + return f"{size:.1f} {unit}" |
| 39 | + size /= 1024 |
| 40 | + return f"{size:.1f} TB" |
| 41 | + |
| 42 | + |
| 43 | +def _fmt_ts(ts: Any) -> str: |
| 44 | + try: |
| 45 | + return datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d %H:%M") |
| 46 | + except (TypeError, ValueError): |
| 47 | + return "—" |
| 48 | + |
| 49 | + |
| 50 | +def _fmt_age(ts: Any) -> str: |
| 51 | + try: |
| 52 | + age = time.time() - float(ts) |
| 53 | + except (TypeError, ValueError): |
| 54 | + return "—" |
| 55 | + if age < 0: |
| 56 | + return "now" |
| 57 | + if age < 60: |
| 58 | + return f"{int(age)}s ago" |
| 59 | + if age < 3600: |
| 60 | + return f"{int(age / 60)}m ago" |
| 61 | + if age < 86400: |
| 62 | + return f"{int(age / 3600)}h ago" |
| 63 | + return f"{int(age / 86400)}d ago" |
| 64 | + |
| 65 | + |
| 66 | +def cmd_status(args: argparse.Namespace) -> int: |
| 67 | + from tools.checkpoint_manager import store_status |
| 68 | + |
| 69 | + info = store_status() |
| 70 | + base = info["base"] |
| 71 | + print(f"Checkpoint base: {base}") |
| 72 | + print(f"Total size: {_fmt_bytes(info['total_size_bytes'])}") |
| 73 | + print(f" store/ {_fmt_bytes(info['store_size_bytes'])}") |
| 74 | + print(f" legacy-* {_fmt_bytes(info['legacy_size_bytes'])}") |
| 75 | + print(f"Projects: {info['project_count']}") |
| 76 | + |
| 77 | + projects = sorted( |
| 78 | + info["projects"], |
| 79 | + key=lambda p: (p.get("last_touch") or 0), |
| 80 | + reverse=True, |
| 81 | + ) |
| 82 | + if projects: |
| 83 | + print() |
| 84 | + print(f" {'WORKDIR':<60} {'COMMITS':>7} {'LAST TOUCH':>12} STATE") |
| 85 | + for p in projects[: args.limit if hasattr(args, "limit") and args.limit else 20]: |
| 86 | + wd = p.get("workdir") or "(unknown)" |
| 87 | + if len(wd) > 60: |
| 88 | + wd = "…" + wd[-59:] |
| 89 | + exists = p.get("exists") |
| 90 | + state = "live" if exists else "orphan" |
| 91 | + commits = p.get("commits", 0) |
| 92 | + last = _fmt_age(p.get("last_touch")) |
| 93 | + print(f" {wd:<60} {commits:>7} {last:>12} {state}") |
| 94 | + |
| 95 | + legacy = info.get("legacy_archives", []) |
| 96 | + if legacy: |
| 97 | + print() |
| 98 | + print(f"Legacy archives ({len(legacy)}):") |
| 99 | + for arch in sorted(legacy, key=lambda a: a.get("mtime", 0), reverse=True): |
| 100 | + print(f" {arch['name']:<40} {_fmt_bytes(arch['size_bytes']):>10}") |
| 101 | + print() |
| 102 | + print("Clear with: hermes checkpoints clear-legacy") |
| 103 | + return 0 |
| 104 | + |
| 105 | + |
| 106 | +def cmd_list(args: argparse.Namespace) -> int: |
| 107 | + # `list` is just a terser status — already covered. |
| 108 | + return cmd_status(args) |
| 109 | + |
| 110 | + |
| 111 | +def cmd_prune(args: argparse.Namespace) -> int: |
| 112 | + from tools.checkpoint_manager import prune_checkpoints |
| 113 | + |
| 114 | + retention_days = args.retention_days |
| 115 | + max_size_mb = args.max_size_mb |
| 116 | + |
| 117 | + print("Pruning checkpoint store…") |
| 118 | + print(f" retention_days: {retention_days}") |
| 119 | + print(f" delete_orphans: {not args.keep_orphans}") |
| 120 | + print(f" max_total_size_mb: {max_size_mb}") |
| 121 | + print() |
| 122 | + |
| 123 | + result = prune_checkpoints( |
| 124 | + retention_days=retention_days, |
| 125 | + delete_orphans=not args.keep_orphans, |
| 126 | + max_total_size_mb=max_size_mb, |
| 127 | + ) |
| 128 | + print(f"Scanned: {result['scanned']}") |
| 129 | + print(f"Deleted orphan: {result['deleted_orphan']}") |
| 130 | + print(f"Deleted stale: {result['deleted_stale']}") |
| 131 | + print(f"Errors: {result['errors']}") |
| 132 | + print(f"Bytes reclaimed: {_fmt_bytes(result['bytes_freed'])}") |
| 133 | + return 0 |
| 134 | + |
| 135 | + |
| 136 | +def _confirm(prompt: str) -> bool: |
| 137 | + try: |
| 138 | + resp = input(f"{prompt} [y/N]: ").strip().lower() |
| 139 | + except (EOFError, KeyboardInterrupt): |
| 140 | + print() |
| 141 | + return False |
| 142 | + return resp in ("y", "yes") |
| 143 | + |
| 144 | + |
| 145 | +def cmd_clear(args: argparse.Namespace) -> int: |
| 146 | + from tools.checkpoint_manager import CHECKPOINT_BASE, clear_all, store_status |
| 147 | + |
| 148 | + info = store_status() |
| 149 | + if info["total_size_bytes"] == 0 and not Path(CHECKPOINT_BASE).exists(): |
| 150 | + print("Nothing to clear — checkpoint base does not exist.") |
| 151 | + return 0 |
| 152 | + |
| 153 | + print(f"This will delete the ENTIRE checkpoint base at {info['base']}") |
| 154 | + print(f" size: {_fmt_bytes(info['total_size_bytes'])}") |
| 155 | + print(f" projects: {info['project_count']}") |
| 156 | + print(f" legacy dirs: {len(info.get('legacy_archives', []))}") |
| 157 | + print() |
| 158 | + print("All /rollback history for every working directory will be lost.") |
| 159 | + if not args.force and not _confirm("Proceed?"): |
| 160 | + print("Aborted.") |
| 161 | + return 1 |
| 162 | + |
| 163 | + result = clear_all() |
| 164 | + if result["deleted"]: |
| 165 | + print(f"Cleared. Reclaimed {_fmt_bytes(result['bytes_freed'])}.") |
| 166 | + return 0 |
| 167 | + print("Could not clear checkpoint base (see logs).") |
| 168 | + return 2 |
| 169 | + |
| 170 | + |
| 171 | +def cmd_clear_legacy(args: argparse.Namespace) -> int: |
| 172 | + from tools.checkpoint_manager import clear_legacy, store_status |
| 173 | + |
| 174 | + info = store_status() |
| 175 | + legacy = info.get("legacy_archives", []) |
| 176 | + if not legacy: |
| 177 | + print("No legacy archives to clear.") |
| 178 | + return 0 |
| 179 | + |
| 180 | + total = sum(a.get("size_bytes", 0) for a in legacy) |
| 181 | + print(f"Found {len(legacy)} legacy archive(s), total {_fmt_bytes(total)}:") |
| 182 | + for arch in legacy: |
| 183 | + print(f" {arch['name']:<40} {_fmt_bytes(arch['size_bytes']):>10}") |
| 184 | + print() |
| 185 | + print("Legacy archives hold pre-v2 per-project shadow repos, moved aside") |
| 186 | + print("during the single-store migration. Delete when you're confident") |
| 187 | + print("you don't need the old /rollback history.") |
| 188 | + if not args.force and not _confirm("Delete all legacy archives?"): |
| 189 | + print("Aborted.") |
| 190 | + return 1 |
| 191 | + |
| 192 | + result = clear_legacy() |
| 193 | + print(f"Deleted {result['deleted']} archive(s), reclaimed {_fmt_bytes(result['bytes_freed'])}.") |
| 194 | + return 0 |
| 195 | + |
| 196 | + |
| 197 | +def register_cli(parser: argparse.ArgumentParser) -> None: |
| 198 | + """Wire subcommands onto the ``hermes checkpoints`` parser.""" |
| 199 | + parser.set_defaults(func=cmd_status) # bare `hermes checkpoints` → status |
| 200 | + subs = parser.add_subparsers(dest="checkpoints_command", metavar="COMMAND") |
| 201 | + |
| 202 | + p_status = subs.add_parser( |
| 203 | + "status", |
| 204 | + help="Show total size, project count, and per-project breakdown", |
| 205 | + ) |
| 206 | + p_status.add_argument("--limit", type=int, default=20, |
| 207 | + help="Max projects to list (default 20)") |
| 208 | + p_status.set_defaults(func=cmd_status) |
| 209 | + |
| 210 | + p_list = subs.add_parser( |
| 211 | + "list", |
| 212 | + help="Alias for 'status'", |
| 213 | + ) |
| 214 | + p_list.add_argument("--limit", type=int, default=20) |
| 215 | + p_list.set_defaults(func=cmd_list) |
| 216 | + |
| 217 | + p_prune = subs.add_parser( |
| 218 | + "prune", |
| 219 | + help="Delete orphan/stale checkpoints and GC the store", |
| 220 | + ) |
| 221 | + p_prune.add_argument("--retention-days", type=int, default=7, |
| 222 | + help="Drop projects whose last_touch is older than N days (default 7)") |
| 223 | + p_prune.add_argument("--max-size-mb", type=int, default=500, |
| 224 | + help="After orphan/stale prune, drop oldest commits " |
| 225 | + "per project until total size <= this (default 500)") |
| 226 | + p_prune.add_argument("--keep-orphans", action="store_true", |
| 227 | + help="Skip deleting projects whose workdir no longer exists") |
| 228 | + p_prune.set_defaults(func=cmd_prune) |
| 229 | + |
| 230 | + p_clear = subs.add_parser( |
| 231 | + "clear", |
| 232 | + help="Delete the entire checkpoint base (all /rollback history)", |
| 233 | + ) |
| 234 | + p_clear.add_argument("-f", "--force", action="store_true", |
| 235 | + help="Skip confirmation prompt") |
| 236 | + p_clear.set_defaults(func=cmd_clear) |
| 237 | + |
| 238 | + p_legacy = subs.add_parser( |
| 239 | + "clear-legacy", |
| 240 | + help="Delete only the legacy-<ts>/ archives from v1 migration", |
| 241 | + ) |
| 242 | + p_legacy.add_argument("-f", "--force", action="store_true", |
| 243 | + help="Skip confirmation prompt") |
| 244 | + p_legacy.set_defaults(func=cmd_clear_legacy) |
0 commit comments