返回 CodeWhale
check-command-crate-boundaries.py
根目录 / scripts / check-command-crate-boundaries.py
1 #!/usr/bin/env python3
2 """Deterministic crate-boundary gate (FEAT-014, runtime split RS-0).
3
4 The gate is table-driven: `BOUNDARY_RULES` names each guarded package, how its
5 dependency graph is read (`metadata` or `tree`, see below), the packages it
6 may never reach, and the source scan for its crate. The runtime/TUI split adds
7 the runtime -> UI reference ratchet (`scripts/split/module_graph.py`).
8
9 Dependency modes:
10
11 * ``metadata`` reads `cargo metadata --no-deps` and walks normal edges between
12 workspace packages. Cheap and exact for "never reach this workspace crate".
13 * ``tree`` runs `cargo tree -p <package> -e normal,build --prefix none`, which
14 resolves features for that package alone. `cargo metadata` unifies features
15 across the workspace, so a rule like "the runtime never reaches ratatui"
16 must use this mode once the TUI enables palette's `ratatui` feature.
17
18 Enforces the EPIC-006 boundary contract:
19
20 1. `codewhale-command-contract` and `codewhale-secrets` may not transitively
21 depend on `codewhale-tui` (normal edges, via `cargo metadata`).
22 Pure portable sanitization lives in `codewhale-sanitize`; contract, protocol
23 and sanitizer also reject runtime and storage dependencies through tree rules.
24 2. `codewhale-command-contract` source may not import the concrete `App`,
25 widget/renderer/view/event-loop surfaces, or `ratatui`/`crossterm`.
26 3. No composite `CommandContext` symbol (supertrait/struct/enum) may exist in
27 the contract — the deep-dive D2 "no super-context" rule.
28 4. No boxed handler storage (`Box<`) in the contract — the D1/D4 fn-pointer
29 transport rule.
30
31 The guard is hermetic: it reads `cargo metadata` and the contract source only;
32 it never starts the TUI and makes no network calls.
33
34 Usage:
35 python3 scripts/check-command-crate-boundaries.py # enforce
36 """
37
38 from __future__ import annotations
39
40 import argparse
41 import importlib.util
42 import json
43 import re
44 import subprocess
45 import sys
46 from dataclasses import dataclass
47 from pathlib import Path
48 from typing import Callable
49
50 REPO_ROOT = Path(__file__).resolve().parent.parent
51 CONTRACT_DIR = REPO_ROOT / "crates" / "command-contract" / "src"
52 CONTRACT_PACKAGE = "codewhale-command-contract"
53 FORBIDDEN_TUI_PACKAGE = "codewhale-tui"
54
55
56 @dataclass(frozen=True)
57 class BoundaryRule:
58 """One guarded package: how to read its graph and what it may not reach."""
59
60 package: str
61 mode: str # "metadata" or "tree"
62 forbidden_packages: tuple[str, ...]
63 reason: str
64 source_dir: Path | None = None
65 source_scan: Callable[[str, str], list] | None = None
66
67
68 RUNTIME_PACKAGE = "codewhale-runtime"
69 RUNTIME_DIR = REPO_ROOT / "crates" / "runtime" / "src"
70 RUNTIME_FORBIDDEN_PACKAGES = (
71 "codewhale-tui",
72 "codewhale-cli",
73 "ratatui",
74 "ratatui-core",
75 "ratatui-widgets",
76 "crossterm",
77 "ansi-to-tui",
78 "codewhale-tui-kit",
79 "codewhale-ratatui",
80 )
81 RUNTIME_FORBIDDEN_SOURCE = [
82 (re.compile(r"\b(ratatui|crossterm|codewhale_tui)::"), "terminal UI path"),
83 (re.compile(r"^\s*(pub\s+)?use\s+(ratatui|crossterm|codewhale_tui)\b"), "terminal UI import"),
84 (re.compile(r"include_(str|bytes)!\(\s*\"[^\"]*\.\./tui/"), "include reaching into crates/tui"),
85 ]
86
87 # Filled in below once the scan functions exist.
88 BOUNDARY_RULES: tuple[BoundaryRule, ...] = ()
89
90 # Import lines that must never appear in the contract (narrowly scoped: real
91 # imports only, comments never match because they do not start with `use`).
92 FORBIDDEN_IMPORT_PATTERNS = [
93 (re.compile(r"^\s*(pub\s+)?use\s+codewhale_tui\b"), "codewhale-tui import"),
94 (re.compile(r"^\s*(pub\s+)?use\s+ratatui\b"), "ratatui (widget) import"),
95 (re.compile(r"^\s*(pub\s+)?use\s+crossterm\b"), "crossterm (terminal) import"),
96 (re.compile(r"^\s*(pub\s+)?use\s+.*\bApp\b"), "concrete App import"),
97 (re.compile(r"^\s*(pub\s+)?use\s+.*\bBuffer\b"), "render buffer import"),
98 (re.compile(r"^\s*(pub\s+)?use\s+.*\bWidget\b"), "widget import"),
99 (re.compile(r"^\s*(pub\s+)?use\s+.*\bViewStack\b"), "view-stack import"),
100 (re.compile(r"^\s*(pub\s+)?use\s+.*\bEventLoop\b"), "event-loop import"),
101 ]
102
103 # Composite super-context symbols (D2: exactly `CommandContext`, not the
104 # plural envelope `CommandContexts` nor facet names like `CommandModelContext`).
105 COMPOSITE_SYMBOL_PATTERN = re.compile(
106 r"^\s*(pub\s+)?(trait|struct|enum)\s+CommandContext\b"
107 )
108 # Boxed handler/closure storage (D1: fn pointers only).
109 BOXED_STORAGE_PATTERN = re.compile(r"\bBox\s*<")
110
111
112 class BoundaryViolation:
113 """One deterministic boundary violation with an actionable diagnostic."""
114
115 def __init__(self, category: str, location: str, detail: str) -> None:
116 self.category = category
117 self.location = location
118 self.detail = detail
119
120 def __str__(self) -> str:
121 return f"{self.category}: {self.location}: {self.detail}"
122
123
124 def load_workspace_metadata() -> dict:
125 """Load the locked workspace dependency graph via cargo metadata."""
126 result = subprocess.run(
127 [
128 "cargo",
129 "metadata",
130 "--format-version",
131 "1",
132 "--locked",
133 "--no-deps",
134 ],
135 cwd=REPO_ROOT,
136 capture_output=True,
137 text=True,
138 check=True,
139 )
140 return json.loads(result.stdout)
141
142
143 def dependency_graph(metadata: dict) -> dict[str, set[str]]:
144 """Map package name -> set of direct NORMAL dependency package names.
145
146 Dev- and build-dependencies are excluded: the gate contract checks normal
147 transitive edges (a dev-dependency on the TUI, e.g. for acceptance
148 harnesses, must not trip the boundary).
149 """
150 graph: dict[str, set[str]] = {}
151 for package in metadata["packages"]:
152 deps = set()
153 for dep in package.get("dependencies", []):
154 # kind is None for normal dependencies, "dev" or "build" otherwise.
155 if dep.get("kind") is not None:
156 continue
157 name = dep.get("name")
158 if name:
159 deps.add(name)
160 graph[package["name"]] = deps
161 return graph
162
163
164 def reaches(package: str, forbidden: set[str], graph: dict[str, set[str]]) -> str | None:
165 """The first forbidden package `package` transitively reaches, if any."""
166 seen: set[str] = set()
167 stack = list(graph.get(package, set()))
168 while stack:
169 name = stack.pop()
170 if name in forbidden:
171 return name
172 if name in seen:
173 continue
174 seen.add(name)
175 stack.extend(graph.get(name, set()))
176 return None
177
178
179 def reaches_tui(package: str, graph: dict[str, set[str]]) -> bool:
180 """Whether `package` transitively reaches the forbidden TUI package."""
181 return reaches(package, {FORBIDDEN_TUI_PACKAGE}, graph) is not None
182
183
184 def metadata_rules() -> tuple[BoundaryRule, ...]:
185 return tuple(rule for rule in BOUNDARY_RULES if rule.mode == "metadata")
186
187
188 def tree_rules() -> tuple[BoundaryRule, ...]:
189 return tuple(rule for rule in BOUNDARY_RULES if rule.mode == "tree")
190
191
192 def check_dependency_graph(graph: dict[str, set[str]]) -> list[BoundaryViolation]:
193 """No metadata-mode package may reach a forbidden package through normal edges."""
194 violations: list[BoundaryViolation] = []
195 for rule in metadata_rules():
196 package = rule.package
197 if package not in graph:
198 violations.append(
199 BoundaryViolation(
200 "dependency-graph",
201 package,
202 "workspace package missing from the cargo metadata graph",
203 )
204 )
205 continue
206 hit = reaches(package, set(rule.forbidden_packages), graph)
207 if hit:
208 violations.append(
209 BoundaryViolation(
210 "dependency-graph",
211 package,
212 f"transitively depends on {hit} ({rule.reason})",
213 )
214 )
215 return violations
216
217
218 def cargo_tree_packages(package: str) -> set[str]:
219 """Package names in `cargo tree -p <package> -e normal,build` (per-package features)."""
220 result = subprocess.run(
221 # `--target all`: a dependency behind `cfg(windows)` counts too, not
222 # only the ones the host target resolves.
223 [
224 "cargo", "tree", "-p", package, "-e", "normal,build", "--target", "all",
225 "--prefix", "none", "--locked",
226 ],
227 cwd=REPO_ROOT,
228 capture_output=True,
229 text=True,
230 check=True,
231 )
232 return parse_cargo_tree(result.stdout)
233
234
235 def parse_cargo_tree(text: str) -> set[str]:
236 names: set[str] = set()
237 for line in text.splitlines():
238 parts = line.split()
239 if parts:
240 names.add(parts[0])
241 return names
242
243
244 def check_tree_packages(rule: BoundaryRule, names: set[str]) -> list[BoundaryViolation]:
245 """A tree-mode package's resolved dependency set must avoid its forbidden list."""
246 return [
247 BoundaryViolation(
248 "dependency-tree",
249 rule.package,
250 f"cargo tree reaches {name} ({rule.reason})",
251 )
252 for name in sorted(names & set(rule.forbidden_packages))
253 ]
254
255
256 def check_contract_source_text(text: str, display_path: str) -> list[BoundaryViolation]:
257 """Scan one source text for forbidden imports/symbols (hermetic test hook)."""
258 violations: list[BoundaryViolation] = []
259 for line_no, line in enumerate(text.splitlines(), start=1):
260 stripped = line.strip()
261 for pattern, label in FORBIDDEN_IMPORT_PATTERNS:
262 if pattern.match(stripped):
263 violations.append(
264 BoundaryViolation(
265 "source-scan",
266 f"{display_path}:{line_no}",
267 f"forbidden {label}: {stripped}",
268 )
269 )
270 if COMPOSITE_SYMBOL_PATTERN.match(stripped):
271 violations.append(
272 BoundaryViolation(
273 "source-scan",
274 f"{display_path}:{line_no}",
275 f"composite CommandContext symbol (D2 forbids super-contexts): {stripped}",
276 )
277 )
278 if BOXED_STORAGE_PATTERN.search(stripped):
279 violations.append(
280 BoundaryViolation(
281 "source-scan",
282 f"{display_path}:{line_no}",
283 f"boxed storage in the contract (D1 requires fn pointers): {stripped}",
284 )
285 )
286 return violations
287
288
289 def check_source_dir(rule: BoundaryRule) -> list[BoundaryViolation]:
290 """Scan one rule's production source for forbidden imports and symbols."""
291 assert rule.source_dir is not None and rule.source_scan is not None
292 if not rule.source_dir.is_dir():
293 return [
294 BoundaryViolation(
295 "source-scan",
296 str(rule.source_dir),
297 f"{rule.package} src directory missing",
298 )
299 ]
300 violations: list[BoundaryViolation] = []
301 for path in sorted(rule.source_dir.rglob("*.rs")):
302 text = path.read_text(encoding="utf-8")
303 rel = path.relative_to(REPO_ROOT)
304 violations.extend(rule.source_scan(text, str(rel)))
305 return violations
306
307
308 def check_runtime_source_text(text: str, display_path: str) -> list[BoundaryViolation]:
309 """Runtime source may not name a terminal UI crate (comments ignored)."""
310 violations: list[BoundaryViolation] = []
311 for line_no, line in enumerate(text.splitlines(), start=1):
312 code = line.split("//", 1)[0]
313 if not code.strip():
314 continue
315 for pattern, label in RUNTIME_FORBIDDEN_SOURCE:
316 if pattern.search(code):
317 violations.append(
318 BoundaryViolation(
319 "source-scan",
320 f"{display_path}:{line_no}",
321 f"forbidden {label} in codewhale-runtime: {line.strip()}",
322 )
323 )
324 return violations
325
326
327 def check_contract_source() -> list[BoundaryViolation]:
328 """Scan contract production source for forbidden imports and symbols."""
329 return check_source_dir(next(r for r in BOUNDARY_RULES if r.package == CONTRACT_PACKAGE))
330
331
332 def load_script(relative: str, name: str):
333 """Import a repository script by path."""
334 spec = importlib.util.spec_from_file_location(name, REPO_ROOT / relative)
335 assert spec and spec.loader
336 module = importlib.util.module_from_spec(spec)
337 sys.modules[spec.name] = module
338 spec.loader.exec_module(module)
339 return module
340
341
342 def load_runtime_ratchet():
343 """Import scripts/split/module_graph.py (the runtime -> UI ratchet)."""
344 return load_script("scripts/split/module_graph.py", "runtime_module_graph")
345
346
347 def detect_baseline_ref() -> str | None:
348 """The merge-base with origin/main, or HEAD's parent on main."""
349 manifest = load_script("scripts/check-command-migration-manifest.py", "command_migration_manifest")
350 return manifest.detect_local_baseline_ref(REPO_ROOT)
351
352
353 def check_runtime_ratchet(baseline_ref: str | None = None) -> list[BoundaryViolation]:
354 """Runtime -> UI references may only go down (docs/design/TUI_DECONSTRUCTION.md, runtime split)."""
355 problems = load_runtime_ratchet().check(baseline_ref=baseline_ref)
356 return [BoundaryViolation("runtime-ratchet", "scripts/runtime-boundary-baseline.json", p) for p in problems]
357
358
359 def run_checks(
360 metadata: dict | None = None,
361 tree: Callable[[str], set[str]] | None = None,
362 ratchet: bool = True,
363 baseline_ref: str | None = None,
364 ) -> list[BoundaryViolation]:
365 """Run all boundary checks; return the collected violations."""
366 graph = dependency_graph(metadata) if metadata is not None else dependency_graph(
367 load_workspace_metadata()
368 )
369 violations = check_dependency_graph(graph)
370 tree = tree or cargo_tree_packages
371 for rule in tree_rules():
372 violations.extend(check_tree_packages(rule, tree(rule.package)))
373 for rule in BOUNDARY_RULES:
374 if rule.source_dir is not None:
375 violations.extend(check_source_dir(rule))
376 if ratchet:
377 violations.extend(check_runtime_ratchet(baseline_ref))
378 return violations
379
380
381 def main(argv: list[str] | None = None) -> int:
382 parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0])
383 parser.add_argument(
384 "--baseline-ref",
385 help=(
386 "git revision whose runtime ratchet baseline may not be exceeded "
387 "(default: the merge-base with origin/main, or HEAD^ on main)"
388 ),
389 )
390 args = parser.parse_args(argv)
391 violations = run_checks(baseline_ref=args.baseline_ref or detect_baseline_ref())
392 if violations:
393 print("[command-crate-boundaries] FAIL", file=sys.stderr)
394 for violation in violations:
395 print(f" {violation}", file=sys.stderr)
396 return 1
397 print(
398 f"[command-crate-boundaries] PASS: "
399 f"{', '.join(rule.package for rule in BOUNDARY_RULES)} avoid their forbidden "
400 "packages; no forbidden import, composite context, or boxed handler in the "
401 "contract; runtime -> UI ratchet holds"
402 )
403 return 0
404
405
406 BOUNDARY_RULES = (
407 # The contract carries the portable command shapes (EPIC-006).
408 BoundaryRule(
409 CONTRACT_PACKAGE,
410 "metadata",
411 (FORBIDDEN_TUI_PACKAGE,),
412 "the command contract must stay UI-free",
413 CONTRACT_DIR,
414 check_contract_source_text,
415 ),
416 # Storage remains UI-free; portable callers use codewhale-sanitize directly.
417 BoundaryRule(
418 "codewhale-secrets",
419 "metadata",
420 (FORBIDDEN_TUI_PACKAGE,),
421 "secret storage must stay UI-free",
422 ),
423 *(BoundaryRule(
424 package, "tree",
425 ("codewhale-tui", "codewhale-core", "codewhale-runtime", "codewhale-config",
426 "codewhale-state", "codewhale-mcp", "codewhale-hooks", "codewhale-secrets",
427 "reqwest", "tokio", "rusqlite", "keyring", "dbus", "zbus", "ratatui", "crossterm"),
428 "portable shapes and sanitization must not import host services",
429 ) for package in ("codewhale-command-contract", "codewhale-commands", "codewhale-protocol", "codewhale-app-server-protocol", "codewhale-sanitize")),
430 # The headless runtime split out of the TUI (docs/design/TUI_DECONSTRUCTION.md):
431 # never a terminal UI crate or library, checked with per-package feature
432 # resolution because the TUI turns on palette's `ratatui` feature.
433 BoundaryRule(
434 RUNTIME_PACKAGE,
435 "tree",
436 RUNTIME_FORBIDDEN_PACKAGES,
437 "the runtime must not link terminal UI code",
438 RUNTIME_DIR,
439 check_runtime_source_text,
440 ),
441 )
442 TUI_FREE_PACKAGES = tuple(rule.package for rule in metadata_rules())
443
444
445 if __name__ == "__main__":
446 sys.exit(main())
447
447 lines PYTHON