Modern Apps git

← Modern-Apps.git

tools: line-count ratchet with per-module budgets

Commit
7c3c97afd6e2ee84694e15f6cc4f6062bdb49661
Author
Vayun Mathur <[email protected]>
When
2026-12-01 14:39 UTC (4 days ago)
Parents
ff2217b
LOC-cut Phase 0. structure_check gains a lines check:
all source (.kt/.java/.rs/.swift incl. tests, excluding
third_party/build/target segments; 1,749,740 lines over
124 module groups) counted per module from
settings.gradle.kts and printed on every run; it fails
when the total grows past the checked-in baseline in
docs/structure/line-budget.json. Shrinking always passes;
deliberate growth bumps the baseline in the same change
(structure_check.py lines --regen + review the diff).

Owner decisions baked in: :communicate-dev is excluded
from the count (the dev-gated lines extraction lands
separately), infra/agents stays counted. Methodology
reconciles with the LOC plan's 1,638,083 (that number
excluded scripts/+infra/; this ratchet counts them per
the stated method). 6 unit tests; a dummy 3-line file
proved the failure path and was removed. The
settings.gradle.kts change in the tree belongs to the
extraction and is not in this commit. ./check structure
still fails on pre-existing wear-drift/marker findings
from other in-flight work — untouched here.

Diff

AGENTS.md
diff --git a/AGENTS.md b/AGENTS.mdindex f617c8cc17..c1aeb93d35 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -124,7 +124,7 @@ Rules: `release` default (dev is almost never the right install), `dev` only whe ``` Never grep repo-wide when a filter will do. Always excluded: `target/ build/ .gradle/ .kotlin/ .git/ .llms/ analysis/ *.log *.onnx metadata_data/photos/`. -`./check` — static verification without building: `:<module>:detekt` (rules in `detekt.yml`) + `:<module>:lint` + `:<module>:ktlintCheck` + `cargo check/clippy/fmt/doc --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir; `cargo fmt --check` is blocking — drift fails the script) + structure ratchets (`tools/structure_check.py`, manifests in `docs/structure/` — Wear protocol-pair drift, generated-source guard, exception-marker inventory; runs on every invocation):+`./check` — static verification without building: `:<module>:detekt` (rules in `detekt.yml`) + `:<module>:lint` + `:<module>:ktlintCheck` + `cargo check/clippy/fmt/doc --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir; `cargo fmt --check` is blocking — drift fails the script) + structure ratchets (`tools/structure_check.py`, manifests in `docs/structure/` — Wear protocol-pair drift, generated-source guard, exception-marker inventory, line-count ratchet against `line-budget.json`; runs on every invocation): ``` ./check <module> [...]   # e.g. ./check notes backup; ./check voxels ./check all              # every app + library module (pure-JVM modules excluded)
docs/structure/README.md
diff --git a/docs/structure/README.md b/docs/structure/README.mdindex 72799a9f7e..1a2e16cd57 100644--- a/docs/structure/README.md+++ b/docs/structure/README.md@@ -8,11 +8,14 @@ current tree and names every violation individually. ## Entry points  ```-python3 tools/structure_check.py all          # all three checks+python3 tools/structure_check.py all          # all four checks python3 tools/structure_check.py wear         # protocol-pair drift only python3 tools/structure_check.py generated    # generated-source guard only python3 tools/structure_check.py exceptions   # exception-marker ratchet only python3 tools/structure_check.py exceptions --regen   # regenerate exceptions.tsv+python3 tools/structure_check.py lines        # line-count ratchet + per-module totals+python3 tools/structure_check.py lines --report   # per-module totals, no enforcement+python3 tools/structure_check.py lines --regen    # bump line budget to today's total ./check structure                             # same as `all`, via ./check ./check <module> [...]                        # structure checks run first ```@@ -24,6 +27,7 @@ Manifests in this directory (tab-separated, `#` comment lines): | `wear-protocol-pairs.tsv` | `pair_id<TAB>phone_path<TAB>wear_path` | | `generated-sources.tsv` | `path<TAB>generator command` | | `exceptions.tsv` | `type<TAB>file<TAB>reason<TAB>count` (generated; see below) |+| `line-budget.json` | JSON: `baseline_lines`, counted `extensions`, `excluded_path_segments`, `excluded_modules`, per-module snapshot (see §4) |  ## 1. Protocol-pair drift (`wear`) @@ -77,3 +81,39 @@ review the `exceptions.tsv` diff (that review is the reason edit), and include both in the change. Malformed markers (missing colon/reason) are still caught by lint (`ExceptionMarkerFormatDetector`); this ratchet catches growth and drift.++## 4. Line-count ratchet (`lines`)++Counts "all source" for the LOC-cut programme: every `.kt`, `.java`,+`.rs` and `.swift` file, tests and screenshot tests included, enumerated+with `git ls-files --cached --others --exclude-standard` (tracked plus+untracked-but-not-ignored files; no full-tree walk, ~1s). Any path with+a `third_party/`, `build/` or `target/` segment is excluded, so+generated build outputs never count. Files are grouped by Gradle+module (parsed from `settings.gradle.kts`, including `projectDir`+overrides; longest project dir wins) and per-module totals are printed+on every run (`lines --report` prints without enforcing).++`line-budget.json` is the checked-in baseline. The ratchet fails when+the counted total grows past `baseline_lines`; shrinking always+passes. The per-module figures in the file are a snapshot for+reporting, not per-module caps — only the total is enforced.+Deliberate growth requires bumping the baseline in the same change:+run `python3 tools/structure_check.py lines --regen`, review the+`line-budget.json` diff, and include it with the source change.++The baseline was measured at 1,749,740 lines on 2026-12-01 with the+method above. (The LOC plan's 1,638,083 figure from 2026-11-30 is+reproduced almost exactly — 1,637,724 today — only if `scripts/` and+`infra/` are also excluded; this ratchet counts them, per the plan's+stated `third_party/`-only exclusion, so its baseline is higher.)++Exclusions are data-driven in `line-budget.json`+(`excluded_modules`). The only exclusion is `communicate-dev`, 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), and+only that exact module is excluded. `infra/` (including+`infra/agents`) is deliberately counted.++Tests: `python3 tools/test_structure_check.py`.
docs/structure/line-budget.json
diff --git a/docs/structure/line-budget.json b/docs/structure/line-budget.jsonnew file mode 100644index 0000000000..7abb47f931--- /dev/null+++ b/docs/structure/line-budget.json@@ -0,0 +1,146 @@+{+  "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": [+    ".kt",+    ".java",+    ".rs",+    ".swift"+  ],+  "excluded_path_segments": [+    "third_party",+    "build",+    "target"+  ],+  "excluded_modules": [+    "communicate-dev"+  ],+  "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. infra/ (including infra/agents) is deliberately counted.",+  "baseline_lines": 1749740,+  "modules": {+    "(root)": 1941,+    "apple": 8535,+    "appstore": 37594,+    "appstore/wear": 1172,+    "astronomy": 7021,+    "auto": 20801,+    "auto/protocol": 9886,+    "backup": 4744,+    "build-logic": 1772,+    "calculator": 9457,+    "calendar": 17070,+    "calendar/wear": 964,+    "camera": 55324,+    "camera-wear": 1252,+    "cast": 15929,+    "cast/protocol": 7200,+    "cast/tv": 9795,+    "clock": 11747,+    "clock/wear": 2591,+    "code": 22329,+    "communicate": 111583,+    "communicate-wear": 1998,+    "contacts": 31519,+    "contacts-wear": 1266,+    "desktop/notes": 2587,+    "desktop/passwords": 827,+    "education": 7391,+    "email": 28049,+    "emergency": 5556,+    "euicc": 10092,+    "everysync": 13960,+    "files": 10902,+    "findfamily": 31793,+    "findfamily-wear": 1464,+    "flashcards": 12500,+    "fooddelivery": 13133,+    "games/arrows": 5821,+    "games/chess": 13987,+    "games/hub": 10177,+    "games/kart": 9929,+    "games/logicgate": 9322,+    "games/minesweeper": 4620,+    "games/nonogram": 5825,+    "games/pipes": 8965,+    "games/solitaire": 11459,+    "games/sudoku": 6954,+    "games/unblockjam": 5488,+    "games/voxels": 26103,+    "games/wordmaker": 8500,+    "globalesim": 3214,+    "health": 34954,+    "infra": 19403,+    "keyboard": 11133,+    "launcher": 21166,+    "launcher/wear": 1289,+    "library": 31304,+    "library/aosp-stubs": 1566,+    "library/avatar": 7533,+    "library/biometric": 908,+    "library/carhost": 2174,+    "library/downloadservice": 2321,+    "library/e2ee-openpgp": 1220,+    "library/e2ee-p2p": 2205,+    "library/everysync-core": 5552,+    "library/format": 156,+    "library/image": 4786,+    "library/ink": 940,+    "library/locationprovider": 276,+    "library/log": 820,+    "library/map": 56024,+    "library/media": 3818,+    "library/ml": 78080,+    "library/network": 5380,+    "library/ocr": 446,+    "library/room": 1545,+    "library/tv": 1889,+    "library/ui": 43370,+    "library/wearlink": 1605,+    "library/widgets": 1249,+    "library/work": 472,+    "lint-rules": 5255,+    "logviewer": 5656,+    "madeveloper": 4824,+    "maps": 75766,+    "maps/wear": 1282,+    "measure": 11357,+    "music": 15227,+    "music/wear": 1779,+    "networklocation": 8512,+    "news": 11588,+    "notes": 9981,+    "notes-wear": 1131,+    "office": 59001,+    "openassistant": 14057,+    "parentalcontrols": 7543,+    "passwords": 19608,+    "pdf": 73891,+    "photos": 49119,+    "screentime": 6231,+    "scripts": 92454,+    "sdk/cast": 2376,+    "sdk/controller": 3646,+    "sdk/games": 1017,+    "sdk/openassistant": 323,+    "securemail": 9447,+    "setupwizard": 3113,+    "share": 21108,+    "shop": 8846,+    "speech": 4792,+    "taxi": 12764,+    "things": 7914,+    "todo": 17044,+    "todo-wear": 1784,+    "translate": 8838,+    "travel": 18664,+    "tuner": 9973,+    "uniflix": 12201,+    "updater": 5483,+    "vpn": 15828,+    "weather": 19955,+    "weather/wear": 453,+    "web": 18699,+    "youpipe": 39782,+    "youpipe/extractor": 25736+  }+}
tools/structure_check.py
diff --git a/tools/structure_check.py b/tools/structure_check.pyindex 7c8b946901..2f25ebc3f9 100755--- a/tools/structure_check.py+++ b/tools/structure_check.py@@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Cheap structure ratchets for Modern-Apps (no build, stdlib only). -Three checks, wired into ./check (see docs/structure/README.md):+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@@ -19,9 +19,18 @@ Three checks, wired into ./check (see docs/structure/README.md):              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|all]+  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/,@@ -29,8 +38,10 @@ 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__)))@@ -38,6 +49,8 @@ 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",@@ -291,9 +304,223 @@ def check_exceptions(regen=False):     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. infra/ (incl. infra/agents) is deliberately NOT excluded:+# it 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. infra/ (including infra/agents) is deliberately "+            "counted.",+        "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()@@ -301,7 +528,10 @@ def main(argv):         violations += check_generated()     if which in ("exceptions", "all"):         violations += check_exceptions(regen=regen)-    if which not in ("wear", "generated", "exceptions", "all"):+    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:
tools/test_structure_check.py
diff --git a/tools/test_structure_check.py b/tools/test_structure_check.pynew file mode 100644index 0000000000..b3e7db1017--- /dev/null+++ b/tools/test_structure_check.py@@ -0,0 +1,108 @@+#!/usr/bin/env python3+"""Unit tests for the lines ratchet in structure_check.py (stdlib only).++Run: python3 tools/test_structure_check.py+  or: python3 -m unittest discover -s tools -p 'test_*.py'+"""+import json+import os+import sys+import tempfile+import unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import structure_check as sc  # noqa: E402+++class CountedSourceTest(unittest.TestCase):+    def test_extensions_and_segment_exclusions(self):+        exts = [".kt", ".java", ".rs", ".swift"]+        segs = ["third_party", "build", "target"]+        self.assertTrue(sc.is_counted_source("notes/src/test/A.kt", exts, segs))+        self.assertTrue(sc.is_counted_source("apple/App.swift", exts, segs))+        self.assertTrue(sc.is_counted_source("infra/agents/agentd/src/main.rs", exts, segs))+        self.assertFalse(sc.is_counted_source("notes/A.py", exts, segs))+        self.assertFalse(sc.is_counted_source("third_party/x/A.kt", exts, segs))+        self.assertFalse(sc.is_counted_source("notes/build/generated/A.kt", exts, segs))+        self.assertFalse(sc.is_counted_source("maps/target/A.rs", exts, segs))++    def test_count_source_lines(self):+        with tempfile.TemporaryDirectory() as tmp:+            path = os.path.join(tmp, "A.kt")+            with open(path, "wb") as fh:+                fh.write(b"one\ntwo\nthree")+            self.assertEqual(sc.count_source_lines(path), 3)+            with open(path, "wb") as fh:+                fh.write(b"")+            self.assertEqual(sc.count_source_lines(path), 0)+++class ModuleMappingTest(unittest.TestCase):+    SETTINGS = """+include(":library")+include(":library:ml")+include(":clock")+include(":clock:wear")+project(":clock:wear").projectDir = file("clock-wear")+include(":communicate")+include(":madeveloper")+"""++    def test_parse_and_longest_match(self):+        modules = sc.parse_module_dirs(self.SETTINGS)+        self.assertEqual(modules["library/ml"], "library/ml")+        self.assertEqual(modules["clock/wear"], "clock-wear")+        self.assertEqual(sc.module_for_path("library/ml/src/A.kt", modules), "library/ml")+        self.assertEqual(sc.module_for_path("library/src/A.kt", modules), "library")+        self.assertEqual(sc.module_for_path("clock-wear/src/A.kt", modules), "clock/wear")+        self.assertEqual(sc.module_for_path("scripts/maps/A.rs", modules), "scripts")+        self.assertEqual(sc.module_for_path("MmTelFeature.java", modules), "(root)")++    def test_excluded_module_matching(self):+        excluded = ["communicate-dev"]+        self.assertTrue(sc.is_excluded_module("communicate-dev", excluded))+        self.assertFalse(sc.is_excluded_module("communicate", excluded))+        self.assertFalse(sc.is_excluded_module("infra", excluded))+        self.assertFalse(sc.is_excluded_module("madeveloper", excluded))+++class TallyTest(unittest.TestCase):+    def test_tally_excludes_only_communicate_dev(self):+        with tempfile.TemporaryDirectory() as tmp:+            def write(relpath, lines):+                path = os.path.join(tmp, relpath)+                os.makedirs(os.path.dirname(path), exist_ok=True)+                with open(path, "w", encoding="utf-8") as fh:+                    fh.write("\n".join("x" for _ in range(lines)) + "\n")++            write("notes/src/A.kt", 3)+            write("communicate-dev/src/B.kt", 5)+            write("infra/agents/agentd/src/C.rs", 2)+            write("notes/build/D.kt", 7)+            budget = sc.default_line_budget()+            modules = {"notes": "notes", "communicate-dev": "communicate-dev"}+            total, per_module, excluded_total, _ = sc.tally_lines(+                tmp,+                ["notes/src/A.kt", "communicate-dev/src/B.kt",+                 "infra/agents/agentd/src/C.rs", "notes/build/D.kt"],+                modules, budget)+            self.assertEqual(total, 5)  # notes (3) + infra/agents (2)+            self.assertEqual(per_module["notes"], 3)+            self.assertEqual(excluded_total, 5)++    def test_budget_roundtrip(self):+        with tempfile.TemporaryDirectory() as tmp:+            path = os.path.join(tmp, "line-budget.json")+            budget = sc.default_line_budget()+            sc.write_line_budget(budget, 42, {"notes": 42}, path=path)+            loaded, error = sc.load_line_budget(path)+            self.assertIsNone(error)+            self.assertEqual(loaded["baseline_lines"], 42)+            self.assertEqual(loaded["excluded_modules"], ["communicate-dev"])+            with open(path, encoding="utf-8") as fh:+                raw = json.load(fh)+            self.assertIn("communicate-dev", raw["excluded_modules_note"])+++if __name__ == "__main__":+    unittest.main()