|
| 1 | +"""Coverage metrics for ``kb init`` (design: kb-init v3 §7). |
| 2 | +
|
| 3 | +Pure and deterministic. Two measures of how much of a repository its |
| 4 | +knowledge routes reach: |
| 5 | +
|
| 6 | +* **module coverage** — the share of modules (``profiles.establish. |
| 7 | + scan_modules_at_depth``) whose every source file matches some owner's |
| 8 | + ``scope_prefixes`` in ``_routes.yaml``; |
| 9 | +* **PR-weighted coverage** — over a window of merged PRs, the share of changed |
| 10 | + source files (counted once per PR that changed them) that route to an owner |
| 11 | + (*routed*), and to an owner whose page carries rules (*rule-bearing*). |
| 12 | +
|
| 13 | +An empty population counts as fully covered (ratio 1.0): there is nothing a |
| 14 | +route could miss. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import fnmatch |
| 20 | +from collections import Counter |
| 21 | +from dataclasses import dataclass |
| 22 | +from pathlib import PurePosixPath |
| 23 | +from typing import Callable, Mapping, Sequence |
| 24 | + |
| 25 | +import yaml |
| 26 | + |
| 27 | +# equals profiles.establish.ROOT_MODULE (kb_service stays free of profile |
| 28 | +# imports; a test pins the two together) |
| 29 | +ROOT_MODULE = "./" |
| 30 | + |
| 31 | + |
| 32 | +@dataclass(frozen=True) |
| 33 | +class Owner: |
| 34 | + owner: str |
| 35 | + path: str |
| 36 | + prefixes: tuple[str, ...] |
| 37 | + |
| 38 | + |
| 39 | +@dataclass(frozen=True) |
| 40 | +class Coverage: |
| 41 | + covered: list[str] |
| 42 | + uncovered: list[str] |
| 43 | + ratio: float |
| 44 | + |
| 45 | + |
| 46 | +@dataclass(frozen=True) |
| 47 | +class PrCoverage: |
| 48 | + total: int |
| 49 | + routed: int |
| 50 | + rule_bearing: int |
| 51 | + routed_ratio: float |
| 52 | + rule_bearing_ratio: float |
| 53 | + uncovered_hot: list[tuple[str, int]] |
| 54 | + |
| 55 | + |
| 56 | +def load_owners(routes_yaml_text: str) -> list[Owner]: |
| 57 | + """The ``owners`` of a ``_routes.yaml`` (schema_version 1); ``models`` are |
| 58 | + name-matched, not path-matched, and play no part in coverage.""" |
| 59 | + data = yaml.safe_load(routes_yaml_text) or {} |
| 60 | + if not isinstance(data, dict): |
| 61 | + raise ValueError("_routes.yaml must be a mapping") |
| 62 | + if data.get("schema_version", 1) != 1: |
| 63 | + raise ValueError(f"unsupported _routes.yaml schema_version {data.get('schema_version')!r}") |
| 64 | + owners = data.get("owners") or [] |
| 65 | + if not isinstance(owners, list): |
| 66 | + raise ValueError("_routes.yaml owners must be a list") |
| 67 | + out = [] |
| 68 | + for item in owners: |
| 69 | + if not isinstance(item, dict) or not item.get("owner") or not item.get("path"): |
| 70 | + raise ValueError(f"malformed _routes.yaml owner: {item!r}") |
| 71 | + prefixes = item.get("scope_prefixes") or [] |
| 72 | + if not isinstance(prefixes, list) or any(not isinstance(p, str) or not p for p in prefixes): |
| 73 | + raise ValueError(f"{item['owner']}: scope_prefixes must be a list of non-empty strings") |
| 74 | + out.append(Owner(str(item["owner"]), str(item["path"]), tuple(prefixes))) |
| 75 | + return out |
| 76 | + |
| 77 | + |
| 78 | +def routes_file(path: str, owners: Sequence[Owner]) -> list[Owner]: |
| 79 | + """Every owner whose scope prefixes reach ``path``, in routing order.""" |
| 80 | + return [o for o in owners if any(path.startswith(p) for p in o.prefixes)] |
| 81 | + |
| 82 | + |
| 83 | +def module_coverage(modules: Mapping[str, Mapping], owners: Sequence[Owner]) -> Coverage: |
| 84 | + covered, uncovered = [], [] |
| 85 | + for key in sorted(modules): |
| 86 | + files = modules[key].get("files") or [] |
| 87 | + (covered if all(routes_file(f, owners) for f in files) else uncovered).append(key) |
| 88 | + total = len(covered) + len(uncovered) |
| 89 | + return Coverage(covered, uncovered, len(covered) / total if total else 1.0) |
| 90 | + |
| 91 | + |
| 92 | +def _normalize(path: str) -> str: |
| 93 | + """Repo-relative POSIX form without leading ``./`` or slashes; the repository |
| 94 | + root is ``""`` (same rule as ``profiles.establish.normalize_root``).""" |
| 95 | + text = PurePosixPath(path.strip().strip("/") or ".").as_posix() |
| 96 | + return "" if text == "." else text |
| 97 | + |
| 98 | + |
| 99 | +def make_include(source_roots: Sequence[str], exclude: Sequence[str], |
| 100 | + suffixes: Sequence[str] = ()) -> Callable[[str], bool]: |
| 101 | + """A filter for changed paths: under a source root (any path when none are |
| 102 | + given), with a source suffix (any when none are given), matching no |
| 103 | + ``exclude`` fnmatch glob. Tests, docs and generated files are the caller's |
| 104 | + ``exclude`` globs; nothing repository-specific is built in.""" |
| 105 | + normalized = {_normalize(r) for r in source_roots} |
| 106 | + # the repository root (".", "./", "") admits every path |
| 107 | + roots = () if "" in normalized else tuple(sorted(r + "/" for r in normalized)) |
| 108 | + sfx = tuple(suffixes) |
| 109 | + |
| 110 | + def include(path: str) -> bool: |
| 111 | + path = _normalize(path) |
| 112 | + if roots and not path.startswith(roots): |
| 113 | + return False |
| 114 | + if sfx and not path.endswith(sfx): |
| 115 | + return False |
| 116 | + return not any(fnmatch.fnmatch(path, glob) for glob in exclude) |
| 117 | + |
| 118 | + return include |
| 119 | + |
| 120 | + |
| 121 | +def pr_weighted_coverage(prs: Sequence[Sequence[str]], owners: Sequence[Owner], *, |
| 122 | + include: Callable[[str], bool], |
| 123 | + rule_pages: set[str] | None = None) -> PrCoverage: |
| 124 | + """Each file a PR changes counts once for that PR. ``rule_pages`` are the |
| 125 | + knowledge paths (as ``_routes.yaml`` names them) holding at least one |
| 126 | + active rule; without them nothing is rule-bearing.""" |
| 127 | + pages = rule_pages or set() |
| 128 | + total = routed = rule_bearing = 0 |
| 129 | + missed: Counter[str] = Counter() |
| 130 | + for files in prs: |
| 131 | + for path in sorted({_normalize(f) for f in files}): |
| 132 | + if not include(path): |
| 133 | + continue |
| 134 | + total += 1 |
| 135 | + hits = routes_file(path, owners) |
| 136 | + if hits: |
| 137 | + routed += 1 |
| 138 | + if any(o.path in pages for o in hits): |
| 139 | + rule_bearing += 1 |
| 140 | + else: |
| 141 | + missed[path] += 1 |
| 142 | + hot = sorted(missed.items(), key=lambda item: (-item[1], item[0])) |
| 143 | + return PrCoverage(total, routed, rule_bearing, |
| 144 | + routed / total if total else 1.0, |
| 145 | + rule_bearing / total if total else 1.0, hot) |
| 146 | + |
| 147 | + |
| 148 | +def module_of(path: str, modules: Mapping[str, Mapping]) -> str | None: |
| 149 | + """The module owning ``path``: the longest module key that prefixes it (a |
| 150 | + file in a folded directory belongs to the ancestor it folded into).""" |
| 151 | + best = None |
| 152 | + for key in modules: |
| 153 | + prefix = "" if key == ROOT_MODULE else key |
| 154 | + if path.startswith(prefix) and (best is None or len(prefix) > len(best[1])): |
| 155 | + best = (key, prefix) |
| 156 | + return best[0] if best else None |
| 157 | + |
| 158 | + |
| 159 | +def churn_by_module(prs: Sequence[Sequence[str]], modules: Mapping[str, Mapping]) -> list[tuple[str, int]]: |
| 160 | + """File changes per module over the PR window, highest first (ties by |
| 161 | + module path). Paths no module owns are not counted.""" |
| 162 | + counts: Counter[str] = Counter() |
| 163 | + for files in prs: |
| 164 | + for path in sorted({_normalize(f) for f in files}): |
| 165 | + key = module_of(path, modules) |
| 166 | + if key is not None: |
| 167 | + counts[key] += 1 |
| 168 | + return sorted(counts.items(), key=lambda item: (-item[1], item[0])) |
0 commit comments