Merge claude/debt-engine: architecture gate exceptions list

This commit is contained in:
Pavlo Ratushnyi
2026-11-14 18:16:57 +01:00
5 changed files with 51 additions and 8 deletions
+2
View File
@@ -49,6 +49,8 @@
"patterns": ["^impl_.*\\.rs$", "_fn\\.rs$", "_[0-9]+(_[0-9]+)*\\.rs$"],
"allow": ["^(quantize_)?q[0-9]_[0-9k]\\.rs$"]
},
"_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.",
"exceptions": [],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
{"id": "instant-now", "regex": "\\bInstant::now\\(\\)", "why": "time must come from an injected Clock in core logic (S14)"},
+4 -2
View File
@@ -66,9 +66,11 @@ def main(argv, default_root):
old = bl.load(baseline_path)
packages = measure.load_metadata(root)
sizes = measure.file_lines(root, packages)
counts = measure.count_patterns(packages, config["source_patterns"])
exceptions, excused = config.get("exceptions", []), {}
counts = measure.count_patterns(packages, config["source_patterns"], exceptions, excused)
exception_errors = rules.exception_findings(exceptions, excused, {p["id"] for p in config["source_patterns"]})
names = measure.mechanical_names(root, packages, config.get("mechanical_names", {}))
found = rules.evaluate(packages, config, old, rules.Measured(sizes, counts, names))
found = rules.evaluate(packages, config, old, rules.Measured(sizes, counts, names, tuple(exception_errors)))
if args.report:
report(packages, config, sizes, counts)
return 0
+12 -5
View File
@@ -94,13 +94,16 @@ def _after_block(lines, start):
return len(lines)
def count_patterns(packages, patterns):
def count_patterns(packages, patterns, exceptions=(), excused=None):
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only
(test files and modules declared under a test cfg are skipped)."""
(test files and modules declared under a test cfg are skipped). A file named by an entry of `exceptions`
({"crate", "file", "ratchet", "reason"}; `file` is relative to the crate directory) is not counted for that
ratchet; the hits it excused are added to `excused` ({(crate, file, ratchet): n}) when it is given."""
compiled = [(p["id"], re.compile(p["regex"]), bool(p.get("ignore_imports"))) for p in patterns]
counts = {}
for pkg in packages:
for pid, n in _package_counts(pkg["dir"] / "src", compiled).items():
skip = {(e["file"], e["ratchet"]) for e in exceptions if e["crate"] == pkg["name"]}
for pid, n in _package_counts(pkg["dir"] / "src", compiled, skip, pkg["name"], excused).items():
counts[f"{pid}:{pkg['name']}"] = n
return counts
@@ -187,7 +190,7 @@ def _under_test_module(path, test_files):
_USE_STATEMENT = re.compile(r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?use\b[^;]*;[ \t]*\n?")
def _package_counts(src, compiled):
def _package_counts(src, compiled, skip=frozenset(), crate="", excused=None):
totals = {}
if not src.is_dir():
return totals
@@ -198,8 +201,12 @@ def _package_counts(src, compiled):
text = _text(path)
rows = production_lines(text)
rows_without_imports = production_lines(_USE_STATEMENT.sub("", text))
relative = path.relative_to(src.parent).as_posix()
for pid, rx, ignore_imports in compiled:
n = sum(len(rx.findall(row)) for row in (rows_without_imports if ignore_imports else rows))
if n:
if n and (relative, pid) in skip:
if excused is not None:
excused[(crate, relative, pid)] = n
elif n:
totals[pid] = totals.get(pid, 0) + n
return totals
+17 -1
View File
@@ -126,12 +126,28 @@ def mechanical_findings(names, baseline):
return errors, stale
def exception_findings(exceptions, excused, known_ratchets):
"""Errors for the `exceptions` list of architecture.json: each needs a reason, a known ratchet and at least one
hit in its file; an entry that excuses nothing is a stale exception and must be removed."""
errors = []
for e in exceptions:
label = f"exception {e.get('crate')} {e.get('file')} {e.get('ratchet')}"
if not str(e.get("reason", "")).strip():
errors.append(f"{label}: an exception needs a reason")
if e.get("ratchet") not in known_ratchets:
errors.append(f"{label}: unknown ratchet")
elif (e.get("crate"), e.get("file"), e.get("ratchet")) not in excused:
errors.append(f"{label}: the file has no such hit any more; remove the exception")
return errors
@dataclass
class Measured:
"""What was measured in the source tree: file line counts, source pattern counts, mechanical file names."""
sizes: dict
counts: dict
names: tuple = ()
exception_errors: tuple = ()
def evaluate(packages, config, baseline, measured):
@@ -143,6 +159,6 @@ def evaluate(packages, config, baseline, measured):
size_errors, size_stale = size_findings(sizes, baseline, config["max_lines"])
ratchet_errors, ratchet_stale = ratchet_findings(counts, baseline)
name_errors, name_stale = mechanical_findings(names, baseline)
result.errors += errors + size_errors + ratchet_errors + name_errors
result.errors += errors + size_errors + ratchet_errors + name_errors + list(measured.exception_errors)
result.stale = stale + size_stale + ratchet_stale + name_stale
return result
+16
View File
@@ -220,6 +220,22 @@ class Measurement(unittest.TestCase):
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 4})
def test_a_listed_exception_is_not_counted_and_an_unused_one_is_an_error(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text('let a = env::var("A");\nmod clock;\n')
(src / "clock.rs").write_text('let b = env::var("B");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
patterns = [{"id": "e", "regex": r"env::var\("}]
listed = {"crate": "p", "file": "src/clock.rs", "ratchet": "e", "reason": "the clock adapter"}
excused = {}
counts = measure.count_patterns([package], patterns, [listed], excused)
self.assertEqual((counts, excused), ({"e:p": 1}, {("p", "src/clock.rs", "e"): 1}))
self.assertEqual(rules.exception_findings([listed], excused, {"e"}), [])
unused = dict(listed, file="src/lib.rs", ratchet="x")
self.assertEqual(len(rules.exception_findings([unused, dict(listed, reason="")], excused, {"e"})), 2)
if __name__ == "__main__":
unittest.main()