Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): flag added suppressions, weakened tests and test-only branches in health check (#4312)
Raghav Chamadiya002e0725ca36
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 880fc4c16..ec2d99f3b 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -258,7 +258,7 @@ result to the index. `repowise health --badge` prints README badge Markdown.## In CI: `repowise health check`-`repowise health check origin/main...HEAD` analyses the changed files at the base and the head, with no index, and exits `1` only on a code-shape finding the change wrote at high severity or above (`--fail-at` moves the floor). A lower one warns, as does a finding it made worse (`--fail-on worsened` fails on it too), and one it moved or renamed never fails. Git-history markers, coverage and file scores never decide the gate, so a squash merge cannot change its verdict. `.repowise/health-rules.json` is read from the change's base, so a change cannot loosen its own gate. Exit codes, formats and setup are in [Repowise in CI](../start/CI.md).+`repowise health check origin/main...HEAD` analyses the changed files at the base and the head, with no index, and exits `1` only on a code-shape finding the change wrote at high severity or above (`--fail-at` moves the floor). A lower one warns, as does a finding it made worse (`--fail-on worsened` fails on it too), and one it moved or renamed never fails. Git-history markers, coverage and file scores never decide the gate, so a squash merge cannot change its verdict. `.repowise/health-rules.json` is read from the change's base, so a change cannot loosen its own gate. It also warns when the change adds a suppression comment, skips or removes tests, loosens a coverage threshold, or adds a test-environment branch to production code; `--diff-risk error` makes those fail. Exit codes, formats and setup are in [Repowise in CI](../start/CI.md).## Configurationdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 84c66acbf..d020c7e7b 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1201,9 +1201,12 @@ Gate a change on the code-health findings it introduces. Built for CI: it needs|------|-------------|| `--fail-on` | `introduced` (default) or `worsened` || `--fail-at` | Lowest severity that can fail: `medium`, `high` (default), `critical` |+| `--diff-risk` | Level of the diff-risk rules: `warn` (default), `error` or `off`. `LEVEL` sets all three, `RULE=LEVEL` one; repeatable || `--path` | A path inside the repository (defaults to cwd) || `--format` | `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |+Three diff-risk rules read the changed text in any supported language and warn by default: `added-suppression` (a new lint, type-check, coverage or repowise suppression comment or attribute, or a biomarker newly disabled in `.repowise/health-rules.json`), `weakened-tests` (a new unconditional skip or focus marker, fewer test cases or assertions, a loosened coverage threshold) and `test-only-branch` (a new test-environment check in production code). A marker that moved to another file with its code does not count.+REVSPEC is the change, resolved as for [`security check`](#repowise-security-check-revspec). Rules in `.repowise/health-rules.json` are read as the change's base has them and apply to both sides, so a change cannot loosen its own gate; an invalid file there exits `2`. A changed code file left unread (unparsable, or over 1.5 MB) warns; a change touching no file health reads passes with a note.```bashdiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/check.py b/packages/cli/src/repowise/cli/commands/health_cmd/check.pyindex a4923f89e..17d785d01 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/check.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/check.py@@ -54,6 +54,15 @@ _FORMATS = (*CI_FORMATS, "sarif", "gitlab")show_default=True,help="The lowest severity that can fail; findings below it warn.",)+ "--diff-risk",+ "diff_risk",+ multiple=True,+ metavar="[RULE=]LEVEL",+ help="Level of the diff-risk rules (added-suppression, weakened-tests, "+ "test-only-branch): warn (default), error or off. LEVEL sets every rule, "+ "RULE=LEVEL one; repeatable.",+)@click.option("--path","repo",@@ -67,7 +76,12 @@ _FORMATS = (*CI_FORMATS, "sarif", "gitlab")"upload; ``gitlab`` is a GitLab Code Quality report.",)def health_check(- revspec: str | None, fail_on: str, fail_at: str, repo: str | None, fmt: str+ revspec: str | None,+ fail_on: str,+ fail_at: str,+ diff_risk: tuple[str, ...],+ repo: str | None,+ fmt: str,) -> None:"""Gate a change on the health findings it introduces (no index needed, built for CI).@@ -77,6 +91,9 @@ def health_check(nesting, size, duplication, error handling) decide; git history, coverageand file scores never do. Rules in .repowise/health-rules.json are readas the change's base has them, so a change cannot loosen its own gate.+ Diff-risk rules also warn on a change that adds a suppression comment,+ skips or removes tests, loosens a coverage threshold, or adds a+ test-environment branch to production code.REVSPEC is the change: ``origin/main...HEAD`` (the pull-request view),``base..head``, or one commit. Without it, the base comes from the CI's@@ -86,6 +103,7 @@ def health_check(repowise health check origin/main...HEADrepowise health check --fail-on worsened --fail-at medium+ repowise health check --diff-risk error --diff-risk test-only-branch=offrepowise health check --format githubrepowise health check --format sarif > health.sarifrepowise health check --format gitlab > gl-code-quality-health.json@@ -94,8 +112,9 @@ def health_check(silence_logs_for_machine_output_until_close()else:configure_cli_logging(verbose=False)+ levels = _diff_risk_levels(diff_risk)try:- verdict = _evaluate(revspec, fail_on, fail_at, repo)+ verdict = _evaluate(revspec, fail_on, fail_at, repo, levels)except (click.exceptions.Exit, click.ClickException, click.Abort):raiseexcept CannotEvaluateError as exc:@@ -117,41 +136,64 @@ class _Verdict:label: str-def _evaluate(revspec: str | None, fail_on: str, fail_at: str, repo: str | None) -> _Verdict:+def _diff_risk_levels(values: tuple[str, ...]) -> dict[str, str]:+ """``{rule: level}`` from ``--diff-risk`` values; later values win."""+ from repowise.core.analysis.diff_risk import RULES++ levels: dict[str, str] = {}+ for value in values:+ rule, _, level = value.rpartition("=")+ if level not in ("warn", "error", "off") or (rule and rule not in RULES):+ raise click.BadParameter(+ f"{value!r}: expected warn, error or off, or RULE=LEVEL with RULE one of "+ f"{', '.join(RULES)}.",+ param_hint="--diff-risk",+ )+ levels.update({rule: level} if rule else dict.fromkeys(RULES, level))+ return levels+++def _evaluate(+ revspec: str | None, fail_on: str, fail_at: str, repo: str | None, levels: dict[str, str]+) -> _Verdict:from repowise.core.analysis.change_health.service import (ChangeHealthDeltaService,DeltaRequest,)from repowise.core.analysis.change_health.sources import GitRevisionSource- from repowise.core.analysis.health_gate import NotEvaluatedError, evaluate+ from repowise.core.analysis.diff_risk import diff_risk_for_change+ from repowise.core.analysis.health_gate import (+ NotEvaluatedError,+ diff_risk_findings,+ evaluate,+ )root = str(repo_root(repo))label = ci_revspec(root, revspec)source = GitRevisionSource(root)- rules = _base_rules(source, label)- delta = ChangeHealthDeltaService(source, repo_path=root, health_config=rules).compare(- DeltaRequest(root, label)- )try:- result = evaluate(delta, fail_on=fail_on, fail_at=fail_at)+ pair = source.resolve(label)+ except ValueError as exc:+ raise _not_evaluated("unsupported_range", str(exc)) from exc+ rules = _base_rules(source, pair.base_sha)+ service = ChangeHealthDeltaService(source, repo_path=root, health_config=rules)+ # One resolution serves the comparison and the diff-risk rules.+ delta = service.compare(DeltaRequest(root, label), pair=pair)+ risks = diff_risk_findings(diff_risk_for_change(source, pair, severities=levels))+ try:+ result = evaluate(delta, fail_on=fail_on, fail_at=fail_at, extra=risks)except NotEvaluatedError as exc:raise _not_evaluated(exc.code, str(exc)) from excreturn _Verdict(result, delta, label)-def _base_rules(source: GitRevisionSource, label: str) -> HealthConfig:- """``.repowise/health-rules.json`` as the change's base has it; defaults when absent.+def _base_rules(source: GitRevisionSource, base: str) -> HealthConfig:+ """``.repowise/health-rules.json`` at the change's *base*; defaults when absent.- Read at the base so a change cannot loosen its own gate. The revision is- resolved here and again by the comparison: one extra diff, kept so the- service stays the single owner of what it compares.+ Read at the base so a change cannot loosen its own gate."""from repowise.core.analysis.health.config import HEALTH_RULES_PATH, HealthConfig- try:- base = source.resolve(label).base_sha- except ValueError as exc:- raise _not_evaluated("unsupported_range", str(exc)) from excraw = source.read(base, [HEALTH_RULES_PATH]).get(HEALTH_RULES_PATH)if raw is None:return HealthConfig()diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.pyindex 985493af4..4e6bbffc1 100644--- a/packages/core/src/repowise/core/analysis/change_health/service.py+++ b/packages/core/src/repowise/core/analysis/change_health/service.py@@ -161,16 +161,21 @@ class ChangeHealthDeltaService:# -- entry point --------------------------------------------------------- def compare(self, request: DeltaRequest) -> ChangeHealthDelta:+ def compare(+ self, request: DeltaRequest, *, pair: RevisionPair | None = None+ ) -> ChangeHealthDelta:"""Compare *request*, serving an identical in-flight call one result.The revision is resolved once and threaded through, so neither thecache key nor a cache hit re-reads the change shape from the source.+ A caller that already resolved ``request.revspec`` on :attr:`source`+ passes that *pair*, so the change is not diffed twice."""- try:- pair = self.source.resolve(request.revspec)- except ValueError as exc:- return _unavailable("unsupported_range", str(exc))+ if pair is None:+ try:+ pair = self.source.resolve(request.revspec)+ except ValueError as exc:+ return _unavailable("unsupported_range", str(exc))key = self._cache_key(request, pair)# One wait, then one retry at becoming the leader. A caller that still# finds work in flight does it rather than blocking a thread again.diff --git a/packages/core/src/repowise/core/analysis/diff_risk/__init__.py b/packages/core/src/repowise/core/analysis/diff_risk/__init__.pynew file mode 100644index 000000000..0458eae35--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/__init__.py@@ -0,0 +1,22 @@+"""Diff-risk rules: textual facts about a change that can game a health gate.++:mod:`.detect` orchestrates the rules in :mod:`.rules`, whose vocabulary is the+data in :mod:`.markers`; :mod:`.source` is the one IO adapter.+"""++from __future__ import annotations++from .detect import detect_diff_risk+from .models import RULES, DiffRiskFinding, FileTexts+from .paths import is_relevant+from .source import diff_risk_for_change, read_change_texts++__all__ = [+ "RULES",+ "DiffRiskFinding",+ "FileTexts",+ "detect_diff_risk",+ "diff_risk_for_change",+ "is_relevant",+ "read_change_texts",+]diff --git a/packages/core/src/repowise/core/analysis/diff_risk/detect.py b/packages/core/src/repowise/core/analysis/diff_risk/detect.pynew file mode 100644index 000000000..6f86584b4--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/detect.py@@ -0,0 +1,228 @@+"""The diff-risk rules: facts about a change that can game a health gate.++- ``added-suppression`` (:mod:`.rules.suppression`): a new lint, type-check,+ coverage or repowise suppression comment or attribute, or a biomarker newly+ disabled in ``.repowise/health-rules.json``.+- ``weakened-tests`` (:mod:`.rules.weakened_tests`, :mod:`.rules.removed_tests`):+ a new skip or focus marker in a test file, fewer test cases across the+ changed test files, fewer assertions in a test file, or a less strict+ coverage or quality threshold.+- ``test-only-branch`` (:mod:`.rules.test_only_branch`): a new+ test-environment check in production source.++:func:`detect_diff_risk` is pure: it reads the base and head text the caller+hands it and touches no filesystem or git. This module only orchestrates:+it reads each file once, nets marker counts across the change, and stamps+severities and ids.+"""++from __future__ import annotations++import hashlib+from collections import Counter, defaultdict+from collections.abc import Iterable, Mapping+from dataclasses import dataclass+from typing import cast, get_args++from ...references import path_identity+from ...test_paths import is_test_path+from ..change_health.analyzer import language_of+from .models import (+ RULES,+ DiffRiskFinding,+ FileTexts,+ Lens,+ RawFinding,+ Rule,+ Severity,+ Tagged,+ TestClassifier,+ TestFile,+)+from .paths import in_scope, is_health_rules, is_production, is_prose, threshold_file+from .rules import removed_tests, suppression, test_only_branch, weakened_tests+from .text import FileView, added_line_indexes++DEFAULT_SEVERITY: Severity = "warn"+_SEVERITIES = frozenset(get_args(Severity))++#: Bumped when the identity inputs change.+IDENTITY_VERSION = 1+_ID_PREFIX = "drf_"++Levels = dict[Rule, Severity]+++def detect_diff_risk(+ files: Iterable[FileTexts],+ *,+ severities: Mapping[str, str] | None = None,+ is_test: TestClassifier | None = None,+) -> list[DiffRiskFinding]:+ """Every diff-risk finding in *files*, sorted by path and line.++ *severities* maps a rule id to ``off``, ``warn`` or ``error``; a missing+ rule is ``warn``. *is_test* classifies ``(path, language)`` as a test+ file; the default is repowise's shared test-path classifier.+ """+ classify = is_test or is_test_path+ level: Levels = {rule: _severity(severities, rule) for rule in RULES}+ files = [f for f in files if in_scope(f)]+ raw: list[RawFinding] = []+ tests: list[TestFile] = []+ hits: list[_FileHits] = []+ for file in files:+ config = _config_findings(file, level)+ if config is not None:+ raw.extend(config)+ continue+ read = _read(file, classify, level)+ hits.append(read.hits)+ tests.extend([read.test] if read.test else [])+ raw.extend(_net(hits))+ if level["weakened-tests"] != "off":+ raw.extend(removed_tests.removed_tests(tests, files, classify))+ return _finalize(raw, level)+++def _severity(severities: Mapping[str, str] | None, rule: str) -> Severity:+ value = (severities or {}).get(rule, DEFAULT_SEVERITY)+ return cast(Severity, value) if value in _SEVERITIES else DEFAULT_SEVERITY+++def _config_findings(file: FileTexts, level: Levels) -> list[RawFinding] | None:+ """Findings of a health-rules or threshold config file; ``None`` for any other file."""+ if is_health_rules(file.path):+ if level["added-suppression"] == "off":+ return []+ return suppression.disabled_biomarkers(file.path, file.base, file.head)+ spec = threshold_file(file.path)+ if spec is None:+ return None+ if level["weakened-tests"] == "off" or file.base is None or file.head is None:+ return []+ return weakened_tests.weakened_thresholds(file.path, spec, file.base, file.head)+++@dataclass(slots=True)+class _FileHits:+ """The line-rule markers of one changed file, on both sides."""++ path: str+ base: list[Tagged]+ head: list[Tagged]+ #: 0-based head lines the change added.+ added: set[int]+ head_lines: list[str]+++@dataclass(slots=True)+class _Read:+ hits: _FileHits+ #: Set for a test file, which the counting rules read too.+ test: TestFile | None+++def _read(file: FileTexts, is_test: TestClassifier, level: Levels) -> _Read:+ """One file's line-rule markers, base on raw lines and head on both masks.++ See :meth:`.text.FileView.raw_hits` for why the sides differ.+ """+ path = file.path+ prose = is_prose(path)+ language = None if prose else language_of(path)+ base = _view(file.base, file.base_path or path, language, prose)+ head = _view(file.head, path, language, prose)+ test = not prose and is_test(path, language)+ lens = Lens(language, prose, test, not (test or prose) and is_production(file))+ base_lines = base.lines if base else []+ head_lines = head.lines if head else []+ hits = _FileHits(+ path,+ _tagged(base, lens, level, raw=True),+ _tagged(head, lens, level, raw=False),+ set(added_line_indexes(base_lines, head_lines)),+ head_lines,+ )+ return _Read(hits, TestFile(path, base, head) if test else None)+++def _view(text: str | None, path: str, language: str | None, prose: bool) -> FileView | None:+ return None if text is None else FileView(text, path, language, prose=prose)+++def _tagged(view: FileView | None, lens: Lens, level: Levels, *, raw: bool) -> list[Tagged]:+ """Every line-rule marker of one side, tagged with its rule and kind."""+ if view is None:+ return []+ out: list[Tagged] = []+ if level["added-suppression"] != "off":+ out += suppression.hits(view, lens, raw=raw)+ if lens.test and level["weakened-tests"] != "off":+ skips = weakened_tests.skip_hits(view, lens.language, raw=raw)+ out += [("weakened-tests", "skip-marker", h) for h in skips]+ if lens.production and level["test-only-branch"] != "off":+ checks = test_only_branch.hits(view, lens.language, raw=raw)+ out += [("test-only-branch", "test-env-check", h) for h in checks]+ return out+++def _net(files: list[_FileHits]) -> list[RawFinding]:+ """Markers the whole change added, net of the ones it removed.++ A marker counts by its key across every changed file, so a suppression or+ a skip that moved to another file with its code (a module split) is not+ added. When head holds *n* more of a key than base, the first *n* head+ occurrences on added lines are reported, in path and line order.+ """+ balance: Counter[tuple[str, str, str]] = Counter()+ for f in files:+ balance.update((rule, kind, hit.key) for rule, kind, hit in f.head)+ balance.subtract((rule, kind, hit.key) for rule, kind, hit in f.base)+ out: list[RawFinding] = []+ for f in sorted(files, key=lambda f: f.path):+ for tagged in sorted(f.head, key=lambda t: t[2].line):+ key = (tagged[0], tagged[1], tagged[2].key)+ if balance[key] > 0 and tagged[2].line - 1 in f.added:+ balance[key] -= 1+ out.append(_line_finding(tagged, f))+ return out+++def _line_finding(tagged: Tagged, f: _FileHits) -> RawFinding:+ rule, kind, hit = tagged+ if rule == "added-suppression":+ message = suppression.message(hit)+ elif rule == "weakened-tests":+ message = weakened_tests.skip_message(f.head_lines[hit.line - 1])+ else:+ message = test_only_branch.message(hit)+ return RawFinding(rule, kind, f.path, hit.line, hit.label, message, hit.key)+++def _finalize(raw: list[RawFinding], level: Levels) -> list[DiffRiskFinding]:+ raw.sort(key=lambda r: (r.path, r.line or 0, r.rule, r.kind, r.evidence))+ ordinals: defaultdict[tuple[str, ...], int] = defaultdict(int)+ out: list[DiffRiskFinding] = []+ for r in raw:+ identity = (r.rule, r.kind, path_identity(r.path), r.label)+ out.append(+ DiffRiskFinding(+ finding_id=_finding_id(identity, ordinals[identity]),+ rule=r.rule,+ kind=r.kind,+ path=r.path,+ line=r.line,+ severity=level[r.rule],+ message=r.message,+ evidence=r.evidence,+ )+ )+ ordinals[identity] += 1+ return out+++def _finding_id(identity: tuple[str, ...], ordinal: int) -> str:+ """No line number: an edit above the finding does not move its id."""+ payload = "\x00".join([str(IDENTITY_VERSION), *identity, str(ordinal)])+ return _ID_PREFIX + hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]diff --git a/packages/core/src/repowise/core/analysis/diff_risk/markers.py b/packages/core/src/repowise/core/analysis/diff_risk/markers.pynew file mode 100644index 000000000..f38f4f847--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/markers.py@@ -0,0 +1,442 @@+"""The marker vocabulary of the diff-risk rules, as data.++Every rule reads these tables; no rule holds a language branch of its own. A+row names the languages it applies to (``None`` means every code language)+and the regular expression that finds it. Adding a linter or a test framework+is one row here, never new code.++Patterns run on a per-line view of the file (see :mod:`.text`):++- suppression patterns run on the *comment* view, where only comment text+ is left, and start at a comment opener, so a marker named in prose inside a+ comment or quoted in a string literal never counts;+- every other pattern runs on the *text* view (comments blanked, strings+ kept), and its match must start in code, not inside a string literal.+"""++from __future__ import annotations++import re+from dataclasses import dataclass++JS = frozenset({"javascript", "typescript", "vue", "svelte", "astro"})+PY = frozenset({"python"})+GO = frozenset({"go"})+RUST = frozenset({"rust"})+JVM = frozenset({"java", "kotlin"})+CSHARP = frozenset({"csharp"})+C_FAMILY = frozenset({"c", "cpp", "objectivec"})+RUBY = frozenset({"ruby"})+PHP = frozenset({"php"})+SWIFT = frozenset({"swift"})+DART = frozenset({"dart"})++#: Languages where ``#`` opens a line comment. Elsewhere ``#`` is code: a+#: preprocessor line, a Rust or PHP attribute, a JS private field.+HASH_COMMENT_LANGUAGES = frozenset(+ {+ "python", "ruby", "php", "shell", "perl", "r", "elixir", "crystal", "nim", "julia",+ "yaml", "toml", "dockerfile", "makefile", "terraform",+ }+)++#: Documentation files whose HTML comments can carry a repowise marker.+PROSE_SUFFIXES = (".md", ".mdx")++#: Where a comment starts: a marker must follow one directly. At the start of+#: a comment any opener counts (``*`` is a docblock continuation line); inside+#: one only a nested ``#`` or ``//`` after a space does, so+#: prose such as ``# a * noqa`` or a URL never matches.+_COMMENT_OPENER = (+ r"(?:(?:^|(?<=\x00))[ \t]*(?:#|//+|/\*+|\*|<!--|--)|(?<=[ \t])(?:#|//+))[ \t]*"+)+++@dataclass(frozen=True, slots=True)+class Marker:+ """One textual marker a rule looks for."""++ label: str+ pattern: re.Pattern[str]+ #: ``None``: every code language.+ languages: frozenset[str] | None = None+ #: Also honoured in Markdown prose, inside an HTML comment.+ prose: bool = False++ def applies_to(self, language: str | None, *, is_prose: bool) -> bool:+ if is_prose:+ return self.prose+ if language is None:+ return False+ return self.languages is None or language in self.languages+++def _comment(label: str, body: str, languages: frozenset[str] | None, **kw: bool) -> Marker:+ return Marker(label, re.compile(_COMMENT_OPENER + "(?:" + body + ")"), languages, **kw)+++def _code(label: str, body: str, languages: frozenset[str] | None, flags: int = 0) -> Marker:+ return Marker(label, re.compile(body, flags), languages)+++# -- added-suppression --------------------------------------------------------++#: Comment markers that turn a check off. The comment text from the marker to+#: the end of the line is the marker's identity, so adding a code to an+#: existing noqa list is an added suppression too.+COMMENT_SUPPRESSIONS: tuple[Marker, ...] = (+ _comment("eslint-disable", r"eslint-disable\b", JS),+ _comment("oxlint-disable", r"oxlint-disable\b", JS),+ _comment("biome-ignore", r"biome-ignore\b", JS),+ _comment("deno-lint-ignore", r"deno-lint-ignore\b", JS),+ _comment("@ts-ignore", r"@ts-ignore\b", JS),+ _comment("@ts-expect-error", r"@ts-expect-error\b", JS),+ _comment("@ts-nocheck", r"@ts-nocheck\b", JS),+ _comment("istanbul ignore", r"istanbul[ \t]+ignore\b", JS),+ _comment("c8 ignore", r"c8[ \t]+ignore\b", JS),+ _comment("v8 ignore", r"v8[ \t]+ignore\b", JS),+ _comment("noqa", r"noqa\b", PY),+ _comment("type: ignore", r"type:[ \t]*ignore\b", PY),+ _comment("pyright: ignore", r"pyright:[ \t]*ignore\b", PY),+ _comment("pylint: disable", r"pylint:[ \t]*disable\b", PY),+ _comment("pragma: no cover", r"pragma:[ \t]*no[ \t]+(?:cover|branch)\b", PY),+ _comment("nosec", r"#?nosec\b", PY | GO),+ _comment("nolint", r"nolint\b", GO),+ _comment("NOLINT", r"NOLINT(?:NEXTLINE|BEGIN)?\b", C_FAMILY),+ _comment("cppcheck-suppress", r"cppcheck-suppress\b", C_FAMILY),+ _comment("ReSharper disable", r"ReSharper[ \t]+disable\b", CSHARP),+ _comment("CHECKSTYLE:OFF", r"CHECKSTYLE[:.]OFF\b", JVM),+ _comment("rubocop:disable", r"rubocop[ \t]*:[ \t]*(?:disable|todo)\b", RUBY),+ _comment("phpcs:ignore", r"phpcs:(?:ignore|disable)\b", PHP),+ _comment("@phpstan-ignore", r"@phpstan-ignore", PHP),+ _comment("@psalm-suppress", r"@psalm-suppress\b", PHP),+ _comment("@codeCoverageIgnore", r"@codeCoverageIgnore", PHP),+ _comment("swiftlint:disable", r"swiftlint:disable\b", SWIFT),+ _comment("ignore:", r"ignore(?:_for_file)?[ \t]*:", DART),+ _comment("NOSONAR", r"NOSONAR\b", None),+ # Markers repowise's own gates honour.+ _comment("repowise-security-ignore", r"repowise-security-ignore\b", None, prose=True),+ _comment("repowise-drift-ignore", r"repowise-drift-ignore", None, prose=True),+ _comment("pragma: allowlist secret", r"pragma:[ \t]*allowlist\b", None, prose=True),+ _comment("gitleaks:allow", r"gitleaks:allow\b", None, prose=True),+ _comment("trufflehog:ignore", r"trufflehog:ignore\b", None, prose=True),+)++#: Suppressions written as code: an attribute, annotation or pragma.+CODE_SUPPRESSIONS: tuple[Marker, ...] = (+ _code("#[allow]", r"#!?\[\s*allow\s*\(", RUST),+ _code(+ "@SuppressWarnings",+ r"(?<![\w.])@(?:file:)?Suppress(?:Warnings|Lint|FBWarnings)?\s*\(",+ JVM,+ ),+ _code("#pragma warning disable", r"^\s*#\s*pragma\s+warning\s+disable\b", CSHARP),+ _code(+ "[SuppressMessage]",+ r"\[\s*(?:assembly\s*:\s*|module\s*:\s*)?(?:[\w.]+\.)?SuppressMessage(?:Attribute)?\s*\(",+ CSHARP,+ ),+ _code(+ "#pragma diagnostic ignored",+ r"^\s*#\s*pragma\s+(?:(?:GCC|clang)\s+diagnostic\s+ignored|warning\s*\(\s*disable)\b",+ C_FAMILY,+ ),+)++#: The marker a test may add on purpose: in a test, ``@ts-expect-error``+#: asserts that a type error exists.+TEST_ALLOWED_SUPPRESSIONS = frozenset({"@ts-expect-error"})+++# -- weakened-tests -----------------------------------------------------------++#: A skip or focus marker in a test file: the test (or every other test) no+#: longer runs. Conditional skips (``skipif``, ``skipIf``, ``XCTSkipIf``, an+#: ``xfail`` with a condition) guard an environment, so they are absent, as is+#: ``.todo``: a new placeholder weakens nothing, and a test turned into one+#: drops the test-case count instead.+SKIP_MARKERS: tuple[Marker, ...] = (+ _code(+ "skip/only",+ r"(?<![\w$.])(?:it|test|specify|describe|suite|context)(?:\.\w+)*"+ r"\.(?:skip|only|fixme)(?![\w$])",+ JS,+ ),+ _code(+ "x/f prefix",+ r"(?<![\w$.])(?:xit|xtest|xdescribe|xcontext|xspecify|fit|fdescribe|fcontext)\s*\(",+ JS,+ ),+ _code(+ "pytest.mark.skip",+ r"(?<![\w.])(?:pytest\.)?mark\.(?:skip\b(?!if)"+ r"|xfail\b(?!\s*\((?!\s*(?:\)|(?:reason|strict|raises|run)\s*=))))",+ PY,+ ),+ _code("pytest.skip", r"(?<![\w.])pytest\.(?:skip|xfail)\s*\(", PY),+ _code(+ "unittest.skip",+ r"^\s*@(?:unittest\.)?(?:skip|expectedFailure)\b(?!\.)"+ r"|(?<![\w.])self\.skipTest\s*\(",+ PY,+ ),+ _code("t.Skip", r"(?<![\w.])[tb]\.Skip(?:f|Now)?\s*\(", GO),+ _code("#[ignore]", r"#\[\s*ignore\b", RUST),+ _code("@Disabled", r"(?<![\w.])@(?:Disabled|Ignore)(?![\w.])", JVM),+ _code(+ "[Ignore]",+ r"[\[,]\s*Ignore\s*[\](,]|\[\s*(?:Fact|Theory)\s*\([^\]]*\bSkip\s*=",+ CSHARP,+ ),+ _code(+ "xit/pending",+ r"^\s*(?:xit|xspecify|xexample|xscenario|xdescribe|xcontext|xfeature"+ r"|fit|fspecify|fexample|fscenario|fdescribe|fcontext|ffeature)\b(?![?!=:])"+ r"|^\s*(?:pending|skip)\b(?!\s*(?:=[^=~]|\.|::|,|\)|\?|!))"+ r"|^\s*(?:it|specify|example|scenario|describe|context|feature)\b.*"+ r"(?<![\w:])(?:skip|pending|focus):(?!:)",+ RUBY,+ ),+ _code("markTestSkipped", r"(?:->|::)markTest(?:Skipped|Incomplete)\s*\(", PHP),+ _code("XCTSkip", r"(?<![\w.])XCTSkip\s*\(|@(?:Test|Suite)\s*\(.*\.disabled\b", SWIFT),+)++#: One test case. Only the counts matter, so a row need not see every style.+TEST_CASES: tuple[Marker, ...] = (+ _code(+ "test case",+ r"(?<![\w$.])(?:it|test|specify|xit|xtest|fit)"+ r"(?:\.(?:skip|only|each|concurrent|sequential|fails|failing|fixme|skipIf|runIf))*"+ r"\s*[(`]",+ JS,+ ),+ _code("test case", r"^\s*(?:async\s+)?def\s+test\w*\s*\(", PY),+ _code("test case", r"^func\s+(?:\([^)]*\)\s*)?(?:Test|Fuzz)\w*\s*\(", GO),+ _code("test case", r"#\[\s*(?:\w+::)*test\s*[\]\(]", RUST),+ _code(+ "test case",+ # Indented: a class-level TestNG ``@Test`` at column 0 is no test case.+ r"^\s+@(?:[\w.]+\.)?(?:Test|ParameterizedTest|RepeatedTest|TestFactory|TestTemplate)"+ r"(?![\w.])",+ JVM,+ ),+ _code("test case", r"[\[,]\s*(?:Fact|Theory|Test|TestMethod)\s*[\](,]", CSHARP),+ _code(+ "test case",+ r"^\s*(?:it|specify|example|scenario|its|xit|fit|xspecify|fspecify)\b"+ r"(?=\s*(?:[\"'({:]|do\b|$))|^\s*def\s+test_\w*",+ RUBY,+ ),+ _code("test case", r"\bfunction\s+test\w*\s*\(", PHP),+ _code("test case", r"\bfunc\s+test\w*\s*\(|(?<![\w.])@Test\b", SWIFT),+)++#: One assertion.+ASSERTIONS: tuple[Marker, ...] = (+ _code(+ "assertion",+ r"(?<![\w$.])(?:expect(?:\.(?:soft|poll))?|assert(?:\.\w+)*)\s*\(|\.should[.(]",+ JS,+ ),+ _code(+ "assertion",+ r"(?<![\w.])assert\b|(?<![\w.])self\.assert\w*\s*\(|(?<![\w.])pytest\.raises\s*\("+ r"|\.assert_\w+\s*\(",+ PY,+ ),+ _code(+ "assertion",+ r"(?<![\w.])(?:assert|require)\.\w+\s*\("+ r"|(?<![\w.])t\.(?:Error|Errorf|Fatal|Fatalf|Fail|FailNow)\s*\(",+ GO,+ ),+ _code("assertion", r"(?<![\w.])(?:debug_)?assert(?:_\w+)?!\s*[(\[]", RUST),+ _code(+ "assertion",+ r"(?<![\w.])assert\w*\s*\(|\bAssert(?:ions)?\.\w+\s*\(|(?<![\w.])verify\s*\("+ r"|\bshould[A-Z]\w*\b",+ JVM,+ ),+ _code("assertion", r"\b\w*Assert\.\w+\s*\(|\.Should\(\)", CSHARP),+ _code(+ "assertion",+ r"(?<![\w.])(?:expect|is_expected)\b|(?<![\w.])(?:assert|refute)\w*\b|\.should\b",+ RUBY,+ ),+ _code("assertion", r"(?:->|::)(?:assert\w+|expectException\w*)\s*\(", PHP),+ _code("assertion", r"\bXCTAssert\w*\s*\(|\bXCTFail\s*\(|#(?:expect|require)\s*\(", SWIFT),+)+++@dataclass(frozen=True, slots=True)+class ThresholdFile:+ """A config file whose numeric keys gate coverage or quality."""++ names: frozenset[str]+ prefixes: tuple[str, ...]+ #: Keys where a lower value is less strict.+ minimums: tuple[str, ...]+ #: Keys where a higher value is less strict.+ maximums: tuple[str, ...] = ()++ def matches(self, name: str) -> bool:+ return name in self.names or name.startswith(self.prefixes)+++THRESHOLD_FILES: tuple[ThresholdFile, ...] = (+ ThresholdFile(+ frozenset(+ {"pyproject.toml", "setup.cfg", "tox.ini", ".coveragerc", "pytest.ini", ".flake8"}+ ),+ (),+ ("fail_under", "--cov-fail-under"),+ ("max-complexity", "max_complexity"),+ ),+ ThresholdFile(+ frozenset(+ {"package.json", ".nycrc", ".nycrc.json", ".nycrc.yml", ".nycrc.yaml", ".c8rc"}+ | {".c8rc.json"}+ ),+ ("vitest.config.", "vitest.workspace.", "vite.config.", "jest.config.", "karma.conf."),+ ("branches", "functions", "lines", "statements"),+ ),+ ThresholdFile(frozenset({"tarpaulin.toml", ".tarpaulin.toml"}), (), ("fail-under",)),+ ThresholdFile(+ frozenset({"codecov.yml", ".codecov.yml", "codecov.yaml", ".codecov.yaml"}),+ (),+ ("target",),+ ("threshold",),+ ),+)+++# -- test-only-branch ---------------------------------------------------------+++@dataclass(frozen=True, slots=True)+class TestEnvCheck:+ """A check that reads whether the code runs under a test.++ *code* must match the text view at a position that is code (the token is+ not quoted); *text*, when set, must match the same line's text view too,+ so a check may name its literal (``'test'``) as well as its token.+ """++ __test__ = False # not a pytest class++ label: str+ languages: frozenset[str]+ code: re.Pattern[str]+ text: re.Pattern[str] | None = None+++def _env(label: str, languages: frozenset[str], code: str, text: str | None = None) -> TestEnvCheck:+ return TestEnvCheck(label, languages, re.compile(code), re.compile(text) if text else None)+++_COMPARES_TEST = r"""[!=]==?\s*['"`]test(?:ing)?['"`]|['"`]test(?:ing)?['"`]\s*[!=]==?"""++TEST_ENV_CHECKS: tuple[TestEnvCheck, ...] = (+ _env("process.env.NODE_ENV", JS, r"\bprocess\.env\.NODE_ENV\b", _COMPARES_TEST),+ _env("process.env.VITEST", JS, r"\bprocess\.env\.(?:VITEST|JEST_WORKER_ID)\b"),+ _env(+ "pytest in sys.modules",+ PY,+ r"\bsys\.(?:modules|argv)\b",+ r"""['"]_?pytest['"]\s+(?:not\s+)?in\s+sys\.(?:modules|argv)"""+ r"""|['"]test['"]\s+(?:not\s+)?in\s+sys\.argv""",+ ),+ _env(+ "os.environ test check",+ PY,+ r"\bos\.(?:environ|getenv)\b",+ r"""['"](?:PYTEST_CURRENT_TEST|TESTING|TEST_MODE|UNIT_TESTING|RUNNING_TESTS)['"]"""+ r"""|[!=]=\s*['"]test(?:ing)?['"]""",+ ),+ _env("testing.Testing()", GO, r"\btesting\.Testing\s*\(\s*\)"),+ _env("flag.Lookup(test.v)", GO, r"\bflag\.Lookup\b", r"""flag\.Lookup\(\s*"test\."""),+ _env("cfg!(test)", RUST, r"\bcfg!\s*\(\s*test\s*\)"),+ _env("Rails.env.test?", RUBY, r"\bRails\.env\.test\?"),+ _env("ENV test check", RUBY, r"\bENV\s*(?:\[|\.fetch\b)", r"""[!=]=\s*['"]test['"]"""),+ _env("runningUnitTests()", PHP, r"->runningUnitTests\s*\("),+ _env(+ "environment('testing')",+ PHP,+ r"\b(?:environment|getenv)\s*\(",+ r"""environment\(\s*['"]test(?:ing)?['"]|[!=]==?\s*['"]test(?:ing)?['"]""",+ ),+ _env(+ "IsEnvironment(Test)",+ CSHARP,+ r"\bIsEnvironment\s*\(",+ r"""IsEnvironment\(\s*"Test(?:ing)?\"""",+ ),+)++#: Languages whose test checks fire only on a branch line. In JS the+#: comparison itself is the signal (``const isTest = ...``);+#: elsewhere a bare read is usually configuration.+BRANCH_FREE_LANGUAGES = JS+BRANCH_KEYWORDS = re.compile(r"\b(?:if|elif|unless|guard|while|when)\b")++#: A skip under one of these, or under a branch, guards an environment.+SKIP_GUARDS = re.compile(+ BRANCH_KEYWORDS.pattern + r"|&&|\|\||\b(?:and|or|except|catch|rescue|else|case|switch)\b"+)++#: The header of a function or test case: the enclosing-block walk of a skip+#: stops there, since a guard above it guards nothing inside.+BLOCK_HEADER = re.compile(+ r"^\s*(?:(?:async\s+)?def|func|fn|function|class)\b"+ r"|(?<![\w.])(?:it|test|specify|describe)\s*\(|^\s*(?:public|private|protected|void)\b"+)++#: A parametrized test: folding cases into one reads as fewer test cases.+PARAMETRIZE = re.compile(+ r"mark\.parametrize\b|\.each\s*[(`]"+ r"|@(?:ParameterizedTest|ValueSource|MethodSource|CsvSource)\b"+ r"|\[\s*(?:Theory|InlineData|TestCase|DataRow)\b|#\[\s*(?:rstest|case)\b|\bt\.Run\s*\("+)++#: A negated check that guards only these calls keeps tests quiet; production+#: takes the same path.+LOG_CALL = re.compile(+ r"^\s*(?:console\.\w+|print|logger\.\w+|log\.\w+|logging\.\w+|warnings\.warn|puts"+ r"|fmt\.Print\w*)\s*\("+)+NEGATED_CHECK = re.compile(r"!==?|\bnot\b|\bunless\b|^\s*if\s*\(?\s*!")++#: A check that only picks an env file is configuration, not a code path.+ENV_FILE_LITERAL = re.compile(r"""['"`]\.env""")+++# -- shared -------------------------------------------------------------------++#: Directories of test fixtures, golden inputs and generated code: a tool or+#: a test wrote what is in them, so their markers are not a choice of the+#: change author.+FIXTURE_OR_GENERATED_DIRS = frozenset(+ {+ "fixture", "fixtures", "__fixtures__", "__snapshots__", "testdata",+ "test_cases", "golden", "goldens", "generated", "__generated__",+ }+)++#: A file name naming a golden or snapshot file (``GOLDEN_PARTIAL.js``).+GOLDEN_NAME = re.compile(r"golden|\.snap$", re.IGNORECASE)++#: Names too common to tie a removed test to removed source code.+NOT_REMOVED_NAMES = frozenset(+ {+ "async", "await", "break", "case", "catch", "class", "console", "const", "continue",+ "default", "delete", "else", "elif", "enum", "except", "export", "exports", "extends",+ "false", "False", "finally", "from", "func", "function", "global", "import", "impl",+ "interface", "lambda", "module", "none", "None", "null", "package", "pass", "private",+ "protected", "public", "raise", "require", "return", "self", "static", "string",+ "struct", "super", "switch", "this", "throw", "throws", "true", "True", "type",+ "typeof", "undefined", "void", "while", "with", "yield",+ }+) # fmt: skip++#: The shortest name that can tie a removed test to removed code.+MIN_REMOVED_NAME_LEN = 4diff --git a/packages/core/src/repowise/core/analysis/diff_risk/models.py b/packages/core/src/repowise/core/analysis/diff_risk/models.pynew file mode 100644index 000000000..231547639--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/models.py@@ -0,0 +1,92 @@+"""Typed vocabulary of the diff-risk rules."""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import asdict, dataclass+from typing import Any, Literal++from .text import FileView, Hit++Rule = Literal["added-suppression", "weakened-tests", "test-only-branch"]+Severity = Literal["off", "warn", "error"]++RULES: tuple[Rule, ...] = ("added-suppression", "weakened-tests", "test-only-branch")++#: ``(path, language) -> is a test file``.+TestClassifier = Callable[[str, "str | None"], bool]+++@dataclass(frozen=True, slots=True)+class FileTexts:+ """Both sides of one changed file. ``None`` means the side has no file."""++ base_path: str | None+ head_path: str | None+ base: str | None+ head: str | None++ @property+ def path(self) -> str:+ return self.head_path or self.base_path or ""+++@dataclass(frozen=True, slots=True)+class DiffRiskFinding:+ """One diff-risk finding. Every one is introduced by the change."""++ #: Line-free, stable across runs and unrelated edits.+ finding_id: str+ rule: Rule+ #: ``comment`` | ``attribute`` | ``config`` | ``skip-marker`` |+ #: ``removed-tests`` | ``assertion-drop`` | ``threshold`` | ``test-env-check``.+ kind: str+ path: str+ #: 1-based head line; ``None`` for a file-level finding.+ line: int | None+ severity: Severity+ message: str+ #: The marker or the value change that supports the finding.+ evidence: str++ def as_dict(self) -> dict[str, Any]:+ return asdict(self)+++@dataclass(slots=True)+class RawFinding:+ """A finding before its severity and id: what a rule reports."""++ rule: Rule+ kind: str+ path: str+ line: int | None+ #: What the finding is about, for its line-free id (a marker, a key).+ label: str+ message: str+ evidence: str+++#: ``(rule, kind, hit)``: one marker occurrence on one side of a file.+Tagged = tuple[Rule, str, Hit]+++@dataclass(frozen=True, slots=True)+class Lens:+ """What one changed file is, and so which line rules read it."""++ language: str | None+ prose: bool+ test: bool+ production: bool+++@dataclass(slots=True)+class TestFile:+ """Both sides of one changed test file, for the counting rules."""++ __test__ = False # not a pytest class++ path: str+ base: FileView | None+ head: FileView | Nonediff --git a/packages/core/src/repowise/core/analysis/diff_risk/paths.py b/packages/core/src/repowise/core/analysis/diff_risk/paths.pynew file mode 100644index 000000000..09ad77fad--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/paths.py@@ -0,0 +1,81 @@+"""Which changed files the diff-risk rules read, and what each one is."""++from __future__ import annotations++from pathlib import PurePosixPath++from ...code_origin import code_origin+from ...references import path_identity+from ..change_health.analyzer import language_of+from . import markers as m+from .models import FileTexts++HEALTH_RULES_PATH = ".repowise/health-rules.json"++#: How much of a file the origin classifier reads.+_HEADER_CHARS = 4096+++def is_prose(path: str) -> bool:+ return path.lower().endswith(m.PROSE_SUFFIXES)+++def threshold_file(path: str) -> m.ThresholdFile | None:+ name = PurePosixPath(path).name+ return next((t for t in m.THRESHOLD_FILES if t.matches(name)), None)+++def is_health_rules(path: str) -> bool:+ return path_identity(path) == HEALTH_RULES_PATH+++def is_relevant(path: str) -> bool:+ """Whether a rule reads *path*. A caller fetching bytes fetches only these."""+ if _in_fixture_or_generated_dir(path):+ return False+ return (+ language_of(path) is not None+ or is_prose(path)+ or threshold_file(path) is not None+ or is_health_rules(path)+ )+++def in_scope(file: FileTexts) -> bool:+ """A relevant file that neither a tool nor a third party wrote."""+ return bool(file.path) and is_relevant(file.path) and not _held(file)+++def _in_fixture_or_generated_dir(path: str) -> bool:+ p = PurePosixPath(path_identity(path))+ return bool(m.GOLDEN_NAME.search(p.name)) or any(+ part in m.FIXTURE_OR_GENERATED_DIRS for part in p.parts[:-1]+ )+++def _held(file: FileTexts) -> bool:+ """Vendored or generated: a tool or a third party wrote the markers."""+ return _origin(file) in ("vendored", "generated")+++def is_production(file: FileTexts) -> bool:+ """Product code: not a tool config or settings module, not tooling or a build file."""+ return not is_tool_config(file.path) and _origin(file) == "production"+++def _origin(file: FileTexts) -> str:+ return code_origin(file.path, (file.head or file.base or "")[:_HEADER_CHARS])+++def is_tool_config(path: str) -> bool:+ """A tool config (``vite.config.ts``, ``.eslintrc.js``) or a settings module.++ A test-environment check is normal there.+ """+ p = PurePosixPath(path)+ name = p.name+ dot_rc = name.startswith(".") and name[1:].split(".", 1)[0].endswith("rc")+ settings = p.stem in {"settings", "config", "conftest"} or any(+ part in {"settings", "config", "configs"} for part in p.parts[:-1]+ )+ return ".config." in name or ".conf." in name or dot_rc or settingsdiff --git a/packages/core/src/repowise/core/analysis/diff_risk/rules/__init__.py b/packages/core/src/repowise/core/analysis/diff_risk/rules/__init__.pynew file mode 100644index 000000000..f0115ad67--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/rules/__init__.py@@ -0,0 +1 @@+"""One module per diff-risk rule; :mod:`..detect` runs them."""diff --git a/packages/core/src/repowise/core/analysis/diff_risk/rules/removed_tests.py b/packages/core/src/repowise/core/analysis/diff_risk/rules/removed_tests.pynew file mode 100644index 000000000..ece72bd9d--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/rules/removed_tests.py@@ -0,0 +1,250 @@+"""``weakened-tests``: removed test cases and assertion drops.++Both report only when the total over every changed test file dropped, so+tests that moved to another changed file do not report. A drop does not+report when the lost test lines name code the change removed (the tests went+with that code), or when the change added a parametrize marker (cases folded+into one). An assertion drop reports only when the file added no assertion+and assertions are at least half of the code lines it lost; otherwise the+test was rewritten. Either drop must also show in the lines the change+removed, each read on its own, so a whole-file mask that drifted on one side+(a quote it misread) never reads as lost tests.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import PurePosixPath++from ...change_health.analyzer import language_of+from .. import markers as m+from ..models import FileTexts, RawFinding, Rule, TestClassifier, TestFile+from ..paths import is_prose+from ..text import FileView, added_line_indexes++RULE: Rule = "weakened-tests"+++@dataclass(frozen=True, slots=True)+class _Counts:+ test: TestFile+ base_cases: int+ head_cases: int+ base_asserts: int+ head_asserts: int++ @classmethod+ def of(cls, test: TestFile) -> _Counts:+ return cls(+ test,+ _count(test.base, m.TEST_CASES),+ _count(test.head, m.TEST_CASES),+ _count(test.base, m.ASSERTIONS),+ _count(test.head, m.ASSERTIONS),+ )+++def removed_tests(+ tests: list[TestFile], files: list[FileTexts], is_test: TestClassifier+) -> list[RawFinding]:+ """``removed-tests`` and ``assertion-drop`` findings over the changed test files."""+ if not tests:+ return []+ removed = RemovedNames.collect(files, is_test)+ rows = [_Counts.of(test) for test in tests]+ cases_dropped = sum(r.head_cases for r in rows) < sum(r.base_cases for r in rows)+ asserts_dropped = sum(r.head_asserts for r in rows) < sum(r.base_asserts for r in rows)+ out: list[RawFinding] = []+ for row in rows:+ if _explained(row.test, removed):+ continue+ if cases_dropped and _cases_dropped(row):+ out.append(_finding(row, "removed-tests", "test cases"))+ elif asserts_dropped and _asserts_dropped(row):+ out.append(_finding(row, "assertion-drop", "assertions"))+ return out+++def _explained(test: TestFile, removed: RemovedNames) -> bool:+ return test.base is None or removed.explain(test.base, test.head) or _parametrized(test)+++def _cases_dropped(row: _Counts) -> bool:+ return row.head_cases < row.base_cases and _lost(row.test, m.TEST_CASES) > 0+++def _asserts_dropped(row: _Counts) -> bool:+ return (+ row.head_cases >= row.base_cases+ and row.head_asserts < row.base_asserts+ and _assertions_led(row.test)+ )+++def _finding(row: _Counts, kind: str, what: str) -> RawFinding:+ if kind == "removed-tests":+ before, after = row.base_cases, row.head_cases+ else:+ before, after = row.base_asserts, row.head_asserts+ evidence = f"{what}: {before} -> {after}"+ message = f"The change removes {what} ({evidence})"+ return RawFinding(RULE, kind, row.test.path, None, kind, message, evidence)+++def _count(view: FileView | None, markers: tuple[m.Marker, ...]) -> int:+ if view is None:+ return 0+ return view.count(k for k in markers if k.applies_to(view.language, is_prose=False))+++def _parametrized(test: TestFile) -> bool:+ """Whether the change added a parametrize marker: cases folded into one."""+ if test.head is None:+ return False+ return any(m.PARAMETRIZE.search(test.head.text_view[i]) for i in _added(test))+++def _lost(test: TestFile, markers: tuple[m.Marker, ...]) -> int:+ """Markers on the test's removed lines minus those on its added lines."""+ return _on_removed_lines(test, markers) - _on_added_lines(test, markers)+++def _applying(view: FileView, markers: tuple[m.Marker, ...]) -> list[m.Marker]:+ return [k for k in markers if k.applies_to(view.language, is_prose=False)]+++def _on_removed_lines(test: TestFile, markers: tuple[m.Marker, ...]) -> int:+ if test.base is None:+ return 0+ return test.base.local_count(_applying(test.base, markers), _removed(test.base, test.head))+++def _on_added_lines(test: TestFile, markers: tuple[m.Marker, ...]) -> int:+ if test.head is None:+ return 0+ return test.head.local_count(_applying(test.head, markers), _added(test))+++def _added(test: TestFile) -> list[int]:+ """0-based head lines the change added to the test."""+ base_lines = test.base.lines if test.base else []+ return added_line_indexes(base_lines, test.head.lines) if test.head else []+++def _removed(base: FileView, head: FileView | None) -> list[int]:+ """0-based base lines the change removed (base lines head does not hold)."""+ return added_line_indexes(head.lines if head else [], base.lines)+++def _assertions_led(test: TestFile) -> bool:+ """Whether the file only lost assertions: it added none, and assertions+ are at least half of the code lines it removed.++ An added assertion means the checks were rewritten (two expectations+ folded into one), which a count cannot tell from a weaker test.+ """+ base = test.base+ if base is None or _on_added_lines(test, m.ASSERTIONS):+ return False+ markers = _applying(base, m.ASSERTIONS)+ code_lines = [i for i in _removed(base, test.head) if base.code_view[i].strip()]+ if not code_lines:+ return False+ asserting = sum(1 for i in code_lines if base.local_count(markers, [i]))+ return asserting * 2 >= len(code_lines)+++@dataclass(frozen=True, slots=True)+class RemovedNames:+ """Names the change took out of the project's non-test source.++ Identifiers a changed source file held in base and no longer holds in+ head; identifiers of a deleted source file that no changed file still+ holds; and the stems and gone directories of deleted files.+ """++ identifiers: frozenset[str]+ segments: frozenset[str]++ @classmethod+ def collect(cls, files: list[FileTexts], is_test: TestClassifier) -> RemovedNames:+ live_dirs = {+ str(parent)+ for f in files+ if f.head_path and f.head is not None+ for parent in PurePosixPath(f.head_path).parents+ }+ segments: set[str] = set()+ for f in files:+ if f.head is None and f.base_path:+ segments |= _gone_segments(f.base_path, live_dirs)+ sources = [(f, lang) for f in files if (lang := _source_language(f, is_test))]+ return cls(frozenset(_removed_identifiers(sources)), frozenset(segments))++ def explain(self, base: FileView, head: FileView | None) -> bool:+ """Whether the lines a test file lost name removed code its head no longer names."""+ removed = _removed(base, head)+ if not removed:+ return False+ head_ids = head.identifiers() if head else set()+ if any(n in self.identifiers and n not in head_ids for n in base.identifiers(removed)):+ return True+ head_text = head.text if head else ""+ tokens = set().union(*(_path_tokens(base.lines[i]) for i in removed))+ return any(s in tokens and s not in head_text for s in self.segments)+++def _source_language(f: FileTexts, is_test: TestClassifier) -> str | None:+ """The language of a changed non-test source file, else ``None``."""+ language = language_of(f.path)+ if language is None or is_prose(f.path) or is_test(f.path, language):+ return None+ return language+++def _removed_identifiers(sources: list[tuple[FileTexts, str]]) -> set[str]:+ """Identifiers that left the changed source files.++ A name of a deleted file that a changed file still holds moved; it did not+ leave. Names the deleted file only imported count too: the ceiling is+ abstaining on a few more removals, never a false alarm.+ """+ identifiers: set[str] = set()+ deleted: set[str] = set()+ head_union: set[str] = set()+ for f, language in sources:+ head_ids = FileView(f.head, f.path, language).identifiers() if f.head else set()+ head_union |= head_ids+ if f.base is None:+ continue+ base_view = FileView(f.base, f.base_path or f.path, language)+ base_ids = {n for n in base_view.identifiers() if _candidate(n)}+ if f.head is None:+ deleted |= base_ids+ else:+ identifiers |= base_ids - head_ids+ return identifiers | (deleted - head_union)+++def _candidate(name: str) -> bool:+ return len(name) >= m.MIN_REMOVED_NAME_LEN and name not in m.NOT_REMOVED_NAMES+++def _gone_segments(path: str, live_dirs: set[str]) -> set[str]:+ """The stem of a deleted file and each directory no changed head file lives in.++ Without a head tree listing a directory that still holds unchanged files+ reads as gone; that only makes the rule abstain more often.+ """+ p = PurePosixPath(path)+ out = {p.stem} if len(p.stem) >= m.MIN_REMOVED_NAME_LEN else set()+ for parent in p.parents:+ if str(parent) not in live_dirs and len(parent.name) >= m.MIN_REMOVED_NAME_LEN:+ out.add(parent.name)+ return out+++def _path_tokens(line: str) -> set[str]:+ for sep in "/.'\"`:\\":+ line = line.replace(sep, " ")+ return set(line.split())diff --git a/packages/core/src/repowise/core/analysis/diff_risk/rules/suppression.py b/packages/core/src/repowise/core/analysis/diff_risk/rules/suppression.pynew file mode 100644index 000000000..a6170e433--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/rules/suppression.py@@ -0,0 +1,81 @@+"""``added-suppression``: a new suppression comment, attribute or config disable."""++from __future__ import annotations++import json+from typing import Any++from .. import markers as m+from ..models import Lens, RawFinding, Rule, Tagged+from ..text import FileView, Hit++RULE: Rule = "added-suppression"+++def hits(view: FileView, lens: Lens, *, raw: bool) -> list[Tagged]:+ """Suppression markers in *view*: comments by their text, attributes by label.++ In a test, ``@ts-expect-error`` asserts that a type error exists, so it is+ not counted.+ """+ language, prose = lens.language, lens.prose+ comment = [k for k in m.COMMENT_SUPPRESSIONS if k.applies_to(language, is_prose=prose)]+ code = [k for k in m.CODE_SUPPRESSIONS if k.applies_to(language, is_prose=prose)]+ comments = view.raw_hits(comment, comment=True) if raw else view.comment_hits(comment)+ codes = view.raw_hits(code, comment=False) if raw else view.code_hits(code)+ tagged: list[Tagged] = [(RULE, "comment", h) for h in comments]+ tagged += [(RULE, "attribute", h) for h in codes]+ if lens.test:+ tagged = [t for t in tagged if t[2].label not in m.TEST_ALLOWED_SUPPRESSIONS]+ return tagged+++def message(hit: Hit) -> str:+ return (+ f"The change adds a `{hit.label}` suppression, "+ "which hides findings instead of fixing them"+ )+++def disabled_biomarkers(path: str, base: str | None, head: str | None) -> list[RawFinding]:+ """Biomarkers ``.repowise/health-rules.json`` newly turns off."""+ before = _disabled_pairs(base)+ after = _disabled_pairs(head)+ if before is None or after is None:+ return []+ return [+ RawFinding(+ RULE,+ "config",+ path,+ None,+ f"{scope}:{name}",+ f"The change disables the `{name}` health check for `{scope}`",+ f"{scope}: {name}",+ )+ for scope, name in sorted(after - before)+ # Narrowing a global disable to a path is stricter, not looser.+ if ("*", name) not in before+ ]+++def _disabled_pairs(text: str | None) -> set[tuple[str, str]] | None:+ """``{(path glob or "*", biomarker)}``; ``None`` when the file is unreadable."""+ if text is None:+ return set()+ try:+ data = json.loads(text)+ except ValueError:+ return None+ if not isinstance(data, dict):+ return None+ pairs = _names("*", data)+ for rule in data.get("rules") or []:+ if isinstance(rule, dict) and isinstance(rule.get("path"), str):+ pairs |= _names(rule["path"], rule)+ return pairs+++def _names(scope: str, entry: dict[str, Any]) -> set[tuple[str, str]]:+ names = entry.get("disabled_biomarkers") or []+ return {(scope, name) for name in names if isinstance(name, str)}diff --git a/packages/core/src/repowise/core/analysis/diff_risk/rules/test_only_branch.py b/packages/core/src/repowise/core/analysis/diff_risk/rules/test_only_branch.pynew file mode 100644index 000000000..72b384c6c--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/rules/test_only_branch.py@@ -0,0 +1,111 @@+"""``test-only-branch``: a new test-environment check in production code."""++from __future__ import annotations++from .. import markers as m+from ..models import Rule+from ..text import FileView, Hit++RULE: Rule = "test-only-branch"++#: The most lines a quiet-logs check reads after a test check.+_MAX_GUARDED_LINES = 12++#: Lines a guarded block may hold besides its log calls.+_BLOCK_PUNCTUATION = frozenset({"", "{", ") {", ")", "):", "then"})+++def hits(view: FileView, language: str | None, *, raw: bool) -> list[Hit]:+ """Test-environment checks in *view*; on raw lines for the base side."""+ checks = [c for c in m.TEST_ENV_CHECKS if language in c.languages]+ if not checks:+ return []+ found = _raw_checks(view, checks, language) if raw else _masked_checks(view, checks, language)+ return [Hit(index + 1, check.label, check.label) for index, check in found]+++def message(hit: Hit) -> str:+ return (+ f"The change adds a `{hit.label}` check to production code, "+ "so tests and production can take different paths"+ )+++def _raw_checks(+ view: FileView, checks: list[m.TestEnvCheck], language: str | None+) -> list[tuple[int, m.TestEnvCheck]]:+ found = ((i, _check(checks, line, line, language)) for i, line in enumerate(view.lines))+ return [(i, check) for i, check in found if check is not None]+++def _masked_checks(+ view: FileView, checks: list[m.TestEnvCheck], language: str | None+) -> list[tuple[int, m.TestEnvCheck]]:+ out: list[tuple[int, m.TestEnvCheck]] = []+ for index, line in enumerate(view.text_view):+ check = _check(checks, line, view.code_view[index], language)+ if check is not None and not _exempt(view, index) and _local_code(view, index, check):+ out.append((index, check))+ return out+++def _check(+ checks: list[m.TestEnvCheck], line: str, code: str, language: str | None+) -> m.TestEnvCheck | None:+ """The first check *line* makes: its token in code, its literal if any, and a+ branch keyword outside the languages where the comparison alone counts."""+ branch_free = language in m.BRANCH_FREE_LANGUAGES or m.BRANCH_KEYWORDS.search(code)+ if not branch_free:+ return None+ for check in checks:+ in_code = any(code[x.start()] == line[x.start()] for x in check.code.finditer(line))+ if in_code and (check.text is None or check.text.search(line)):+ return check+ return None+++def _local_code(view: FileView, index: int, check: m.TestEnvCheck) -> bool:+ """The check's token is code on its own line too, not only in the whole-file mask."""+ text, code = view.local(index)+ return any(code[x.start()] == text[x.start()] for x in check.code.finditer(text))+++def _exempt(view: FileView, index: int) -> bool:+ """An env-file pick, or a negated check that guards only log calls."""+ if m.ENV_FILE_LITERAL.search(view.text_view[index]):+ return True+ code = view.code_view[index]+ if not m.NEGATED_CHECK.search(code):+ return False+ return bool(m.LOG_CALL.search(code)) or _guards_only_logs(view.code_view, index)+++def _guards_only_logs(code: list[str], index: int) -> bool:+ """Whether the block under line *index* holds only log calls and their arguments."""+ indent = _indent(code[index])+ end = min(index + 1 + _MAX_GUARDED_LINES, len(code))+ body = [line for line in code[index + 1 : end] if line.strip() not in _BLOCK_PUNCTUATION]+ if not body or not m.LOG_CALL.match(body[0].strip()):+ return False+ for line in body[1:]:+ if _closes(line, indent):+ return True+ if not _logs(line.strip()):+ return False+ return False+++def _closes(line: str, indent: int) -> bool:+ """Whether *line* ends the block opened at *indent*."""+ stripped = line.strip()+ return stripped.startswith("}") or stripped == "end" or _indent(line) <= indent+++def _logs(stripped: str) -> bool:+ """A log call, or a continuation of a log call's arguments."""+ continues = stripped.startswith((")", ",")) or stripped.endswith(",")+ return bool(m.LOG_CALL.match(stripped)) or continues+++def _indent(line: str) -> int:+ return len(line) - len(line.lstrip())diff --git a/packages/core/src/repowise/core/analysis/diff_risk/rules/weakened_tests.py b/packages/core/src/repowise/core/analysis/diff_risk/rules/weakened_tests.pynew file mode 100644index 000000000..38deb3e85--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/rules/weakened_tests.py@@ -0,0 +1,96 @@+"""``weakened-tests``: new skip or focus markers and loosened thresholds.++Removed test cases and assertion drops live in :mod:`.removed_tests`.+"""++from __future__ import annotations++from collections.abc import Iterable+from itertools import chain++from .. import markers as m+from ..models import RawFinding, Rule+from ..text import FileView, Hit, numeric_values++RULE: Rule = "weakened-tests"+++def skip_hits(view: FileView, language: str | None, *, raw: bool) -> list[Hit]:+ """Skip and focus markers, minus the guarded ones.++ A skip on a branch line or right under one (``if not HAS_GO:+ pytest.skip(...)``, ``skip "x" unless windows?``, an ``except`` handler)+ guards an environment rather than turning a test off, so it does not count.+ """+ markers = [k for k in m.SKIP_MARKERS if k.applies_to(language, is_prose=False)]+ if raw:+ return view.raw_hits(markers, comment=False)+ return [h for h in view.code_hits(markers) if not _guarded(view.code_view, h.line - 1)]+++def skip_message(line: str) -> str:+ return f"The change adds a skip or focus marker, so tests stop running: {line.strip()[:80]}"+++def _guarded(code: list[str], index: int) -> bool:+ """Whether a guard sits on the skip's line, the code line right above it,+ or a line that encloses it (less indented) below the enclosing function+ or test header."""+ if m.SKIP_GUARDS.search(code[index]):+ return True+ above = (i for i in range(index - 1, -1, -1) if code[i].strip())+ first = next(above, None)+ if first is None:+ return False+ if m.SKIP_GUARDS.search(code[first]):+ return True+ return _enclosing_guard(code, chain([first], above), _indent(code[index]))+++def _enclosing_guard(code: list[str], above: Iterable[int], indent: int) -> bool:+ """Walk outwards through the lines that enclose a skip, up to its header."""+ for i in above:+ line = code[i]+ if _indent(line) >= indent:+ continue+ if m.SKIP_GUARDS.search(line):+ return True+ indent = _indent(line)+ if m.BLOCK_HEADER.search(line) or indent == 0:+ return False+ return False+++def _indent(line: str) -> int:+ return len(line) - len(line.lstrip())+++def weakened_thresholds(path: str, spec: m.ThresholdFile, base: str, head: str) -> list[RawFinding]:+ """Threshold values the change made less strict.++ Occurrences of a key pair in file order, and only when both sides hold+ the same number of them: an added, removed or reordered entry cannot be+ paired by position, so the rule abstains.+ """+ keyed = [(key, True) for key in spec.minimums] + [(key, False) for key in spec.maximums]+ return [+ _threshold(path, key, change)+ for key, lower_is_weaker in keyed+ for change in _paired(base, head, key)+ if (change[1] < change[0] if lower_is_weaker else change[1] > change[0])+ ]+++def _paired(base: str, head: str, key: str) -> list[tuple[float, float, int]]:+ """``(before, after, head line)`` per occurrence of *key*; none when counts differ."""+ olds, news = numeric_values(base, key), numeric_values(head, key)+ if len(olds) != len(news):+ return []+ return [(b, a, line) for (b, _), (a, line) in zip(olds, news, strict=True)]+++def _threshold(path: str, key: str, change: tuple[float, float, int]) -> RawFinding:+ before, after, line = change+ evidence = f"{key}: {before:g} -> {after:g}"+ message = f"The change makes a threshold less strict ({evidence})"+ return RawFinding(RULE, "threshold", path, line, key, message, evidence)diff --git a/packages/core/src/repowise/core/analysis/diff_risk/source.py b/packages/core/src/repowise/core/analysis/diff_risk/source.pynew file mode 100644index 000000000..f8ef24d05--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/source.py@@ -0,0 +1,63 @@+"""The one IO adapter: both sides of a change, read from a revision source."""++from __future__ import annotations++from collections.abc import Mapping++from ..change_health.sources import RevisionPair, RevisionSource+from .detect import detect_diff_risk+from .models import DiffRiskFinding, FileTexts+from .paths import is_relevant++#: Larger files are bundles or data, not hand-written code.+MAX_FILE_BYTES = 1_000_000+++def read_change_texts(source: RevisionSource, pair: RevisionPair) -> list[FileTexts]:+ """Both sides of every relevant changed file, in two bulk reads.++ A rename reads its base text at the old path. A side that should exist+ and cannot be read drops the file: a failed read must never pass for a+ new file, where every marker would read as added.+ """+ changes = [c for c in pair.changes if is_relevant(c.path)]+ head_paths = [c.head_path for c in changes if c.head_path]+ base_paths = [c.base_path for c in changes if c.base_path]+ head = (+ source.read_working_tree(head_paths)+ if pair.working_tree+ else source.read(pair.head_sha, head_paths)+ )+ base = source.read(pair.base_sha, base_paths)+ texts = (_texts(c.base_path, c.head_path, base, head) for c in changes)+ return [t for t in texts if t is not None]+++def _texts(+ base_path: str | None, head_path: str | None, base: dict[str, bytes], head: dict[str, bytes]+) -> FileTexts | None:+ """Both sides of one file, or ``None`` when a side that exists did not read as text."""+ sides: list[str | None] = []+ for path, blobs in ((base_path, base), (head_path, head)):+ text = None if path is None else _decode(blobs.get(path))+ if path is not None and text is None:+ return None+ sides.append(text)+ return FileTexts(base_path, head_path, sides[0], sides[1])+++def _decode(raw: bytes | None) -> str | None:+ """Text of *raw*; ``None`` for a missing, binary or oversized blob."""+ if raw is None or len(raw) > MAX_FILE_BYTES or b"\x00" in raw:+ return None+ return raw.decode("utf-8", errors="replace")+++def diff_risk_for_change(+ source: RevisionSource,+ pair: RevisionPair,+ *,+ severities: Mapping[str, str] | None = None,+) -> list[DiffRiskFinding]:+ """:func:`.detect.detect_diff_risk` over a resolved revision pair."""+ return detect_diff_risk(read_change_texts(source, pair), severities=severities)diff --git a/packages/core/src/repowise/core/analysis/diff_risk/text.py b/packages/core/src/repowise/core/analysis/diff_risk/text.pynew file mode 100644index 000000000..16472871e--- /dev/null+++ b/packages/core/src/repowise/core/analysis/diff_risk/text.py@@ -0,0 +1,288 @@+"""Line views and line arithmetic over one file's text. No parse, no IO.++A line counts as added when its trimmed text occurs more often in head than+in base, so a moved line is not added. Markers are counted the same way+(see :func:`.detect._net`), so editing a line that already carried a+suppression does not read as a new one.+"""++from __future__ import annotations++import re+from collections import Counter+from collections.abc import Iterable+from dataclasses import dataclass+from functools import cached_property++from ..security.masking import mask_comments_and_strings, mask_dialect, source_lines+from .markers import HASH_COMMENT_LANGUAGES, Marker++#: Code characters in the comment view: never part of a marker match.+_HIDDEN = "\x00"++#: A Rust lifetime (``'a``, ``'static``), which the masker would read as a+#: string opener. A char literal (``'a'``) is left alone.+_RUST_LIFETIME = re.compile(r"'(?=[A-Za-z_]\w*(?![\w']))")++#: Line comment openers of TOML, INI, YAML and JS config files.+_CONFIG_COMMENT = ("#", ";", "//", "/*", "*")++_FENCE = re.compile(r"^\s*(?:```|~~~)")+_CODE_SPAN = re.compile(r"(`+).+?\1")+_IDENTIFIER = re.compile(r"[A-Za-z_$][\w$]*")+++@dataclass(frozen=True, slots=True)+class Hit:+ """One marker occurrence on a 1-based line."""++ line: int+ label: str+ #: What a hit is counted by. The label, or for a suppression the comment+ #: text from the marker on, so a widened suppression is a new one.+ key: str+++class FileView:+ """The text of one side of one file, with per-line views."""++ def __init__(self, text: str, path: str, language: str | None, *, prose: bool = False) -> None:+ self.text = text+ self.path = path+ self.language = language+ self.prose = prose+ self.lines = source_lines(text)+ self._local: dict[int, tuple[str, str]] = {}++ @cached_property+ def text_view(self) -> list[str]:+ """Comments blanked, strings kept."""+ if self.prose:+ return [""] * len(self.lines)+ return source_lines(self._mask(strings=False))++ @cached_property+ def code_view(self) -> list[str]:+ """Comments and strings blanked."""+ if self.prose:+ return [""] * len(self.lines)+ return source_lines(self._mask(strings=True))++ @cached_property+ def comment_view(self) -> list[str]:+ """Only comment text; every code or string character is hidden."""+ if self.prose:+ return _prose_comments(self.lines)+ # A marker quoted in a code span is documented, not applied.+ return [+ _hide_code_spans(+ "".join(+ c if (c != m or c.isspace()) else _HIDDEN+ for c, m in zip(raw, masked, strict=False)+ )+ )+ for raw, masked in zip(self.lines, self.text_view, strict=False)+ ]++ def _mask(self, *, strings: bool) -> str:+ source = self.text+ if self.language == "rust":+ source = _RUST_LIFETIME.sub(" ", source)+ return mask_comments_and_strings(+ source,+ strings=strings,+ hash_comments=self.language in HASH_COMMENT_LANGUAGES,+ **mask_dialect(self.path),+ )++ def local(self, index: int) -> tuple[str, str]:+ """``(text view, code view)`` of line *index* masked on its own.++ The whole-file mask carries string state across lines, so one quote+ it misreads (an apostrophe in a JS regex literal) shifts every later+ line. A hit must also hold on its own line, which no earlier line can+ throw off; the cost is a miss inside a multi-line string, never a+ false alarm.+ """+ if index not in self._local:+ alone = FileView(self.lines[index], self.path, self.language)+ self._local[index] = (alone.text_view[0], alone.code_view[0])+ return self._local[index]++ def is_code(self, index: int, at: int) -> bool:+ """Whether column *at* of line *index* is code in both masks."""+ raw = self.lines[index][at]+ if self.text_view[index][at] != raw or self.code_view[index][at] != raw:+ return False+ text, code = self.local(index)+ return text[at] == raw and code[at] == raw++ def code_hits(self, markers: Iterable[Marker]) -> list[Hit]:+ """Matches on the text view that start in code, not in a string."""+ hits: list[Hit] = []+ for marker in markers:+ for index, line in enumerate(self.text_view):+ if any(self.is_code(index, x.start()) for x in marker.pattern.finditer(line)):+ hits.append(Hit(index + 1, marker.label, marker.label))+ return hits++ def comment_hits(self, markers: Iterable[Marker]) -> list[Hit]:+ """Suppression markers that open a comment, keyed by their text."""+ hits: list[Hit] = []+ for index, line in enumerate(self.comment_view):+ if not line.strip(_HIDDEN + " \t"):+ continue+ for marker in markers:+ match = marker.pattern.search(line)+ if match is not None and not self._in_local_string(index, match.start()):+ hits.append(Hit(index + 1, marker.label, _marker_text(line, match.start())))+ return hits++ def raw_hits(self, markers: Iterable[Marker], *, comment: bool) -> list[Hit]:+ """Matches on the raw lines, with no mask at all.++ The base side of a change counts this way: a base marker the mask+ missed would make an unchanged head marker read as added, so base+ errs toward seeing more, which only makes a rule abstain.+ """+ found = (+ (index, line, marker, marker.pattern.search(line))+ for index, line in enumerate(self.lines)+ for marker in markers+ )+ return [+ Hit(index + 1, marker.label, _marker_text(line, x.start()) if comment else marker.label)+ for index, line, marker, x in found+ if x is not None+ ]++ def _in_local_string(self, index: int, at: int) -> bool:+ if self.prose:+ return False+ text, code = self.local(index)+ return text[at] != code[at]++ def count(self, markers: Iterable[Marker]) -> int:+ """Occurrences of *markers* in code, every match on a line counted."""+ markers = list(markers)+ return sum(+ 1+ for index, line in enumerate(self.text_view)+ for marker in markers+ for x in marker.pattern.finditer(line)+ if self.is_code(index, x.start())+ )++ def local_count(self, markers: Iterable[Marker], lines: Iterable[int]) -> int:+ """Occurrences of *markers* on *lines*, each line masked on its own.++ For lines the change added or removed, where the whole-file mask of+ one side may have drifted while the other's did not.+ """+ markers = list(markers)+ total = 0+ for index in lines:+ text, code = self.local(index)+ total += sum(+ 1+ for marker in markers+ for x in marker.pattern.finditer(text)+ if code[x.start()] == text[x.start()]+ )+ return total++ def identifiers(self, lines: Iterable[int] | None = None) -> set[str]:+ """Identifier tokens in code (0-based *lines*, or every line)."""+ view = self.code_view+ indexes = range(len(view)) if lines is None else lines+ return {token for i in indexes for token in _IDENTIFIER.findall(view[i])}+++def _marker_text(line: str, start: int) -> str:+ """The comment text from *start*, whitespace collapsed, closers dropped."""+ text = line[start:].split(_HIDDEN, 1)[0]+ for closer in ("*/", "-->"):+ text = text.split(closer, 1)[0]+ return " ".join(text.split())+++def _prose_comments(lines: list[str]) -> list[str]:+ """The HTML comments of Markdown lines; everything else is hidden.++ A marker quoted in a fence or a backtick span is documented, not applied,+ and one in plain prose (a heading, a bullet) applies to nothing.+ """+ out: list[str] = []+ fenced = in_comment = False+ for raw in lines:+ fence = not in_comment and _FENCE.match(raw)+ fenced ^= bool(fence)+ if fence or fenced:+ out.append("")+ continue+ line, in_comment = _html_comments(_hide_code_spans(raw), in_comment)+ out.append(line)+ return out+++def _html_comments(line: str, in_comment: bool) -> tuple[str, bool]:+ """*line* with everything outside ``<!-- -->`` hidden, and whether a+ comment is still open at its end."""+ kept: list[str] = []+ at = 0+ while at < len(line):+ if in_comment:+ close = line.find("-->", at)+ stop = len(line) if close == -1 else close + 3+ kept.append(line[at:stop])+ in_comment = close == -1+ else:+ opened = line.find("<!--", at)+ stop = len(line) if opened == -1 else opened+ kept.append(_HIDDEN * (stop - at))+ in_comment = opened != -1+ at = stop+ return "".join(kept), in_comment+++def _hide_code_spans(line: str) -> str:+ return _CODE_SPAN.sub(lambda m: _HIDDEN * len(m.group()), line) if "`" in line else line+++def added_line_indexes(base: list[str], head: list[str]) -> list[int]:+ """0-based indexes of *head* lines that *base* does not hold.++ Lines compare by trimmed text as a multiset; when head has more copies+ than base, the last copies count as added. Blank lines never count.+ """+ kept = Counter(line.strip() for line in base)+ head_counts = Counter(line.strip() for line in head)+ keep = {text: min(n, kept.get(text, 0)) for text, n in head_counts.items()}+ added: list[int] = []+ for index, line in enumerate(head):+ text = line.strip()+ if not text:+ continue+ if keep.get(text, 0) > 0:+ keep[text] -= 1+ continue+ added.append(index)+ return added+++def numeric_values(text: str, key: str) -> list[tuple[float, int]]:+ """Every number assigned to *key* (``key: 90``, ``key = 0.8``, ``"key": 90``).++ The key must stand alone, so ``lines`` does not match ``maxLines``, and+ a commented-out line does not count. Returns ``(value, 1-based line)`` in+ file order.+ """+ pattern = re.compile(+ r"(?<![\w-])" + re.escape(key) + r"""(?![\w-])["']?\s*[:=]\s*["']?(-?\d+(?:\.\d+)?)"""+ )+ return [+ (float(m.group(1)), number)+ for number, line in enumerate(source_lines(text), 1)+ if not line.lstrip().startswith(_CONFIG_COMMENT)+ for m in pattern.finditer(line)+ ]diff --git a/packages/core/src/repowise/core/analysis/health_gate.py b/packages/core/src/repowise/core/analysis/health_gate.pyindex 271975a8d..b19723b1b 100644--- a/packages/core/src/repowise/core/analysis/health_gate.py+++ b/packages/core/src/repowise/core/analysis/health_gate.py@@ -25,6 +25,7 @@ from repowise.core.ci.markdown import ROW_LIMIT, cell, details, more_line, plurafrom ..test_paths import is_test_related_pathfrom .change_health.identity import severity_rankfrom .change_health.models import INCIDENTAL_BASES, ChangeFinding, ChangeHealthDelta+from .diff_risk import DiffRiskFindingfrom .health.biomarker_labels import biomarker_labelfrom .health.scoring import is_code_shape@@ -251,6 +252,24 @@ def _message(f: ChangeFinding) -> str:return f"{what} ({f.change_kind}, {f.severity})"+def diff_risk_findings(findings: Iterable[DiffRiskFinding]) -> list[GateFinding]:+ """Diff-risk findings (added suppressions, weakened tests, test-only branches)+ as gate findings, for :func:`evaluate`'s *extra*. ``off`` rules never get here."""+ return [+ GateFinding(+ source="diff-risk",+ rule=f.rule,+ level=ERROR if f.severity == "error" else WARNING,+ path=f.path,+ line=f.line,+ message=f.message,+ fingerprint=f.finding_id,+ extra={"kind": f.kind, "evidence": f.evidence},+ )+ for f in findings+ ]++def _unread_files(skipped: Mapping[str, str]) -> list[GateFinding]:"""A warning per changed code file left unread on either side (unparsable, too large)."""return [diff --git a/tests/unit/change_health/test_diff_risk.py b/tests/unit/change_health/test_diff_risk.pynew file mode 100644index 000000000..cdd245eae--- /dev/null+++ b/tests/unit/change_health/test_diff_risk.py@@ -0,0 +1,638 @@+"""Diff-risk rules: added suppressions, weakened tests, test-only branches."""++from __future__ import annotations++import pytest++from repowise.core.analysis.change_health import GitRevisionSource+from repowise.core.analysis.diff_risk import (+ DiffRiskFinding,+ FileTexts,+ detect_diff_risk,+ diff_risk_for_change,+ is_relevant,+)+from repowise.core.analysis.diff_risk.text import added_line_indexes+++def change(path: str, base: str | None, head: str | None, *, old: str | None = None) -> FileTexts:+ return FileTexts(+ base_path=(old or path) if base is not None else None,+ head_path=path if head is not None else None,+ base=base,+ head=head,+ )+++def found(*files: FileTexts, **kw) -> list[tuple[str, str, str, int | None]]:+ return [(f.rule, f.kind, f.path, f.line) for f in detect_diff_risk(files, **kw)]+++def evidence(*files: FileTexts) -> list[str]:+ return [f.evidence for f in detect_diff_risk(files)]+++# -- added lines --------------------------------------------------------------+++def test_moved_lines_are_not_added():+ assert added_line_indexes(["a", "b", "c"], ["c", "a", "b", "d", ""]) == [3]+++# -- added-suppression --------------------------------------------------------+++ ("path", "line", "label"),+ [+ ("src/a.py", "x = f() # noqa: E501", "noqa"),+ ("src/a.py", "x = f() # type: ignore[attr-defined]", "type: ignore"),+ ("src/a.py", "x = f() # pyright: ignore", "pyright: ignore"),+ ("src/a.py", "x = f() # pylint: disable=broad-except", "pylint: disable"),+ ("src/a.py", "x = f() # nosec B101", "nosec"),+ ("src/a.py", "def f(): # pragma: no cover", "pragma: no cover"),+ ("src/a.ts", "// eslint-disable-next-line no-console", "eslint-disable"),+ ("src/a.ts", "/* istanbul ignore next */", "istanbul ignore"),+ ("src/a.tsx", "{/* @ts-ignore */}", "@ts-ignore"),+ ("src/a.js", "// biome-ignore lint: reason", "biome-ignore"),+ ("src/a.go", "x := f() //nolint:errcheck", "nolint"),+ ("src/a.go", "x := f() // #nosec G104", "nosec"),+ ("src/a.rs", "#[allow(dead_code)]", "#[allow]"),+ ("src/a.rs", "#![allow(clippy::all)]", "#[allow]"),+ ("src/A.java", '@SuppressWarnings("unchecked")', "@SuppressWarnings"),+ ("src/A.kt", '@Suppress("UNUSED")', "@SuppressWarnings"),+ ("src/A.cs", "#pragma warning disable CS0168", "#pragma warning disable"),+ ("src/A.cs", '[SuppressMessage("Style", "IDE0060")]', "[SuppressMessage]"),+ ("src/a.rb", "x = f # rubocop:disable Style/Foo", "rubocop:disable"),+ ("src/a.php", "$x = f(); // @phpstan-ignore-line", "@phpstan-ignore"),+ ("src/a.php", "/** @psalm-suppress InvalidArgument */", "@psalm-suppress"),+ ("src/a.php", "// phpcs:ignore Generic.Foo", "phpcs:ignore"),+ ("src/a.swift", "// swiftlint:disable:next force_cast", "swiftlint:disable"),+ ("src/a.py", "TOKEN = 'abc' # repowise-security-ignore", "repowise-security-ignore"),+ ("docs/guide.md", "<!-- repowise-drift-ignore -->", "repowise-drift-ignore"),+ ],+)+def test_added_suppression_is_found_in_each_language(path, line, label):+ base = "keep = 1\n"+ head = f"keep = 1\n{line}\n"+ findings = detect_diff_risk([change(path, base, head)])+ assert [(f.rule, f.line) for f in findings] == [("added-suppression", 2)]+ assert label in findings[0].message+++ ("path", "head"),+ [+ # Quoted in a string literal.+ ("src/a.py", "s = '# noqa'\nt = \"# type: ignore\"\n"),+ ("src/a.py", 'DOC = """\nx = 1 # noqa\n"""\n'),+ ("src/a.ts", "const s = '// eslint-disable';\nconst u = `/* @ts-ignore */`;\n"),+ ("src/a.rs", 'fn f(x: &\'static str) { let s = "#[allow(x)]"; }\n'),+ ("src/A.java", 'String s = "@SuppressWarnings(x)";\n'),+ # Named in prose inside a comment, not applied.+ ("src/a.py", "# never add noqa here, fix the code\n"),+ ("src/a.ts", "// we removed the old eslint-disable comments\n"),+ # A JS private field is code, not a hash comment.+ ("src/a.ts", "this.#noqa = 1;\n"),+ # A documented marker in a fence or code span.+ ("docs/guide.md", "Use `<!-- repowise-drift-ignore -->` to skip.\n```\n<!-- repowise-drift-ignore -->\n```\n"),+ ],+)+def test_markers_outside_comments_are_not_suppressions(path, head):+ assert found(change(path, "", head)) == []+++def test_editing_a_line_that_already_had_the_suppression_is_not_added():+ base = "x = f(a) # noqa: E501\n"+ head = "x = f(a, b) # noqa: E501\n"+ assert found(change("src/a.py", base, head)) == []+++def test_moving_a_suppression_is_not_added():+ base = "a = 1 # noqa\nb = 2\n"+ head = "b = 2\na = 1 # noqa\n"+ assert found(change("src/a.py", base, head)) == []+++def test_widening_a_suppression_is_added():+ base = "x = f() # noqa: E501\n"+ head = "x = f() # noqa: E501, F401\n"+ assert evidence(change("src/a.py", base, head)) == ["# noqa: E501, F401"]+++def test_ts_expect_error_in_a_test_is_an_assertion_not_a_suppression():+ head = "// @ts-expect-error\nconst x: number = 'a';\n"+ assert found(change("src/a.test.ts", "", head)) == []+ assert found(change("src/a.ts", "", head)) == [("added-suppression", "comment", "src/a.ts", 1)]+++def test_fixture_vendored_and_generated_files_are_exempt():+ head = "x = 1 # noqa\n"+ assert found(change("tests/fixtures/sample/a.py", "", head)) == []+ assert found(change("vendor/lib/a.py", "", head)) == []+ assert found(change("src/a_pb2.py", "", "# Generated by the protocol buffer compiler. DO NOT EDIT!\n" + head)) == []+++def test_a_newly_disabled_biomarker_is_an_added_suppression():+ base = '{"disabled_biomarkers": ["dry_violation"]}'+ head = (+ '{"disabled_biomarkers": ["dry_violation", "complex_method"],'+ ' "rules": [{"path": "src/**", "disabled_biomarkers": ["large_file"]}]}'+ )+ findings = detect_diff_risk([change(".repowise/health-rules.json", base, head)])+ assert [(f.rule, f.kind, f.evidence) for f in findings] == [+ ("added-suppression", "config", "*: complex_method"),+ ("added-suppression", "config", "src/**: large_file"),+ ]+++def test_a_blanket_suppression_cannot_hide_an_added_suppression():+ # Inline markers never silence a diff-risk finding, so a file-wide+ # disable comment is itself reported, along with what it covers.+ head = "/* eslint-disable */\n// @ts-nocheck\nconst a = 1; // eslint-disable-line\n"+ assert [f[3] for f in found(change("src/a.ts", "", head))] == [1, 2, 3]+++# -- weakened-tests: skip and focus markers ------------------------------------+++ ("path", "base", "head"),+ [+ ("tests/test_a.py", "def test_a():\n pass\n", "@pytest.mark.skip(reason='x')\ndef test_a():\n pass\n"),+ ("tests/test_a.py", "def test_a():\n pass\n", "@pytest.mark.xfail\ndef test_a():\n pass\n"),+ ("tests/test_a.py", "def test_a():\n pass\n", "def test_a():\n pytest.skip('flaky')\n"),+ ("tests/test_a.py", "class T:\n def test_a(self):\n pass\n", "class T:\n @unittest.skip('x')\n def test_a(self):\n pass\n"),+ ("src/a.test.ts", "it('a', () => {});\n", "it.skip('a', () => {});\n"),+ ("src/a.test.ts", "describe('s', () => {});\n", "describe.only('s', () => {});\n"),+ ("src/a.spec.js", "it('a', f);\n", "xit('a', f);\n"),+ ("src/a.spec.js", "it('a', f);\n", "fit('a', f);\n"),+ ("pkg/a_test.go", "func TestA(t *testing.T) {\n}\n", "func TestA(t *testing.T) {\n\tt.Skip(\"flaky\")\n}\n"),+ ("tests/a.rs", "#[test]\nfn a() {}\n", "#[test]\n#[ignore]\nfn a() {}\n"),+ ("src/test/java/ATest.java", " @Test\n void a() {}\n", " @Test\n @Disabled\n void a() {}\n"),+ ("tests/ATests.cs", "[Fact]\npublic void A() {}\n", "[Fact(Skip = \"flaky\")]\npublic void A() {}\n"),+ ("spec/a_spec.rb", "it 'works' do\nend\n", "xit 'works' do\nend\n"),+ ("spec/a_spec.rb", "it 'works' do\nend\n", "it 'works' do\n skip 'later'\nend\n"),+ ("tests/ATest.php", "function testA() {}\n", "function testA() {\n $this->markTestSkipped('x');\n}\n"),+ ("Tests/ATests.swift", "func testA() {}\n", "func testA() throws {\n throw XCTSkip(\"x\")\n}\n"),+ ],+)+def test_added_skip_marker_is_found_in_each_language(path, base, head):+ kinds = [(f.rule, f.kind) for f in detect_diff_risk([change(path, base, head)])]+ assert ("weakened-tests", "skip-marker") in kinds+++ ("path", "head"),+ [+ # Production code may say skip.+ ("src/a.ts", "it.skip('a', f);\n"),+ ("src/a.py", "@pytest.mark.skip\ndef helper():\n pass\n"),+ # Commented out, quoted, or a different member.+ ("src/a.test.ts", "// it.only('x')\nconst s = 'it.skip(';\nconst profit = obj.fit(1);\n"),+ ("tests/test_a.py", "# @pytest.mark.skip\nreason = 'pytest.skip(x)'\n"),+ # A placeholder is not a weakened test.+ ("src/a.test.ts", "it.todo('write later');\n"),+ ("spec/a_spec.rb", "skip_count = 1\nskip = true\n"),+ ],+)+def test_no_skip_marker_outside_test_code(path, head):+ assert [f for f in detect_diff_risk([change(path, "", head)]) if f.kind == "skip-marker"] == []+++def test_existing_skip_marker_is_not_added():+ base = "it.skip('a', () => {});\n"+ head = "it.skip('a renamed', () => {});\n"+ assert found(change("src/a.test.ts", base, head)) == []+++# -- weakened-tests: removed tests and assertions -----------------------------++PY_TESTS = "def test_a():\n assert f() == 1\n\n\ndef test_b():\n assert keep_me() == 2\n"+++def test_removed_tests_are_found():+ head = "def test_a():\n assert f() == 1\n"+ assert found(change("tests/test_x.py", PY_TESTS, head)) == [+ ("weakened-tests", "removed-tests", "tests/test_x.py", None)+ ]+++def test_tests_that_moved_to_another_test_file_are_not_removed():+ head = "def test_a():\n assert f() == 1\n"+ moved = "def test_b():\n assert keep_me() == 2\n"+ assert found(change("tests/test_x.py", PY_TESTS, head), change("tests/test_y.py", None, moved)) == []+++def test_tests_removed_with_the_code_they_named_are_not_reported():+ source_base = "def f():\n return 1\n\n\ndef keep_me():\n return 2\n"+ source_head = "def f():\n return 1\n"+ head = "def test_a():\n assert f() == 1\n"+ files = (change("src/x.py", source_base, source_head), change("tests/test_x.py", PY_TESTS, head))+ assert found(*files) == []+++def test_a_deleted_test_file_with_its_deleted_module_is_not_reported():+ files = (+ change("src/legacy_parser.py", "def parse_legacy():\n return 1\n", None),+ change("tests/test_legacy_parser.py", "from src.legacy_parser import parse_legacy\n\n\ndef test_p():\n assert parse_legacy() == 1\n", None),+ )+ assert found(*files) == []+++def test_assertion_drop_is_found_when_assertions_lead_the_removal():+ base = "it('a', () => {\n expect(a).toBe(1);\n expect(b).toBe(2);\n expect(c).toBe(3);\n});\n"+ head = "it('a', () => {\n expect(a).toBe(1);\n});\n"+ findings = detect_diff_risk([change("src/a.test.ts", base, head)])+ assert [(f.kind, f.evidence) for f in findings] == [("assertion-drop", "assertions: 3 -> 1")]+++def test_a_rewritten_test_is_not_an_assertion_drop():+ base = (+ "it('a', () => {\n const x = setup();\n const y = build(x);\n const z = run(y);\n"+ " const w = more(z);\n expect(x).toBe(1);\n expect(y).toBe(2);\n});\n"+ )+ head = "it('a', () => {\n const w = helper();\n expect(w).toBe(1);\n});\n"+ assert found(change("src/a.test.ts", base, head)) == []+++ ("path", "base", "head"),+ [+ ("pkg/a_test.go", "func TestA(t *testing.T) {}\nfunc TestB(t *testing.T) {}\n", "func TestA(t *testing.T) {}\n"),+ ("tests/a.rs", "#[test]\nfn a() {}\n#[tokio::test]\nasync fn b() {}\n", "#[test]\nfn a() {}\n"),+ ("src/test/java/ATest.java", " @Test\n void a() {}\n @Test\n void b() {}\n", " @Test\n void a() {}\n"),+ ("spec/a_spec.rb", "it 'a' do\nend\nit 'b' do\nend\n", "it 'a' do\nend\n"),+ ("tests/ATests.cs", "[Fact]\nvoid A() {}\n[Fact]\nvoid B() {}\n", "[Fact]\nvoid A() {}\n"),+ ],+)+def test_removed_tests_in_each_language(path, base, head):+ assert [f.kind for f in detect_diff_risk([change(path, base, head)])] == ["removed-tests"]+++def test_a_class_level_testng_annotation_is_not_a_test_case():+ base = '@Test(dataProviderClass = P.class)\npublic final class ATest {\n @Test(dataProvider = "c")\n public void a() {}\n}\n'+ head = "final class ATest {\n @ParameterizedTest\n void a() {}\n}\n"+ assert found(change("src/test/java/ATest.java", base, head)) == []+++def test_a_test_turned_into_a_todo_is_a_removed_test():+ base = "it('a', f);\nit('b', g);\n"+ head = "it('a', f);\nit.todo('b');\n"+ assert [f.kind for f in detect_diff_risk([change("src/a.test.ts", base, head)])] == ["removed-tests"]+++# -- weakened-tests: thresholds ------------------------------------------------+++ ("path", "base", "head", "expected"),+ [+ ("pyproject.toml", "[tool.coverage.report]\nfail_under = 90\n", "[tool.coverage.report]\nfail_under = 85.5\n", "fail_under: 90 -> 85.5"),+ ("setup.cfg", "[tool:pytest]\naddopts = --cov-fail-under=80\n", "[tool:pytest]\naddopts = --cov-fail-under=60\n", "--cov-fail-under: 80 -> 60"),+ ("vitest.config.ts", "thresholds: {\n lines: 90,\n branches: 80,\n},\n", "thresholds: {\n lines: 70,\n branches: 85,\n},\n", "lines: 90 -> 70"),+ ("package.json", '{"jest": {"coverageThreshold": {"global": {"statements": 95}}}}', '{"jest": {"coverageThreshold": {"global": {"statements": 50}}}}', "statements: 95 -> 50"),+ (".flake8", "[flake8]\nmax-complexity = 10\n", "[flake8]\nmax-complexity = 18\n", "max-complexity: 10 -> 18"),+ ("codecov.yml", "coverage:\n status:\n project:\n default:\n target: 80%\n", "coverage:\n status:\n project:\n default:\n target: 60%\n", "target: 80 -> 60"),+ ],+)+def test_loosened_threshold_is_found(path, base, head, expected):+ assert evidence(change(path, base, head)) == [expected]+++def test_tightened_or_unrelated_threshold_is_not_found():+ assert found(change("pyproject.toml", "fail_under = 80\nmaxLines = 5\n", "fail_under = 90\nmaxLines = 1\n")) == []+ assert found(change("src/lines.ts", "const lines = 90;\n", "const lines = 10;\n")) == []+++# -- test-only-branch ---------------------------------------------------------+++ ("path", "line"),+ [+ ("src/a.ts", "if (process.env.NODE_ENV === 'test') return;"),+ ("src/a.ts", "const w = process.env.JEST_WORKER_ID;"),+ ("src/a.py", "if 'pytest' in sys.modules:"),+ ("src/a.py", "if os.environ.get('TESTING'):"),+ ("src/a.py", "if os.getenv('APP_ENV') == 'test':"),+ ("pkg/a.go", "if testing.Testing() {"),+ ("src/a.rs", "if cfg!(test) {"),+ ("app/models/a.rb", "return if Rails.env.test?"),+ ("app/Services/A.php", "if (app()->runningUnitTests()) {"),+ ("src/A.cs", 'if (env.IsEnvironment("Testing")) {'),+ ],+)+def test_added_test_env_check_is_found(path, line):+ assert found(change(path, "", f"{line}\n")) == [("test-only-branch", "test-env-check", path, 1)]+++ ("path", "head"),+ [+ # Test code, tool configs and settings modules check on purpose.+ ("tests/test_a.py", "if 'pytest' in sys.modules:\n pass\n"),+ ("vite.config.ts", "if (process.env.NODE_ENV === 'test') x();\n"),+ ("myapp/settings.py", "if 'test' in sys.argv:\n DEBUG = False\n"),+ # Inside a string or a comment.+ ("src/a.ts", "const s = \"process.env.VITEST\";\n// if (process.env.NODE_ENV === 'test')\n"),+ # A comparison against another environment.+ ("src/a.ts", "if (process.env.NODE_ENV === 'production') x();\n"),+ # Picks an env file.+ ("src/a.ts", "config({ path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env' });\n"),+ # Keeps tests quiet; production takes the same path.+ ("src/a.ts", "if (process.env.NODE_ENV !== 'test') {\n console.error(message);\n}\n"),+ ("src/a.py", "if 'pytest' not in sys.modules:\n logger.warning('x')\nrun()\n"),+ # A read with no branch outside JS is configuration.+ ("src/a.py", "TESTING = os.environ.get('TESTING')\n"),+ # The Rust test module.+ ("src/a.rs", "#[cfg(test)]\nmod tests {}\n"),+ ],+)+def test_no_test_only_branch(path, head):+ assert found(change(path, "", head)) == []+++def test_a_negated_check_guarding_real_work_is_found():+ head = "if (process.env.NODE_ENV !== 'test') {\n sendMetrics();\n}\n"+ assert found(change("src/a.ts", "", head)) == [("test-only-branch", "test-env-check", "src/a.ts", 1)]+++# -- shape, severity, identity ------------------------------------------------+++def test_severity_is_warn_by_default_and_configurable():+ head = "x = 1 # noqa\n"+ (default,) = detect_diff_risk([change("src/a.py", "", head)])+ assert default.severity == "warn"+ (error,) = detect_diff_risk([change("src/a.py", "", head)], severities={"added-suppression": "error"})+ assert error.severity == "error"+ assert detect_diff_risk([change("src/a.py", "", head)], severities={"added-suppression": "off"}) == []+++def test_finding_id_is_line_free_and_serializable():+ head = "x = 1 # noqa\n"+ (first,) = detect_diff_risk([change("src/a.py", "", head)])+ (shifted,) = detect_diff_risk([change("src/a.py", "", "\n\nimport os\n" + head)])+ assert first.finding_id == shifted.finding_id+ assert first.finding_id.startswith("drf_")+ assert first.line != shifted.line+ assert set(first.as_dict()) == set(DiffRiskFinding.__dataclass_fields__)+++def test_custom_test_classifier():+ head = "it.skip('a', f);\n"+ assert detect_diff_risk([change("checks/a.ts", "", head)]) == []+ findings = detect_diff_risk([change("checks/a.ts", "", head)], is_test=lambda p, _lang: p.startswith("checks/"))+ assert [f.kind for f in findings] == ["skip-marker"]+++def test_relevance():+ for path in ("src/a.py", "docs/a.md", "pyproject.toml", "package.json", ".repowise/health-rules.json"):+ assert is_relevant(path), path+ for path in ("assets/logo.png", "tests/fixtures/a.py", "yarn.lock", "t/GOLDEN_PARTIAL.js"):+ assert not is_relevant(path), path+++# -- git adapter --------------------------------------------------------------+++def test_git_adapter_reads_a_rename_at_its_old_path(make_repo):+ repo = make_repo()+ body = "".join(f"def f{i}():\n return {i}\n\n\n" for i in range(12))+ base = repo.commit("base", {"src/old.py": body + "x = 1 # noqa\n"})+ repo.move("src/old.py", "src/new.py")+ repo.write("src/new.py", body + "x = 1 # noqa\ny = 2 # type: ignore\n")+ head = repo.commit("move")+ source = GitRevisionSource(str(repo.path))+ findings = diff_risk_for_change(source, source.resolve(f"{base}..{head}"))+ assert [(f.path, f.evidence) for f in findings] == [("src/new.py", "# type: ignore")]+++def test_git_adapter_reads_the_working_tree(make_repo):+ repo = make_repo()+ repo.commit("base", {"src/a.ts": "const a = 1;\n"})+ repo.write("src/a.ts", "// @ts-ignore\nconst a = 1;\n")+ source = GitRevisionSource(str(repo.path))+ findings = diff_risk_for_change(source, source.resolve(None))+ assert [(f.rule, f.line) for f in findings] == [("added-suppression", 1)]+++# -- change-wide netting and guards -------------------------------------------+++def test_a_suppression_that_moved_to_another_file_is_not_added():+ # A module split carries its suppressions along.+ base = "import a\nctx.x = 1 # type: ignore[attr-defined]\nctx.y = 2 # type: ignore[attr-defined]\n"+ files = (+ change("src/pkg.py", base, "import a\n"),+ change("src/pkg_x.py", None, "ctx.x = 1 # type: ignore[attr-defined]\n"),+ change("src/pkg_y.py", None, "ctx.y = 2 # type: ignore[attr-defined]\n"),+ )+ assert found(*files) == []+++def test_a_suppression_out_of_a_deleted_file_is_not_added():+ files = (+ change("src/old.py", "x = 1 # noqa: F401\n", None),+ change("src/new.py", None, "x = 1 # noqa: F401\n"),+ )+ assert found(*files) == []+++def test_only_the_net_extra_suppression_is_reported():+ files = (+ change("src/a.py", "a = 1 # noqa\n", "a = 1\n"),+ change("src/b.py", None, "b = 1 # noqa\nc = 2 # noqa\n"),+ )+ assert found(*files) == [("added-suppression", "comment", "src/b.py", 1)]+++ ("path", "head"),+ [+ ("tests/test_a.py", "@pytest.mark.skipif(sys.platform == 'win32', reason='x')\ndef test_a():\n pass\n"),+ ("tests/test_a.py", "@pytest.mark.xfail(sys.platform == 'win32', reason='x')\ndef test_a():\n pass\n"),+ ("tests/test_a.py", "def test_a():\n if not HAS_GO:\n pytest.skip('go missing')\n"),+ ("tests/test_a.py", "@unittest.skipIf(PY2, 'x')\ndef test_a(self):\n pass\n"),+ ("src/a.test.ts", "it.skipIf(process.platform === 'win32')('a', f);\n"),+ ("pkg/a_test.go", "func TestA(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip()\n\t}\n}\n"),+ ("spec/a_spec.rb", "it 'a' do\n skip 'later' unless windows?\nend\n"),+ ("tests/test_a.py", "def test_a():\n try:\n import x\n except ImportError:\n pytest.skip('x missing')\n"),+ ("tests/test_a.py", "@skip.if_pypy\ndef test_a():\n pass\n"),+ ],+)+def test_conditional_skips_guard_an_environment(path, head):+ assert [f for f in detect_diff_risk([change(path, "", head)]) if f.kind == "skip-marker"] == []+++def test_unconditional_xfail_is_a_skip_marker():+ head = "@pytest.mark.xfail(reason='flaky')\ndef test_a():\n pass\n"+ assert [f.kind for f in detect_diff_risk([change("tests/test_a.py", "", head)])] == ["skip-marker"]+++def test_a_marker_quoted_in_a_comment_code_span_is_documented():+ head = "# Never add ``# noqa`` here; fix the import instead.\nx = 1\n"+ assert found(change("src/a.py", "", head)) == []+++def test_a_quote_the_whole_file_mask_misreads_does_not_read_as_lost_tests():+ # The apostrophe in the regex literal opens a "string" for the rest of+ # the whole-file mask; the lines the change removed hold no test case.+ base = "it('a', f);\nit('b', g);\nit('c', h);\n"+ head = "it('new', () => expect(() => x()).toThrow(/NG0: 'bad/));\n" + base+ assert found(change("src/a.spec.ts", base, head)) == []+++def test_folding_two_expectations_into_one_is_not_an_assertion_drop():+ base = (+ "function testA() {\n $this->expectException(E::class);\n"+ " $this->expectExceptionMessage('m');\n run();\n}\n"+ )+ head = "function testA() {\n $this->expectExceptionObject(new E('m'));\n run();\n}\n"+ assert found(change("tests/ATest.php", base, head)) == []+++# -- review regressions -------------------------------------------------------+++ "head",+ [+ "# repowise-security-ignore\n",+ "* gitleaks:allow suppresses a secret\n",+ "text -- repowise-drift-ignore here\n",+ ],+)+def test_prose_outside_an_html_comment_is_not_a_suppression(head):+ assert found(change("docs/a.md", "", head)) == []+++def test_a_multi_line_html_comment_in_prose_is_read():+ head = "Intro\n<!--\nrepowise-drift-ignore-file\n-->\n"+ assert found(change("docs/a.md", "", head)) == []+ head = "Intro\n<!-- note\n-- repowise-drift-ignore -->\n"+ assert [f[3] for f in found(change("docs/a.md", "", head))] == [3]+++ ("path", "head"),+ [+ ("src/a.py", "x = 1 # we never write -- noqa here\n"),+ ("src/a.py", "x = 1 # a * noqa\n"),+ ("src/a.ts", "// see http://eslint-disable.example\n"),+ ],+)+def test_a_marker_in_the_middle_of_a_comment_is_prose(path, head):+ assert found(change(path, "", head)) == []+++def test_a_nested_hash_comment_marker_still_counts():+ assert [f[3] for f in found(change("src/a.py", "", "x = 1 # why # noqa: E501\n"))] == [1]+++ ("path", "head"),+ [+ ("tests/test_a.py", "def test_a():\n if not x:\n log('a')\n pytest.skip('no')\n"),+ ("pkg/a_test.go", "func TestA(t *testing.T) {\n\tif !ok {\n\t\tt.Log(1)\n\t\tt.Skip()\n\t}\n}\n"),+ ],+)+def test_a_skip_inside_a_guard_block_is_conditional(path, head):+ assert [f for f in detect_diff_risk([change(path, "", head)]) if f.kind == "skip-marker"] == []+++def test_an_unguarded_skip_below_a_finished_guard_still_counts():+ head = "def test_a():\n if x:\n y()\n\n\ndef test_b():\n pytest.skip('off')\n"+ kinds = [f.kind for f in detect_diff_risk([change("tests/test_a.py", "", head)])]+ assert kinds == ["skip-marker"]+++def test_an_added_or_reordered_threshold_is_not_paired_by_position():+ base = '{"coverageThreshold": {"global": {"lines": 90}}}'+ head = '{"coverageThreshold": {"./src": {"lines": 50}, "global": {"lines": 90}}}'+ assert found(change("package.json", base, head)) == []+ base = "[tool.coverage.report]\nfail_under = 90\n"+ head = "[tool.coverage.report]\n# was fail_under = 70\nfail_under = 90\n"+ assert found(change("pyproject.toml", base, head)) == []+++def test_narrowing_a_global_disable_to_a_path_is_not_a_suppression():+ base = '{"disabled_biomarkers": ["x"]}'+ head = '{"rules": [{"path": "src/a.py", "disabled_biomarkers": ["x"]}]}'+ assert found(change(".repowise/health-rules.json", base, head)) == []+++def test_tests_folded_into_a_parametrized_test_are_not_removed():+ base = "def test_one():\n assert f(1)\n\n\ndef test_two():\n assert f(2)\n"+ head = "@pytest.mark.parametrize('x', [1, 2])\ndef test_f(x):\n assert f(x)\n"+ assert found(change("tests/test_a.py", base, head)) == []+++def test_a_plain_default_read_is_not_a_test_only_branch():+ assert found(change("src/app.py", "", "testing = os.environ.get('TESTING') or ''\n")) == []+++def test_a_base_marker_the_mask_missed_does_not_make_an_edited_line_added():+ # The apostrophe in the base regex literal derails the base mask; the+ # head edits a line that already carried the same suppression.+ base = "const r = /it's/;\nfoo(); // eslint-disable-line no-console\n"+ head = "const r = /it's/;\nfoo(1); // eslint-disable-line no-console\n"+ assert found(change("src/a.ts", base, head)) == []+++def test_an_unchanged_block_comment_suppression_on_an_edited_line_is_not_added():+ base = "/* istanbul ignore next */ foo();\n"+ head = "/* istanbul ignore next */ bar();\n"+ assert found(change("src/a.ts", base, head)) == []+++def test_detection_touches_no_filesystem_or_git(monkeypatch):+ import builtins+ import subprocess++ def refuse(*_a, **_k):+ raise AssertionError("detect_diff_risk must be pure")++ monkeypatch.setattr(builtins, "open", refuse)+ monkeypatch.setattr(subprocess, "run", refuse)+ monkeypatch.setattr(subprocess, "Popen", refuse)+ files = (+ change("src/a.py", "", "x = 1 # noqa\n"),+ change("tests/test_a.py", "def test_a():\n pass\n", "@pytest.mark.skip\ndef test_a():\n pass\n"),+ change("src/b.py", "", "if 'pytest' in sys.modules:\n pass\n"),+ )+ assert len(detect_diff_risk(files)) == 3+++class _Source:+ """A revision source whose reads fail or return binary bytes."""++ def __init__(self, base: dict[str, bytes], head: dict[str, bytes]) -> None:+ self.base, self.head = base, head++ def read(self, sha: str, paths: list[str]) -> dict[str, bytes]:+ side = self.base if sha == "b" else self.head+ return {p: side[p] for p in paths if p in side}++ def read_working_tree(self, paths: list[str]) -> dict[str, bytes]:+ return {}+++def test_a_failed_or_binary_read_drops_the_file():+ from repowise.core.analysis.change_health import FileChange, RevisionPair+ from repowise.core.analysis.diff_risk import read_change_texts++ pair = RevisionPair(+ "b", "h", "b", "h", False,+ [+ FileChange(head_path="src/a.py", base_path="src/a.py", status="modified"),+ FileChange(head_path="src/b.py", base_path="src/b.py", status="modified"),+ FileChange(head_path="src/c.py", base_path=None, status="added"),+ ],+ ) # fmt: skip+ source = _Source(+ {"src/b.py": b"x = 1\n"},+ {"src/a.py": b"x = 1 # noqa\n", "src/b.py": b"\x00binary", "src/c.py": b"y = 2 # noqa\n"},+ )+ assert [f.path for f in read_change_texts(source, pair)] == ["src/c.py"]diff --git a/tests/unit/cli/test_health_check_cmd.py b/tests/unit/cli/test_health_check_cmd.pyindex 32d5390b9..c717312a6 100644--- a/tests/unit/cli/test_health_check_cmd.py+++ b/tests/unit/cli/test_health_check_cmd.py@@ -163,3 +163,53 @@ def test_fail_at_moves_the_severity_floor(repo):repo.commit("tame", {"app.py": SIMPLE + "\n\n" + python_complex("tangle", 6)})assert check(repo).exit_code == 0assert check(repo, "--fail-at", "medium").exit_code == 1+++def test_an_added_suppression_warns_and_can_fail(repo):+ repo.commit("silence", {"app.py": SIMPLE + "import os # noqa: F401\n"})+ result = check(repo, "--format", "json")+ assert result.exit_code == 0, result.output+ doc = json.loads(result.stdout)+ assert doc["gate"]["verdict"] == "warn"+ (row,) = [f for f in doc["findings"] if f["source"] == "diff-risk"]+ assert (row["rule"], row["level"], row["line_number"]) == ("added-suppression", "warning", 3)+ assert row["fingerprint"].startswith("drf_")++ result = check(repo, "--format", "json", "--diff-risk", "added-suppression=error")+ assert result.exit_code == 1, result.output+ result = check(repo, "--format", "json", "--diff-risk", "off")+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout)["gate"]["verdict"] == "pass"+++def test_a_loosened_threshold_in_a_config_only_change_warns(repo):+ repo.commit("base cfg", {"pyproject.toml": "[tool.coverage.report]\nfail_under = 90\n"})+ git(repo.path, "branch", "-f", "main")+ repo.commit("loosen", {"pyproject.toml": "[tool.coverage.report]\nfail_under = 60\n"})+ result = check(repo, "--format", "json")+ assert result.exit_code == 0, result.output+ rules = [f["rule"] for f in json.loads(result.stdout)["findings"]]+ assert rules == ["weakened-tests"]+++def test_a_bad_diff_risk_level_is_a_usage_error(repo):+ result = check(repo, "--diff-risk", "added-suppression=loud")+ assert result.exit_code == 2+ assert "--diff-risk" in result.stderr+++def test_the_change_is_resolved_once(repo, monkeypatch):+ from repowise.core.analysis.change_health.sources import GitRevisionSource++ calls = []+ resolve = GitRevisionSource.resolve++ def counted(self, revspec):+ calls.append(revspec)+ return resolve(self, revspec)++ monkeypatch.setattr(GitRevisionSource, "resolve", counted)+ repo.commit("silence", {"app.py": SIMPLE + "import os # noqa: F401\n"})+ result = check(repo, "--format", "json")+ assert result.exit_code == 0, result.output+ assert calls == ["main...HEAD"]