curator.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. """CLI subcommand: `hermes curator <subcommand>`."""
  2. from __future__ import annotations
  3. import argparse
  4. import sys
  5. from datetime import datetime, timezone, UTC
  6. from pathlib import Path
  7. from typing import Optional
  8. def _parse_ts(ts) -> Optional[datetime]:
  9. """ISO timestamp -> aware UTC datetime, or None when unparseable."""
  10. try:
  11. dt = datetime.fromisoformat(ts)
  12. except (TypeError, ValueError):
  13. return None
  14. return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt
  15. def _fmt_ts(ts: Optional[str]) -> str:
  16. if not ts:
  17. return "never"
  18. dt = _parse_ts(ts)
  19. if dt is None:
  20. return str(ts)
  21. secs = int((datetime.now(UTC) - dt).total_seconds())
  22. for unit, div, limit in (("s", 1, 60), ("m", 60, 3600), ("h", 3600, 86400)):
  23. if secs < limit:
  24. return f"{secs // div}{unit} ago"
  25. return f"{secs // 86400}d ago"
  26. def _confirm(prompt: str, cancel: str = "cancelled", eof_prefix: str = "\n") -> bool:
  27. """Ask ``prompt``; print ``cancel`` (prefixed on EOF/Ctrl-C) and return False unless y/yes."""
  28. try:
  29. if input(prompt).strip().lower() in {"y", "yes"}:
  30. return True
  31. except (EOFError, KeyboardInterrupt):
  32. print(eof_prefix, end="")
  33. print(cancel)
  34. return False
  35. def _print_skill_rows(title: str, rows: list) -> None:
  36. print(f"\n{title}:")
  37. for r in rows:
  38. print(
  39. f" {r['name']:40s} "
  40. f"activity={r.get('activity_count', 0):3d} "
  41. f"use={r.get('use_count', 0):3d} "
  42. f"view={r.get('view_count', 0):3d} "
  43. f"patches={r.get('patch_count', 0):3d} "
  44. f"last_activity={_fmt_ts(r.get('last_activity_at'))}")
  45. def _print_unmanaged_summary() -> None:
  46. """Report curation-eligible skills that carry no provenance marker: only background-review
  47. creations get ``created_by: agent``; older skills and every foreground ``skill_manage(create)``
  48. are eligible but unmanaged, so no automatic transition touches them."""
  49. from tools import skill_usage
  50. try:
  51. unmanaged = skill_usage.unmanaged_report()
  52. except Exception:
  53. return
  54. if not unmanaged:
  55. return
  56. legacy = sum(1 for r in unmanaged if not r.get("has_provenance_key"))
  57. foreground = len(unmanaged) - legacy
  58. print(f"\nunmanaged (no provenance marker): {len(unmanaged)} total")
  59. print(f" pre-dates marker {legacy}")
  60. print(f" foreground-created {foreground}")
  61. print(" never auto-staled or archived — `hermes curator adopt <name>` hands one over")
  62. def _print_curator_config(curator) -> None:
  63. state = curator.load_state()
  64. status_line = (
  65. "PAUSED" if state.get("paused", False)
  66. else "ENABLED" if curator.is_enabled() else "DISABLED")
  67. print(f"curator: {status_line}")
  68. print(f" runs: {state.get('run_count', 0)}")
  69. print(f" last run: {_fmt_ts(state.get('last_run_at'))}")
  70. # Multi-line when the curator archived skills (rename map appended as `name → umbrella`
  71. # lines); indent continuation lines so the block reads as one field.
  72. summary = state.get("last_run_summary") or "(none)"
  73. first, *rest = summary.splitlines() if "\n" in summary else [summary]
  74. print(f" last summary: {first}")
  75. for line in rest:
  76. print(f" {line}")
  77. report = state.get("last_report_path")
  78. if report:
  79. print(f" last report: {report}{'' if Path(report).exists() else ' (missing)'}")
  80. ih = curator.get_interval_hours()
  81. print(f" interval: every {f'{ih // 24}d' if ih % 24 == 0 and ih >= 24 else f'{ih}h'}")
  82. print(f" stale after: {curator.get_stale_after_days()}d unused")
  83. print(f" archive after: {curator.get_archive_after_days()}d unused")
  84. consolidate = curator.get_consolidate()
  85. print(
  86. f" consolidate: {'on' if consolidate else 'off'}"
  87. f"{'' if consolidate else ' (prune-only; LLM merge pass opt-in)'}")
  88. def _cmd_status(args) -> int:
  89. from agent import curator
  90. from tools import skill_usage
  91. _print_curator_config(curator)
  92. if locked := skill_usage.locked_skill_names():
  93. print(f"\nlocked ({len(locked)}): {', '.join(locked)} "
  94. f"(the agent cannot change these; `hermes curator unlock <skill>` lifts it)")
  95. rows = skill_usage.curated_report()
  96. if not rows:
  97. print("\nno curator-managed skills")
  98. _print_unmanaged_summary()
  99. return 0
  100. by_state: dict = {}
  101. for r in rows:
  102. by_state.setdefault(r.get("state", "active"), []).append(r)
  103. pinned = [r["name"] for r in rows if r.get("pinned")]
  104. provenance = [r.get("provenance", "agent") for r in rows]
  105. print(f"\ncurator-managed skills: {len(rows)} total "
  106. f"(agent-created={provenance.count('agent')} bundled={provenance.count('bundled')})")
  107. for state_name in ("active", "stale", "archived"):
  108. print(f" {state_name:10s} {len(by_state.get(state_name, []))}")
  109. if pinned:
  110. print(f"\npinned ({len(pinned)}): {', '.join(pinned)}")
  111. _print_unmanaged_summary() # the curation blind spot matters on the managed path too
  112. # Views and edits count as activity: a skill must not read as "never used" right after
  113. # skill_view()/skill_manage() touched it. Recency (last_activity_at) and frequency
  114. # (activity_count) are different signals, so both top-5s are shown.
  115. active_all = by_state.get("active", [])
  116. if not active_all:
  117. return 0
  118. recency = sorted(
  119. active_all, key=lambda r: r.get("last_activity_at") or r.get("created_at") or "")
  120. _print_skill_rows("least recently active (top 5)", recency[:5])
  121. def _freq(r):
  122. return (r.get("activity_count") or 0, r.get("last_activity_at") or "")
  123. most_active = sorted(active_all, key=_freq, reverse=True)[:5]
  124. if (most_active[0].get("activity_count") or 0) > 0:
  125. _print_skill_rows("most active (top 5)", most_active)
  126. _print_skill_rows("least active (top 5)", sorted(active_all, key=_freq)[:5])
  127. return 0
  128. def _cmd_run(args) -> int:
  129. from agent import curator
  130. if not curator.is_enabled():
  131. print("curator: disabled via config; enable with `curator.enabled: true`")
  132. return 1
  133. dry = bool(getattr(args, "dry_run", False))
  134. background = bool(getattr(args, "background", False))
  135. synchronous = bool(getattr(args, "synchronous", False)) or not background
  136. # --consolidate forces the LLM umbrella pass on; absent => None so run_curator_review reads
  137. # curator.consolidate from config.
  138. consolidate = True if getattr(args, "consolidate", False) else None
  139. print(
  140. "curator: running DRY-RUN (report only, no mutations)..." if dry
  141. else "curator: running review pass...")
  142. if consolidate is None and not curator.get_consolidate():
  143. print(
  144. "curator: consolidation is off — running prune-only "
  145. "(deterministic stale/archive). Pass --consolidate or set "
  146. "`curator.consolidate: true` to enable the LLM merge pass.")
  147. result = curator.run_curator_review(
  148. on_summary=print, synchronous=synchronous, dry_run=dry, consolidate=consolidate)
  149. auto = result.get("auto_transitions", {})
  150. if auto and dry:
  151. print(
  152. f"auto (preview): {auto.get('checked', 0)} candidate skill(s) "
  153. "— no transitions applied in dry-run")
  154. elif auto:
  155. print(
  156. f"auto: checked={auto.get('checked', 0)} "
  157. f"stale={auto.get('marked_stale', 0)} "
  158. f"archived={auto.get('archived', 0)} "
  159. f"reactivated={auto.get('reactivated', 0)}")
  160. if not synchronous:
  161. print("llm pass running in background — check `hermes curator status` later")
  162. if dry:
  163. print(
  164. "dry-run: no changes applied. Read the report with "
  165. "`hermes curator status` and run `hermes curator run` (no flag) to apply."
  166. if synchronous else
  167. "dry-run: no changes applied. When the report lands, read it with "
  168. "`hermes curator status` and run `hermes curator run` (no flag) to apply.")
  169. return 0
  170. def _set_paused(paused: bool) -> int:
  171. from agent import curator
  172. curator.set_paused(paused)
  173. print("curator: paused" if paused else "curator: resumed")
  174. return 0
  175. def _cmd_pause(args) -> int: return _set_paused(True)
  176. def _cmd_resume(args) -> int: return _set_paused(False)
  177. _PIN_MESSAGES = {
  178. True: (
  179. "cannot pin (only agent-created skills participate in curation)",
  180. "could not pin '{skill}' — the skill is not curation-eligible (protected built-in or "
  181. "external). `hermes curator list-unmanaged` shows which skills the curator tracks.",
  182. # Unmanaged skills are never auto-transitioned, so the pin is recorded but only
  183. # becomes protective once the skill is adopted — say so and point at `adopt`.
  184. "pinned '{skill}' (recorded; this skill is unmanaged — auto-transitions never consider "
  185. "it. Run `hermes curator adopt {skill}` to put it under curator management)",
  186. "pinned '{skill}' (will bypass auto-transitions)"),
  187. False: (
  188. "there's nothing to unpin (curator only tracks agent-created skills)",
  189. "could not unpin '{skill}' — the skill is not curation-eligible (protected built-in or "
  190. "external).",
  191. "unpinned '{skill}' (recorded; this skill is unmanaged — it was never under "
  192. "auto-transitions to begin with)",
  193. "unpinned '{skill}'")}
  194. def _set_pin(args, pinned: bool) -> int:
  195. from tools import skill_usage
  196. not_agent, not_eligible, unmanaged, done = _PIN_MESSAGES[pinned]
  197. skill = args.skill
  198. if not skill_usage.is_agent_created(skill):
  199. print(f"curator: '{skill}' is bundled or hub-installed — {not_agent}")
  200. return 1
  201. if not skill_usage.set_pinned(skill, pinned):
  202. print("curator: " + not_eligible.replace("{skill}", skill))
  203. return 1
  204. if not skill_usage.is_curator_managed(skill):
  205. print("curator: " + unmanaged.replace("{skill}", skill))
  206. return 0
  207. print("curator: " + done.replace("{skill}", skill))
  208. return 0
  209. def _cmd_pin(args) -> int: return _set_pin(args, True)
  210. def _cmd_unpin(args) -> int: return _set_pin(args, False)
  211. def _set_lock(args, locked: bool) -> int:
  212. """``hermes curator lock|unlock``: a user declaration stored beside ``pinned`` in the active
  213. profile's skills/.usage.json, enforced by tools/skill_lock on every agent write path. Any skill
  214. can be locked, but the name must resolve in this profile, so a typo never forges a record."""
  215. from tools import skill_usage
  216. from tools.skill_manager_tool import _find_skill
  217. verb = "lock" if locked else "unlock"
  218. existing = _find_skill(args.skill)
  219. if existing is None:
  220. print(f"curator: no skill named '{args.skill}' in the active profile — nothing to {verb}. "
  221. f"`hermes skills list` shows the names.")
  222. return 1
  223. key = existing["path"].name # directory name: the key the skill_manage guard resolves to
  224. if not skill_usage.set_locked(key, locked):
  225. print(f"curator: could not record the {verb} for '{key}' (skills/.usage.json not writable).")
  226. return 1
  227. if locked:
  228. print(f"curator: locked '{key}'. The agent can no longer change it: skill_manage, write_file, "
  229. f"patch and terminal refuse, in normal turns and the background passes alike, and the "
  230. f"curator won't archive it. It stays readable and auto-loadable, and you can still edit it "
  231. f"yourself. Unlock with `hermes curator unlock {key}`.")
  232. else:
  233. print(f"curator: unlocked '{key}'. The agent may edit it again.")
  234. return 0
  235. def _cmd_lock(args) -> int: return _set_lock(args, True)
  236. def _cmd_unlock(args) -> int: return _set_lock(args, False)
  237. def _cmd_list_unmanaged(args) -> int:
  238. """Itemize the unmanaged population that `status` summarizes (input for `adopt`)."""
  239. from tools import skill_usage
  240. rows = skill_usage.unmanaged_report()
  241. if not rows:
  242. print("curator: no unmanaged skills — every eligible skill is managed")
  243. return 0
  244. print(f"unmanaged skills ({len(rows)}):")
  245. for r in sorted(rows, key=lambda x: x["name"]):
  246. why = f"created_by:{r.get('created_by') or 'null'}" if r.get("has_provenance_key") else "no marker"
  247. print(
  248. f" {r['name']:44s} activity={r.get('activity_count', 0):4d} "
  249. f"last_activity={_fmt_ts(r.get('last_activity_at')):14s} ({why})")
  250. print("\nadopt one with `hermes curator adopt <name>`, "
  251. "or all with `hermes curator adopt --all-unmanaged`")
  252. return 0
  253. def _cmd_adopt(args) -> int:
  254. """Hand unmanaged skills to the curator by explicit user declaration: provenance cannot be
  255. inferred from telemetry (a high patch count proves the agent MAINTAINS a skill, not that it
  256. AUTHORED it)."""
  257. from tools import skill_usage
  258. names = list(getattr(args, "skill", None) or [])
  259. adopt_all = bool(getattr(args, "all_unmanaged", False))
  260. if adopt_all:
  261. if names:
  262. print("curator: pass either skill names or --all-unmanaged, not both")
  263. return 1
  264. names = skill_usage.list_unmanaged_skill_names()
  265. if not names:
  266. print("curator: no unmanaged skills to adopt")
  267. return 0
  268. if not names:
  269. print("curator: name a skill to adopt, or pass --all-unmanaged")
  270. return 1
  271. if getattr(args, "dry_run", False):
  272. print(f"curator: would adopt {len(names)} skill(s) (dry run):")
  273. for n in names:
  274. print(f" + {n}")
  275. return 0
  276. # Bulk adoption is a lifecycle change (adopted skills become archivable): confirm.
  277. if adopt_all and not getattr(args, "yes", False):
  278. print(f"curator: adopt {len(names)} unmanaged skill(s) into curator management?")
  279. print(" they become eligible for automatic staleness + archival")
  280. if not _confirm(" proceed? [y/N] ", "curator: aborted", eof_prefix=""):
  281. return 1
  282. failed = 0
  283. for n in names:
  284. ok, msg = skill_usage.adopt_skill(n)
  285. print(f"curator: {msg}")
  286. failed += not ok
  287. if len(names) > 1:
  288. print(f"curator: adopted {len(names) - failed}/{len(names)}")
  289. return 1 if failed else 0
  290. def _as_user(fn, skill: str) -> int:
  291. """Run a skill mutation with the ledger actor set to ``user``; print and map its result."""
  292. from tools import skill_ledger
  293. tok = skill_ledger.set_ledger_actor("user")
  294. try:
  295. ok, msg = fn(skill)
  296. finally:
  297. skill_ledger.reset_ledger_actor(tok)
  298. print(f"curator: {msg}")
  299. return 0 if ok else 1
  300. def _cmd_restore(args) -> int:
  301. from tools import skill_usage
  302. return _as_user(skill_usage.restore_skill, args.skill)
  303. def _cmd_archive(args) -> int:
  304. """Manually archive an agent-created skill. Refuses if pinned."""
  305. from tools import skill_usage
  306. if skill_usage.get_record(args.skill).get("pinned"):
  307. print(
  308. f"curator: '{args.skill}' is pinned — unpin first with "
  309. f"`hermes curator unpin {args.skill}`")
  310. return 1
  311. return _as_user(skill_usage.archive_skill, args.skill)
  312. def _idle_days(record: dict) -> Optional[int]:
  313. """Days since last activity, falling back to ``created_at`` so never-used skills aren't
  314. immortal; None only when both fields are missing or unparseable."""
  315. ts = record.get("last_activity_at") or record.get("created_at")
  316. dt = _parse_ts(str(ts)) if ts else None
  317. return None if dt is None else max(0, (datetime.now(UTC) - dt).days)
  318. def _cmd_prune(args) -> int:
  319. """Bulk-archive curator-managed skills idle for >= N days (pinned exempt, archived skipped)."""
  320. from agent import curator
  321. from tools import skill_usage
  322. days = getattr(args, "days", None)
  323. if days is None:
  324. days = curator.get_archive_after_days()
  325. if days < 1:
  326. print(f"curator: --days must be >= 1 (got {days})", file=sys.stderr)
  327. return 2
  328. candidates = [
  329. (r["name"], idle) for r in skill_usage.curated_report()
  330. if not (r.get("pinned") or r.get("state") == skill_usage.STATE_ARCHIVED)
  331. and (idle := _idle_days(r)) is not None and idle >= days]
  332. if not candidates:
  333. print(f"curator: nothing to prune (no unpinned skills idle >= {days}d)")
  334. return 0
  335. candidates.sort(key=lambda c: -c[1])
  336. print(f"curator: {len(candidates)} skill(s) idle >= {days}d:")
  337. for name, idle in candidates:
  338. print(f" {name:40s} idle {idle}d")
  339. if getattr(args, "dry_run", False):
  340. print("\n(dry run — no changes made)")
  341. return 0
  342. if not getattr(args, "yes", False) and not _confirm(
  343. f"\nArchive {len(candidates)} skill(s)? [y/N] ", "curator: aborted"):
  344. return 1
  345. results = [(name, *skill_usage.archive_skill(name)) for name, _ in candidates]
  346. failures = [(name, msg) for name, ok, msg in results if not ok]
  347. print(f"\ncurator: archived {len(results) - len(failures)}/{len(candidates)}")
  348. if failures:
  349. print("failures:")
  350. for name, msg in failures:
  351. print(f" {name}: {msg}")
  352. return 1
  353. return 0
  354. def _cmd_backup(args) -> int:
  355. """Manual skills-tree snapshot (same mechanism as the automatic pre-run snapshot)."""
  356. from agent import curator_backup
  357. if not curator_backup.is_enabled():
  358. print(
  359. "curator: backups are disabled via config "
  360. "(`curator.backup.enabled: false`); re-enable to snapshot")
  361. return 1
  362. snap = curator_backup.snapshot_skills(reason=getattr(args, "reason", None) or "manual")
  363. if snap is None:
  364. print("curator: snapshot failed — check logs (backup disabled or IO error)")
  365. return 1
  366. print(f"curator: snapshot created at ~/.hermes/skills/.curator_backups/{snap.name}")
  367. return 0
  368. def _cmd_ledger(args) -> int:
  369. """List per-mutation audit ledger entries (newest first), or compact the file in place."""
  370. from tools import skill_ledger
  371. if getattr(args, "compact", False):
  372. entries, before, after = skill_ledger.compact_ledger()
  373. blobs, freed = skill_ledger.gc_blobs()
  374. print(f"curator: ledger compacted — {entries} entries, {before / 2**20:.1f} MB → {after / 2**20:.1f} MB; "
  375. f"{blobs} unreferenced blob(s) removed ({freed / 2**20:.1f} MB)")
  376. return 0
  377. rows = skill_ledger.list_entries(
  378. skill=getattr(args, "skill", None), limit=getattr(args, "limit", None) or 20)
  379. if not rows:
  380. print("curator: ledger is empty (or skills.ledger is disabled).")
  381. return 0
  382. print(f"{'id':<14} {'when':<12} {'actor':<8} {'action':<12} skill")
  383. for r in rows:
  384. evidence = r.get("evidence") or {}
  385. extra = ""
  386. if evidence.get("absorbed_into"):
  387. extra = f" → absorbed into '{evidence['absorbed_into']}'"
  388. elif evidence.get("rollback_target"):
  389. extra = f" → rollback of {evidence['rollback_target']}"
  390. print(
  391. f"{r.get('id', '?'):<14} {_fmt_ts(r.get('ts')):<12} "
  392. f"{r.get('actor', '?'):<8} {r.get('action', '?'):<12} "
  393. f"{r.get('skill', '?')}{extra}")
  394. print(
  395. "\nRoll back a single mutation with `hermes curator rollback <id>`; "
  396. "whole-tree snapshots remain available via `hermes curator rollback --list`.")
  397. return 0
  398. def _cmd_purge(args) -> int:
  399. """Delete archived skills older than curator.archive_ttl_days. Explicit only — never
  400. automatic; each purged skill is captured (before-blobs) and recorded as a 'purge' ledger
  401. entry, so even a purge is auditable and blob-recoverable."""
  402. import shutil
  403. import time
  404. from hermes_cli.config import cfg_get, load_config
  405. from tools import skill_ledger, skill_usage
  406. ttl_days = getattr(args, "days", None)
  407. if ttl_days is None:
  408. ttl_days = int(cfg_get(load_config(), "curator", "archive_ttl_days", default=0) or 0)
  409. if ttl_days <= 0:
  410. print(
  411. "curator: purge disabled (curator.archive_ttl_days is 0). Set the "
  412. "config key or pass --days N to purge archives older than N days.")
  413. return 1
  414. archive_root = skill_usage._archive_dir()
  415. if not archive_root.exists():
  416. print("curator: no archive directory — nothing to purge.")
  417. return 0
  418. cutoff = time.time() - ttl_days * 86400
  419. usage = skill_usage.load_usage()
  420. def _archived_ts(p: Path) -> float:
  421. # The NEWER of the record's archived_at and the dir mtime: archives made before
  422. # archive_skill stamped the mtime carry the skill's last-edit mtime, and a stale
  423. # archived_at survives a manual un-archive + re-archive. Never purge before either says so.
  424. # Key by the SKILL.md frontmatter name: older archives were flattened under the directory
  425. # name (`accelerate` for `huggingface-accelerate`), which is not the usage-record key.
  426. rec = usage.get(skill_usage.read_skill_name(p / "SKILL.md", fallback=p.name)) or {}
  427. archived = rec.get("state") == skill_usage.STATE_ARCHIVED
  428. at = skill_usage._parse_iso_timestamp(rec.get("archived_at")) if archived else None
  429. return max(at.timestamp(), p.stat().st_mtime) if at else p.stat().st_mtime
  430. candidates = sorted(
  431. p for p in archive_root.iterdir() if p.is_dir() and _archived_ts(p) < cutoff)
  432. if not candidates:
  433. print(f"curator: no archived skills older than {ttl_days}d.")
  434. return 0
  435. print(f"Archived skills older than {ttl_days}d:")
  436. for p in candidates:
  437. print(f" {p.name}")
  438. if getattr(args, "dry_run", False):
  439. print("(dry run — nothing deleted)")
  440. return 0
  441. if not getattr(args, "yes", False) and not _confirm(
  442. f"Permanently delete {len(candidates)} archived skill(s)? [y/N] "):
  443. return 1
  444. purged = 0
  445. for p in candidates:
  446. before = skill_ledger.capture_before(p, complete_package=True, skill=p.name)
  447. try:
  448. shutil.rmtree(p)
  449. except OSError as e:
  450. print(f"curator: failed to purge {p.name}: {e}")
  451. continue
  452. skill_ledger.append_entry(
  453. "purge", p.name, before=before or [], after=[], actor="user",
  454. evidence={"ttl_days": ttl_days})
  455. purged += 1
  456. print(f"curator: purged {purged} archived skill(s). Ledger entries recorded.")
  457. return 0
  458. def _report_rollback(ok: bool, msg: str) -> int:
  459. print(f"curator: {msg}" if ok else f"curator: rollback failed — {msg}")
  460. return 0 if ok else 1
  461. def _rollback_ledger_entry(args, entry_id: str) -> int:
  462. """Restore exactly the files touched by one ledger entry (from content-addressed blobs); a
  463. pre-rollback safety ledger entry is taken first and it fails closed if that capture fails."""
  464. from tools import skill_ledger
  465. entry = skill_ledger.get_entry(entry_id)
  466. if entry is None:
  467. print(
  468. f"curator: no ledger entry '{entry_id}'. "
  469. "See `hermes curator ledger` for entry ids, or use "
  470. "`--id <snapshot>` for whole-tree snapshot rollback.")
  471. return 1
  472. print(f"Rollback target: ledger entry {entry_id}")
  473. print(f" action: {entry.get('action', '?')}")
  474. print(f" skill: {entry.get('skill', '?')}")
  475. print(f" actor: {entry.get('actor', '?')}")
  476. print(f" when: {entry.get('ts', '?')}")
  477. touched = {i.get("path") for i in (entry.get("before") or []) + (entry.get("after") or [])}
  478. print(f" files: {len(touched)}")
  479. if not getattr(args, "yes", False) and not _confirm(
  480. "Restore this mutation's before-state? [y/N] "):
  481. return 1
  482. return _report_rollback(*skill_ledger.rollback_entry(entry_id))
  483. def _cmd_rollback(args) -> int:
  484. """Restore the skills tree from a snapshot, or a single mutation from the audit ledger."""
  485. from agent import curator_backup
  486. entry_id = getattr(args, "entry_id", None)
  487. if entry_id:
  488. return _rollback_ledger_entry(args, entry_id)
  489. if getattr(args, "list", False):
  490. print(curator_backup.summarize_backups())
  491. return 0
  492. backup_id = getattr(args, "backup_id", None)
  493. target_path = curator_backup._resolve_backup(backup_id)
  494. if target_path is None:
  495. if not curator_backup.list_backups():
  496. print(
  497. "curator: no snapshots exist yet. Take one with "
  498. "`hermes curator backup` or wait for the next curator run.")
  499. else:
  500. print(
  501. f"curator: no snapshot matching "
  502. f"{'id ' + repr(backup_id) if backup_id else 'your query'}.")
  503. print("Available:")
  504. print(curator_backup.summarize_backups())
  505. return 1
  506. manifest = curator_backup._read_manifest(target_path)
  507. print(f"Rollback target: {target_path.name}")
  508. if manifest:
  509. print(f" reason: {manifest.get('reason', '?')}")
  510. print(f" created_at: {manifest.get('created_at', '?')}")
  511. print(f" skill files: {manifest.get('skill_files', '?')}")
  512. cron = manifest.get("cron_jobs") or {}
  513. if isinstance(cron, dict):
  514. if cron.get("backed_up"):
  515. print(
  516. f" cron jobs: {cron.get('jobs_count', 0)} "
  517. f"(will be restored for skill-link fields only)")
  518. else:
  519. print(f" cron jobs: not in snapshot ({cron.get('reason', 'not captured')})")
  520. print(
  521. "\nThis will replace the current ~/.hermes/skills/ tree (a safety "
  522. "snapshot of the current state is taken first so this is undoable). "
  523. "Cron jobs that still exist will have their skills/skill fields "
  524. "restored from the snapshot; all other cron fields are left alone.")
  525. if not getattr(args, "yes", False) and not _confirm("Proceed? [y/N] "):
  526. return 1
  527. ok, msg, _ = curator_backup.rollback(backup_id=target_path.name)
  528. return _report_rollback(ok, msg)
  529. def _cmd_list_archived(args) -> int:
  530. """List archived (recoverable) skills."""
  531. from tools import skill_usage
  532. names = skill_usage.list_archived_skill_names()
  533. print("\n".join(names) if names else "curator: no archived skills")
  534. return 0
  535. _USAGE_SORTS = {
  536. "name": (lambda r: r["name"], False),
  537. "recent": (lambda r: r.get("last_activity_at") or "", True),
  538. "activity": (lambda r: r.get("activity_count", 0), True)}
  539. def _cmd_usage(args) -> int:
  540. """Usage telemetry for ALL skills on disk (bundled + hub included), with provenance."""
  541. import json as _json
  542. from tools import skill_usage
  543. rows = skill_usage.usage_report()
  544. prov_filter = getattr(args, "provenance", None)
  545. if prov_filter:
  546. rows = [r for r in rows if r.get("provenance") == prov_filter]
  547. # name: alphabetical; recent: most-recently-active first (never-active sinks); activity
  548. # (default): most-used first.
  549. key, reverse = _USAGE_SORTS.get(getattr(args, "sort", "activity"), _USAGE_SORTS["activity"])
  550. rows.sort(key=key, reverse=reverse)
  551. if getattr(args, "json", False):
  552. print(_json.dumps(rows, indent=2, ensure_ascii=False))
  553. return 0
  554. if not rows:
  555. print("curator: no skills found")
  556. return 0
  557. provenance = [r.get("provenance", "agent") for r in rows]
  558. counts = {k: provenance.count(k) for k in ("agent", "bundled", "hub", "external")}
  559. print(
  560. f"skills: {len(rows)} total "
  561. f"(agent={counts['agent']} bundled={counts['bundled']} hub={counts['hub']} external={counts['external']})\n")
  562. print(
  563. f" {'skill':40s} {'origin':8s} "
  564. f"{'use':>4s} {'view':>4s} {'patch':>5s} {'act':>4s} last_activity")
  565. for r in rows:
  566. print(
  567. f" {r['name'][:40]:40s} "
  568. f"{r.get('provenance', 'agent'):8s} "
  569. f"{r.get('use_count', 0):>4d} "
  570. f"{r.get('view_count', 0):>4d} "
  571. f"{r.get('patch_count', 0):>5d} "
  572. f"{r.get('activity_count', 0):>4d} "
  573. f"{_fmt_ts(r.get('last_activity_at'))}")
  574. return 0
  575. def _arg(*flags, **kwargs):
  576. return flags, kwargs
  577. _SKILL = _arg("skill", help="Skill name")
  578. _YES = _arg("-y", "--yes", action="store_true", help="Skip the confirmation prompt")
  579. _STORE_TRUE = dict(action="store_true")
  580. # argparse wiring: (name, help, handler, *(flags, add_argument kwargs))
  581. _SUBCOMMANDS = (
  582. ("status", "Show curator status and skill stats", _cmd_status),
  583. (
  584. "usage", "Show usage telemetry for ALL skills (built-in, hub, agent) with provenance",
  585. _cmd_usage,
  586. _arg("--sort", choices=("activity", "recent", "name"), default="activity",
  587. help="Sort order: activity (most-used first, default), recent "
  588. "(most-recently-active first), or name (alphabetical)"),
  589. _arg("--provenance", choices=("agent", "bundled", "hub", "external"), default=None,
  590. help="Only show skills of this origin"),
  591. _arg("--json", **_STORE_TRUE, help="Emit the full report as JSON instead of a table")),
  592. (
  593. "run", "Trigger a curator review now", _cmd_run,
  594. _arg("--sync", "--synchronous", dest="synchronous", **_STORE_TRUE,
  595. help="Wait for the LLM review pass to finish (default for manual runs)"),
  596. _arg("--background", dest="background", **_STORE_TRUE,
  597. help="Start the LLM review pass in a background thread and return immediately"),
  598. _arg("--dry-run", dest="dry_run", **_STORE_TRUE,
  599. help="Report only — no state changes, no archives, no consolidation "
  600. "(use this to preview what curator would do)"),
  601. _arg("--consolidate", dest="consolidate", **_STORE_TRUE,
  602. help="Force the LLM umbrella-building consolidation pass on for this "
  603. "run, overriding the config default (off). Without this flag the "
  604. "run is prune-only unless `curator.consolidate: true` is set.")),
  605. ("pause", "Pause the curator until resumed", _cmd_pause),
  606. ("resume", "Resume a paused curator", _cmd_resume),
  607. ("pin", "Pin a skill so the curator never auto-transitions it", _cmd_pin, _SKILL),
  608. ("unpin", "Unpin a skill", _cmd_unpin, _SKILL),
  609. ("lock", "Lock a skill so the agent cannot change it (skill_manage, write_file, patch and terminal "
  610. "refuse; it stays readable and auto-loadable; your own edits are unaffected)", _cmd_lock, _SKILL),
  611. ("unlock", "Lift a content lock", _cmd_unlock, _SKILL),
  612. ("list-unmanaged", "List curation-eligible skills with no provenance marker",
  613. _cmd_list_unmanaged),
  614. (
  615. "adopt", "Hand unmanaged skills to the curator (provenance is a user declaration)",
  616. _cmd_adopt,
  617. _arg("skill", nargs="*", help="Skill name(s) to adopt. Omit when using --all-unmanaged."),
  618. _arg("--all-unmanaged", **_STORE_TRUE,
  619. help="Adopt every curation-eligible skill that has no provenance marker"),
  620. _arg("--dry-run", **_STORE_TRUE,
  621. help="List what would be adopted without writing anything"),
  622. _arg("--yes", **_STORE_TRUE, help="Skip the confirmation prompt for --all-unmanaged")),
  623. ("restore", "Restore an archived skill", _cmd_restore, _SKILL),
  624. ("list-archived", "List archived skills", _cmd_list_archived),
  625. ("archive", "Manually archive a skill (move to .archive/, excluded from prompt)", _cmd_archive,
  626. _SKILL),
  627. (
  628. "prune", "Bulk-archive curator-managed skills idle for >= N days (default: curator.archive_after_days)",
  629. _cmd_prune,
  630. _arg("--days", type=int, default=None,
  631. help="Archive skills idle for at least N days (default: curator.archive_after_days, 30)"),
  632. _YES,
  633. _arg("--dry-run", dest="dry_run", **_STORE_TRUE,
  634. help="Show what would be archived without doing it")),
  635. (
  636. "backup",
  637. "Take a manual tar.gz snapshot of ~/.hermes/skills/ "
  638. "(curator also does this automatically before every real run)",
  639. _cmd_backup,
  640. _arg("--reason", default=None,
  641. help="Free-text label stored in manifest.json (default: 'manual')")),
  642. (
  643. "rollback",
  644. "Restore ~/.hermes/skills/ from a curator snapshot, or a single "
  645. "mutation by ledger entry id (see `hermes curator ledger`)",
  646. _cmd_rollback,
  647. _arg("entry_id", nargs="?", default=None,
  648. help="Ledger entry id for single-mutation rollback (from "
  649. "`hermes curator ledger`). Omit for whole-tree snapshot rollback."),
  650. _arg("--list", **_STORE_TRUE, help="List available snapshots and exit without restoring"),
  651. _arg("--id", dest="backup_id", default=None,
  652. help="Snapshot id to restore (see `--list`); default: newest"),
  653. _arg("-y", "--yes", **_STORE_TRUE, help="Skip confirmation prompt")),
  654. (
  655. "ledger", "List the per-mutation skill audit ledger (all actors: curator/agent/user)",
  656. _cmd_ledger,
  657. _arg("--skill", default=None, help="Only show entries for this skill"),
  658. _arg("--limit", type=int, default=20, help="Max entries to show (default: 20)"),
  659. _arg("--compact", **_STORE_TRUE,
  660. help="Rewrite the ledger dropping unchanged paths from every entry (ids and rollback preserved)")),
  661. (
  662. "purge",
  663. "Delete archived skills older than curator.archive_ttl_days "
  664. "(explicit only — never automatic; recorded in the ledger)",
  665. _cmd_purge,
  666. _arg("--days", type=int, default=None,
  667. help="Override curator.archive_ttl_days for this invocation"),
  668. _arg("--dry-run", dest="dry_run", **_STORE_TRUE,
  669. help="Show what would be purged without deleting"),
  670. _YES))
  671. def register_cli(parent: argparse.ArgumentParser) -> None:
  672. """Attach `curator` subcommands to *parent*."""
  673. parent.set_defaults(func=lambda a: (parent.print_help(), 0)[1])
  674. subs = parent.add_subparsers(dest="curator_command")
  675. for name, help_text, handler, *arguments in _SUBCOMMANDS:
  676. sub = subs.add_parser(name, help=help_text)
  677. for flags, arg_kwargs in arguments:
  678. sub.add_argument(*flags, **arg_kwargs)
  679. sub.set_defaults(func=handler)
  680. def cli_main(argv=None) -> int:
  681. """Standalone entry (also usable by hermes_cli.main fallthrough)."""
  682. parser = argparse.ArgumentParser(prog="hermes curator")
  683. register_cli(parser)
  684. args = parser.parse_args(argv)
  685. return int(args.func(args) or 0)
  686. if __name__ == "__main__": # pragma: no cover
  687. sys.exit(cli_main())