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): verify clone pairs on identifiers, not shape alone (#2693)
Swati Ahuja6cbfd651415e
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.pyindex d955a1880..6287efaaa 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py@@ -71,6 +71,9 @@ class FileContext:# is the percent of NLOC covered by clones.clones: list[ClonePair] = field(default_factory=list)duplication_pct: float | None = None+ # Source lines of this file and its clone partners, by repo path. Filled+ # only for a test file with clones; a missing path means "not read".+ clone_sources: dict[str, list[str]] = field(default_factory=dict)# Thin graph view exposing only ``has_edge``. ``None`` on test fixtures# that never construct a graph.graph_view: HasEdge | None = Nonediff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py b/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.pyindex 8c7a8e949..09a575ef2 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py@@ -4,7 +4,9 @@ When the same run of assertions appears in more than one test, a change tothe asserted behaviour has to be edited in several places — and usuallyisn't, so the copies drift. This biomarker reuses the engine's Rabin-Karpclone detector (``ctx.clones``) and keeps only the clone regions that-overlap an assertion block on a **test file**.+overlap an assertion block on a **test file**, and only when the block's+text, whitespace aside, really appears in the partner region. Clones match+on token shape, so without that check two asserts on different values pair up.It complements ``dry_violation`` (which flags clones anywhere, weighted byco-change): this one is scoped to test assertions and lands in the milder@@ -22,6 +24,34 @@ def _overlaps(a_start: int, a_end: int, b_start: int, b_end: int) -> bool:return a_start <= b_end and b_start <= a_end+def _normalized(lines: list[str], start: int, end: int) -> str:+ """Lines ``start..end`` (1-indexed, inclusive) with whitespace collapsed."""+ return " ".join(" ".join(lines[max(start, 1) - 1 : end]).split())+++def _block_copied(+ ctx: FileContext,+ block: tuple[int, int],+ span: tuple[int, int],+ partner: str,+ partner_span: tuple[int, int],+) -> bool:+ """Does the whole assertion *block* appear verbatim (whitespace aside) in+ the partner region, widened by however far the block runs past the clone?"""+ own_lines = ctx.clone_sources.get(ctx.file_path)+ partner_lines = ctx.clone_sources.get(partner)+ if own_lines is None or partner_lines is None:+ return False+ (bs, be), (cs, ce) = block, span+ lo = partner_span[0] - max(0, cs - bs)+ hi = partner_span[1] + max(0, be - ce)+ # An intra-file clone overlapping itself would find the block in place.+ if partner == ctx.file_path and _overlaps(lo, hi, bs, be):+ return False+ text = _normalized(own_lines, bs, be)+ return bool(text) and f" {text} " in f" {_normalized(partner_lines, lo, hi)} "++class DuplicatedAssertionBlockDetector:name = "duplicated_assertion_block"category = "test_quality"@@ -40,15 +70,18 @@ class DuplicatedAssertionBlockDetector:out: list[BiomarkerResult] = []seen: set[tuple[int, int]] = set()for clone in ctx.clones:- spans: list[tuple[int, int]] = []+ a_span = (clone.a_start_line, clone.a_end_line)+ b_span = (clone.b_start_line, clone.b_end_line)+ sides: list[tuple[tuple[int, int], str, tuple[int, int]]] = []if clone.file_a == ctx.file_path:- spans.append((clone.a_start_line, clone.a_end_line))+ sides.append((a_span, clone.file_b, b_span))if clone.file_b == ctx.file_path:- spans.append((clone.b_start_line, clone.b_end_line))- partner = clone.file_b if clone.file_a == ctx.file_path else clone.file_a- for cs, ce in spans:+ sides.append((b_span, clone.file_a, a_span))+ for span, partner, partner_span in sides:for bs, be in blocks:- if not _overlaps(cs, ce, bs, be) or (bs, be) in seen:+ if not _overlaps(*span, bs, be) or (bs, be) in seen:+ continue+ if not _block_copied(ctx, (bs, be), span, partner, partner_span):continueseen.add((bs, be))out.append(diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.pyindex 3529a8b77..6e5d1db47 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py@@ -3,9 +3,11 @@Pipeline:1. Tokenize every parsed file with the duplication ``tokenizer``.-2. Rolling-hash each token stream into fixed-size windows.+2. Rolling-hash each token stream into fixed-size windows, dropping+ windows made almost entirely of literals and punctuation (data tables).3. Bucket windows by hash; for each multi-window bucket, verify token- equality (hash collision-proof) and emit a ``ClonePair``.+ equality (hash collision-proof) and that the two windows share most of+ their raw identifier names, then emit a ``ClonePair``.4. Merge adjacent windows in the same (file_a, file_b) pair into asingle contiguous clone region.5. Weight active vs dormant clone pairs using@@ -24,6 +26,7 @@ import timefrom collections import defaultdictfrom collections.abc import Iterablefrom dataclasses import dataclass, field+from itertools import accumulatefrom pathlib import Pathfrom typing import Any@@ -43,6 +46,15 @@ log = structlog.get_logger(__name__)DEFAULT_WINDOW_TOKENS = 50DEFAULT_MIN_LINES = 6+# A window above this share of literal/punctuation tokens is a data literal.+_MAX_NOISE_SHARE = 0.8+# Same shape with mostly different names is not copied code.+_MIN_NAME_JACCARD = 0.5++# One file's token stream: (normalized kinds, raw identifier names). The+# lists are parallel; ``names[i]`` is empty unless token ``i`` is an ``ID``.+_Stream = tuple[list[str], list[str]]+@dataclass(slots=True)class ClonePair:@@ -120,22 +132,37 @@ def _co_change_score(return max(_partner_support(a_meta, file_b), _partner_support(b_meta, file_a))-def _tokens_equal(- a_kinds: list[str],- b_kinds: list[str],- a_start: int,- b_start: int,- window: int,-) -> bool:- """Verify hash-collision by comparing token ``kind`` sequences.+def _is_noise(kind: str) -> bool:+ return kind == "LIT" or not any(ch.isalnum() for ch in kind)+++def _informative_windows(+ windows: list[WindowHash], kinds: list[str], window: int+) -> list[WindowHash]:+ """Drop windows that are more than ``_MAX_NOISE_SHARE`` literals/punctuation."""+ noise = list(accumulate((_is_noise(k) for k in kinds), initial=0))+ limit = _MAX_NOISE_SHARE * window+ return [w for w in windows if noise[w.start_index + window] - noise[w.start_index] <= limit]- Operates on the per-file kind list (all the verifier ever compared of- the full ``Token`` records) so cached token streams round-trip without- rebuilding Token objects.++def _windows_match(a: _Stream, b: _Stream, a_start: int, b_start: int, window: int) -> bool:+ """Confirm a hash match: equal token kinds, then shared identifier names.++ Operates on the per-file streams so cached token streams round-trip+ without rebuilding Token objects."""+ a_kinds, a_names = a+ b_kinds, b_names = bif a_start + window > len(a_kinds) or b_start + window > len(b_kinds):return False- return a_kinds[a_start : a_start + window] == b_kinds[b_start : b_start + window]+ if a_kinds[a_start : a_start + window] != b_kinds[b_start : b_start + window]:+ return False+ a_set = set(a_names[a_start : a_start + window])+ b_set = set(b_names[b_start : b_start + window])+ a_set.discard("")+ b_set.discard("")+ union = len(a_set | b_set)+ return union > 0 and len(a_set & b_set) >= _MIN_NAME_JACCARD * uniondef _merge_adjacent_pairs(raw: list[ClonePair]) -> list[ClonePair]:@@ -251,14 +278,14 @@ def detect_clones(# Fall through to the full pipeline; it refreshes the artifact.diag = DuplicationDiagnostics()- per_file_kinds, per_file_nloc, all_windows, per_file_hash = _collect_windows(+ per_file_streams, per_file_nloc, all_windows, per_file_hash = _collect_windows(parsed_list, window_tokens, lim, diag, cache, source_reader)if cache is not None:cache.save()# The persisted form holds another representation of every token# stream and window. Collision verification only needs the returned- # per-file kinds, so release the cache's owning dictionaries before+ # per-file streams, so release the cache's owning dictionaries before# allocating the repo-wide hash index and clone-pair lists.cache.release_memory()log.debug(@@ -273,7 +300,7 @@ def detect_clones(# Every WindowHash is now owned by a bucket. Keeping the flat list too# adds millions of redundant references at the scan's high-water mark.del all_windows- raw_pairs = _pairs_from_buckets(bucket, per_file_kinds, window_tokens, lim, diag)+ raw_pairs = _pairs_from_buckets(bucket, per_file_streams, window_tokens, lim, diag)if cache is not None and cache_dir is not None:all_paths = {pf.file_info.path for pf in parsed_list}@@ -282,7 +309,7 @@ def detect_clones(window_tokens,lim,diag,- per_file_kinds,+ per_file_streams,per_file_hash,raw_pairs,all_paths,@@ -291,7 +318,7 @@ def detect_clones(# Neither structure participates in merge/finalize/aggregation. Drop# them before those stages allocate their output lists so freed arenas# can be reused inside this phase rather than growing the process again.- del bucket, per_file_kinds+ del bucket, per_file_streamsfinal = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)@@ -316,8 +343,8 @@ def _collect_windows(diag: DuplicationDiagnostics,cache: Any | None = None,read_source: Any | None = None,-) -> tuple[dict[str, list[str]], dict[str, int], list[WindowHash], dict[str, str]]:- """Tokenize each file once and emit its rolling-hash windows.+) -> tuple[dict[str, _Stream], dict[str, int], list[WindowHash], dict[str, str]]:+ """Tokenize each file once and emit its informative rolling-hash windows.Files are dropped (and counted in *diag*) when they are unreadable,minified/generated, shorter than one window, or exceed the per-file@@ -326,14 +353,14 @@ def _collect_windows(When a :class:`~.token_cache.DuplicationTokenCache` is supplied,unchanged files (by content hash) skip the tokenize + rolling-hash- work and replay their cached kind sequence and window tuples; every+ work and replay their cached stream and window tuples; everygate above still re-evaluates live against the cached lengths. Thereturned hash map (path -> content hash, gate survivors only) feedsthe persisted pair index; it is empty when no cache is supplied."""import hashlib- per_file_kinds: dict[str, list[str]] = {}+ per_file_streams: dict[str, _Stream] = {}per_file_nloc: dict[str, int] = {}all_windows: list[WindowHash] = []per_file_hash: dict[str, str] = {}@@ -368,7 +395,7 @@ def _collect_windows(cached = cache.get(content_hash)if cached is not None:- kinds, nloc, window_tuples = cached+ kinds, names, nloc, window_tuples = cachedwindows = [WindowHash(file_path=path,@@ -385,12 +412,16 @@ def _collect_windows(diag.skipped_token_cap += 1continuekinds = [t.kind for t in toks]+ names = [t.name for t in toks]nloc = _nloc(source)- windows = rolling_hashes(path, toks, window_tokens)+ windows = _informative_windows(+ rolling_hashes(path, toks, window_tokens), kinds, window_tokens+ )if cache is not None:cache.put(content_hash,kinds,+ names,nloc,[(w.hash_value, w.start_index, w.start_line, w.end_line) for w in windows],)@@ -405,7 +436,7 @@ def _collect_windows(diag.window_budget_hit = Truebreak- per_file_kinds[path] = kinds+ per_file_streams[path] = (kinds, names)per_file_nloc[path] = nlocall_windows.extend(windows)if content_hash:@@ -413,7 +444,7 @@ def _collect_windows(diag.files_tokenized += 1diag.total_windows = len(all_windows)- return per_file_kinds, per_file_nloc, all_windows, per_file_hash+ return per_file_streams, per_file_nloc, all_windows, per_file_hash# ---------------------------------------------------------------------------@@ -423,7 +454,7 @@ def _collect_windows(def _pairs_from_buckets(bucket: dict[int, list[WindowHash]],- per_file_kinds: dict[str, list[str]],+ per_file_streams: dict[str, _Stream],window_tokens: int,limits: DuplicationLimits,diag: DuplicationDiagnostics,@@ -452,22 +483,22 @@ def _pairs_from_buckets(if deadline is not None and (i & 0x3FF) == 0 and time.monotonic() > deadline:diag.timed_out = Truebreak- _verify_bucket(windows, per_file_kinds, window_tokens, seen, raw_pairs)+ _verify_bucket(windows, per_file_streams, window_tokens, seen, raw_pairs)return raw_pairsdef _verify_bucket(windows: list[WindowHash],- per_file_kinds: dict[str, list[str]],+ per_file_streams: dict[str, _Stream],window_tokens: int,seen: set[tuple[str, int, str, int]],out: list[ClonePair],) -> None:"""Confirm every unordered pair in one (bounded) hash bucket.- Hash equality is necessary but not sufficient — ``_tokens_equal``- rejects collisions by comparing the actual token sequences.+ Hash equality is necessary but not sufficient — ``_windows_match``+ rejects collisions and renamed look-alikes."""for i in range(len(windows)):for j in range(i + 1, len(windows)):@@ -479,9 +510,9 @@ def _verify_bucket(if key in seen:continueseen.add(key)- if not _tokens_equal(- per_file_kinds[a.file_path],- per_file_kinds[b.file_path],+ if not _windows_match(+ per_file_streams[a.file_path],+ per_file_streams[b.file_path],a.start_index,b.start_index,window_tokens,@@ -571,41 +602,41 @@ def _detect_clones_incremental(# 1. Collect the changed files live (read, gates, tokenize, windows).# Sorted for deterministic window-budget behaviour.changed_pfs = [current[p] for p in sorted(changed)]- new_kinds, new_nloc, new_windows, new_hash = _collect_windows(+ new_streams, new_nloc, new_windows, new_hash = _collect_windows(changed_pfs, window_tokens, lim, diag, cache, read_source)if diag.window_budget_hit:return None- # 2. Old windows + kinds of affected files, from the token cache.- old_aff: dict[str, tuple[list[str], list[tuple[int, int, int, int]]]] = {}+ # 2. Old windows + streams of affected files, from the token cache.+ old_aff: dict[str, tuple[_Stream, list[tuple[int, int, int, int]]]] = {}for p in affected_old:entry = cache.entry(old_files[p])if entry is None:return None- kinds, _nloc, window_tuples = entry- old_aff[p] = (kinds, window_tuples)+ kinds, names, _nloc, window_tuples = entry+ old_aff[p] = ((kinds, names), window_tuples)# 3. Window-budget equivalence: splicing is only valid when the full# pipeline would not truncate either state.- n_old_aff = sum(len(wt) for _k, wt in old_aff.values())+ n_old_aff = sum(len(wt) for _s, wt in old_aff.values())if index.total_windows - n_old_aff + len(new_windows) > lim.max_total_windows:return None# 4. Touched buckets = hashes present in moving windows (old or new).touched: set[int] = {w.hash_value for w in new_windows}- for _kinds, window_tuples in old_aff.values():+ for _stream, window_tuples in old_aff.values():touched.update(row[0] for row in window_tuples)# 5. One pass over the unchanged files' cached windows builds the# touched buckets' membership; rows of unchanged files belong to- # both the old and the new bucket composition. Kinds maps are- # split because a modified file verifies with its old kinds on- # the old side and its new kinds on the new side.+ # both the old and the new bucket composition. Stream maps are+ # split because a modified file verifies with its old stream on+ # the old side and its new stream on the new side.old_rows: dict[int, list[WindowHash]] = defaultdict(list)new_rows: dict[int, list[WindowHash]] = defaultdict(list)- old_kinds_map: dict[str, list[str]] = {}- new_kinds_map: dict[str, list[str]] = dict(new_kinds)+ old_streams_map: dict[str, _Stream] = {}+ new_streams_map: dict[str, _Stream] = dict(new_streams)per_file_nloc: dict[str, int] = dict(new_nloc)for p in unchanged:check_cancelled()@@ -613,7 +644,7 @@ def _detect_clones_incremental(entry = cache.entry(h)if entry is None:return None- kinds, nloc, window_tuples = entry+ kinds, names, nloc, window_tuples = entryper_file_nloc[p] = nlochit = Falsefor row in window_tuples:@@ -629,11 +660,11 @@ def _detect_clones_incremental(new_rows[row[0]].append(w)hit = Trueif hit:- old_kinds_map[p] = kinds- new_kinds_map[p] = kinds+ old_streams_map[p] = (kinds, names)+ new_streams_map[p] = (kinds, names)cache.retain(h)- for p, (kinds, window_tuples) in old_aff.items():+ for p, (stream, window_tuples) in old_aff.items():for row in window_tuples:if row[0] in touched:old_rows[row[0]].append(@@ -645,13 +676,13 @@ def _detect_clones_incremental(end_line=row[3],))- old_kinds_map[p] = kinds+ old_streams_map[p] = streamfor w in new_windows:new_rows[w.hash_value].append(w)# 6. Per-bucket contributions, old and new.- old_contrib = _bucket_contributions(old_rows, old_kinds_map, window_tokens, lim, None)- new_contrib = _bucket_contributions(new_rows, new_kinds_map, window_tokens, lim, diag)+ old_contrib = _bucket_contributions(old_rows, old_streams_map, window_tokens, lim, None)+ new_contrib = _bucket_contributions(new_rows, new_streams_map, window_tokens, lim, diag)# 7. Splice the multiset. A negative count means the persisted state# disagrees with the recomputed old contribution — fall back.@@ -734,7 +765,7 @@ def _pair_key(p: ClonePair) -> _PairKey:def _bucket_contributions(rows_by_hash: dict[int, list[WindowHash]],- kinds_map: dict[str, list[str]],+ streams_map: dict[str, _Stream],window_tokens: int,lim: DuplicationLimits,diag: DuplicationDiagnostics | None,@@ -758,7 +789,7 @@ def _bucket_contributions(diag.degenerate_buckets += 1continuecheck_cancelled()- _verify_bucket(rows, kinds_map, window_tokens, seen, out)+ _verify_bucket(rows, streams_map, window_tokens, seen, out)return out@@ -767,7 +798,7 @@ def _persist_pair_index(window_tokens: int,lim: DuplicationLimits,diag: DuplicationDiagnostics,- per_file_kinds: dict[str, list[str]],+ per_file_streams: dict[str, _Stream],per_file_hash: dict[str, str],raw_pairs: list[ClonePair],all_paths: set[str],@@ -777,8 +808,8 @@ def _persist_pair_index(from .pair_index import DuplicationPairIndex, limits_fingerprint, save_pair_index- files = {p: per_file_hash[p] for p in per_file_kinds if p in per_file_hash}- if len(files) != len(per_file_kinds):+ files = {p: per_file_hash[p] for p in per_file_streams if p in per_file_hash}+ if len(files) != len(per_file_streams):# A gate survivor without a content hash should be impossible# when the cache is active; don't persist a state we can't trust.returndiff --git a/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py b/packages/core/src/repowise/core/analysis/health/duplication/pair_index.pyindex 4141e32ae..1f0950a5f 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py@@ -40,7 +40,7 @@ from .limits import DuplicationLimitslog = structlog.get_logger(__name__)-_INDEX_VERSION = 1+_INDEX_VERSION = 2_INDEX_FILENAME = "duplication_pairs.pkl"# One raw-pair multiset entry as a path-id row: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 2358b0caa..2a6faeb93 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@@ -9,9 +9,9 @@ pinned hash constants), so they cache safely by the key the detector buildsfrom the two. The grammar is a second term only for a file whose extensionpicks a grammar its language tag does not, which today means ``.tsx``.-Cached per file: the normalized token-kind sequence (all the verifier-ever compares), the non-blank line count, and the rolling-hash windows-as plain tuples (``WindowHash`` is rebuilt with the file's *current*+Cached per file: the normalized token-kind sequence and the parallel raw+identifier names (all the verifier ever compares), the non-blank line+count, and the rolling-hash windows as plain tuples (``WindowHash`` is rebuilt with the file's *current*path, which makes hits rename-proof). The minified/token-cap/window-budget gates in the detector stay live — they re-evaluate against thecached lengths, so config changes apply to cached entries too.@@ -32,12 +32,15 @@ from repowise.core.cache_seal import dump_sealed_pickle, load_sealed_picklelog = structlog.get_logger(__name__)-_CACHE_VERSION = 1+_CACHE_VERSION = 2_CACHE_FILENAME = "duplication_cache.pkl"+# (kinds, identifier names, nloc, window tuples)+_Entry = tuple[list[str], list[str], int, list[tuple[int, int, int, int]]]+class DuplicationTokenCache:- """Pickle-backed ``content_hash -> (kinds, nloc, windows)`` store."""+ """Pickle-backed ``content_hash -> (kinds, names, nloc, windows)`` store."""def __init__(self, cache_dir: Path, window_tokens: int, analyzer_version: int) -> None:self._path = Path(cache_dir) / _CACHE_FILENAME@@ -46,8 +49,8 @@ class DuplicationTokenCache:# 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_version- self._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._entries: dict[str, _Entry] = {}+ self._fresh: dict[str, _Entry] = {}self.hits = 0self.misses = 0@@ -93,9 +96,7 @@ class DuplicationTokenCache:# -- access ------------------------------------------------------------- def get(- self, content_hash: str- ) -> tuple[list[str], int, list[tuple[int, int, int, int]]] | None:+ def get(self, content_hash: str) -> _Entry | None:entry = self._entries.get(content_hash)if entry is None:self.misses += 1@@ -105,9 +106,7 @@ class DuplicationTokenCache:self._fresh[content_hash] = entryreturn entry- def entry(- self, content_hash: str- ) -> tuple[list[str], int, list[tuple[int, int, int, int]]] | None:+ def entry(self, content_hash: str) -> _Entry | None:"""Read an entry without touching hit/miss stats or freshness.The incremental pair-splice path reads unchanged files' cached@@ -133,6 +132,7 @@ class DuplicationTokenCache:self,content_hash: str,kinds: list[str],+ names: list[str],nloc: int,windows: list[tuple[int, int, int, int]],) -> None:@@ -141,6 +141,6 @@ class DuplicationTokenCache:# Identity reuse also keeps the pickle compact and comparisons cheap.for index, kind in enumerate(kinds):kinds[index] = sys.intern(kind)- entry = (kinds, nloc, windows)+ entry = (kinds, names, nloc, windows)self._entries[content_hash] = entryself._fresh[content_hash] = entrydiff --git a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.pyindex 69cc812a2..1ea0a96e8 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py@@ -7,6 +7,8 @@ per leaf node, excluding:- comment nodes (``comment``, ``line_comment``, ``block_comment``,``doc_comment``)- syntax-error and missing nodes+- import statements and re-exports (``export ... from``): every file opens+ with one, so they pair up without being duplicated logicTwo normalization knobs control how aggressive matching is:@@ -17,7 +19,8 @@ Two normalization knobs control how aggressive matching is:reason; string content is rarely the meaningful signal in a clone.Operators and keywords pass through as their literal token text so we-preserve structure.+preserve structure. Each identifier token also keeps its raw text in+``Token.name`` so a hash match can be checked against the real names."""from __future__ import annotations@@ -83,6 +86,11 @@ _LITERAL_KINDS = frozenset()+# Config "import" kinds that also cover real code: generic calls or commands+# (Ruby ``require``, shell ``source``) and GDScript's superclass clause.+_NOT_IMPORT_KINDS = frozenset({"call", "command", "function_call", "extends_statement"})++@dataclass(frozen=True, slots=True)class Token:"""One AST token with the source location of its origin node."""@@ -92,6 +100,17 @@ class Token:end_line: int # 1-indexedstart_byte: intend_byte: int+ name: str = "" # raw identifier text; empty for every other token+++def import_node_kinds(language: str) -> frozenset[str]:+ """The language's import statement node kinds, minus ones that are real code."""+ from repowise.core.ingestion.language_configs import LANGUAGE_CONFIGS++ config = LANGUAGE_CONFIGS.get(language)+ if config is None:+ return frozenset()+ return frozenset(config.import_node_types) - _NOT_IMPORT_KINDSdef _is_skippable(node: Node) -> bool:@@ -102,17 +121,25 @@ def _is_skippable(node: Node) -> bool:return bool(getattr(node, "has_error", False) and node.child_count == 0)-def tokenize_tree(root: Node, source: bytes) -> list[Token]:+def _is_reexport(node: Node) -> bool:+ # JS/TS ``export { a } from "./b"``: an import in all but name.+ return node.type == "export_statement" and node.child_by_field_name("source") is not None+++def tokenize_tree(+ root: Node, source: bytes, skip_kinds: frozenset[str] = frozenset()+) -> list[Token]:"""Walk *root* and return the flattened token list.- Iterative DFS — uses a stack rather than recursion so very deep- files don't blow the recursion limit.+ Subtrees whose node kind is in *skip_kinds* (import statements) and+ re-exports are dropped whole. Iterative DFS — uses a stack rather than+ recursion so very deep files don't blow the recursion limit."""out: list[Token] = []stack: list[Node] = [root]while stack:node = stack.pop()- if _is_skippable(node):+ if _is_skippable(node) or node.type in skip_kinds or _is_reexport(node):continueif node.child_count == 0:tok = _tokenize_leaf(node, source)@@ -126,8 +153,10 @@ def tokenize_tree(root: Node, source: bytes) -> list[Token]:def _tokenize_leaf(node: Node, source: bytes) -> Token | None:+ name = ""if node.type in _IDENTIFIER_KINDS:kind = "ID"+ name = sys.intern(source[node.start_byte : node.end_byte].decode("utf-8", errors="replace"))elif node.type in _LITERAL_KINDS:kind = "LIT"else:@@ -149,6 +178,7 @@ def _tokenize_leaf(node: Node, source: bytes) -> Token | None:end_line=node.end_point[0] + 1,start_byte=node.start_byte,end_byte=node.end_byte,+ name=name,)@@ -181,4 +211,4 @@ def tokenize_file(language: str, source: bytes, path: str | None = None) -> listtree = parser.parse(source)except Exception:return []- return tokenize_tree(tree.root_node, source)+ return tokenize_tree(tree.root_node, source, import_node_kinds(language))diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 037298e27..82f7483ca 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -45,7 +45,7 @@ from .biomarkers import FileContext, detect_allfrom .complexity import FileComplexity, FunctionComplexity, walk_filefrom .coverage import is_test_file as _coverage_is_test_filefrom .dataflow import FileDataflowCache-from .duplication import DuplicationReport+from .duplication import ClonePair, DuplicationReportfrom .duplication.isolation import detect_clones_with_isolation as detect_clonesfrom .history_refresh import BLAME_MARKERS, as_biomarker_resultfrom .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity@@ -398,6 +398,25 @@ def _read_source_lines(abs_path: str, read_source: SourceReader) -> list[str] |return text.splitlines()+def _clone_sources(+ file_path: str,+ own_lines: list[str],+ clones: list[ClonePair],+ abs_paths: dict[str, str],+ read_source: SourceReader,+) -> dict[str, list[str]]:+ """This file's lines plus each clone partner's, for text-level checks."""+ out = {file_path: own_lines}+ for clone in clones:+ for path in (clone.file_a, clone.file_b):+ if path in out or path not in abs_paths:+ continue+ lines = _read_source_lines(abs_paths[path], read_source)+ if lines is not None:+ out[path] = lines+ return out++def _percentile_p80(counts: list[int]) -> int | None:"""80th percentile of *counts* using the inclusive-lower conventionalready used by ``churn_percentile`` in ``enrich.compute_percentiles``.@@ -531,6 +550,7 @@ class HealthAnalyzer:self.graph = graphself.git_meta_map = git_meta_map or {}self.parsed_files = list(parsed_files or [])+ self._abs_paths = {pf.file_info.path: pf.file_info.abs_path for pf in self.parsed_files}# Per-file coverage keyed by repo-relative POSIX path. Each value# is ``{line_coverage_pct, branch_coverage_pct, covered_lines,# total_coverable_lines}``. ``None``-equivalent files are simply@@ -1323,6 +1343,15 @@ class HealthAnalyzer:clones = dup_report.pairs_by_file.get(file_path, [])dup_pct = dup_report.duplication_pct.get(file_path)+ # Read only for clone-bearing files, keeping the read proportional.+ source_lines = (+ _read_source_lines(pf.file_info.abs_path, self.read_source) if clones else None+ )+ clone_sources = (+ _clone_sources(file_path, source_lines, clones, self._abs_paths, self.read_source)+ if source_lines is not None and _coverage_is_test_file(file_path)+ else {}+ )# The enclosing package root, falling back to the top-level directory# when the repo has no nested packages.@@ -1364,6 +1393,7 @@ class HealthAnalyzer:total_coverable_lines=total_coverable_lines,clones=list(clones),duplication_pct=dup_pct,+ clone_sources=clone_sources,graph_view=graph_view,blame_index=blame_index,repo_function_mod_p80=repo_function_mod_p80,@@ -1442,13 +1472,8 @@ class HealthAnalyzer:),function_analyses=self._extract_method_analyses(pf, findings, dataflow_cache),blame_index=blame_index,- # Source is threaded only for clone-bearing files (the Extract Helper- # detector's snippet). Reading it unconditionally would put a- # repo-sized read back into the per-file path; gating on clones keeps- # it proportional to the small set of files that actually carry one.- source_lines=(- _read_source_lines(pf.file_info.abs_path, self.read_source) if clones else None- ),+ # The Extract Helper snippet; ``None`` unless the file carries clones.+ source_lines=source_lines,)suggestions = detect_refactorings(rctx,diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.jsonindex bdda29b80..5ed10f098 100644--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json@@ -1,7 +1,7 @@{"gopkg": [{- "addresses_primary_problem": false,+ "addresses_primary_problem": null,"affected_files": ["inventory.go"],@@ -10,7 +10,7 @@"evidence": [],"file_path": "inventory.go","judgment_steps": 1,- "lead_biomarker": "dry_violation",+ "lead_biomarker": null,"lead_refactoring_type": "split_file","mechanical_steps": 0,"opportunity_id": "refop2_f8df0afac1fe67c55d05",diff --git a/tests/unit/health/test_duplication.py b/tests/unit/health/test_duplication.pyindex 6b9c8af78..9f91affd2 100644--- a/tests/unit/health/test_duplication.py+++ b/tests/unit/health/test_duplication.py@@ -375,3 +375,80 @@ def test_aggregate_skips_files_without_nloc():pairs = [_pair("a.py", 1, 10, "b.py", 1, 10)]_, pct = _aggregate(pairs, {"a.py": 50})assert "b.py" not in pct+++# ---- identifier-level verification ----------------------------------------++_LOOP_BODY = "\n".join(+ [+ "def {fn}({a}, {b}, {c}):",+ " {t} = 0",+ " for {i} in range({a}):",+ " if {i} > {b}:",+ " {t} = {t} + {i} * {c}",+ " else:",+ " {t} = {t} - {b}",+ " return {t} + {a} + {b} + {c}",+ "",+ ]+)+++def _loop(**names: str) -> str:+ return _LOOP_BODY.format(**names)+++def test_tokenize_file_drops_python_imports():+ toks = tokenize_file("python", b"import os\nfrom a.b import c, d\nx = 1\n")+ assert [t.kind for t in toks] == ["ID", "=", "LIT"]+++def test_tokenize_file_drops_ts_imports_and_reexports_but_keeps_local_exports():+ source = (+ b'import { a, b } from "./x";\n'+ b'export { c } from "./y";\n'+ b'export * from "./z";\n'+ b"export const n = 1;\n"+ )+ toks = tokenize_file("typescript", source, "src/i.ts")+ assert [t.kind for t in toks] == ["export", "const", "ID", "=", "LIT", ";"]++[email protected]("language", ["ruby", "elixir", "shell", "luau", "gdscript"])+def test_import_node_kinds_never_skip_calls_or_superclass_clauses(language: str):+ from repowise.core.analysis.health.duplication.tokenizer import import_node_kinds++ assert import_node_kinds(language) == frozenset()+++def test_tokenize_file_keeps_raw_identifier_names():+ toks = tokenize_file("python", b"total = count + 1\n")+ assert [t.name for t in toks] == ["total", "", "count", "", ""]+++def test_detect_clones_ignores_identical_import_blocks(tmp_path: Path):+ imports = "".join(f"from pkg.mod{i} import name{i}, other{i}\n" for i in range(12))+ a = _write(tmp_path, "a.py", imports + "def f():\n return 1\n")+ b = _write(tmp_path, "b.py", imports + "def g(x):\n return x * 2\n")+ report = detect_clones([_pf("a.py", str(a)), _pf("b.py", str(b))], window_tokens=20, min_lines=4)+ assert report.pairs == []+++def test_detect_clones_ignores_matching_data_literals(tmp_path: Path):+ table = "TABLE = [\n" + "".join(f" ({i}, '{i}', {i}.5),\n" for i in range(20)) + "]\n"+ a = _write(tmp_path, "a.py", table)+ b = _write(tmp_path, "b.py", table.replace("TABLE", "OTHER"))+ report = detect_clones([_pf("a.py", str(a)), _pf("b.py", str(b))], window_tokens=20, min_lines=4)+ assert report.pairs == []+++def test_detect_clones_needs_shared_identifier_names(tmp_path: Path):+ same = dict(fn="f", a="a", b="b", c="c", t="total", i="i")+ renamed = dict(fn="g", a="rows", b="limit", c="scale", t="acc", i="k")+ a = _write(tmp_path, "a.py", _loop(**same))+ b = _write(tmp_path, "b.py", _loop(**renamed))+ c = _write(tmp_path, "c.py", _loop(**{**same, "fn": "f_copy"}))+ parsed = [_pf("a.py", str(a)), _pf("b.py", str(b)), _pf("c.py", str(c))]+ report = detect_clones(parsed, window_tokens=20, min_lines=4)+ # Same shape with every name changed is not a copy; a real copy still is.+ assert {(p.file_a, p.file_b) for p in report.pairs} == {("a.py", "c.py")}diff --git a/tests/unit/health/test_duplication_cache.py b/tests/unit/health/test_duplication_cache.pyindex 31d0de802..f472e1971 100644--- a/tests/unit/health/test_duplication_cache.py+++ b/tests/unit/health/test_duplication_cache.py@@ -124,11 +124,11 @@ def test_cache_shares_interned_kinds_and_can_release_memory(tmp_path: Path):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)])+ cache.put("digest", kinds, ["", ""], 1, [(1, 0, 1, 1)])cached = cache.get("digest")assert cached is not None- cached_kinds, _, _ = cached+ cached_kinds, _, _, _ = cachedassert cached_kinds is kindsassert all(kind is sys.intern(kind) for kind in kinds)diff --git a/tests/unit/health/test_test_quality_biomarkers.py b/tests/unit/health/test_test_quality_biomarkers.pyindex 14ebabcac..dd8ab8abc 100644--- a/tests/unit/health/test_test_quality_biomarkers.py+++ b/tests/unit/health/test_test_quality_biomarkers.py@@ -46,6 +46,7 @@ def _ctx(file_path: str,functions: list[FunctionComplexity],clones: list[ClonePair] | None = None,+ clone_sources: dict[str, list[str]] | None = None,) -> FileContext:return FileContext(file_path=file_path,@@ -55,6 +56,7 @@ def _ctx(module=None,all_functions=tuple(functions),clones=clones or [],+ clone_sources=clone_sources or {},)@@ -107,17 +109,70 @@ def _clone(path: str, a: tuple[int, int], partner: str, b: tuple[int, int]) -> C)+def _lines(block: list[str], at: int, total: int = 40) -> list[str]:+ """*total* filler lines with *block* placed from line *at* (1-indexed)."""+ out = [f"x{i} = setup({i})" for i in range(1, total + 1)]+ out[at - 1 : at - 1 + len(block)] = block+ return out+++_BLOCK = ["assert result.exit_code == 0", "assert result.output == 'ok'"]++def test_duplicated_assertion_block_fires_when_clone_overlaps_block():- fn = _fn("test_x", assertion_blocks=[(10, 20, 6)])- clone = _clone("tests/test_x.py", (12, 19), "tests/test_y.py", (5, 12))+ fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))+ sources = {+ "tests/test_x.py": _lines(_BLOCK, 12),+ # Same statements, different indentation and spacing.+ "tests/test_y.py": _lines(+ [" assert result.exit_code == 0", "\tassert result.output == 'ok'"], 7+ ),+ }out = DuplicatedAssertionBlockDetector().detect(- _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone])+ _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone], clone_sources=sources))assert len(out) == 1assert out[0].severity == Severity.MEDIUMassert out[0].details["partner_file"] == "tests/test_y.py"+def test_duplicated_assertion_block_needs_the_same_text_not_just_shape():+ fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))+ sources = {+ "tests/test_x.py": _lines(_BLOCK, 12),+ # Token-for-token the same shape, different values.+ "tests/test_y.py": _lines(+ ["assert result.exit_code == 2", "assert result.output == 'usage'"], 7+ ),+ }+ out = DuplicatedAssertionBlockDetector().detect(+ _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone], clone_sources=sources)+ )+ assert out == []+++def test_duplicated_assertion_block_silent_without_partner_source():+ fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ clone = _clone("tests/test_x.py", (10, 16), "tests/test_y.py", (5, 11))+ sources = {"tests/test_x.py": _lines(_BLOCK, 12)}+ out = DuplicatedAssertionBlockDetector().detect(+ _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone], clone_sources=sources)+ )+ assert out == []+++def test_duplicated_assertion_block_ignores_an_intra_file_clone_overlapping_itself():+ fn = _fn("test_x", assertion_blocks=[(12, 13, 2)])+ clone = _clone("tests/test_x.py", (10, 16), "tests/test_x.py", (11, 17))+ sources = {"tests/test_x.py": _lines(_BLOCK, 12)}+ out = DuplicatedAssertionBlockDetector().detect(+ _ctx(file_path="tests/test_x.py", functions=[fn], clones=[clone], clone_sources=sources)+ )+ assert out == []++def test_duplicated_assertion_block_ignores_clone_outside_block():fn = _fn("test_x", assertion_blocks=[(10, 20, 6)])clone = _clone("tests/test_x.py", (40, 48), "tests/test_y.py", (5, 12))