cleanup-legacy.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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(bmad_dir: str, dirs_to_remove: list, verbose: bool = False) -> tuple:
  126. """Remove specified directories under bmad_dir.
  127. Returns:
  128. (removed, not_found, total_files_removed) tuple
  129. """
  130. removed = []
  131. not_found = []
  132. total_files = 0
  133. for dirname in dirs_to_remove:
  134. target = Path(bmad_dir) / dirname
  135. if not target.exists():
  136. not_found.append(dirname)
  137. if verbose:
  138. print(f"Not found (skipping): {target}", file=sys.stderr)
  139. continue
  140. if not target.is_dir():
  141. if verbose:
  142. print(f"Not a directory (skipping): {target}", file=sys.stderr)
  143. not_found.append(dirname)
  144. continue
  145. file_count = count_files(target)
  146. if verbose:
  147. print(
  148. f"Removing {target} ({file_count} files)",
  149. file=sys.stderr,
  150. )
  151. try:
  152. shutil.rmtree(target)
  153. except OSError as e:
  154. error_result = {
  155. "status": "error",
  156. "error": f"Failed to remove {target}: {e}",
  157. "directories_removed": removed,
  158. "directories_failed": dirname,
  159. }
  160. print(json.dumps(error_result, indent=2))
  161. sys.exit(2)
  162. removed.append(dirname)
  163. total_files += file_count
  164. return removed, not_found, total_files
  165. def reject_unresolved_paths(named_paths: list[tuple[str, str]]) -> None:
  166. """Exit with a clear error if any path argument still contains the literal
  167. ``{project-root}`` token. That token is meaningful only inside config
  168. values; filesystem path arguments must be resolved by the caller. Failing
  169. loudly here prevents silently operating on a junk ``{project-root}/`` directory.
  170. """
  171. for name, value in named_paths:
  172. if value and "{project-root}" in value:
  173. print(
  174. json.dumps(
  175. {
  176. "status": "error",
  177. "error": (
  178. f"Unresolved '{{project-root}}' token in {name} path: {value!r}. "
  179. "Resolve '{project-root}' to the actual project root before running "
  180. "this script — it is a filesystem path, not a config value."
  181. ),
  182. },
  183. indent=2,
  184. )
  185. )
  186. sys.exit(1)
  187. def main():
  188. args = parse_args()
  189. reject_unresolved_paths([("--bmad-dir", args.bmad_dir), ("--skills-dir", args.skills_dir)])
  190. bmad_dir = args.bmad_dir
  191. module_code = args.module_code
  192. # Build the list of directories to remove
  193. dirs_to_remove = [module_code, "core"] + args.also_remove
  194. # Deduplicate while preserving order
  195. seen = set()
  196. unique_dirs = []
  197. for d in dirs_to_remove:
  198. if d not in seen:
  199. seen.add(d)
  200. unique_dirs.append(d)
  201. dirs_to_remove = unique_dirs
  202. if args.verbose:
  203. print(f"Directories to remove: {dirs_to_remove}", file=sys.stderr)
  204. # Safety check: verify skills are installed before removing
  205. verified_skills = None
  206. if args.skills_dir:
  207. if args.verbose:
  208. print(
  209. f"Verifying skills installed at {args.skills_dir}",
  210. file=sys.stderr,
  211. )
  212. verified_skills = verify_skills_installed(
  213. bmad_dir, dirs_to_remove, args.skills_dir, args.verbose
  214. )
  215. # Remove directories
  216. removed, not_found, total_files = cleanup_directories(bmad_dir, dirs_to_remove, args.verbose)
  217. # Build result
  218. result = {
  219. "status": "success",
  220. "bmad_dir": str(Path(bmad_dir).resolve()),
  221. "directories_removed": removed,
  222. "directories_not_found": not_found,
  223. "files_removed_count": total_files,
  224. }
  225. if args.skills_dir:
  226. result["safety_checks"] = {
  227. "skills_verified": True,
  228. "skills_dir": str(Path(args.skills_dir).resolve()),
  229. "verified_skills": verified_skills,
  230. }
  231. else:
  232. result["safety_checks"] = None
  233. print(json.dumps(result, indent=2))
  234. if __name__ == "__main__":
  235. main()