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
fix(health): read a .tsx file with the JSX grammar (#2398)
Raghav Chamadiya19310f292779
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 5b377da9f..f9a81b35c 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -456,8 +456,7 @@ accounted for every false positive.`assertion_free_test` measures **52%** on TypeScript and **53%** on Python, anddoes not report on Go or Java at all; the per-language reasoning is in-[LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage). It also declines-`.tsx` files, whose assertions the walk cannot currently see.+[LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md#code-health-coverage).It asks a question with a yes-or-no answer rather than athreshold, which is why it can be stated plainly: a test case whose assertiondiff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 5b28a0d93..6d8eb8ec9 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -494,6 +494,53 @@ from the test that calls it:Separating them needs the assertions of a called function to reach its caller,which is a cross-function question this pass does not ask.+**A `.tsx` file is read with the JSX grammar.** It arrives tagged `typescript`,+and the grammar that tag selects fails on the first `<Component />`; everything+after it lands in ERROR recovery. The health pass picks the grammar from the+path instead, in all three places it parses: the complexity walk, the clone+tokenizer and the dataflow CFG. A React suite is read the way a `.ts` suite+always was. What it was costing, measured on two React corpora (374 and 562+`.tsx` files):++| | 374-file corpus | 562-file corpus |+|---|---|---|+| Assertions counted on `.tsx` | 1,367 to 2,085 | 175 to 377 |+| Assertion runs on `.tsx` | 264 to 391 | 30 to 69 |+| `.tsx` files whose clone token stream changed | 365 of 374 | 550 of 562 |+| Function names over 60 chars, a proxy for recovery wreckage | 124 to 0 | 20 to 3 |+| `assertion_free_test` on `.tsx` | 15 to 0 | 0 to 1 |+| Non-`.tsx` files whose walk or token stream moved | 0 of 1,165 | 0 of 1,868 |++Every one of those 15 findings was the grammar rather than the test, which is+why the marker declined `.tsx` files until now. The second corpus's one new+finding is a test that genuinely asserts nothing, hidden by that same rule.++Two calibrated markers read the same walk, and both read it through the+name-keyed `function_metrics`, which keeps one row per distinct function name+and so drops all but one of a file's anonymous `it` callbacks. That key is the+thing to understand here. Recovery had been swallowing whole source spans into+each callback's *name*, and those accidentally unique names were defeating it,+so a `.tsx` file kept rows that a `.ts` file has always lost. Counting names+longer than 60 characters as a proxy for that wreckage: 124 of them on the first+corpus, 0 after. Measured as the share of walked functions that survive the key,+`.tsx` goes from 44.4% to 22.9%, against a `.ts`/`.js` control of 16.0%.++`large_assertion_block` does not move on either corpus (0 and 0, then 1 and 1).+Its floor is fifteen assertions in one run and React cases are short, but the+same name key drops most of the newly visible runs before that floor is ever+consulted, so the floor is not the whole reason.++`duplicated_assertion_block` falls from 304 to 262 on the first corpus, and this+is a loss rather than a correction. Six of the lost findings were read by hand+and every one is a genuine run of consecutive assertions, correctly bounded; the+rows were real and the clone partner was real. What was not real is the+mechanism that kept them visible, which was a mangled name defeating a lossy+key. So `.tsx` files now under-report duplicated assertion blocks exactly as+`.ts` files always have. The corpus carries more real assertion runs after this+change, 264 to 391, and the marker reports fewer of them. Re-keying+`function_metrics` is the fix for that, it moves every calibrated marker at+once, and it is a change of its own.+Svelte and Vue stay `later` rather than following TypeScript: an SFC is walked asa TypeScript buffer, but a single-file component is essentially never a testfile, so the row would be untestable rather than useful.diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.py b/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.pyindex 014449934..fbb311177 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/assertion_free_test.py@@ -48,7 +48,7 @@ class AssertionFreeTestDetector:def detect(self, ctx: FileContext) -> list[BiomarkerResult]:if ctx.language not in SHIPPING_LANGUAGES:return []- if not is_test_file(ctx.file_path) or _jsx_parsed_without_jsx(ctx):+ if not is_test_file(ctx.file_path):return []out: list[BiomarkerResult] = []# ``all_functions``, not ``function_metrics``: name-keying collapses a@@ -75,20 +75,4 @@ class AssertionFreeTestDetector:return out-def _jsx_parsed_without_jsx(ctx: FileContext) -> bool:- """Is this a ``.tsx`` file the walk parsed with the non-JSX grammar?-- ``walker.py`` passes the language tag straight to ``_get_language``, so a- ``.tsx`` file — which arrives tagged ``typescript`` — is parsed by the- grammar that cannot read JSX, and every assertion after the first element is- lost. The root cause is that one call, which ``ingestion/parser.py`` already- gets right; fixing it there also moves the calibrated block markers, which- read low on these files today, so it is a change of its own. Until then this- marker declines to call a test assertion-free on evidence it knows is- missing. ``.jsx`` needs no guard: there is no jsx grammar, so those files are- walked by tree-sitter-javascript, which reads JSX natively.- """- return ctx.file_path.endswith(".tsx") and ctx.language == "typescript"--BIOMARKER = AssertionFreeTestDetector()diff --git a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py b/packages/core/src/repowise/core/analysis/health/complexity/test_case.pyindex 147bc5c16..d7d49af18 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/test_case.py@@ -31,8 +31,9 @@ the marker could never defend:classifies nothing, so it produces no finding rather than a guess.The verdict depends on the function node and the language, never on the file-path — ``HealthWalkCache`` keys on language and bytes, so a path-derived field-would be served from a byte-identical file elsewhere in the tree. The test-file+path. ``HealthWalkCache`` keys on bytes and the grammar alone, so a field+derived from anything else in the path would be served from a byte-identical+file elsewhere in the tree. The test-filegate stays in the biomarker, which sees ``ctx.file_path``."""diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex 0ba73d59c..522730b64 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -122,12 +122,15 @@ def walk_file(# Reuse the ingestion parser's language registry. Importing# lazily avoids pulling tree-sitter at module load time when# health is run from a context where it isn't installed.- from repowise.core.ingestion.parser import _get_language+ from repowise.core.ingestion.parser import _get_language, grammar_tag_forexcept Exception as exc:log.debug("complexity_walker_import_failed", error=str(exc))return FileComplexity(functions=[], classes=[], file_nloc=_count_file_nloc(source))- grammar = _get_language(language)+ # The grammar follows the path, the language tag does not: everything+ # below still selects its dialects by ``language``. ``engine.py`` keys the+ # walk cache on this same tag, so the two must not drift.+ grammar = _get_language(grammar_tag_for(language, abs_path))if grammar is None:return FileComplexity(functions=[], classes=[], file_nloc=_count_file_nloc(source))@@ -147,8 +150,8 @@ def walk_file(functions: list[FunctionComplexity] = []fc_by_node_id: dict[int, FunctionComplexity] = {}# Dialect first: it is a dict hit that rules out most languages before the- # byte scan. Keyed on language and bytes only, never the path, which is what- # the walk cache keys on.+ # byte scan. Keyed on the language and the bytes, never the path: above,+ # the path settles the grammar and nothing else.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,diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py b/packages/core/src/repowise/core/analysis/health/dataflow/parsing.pyindex 402049342..d89a99c2b 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py@@ -38,12 +38,12 @@ def parse_source(try:from tree_sitter import Parser- from repowise.core.ingestion.parser import _get_language+ from repowise.core.ingestion.parser import _get_language, grammar_tag_forexcept Exception as exc:log.debug("dataflow_import_failed", error=str(exc))return None- grammar = _get_language(language)+ grammar = _get_language(grammar_tag_for(language, abs_path))if grammar is None:return Nonediff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.pyindex 92485477e..3529a8b77 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py@@ -218,9 +218,12 @@ def detect_clones(cache = Noneif cache_dir is not None:+ from ..engine import HEALTH_ANALYZER_VERSIONfrom .token_cache import DuplicationTokenCache- cache = DuplicationTokenCache(cache_dir, window_tokens)+ # Imported at call time: engine imports this module. By the time a+ # caller reaches here the constant is loaded.+ cache = DuplicationTokenCache(cache_dir, window_tokens, HEALTH_ANALYZER_VERSION)cache.load()parsed_list = list(parsed_files)@@ -352,7 +355,16 @@ def _collect_windows(cached = Nonecontent_hash = ""if cache is not None:+ from repowise.core.ingestion.parser import grammar_tag_for+content_hash = hashlib.sha256(source).hexdigest()+ # The grammar joins the key where it is not the language tag: a+ # .tsx file and a byte-identical .ts file tokenize differently now,+ # and this cache and the pair index below both key on this value.+ # Every other file keys exactly as before and no entry ages out.+ grammar = grammar_tag_for(language, path)+ if grammar != language:+ content_hash = f"{grammar}:{content_hash}"cached = cache.get(content_hash)if cached is not None:diff --git a/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.pyindex b88613bff..2358b0caa 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py@@ -4,8 +4,10 @@ Tokenizing every file (a full tree-sitter re-parse plus a pure-Pythonleaf walk) and re-rolling 1M+ window hashes dominates the duplicationpass — and an incremental ``repowise update`` re-pays it for the wholerepo when a single file changed. Both outputs are pure functions of the-file *bytes* (given fixed window size and pinned hash constants), so they-cache safely by content hash.+file *bytes* and the grammar it is read with (given fixed window size and+pinned hash constants), so they cache safely by the key the detector builds+from the two. The grammar is a second term only for a file whose extension+picks a grammar its language tag does not, which today means ``.tsx``.Cached per file: the normalized token-kind sequence (all the verifierever compares), the non-blank line count, and the rolling-hash windows@@ -37,9 +39,13 @@ _CACHE_FILENAME = "duplication_cache.pkl"class DuplicationTokenCache:"""Pickle-backed ``content_hash -> (kinds, nloc, windows)`` store."""- def __init__(self, cache_dir: Path, window_tokens: int) -> None:+ def __init__(self, cache_dir: Path, window_tokens: int, analyzer_version: int) -> None:self._path = Path(cache_dir) / _CACHE_FILENAMEself._window_tokens = window_tokens+ # A tokenizer change alters these streams for the same bytes, and+ # nothing else in the payload would notice. The walk cache next door+ # has carried this stamp for the same reason since it existed.+ self._analyzer_version = analyzer_versionself._entries: dict[str, tuple[list[str], int, list[tuple[int, int, int, int]]]] = {}self._fresh: dict[str, tuple[list[str], int, list[tuple[int, int, int, int]]]] = {}self.hits = 0@@ -53,6 +59,7 @@ class DuplicationTokenCache:if (payload.get("version") != _CACHE_VERSIONor payload.get("window_tokens") != self._window_tokens+ or payload.get("analyzer_version") != self._analyzer_version):returnself._entries = payload.get("files", {})@@ -67,6 +74,7 @@ class DuplicationTokenCache:payload = {"version": _CACHE_VERSION,"window_tokens": self._window_tokens,+ "analyzer_version": self._analyzer_version,"files": self._fresh,}dump_sealed_pickle(self._path, payload, domain=_CACHE_FILENAME)diff --git a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.pyindex 4501c0aeb..69cc812a2 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py@@ -157,18 +157,18 @@ def tokenize_file(language: str, source: bytes, path: str | None = None) -> listReturns an empty list when the language is unsupported or parsingfails — callers treat that as "no clone candidates from this file".- ``path`` is only used by languages whose sanitizer needs it (Pascal,- to gate its project-file sanitizer on the extension); omit it for- everything else.+ ``path`` selects the grammar where the language tag does not settle it+ (a ``.tsx`` file is tagged ``typescript`` and needs the JSX grammar) and+ gates Pascal's project-file sanitizer. Omitting it costs both."""try:from tree_sitter import Parser- from repowise.core.ingestion.parser import _get_language+ from repowise.core.ingestion.parser import _get_language, grammar_tag_forexcept Exception:return []- grammar = _get_language(language)+ grammar = _get_language(grammar_tag_for(language, path or ""))if grammar is None:return []try:diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 517579175..e6013779c 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -100,7 +100,19 @@ log = structlog.get_logger(__name__)# Not a licence to move a calibrated scoring weight — those are frozen# independently of this stamp.#-# Current stamp: ``assertion_free_test`` landed, and the walker records two new+# Current stamp: the health pass reads a ``.tsx`` file with the JSX grammar.+# It arrives tagged ``typescript``, and the grammar that tag selects errors on+# the first ``<Component />``, so a cached v15 walk stored an ERROR-recovered+# tree. Three things stored under it change for ``.tsx`` files and nothing+# else: ``assertion_count`` and ``assertion_blocks`` (assertions after the+# first element were not seen at all), the clone token stream the duplication+# detector hashes, and the dataflow CFG. Function names change too -- recovery+# swallowed whole source spans into the callee name, and those accidentally+# unique names were defeating ``function_metrics``' name key, so the two+# calibrated block markers see a ``.tsx`` file the way they have always seen a+# ``.ts`` one. Non-``.tsx`` files are byte-identical, verified file for file.+#+# v15: ``assertion_free_test`` landed, and the walker records two new# ``FunctionComplexity`` fields for it (``verification_count``, ``is_test_case``)# that a cached v14 walk does not carry. It also widens ``assertion_count`` in# every language that counts assertions at all -- a ``with`` header, a@@ -144,7 +156,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 = 15+HEALTH_ANALYZER_VERSION = 16# 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.@@ -973,8 +985,13 @@ class HealthAnalyzer:key = Noneif self._walk_cache is not None:from repowise.core.ingestion import compute_content_hash+ from repowise.core.ingestion.parser import grammar_tag_for- key = HealthWalkCache.key(language, compute_content_hash(source), vocab.key)+ # The grammar, not the language: a .tsx file and a byte-identical+ # .ts file are walked by different grammars and must key apart.+ key = HealthWalkCache.key(+ grammar_tag_for(language, path), compute_content_hash(source), vocab.key+ )cached = self._walk_cache.get(key)if cached is not None:return cacheddiff --git a/packages/core/src/repowise/core/analysis/health/walk_cache.py b/packages/core/src/repowise/core/analysis/health/walk_cache.pyindex 2cb946cbf..a87fd909b 100644--- a/packages/core/src/repowise/core/analysis/health/walk_cache.py+++ b/packages/core/src/repowise/core/analysis/health/walk_cache.py@@ -1,6 +1,6 @@"""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+The walk over a file is a pure function of its bytes, its grammar and thewalker's version (and, where a repository configures one, its assertionvocabulary -- see :meth:`HealthWalkCache.key`), and on an update most of thefiles the health pass walks@@ -33,7 +33,7 @@ _CACHE_VERSION = 1class HealthWalkCache:- """``(language, content hash) -> pickled FileComplexity`` for one repository.+ """``(grammar, content hash) -> pickled FileComplexity`` for one repository.``load`` reads the previous run's entries; ``get`` and ``put`` serve thewalk; ``save`` writes back the entries this run used or created, so a file@@ -49,18 +49,22 @@ class HealthWalkCache:self.misses = 0@staticmethod- def key(language: str, content_hash: str, vocabulary: str = "") -> str:+ def key(grammar: str, content_hash: str, vocabulary: str = "") -> str:"""The cache key, optionally qualified by a configured vocabulary.+ *grammar* is the tree-sitter grammar the walk used, which for ``.tsx``+ is not the file's language tag. Keying on the language instead would+ serve a ``.tsx`` walk for a byte-identical ``.ts`` file.+A repository that configures an assertion vocabulary breaks the "bytes- plus language plus version" purity this cache rests on, so the+ plus grammar plus version" purity this cache rests on, so thevocabulary joins the key and an edit to it simply misses and ages out.Empty is the overwhelmingly common case and keys exactly as before, sono existing cache is invalidated by this parameter existing."""if not vocabulary:- return f"{language}:{content_hash}"- return f"{language}:{content_hash}:{vocabulary}"+ return f"{grammar}:{content_hash}"+ return f"{grammar}:{content_hash}:{vocabulary}"def load(self) -> None:try:diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 27a114e90..cf523cd3a 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -945,6 +945,21 @@ def _get_language(tag: str) -> Language | None:return _LANGUAGE_REGISTRY.get(tag)+def grammar_tag_for(language: str, path: str) -> str:+ """The grammar a file is read with, which is not always its language tag.++ A ``.tsx`` file arrives tagged ``typescript``, and tree-sitter-typescript's+ default grammar errors on every ``<Component />``. Only the grammar moves:+ the language tag keeps selecting dialects and vocabularies, several of+ which (``mocks/lexicon.py`` among them) carry no ``tsx`` row and would+ silently degrade if handed one.+ """+ # Case-folded, because the extension table that tagged the file is.+ if language == "typescript" and path.lower().endswith(".tsx"):+ return "tsx"+ return language++# Private alias for internal use (kept for compatibility with _find_parent)_node_text = node_text@@ -998,11 +1013,10 @@ class ASTParser:return parsedconfig = LANGUAGE_CONFIGS.get(lang)- # .tsx files need the JSX-aware grammar; tree-sitter-typescript's- # default `language_typescript` errors out on every `<Component />`- # and the resulting ERROR-node recovery hoists nested helpers- # (handlers defined inside component bodies) to the top level.- grammar_tag = "tsx" if lang == "typescript" and file_info.path.endswith(".tsx") else lang+ # .tsx needs the JSX-aware grammar: the default one's ERROR-node+ # recovery hoists nested helpers (handlers defined inside component+ # bodies) to the top level.+ grammar_tag = grammar_tag_for(lang, file_info.path)language = _get_language(grammar_tag)# tree-sitter-fsharp ships a second grammar (``language_signature``)diff --git a/tests/unit/health/test_assertion_free_test.py b/tests/unit/health/test_assertion_free_test.pyindex 7f14d0abf..48bee2f8f 100644--- a/tests/unit/health/test_assertion_free_test.py+++ b/tests/unit/health/test_assertion_free_test.py@@ -143,7 +143,7 @@ def test_a_language_with_no_row_classifies_nothing() -> None:def test_is_test_case_does_not_read_the_path() -> None:_require("python")- # ``HealthWalkCache`` keys on language and bytes with no path component, so+ # ``HealthWalkCache`` keys on the grammar and bytes with no path component, so# a path-derived field would be served from a byte-identical file elsewhere.body = b"def test_bare():\n do()\n"in_tests = walk_file("tests/test_a.py", "python", body)@@ -392,11 +392,11 @@ def test_js_verification_counts_through_the_narrow_tier() -> None:assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]-def test_silent_on_a_jsx_file_walked_without_the_jsx_grammar() -> None:+def test_a_tsx_file_tagged_typescript_reads_its_assertions() -> None:_require("typescript")- # A ``.tsx`` file arrives tagged ``typescript`` and loses its assertions to- # the non-JSX grammar, so every finding on one would be this bug rather- # than a real result. The guard lapses once the tag is right.+ # A ``.tsx`` file arrives tagged ``typescript``, and the grammar follows the+ # path rather than the tag. Read with the non-JSX grammar, the assertion+ # after the element is lost and this test is called assertion-free.source = ('describe("C", () => {\n'' it("renders", () => {\n'@@ -406,11 +406,19 @@ def test_silent_on_a_jsx_file_walked_without_the_jsx_grammar() -> None:"});\n")assert _flagged(source, "src/C.spec.tsx", "typescript") == []- # Walked as tsx the assertion is visible, so the guard must not apply.assert _flagged(source, "src/C.spec.tsx", "tsx") == []+ # A genuinely bare one still fires, under either tag.bare = 'describe("C", () => { it("bare", () => { render(<A />); }); });\n'assert _flagged(bare, "src/C.spec.tsx", "tsx") == ["it callback"]- assert _flagged(bare, "src/C.spec.tsx", "typescript") == []+ assert _flagged(bare, "src/C.spec.tsx", "typescript") == ["it callback"]+++def test_a_ts_path_keeps_the_typescript_grammar() -> None:+ _require("typescript")+ # The mirror of the above: ``<T,>`` is a type parameter and not an element,+ # so the tsx grammar is the one that would misread it.+ source = 'const id = <T,>(x: T): T => x;\nit("bare", () => { id(1); });\n'+ assert _flagged(source, "src/x.test.ts", "typescript") == ["it callback"]def test_a_private_assertion_helper_counts() -> None:diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.pyindex 75ed2d42b..d32c9793b 100644--- a/tests/unit/health/test_dataflow_langs.py+++ b/tests/unit/health/test_dataflow_langs.py@@ -1388,3 +1388,23 @@ def test_hoisted_binding_precompute_matches_the_direct_test() -> None:precomputed = any(low <= d <= high and u < low for d, u in hoisted)assert precomputed == directly(def_lines, use_lines, low, high)assert compared, "the corpus produced no spans to compare"+++def test_tsx_parses_without_error_recovery() -> None:+ """A .tsx file is tagged ``typescript`` and needs the JSX grammar here too.++ Read without it, every element lands in ERROR recovery and the CFG is built+ over a tree that does not describe the file.+ """+ from repowise.core.analysis.health.dataflow.parsing import parse_source++ source = b"export function C({ n }: P) {\n return <div id={n}>{n + 1}</div>;\n}\n"+ parsed = parse_source("src/C.tsx", "typescript", source)+ if parsed is None:+ pytest.skip("tree-sitter typescript pack missing")+ root, _ = parsed+ assert not root.has_error+ # The same bytes under a .ts path keep the grammar the tag alone picks.+ as_ts = parse_source("src/C.ts", "typescript", source)+ assert as_ts is not None+ assert as_ts[0].has_errordiff --git a/tests/unit/health/test_duplication.py b/tests/unit/health/test_duplication.pyindex 588dbe054..6b9c8af78 100644--- a/tests/unit/health/test_duplication.py+++ b/tests/unit/health/test_duplication.py@@ -70,6 +70,22 @@ def test_tokenize_file_drops_comments_and_normalizes_identifiers():assert not any("comment" in k for k in kinds)+def test_tokenize_file_reads_tsx_with_the_jsx_grammar():+ # A .tsx file is tagged ``typescript``, and the grammar that cannot read+ # JSX recovers from every element into ERROR nodes, so the token stream the+ # clone detector hashes is partly invented. The path settles it.+ source = b"export const C = () => <div className=\"x\">{label}</div>;\n"+ as_tsx = [t.kind for t in tokenize_file("typescript", source, "src/C.tsx")]+ as_ts = [t.kind for t in tokenize_file("typescript", source, "src/C.ts")]+ assert as_tsx == [t.kind for t in tokenize_file("tsx", source, "src/C.tsx")]+ assert as_tsx != as_ts+ # Nothing else moves: the path only settles the grammar for .tsx.+ plain = b"export const add = (a: number, b: number): number => a + b;\n"+ assert [t.kind for t in tokenize_file("typescript", plain, "src/a.ts")] == [+ t.kind for t in tokenize_file("typescript", plain, "src/a.other")+ ]++def test_tokenize_file_pascal_normalizes_identifiers_and_literals():source = (b"unit U;\n interface\n implementation\n"diff --git a/tests/unit/health/test_duplication_cache.py b/tests/unit/health/test_duplication_cache.pyindex 9337e03a6..31d0de802 100644--- a/tests/unit/health/test_duplication_cache.py+++ b/tests/unit/health/test_duplication_cache.py@@ -14,6 +14,7 @@ from repowise.core.analysis.health.duplication.token_cache import (DuplicationTokenCache,)from repowise.core.analysis.health.duplication.tokenizer import Token+from repowise.core.analysis.health.engine import HEALTH_ANALYZER_VERSIONdef _pf(path: str, abs_path: str) -> SimpleNamespace:@@ -78,7 +79,7 @@ def test_second_run_hits_cache_and_edit_misses(tmp_path: Path):cache_dir = tmp_path / ".repowise"detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)- cache = DuplicationTokenCache(cache_dir, 20)+ cache = DuplicationTokenCache(cache_dir, 20, HEALTH_ANALYZER_VERSION)cache.load()import hashlib@@ -88,7 +89,7 @@ def test_second_run_hits_cache_and_edit_misses(tmp_path: Path):# Edit one file -> its hash misses; the others still hit.(tmp_path / "a.py").write_text(_BODY.replace("doit", "changed"))- fresh = DuplicationTokenCache(cache_dir, 20)+ fresh = DuplicationTokenCache(cache_dir, 20, HEALTH_ANALYZER_VERSION)fresh.load()a_digest = hashlib.sha256((tmp_path / "a.py").read_bytes()).hexdigest()assert fresh.get(a_digest) is None@@ -103,7 +104,7 @@ def test_window_size_mismatch_invalidates(tmp_path: Path):cache_dir = tmp_path / ".repowise"detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)- other = DuplicationTokenCache(cache_dir, 10)+ other = DuplicationTokenCache(cache_dir, 10, HEALTH_ANALYZER_VERSION)other.load()assert other._entries == {}@@ -120,7 +121,7 @@ def test_corrupt_cache_degrades_to_full_run(tmp_path: Path):def test_cache_shares_interned_kinds_and_can_release_memory(tmp_path: Path):- cache = DuplicationTokenCache(tmp_path, 20)+ cache = DuplicationTokenCache(tmp_path, 20, HEALTH_ANALYZER_VERSION)kinds = [bytearray(b"identifier").decode() for _ in range(2)]cache.put("digest", kinds, 1, [(1, 0, 1, 1)])diff --git a/tests/unit/health/test_duplication_incremental.py b/tests/unit/health/test_duplication_incremental.pyindex a884940ff..e07af07a3 100644--- a/tests/unit/health/test_duplication_incremental.py+++ b/tests/unit/health/test_duplication_incremental.py@@ -348,6 +348,7 @@ def test_unchanged_token_cache_entries_survive_splice(tmp_path: Path):from repowise.core.analysis.health.duplication.token_cache import (DuplicationTokenCache,)+ from repowise.core.analysis.health.engine import HEALTH_ANALYZER_VERSIONcache_dir = _seed(tmp_path, {"a.py": _BODY, "b.py": _BODY, "c.py": _OTHER})(tmp_path / "a.py").write_text(_BODY.replace("doit", "edited"))@@ -355,7 +356,7 @@ def test_unchanged_token_cache_entries_survive_splice(tmp_path: Path):report = _incremental(parsed, cache_dir, {"a.py"})assert report.diagnostics.get("incremental") is True- cache = DuplicationTokenCache(cache_dir, WINDOW)+ cache = DuplicationTokenCache(cache_dir, WINDOW, HEALTH_ANALYZER_VERSION)cache.load()for rel in ("a.py", "b.py", "c.py"):digest = hashlib.sha256((tmp_path / rel).read_bytes()).hexdigest()diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.pyindex 58ad39cf3..d9ed019a1 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 = (15, 2, 2)+_STAMPS = (16, 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.pyindex a0e13ed4d..ac25891c3 100644--- a/tests/unit/health/test_walk_cache.py+++ b/tests/unit/health/test_walk_cache.py@@ -1,6 +1,6 @@"""The walk cache answers exactly what the walk answers, and never leaks a run.-The complexity walk over a file depends on its bytes, its language and the+The complexity walk over a file depends on its bytes, its grammar and thewalker's version. The pass mutates the result it is handed, so a cached entryhas to come back pristine every time or one run's annotations would becomethe next run's input.@@ -9,11 +9,14 @@ the next run's input.from __future__ import annotationsfrom pathlib import Path+from types import SimpleNamespace+from repowise.core.analysis.health.asserts.lexicon import AssertVocabularyfrom repowise.core.analysis.health.complexity import walk_file-from repowise.core.analysis.health.engine import HEALTH_ANALYZER_VERSION+from repowise.core.analysis.health.engine import HEALTH_ANALYZER_VERSION, HealthAnalyzerfrom repowise.core.analysis.health.walk_cache import _CACHE_FILENAME, HealthWalkCachefrom repowise.core.ingestion import compute_content_hash+from repowise.core.ingestion.parser import grammar_tag_for_SRC = b"""def outer(items):@@ -131,3 +134,42 @@ def test_the_analyzer_walks_once_and_serves_the_second_pass_from_the_cache(tmp_passert [(f.biomarker_type, f.function_name) for f in first.findings] == [(f.biomarker_type, f.function_name) for f in second.findings]+++def test_a_tsx_and_a_byte_identical_ts_file_key_apart() -> None:+ # The walk reads .tsx with the JSX grammar and .ts without it, so the same+ # bytes under the two paths are two different walks and must not share a+ # key. Both arrive tagged ``typescript``, which is why the tag alone cannot+ # separate them.+ src = b'it("x", () => { render(1); });\n'+ digest = compute_content_hash(src)+ as_ts = HealthWalkCache.key(grammar_tag_for("typescript", "src/a.ts"), digest)+ as_tsx = HealthWalkCache.key(grammar_tag_for("typescript", "src/a.tsx"), digest)+ assert as_ts != as_tsx+ # Every other language keys exactly as it did before.+ assert HealthWalkCache.key(grammar_tag_for("python", "a.py"), digest) == f"python:{digest}"+++def test_the_walk_itself_does_not_serve_a_ts_file_to_a_tsx_file(tmp_path: Path) -> None:+ # The key helper is checked above; this drives the line that uses it, so a+ # revert to keying on the language tag fails here rather than passing.+ src = b'const C = () => <div>{label}</div>;\nit("t", () => { render(<C />); });\n'+ cache = HealthWalkCache(tmp_path, HEALTH_ANALYZER_VERSION)+ analyzer = SimpleNamespace(read_source=lambda _p: src, _walk_cache=cache)++ def parsed(name: str):+ return SimpleNamespace(+ file_info=SimpleNamespace(abs_path=str(tmp_path / name), language="typescript")+ )++ vocab = AssertVocabulary()+ as_ts = HealthAnalyzer._walk(analyzer, parsed("a.ts"), vocab)+ as_tsx = HealthAnalyzer._walk(analyzer, parsed("a.tsx"), vocab)++ # Two misses: the second file was walked, not served the first one's entry.+ assert cache.misses == 2+ assert cache.hits == 0+ # And the two walks really do differ, or the assertion above proves nothing.+ ts_asserts = sum(f.assertion_count for f in as_ts.functions)+ tsx_asserts = sum(f.assertion_count for f in as_tsx.functions)+ assert (len(as_ts.functions), ts_asserts) != (len(as_tsx.functions), tsx_asserts)