Skill Tracer
Skills › BMAD Method › bmad › resolve_customization.py

resolve_customization.py

180 lines · skills/bmad/scripts/resolve_customization.py at bd70c64

1#!/usr/bin/env python3
2# /// script
3# requires-python = ">=3.11"
4# ///
5"""Resolve a skill's default, team, and user TOML customization layers."""
6
7import argparse
8import json
9import sys
10from pathlib import Path
12# Installed scripts are consumer files, not a location for interpreter caches.
13sys.dont_write_bytecode = True
15try:
16 from config_utils import ConfigError, load_customization
17except ModuleNotFoundError as error:
18 if error.name != "tomllib":
19 raise
20 sys.stderr.write("error: Python 3.11+ is required (stdlib `tomllib` not found).\n")
21 raise SystemExit(3) from None
24_MISSING = object()
27def find_project_root(start: Path) -> Path | None:
28 """Nearest ancestor holding `_bmad/`, falling back to the nearest holding `.git`.
30 `_bmad/` outranks `.git` at every depth: a submodule or nested repo carries
31 `.git` without being the BMad project, so treating the two as equal stops the
32 walk short of the root that owns `_bmad/custom/`.
33 """
34 git_root: Path | None = None
35 current = start.resolve()
36 while True:
37 if (current / "_bmad").is_dir():
38 return current
39 if git_root is None and (current / ".git").exists():
40 git_root = current
41 if current.parent == current:
42 return git_root
43 current = current.parent
46def script_project_root() -> Path | None:
47 """Project root implied by this script's own install path.
49 Skills invoke `{project-root}/_bmad/scripts/resolve_customization.py`, so when
50 this file sits at that path its grandparent is a project root the caller already
51 resolved.
52 """
53 parents = Path(__file__).resolve().parents
54 if len(parents) >= 3 and parents[0].name == "scripts" and parents[1].name == "_bmad":
55 return parents[2]
56 return None
59def candidate_project_roots(skill_dir: Path) -> list[Path]:
60 """Plausible project roots, most trustworthy first.
62 The working directory leads because the project is where the user is working,
63 not where the skill happens to be installed — a home-installed skill walks up to
64 `~`, and any `~/_bmad` there would otherwise mask the real project's overrides.
65 """
66 ordered: list[Path] = []
67 for root in (
68 find_project_root(Path.cwd()),
69 script_project_root(),
70 find_project_root(skill_dir),
71 ):
72 if root is not None and root not in ordered:
73 ordered.append(root)
74 return ordered
77def has_override(root: Path, skill_name: str) -> bool:
78 custom_dir = root / "_bmad" / "custom"
79 return any((custom_dir / name).is_file() for name in (f"{skill_name}.toml", f"{skill_name}.user.toml"))
82def warn_on_masked_override(chosen: Path, rejected: list[Path], skill_name: str) -> None:
83 """Break the silence when a real override exists under a root we did not pick."""
84 if has_override(chosen, skill_name):
85 return
86 for root in rejected:
87 if has_override(root, skill_name):
88 sys.stderr.write(
89 f"note: resolved project root {chosen} has no customization for "
90 f"`{skill_name}`, but {root} does. Using {chosen}; pass "
91 f"--project-root to select the other explicitly.\n"
92 )
93 return
96def extract_key(data, dotted_key: str):
97 current = data
98 for part in dotted_key.split("."):
99 if isinstance(current, dict) and part in current:
100 current = current[part]
101 else:
102 return _MISSING
103 return current
106def write_json_stdout(output) -> None:
107 reconfigure = getattr(sys.stdout, "reconfigure", None)
108 if reconfigure is not None:
109 reconfigure(encoding="utf-8")
110 sys.stdout.write(json.dumps(output, indent=2, ensure_ascii=False) + "\n")
113def main() -> int:
114 parser = argparse.ArgumentParser(description="Resolve skill customization using three-layer TOML merge.")
115 parser.add_argument("--skill", "-s", required=True, help="Absolute path to the skill directory")
116 parser.add_argument(
117 "--project-root",
118 "-p",
119 help="Explicit project root containing _bmad/ (recommended)",
120 )
121 parser.add_argument(
122 "--key",
123 "-k",
124 action="append",
125 default=[],
126 help="Dotted field path to resolve (repeatable). Omit for full dump.",
127 )
128 parser.add_argument(
129 "--root",
130 type=Path,
131 action="append",
132 default=[],
133 help="A skills root the host has active, in precedence order, project roots first (repeatable). "
134 "Without it, the setup preflight makes no claim about other skills or the module record.",
135 )
136 args = parser.parse_args()
138 skill_dir = Path(args.skill).resolve()
139 if args.project_root:
140 project_root = Path(args.project_root).resolve()
141 else:
142 candidates = candidate_project_roots(skill_dir)
143 project_root = candidates[0] if candidates else None
144 if project_root is not None:
145 warn_on_masked_override(project_root, candidates[1:], skill_dir.name)
147 try:
148 merged = load_customization(project_root, skill_dir)
149 except ConfigError as error:
150 sys.stderr.write(f"error: {error}\n")
151 return 1
153 output = merged
154 if args.key:
155 output = {}
156 for key in args.key:
157 value = extract_key(merged, key)
158 if value is not _MISSING:
159 output[key] = value
160 write_json_stdout(output)
161 report_owed_setup(skill_dir, project_root, tuple(args.root))
162 return 0
165def report_owed_setup(skill_dir: Path, project_root: Path | None, roots: tuple[Path, ...] = ()) -> None:
166 # The resolver is the first thing every skill runs, so it is where a skill
167 # learns that setup owes it something. It must never fail the resolve.
168 try:
169 import setup_check
170 except Exception:
171 return
172 setup_check.report(skill_dir, project_root, roots)
175if __name__ == "__main__":
176 if sys.platform == "win32":
177 # Piped output on Windows defaults to a legacy code page, not UTF-8.
178 sys.stdout.reconfigure(encoding="utf-8")
179 sys.stderr.reconfigure(encoding="utf-8")
180 raise SystemExit(main())