#!/usr/bin/env python3 """Cheap structure ratchets for Modern-Apps (no build, stdlib only). Four checks, wired into ./check (see docs/structure/README.md): wear Token-stream identity of the duplicated Wear protocol pairs listed in docs/structure/wear-protocol-pairs.tsv. Each file is normalized (package/import lines dropped, comments stripped with a string-aware scanner) and the resulting token streams must be identical per pair. generated Every Kotlin/Rust file carrying a GENERATED/@generated header (definition in docs/structure/README.md) must be listed in docs/structure/generated-sources.tsv with a generator command, and every listed file must still exist and carry the header. Presence only: nothing is regenerated. exceptions Every escape-hatch marker occurrence in Kotlin sources must match docs/structure/exceptions.tsv exactly (type, file, reason). Regenerate with --regen after an intentional change and review the TSV diff; a new marker without a reason edit fails here (and malformed markers fail lint anyway). lines Total source lines (.kt/.java/.rs/.swift, tests included, via git ls-files) must not exceed the baseline in docs/structure/line-budget.json. Per-module totals are printed. Excluded modules (data-driven, in that file -- currently the forthcoming communicate-dev module) do not count. Shrinking passes; growing fails until the baseline is deliberately bumped in the same change. Usage: python3 tools/structure_check.py [wear|generated|exceptions|lines|all] python3 tools/structure_check.py exceptions --regen python3 tools/structure_check.py lines [--report|--regen] Exit code 0 = clean, 1 = violations (each violation is named). Scope exclusions follow root AGENTS.md "Never scan": build/, target/, third_party/, analysis/, personal/, .git/ etc. are never walked, and lint-rules/ + tools/ + docs/ are excluded from the marker/generated scans because they legitimately quote marker/header strings as data. """ import json import os import re import subprocess import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DOCS = os.path.join(ROOT, "docs", "structure") WEAR_TSV = os.path.join(DOCS, "wear-protocol-pairs.tsv") GENERATED_TSV = os.path.join(DOCS, "generated-sources.tsv") EXCEPTIONS_TSV = os.path.join(DOCS, "exceptions.tsv") LINE_BUDGET_JSON = os.path.join(DOCS, "line-budget.json") SETTINGS_GRADLE = os.path.join(ROOT, "settings.gradle.kts") SKIP_DIRS = { ".git", ".gradle", ".kotlin", "build", "target", "analysis", "third_party", "personal", "release", "captures", ".idea", "__pycache__", } # Dirs whose files quote markers/headers as data, not as uses. DATA_DIRS = ("lint-rules/", "tools/", "docs/") def rel(path): return os.path.relpath(path, ROOT).replace(os.sep, "/") def walk_files(exts): for dirpath, dirnames, filenames in os.walk(ROOT): dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS] for name in sorted(filenames): if name.endswith(exts): yield os.path.join(dirpath, name) def is_data_path(rpath): return rpath.startswith(DATA_DIRS) # ---------------------------------------------------------------- wear ---- def strip_comments(text): """Remove // and /* */ comments, respecting Kotlin strings/chars.""" out = [] i, n = 0, len(text) while i < n: if text.startswith('"""', i): j = text.find('"""', i + 3) j = n if j < 0 else j + 3 out.append(text[i:j]); i = j elif text[i] == '"': j = i + 1 while j < n and text[j] != '"': j += 2 if text[j] == "\\" else 1 out.append(text[i:j + 1]); i = j + 1 elif text[i] == "'": j = i + 1 while j < n and text[j] != "'": j += 2 if text[j] == "\\" else 1 out.append(text[i:j + 1]); i = j + 1 elif text.startswith("//", i): j = text.find("\n", i) i = n if j < 0 else j elif text.startswith("/*", i): depth, j = 1, i + 2 while j < n and depth: if text.startswith("/*", j): depth += 1; j += 2 elif text.startswith("*/", j): depth -= 1; j += 2 else: j += 1 out.append(" "); i = j else: out.append(text[i]); i += 1 return "".join(out) TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|[^\w\s]") def normalized_tokens(path): text = open(path, encoding="utf-8", errors="ignore").read() text = strip_comments(text) lines = [ ln for ln in text.splitlines() if not re.match(r"\s*(package|import)\s", ln) ] return TOKEN_RE.findall("\n".join(lines)) def check_wear(): violations = [] pairs = [] for ln, line in enumerate(open(WEAR_TSV, encoding="utf-8"), 1): if not line.strip() or line.startswith("#"): continue parts = line.rstrip("\n").split("\t") if len(parts) != 3: violations.append(f"wear: {WEAR_TSV}:{ln}: expected 3 tab-separated fields") continue pairs.append(parts) for pair_id, phone, wear in pairs: pp, wp = os.path.join(ROOT, phone), os.path.join(ROOT, wear) if not os.path.isfile(pp): violations.append(f"wear[{pair_id}]: missing phone file {phone}") continue if not os.path.isfile(wp): violations.append(f"wear[{pair_id}]: missing wear file {wear}") continue a, b = normalized_tokens(pp), normalized_tokens(wp) if a != b: idx = next((k for k in range(min(len(a), len(b))) if a[k] != b[k]), min(len(a), len(b))) lo = max(0, idx - 6) violations.append( f"wear[{pair_id}]: DRIFT {phone} <-> {wear} " f"(tokens phone={len(a)} wear={len(b)}, first diff at token {idx}: " f"phone ...{' '.join(a[lo:idx + 6])} | wear ...{' '.join(b[lo:idx + 6])})") print(f"wear: {len(pairs)} pairs checked") return violations # ------------------------------------------------------------- generated ---- GENERATED_RE = re.compile( r"BEGIN GENERATED|@generated\b" r"|^\s*(?://[!/]?|/\*+|\*)?\s*GENERATED\b" r"|Code generated[^\n]*DO NOT EDIT|// Generated (constants|constant tables)" r"|Do not hand-edit") HEADER_LINES = 40 def has_generated_header(path): try: with open(path, encoding="utf-8", errors="ignore") as fh: for i, line in enumerate(fh): if i >= HEADER_LINES: break if GENERATED_RE.search(line): return line.strip() except OSError: return None return None def check_generated(): violations = [] listed = {} for ln, line in enumerate(open(GENERATED_TSV, encoding="utf-8"), 1): if not line.strip() or line.startswith("#"): continue parts = line.rstrip("\n").split("\t") if len(parts) != 2 or not parts[1].strip(): violations.append( f"generated: {GENERATED_TSV}:{ln}: expected '\\t'") continue listed[parts[0]] = parts[1] found = {} for path in walk_files((".kt", ".rs")): rpath = rel(path) if is_data_path(rpath): continue marker = has_generated_header(path) if marker: found[rpath] = marker for rpath in sorted(found): if rpath not in listed: violations.append( f"generated: UNLISTED {rpath} (header: {found[rpath][:100]}) " f"-- add it to docs/structure/generated-sources.tsv with its generator") for rpath in sorted(listed): path = os.path.join(ROOT, rpath) if not os.path.isfile(path): violations.append(f"generated: STALE {rpath} listed but file is gone") elif not has_generated_header(path): violations.append( f"generated: STALE {rpath} listed but its GENERATED header is gone") print(f"generated: {len(found)} generated files in tree, {len(listed)} listed") return violations # ------------------------------------------------------------ exceptions ---- # Canonical markers (verbatim list in root AGENTS.md and # lint-rules ExceptionMarkerFormatDetector). type -> (keyword, reason prefix) MARKERS = [ ("PACKAGE_JNI", "PACKAGE STRUCTURE EXCEPTION (JNI)", None), ("RAW_SCAFFOLD", "RAW SCAFFOLD EXCEPTION", "// RAW SCAFFOLD EXCEPTION:"), ("TOAST", "TOAST EXCEPTION", "// TOAST EXCEPTION:"), ("RAW_ANIMATION", "RAW ANIMATION EXCEPTION", "// RAW ANIMATION EXCEPTION:"), ("SCAFFOLD_LOADING", "SCAFFOLD LOADING EXCEPTION", "// SCAFFOLD LOADING EXCEPTION:"), ("SCAFFOLD_SEARCH", "SCAFFOLD SEARCH EXCEPTION", "// SCAFFOLD SEARCH EXCEPTION:"), ("SCREENSHOT_COVERAGE", "SCREENSHOT COVERAGE EXCEPTION", "// SCREENSHOT COVERAGE EXCEPTION:"), ] def scan_exceptions(): # Aggregated by (type, file, reason) with an occurrence count: line # numbers are deliberately not recorded, so moving a marker inside its # file does not churn the inventory -- only adding, removing, or # rewording a marker does (the growth this ratchet exists to catch). from collections import Counter counts = Counter() total = 0 for path in walk_files((".kt", ".kts")): rpath = rel(path) if is_data_path(rpath): continue with open(path, encoding="utf-8", errors="ignore") as fh: for line in fh: for mtype, keyword, prefix in MARKERS: if keyword in line: if prefix is None: reason = "JNI (verbatim marker; no free-text reason)" else: idx = line.find(prefix) reason = (line[idx + len(prefix):].strip() if idx >= 0 else "(malformed: no colon prefix)") counts[(mtype, rpath, reason)] += 1 total += 1 break rows = [(t, f, r, str(c)) for (t, f, r), c in sorted(counts.items())] return rows, total def exceptions_tsv_text(rows): out = ["# type\tfile\treason\tcount", "# Generated by: python3 tools/structure_check.py exceptions --regen", "# A new/changed marker requires regenerating this file and reviewing " "the diff; the reason column is copied verbatim from the source marker."] out += ["\t".join(r) for r in rows] return "\n".join(out) + "\n" def check_exceptions(regen=False): rows, total = scan_exceptions() if regen: with open(EXCEPTIONS_TSV, "w", encoding="utf-8", newline="\n") as fh: fh.write(exceptions_tsv_text(rows)) print(f"exceptions: regenerated {EXCEPTIONS_TSV} with {total} markers") return [] expected = exceptions_tsv_text(rows) actual = "" if os.path.isfile(EXCEPTIONS_TSV): actual = open(EXCEPTIONS_TSV, encoding="utf-8").read() if actual != expected: exp = [l for l in expected.splitlines() if l and not l.startswith("#")] act = [l for l in actual.splitlines() if l and not l.startswith("#")] violations = [] for l in sorted(set(exp) - set(act)): violations.append(f"exceptions: UNRECORDED {l}") for l in sorted(set(act) - set(exp)): violations.append(f"exceptions: STALE {l}") violations.append( "exceptions: run `python3 tools/structure_check.py exceptions --regen` " "and review/commit the docs/structure/exceptions.tsv diff") recorded = sum(int(l.split("\t")[3]) for l in act if len(l.split("\t")) == 4) print(f"exceptions: {total} markers in tree, {recorded} recorded") return violations from collections import Counter counts = Counter() for r in rows: counts[r[0]] += int(r[3]) print(f"exceptions: {total} markers recorded " f"({', '.join(f'{k}={v}' for k, v in sorted(counts.items()))})") return [] # --------------------------------------------------------------- lines ---- DEFAULT_SOURCE_EXTENSIONS = (".kt", ".java", ".rs", ".swift") DEFAULT_EXCLUDED_SEGMENTS = ("third_party", "build", "target") # Communicate dev module, pre-registered before it existed. The exact # Gradle/dir name is communicate-dev -- include(":communicate-dev") # with dir communicate-dev/ (settings.gradle.kts also has :madeveloper, # a different app). Only a module with exactly that name/dir is # excluded; every other module counts. DEFAULT_EXCLUDED_MODULES = ("communicate-dev",) def default_line_budget(): return { "version": 1, "extensions": list(DEFAULT_SOURCE_EXTENSIONS), "excluded_path_segments": list(DEFAULT_EXCLUDED_SEGMENTS), "excluded_modules": list(DEFAULT_EXCLUDED_MODULES), "baseline_lines": 0, "modules": {}, } def load_line_budget(path=LINE_BUDGET_JSON): """Return (budget_dict, error_or_None). Defaults fill absent keys.""" budget = default_line_budget() if not os.path.isfile(path): return budget, f"lines: missing baseline {rel(path)} -- create it with " \ "`python3 tools/structure_check.py lines --regen`" try: with open(path, encoding="utf-8") as fh: data = json.load(fh) except (OSError, ValueError) as exc: return budget, f"lines: cannot parse {rel(path)}: {exc}" if not isinstance(data, dict): return budget, f"lines: {rel(path)} must be a JSON object" for key in budget: if key in data: budget[key] = data[key] if not isinstance(budget["baseline_lines"], int) or budget["baseline_lines"] < 0: return budget, f"lines: {rel(path)}: baseline_lines must be a non-negative int" return budget, None def is_counted_source(rpath, extensions, excluded_segments): if not rpath.endswith(tuple(extensions)): return False segments = rpath.split("/") return not any(seg in excluded_segments for seg in segments) def parse_module_dirs(settings_text): """Gradle module display name (slash form) -> project dir (slash form). Parses include(":a:b") plus project(":a:b").projectDir = file("...") overrides from settings.gradle.kts. includeBuild is not a module. """ modules = {} for match in re.finditer(r'include\("(:[^"]+)"\)', settings_text): name = match.group(1)[1:].replace(":", "/") modules[name] = name for match in re.finditer( r'project\("(:[^"]+)"\)\.projectDir\s*=\s*file\("([^"]+)"\)', settings_text): name = match.group(1)[1:].replace(":", "/") if name in modules: modules[name] = match.group(2).replace("\\", "/").strip("/") return modules def module_for_path(rpath, module_dirs): """Longest matching project dir wins; fallback is the top segment.""" best_name, best_len = None, -1 for name, mdir in module_dirs.items(): if (rpath == mdir or rpath.startswith(mdir + "/")) and len(mdir) > best_len: best_name, best_len = name, len(mdir) if best_name is not None: return best_name return rpath.split("/")[0] if "/" in rpath else "(root)" def is_excluded_module(module, excluded_modules): for entry in excluded_modules: norm = entry.strip().lstrip(":").replace(":", "/").strip("/") if module == norm or module.replace("/", "-") == norm.replace("/", "-"): return True return False def count_source_lines(path): """Logical lines: newline count, plus a final unterminated line.""" with open(path, "rb") as fh: data = fh.read() if not data: return 0 return data.count(b"\n") + (0 if data.endswith(b"\n") else 1) def tally_lines(root, rpaths, module_dirs, budget): """Return (total, per_module, excluded_total, excluded_per_module).""" extensions = budget.get("extensions") or DEFAULT_SOURCE_EXTENSIONS excluded_segments = set(budget.get("excluded_path_segments") or DEFAULT_EXCLUDED_SEGMENTS) excluded_modules = budget.get("excluded_modules") or [] per_module, excluded_per_module = {}, {} total = excluded_total = 0 for rpath in rpaths: if not is_counted_source(rpath, extensions, excluded_segments): continue try: lines = count_source_lines(os.path.join(root, rpath)) except OSError: continue # tracked file deleted in the working tree module = module_for_path(rpath, module_dirs) if is_excluded_module(module, excluded_modules): excluded_per_module[module] = excluded_per_module.get(module, 0) + lines excluded_total += lines else: per_module[module] = per_module.get(module, 0) + lines total += lines return total, per_module, excluded_total, excluded_per_module def list_source_files(root, extensions): """git ls-files based enumeration (tracked + untracked, not ignored). No full-tree walk: build/, target/, third_party/ etc. are filtered afterwards by segment, and git itself drops ignored build outputs. """ patterns = ["*" + ext for ext in extensions] out = subprocess.check_output( ["git", "-C", root, "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--"] + patterns) return [p for p in out.decode("utf-8", errors="ignore").split("\0") if p] def write_line_budget(budget, total, per_module, path=LINE_BUDGET_JSON): data = { "version": 1, "description": "Line-count ratchet baseline. Total source lines " "(.kt/.java/.rs/.swift, tests included; third_party/, build/, " "target/ segments excluded) must not exceed baseline_lines. " "Shrinking passes; deliberate growth bumps baseline_lines in " "the same change. Regenerate: python3 tools/structure_check.py " "lines --regen (review the diff). Per-module figures are a " "snapshot for reporting, not per-module caps.", "extensions": list(budget.get("extensions") or DEFAULT_SOURCE_EXTENSIONS), "excluded_path_segments": list( budget.get("excluded_path_segments") or DEFAULT_EXCLUDED_SEGMENTS), "excluded_modules": list( budget.get("excluded_modules") or DEFAULT_EXCLUDED_MODULES), "excluded_modules_note": "communicate-dev is the Communicate " "dev module, pre-registered before it existed. The exact " "name is include(\":communicate-dev\") with dir " "communicate-dev/ (settings.gradle.kts also has " ":madeveloper, a different app); only that exact module is " "excluded.", "baseline_lines": total, "modules": dict(sorted(per_module.items())), } with open(path, "w", encoding="utf-8", newline="\n") as fh: json.dump(data, fh, indent=2, sort_keys=False) fh.write("\n") return data def check_lines(regen=False, report=False): budget, error = load_line_budget() violations = [] if error and not regen: return [error] try: settings_text = open(SETTINGS_GRADLE, encoding="utf-8").read() except OSError: settings_text = "" module_dirs = parse_module_dirs(settings_text) extensions = budget.get("extensions") or DEFAULT_SOURCE_EXTENSIONS try: rpaths = list_source_files(ROOT, extensions) except (OSError, subprocess.CalledProcessError) as exc: return [f"lines: git ls-files failed ({exc}); ratchet cannot run"] total, per_module, excluded_total, excluded_per = tally_lines( ROOT, rpaths, module_dirs, budget) if regen: write_line_budget(budget, total, per_module) print(f"lines: regenerated {rel(LINE_BUDGET_JSON)} " f"at {total:,} lines ({len(per_module)} modules)") return [] baseline = budget["baseline_lines"] print(f"lines: {total:,} source lines, baseline {baseline:,}, " f"{len(per_module)} modules" + (f", excluded {excluded_total:,} lines in " f"{', '.join(sorted(excluded_per))}" if excluded_total else " (excluded modules: " + ", ".join(budget.get("excluded_modules") or []) + ")")) for module in sorted(per_module, key=lambda m: (-per_module[m], m)): print(f"lines: {per_module[module]:>9,} {module}") if report: print("lines: --report only, ratchet not enforced") return [] if total > baseline: violations.append( f"lines: total {total:,} exceeds baseline {baseline:,} by " f"{total - baseline:,} -- cut lines, or if this growth is " f"deliberate bump the baseline in the same change: " f"`python3 tools/structure_check.py lines --regen` and review " f"the docs/structure/line-budget.json diff") else: print(f"lines: {baseline - total:,} lines of headroom under baseline") return violations def main(argv): which = argv[1] if len(argv) > 1 else "all" regen = "--regen" in argv report = "--report" in argv violations = [] if which in ("wear", "all"): violations += check_wear() if which in ("generated", "all"): violations += check_generated() if which in ("exceptions", "all"): violations += check_exceptions(regen=regen) if which in ("lines", "all"): violations += check_lines(regen=regen and which == "lines", report=report and which == "lines") if which not in ("wear", "generated", "exceptions", "lines", "all"): print(__doc__) return 2 if violations: print("\nSTRUCTURE CHECK FAILURES:") for v in violations: print(f" - {v}") return 1 print("structure: OK") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))