| 1 | #!/usr/bin/env python3 |
| 2 | """Runtime -> UI boundary ratchet for the runtime/TUI crate split. |
| 3 | |
| 4 | Builds the top-level module graph of `crates/tui/src`, `crates/engine/src` |
| 5 | `crates/app-server/src` and `crates/runtime/src` |
| 6 | with a lexer that masks comments and string literals and expands grouped |
| 7 | `use crate::{...}` imports, then counts every reference from the *runtime |
| 8 | closure* upward into UI code. |
| 9 | |
| 10 | The runtime closure is every module reachable over production edges from the |
| 11 | eight seed modules (`core`, `tools`, `runtime_api`, `runtime_threads`, |
| 12 | `client`, `llm_client`, `config`, `session_manager`) without passing through a |
| 13 | UI module, plus every module that already lives in `crates/runtime`. It is |
| 14 | computed on every run; the member list is never written by hand. |
| 15 | |
| 16 | Categories counted (keyed `from|to`): |
| 17 | |
| 18 | * ``prod`` production references from the closure into UI modules |
| 19 | (`tui`, `commands`, `context_report`, |
| 20 | `composer_*`) or into private crate-root (`lib.rs`) items; |
| 21 | * ``test`` the same, from `#[cfg(test)]` code and test files; |
| 22 | * ``late`` references (production or test) from the closure into modules |
| 23 | outside it that are not UI either, i.e. modules that move after |
| 24 | the strongly connected core (`exec_agent`, `route_preferences`, |
| 25 | ...). A test edge constrains a crate move exactly like a |
| 26 | production edge; |
| 27 | * ``uilib`` closure files that use a UI library (`ratatui`, `crossterm`, |
| 28 | `codewhale_tui`), keyed `module|library`. `codewhale_palette` is |
| 29 | not one since its `ratatui` feature became optional (RS-3); the |
| 30 | runtime links it with `default-features = false`; |
| 31 | * ``doc`` intra-doc links in closure doc comments that point at UI code |
| 32 | (`crate::tui::...`, `crate::commands::...`). rustdoc checks them |
| 33 | once the module is public in `codewhale-runtime`. |
| 34 | |
| 35 | The baseline is `scripts/runtime-boundary-baseline.json`. `--check` (default) |
| 36 | fails on any increased count or new key and prints `file:line` for it; it also |
| 37 | fails when a count dropped and the baseline was not lowered in the same change, |
| 38 | so the baseline stays honest. `--update` rewrites the baseline and refuses to |
| 39 | raise any count. `--baseline-ref REV` also fails when the committed baseline |
| 40 | holds any count above the baseline at REV, so a hand-edited JSON cannot raise |
| 41 | the ratchet either; scripts/check-command-crate-boundaries.py passes the |
| 42 | merge-base with origin/main, or HEAD^ on main. |
| 43 | |
| 44 | `super::` chains that climb to the crate root count like `crate::` paths. |
| 45 | |
| 46 | See docs/design/TUI_DECONSTRUCTION.md (runtime split, ratchet). |
| 47 | """ |
| 48 | |
| 49 | from __future__ import annotations |
| 50 | |
| 51 | import argparse |
| 52 | import collections |
| 53 | import json |
| 54 | import importlib.util |
| 55 | import os |
| 56 | import re |
| 57 | import subprocess |
| 58 | import sys |
| 59 | from dataclasses import dataclass, field |
| 60 | from pathlib import Path |
| 61 | |
| 62 | REPO_ROOT = Path(__file__).resolve().parents[2] |
| 63 | TUI_SRC = REPO_ROOT / "crates" / "tui" / "src" |
| 64 | RUNTIME_SRC = REPO_ROOT / "crates" / "runtime" / "src" |
| 65 | ENGINE_SRC = REPO_ROOT / "crates" / "engine" / "src" |
| 66 | APP_SERVER_SRC = REPO_ROOT / "crates" / "app-server" / "src" |
| 67 | BASELINE_REPO_PATH = "scripts/runtime-boundary-baseline.json" |
| 68 | BASELINE = REPO_ROOT / BASELINE_REPO_PATH |
| 69 | |
| 70 | SEEDS = ( |
| 71 | "core", |
| 72 | "tools", |
| 73 | "runtime_api", |
| 74 | "runtime_threads", |
| 75 | "client", |
| 76 | "llm_client", |
| 77 | "config", |
| 78 | "session_manager", |
| 79 | ) |
| 80 | UI_MODULES = {"tui", "commands", "context_report"} |
| 81 | UI_PREFIXES = ("composer_",) |
| 82 | ROOT_ITEMS = "lib.rs" |
| 83 | CATEGORIES = ("prod", "test", "late", "uilib", "doc") |
| 84 | |
| 85 | HINTS = { |
| 86 | "tui": "move the item down (e.g. into core::authority) or reach the UI " |
| 87 | "through the host_terminal port", |
| 88 | "commands": "read commands through the runtime CommandCatalog, or split " |
| 89 | "the non-UI half of the command into a runtime module", |
| 90 | ROOT_ITEMS: "move the crate-root helper into the runtime module that owns it", |
| 91 | } |
| 92 | |
| 93 | |
| 94 | def is_ui(module: str) -> bool: |
| 95 | return ( |
| 96 | module in UI_MODULES |
| 97 | or module.startswith(UI_PREFIXES) |
| 98 | or module in (ROOT_ITEMS, "main.rs") |
| 99 | ) |
| 100 | |
| 101 | |
| 102 | # -------------------------------------------------------------------------- |
| 103 | # Lexer: blank comments, string and char literals; keep offsets and newlines. |
| 104 | # -------------------------------------------------------------------------- |
| 105 | |
| 106 | _RAW_STR = re.compile(r'b?r(#*)"') |
| 107 | _CHAR = re.compile(r"'(\\.[^']*|[^\\'])'") |
| 108 | _START = re.compile(r'//|/\*|b?r#*"|b?"|\'') |
| 109 | _BLOCK = re.compile(r'/\*|\*/') |
| 110 | _STR_STOP = re.compile(r'[\\"]') |
| 111 | _NOT_NL = re.compile(r'[^\n]') |
| 112 | |
| 113 | |
| 114 | def lex_mask(src: str) -> str: |
| 115 | n = len(src) |
| 116 | out = [] |
| 117 | last = 0 |
| 118 | i = 0 |
| 119 | |
| 120 | def blank(a, b): |
| 121 | nonlocal last |
| 122 | b = min(b, n) |
| 123 | if a >= b: |
| 124 | return |
| 125 | out.append(src[last:a]) |
| 126 | out.append(_NOT_NL.sub(" ", src[a:b])) |
| 127 | last = b |
| 128 | |
| 129 | search = _START.search |
| 130 | while True: |
| 131 | m = search(src, i) |
| 132 | if not m: |
| 133 | break |
| 134 | i = m.start() |
| 135 | c = src[i] |
| 136 | if src.startswith("//", i): |
| 137 | j = src.find("\n", i) |
| 138 | j = n if j < 0 else j |
| 139 | blank(i, j) |
| 140 | i = j |
| 141 | continue |
| 142 | if src.startswith("/*", i): |
| 143 | depth, j = 1, i + 2 |
| 144 | while j < n and depth: |
| 145 | mm = _BLOCK.search(src, j) |
| 146 | if not mm: |
| 147 | j = n |
| 148 | break |
| 149 | if mm.group(0) == "/*": |
| 150 | depth += 1 |
| 151 | else: |
| 152 | depth -= 1 |
| 153 | j = mm.end() |
| 154 | blank(i, j) |
| 155 | i = j |
| 156 | continue |
| 157 | prev_ident = i > 0 and (src[i - 1].isalnum() or src[i - 1] == "_") |
| 158 | rm = _RAW_STR.match(src, i, i + 10) |
| 159 | if rm and not prev_ident: |
| 160 | end = '"' + rm.group(1) |
| 161 | j = src.find(end, i + len(rm.group(0))) |
| 162 | j = n if j < 0 else j + len(end) |
| 163 | blank(i + 1, j - 1) |
| 164 | i = j |
| 165 | continue |
| 166 | if c == '"' or (c == "b" and i + 1 < n and src[i + 1] == '"' and not prev_ident): |
| 167 | j = i + (2 if c == "b" else 1) |
| 168 | while j < n and src[j] != '"': |
| 169 | sm = _STR_STOP.search(src, j) |
| 170 | if not sm: |
| 171 | j = n |
| 172 | break |
| 173 | j = sm.start() |
| 174 | if src[j] == "\\": |
| 175 | j += 2 |
| 176 | blank(i + 1, j) |
| 177 | i = j + 1 |
| 178 | continue |
| 179 | if c == "'": |
| 180 | cm = _CHAR.match(src, i, i + 12) |
| 181 | if cm: |
| 182 | blank(i + 1, i + len(cm.group(0)) - 1) |
| 183 | i += len(cm.group(0)) |
| 184 | continue |
| 185 | i += 1 |
| 186 | out.append(src[last:]) |
| 187 | return "".join(out) |
| 188 | |
| 189 | |
| 190 | def match_brace(code: str, start: int) -> int: |
| 191 | depth = 0 |
| 192 | for k in range(start, len(code)): |
| 193 | if code[k] == "{": |
| 194 | depth += 1 |
| 195 | elif code[k] == "}": |
| 196 | depth -= 1 |
| 197 | if depth == 0: |
| 198 | return k |
| 199 | return len(code) - 1 |
| 200 | |
| 201 | |
| 202 | CFG_TEST = re.compile( |
| 203 | r"#\[cfg\((?:test|all\(test[^\]]*\)|any\(test[^\]]*\)|feature\s*=\s*\"test-support\")\)\]" |
| 204 | ) |
| 205 | |
| 206 | |
| 207 | def strip_cfg_test(code: str, test_mod_decls: list[str]) -> str: |
| 208 | """Blank items annotated `#[cfg(test)]`; collect `mod x;` declarations.""" |
| 209 | out = list(code) |
| 210 | for m in CFG_TEST.finditer(code): |
| 211 | j = m.end() |
| 212 | while True: |
| 213 | ws = re.match(r"\s*(#\[[^\]]*\])?", code[j:]) |
| 214 | if ws and ws.group(1): |
| 215 | j += ws.end() |
| 216 | continue |
| 217 | j += len(code[j:]) - len(code[j:].lstrip()) |
| 218 | break |
| 219 | md = re.match(r"(pub(\([^)]*\))?\s+)?mod\s+(\w+)\s*;", code[j:]) |
| 220 | if md: |
| 221 | test_mod_decls.append(md.group(3)) |
| 222 | semi = code.find(";", j) |
| 223 | brace = code.find("{", j) |
| 224 | if brace >= 0 and (semi < 0 or brace < semi): |
| 225 | end = match_brace(code, brace) |
| 226 | else: |
| 227 | end = semi if semi >= 0 else j |
| 228 | for k in range(m.start(), end + 1): |
| 229 | if out[k] != "\n": |
| 230 | out[k] = " " |
| 231 | return "".join(out) |
| 232 | |
| 233 | |
| 234 | def is_test_path(rel: str) -> bool: |
| 235 | base = os.path.basename(rel) |
| 236 | return ( |
| 237 | "/tests/" in "/" + rel |
| 238 | or base in ("tests.rs", "test_support.rs", "test_env_lock.rs") |
| 239 | or base.endswith(("_tests.rs", "_test.rs", "_acceptance.rs")) |
| 240 | or base == "golden_harness.rs" |
| 241 | or "goldens" in rel |
| 242 | or "/fixtures/" in "/" + rel |
| 243 | ) |
| 244 | |
| 245 | |
| 246 | def top_module(rel: str, root_module: str = ROOT_ITEMS) -> str: |
| 247 | parts = rel.split("/") |
| 248 | if len(parts) == 1: |
| 249 | stem = parts[0][:-3] |
| 250 | module = {"lib": root_module, "main": "main.rs"}.get(stem, stem) |
| 251 | else: |
| 252 | module = parts[0] |
| 253 | return f"{root_module}::{module}" if root_module != ROOT_ITEMS and module != root_module else module |
| 254 | |
| 255 | |
| 256 | def split_top(s: str) -> list[str]: |
| 257 | parts, depth, cur = [], 0, "" |
| 258 | for ch in s: |
| 259 | if ch == "{": |
| 260 | depth += 1 |
| 261 | elif ch == "}": |
| 262 | depth -= 1 |
| 263 | if ch == "," and depth == 0: |
| 264 | parts.append(cur) |
| 265 | cur = "" |
| 266 | else: |
| 267 | cur += ch |
| 268 | parts.append(cur) |
| 269 | return [p.strip() for p in parts if p.strip()] |
| 270 | |
| 271 | |
| 272 | def use_leaves(tree: str, prefix: tuple[str, ...] = ()) -> list[tuple[str, tuple[str, ...]]]: |
| 273 | """Flatten a use tree into (bound name, full path) pairs.""" |
| 274 | tree = tree.strip() |
| 275 | if not tree: |
| 276 | return [] |
| 277 | brace = tree.find("{") |
| 278 | if brace >= 0: |
| 279 | head = [p for p in tree[:brace].split("::") if p.strip()] |
| 280 | inner = tree[brace + 1 : tree.rindex("}")] |
| 281 | out = [] |
| 282 | for part in split_top(inner): |
| 283 | out.extend(use_leaves(part, prefix + tuple(h.strip() for h in head))) |
| 284 | return out |
| 285 | alias = None |
| 286 | m = re.match(r"(.*?)\s+as\s+(\w+)$", tree) |
| 287 | if m: |
| 288 | tree, alias = m.group(1), m.group(2) |
| 289 | path = prefix + tuple(p.strip() for p in tree.split("::") if p.strip()) |
| 290 | if not path: |
| 291 | return [] |
| 292 | name = alias or path[-1] |
| 293 | if name == "self": |
| 294 | name = path[-2] if len(path) > 1 else name |
| 295 | return [(name, path)] |
| 296 | |
| 297 | |
| 298 | # -------------------------------------------------------------------------- |
| 299 | # Graph construction |
| 300 | # -------------------------------------------------------------------------- |
| 301 | |
| 302 | |
| 303 | @dataclass |
| 304 | class Ref: |
| 305 | kind: str # "prod" or "test" |
| 306 | src: str # module |
| 307 | dst: str # module, or lib.rs |
| 308 | file: str |
| 309 | line: int |
| 310 | text: str |
| 311 | |
| 312 | |
| 313 | @dataclass |
| 314 | class Crate: |
| 315 | name: str |
| 316 | root: Path |
| 317 | files: dict[str, tuple[str, str, str]] = field(default_factory=dict) |
| 318 | modules: set[str] = field(default_factory=set) |
| 319 | # names bound at the crate root by `use` -> resolving module (or "extern") |
| 320 | root_names: dict[str, str] = field(default_factory=dict) |
| 321 | # modules whose every file is test code (e.g. `#[cfg(test)] mod test_support;`) |
| 322 | test_only: set[str] = field(default_factory=set) |
| 323 | # Actual module/include production conflicts override path heuristics. |
| 324 | production_files: set[str] = field(default_factory=set) |
| 325 | root_module: str = ROOT_ITEMS |
| 326 | |
| 327 | |
| 328 | USE_RE = re.compile(r"\buse\s+(crate|codewhale_engine|codewhale_runtime|codewhale_app_server)::") |
| 329 | PATH_RE = re.compile(r"(?<![\$\w])(crate|codewhale_engine|codewhale_runtime|codewhale_app_server)::(\w+)") |
| 330 | # `super::super::tui::x` reaches the crate root just like `crate::tui::x`. |
| 331 | SUPER_RE = re.compile(r"(?<![\$\w:])((?:super\s*::\s*)+)(\{|\w+)") |
| 332 | INLINE_MOD_RE = re.compile(r"\bmod\s+\w+\s*\{") |
| 333 | UILIB_RE = re.compile(r"(?<![\w:])(ratatui|crossterm|codewhale_tui)(?:::|\s*;|\s*\{)") |
| 334 | DOC_LINK_RE = re.compile(r"\[`?crate::(tui|commands)\b") |
| 335 | |
| 336 | |
| 337 | def load_crate(name: str, root: Path) -> Crate: |
| 338 | crate = Crate(name, root, root_module=ROOT_ITEMS if name == "codewhale-tui" else name.replace("-", "_")) |
| 339 | if not root.is_dir(): |
| 340 | return crate |
| 341 | for dirpath, _, filenames in os.walk(root): |
| 342 | for fname in filenames: |
| 343 | if not fname.endswith(".rs"): |
| 344 | continue |
| 345 | rel = os.path.relpath(os.path.join(dirpath, fname), root).replace(os.sep, "/") |
| 346 | src = Path(dirpath, fname).read_text(encoding="utf-8", errors="replace") |
| 347 | code = lex_mask(src) |
| 348 | crate.files[rel] = (src, code, "") |
| 349 | crate.modules = {top_module(r, crate.root_module) for r in crate.files} - {ROOT_ITEMS, "main.rs"} |
| 350 | return crate |
| 351 | |
| 352 | |
| 353 | def resolve_root_names(crate: Crate, all_modules: set[str]) -> None: |
| 354 | """Map names the crate root imports with `use` to the module they come from.""" |
| 355 | entry = crate.files.get("lib.rs") |
| 356 | if not entry: |
| 357 | return |
| 358 | code = entry[1] |
| 359 | depth = 0 |
| 360 | i = 0 |
| 361 | # Only top-level `use` items (brace depth 0) bind crate-root names. |
| 362 | for m in re.finditer(r"[{}]|\b(?:pub(?:\([^)]*\))?\s+)?use\s+", code): |
| 363 | tok = m.group(0) |
| 364 | if tok == "{": |
| 365 | depth += 1 |
| 366 | continue |
| 367 | if tok == "}": |
| 368 | depth -= 1 |
| 369 | continue |
| 370 | if depth != 0 or m.start() < i: |
| 371 | continue |
| 372 | end = code.find(";", m.end()) |
| 373 | i = end |
| 374 | for bound, path in use_leaves(code[m.end() : end]): |
| 375 | head = path[0] |
| 376 | if head == "crate" and len(path) > 1: |
| 377 | target = top_module(path[1] + ".rs", crate.root_module) |
| 378 | crate.root_names[bound] = target if target in crate.modules else crate.root_module |
| 379 | elif head in ("self", "super"): |
| 380 | continue |
| 381 | elif top_module(head + ".rs", crate.root_module) in crate.modules: |
| 382 | crate.root_names[bound] = top_module(head + ".rs", crate.root_module) |
| 383 | elif head in ("codewhale_runtime", "codewhale_engine", "codewhale_app_server") and len(path) > 1: |
| 384 | target = top_module(path[1] + ".rs", head) |
| 385 | crate.root_names[bound] = target if target in all_modules else head if head in all_modules else "extern" |
| 386 | else: |
| 387 | crate.root_names[bound] = "extern" |
| 388 | |
| 389 | |
| 390 | def test_file_set(crate: Crate) -> tuple[set[str], set[str]]: |
| 391 | """Reuse the blocking gate's conservative cfg/module/include graph.""" |
| 392 | for rel, (src, code, _) in list(crate.files.items()): |
| 393 | crate.files[rel] = (src, code, strip_cfg_test(code, [])) |
| 394 | path = Path(__file__).resolve().parents[1] / "check-blocking-calls-budget.py" |
| 395 | spec = importlib.util.spec_from_file_location("boundary_test_scope_graph", path) |
| 396 | if spec is None or spec.loader is None: |
| 397 | raise RuntimeError(f"cannot load shared Rust test-scope reader: {path}") |
| 398 | graph = importlib.util.module_from_spec(spec) |
| 399 | spec.loader.exec_module(graph) |
| 400 | # Include the manifest and custom targets outside src when a real crate |
| 401 | # is supplied. Hermetic source trees do not consult a neighboring crate. |
| 402 | scan_root = crate.root.parent if (crate.root.parent / "Cargo.toml").is_file() else crate.root |
| 403 | test_only, production = graph.module_file_scopes(scan_root) |
| 404 | exact = {rel for rel in crate.files if (crate.root / rel).resolve() in test_only} |
| 405 | crate.production_files = {rel for rel in crate.files if (crate.root / rel).resolve() in production} |
| 406 | # No guessed directory-prefix exemption: classification is per actual file. |
| 407 | return exact, set() |
| 408 | |
| 409 | |
| 410 | def file_is_test( |
| 411 | rel: str, exact: set[str], prefixes: set[str], production: set[str] | None = None |
| 412 | ) -> bool: |
| 413 | if production is not None and rel in production: |
| 414 | return False |
| 415 | return is_test_path(rel) or rel in exact or any(rel.startswith(p) for p in prefixes) |
| 416 | |
| 417 | |
| 418 | def file_depth(rel: str) -> int: |
| 419 | """Module depth of a source file below the crate root (`lib.rs` is 0).""" |
| 420 | parts = rel.split("/") |
| 421 | if len(parts) == 1: |
| 422 | return 0 if parts[0] in ("lib.rs", "main.rs") else 1 |
| 423 | return len(parts) - 1 if parts[-1] == "mod.rs" else len(parts) |
| 424 | |
| 425 | |
| 426 | def inline_mod_spans(code: str) -> list[tuple[int, int]]: |
| 427 | """Byte ranges of inline `mod name { ... }` bodies (each adds one level).""" |
| 428 | return [(m.end() - 1, match_brace(code, m.end() - 1)) for m in INLINE_MOD_RE.finditer(code)] |
| 429 | |
| 430 | |
| 431 | def super_root_targets(code: str, rel: str) -> list[tuple[int, str]]: |
| 432 | """`(offset, first segment)` for every `super::` chain that climbs to the crate root. |
| 433 | |
| 434 | A chain of k `super`s written at module depth d (file depth plus the |
| 435 | enclosing inline `mod` blocks) names the crate root when k == d; a |
| 436 | shorter chain stays inside the module and is not a cross-module edge. |
| 437 | """ |
| 438 | base = file_depth(rel) |
| 439 | spans = inline_mod_spans(code) |
| 440 | out: list[tuple[int, str]] = [] |
| 441 | for m in SUPER_RE.finditer(code): |
| 442 | k = m.group(1).count("super") |
| 443 | depth = base + sum(1 for a, b in spans if a < m.start() < b) |
| 444 | if k != depth: |
| 445 | continue |
| 446 | if m.group(2) == "{": |
| 447 | end = match_brace(code, m.end() - 1) |
| 448 | for _, path in use_leaves(code[m.end() : end]): |
| 449 | out.append((m.start(), path[0])) |
| 450 | else: |
| 451 | out.append((m.start(), m.group(2))) |
| 452 | return out |
| 453 | |
| 454 | |
| 455 | def collect_refs(crate: Crate, all_modules: set[str], prefix: str) -> list[Ref]: |
| 456 | exact, prefixes = test_file_set(crate) |
| 457 | refs: list[Ref] = [] |
| 458 | by_module: dict[str, list[bool]] = collections.defaultdict(list) |
| 459 | for rel in crate.files: |
| 460 | by_module[top_module(rel, crate.root_module)].append(file_is_test(rel, exact, prefixes, crate.production_files)) |
| 461 | crate.test_only = {m for m, flags in by_module.items() if all(flags)} |
| 462 | |
| 463 | def target_of(name: str, external: str | None = None) -> str: |
| 464 | target = top_module(name + ".rs", external or crate.root_module) |
| 465 | if external: |
| 466 | return target if target in all_modules else external if external in all_modules else "extern" |
| 467 | return target if target in crate.modules else crate.root_names.get(name, crate.root_module) |
| 468 | |
| 469 | for rel, (src, code, stripped) in crate.files.items(): |
| 470 | mod = top_module(rel, crate.root_module) |
| 471 | whole_test = file_is_test(rel, exact, prefixes, crate.production_files) |
| 472 | lines = src.split("\n") |
| 473 | |
| 474 | def kind_at(pos: int) -> str: |
| 475 | if whole_test: |
| 476 | return "test" |
| 477 | return "prod" if stripped[pos] == code[pos] and not stripped[pos].isspace() else "test" |
| 478 | |
| 479 | covered: set[int] = set() |
| 480 | for m in USE_RE.finditer(code): |
| 481 | end = code.find(";", m.end()) |
| 482 | if end < 0: |
| 483 | continue |
| 484 | covered.update(range(m.start(), end)) |
| 485 | body = code[m.end() : end] |
| 486 | line = code.count("\n", 0, m.start()) + 1 |
| 487 | for _, path in use_leaves(body): |
| 488 | t = path[0] |
| 489 | if t in ("self", "super"): |
| 490 | continue |
| 491 | refs.append(Ref(kind_at(m.start()), mod, target_of(t, m.group(1) if m.group(1) != "crate" else None), f"{prefix}/{rel}", line, lines[line - 1].strip()[:160])) |
| 492 | for m in PATH_RE.finditer(code): |
| 493 | if m.start() in covered: |
| 494 | continue |
| 495 | line = code.count("\n", 0, m.start()) + 1 |
| 496 | refs.append(Ref(kind_at(m.start()), mod, target_of(m.group(2), m.group(1) if m.group(1) != "crate" else None), f"{prefix}/{rel}", line, lines[line - 1].strip()[:160])) |
| 497 | for pos, name in super_root_targets(code, rel): |
| 498 | # `pub(in super::super)` and glob imports name no item; only a |
| 499 | # known module or crate-root binding is an edge. |
| 500 | if top_module(name + ".rs", crate.root_module) not in crate.modules and name not in crate.root_names: |
| 501 | continue |
| 502 | line = code.count("\n", 0, pos) + 1 |
| 503 | refs.append(Ref(kind_at(pos), mod, target_of(name), f"{prefix}/{rel}", line, lines[line - 1].strip()[:160])) |
| 504 | return refs |
| 505 | |
| 506 | |
| 507 | @dataclass |
| 508 | class Report: |
| 509 | closure: list[str] |
| 510 | counts: dict[str, dict[str, int]] |
| 511 | locations: dict[str, dict[str, list[str]]] |
| 512 | |
| 513 | |
| 514 | def load_graph(tui_src: Path = TUI_SRC, runtime_src: Path = RUNTIME_SRC, app_server_src: Path | None = None) -> tuple[list[Crate], list[Ref]]: |
| 515 | crates = [load_crate("codewhale-tui", tui_src), load_crate("codewhale-runtime", runtime_src)] |
| 516 | if tui_src == TUI_SRC and runtime_src == RUNTIME_SRC: |
| 517 | crates.append(load_crate("codewhale-engine", ENGINE_SRC)) |
| 518 | if app_server_src is None: |
| 519 | app_server_src = APP_SERVER_SRC |
| 520 | if app_server_src is not None: |
| 521 | crates.append(load_crate("codewhale-app-server", app_server_src)) |
| 522 | all_modules = set().union(*(crate.modules for crate in crates)) |
| 523 | refs = [] |
| 524 | for crate in crates: |
| 525 | resolve_root_names(crate, all_modules) |
| 526 | prefix = f"crates/{crate.name.removeprefix('codewhale-')}/src" |
| 527 | refs.extend(collect_refs(crate, all_modules, prefix)) |
| 528 | return crates, refs |
| 529 | |
| 530 | |
| 531 | def build_report(tui_src: Path = TUI_SRC, runtime_src: Path = RUNTIME_SRC, app_server_src: Path | None = None) -> Report: |
| 532 | crates, refs = load_graph(tui_src, runtime_src, app_server_src) |
| 533 | all_modules = set().union(*(crate.modules for crate in crates)) |
| 534 | |
| 535 | prod_edges: dict[str, set[str]] = collections.defaultdict(set) |
| 536 | for r in refs: |
| 537 | if r.kind == "prod" and r.src != r.dst: |
| 538 | prod_edges[r.src].add(r.dst) |
| 539 | |
| 540 | # A test-only module that closure tests use (`test_support`) compiles in |
| 541 | # the same crate as those tests, so it belongs to the closure too and its |
| 542 | # own upward references count as test references. |
| 543 | test_only = set().union(*(crate.test_only for crate in crates)) |
| 544 | test_edges: dict[str, set[str]] = collections.defaultdict(set) |
| 545 | for r in refs: |
| 546 | if r.src != r.dst and r.dst in test_only: |
| 547 | test_edges[r.src].add(r.dst) |
| 548 | |
| 549 | seen: set[str] = set() |
| 550 | stack = [s for s in SEEDS if s in all_modules] + sorted(set().union(*(crate.modules for crate in crates[1:]))) |
| 551 | while stack: |
| 552 | m = stack.pop() |
| 553 | if m in seen or is_ui(m) or m == "extern": |
| 554 | continue |
| 555 | seen.add(m) |
| 556 | stack.extend(prod_edges.get(m, ())) |
| 557 | stack.extend(test_edges.get(m, ())) |
| 558 | |
| 559 | counts = {c: collections.Counter() for c in CATEGORIES} |
| 560 | where: dict[str, dict[str, list[str]]] = {c: collections.defaultdict(list) for c in CATEGORIES} |
| 561 | for r in refs: |
| 562 | if r.src not in seen or r.src == r.dst or r.dst == "extern": |
| 563 | continue |
| 564 | if is_ui(r.dst): |
| 565 | cat = r.kind |
| 566 | elif r.dst not in seen: |
| 567 | cat = "late" |
| 568 | else: |
| 569 | continue |
| 570 | key = f"{r.src}|{r.dst}" |
| 571 | counts[cat][key] += 1 |
| 572 | where[cat][key].append(f"{r.file}:{r.line}: {r.text}") |
| 573 | |
| 574 | for crate in crates: |
| 575 | prefix = f"crates/{crate.name.removeprefix('codewhale-')}/src" |
| 576 | for rel, (src, code, _) in crate.files.items(): |
| 577 | mod = top_module(rel, crate.root_module) |
| 578 | if mod not in seen: |
| 579 | continue |
| 580 | lines = src.split("\n") |
| 581 | for m in UILIB_RE.finditer(code): |
| 582 | lib = m.group(1) |
| 583 | line = code.count("\n", 0, m.start()) + 1 |
| 584 | key = f"{mod}|{lib}" |
| 585 | counts["uilib"][key] += 1 |
| 586 | where["uilib"][key].append(f"{prefix}/{rel}:{line}: {lines[line - 1].strip()[:160]}") |
| 587 | for line_no, raw in enumerate(lines, start=1): |
| 588 | stripped = raw.lstrip() |
| 589 | if not (stripped.startswith("///") or stripped.startswith("//!")): |
| 590 | continue |
| 591 | for m in DOC_LINK_RE.finditer(stripped): |
| 592 | target = top_module(m.group(1) + ".rs", crate.root_module) |
| 593 | if is_ui(target): |
| 594 | key = f"{mod}|{target}" |
| 595 | counts["doc"][key] += 1 |
| 596 | where["doc"][key].append(f"{prefix}/{rel}:{line_no}: {stripped[:160]}") |
| 597 | |
| 598 | return Report( |
| 599 | sorted(seen), |
| 600 | {c: dict(sorted(counts[c].items())) for c in CATEGORIES}, |
| 601 | {c: dict(where[c]) for c in CATEGORIES}, |
| 602 | ) |
| 603 | |
| 604 | |
| 605 | # -------------------------------------------------------------------------- |
| 606 | # Ratchet |
| 607 | # -------------------------------------------------------------------------- |
| 608 | |
| 609 | |
| 610 | def totals(counts: dict[str, dict[str, int]]) -> dict[str, int]: |
| 611 | return {c: sum(counts.get(c, {}).values()) for c in CATEGORIES} |
| 612 | |
| 613 | |
| 614 | def compare(baseline: dict, report: Report) -> tuple[list[str], list[str]]: |
| 615 | """Return (increases, unrecorded decreases) as human-readable lines.""" |
| 616 | rises: list[str] = [] |
| 617 | drops: list[str] = [] |
| 618 | base_counts = baseline.get("counts", {}) |
| 619 | for cat in CATEGORIES: |
| 620 | base = base_counts.get(cat, {}) |
| 621 | cur = report.counts.get(cat, {}) |
| 622 | for key, n in cur.items(): |
| 623 | b = base.get(key, 0) |
| 624 | if n > b: |
| 625 | dst = key.split("|", 1)[1] |
| 626 | hint = HINTS.get(dst, "see docs/design/TUI_DECONSTRUCTION.md (runtime split blockers)") |
| 627 | head = f"{cat} {key}: {b} -> {n}" + (" (new pair)" if key not in base else "") |
| 628 | rises.append(f"{head}; {hint}") |
| 629 | for loc in report.locations.get(cat, {}).get(key, [])[:20]: |
| 630 | rises.append(f" {loc}") |
| 631 | for key, b in base.items(): |
| 632 | n = cur.get(key, 0) |
| 633 | if n < b: |
| 634 | drops.append(f"{cat} {key}: {b} -> {n}") |
| 635 | return rises, drops |
| 636 | |
| 637 | |
| 638 | def load_baseline(path: Path = BASELINE) -> dict: |
| 639 | return json.loads(path.read_text(encoding="utf-8")) |
| 640 | |
| 641 | |
| 642 | def load_baseline_at_ref(ref: str, root: Path = REPO_ROOT) -> dict | None: |
| 643 | """The baseline as committed at `ref`; None when it did not exist yet.""" |
| 644 | commit = subprocess.run( |
| 645 | ["git", "rev-parse", "--verify", f"{ref}^{{commit}}"], |
| 646 | cwd=root, capture_output=True, text=True, check=False, |
| 647 | ) |
| 648 | if commit.returncode != 0: |
| 649 | raise ValueError(f"baseline ref {ref!r} is unavailable: {commit.stderr.strip()}") |
| 650 | shown = subprocess.run( |
| 651 | ["git", "show", f"{ref}:{BASELINE_REPO_PATH}"], |
| 652 | cwd=root, capture_output=True, text=True, check=False, |
| 653 | ) |
| 654 | if shown.returncode != 0: |
| 655 | return None |
| 656 | return json.loads(shown.stdout) |
| 657 | |
| 658 | |
| 659 | def baseline_raises(previous: dict, current: dict) -> list[str]: |
| 660 | """Counts the committed baseline holds above the baseline it replaces. |
| 661 | |
| 662 | The local `--update` refuses to raise, but the JSON is an ordinary file: |
| 663 | without this comparison a change could add a reference and bump the |
| 664 | count by hand in the same commit, and `check` would pass. |
| 665 | """ |
| 666 | raised: list[str] = [] |
| 667 | prev_counts = previous.get("counts", {}) |
| 668 | for cat in CATEGORIES: |
| 669 | prev = prev_counts.get(cat, {}) |
| 670 | for key, n in current.get("counts", {}).get(cat, {}).items(): |
| 671 | b = prev.get(key, 0) |
| 672 | if n > b: |
| 673 | raised.append(f"{cat} {key}: {b} -> {n}" + (" (new pair)" if key not in prev else "")) |
| 674 | return raised |
| 675 | |
| 676 | |
| 677 | def baseline_document(report: Report) -> dict: |
| 678 | return { |
| 679 | "_comment": ( |
| 680 | "Runtime -> UI boundary ratchet (docs/design/TUI_DECONSTRUCTION.md, runtime split). Counts may " |
| 681 | "only go down. Regenerate with python3 scripts/split/module_graph.py " |
| 682 | "--update after removing references; never raise a count by hand." |
| 683 | ), |
| 684 | "totals": totals(report.counts), |
| 685 | "counts": report.counts, |
| 686 | } |
| 687 | |
| 688 | |
| 689 | def check( |
| 690 | path: Path = BASELINE, |
| 691 | report: Report | None = None, |
| 692 | baseline_ref: str | None = None, |
| 693 | ) -> list[str]: |
| 694 | """Return violation lines (empty when the ratchet holds). |
| 695 | |
| 696 | With `baseline_ref`, the committed baseline must also be no higher than |
| 697 | the one at that revision. |
| 698 | """ |
| 699 | report = report or build_report() |
| 700 | if not path.is_file(): |
| 701 | return [f"missing baseline {path.relative_to(REPO_ROOT)}; run with --update"] |
| 702 | problems = [] |
| 703 | if baseline_ref: |
| 704 | try: |
| 705 | previous = load_baseline_at_ref(baseline_ref) |
| 706 | except (ValueError, json.JSONDecodeError) as error: |
| 707 | return [str(error)] |
| 708 | if previous is not None: |
| 709 | raised = baseline_raises(previous, load_baseline(path)) |
| 710 | if raised: |
| 711 | problems.append( |
| 712 | f"the baseline was raised relative to {baseline_ref} (counts only go down; " |
| 713 | "remove the reference instead of editing the JSON):" |
| 714 | ) |
| 715 | problems.extend(f" {r}" for r in raised) |
| 716 | rises, drops = compare(load_baseline(path), report) |
| 717 | if rises: |
| 718 | problems.append("runtime -> UI references rose (the ratchet only goes down):") |
| 719 | problems.extend(f" {r}" for r in rises) |
| 720 | if drops: |
| 721 | problems.append( |
| 722 | "runtime -> UI references dropped but the baseline was not lowered; " |
| 723 | "run python3 scripts/split/module_graph.py --update and commit it:" |
| 724 | ) |
| 725 | problems.extend(f" {d}" for d in drops) |
| 726 | return problems |
| 727 | |
| 728 | |
| 729 | def main(argv: list[str] | None = None) -> int: |
| 730 | parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 731 | mode = parser.add_mutually_exclusive_group() |
| 732 | mode.add_argument("--check", action="store_true", help="enforce the ratchet (default)") |
| 733 | mode.add_argument("--update", action="store_true", help="lower the baseline to the current counts") |
| 734 | mode.add_argument("--report", action="store_true", help="print counts and closure as JSON") |
| 735 | parser.add_argument( |
| 736 | "--baseline-ref", |
| 737 | help="git revision whose committed baseline the current one may not exceed", |
| 738 | ) |
| 739 | parser.add_argument("--tui-src", type=Path, default=TUI_SRC, help="source directory of the crate being split") |
| 740 | parser.add_argument("--runtime-src", type=Path, default=RUNTIME_SRC, help="source directory of the destination crate") |
| 741 | parser.add_argument("--app-server-src", type=Path, help="optional host source directory; defaults to the workspace host only with default source roots") |
| 742 | args = parser.parse_args(argv) |
| 743 | |
| 744 | report = build_report(args.tui_src.resolve(), args.runtime_src.resolve(), args.app_server_src.resolve() if args.app_server_src else None) |
| 745 | if args.report: |
| 746 | json.dump( |
| 747 | {"closure": report.closure, "totals": totals(report.counts), "counts": report.counts, |
| 748 | "locations": report.locations}, |
| 749 | sys.stdout, |
| 750 | indent=1, |
| 751 | ) |
| 752 | print() |
| 753 | return 0 |
| 754 | if args.update: |
| 755 | if BASELINE.is_file(): |
| 756 | rises, _ = compare(load_baseline(), report) |
| 757 | if rises: |
| 758 | print("[runtime-boundary] refusing to raise the baseline:", file=sys.stderr) |
| 759 | for r in rises: |
| 760 | print(f" {r}", file=sys.stderr) |
| 761 | return 1 |
| 762 | BASELINE.write_text(json.dumps(baseline_document(report), indent=2) + "\n", encoding="utf-8") |
| 763 | print(f"[runtime-boundary] baseline written: {totals(report.counts)}") |
| 764 | return 0 |
| 765 | problems = check(report=report, baseline_ref=args.baseline_ref) |
| 766 | if problems: |
| 767 | print("[runtime-boundary] FAIL", file=sys.stderr) |
| 768 | for p in problems: |
| 769 | print(p, file=sys.stderr) |
| 770 | return 1 |
| 771 | print(f"[runtime-boundary] PASS: {totals(report.counts)} ({len(report.closure)} closure modules)") |
| 772 | return 0 |
| 773 | |
| 774 | |
| 775 | if __name__ == "__main__": |
| 776 | sys.exit(main()) |
| 777 |