data_cleanup.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. """Data-only deletion separates user state from the runtime that must survive."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. from pathlib import Path
  5. import stat
  6. from pm.filesystem import is_junction
  7. @dataclass(frozen=True)
  8. class DataRemovalPlan:
  9. home: Path
  10. remove: tuple[Path, ...]
  11. keep: tuple[Path, ...]
  12. def plan_data_removal(home: Path, project: Path, userdata: Path | None = None) -> DataRemovalPlan:
  13. from hermes_constants import get_default_hermes_root
  14. from pm.environments import base_venv, installs_root, store_root
  15. from hermes_cli.steward import is_bundled_payload
  16. from tools.checkpoint_pruning import store_lock_path
  17. home = home.resolve()
  18. if home == Path(home.anchor) or home == Path.home().resolve():
  19. raise ValueError(f"refusing to erase an entire filesystem or user home: {home}")
  20. machine = get_default_hermes_root(home=home).resolve()
  21. protected = {
  22. project.resolve(), base_venv(project).resolve(), store_root(project).resolve(),
  23. installs_root().resolve(), machine / "tools", machine / "bin", machine / "cache",
  24. machine / "spawn-ledger.json", machine / "spawn-ledger.json.lock", home / "gateway.lock", home / ".backup.lock",
  25. home / "runtime" / "active_sessions.lock", home / "cron" / ".tick.lock",
  26. store_lock_path(home / "checkpoints"),
  27. }
  28. if home == machine:
  29. protected.add(machine / "profiles")
  30. if is_bundled_payload(project):
  31. from hermes_cli.bundled_app import NotBundledApp, resolve_bundle_layout
  32. try:
  33. protected.add(resolve_bundle_layout(project).app_root)
  34. except NotBundledApp as exc:
  35. raise ValueError(str(exc)) from exc
  36. # The canonical source installation may coexist with the invoking package.
  37. canonical = home / "hermes-agent"
  38. if (canonical / "hermes_cli" / "__init__.py").is_file():
  39. protected.add(canonical)
  40. remove: list[Path] = []
  41. keep: set[Path] = set()
  42. def visit(path: Path) -> None:
  43. try:
  44. mode = path.lstat().st_mode
  45. except FileNotFoundError:
  46. return
  47. resolved = path.resolve()
  48. if any(path == root or resolved == root or path.is_relative_to(root) for root in protected):
  49. keep.add(path)
  50. elif path.is_symlink() or is_junction(path):
  51. remove.append(path) # Remove the directory entry, never its target.
  52. elif any(root.is_relative_to(path) for root in protected):
  53. if stat.S_ISDIR(mode):
  54. for child in sorted(path.iterdir()):
  55. visit(child)
  56. else:
  57. keep.add(path)
  58. else:
  59. remove.append(path)
  60. if home.is_dir():
  61. for child in sorted(home.iterdir()):
  62. visit(child)
  63. if home != machine:
  64. userdata = None # Desktop preferences belong to the app, not a named profile.
  65. if userdata is not None and not userdata.resolve().is_relative_to(home):
  66. if userdata.resolve() == Path.home().resolve() or home.is_relative_to(userdata.resolve()):
  67. raise ValueError(f"desktop data directory must not contain the Hermes or user home: {userdata}")
  68. visit(userdata.parent.resolve() / userdata.name)
  69. return DataRemovalPlan(home, tuple(remove), tuple(sorted(keep)))
  70. def remove_data(plan: DataRemovalPlan) -> tuple[list[Path], list[tuple[Path, str]]]:
  71. import shutil
  72. removed: list[Path] = []
  73. failed: list[tuple[Path, str]] = []
  74. for path in plan.remove:
  75. try:
  76. if path.parent.resolve() != path.parent:
  77. raise OSError("parent directory changed after confirmation; refusing to follow a link")
  78. mode = path.lstat().st_mode
  79. if path.is_symlink() or not stat.S_ISDIR(mode):
  80. path.unlink()
  81. elif is_junction(path):
  82. path.rmdir()
  83. else:
  84. shutil.rmtree(path)
  85. removed.append(path)
  86. except FileNotFoundError:
  87. continue
  88. except OSError as exc:
  89. failed.append((path, str(exc)))
  90. return removed, failed