cleanup-legacy.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. #!/usr/bin/env python3
  2. # /// script
  3. # requires-python = ">=3.9"
  4. # dependencies = []
  5. # ///
  6. """Remove legacy module directories from _bmad/ after config migration.
  7. After merge-config.py and merge-help-csv.py have migrated config data and
  8. deleted individual legacy files, this script removes the now-redundant
  9. directory trees. These directories contain skill files that are already
  10. installed at .claude/skills/ (or equivalent) — only the config files at
  11. _bmad/ root need to persist.
  12. When --skills-dir is provided, the script verifies that every skill found
  13. in the legacy directories exists at the installed location before removing
  14. anything. Directories without skills (like _config/) are removed directly.
  15. Exit codes: 0=success (including nothing to remove), 1=validation error, 2=runtime error
  16. """
  17. import argparse
  18. import json
  19. import shutil
  20. import sys
  21. from pathlib import Path
  22. def parse_args():
  23. parser = argparse.ArgumentParser(
  24. description="Remove legacy module directories from _bmad/ after config migration."
  25. )
  26. parser.add_argument(
  27. "--bmad-dir",
  28. required=True,
  29. help="Path to the _bmad/ directory",
  30. )
  31. parser.add_argument(
  32. "--module-code",
  33. required=True,
  34. help="Module code being cleaned up (e.g. 'bmb')",
  35. )
  36. parser.add_argument(
  37. "--also-remove",
  38. action="append",
  39. default=[],
  40. help="Additional directory names under _bmad/ to remove (repeatable)",
  41. )
  42. parser.add_argument(
  43. "--skills-dir",
  44. help="Path to .claude/skills/ — enables safety verification that skills "
  45. "are installed before removing legacy copies",
  46. )
  47. parser.add_argument(
  48. "--verbose",
  49. action="store_true",
  50. help="Print detailed progress to stderr",
  51. )
  52. return parser.parse_args()
  53. def find_skill_dirs(base_path: str) -> list:
  54. """Find directories that contain a SKILL.md file.
  55. Walks the directory tree and returns the leaf directory name for each
  56. directory containing a SKILL.md. These are considered skill directories.
  57. Returns:
  58. List of skill directory names (e.g. ['bmad-agent-builder', 'bmad-builder-setup'])
  59. """
  60. skills = []
  61. root = Path(base_path)
  62. if not root.exists():
  63. return skills
  64. for skill_md in root.rglob("SKILL.md"):
  65. skills.append(skill_md.parent.name)
  66. return sorted(set(skills))
  67. def verify_skills_installed(
  68. bmad_dir: str, dirs_to_check: list, skills_dir: str, verbose: bool = False
  69. ) -> list:
  70. """Verify that skills in legacy directories exist at the installed location.
  71. Scans each directory in dirs_to_check for skill folders (containing SKILL.md),
  72. then checks that a matching directory exists under skills_dir. Directories
  73. that contain no skills (like _config/) are silently skipped.
  74. Returns:
  75. List of verified skill names.
  76. Raises SystemExit(1) if any skills are missing from skills_dir.
  77. """
  78. all_verified = []
  79. missing = []
  80. for dirname in dirs_to_check:
  81. legacy_path = Path(bmad_dir) / dirname
  82. if not legacy_path.exists():
  83. continue
  84. skill_names = find_skill_dirs(str(legacy_path))
  85. if not skill_names:
  86. if verbose:
  87. print(
  88. f"No skills found in {dirname}/ — skipping verification",
  89. file=sys.stderr,
  90. )
  91. continue
  92. for skill_name in skill_names:
  93. installed_path = Path(skills_dir) / skill_name
  94. if installed_path.is_dir():
  95. all_verified.append(skill_name)
  96. if verbose:
  97. print(
  98. f"Verified: {skill_name} exists at {installed_path}",
  99. file=sys.stderr,
  100. )
  101. else:
  102. missing.append(skill_name)
  103. if verbose:
  104. print(
  105. f"MISSING: {skill_name} not found at {installed_path}",
  106. file=sys.stderr,
  107. )
  108. if missing:
  109. error_result = {
  110. "status": "error",
  111. "error": "Skills not found at installed location",
  112. "missing_skills": missing,
  113. "skills_dir": str(Path(skills_dir).resolve()),
  114. }
  115. print(json.dumps(error_result, indent=2))
  116. sys.exit(1)
  117. return sorted(set(all_verified))
  118. def count_files(path: Path) -> int:
  119. """Count all files recursively in a directory."""
  120. count = 0
  121. for item in path.rglob("*"):
  122. if item.is_file():
  123. count += 1
  124. return count
  125. def cleanup_directories(
  126. bmad_dir: str, dirs_to_remove: list, verbose: bool = False
  127. ) -> tuple:
  128. """Remove specified directories under bmad_dir.
  129. Returns:
  130. (removed, not_found, total_files_removed) tuple
  131. """
  132. removed = []
  133. not_found = []
  134. total_files = 0
  135. for dirname in dirs_to_remove:
  136. target = Path(bmad_dir) / dirname
  137. if not target.exists():
  138. not_found.append(dirname)
  139. if verbose:
  140. print(f"Not found (skipping): {target}", file=sys.stderr)
  141. continue
  142. if not target.is_dir():
  143. if verbose:
  144. print(f"Not a directory (skipping): {target}", file=sys.stderr)
  145. not_found.append(dirname)
  146. continue
  147. file_count = count_files(target)
  148. if verbose:
  149. print(
  150. f"Removing {target} ({file_count} files)",
  151. file=sys.stderr,
  152. )
  153. try:
  154. shutil.rmtree(target)
  155. except OSError as e:
  156. error_result = {
  157. "status": "error",
  158. "error": f"Failed to remove {target}: {e}",
  159. "directories_removed": removed,
  160. "directories_failed": dirname,
  161. }
  162. print(json.dumps(error_result, indent=2))
  163. sys.exit(2)
  164. removed.append(dirname)
  165. total_files += file_count
  166. return removed, not_found, total_files
  167. def reject_unresolved_paths(named_paths: list[tuple[str, str]]) -> None:
  168. """Exit with a clear error if any path argument still contains the literal
  169. ``{project-root}`` token. That token is meaningful only inside config
  170. values; filesystem path arguments must be resolved by the caller. Failing
  171. loudly here prevents silently operating on a junk ``{project-root}/`` directory.
  172. """
  173. for name, value in named_paths:
  174. if value and "{project-root}" in value:
  175. print(
  176. json.dumps(
  177. {
  178. "status": "error",
  179. "error": (
  180. f"Unresolved '{{project-root}}' token in {name} path: {value!r}. "
  181. "Resolve '{project-root}' to the actual project root before running "
  182. "this script — it is a filesystem path, not a config value."
  183. ),
  184. },
  185. indent=2,
  186. )
  187. )
  188. sys.exit(1)
  189. def main():
  190. args = parse_args()
  191. reject_unresolved_paths(
  192. [("--bmad-dir", args.bmad_dir), ("--skills-dir", args.skills_dir)]
  193. )
  194. bmad_dir = args.bmad_dir
  195. module_code = args.module_code
  196. # Build the list of directories to remove
  197. dirs_to_remove = [module_code, "core"] + args.also_remove
  198. # Deduplicate while preserving order
  199. seen = set()
  200. unique_dirs = []
  201. for d in dirs_to_remove:
  202. if d not in seen:
  203. seen.add(d)
  204. unique_dirs.append(d)
  205. dirs_to_remove = unique_dirs
  206. if args.verbose:
  207. print(f"Directories to remove: {dirs_to_remove}", file=sys.stderr)
  208. # Safety check: verify skills are installed before removing
  209. verified_skills = None
  210. if args.skills_dir:
  211. if args.verbose:
  212. print(
  213. f"Verifying skills installed at {args.skills_dir}",
  214. file=sys.stderr,
  215. )
  216. verified_skills = verify_skills_installed(
  217. bmad_dir, dirs_to_remove, args.skills_dir, args.verbose
  218. )
  219. # Remove directories
  220. removed, not_found, total_files = cleanup_directories(
  221. bmad_dir, dirs_to_remove, args.verbose
  222. )
  223. # Build result
  224. result = {
  225. "status": "success",
  226. "bmad_dir": str(Path(bmad_dir).resolve()),
  227. "directories_removed": removed,
  228. "directories_not_found": not_found,
  229. "files_removed_count": total_files,
  230. }
  231. if args.skills_dir:
  232. result["safety_checks"] = {
  233. "skills_verified": True,
  234. "skills_dir": str(Path(args.skills_dir).resolve()),
  235. "verified_skills": verified_skills,
  236. }
  237. else:
  238. result["safety_checks"] = None
  239. print(json.dumps(result, indent=2))
  240. if __name__ == "__main__":
  241. main()