Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): count assertions with a per-language vocabulary (#2371)

Raghav Chamadiya660ed03fd946
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 29b8df867..a0641577c 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -378,6 +378,28 @@ or it stays silent, and an `n/a` records a metric the language cannot carry
rather than one nobody got to. Kotlin's Extract Method is **blocked on the
grammar**, not unscheduled.
+**The assertion count** is the denominator of every test-quality ratio, counted
+in two tiers (`analysis/health/asserts/lexicon.py`). The narrow tier is the
+`assert` / `expect` prefix match that `large_assertion_block` and
+`duplicated_assertion_block` are calibrated on, and it never changes. The broad
+tier adds a per-language row plus anything a repository declares in the
+`assertions:` block, and feeds the advisory count alone, so a vocabulary edit
+cannot move a score. Broad-tier names are matched exactly, never as prefixes:
+over three corpora the `check` / `validate` / `approve` / `fail` prefix families
+matched ~600 production functions under test and not one assertion.
+
+Counted assertions, narrow tier then both, when the tiers were introduced:
+
+| Corpus | Test files | Narrow | Both |
+|---|---|---|---|
+| Go, stdlib `t.Errorf` idiom | 502 | 87 | **3,454** |
+| Go, testify idiom | 476 | 1,586 | **3,656** |
+| TypeScript, should.js present | 521 | 9,956 | **11,165** |
+| TypeScript, no should.js | 574 | 15,595 | 15,595 |
+
+Go was effectively invisible. Assertion *runs* were byte-identical in every
+corpus, which is what makes the broad tier safe.
+
**Mock saturation** measures a test's mock setup against its assertions, so it
needs both a mock vocabulary and a trustworthy assertion count. The vocabulary
is one data row per language in
@@ -393,9 +415,9 @@ fail differently, and for the same underlying reason — the assertion count is
denominator of every ratio, so a language whose assertions cannot be counted
honestly cannot carry the marker at all:
-- **Go** — its `assert_call_kinds` is best-effort for testify only, so idiomatic
- `t.Error` / `t.Fatal` tests are invisible to the shared assert/expect prefix
- match. Go needs its own assertion vocabulary first.
+- **Go** — the assertion half is fixed (table above). What still blocks the
+ marker is the other half: no row in `mocks/lexicon.py` and no hand-labelled
+ precision figure.
- **Java** — Mockito states a test's real checks as `verify(...)`, which is
deliberately not an assertion here (counting it would hide the very tests this
marker looks for). An over-mocked Java test therefore arrives with one vacuous
@@ -404,7 +426,9 @@ honestly cannot carry the marker at all:
irreducible fixture. Java needs a verification vocabulary of its own first.
Measured at 20% precision over 30 hand-labelled findings, flat across every
threshold tried — but the mechanism above, not that number, is why it is
- blocked.
+ blocked, and why Java has no assertion row either: Mockito verification is
+ 1,080 lines over 299 test files, 16 of which hold no `assert*` at all, and
+ counting them here would blind the marker where it is meant to fire.
Svelte and Vue stay `later` rather than following TypeScript: an SFC is walked as
a TypeScript buffer, but a single-file component is essentially never a test
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 8257d8bd2..8d54ee9cc 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -14,7 +14,8 @@ The `.repowise/` directory, provider setup, API keys, and what's customizable.
[The `hooks:` block](#the-hooks-block) ·
[The `mcp:` block](#the-mcp-block) ·
[The `decisions:` block](#the-decisions-block) ·
-[The `refactoring:` block](#the-refactoring-block)
+[The `refactoring:` block](#the-refactoring-block) ·
+[The `assertions:` block](#the-assertions-block)
**Code health rules**
[The `health-rules.json` file](#the-health-rulesjson-file)
@@ -126,6 +127,9 @@ mcp: # see "The mcp: block" below
refactoring: # see "The refactoring: block" below
enabled: true
+
+assertions: # see "The assertions: block" below
+ extra_names: []
```
You can edit this file directly. Changes take effect on the next `init`,
@@ -559,6 +563,35 @@ refactoring:
same one markers use).
- Full reference: [REFACTORING.md](../layers/REFACTORING.md).
+### The `assertions:` block
+
+Names your own assertion helpers, for the test-quality markers that divide by a
+test's assertion count.
+
+```yaml
+assertions:
+ extra_names: [ensureInvariant, mustMatch] # exact callee names, not prefixes
+```
+
+Repowise recognises the xUnit and BDD families out of the box (`assert*`,
+`expect*`) plus a per-language vocabulary for the idioms those miss, such as
+Go's `t.Fatalf` and testify's `require`. A house helper that follows neither
+convention is invisible to it, and a test built entirely of those helpers reads
+as having no assertions at all. This block is the escape hatch, the same one
+SonarQube, Qodana and ESLint's `expect-expect` rule each provide.
+
+- **Names are exact and case-insensitive, never prefixes.** `ensureInvariant`
+ matches `ensureInvariant(...)` and not `ensureConnectionPool(...)`. Prefix
+ matching was measured against three real test corpora and matched production
+ functions under test far more often than assertions.
+- A name matches whether it is the call itself or the receiver of one, so both
+ `ensureInvariant(x)` and `ensureInvariant(x).isTrue()` count.
+- **Nothing here can change a health score.** These names reach only the
+ advisory assertion total; the calibrated `large_assertion_block` and
+ `duplicated_assertion_block` markers read a separate count that takes no
+ configuration. Adding a wrong name costs you signal, never a wrong score.
+- Changing the list re-walks the affected files on the next `init` / `update`.
+
---
## The `health-rules.json` file
diff --git a/packages/core/src/repowise/core/analysis/health/asserts/__init__.py b/packages/core/src/repowise/core/analysis/health/asserts/__init__.py
new file mode 100644
index 000000000..ca240f3bc
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/asserts/__init__.py
@@ -0,0 +1 @@
+"""Per-language assertion vocabulary for the assertion pass. See ``lexicon.py``."""
diff --git a/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py b/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py
new file mode 100644
index 000000000..395efc506
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/asserts/lexicon.py
@@ -0,0 +1,144 @@
+"""Per-language assertion vocabulary, as data, in two tiers.
+
+The assertion pass (``complexity/assertions.py``) counts two things from one
+walk, and they are deliberately not the same count:
+
+* the **narrow** tier — a callee name starting ``assert`` or ``expect``, plus
+ the language's own ``assert`` statement. It is what every shipped release has
+ counted and it feeds ``assertion_blocks``, which the calibrated
+ ``large_assertion_block`` / ``duplicated_assertion_block`` read. It takes
+ nothing from this file and nothing from user config.
+* the **broad** tier — narrow, plus the rows below and any name the repository
+ configures. It feeds ``assertion_count``, whose only reader is the advisory
+ ``mock_saturated_test``.
+
+That split is the reason a row here can never move a score, and it is the only
+reason this file is safe to edit freely.
+
+Names are matched **exactly**, never as prefixes. SonarQube keeps a wide list
+and a narrow one for the same reason we keep two, but its wide list matches
+name prefixes; measured across three test corpora, the ambiguous English verbs
+in that shape (``check``, ``validate``, ``approve``, ``fail``) matched
+production functions under test and no assertions at all. Measurements and
+reasoning in LANGUAGE_SUPPORT.md#code-health-coverage.
+
+Both directions of error are understood. Over-counting shrinks a saturation
+ratio and can only suppress a finding; under-counting inflates it. A missing
+row is the dangerous side and a slightly over-inclusive one is cheap.
+
+**Adding a language** is one row plus a key in :data:`ASSERT_DIALECTS` — but
+only when its assertions are a named call, and only when its ``LanguageNodeMap``
+already opts into ``assert_call_kinds``. Two things a row will not do: it cannot
+express a prefix family, so an ``assert_*``-style family must be enumerated; and
+it cannot see an assertion that is not a call, so an infix DSL (ScalaTest's
+``x shouldBe y``) needs a grammar change in ``complexity/`` first. A language
+absent from the table keeps the narrow tier alone, which is exactly today's
+behaviour.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+#: Callee-name prefixes of the narrow tier. Matched case-insensitively against
+#: every identifier in a call's callee chain. Frozen: the calibrated markers
+#: count with these and nothing else.
+NARROW_PREFIXES: tuple[str, ...] = ("assert", "expect")
+
+
+@dataclass(frozen=True)
+class AssertVocabulary:
+ """One run's configured assertion names, and the cache key they imply.
+
+ Built once per analysis and passed down to the walk, so nothing about a
+ run's vocabulary lives on the analyzer between runs. An empty vocabulary
+ keys the walk cache exactly as it was keyed before this existed.
+ """
+
+ names: frozenset[str] = frozenset()
+ key: str = ""
+
+ @classmethod
+ def from_analyzer_config(cls, cfg: dict) -> AssertVocabulary:
+ """Read ``assert_extra_names``, already coerced by ``HealthConfig``."""
+ names = frozenset(cfg.get("assert_extra_names") or ())
+ return cls(names=names, key=",".join(sorted(names)))
+
+
+@dataclass(frozen=True)
+class AssertDialect:
+ """One language's broad-tier assertion vocabulary. Data only."""
+
+ #: Exact lowercase names that make a call an assertion, matched against the
+ #: called name *or* any receiver root. Both, because a verification reads
+ #: either way round: ``verify(mock)`` is the callee, and in
+ #: ``verify(mock).save()`` it is the receiver of ``save``.
+ assert_names: frozenset[str] = frozenset()
+
+ #: Receiver root -> the methods ON it that assert, for a root too generic to
+ #: take whole. Go's ``t`` is the test handle: ``t.Fatalf`` asserts, ``t.Run``
+ #: and ``t.Log`` do not.
+ receiver_methods: dict[str, frozenset[str]] = field(default_factory=dict)
+
+
+# ``testing.TB``'s failure reporters, keyed by the conventional receiver names.
+# Matched by receiver name and not by type, which the walker cannot resolve; in
+# a Go test file a ``t``/``b``/``tb`` receiver is the test handle. ``Skip`` /
+# ``Log`` / ``Run`` / ``Helper`` are deliberately absent.
+_GO_TB_FAILURES = frozenset({"error", "errorf", "fatal", "fatalf", "fail", "failnow"})
+
+_GO = AssertDialect(
+ # testify's two halves are one API, and the narrow tier already takes
+ # ``assert.Equal`` on its receiver name while nothing took ``require``.
+ # Taken whole rather than by method list: the cost is a domain package of
+ # the same name counted in the harmless direction, the benefit is never
+ # missing a testify method.
+ assert_names=frozenset({"require"}),
+ receiver_methods={r: _GO_TB_FAILURES for r in ("t", "b", "tb")},
+)
+
+
+# Java has no row, and the omission is a result rather than a gap: its only real
+# gap is Mockito verification, and a verification must not enter the count
+# ``mock_saturated_test`` divides by, since a test built of mocks and verifies
+# is the thing that marker measures. See LANGUAGE_SUPPORT.md#code-health-coverage.
+
+
+_JS_TS = AssertDialect(
+ # should.js / chai's BDD chain, as the receiver root of the matcher call:
+ # ``result.should.equal(x)``. The property form (``x.should.be.true``) is
+ # not a call and stays uncounted, an undercount in the safe direction.
+ assert_names=frozenset({"should"}),
+)
+
+
+# Keyed by ``LanguageTag`` (``ingestion/models.py``), as ``LANGUAGE_MAPS`` and
+# ``MOCK_DIALECTS`` are. Python has no row on purpose: the same survey found no
+# gap in its narrow tier, and an unmeasured row is a guess.
+ASSERT_DIALECTS: dict[str, AssertDialect] = {
+ "go": _GO,
+ "javascript": _JS_TS,
+ "jsx": _JS_TS,
+ "typescript": _JS_TS,
+ "tsx": _JS_TS,
+}
+
+
+def assert_dialect(
+ language: str, extra_names: frozenset[str] = frozenset()
+) -> AssertDialect | None:
+ """The vocabulary for *language*, or ``None`` when it adds nothing to narrow.
+
+ *extra_names* is the repository's own list, for a house assertion helper the
+ conventions miss. It joins the broad tier for every language, so it can
+ never move a scored marker.
+ """
+ dialect = ASSERT_DIALECTS.get(language)
+ if not extra_names:
+ return dialect
+ if dialect is None:
+ return AssertDialect(assert_names=extra_names)
+ return AssertDialect(
+ assert_names=dialect.assert_names | extra_names,
+ receiver_methods=dialect.receiver_methods,
+ )
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.md
index 4c9f8a583..a33a96109 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md
+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md
@@ -9,7 +9,7 @@ Tree-sitter AST walker. Single AST pass per file computes:
> |--------|----------------|
> | `walker.py` | Orchestration (`walk_file` / `walk_file_complexity`) + public re-exports |
> | `models.py` | Output dataclasses (`FunctionComplexity`, `ClassComplexity`, `PerfHit`, ...) |
-> | `ast_utils.py` | Name/text helpers, function-node collection, parameter counting |
+> | `ast_utils.py` | Name/text helpers, callee-name reading, function-node collection, parameter counting |
> | `nloc.py` | Non-blank / non-comment line counting |
> | `cyclomatic.py` | The CCN / cognitive / max-nesting engine (`_walk_function_body`) |
> | `assertions.py` | Assertion-block detection (test-quality smells) |
@@ -61,6 +61,10 @@ fcx: FileComplexity = walk_file(abs_path, language, source_bytes)
fcx.functions # list[FunctionComplexity]
fcx.classes # list[ClassComplexity]
+# Optional 4th argument: the repository's own assertion names, from the
+# `assertions:` config block. Reaches the broad assertion tier only.
+fcx = walk_file(abs_path, language, source_bytes, frozenset({"ensureinvariant"}))
+
# Back-compat shortcut for callers that only need functions:
results: list[FunctionComplexity] = walk_file_complexity(
abs_path, language, source_bytes
@@ -160,8 +164,15 @@ opt-in fields:
kinds whose callee name starts with `assert` or `expect` (covers
`assertEqual` / `assert_eq!` / `expect(...).toBe(...)`).
-A language that maps neither produces no assertion blocks — never a false
-positive. (Languages without an `expression_statement` wrapper — e.g.
+These two fields say which *nodes* can be an assertion. Which *names* count is
+separate, in `../asserts/lexicon.py`, and is two-tiered: the `assert`/`expect`
+prefixes above feed the calibrated block markers and never change, while a
+per-language row (Go's `t.Fatalf`, testify's `require`, should.js's `.should.`)
+feeds the advisory assertion total only. Adding a language's names is a row
+there; adding a language at all still starts here.
+
+A language that maps neither field produces no assertion facts at all — never a
+false positive, and no vocabulary row can give it any. (Languages without an `expression_statement` wrapper — e.g.
Kotlin, where the call node sits directly in the statement list — are
handled too: the call node is matched as the statement itself.)
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/assertions.py b/packages/core/src/repowise/core/analysis/health/complexity/assertions.py
index 0a15e03a2..6735e871a 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/assertions.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/assertions.py
@@ -7,27 +7,37 @@ count. Opt-in per language via the ``LanguageNodeMap`` ``assert_kinds`` /
(never a false positive). Consumed by the ``large_assertion_block`` /
``duplicated_assertion_block`` biomarkers, and by ``mock_saturated_test``,
which divides mock setup by the total.
+
+Two tiers are counted in one walk, and which marker reads which is the whole
+design (``asserts/lexicon.py`` carries the vocabulary and the evidence):
+
+* ``blocks`` counts the **narrow** tier only — an ``assert``/``expect`` callee
+ or the language's own ``assert`` statement. The two block markers are
+ calibrated on it, so it takes no per-language and no user vocabulary, and a
+ broad-only statement breaks a run exactly as a non-assertion always has.
+* ``total`` counts the **broad** tier, which is narrow plus the language's
+ dialect. Its only reader is the advisory ``mock_saturated_test``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
-from .ast_utils import _IDENTIFIER_SUFFIX
+from ..asserts.lexicon import NARROW_PREFIXES, AssertDialect
+from .ast_utils import _IDENTIFIER_SUFFIX, _callee_names, _receiver_method_verdict
from .languages import LanguageNodeMap
if TYPE_CHECKING:
from tree_sitter import Node
-# Callee-name prefixes that mark a call as a test assertion. Matched
-# case-insensitively against every identifier in the call's callee chain,
-# so ``assertEqual`` / ``assert_eq`` / ``Assert.assertTrue`` / ``expect``
-# all qualify. Deliberately small — these two prefixes cover xUnit-family
-# (``assert*``) and the BDD/expect family (``expect(...)``).
-_ASSERT_CALL_PREFIXES = ("assert", "expect")
_EXPRESSION_STATEMENT = "expression_statement"
_AWAIT_WRAPPER_KINDS = ("await_expression", "await", "parenthesized_expression")
+# Assertion tiers. Narrow implies broad, so a statement carries one of three.
+_NOT_ASSERTION = 0
+_BROAD = 1
+_NARROW = 2
+
def _callee_matches_assert(call_node: Node) -> bool:
"""True if any identifier in *call_node*'s callee chain is assert-ish.
@@ -45,13 +55,30 @@ def _callee_matches_assert(call_node: Node) -> bool:
node = stack.pop()
if node.type.endswith(_IDENTIFIER_SUFFIX) and node.text is not None:
name = node.text.decode("utf-8", errors="replace").lower()
- if any(name.startswith(p) for p in _ASSERT_CALL_PREFIXES):
+ if any(name.startswith(p) for p in NARROW_PREFIXES):
return True
for child in node.children:
stack.append(child)
return False
+def _callee_matches_dialect(call_node: Node, dialect: AssertDialect) -> bool:
+ """True if *call_node* asserts in this language's broad vocabulary.
+
+ Names are exact and read from both ends of the call, because a verification
+ reads either way round: ``verify(mock)`` is the callee, and in
+ ``verify(mock).save()`` it is the receiver of ``save``.
+ """
+ names = _callee_names(call_node)
+ if names is None:
+ return False
+ called, roots = names
+ verdict = _receiver_method_verdict(called, roots, dialect.receiver_methods)
+ if verdict is not None:
+ return verdict
+ return called in dialect.assert_names or bool(roots & dialect.assert_names)
+
+
def _find_assert_call(stmt: Node, kinds: frozenset[str]) -> Node | None:
"""Find an assertion-call node that is *stmt*'s own expression.
@@ -72,43 +99,63 @@ def _find_assert_call(stmt: Node, kinds: frozenset[str]) -> Node | None:
return None
-def _is_assertion_statement(stmt: Node, lmap: LanguageNodeMap) -> bool:
- """True if *stmt* is a test assertion (bare ``assert`` or assert call)."""
+def _assertion_tier(stmt: Node, lmap: LanguageNodeMap, dialect: AssertDialect | None) -> int:
+ """The tier *stmt* asserts at: ``_NARROW``, ``_BROAD`` or ``_NOT_ASSERTION``.
+
+ The broad tier is consulted only once the narrow one has declined, which is
+ what keeps a language with no dialect classifying exactly as narrow alone.
+ """
if stmt.type in lmap.assert_kinds:
- return True
+ return _NARROW
if not lmap.assert_call_kinds:
- return False
- # Some grammars (Kotlin) have no ``expression_statement`` wrapper — the
- # call node sits directly in the statement list. Match it as the
- # statement itself. (Wrapper languages never hit this: their call nodes
- # only ever appear as the single child of an ``expression_statement``,
- # so they can't form a run of ≥2 at this level.)
+ return _NOT_ASSERTION
if stmt.type in lmap.assert_call_kinds:
- return _callee_matches_assert(stmt)
- if stmt.type != _EXPRESSION_STATEMENT:
- return False
- call = _find_assert_call(stmt, lmap.assert_call_kinds)
- return call is not None and _callee_matches_assert(call)
+ # Some grammars (Kotlin) have no ``expression_statement`` wrapper — the
+ # call node sits directly in the statement list. Match it as the
+ # statement itself. (Wrapper languages never hit this: their call nodes
+ # only ever appear as the single child of an ``expression_statement``,
+ # so they can't form a run of ≥2 at this level.)
+ call: Node | None = stmt
+ elif stmt.type == _EXPRESSION_STATEMENT:
+ call = _find_assert_call(stmt, lmap.assert_call_kinds)
+ else:
+ return _NOT_ASSERTION
+ if call is None:
+ return _NOT_ASSERTION
+ if _callee_matches_assert(call):
+ return _NARROW
+ if dialect is not None and _callee_matches_dialect(call, dialect):
+ return _BROAD
+ return _NOT_ASSERTION
+
+
+def _is_assertion_statement(
+ stmt: Node, lmap: LanguageNodeMap, dialect: AssertDialect | None = None
+) -> bool:
+ """True if *stmt* is a test assertion at the broad tier."""
+ return _assertion_tier(stmt, lmap, dialect) != _NOT_ASSERTION
def _collect_assertion_facts(
- body_node: Node, lmap: LanguageNodeMap
+ body_node: Node, lmap: LanguageNodeMap, dialect: AssertDialect | None = None
) -> tuple[list[tuple[int, int, int]], int]:
"""``(blocks, total)`` assertion facts for one function body.
- *blocks* are runs of ≥2 consecutive assertion statements, each recorded as
- ``(start_line, end_line, count)``. Runs are found per statement-list (a
- block's direct children), so an assertion sequence broken by a
- non-assertion statement starts a new run. Nested function bodies are
- skipped: their assertions belong to them.
-
- *total* counts assertion **statements** only, at block level. The run scan
- keeps scanning everywhere, which is a deliberate asymmetry: it feeds the
- calibrated ``duplicated_assertion_block``, and narrowing it would change
- scored findings. A run needs two siblings so it rarely fires off a statement
- list, but a total counts each match on its own and would double-count every
- assertion in a language whose ``assert_call_kinds`` is its plain call node.
- Block level also makes it commensurable with ``mock_walk._count_body_setup``.
+ *blocks* are runs of ≥2 consecutive **narrow-tier** assertion statements,
+ each recorded as ``(start_line, end_line, count)``. Runs are found per
+ statement-list (a block's direct children), so an assertion sequence broken
+ by a non-assertion statement starts a new run — and a broad-only statement
+ breaks one, because these runs are what the calibrated markers read.
+ Nested function bodies are skipped: their assertions belong to them.
+
+ *total* counts **broad-tier** assertion **statements** only, at block level.
+ The run scan keeps scanning everywhere, which is a deliberate asymmetry: it
+ feeds the calibrated ``duplicated_assertion_block``, and narrowing it would
+ change scored findings. A run needs two siblings so it rarely fires off a
+ statement list, but a total counts each match on its own and would
+ double-count every assertion in a language whose ``assert_call_kinds`` is
+ its plain call node. Block level also makes it commensurable with
+ ``mock_walk._count_body_setup``.
"""
if not lmap.assert_kinds and not lmap.assert_call_kinds:
return [], 0
@@ -123,9 +170,10 @@ def _collect_assertion_facts(
for child in parent.children:
if not child.is_named:
continue
- if _is_assertion_statement(child, lmap):
- if count_total:
- total += 1
+ tier = _assertion_tier(child, lmap, dialect)
+ if count_total and tier != _NOT_ASSERTION:
+ total += 1
+ if tier == _NARROW:
if run_count == 0:
run_start = child.start_point[0] + 1
run_end = child.end_point[0] + 1
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
index a21f7816e..5559bf83c 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
@@ -1,9 +1,14 @@
"""Shared tree-sitter AST helpers used across the walker passes.
Name/text extraction, function-entry naming (including lambdas assigned to
-a variable or passed as a callback), top-level function-node collection, and
-parameter counting. These are the cross-pass primitives; the metric passes
-(cyclomatic, assertions, error-handling, perf, class-analysis) build on them.
+a variable or passed as a callback), top-level function-node collection,
+parameter counting, and callee-name reading. These are the cross-pass
+primitives; the metric passes (cyclomatic, assertions, error-handling, perf,
+class-analysis) build on them.
+
+``_identifier_chain`` / ``_callee_names`` / ``_receiver_method_verdict`` live
+here because the mock pass and the assertion pass both read callee names and
+both ask the same question of a listed receiver.
"""
from __future__ import annotations
@@ -294,3 +299,72 @@ def _count_parameters(fn_node: Node) -> int:
if child.is_named:
count += 1
return count
+
+
+def _identifier_chain(node: Node) -> list[str]:
+ """Every identifier under *node*, lowercased, in document order.
+
+ Order is load-bearing: the last entry is the name being called, the rest
+ the receiver path. Argument lists are never descended into.
+ """
+ names: list[str] = []
+ stack: list[Node] = [node]
+ while stack:
+ cur = stack.pop()
+ if cur.type in ("argument_list", "arguments"):
+ continue
+ if cur.type.endswith(_IDENTIFIER_SUFFIX) and cur.text is not None:
+ names.append(cur.text.decode("utf-8", "replace").lower())
+ stack.extend(reversed(cur.children))
+ return names
+
+
+def _callee_names(call_node: Node) -> tuple[str, set[str]] | None:
+ """``(called_name, receiver_roots)`` for a call, or ``None``.
+
+ Two grammar shapes: a single callee subtree under ``function`` / ``macro``,
+ read rightmost-last so ``mock.patch(...)`` gives ``("patch", {"mock"})``; or
+ a ``name`` field beside an ``object`` field (Java, C#), where the callee is
+ not one node. Arguments are excluded in both.
+ """
+ name_node = call_node.child_by_field_name("name")
+ if name_node is not None:
+ # Split shape: the name IS the called name, the receiver is ``object``.
+ called = (name_node.text or b"").decode("utf-8", "replace").lower()
+ if not called:
+ return None
+ receiver = call_node.child_by_field_name("object")
+ return called, set(_identifier_chain(receiver)) if receiver is not None else set()
+
+ callee = call_node.child_by_field_name("function") or call_node.child_by_field_name("macro")
+ if callee is None:
+ named = [
+ c
+ for c in call_node.children
+ if c.is_named and c.type not in ("argument_list", "arguments")
+ ]
+ callee = named[0] if named else None
+ if callee is None:
+ return None
+ chain = _identifier_chain(callee)
+ if not chain:
+ return None
+ return chain[-1], set(chain[:-1])
+
+
+def _receiver_method_verdict(
+ called: str, roots: set[str], receiver_methods: dict[str, frozenset[str]]
+) -> bool | None:
+ """Whether a listed receiver licenses *called*, or ``None`` if none is listed.
+
+ A listed receiver is exhaustive about its own methods, so a hit settles the
+ call either way and the caller stops. Roots are read in sorted order: a
+ chain naming two listed receivers must not resolve by set iteration order.
+ """
+ if not receiver_methods:
+ return None
+ for root in sorted(roots):
+ methods = receiver_methods.get(root)
+ if methods is not None:
+ return called in methods
+ return None
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index f1fa38dd7..e6c03dc84 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -105,11 +105,14 @@ class LanguageNodeMap:
# assertion *call* (``assertEqual`` / ``expect`` / ``assert_eq!``).
# A statement counts as an assertion when its expression is a call
# of one of these kinds whose callee name starts with ``assert`` or
- # ``expect`` (see ``walker._ASSERT_CALL_PREFIXES``).
+ # ``expect``, or which the language's row in ``asserts/lexicon.py``
+ # names. These fields say which nodes to look at; that file says which
+ # names count (see ``assertions._assertion_tier``).
#
# Consumed by ``large_assertion_block`` / ``duplicated_assertion_block``
- # (both fire only on test files). A language that maps neither field
- # simply produces no assertion blocks — never a false positive.
+ # (both fire only on test files) and by ``mock_saturated_test``. A language
+ # that maps neither field produces no assertion facts at all — never a
+ # false positive, and no vocabulary row can give it any.
assert_kinds: frozenset[str] = frozenset()
assert_call_kinds: frozenset[str] = frozenset()
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/mock_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/mock_walk.py
index 2eee3387b..025d60c2c 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/mock_walk.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/mock_walk.py
@@ -26,9 +26,10 @@ from __future__ import annotations
from typing import TYPE_CHECKING
+from ..asserts.lexicon import AssertDialect
from ..mocks.lexicon import MOCK_DIALECTS, MOCK_IDENTIFIER_TOKENS, MockDialect
from .assertions import _is_assertion_statement
-from .ast_utils import _IDENTIFIER_SUFFIX
+from .ast_utils import _callee_names, _identifier_chain, _receiver_method_verdict
from .languages import LanguageNodeMap
if TYPE_CHECKING:
@@ -58,68 +59,15 @@ def file_may_contain_mocks(source: bytes) -> bool:
return any(marker in lowered for marker in _FILE_MARKERS)
-def _identifier_chain(node: Node) -> list[str]:
- """Every identifier under *node*, lowercased, in document order.
-
- Order is load-bearing: the last entry is the name being called, the rest
- the receiver path. Argument lists are never descended into.
- """
- names: list[str] = []
- stack: list[Node] = [node]
- while stack:
- cur = stack.pop()
- if cur.type in ("argument_list", "arguments"):
- continue
- if cur.type.endswith(_IDENTIFIER_SUFFIX) and cur.text is not None:
- names.append(cur.text.decode("utf-8", "replace").lower())
- stack.extend(reversed(cur.children))
- return names
-
-
-def _callee_names(call_node: Node) -> tuple[str, set[str]] | None:
- """``(called_name, receiver_roots)`` for a call, or ``None``.
-
- Two grammar shapes: a single callee subtree under ``function`` / ``macro``,
- read rightmost-last so ``mock.patch(...)`` gives ``("patch", {"mock"})``; or
- a ``name`` field beside an ``object`` field (Java, C#), where the callee is
- not one node. Arguments are excluded in both.
- """
- name_node = call_node.child_by_field_name("name")
- if name_node is not None:
- # Split shape: the name IS the called name, the receiver is ``object``.
- called = (name_node.text or b"").decode("utf-8", "replace").lower()
- if not called:
- return None
- receiver = call_node.child_by_field_name("object")
- return called, set(_identifier_chain(receiver)) if receiver is not None else set()
-
- callee = call_node.child_by_field_name("function") or call_node.child_by_field_name("macro")
- if callee is None:
- named = [
- c
- for c in call_node.children
- if c.is_named and c.type not in ("argument_list", "arguments")
- ]
- callee = named[0] if named else None
- if callee is None:
- return None
- chain = _identifier_chain(callee)
- if not chain:
- return None
- return chain[-1], set(chain[:-1])
-
-
def _is_mock_call(call_node: Node, dialect: MockDialect) -> bool:
"""True when *call_node* constructs, patches or configures a test double."""
names = _callee_names(call_node)
if names is None:
return False
called, roots = names
- for root in roots:
- methods = dialect.receiver_methods.get(root)
- if methods is not None:
- # A listed receiver is exhaustive about its own methods.
- return called in methods
+ verdict = _receiver_method_verdict(called, roots, dialect.receiver_methods)
+ if verdict is not None:
+ return verdict
if any(token in name for name in (called, *roots) for token in MOCK_IDENTIFIER_TOKENS):
return True
if called in dialect.setup_callees or roots & dialect.setup_callees:
@@ -198,7 +146,12 @@ def _count_decorators(fn_node: Node, lmap: LanguageNodeMap, dialect: MockDialect
return count
-def _count_body_setup(body: Node, lmap: LanguageNodeMap, dialect: MockDialect) -> int:
+def _count_body_setup(
+ body: Node,
+ lmap: LanguageNodeMap,
+ dialect: MockDialect,
+ asserts: AssertDialect | None,
+) -> int:
"""Mock-setup statements within *body*.
Statements are the named children of a block, so a nested block's
@@ -212,8 +165,10 @@ def _count_body_setup(body: Node, lmap: LanguageNodeMap, dialect: MockDialect) -
if not stmt.is_named:
continue
# Assertions are classified first and are never setup, even when
- # they read a double (``mock.assert_called_once()``).
- if _is_assertion_statement(stmt, lmap):
+ # they read a double (``mock.assert_called_once()``). Broad tier,
+ # the same one the ratio divides by, so no statement can land in
+ # both halves of it.
+ if _is_assertion_statement(stmt, lmap, asserts):
continue
if _is_config_assignment(stmt, lmap, dialect) or _contains_mock_call(
stmt, lmap, dialect
@@ -239,8 +194,11 @@ def _count_mock_setup(
body: Node,
lmap: LanguageNodeMap,
dialect: MockDialect | None,
+ asserts: AssertDialect | None = None,
) -> int:
"""Mock-setup statements for one function, decorators included."""
if dialect is None or not lmap.block_kinds or not lmap.call_kinds:
return 0
- return _count_decorators(fn_node, lmap, dialect) + _count_body_setup(body, lmap, dialect)
+ return _count_decorators(fn_node, lmap, dialect) + _count_body_setup(
+ body, lmap, dialect, asserts
+ )
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 6984db02c..7b4762aac 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -38,6 +38,7 @@ from typing import TYPE_CHECKING
import structlog
+from ..asserts.lexicon import assert_dialect as _assert_dialect
from ..mocks.lexicon import mock_dialect as _mock_dialect
from .assertions import _collect_assertion_facts
from .ast_utils import (
@@ -92,6 +93,7 @@ def walk_file(
abs_path: str,
language: str,
source: bytes,
+ extra_assert_names: frozenset[str] = frozenset(),
) -> FileComplexity:
"""Walk one file's AST once → per-function and per-class metrics.
@@ -102,6 +104,11 @@ def walk_file(
Class-level metrics are populated only when the language's
``LanguageNodeMap`` opts in via ``class_kinds`` (see ``languages.py``).
+
+ *extra_assert_names* is the repository's configured assertion vocabulary.
+ It reaches the broad tier only, so the result stays a pure function of the
+ bytes, the language and the walker's version for every repository that
+ configures none — which is what the walk cache keys on.
"""
lmap = get_language_map(language)
if lmap is None:
@@ -142,10 +149,14 @@ def walk_file(
# the walk cache keys on.
dialect = _mock_dialect(language)
mock_dialect = dialect if dialect is not None and file_may_contain_mocks(source) else None
+ # Broad-tier assertion vocabulary. ``None`` for a language with no row,
+ # which leaves the narrow tier alone and is what every language counted
+ # before this existed.
+ asserts = _assert_dialect(language, extra_assert_names)
for fn_node in _collect_function_nodes(tree.root_node, lmap):
body = fn_node.child_by_field_name("body") or fn_node
ccn, max_nest, cognitive, bumps, conditions = _walk_function_body(body, lmap)
- assertion_blocks, assertion_count = _collect_assertion_facts(body, lmap)
+ assertion_blocks, assertion_count = _collect_assertion_facts(body, lmap, asserts)
fc = FunctionComplexity(
name=_find_function_entry_name(fn_node, lmap),
start_line=fn_node.start_point[0] + 1,
@@ -159,7 +170,7 @@ def walk_file(
complex_conditions=conditions,
assertion_blocks=assertion_blocks,
assertion_count=assertion_count,
- mock_setup_count=_count_mock_setup(fn_node, body, lmap, mock_dialect),
+ mock_setup_count=_count_mock_setup(fn_node, body, lmap, mock_dialect, asserts),
)
functions.append(fc)
fc_by_node_id[fn_node.id] = fc
diff --git a/packages/core/src/repowise/core/analysis/health/config.py b/packages/core/src/repowise/core/analysis/health/config.py
index 73bf69555..1f5ed9d8c 100644
--- a/packages/core/src/repowise/core/analysis/health/config.py
+++ b/packages/core/src/repowise/core/analysis/health/config.py
@@ -86,6 +86,20 @@ _PROFILES: dict[str, dict[str, Severity]] = {
}
+def _assertion_names(raw: object) -> list[str]:
+ """Coerce ``assertions.extra_names`` to sorted, matchable lowercase names.
+
+ Accepts one string or a list of them, as the ``coverage:`` block does, and
+ drops anything else rather than raising: a typo in optional config must not
+ fail an analysis.
+ """
+ if isinstance(raw, str):
+ raw = [raw]
+ if not isinstance(raw, (list, tuple)):
+ return []
+ return sorted({n.strip().lower() for n in raw if isinstance(n, str) and n.strip()})
+
+
def _string_list(raw: object, *, field: str) -> list[str]:
"""Parse a list-of-names field, dropping anything that is not one.
@@ -236,6 +250,12 @@ class HealthConfig:
refactoring_enabled: bool = True
disabled_refactorings: list[str] = field(default_factory=list)
refactoring_min_confidence: str | None = None
+ # Extra assertion names, from the ``assertions:`` block of
+ # ``.repowise/config.yaml``, for a house assertion helper the built-in
+ # vocabulary misses. Exact lowercase names, never prefixes. They reach the
+ # broad tier only (``asserts/lexicon.py``), so unlike every other key here
+ # this one provably cannot move a score.
+ assert_extra_names: list[str] = field(default_factory=list)
@classmethod
def load(cls, repo_path: Path | str) -> HealthConfig:
@@ -243,11 +263,12 @@ class HealthConfig:
The per-file biomarker overrides come from ``health-rules.json``; the
refactoring-layer knobs come from the ``refactoring:`` block of
- ``.repowise/config.yaml`` (loaded here and merged onto the same config
+ ``.repowise/config.yaml``, and the assertion vocabulary from its
+ ``assertions:`` block (both loaded here and merged onto the same config
object). Missing file → empty config. Malformed file → empty config +
a single warning log. Never raises.
"""
- cfg = cls._load_refactoring(repo_path)
+ cfg = cls._load_config_yaml_blocks(repo_path)
rules_path = get_repowise_dir(repo_path) / HEALTH_RULES_FILENAME
if not rules_path.exists():
return cfg
@@ -260,24 +281,29 @@ class HealthConfig:
rules_cfg.refactoring_enabled = cfg.refactoring_enabled
rules_cfg.disabled_refactorings = cfg.disabled_refactorings
rules_cfg.refactoring_min_confidence = cfg.refactoring_min_confidence
+ rules_cfg.assert_extra_names = cfg.assert_extra_names
return rules_cfg
@classmethod
- def _load_refactoring(cls, repo_path: Path | str) -> HealthConfig:
- """Read the ``refactoring:`` block from ``.repowise/config.yaml``.
+ def _load_config_yaml_blocks(cls, repo_path: Path | str) -> HealthConfig:
+ """Read the ``refactoring:`` and ``assertions:`` blocks of config.yaml.
- Returns a config carrying only the refactoring knobs (biomarker fields
- left at their defaults). Never raises: a missing/malformed file or an
- unexpected shape degrades to the defaults (everything on, no floor).
+ Returns a config carrying only those knobs (biomarker fields left at
+ their defaults). Never raises: a missing/malformed file or an
+ unexpected shape degrades to the defaults (everything on, no floor,
+ no extra assertion names).
"""
try:
raw = load_repo_config(repo_path)
except Exception as exc: # defensive: config.yaml read must never break load
- log.debug("refactoring_config_load_failed", error=str(exc))
+ log.debug("health_config_yaml_load_failed", error=str(exc))
return cls()
- return cls._from_refactoring_block(
- raw.get("refactoring") if isinstance(raw, dict) else None
- )
+ block = raw if isinstance(raw, dict) else {}
+ cfg = cls._from_refactoring_block(block.get("refactoring"))
+ assertions = block.get("assertions")
+ if isinstance(assertions, dict):
+ cfg.assert_extra_names = _assertion_names(assertions.get("extra_names"))
+ return cfg
@classmethod
def _from_refactoring_block(cls, block: object) -> HealthConfig:
@@ -426,4 +452,5 @@ class HealthConfig:
"refactoring_enabled": self.refactoring_enabled,
"disabled_refactorings": list(self.disabled_refactorings),
"refactoring_min_confidence": self.refactoring_min_confidence,
+ "assert_extra_names": list(self.assert_extra_names),
}
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 6e09bbf61..3cc35fa0e 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -39,6 +39,7 @@ from ...ingestion.package_roots import package_roots_from_paths as _package_root
from ...ingestion.package_roots import scan_package_roots as _scan_package_roots
from ..graph_view import HasEdge, ImportEdgeView
from ..test_reachability import files_reached_by_tests
+from .asserts.lexicon import AssertVocabulary
from .biomarkers import FileContext, detect_all
from .complexity import FileComplexity, FunctionComplexity, walk_file
from .coverage import is_test_file as _coverage_is_test_file
@@ -99,7 +100,14 @@ log = structlog.get_logger(__name__)
# Not a licence to move a calibrated scoring weight — those are frozen
# independently of this stamp.
#
-# Current stamp: ``mock_saturated_test`` gained a TypeScript / JavaScript
+# Current stamp: the assertion count gained a per-language broad tier, so a Go
+# or JS/TS file's ``assertion_count`` changes from what a cached v13 walk stored
+# for it. The narrow tier the calibrated block markers read is unchanged, so no
+# score moves; this stamp is what re-walks the files whose advisory denominator
+# does. Go's row changes no finding until Go also has a mock dialect — it is
+# there for the markers that read this count next.
+#
+# v13: ``mock_saturated_test`` gained a TypeScript / JavaScript
# vocabulary, so a TS or JS file's ``mock_setup_count`` changes from the zero a
# cached v12 walk stored for it.
#
@@ -126,7 +134,7 @@ log = structlog.get_logger(__name__)
# forms. Files that were counted untested and are not become tested, which
# moves untested-hotspot findings and the scores that carry them, on every
# language with a prefix or spec convention rather than Ruby alone.
-HEALTH_ANALYZER_VERSION = 13
+HEALTH_ANALYZER_VERSION = 14
# Method-level smells that make the dataflow / Extract Method pass worthwhile.
# Only files carrying one of these get a CFG + def/use + reaching pass built.
@@ -455,6 +463,7 @@ class HealthAnalyzer:
from repowise.core.pipeline.phase_timing import timed
cfg = config or {}
+ vocab = AssertVocabulary.from_analyzer_config(cfg)
disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))
per_file_disabled: dict[str, set[str]] = cfg.get("per_file_disabled", {}) or {}
repo_severity_overrides: dict[str, Severity] = cfg.get("severity_overrides", {}) or {}
@@ -523,7 +532,7 @@ class HealthAnalyzer:
if not scores_language(pf.file_info.language):
continue
try:
- fcx = self._walk(pf)
+ fcx = self._walk(pf, vocab)
except Exception as exc:
log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))
fcx = FileComplexity(functions=[], classes=[])
@@ -667,6 +676,7 @@ class HealthAnalyzer:
repo so the gate is not biased by the changed-files subset.
"""
cfg = config or {}
+ vocab = AssertVocabulary.from_analyzer_config(cfg)
disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))
per_file_disabled: dict[str, set[str]] = cfg.get("per_file_disabled", {}) or {}
repo_severity_overrides: dict[str, Severity] = cfg.get("severity_overrides", {}) or {}
@@ -725,7 +735,7 @@ class HealthAnalyzer:
async def _one(pf: Any) -> tuple[Any, FileComplexity]:
async with semaphore:
try:
- fcx = await asyncio.to_thread(self._walk, pf)
+ fcx = await asyncio.to_thread(self._walk, pf, vocab)
except Exception as exc:
log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))
fcx = FileComplexity(functions=[], classes=[])
@@ -944,7 +954,7 @@ class HealthAnalyzer:
log.debug("function_blame_rollup_failed", error=str(exc))
return []
- def _walk(self, pf: Any) -> FileComplexity:
+ def _walk(self, pf: Any, vocab: AssertVocabulary) -> FileComplexity:
path = pf.file_info.abs_path
language = pf.file_info.language
source = self.read_source(path)
@@ -954,7 +964,7 @@ class HealthAnalyzer:
if self._walk_cache is not None:
from repowise.core.ingestion import compute_content_hash
- key = HealthWalkCache.key(language, compute_content_hash(source))
+ key = HealthWalkCache.key(language, compute_content_hash(source), vocab.key)
cached = self._walk_cache.get(key)
if cached is not None:
return cached
@@ -965,7 +975,7 @@ class HealthAnalyzer:
fcx = walk_sql_file(pf.file_info, source)
else:
- fcx = walk_file(path, language, source)
+ fcx = walk_file(path, language, source, vocab.names)
if key is not None and self._walk_cache is not None:
self._walk_cache.put(key, fcx)
return fcx
diff --git a/packages/core/src/repowise/core/analysis/health/walk_cache.py b/packages/core/src/repowise/core/analysis/health/walk_cache.py
index cce8d8b81..2cb946cbf 100644
--- a/packages/core/src/repowise/core/analysis/health/walk_cache.py
+++ b/packages/core/src/repowise/core/analysis/health/walk_cache.py
@@ -1,7 +1,9 @@
"""Content-keyed cache of the complexity walk, kept beside the index.
The walk over a file is a pure function of its bytes, its language and the
-walker's version, and on an update most of the files the health pass walks
+walker's version (and, where a repository configures one, its assertion
+vocabulary -- see :meth:`HealthWalkCache.key`), and on an update most of the
+files the health pass walks
did not change: the performance closure re-walks every file whose call path
reaches a changed sink, so the walk was two fifths of a one-file update.
This keeps each file's :class:`FileComplexity` under its content hash the way
@@ -47,8 +49,18 @@ class HealthWalkCache:
self.misses = 0
@staticmethod
- def key(language: str, content_hash: str) -> str:
- return f"{language}:{content_hash}"
+ def key(language: str, content_hash: str, vocabulary: str = "") -> str:
+ """The cache key, optionally qualified by a configured vocabulary.
+
+ A repository that configures an assertion vocabulary breaks the "bytes
+ plus language plus version" purity this cache rests on, so the
+ vocabulary joins the key and an edit to it simply misses and ages out.
+ Empty is the overwhelmingly common case and keys exactly as before, so
+ no existing cache is invalidated by this parameter existing.
+ """
+ if not vocabulary:
+ return f"{language}:{content_hash}"
+ return f"{language}:{content_hash}:{vocabulary}"
def load(self) -> None:
try:
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index 8a9e5cc79..061548192 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -21,7 +21,7 @@ MANIFEST_BASENAME = "decisions.yaml"
CONFIG_DEPENDENCY_KEYS: dict[str, frozenset[str]] = {
"traversal": frozenset({"exclude_patterns"}),
"git_history": frozenset({"commit_limit", "follow_renames"}),
- "health": frozenset({"coverage", "refactoring"}),
+ "health": frozenset({"assertions", "coverage", "refactoring"}),
"generation": frozenset(
{
"provider",
diff --git a/tests/unit/health/test_assertion_vocabulary.py b/tests/unit/health/test_assertion_vocabulary.py
new file mode 100644
index 000000000..a2239fb22
--- /dev/null
+++ b/tests/unit/health/test_assertion_vocabulary.py
@@ -0,0 +1,255 @@
+"""The two-tier assertion vocabulary: what each tier counts, and for whom.
+
+Written as real source through the walker rather than as hand-built rows,
+because every case here is grammar-shaped: a receiver read in the wrong order,
+a matcher chain whose assertion verb sits in the middle, a ``t.Run`` that looks
+exactly like a ``t.Fatal`` to a name-only rule.
+
+The load-bearing test in this file is
+:func:`test_a_dialect_never_changes_the_narrow_blocks`. The broad tier is only
+shippable because the calibrated block markers cannot see it.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.asserts.lexicon import (
+ AssertVocabulary,
+ assert_dialect,
+)
+from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.config import _assertion_names
+from repowise.core.analysis.health.walk_cache import HealthWalkCache
+
+
+def _require(language: str) -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ if _get_language(language) is None:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+
+
+def _counts(
+ source: str, path: str, language: str, extra: frozenset[str] = frozenset()
+) -> dict[str, tuple[int, int]]:
+ """``{function: (assertion_count, number of assertion blocks)}``."""
+ fc = walk_file(path, language, source.encode("utf-8"), extra)
+ return {f.name: (f.assertion_count, len(f.assertion_blocks)) for f in fc.functions}
+
+
+# ---------------------------------------------------------------------------
+# Go — the language the single-tier vocabulary left invisible
+# ---------------------------------------------------------------------------
+
+GO_TB = """
+func TestThing(t *testing.T) {
+ if got != want {
+ t.Errorf("got %v want %v", got, want)
+ }
+ if err != nil {
+ t.Fatalf("boom: %v", err)
+ }
+ t.Log("diagnostic, not an assertion")
+ t.Run("subtest", func(t *testing.T) {})
+ t.Skip("not an assertion either")
+}
+"""
+
+
+def test_go_testing_failures_are_assertions() -> None:
+ """``t.Errorf`` / ``t.Fatalf`` are how stdlib Go asserts.
+
+ They carry almost all of Go's assertion volume and none of it was visible
+ to the ``assert``/``expect`` prefix rule. Figures in LANGUAGE_SUPPORT.md.
+ """
+ _require("go")
+ assert _counts(GO_TB, "pkg/thing_test.go", "go")["TestThing"][0] == 2
+
+
+def test_go_test_handle_reporting_methods_are_not_assertions() -> None:
+ """``t.Log`` / ``t.Run`` / ``t.Skip`` share the receiver and assert nothing.
+
+ The reason the ``t`` receiver carries a method list rather than being taken
+ whole, the way ``require`` is.
+ """
+ _require("go")
+ source = """
+func TestThing(t *testing.T) {
+ t.Log("a")
+ t.Logf("b %v", c)
+ t.Run("sub", func(t *testing.T) {})
+ t.Skip("c")
+ t.Helper()
+}
+"""
+ assert _counts(source, "pkg/thing_test.go", "go")["TestThing"][0] == 0
+
+
+def test_go_testify_require_joins_assert() -> None:
+ """``require.NoError`` is ``assert.NoError``'s sibling and was a total miss.
+
+ ``assert.Equal`` already matched on its receiver name; ``require`` did not.
+ """
+ _require("go")
+ source = """
+func TestThing(t *testing.T) {
+ require.NoError(t, err)
+ require.Equal(t, want, got)
+ assert.Equal(t, want, got)
+}
+"""
+ assert _counts(source, "pkg/thing_test.go", "go")["TestThing"][0] == 3
+
+
+# ---------------------------------------------------------------------------
+# TypeScript — should.js / chai's BDD chain
+# ---------------------------------------------------------------------------
+
+
+def test_typescript_should_chain_is_an_assertion() -> None:
+ """``result.should.equal(x)`` asserts through a receiver, not a callee."""
+ _require("typescript")
+ source = """
+describe("thing", () => {
+ it("works", () => {
+ result.should.equal(5);
+ other.should.containEql("a");
+ });
+});
+"""
+ assert _counts(source, "tests/thing.test.ts", "typescript")["it callback"][0] == 2
+
+
+def test_typescript_should_prefixed_callee_is_not_an_assertion() -> None:
+ """``shouldRetry(cfg)`` is the code under test.
+
+ A prefix rule takes this; an exact one does not. The measured reason the
+ vocabulary is exact names only.
+ """
+ _require("typescript")
+ source = """
+describe("thing", () => {
+ it("works", () => {
+ shouldRetry(cfg);
+ shouldZeroCost(opts);
+ });
+});
+"""
+ assert _counts(source, "tests/thing.test.ts", "typescript")["it callback"][0] == 0
+
+
+# ---------------------------------------------------------------------------
+# The boundary the phase turns on
+# ---------------------------------------------------------------------------
+
+
+def test_a_dialect_never_changes_the_narrow_blocks() -> None:
+ """A broad-only assertion breaks a run exactly as a non-assertion does.
+
+ ``large_assertion_block`` and ``duplicated_assertion_block`` are calibrated
+ on these runs. If a vocabulary row could join one, this phase would move
+ scored findings, and it must not.
+ """
+ _require("go")
+ source = """
+func TestThing(t *testing.T) {
+ assert.Equal(t, a, b)
+ require.NoError(t, err)
+ assert.Equal(t, c, d)
+}
+"""
+ with_dialect = _counts(source, "pkg/thing_test.go", "go")["TestThing"]
+ assert with_dialect[0] == 3, "broad tier counts all three"
+ assert with_dialect[1] == 0, "the require between them still splits the run"
+
+
+def test_a_language_with_no_dialect_counts_exactly_as_before() -> None:
+ """Python has no row, so nothing about its counting changed."""
+ source = """
+def test_thing():
+ assert a == b
+ self.assertEqual(c, d)
+ verify(mock)
+ result.should.equal(5)
+"""
+ counts = _counts(source, "tests/test_thing.py", "python")["test_thing"]
+ assert counts == (2, 1), "the assert statement and assertEqual, as one run"
+
+
+# ---------------------------------------------------------------------------
+# The repository's own vocabulary
+# ---------------------------------------------------------------------------
+
+
+def test_configured_names_reach_the_broad_tier() -> None:
+ """A house assertion helper the conventions miss can be declared."""
+ source = """
+def test_thing():
+ ensureInvariant(client)
+ ensureInvariant(client)
+"""
+ path, lang = "tests/test_thing.py", "python"
+ assert _counts(source, path, lang)["test_thing"][0] == 0
+ extra = frozenset({"ensureinvariant"})
+ assert _counts(source, path, lang, extra)["test_thing"][0] == 2
+
+
+def test_configured_names_cannot_move_a_block() -> None:
+ """The property that makes user config safe to expose at all.
+
+ Two consecutive configured assertions are two broad-tier counts and still
+ zero narrow-tier runs, so no scored marker can see them.
+ """
+ source = """
+def test_thing():
+ ensureInvariant(client)
+ ensureInvariant(client)
+"""
+ counts = _counts(source, "tests/test_thing.py", "python", frozenset({"ensureinvariant"}))
+ assert counts["test_thing"] == (2, 0)
+
+
+def test_configured_names_are_exact_not_prefixes() -> None:
+ """``ensure`` must not sweep in ``ensureConnectionPool(...)``."""
+ source = """
+def test_thing():
+ ensureInvariant(client)
+ ensureConnectionPool(client)
+"""
+ counts = _counts(source, "tests/test_thing.py", "python", frozenset({"ensureinvariant"}))
+ assert counts["test_thing"][0] == 1
+
+
+def test_a_dialect_language_keeps_its_rows_when_names_are_configured() -> None:
+ """Extras join a dialect rather than replacing it."""
+ dialect = assert_dialect("go", frozenset({"mustmatch"}))
+ assert dialect is not None
+ assert "require" in dialect.assert_names and "mustmatch" in dialect.assert_names
+ assert dialect.receiver_methods["t"], "the Go receiver list survives"
+
+
+def test_configured_names_are_coerced_to_what_config_can_hold() -> None:
+ """One string, a list, and anything else. A typo must not fail a run."""
+ assert _assertion_names("MustMatch") == ["mustmatch"]
+ assert _assertion_names([" Ensure ", "ok"]) == ["ensure", "ok"]
+ assert _assertion_names(["", None, 17]) == []
+ assert _assertion_names(None) == []
+ assert _assertion_names(17) == []
+
+
+def test_the_vocabulary_cache_key_ignores_list_order() -> None:
+ """Two orderings of one list must share a cached walk."""
+ a = AssertVocabulary.from_analyzer_config({"assert_extra_names": ["b", "a"]})
+ b = AssertVocabulary.from_analyzer_config({"assert_extra_names": ["a", "b"]})
+ assert a.key == b.key == "a,b"
+ assert AssertVocabulary.from_analyzer_config({}).key == ""
+
+
+def test_walk_cache_key_is_unchanged_without_a_vocabulary() -> None:
+ """No existing cache entry is invalidated by the parameter existing."""
+ assert HealthWalkCache.key("go", "abc") == "go:abc"
+ assert HealthWalkCache.key("go", "abc", "") == "go:abc"
+ assert HealthWalkCache.key("go", "abc", "ensure") == "go:abc:ensure"
diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.py
index 2ac0caa34..689db3a73 100644
--- a/tests/unit/health/test_model_version_coupling.py
+++ b/tests/unit/health/test_model_version_coupling.py
@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (
# The three stamps as they stand together. Moving either identity model means
# moving the analyzer with it, and updating this tuple in the same commit.
-_STAMPS = (13, 2, 2)
+_STAMPS = (14, 2, 2)
def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:
diff --git a/tests/unit/health/test_walk_cache.py b/tests/unit/health/test_walk_cache.py
index 7b0f9b99d..a0e13ed4d 100644
--- a/tests/unit/health/test_walk_cache.py
+++ b/tests/unit/health/test_walk_cache.py
@@ -109,9 +109,9 @@ def test_the_analyzer_walks_once_and_serves_the_second_pass_from_the_cache(tmp_p
calls: list[str] = []
real_walk = engine_mod.walk_file
- def counting_walk(path, language, source):
+ def counting_walk(path, language, source, extra_assert_names=frozenset()):
calls.append(path)
- return real_walk(path, language, source)
+ return real_walk(path, language, source, extra_assert_names)
monkeypatch.setattr(engine_mod, "walk_file", counting_walk)