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): stop pairing the shared skeleton of sibling files as duplication (#4788)
Raghav Chamadiya02a45cace292
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/README.md b/packages/core/src/repowise/core/analysis/health/duplication/README.mdindex fa509f189..4764befbc 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/README.md+++ b/packages/core/src/repowise/core/analysis/health/duplication/README.md@@ -30,7 +30,9 @@ report = detect_clones(parsed_files, git_meta_map)to rule out hash collisions before emitting a `ClonePair`.4. **Merge adjacent windows** — adjacent or overlapping clone windowsbetween the same `(file_a, file_b)` collapse into one contiguous- region.+ region. A region shared by two non-test files of one directory with no+ branch and no lambda in it (`tokenizer.decision_lines`) is dropped: it is+ the skeleton sibling implementations share, not copied logic.5. **Co-change correlation** — for each surviving pair we look up`git_meta_map[file_a]['co_change_partners_json']` (and the reversedirection). The max count attaches to `ClonePair.co_change_count`diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.pyindex a42d05be5..cefb10468 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py@@ -22,6 +22,7 @@ size.from __future__ import annotations+import posixpathimport timefrom collections import defaultdictfrom collections.abc import Iterable@@ -34,10 +35,11 @@ import structlogfrom repowise.core.cancellation import check_cancelledfrom repowise.core.co_change import parse_partners+from repowise.core.code_origin import code_originfrom .limits import DuplicationDiagnostics, DuplicationLimits, looks_minifiedfrom .rabin_karp import WindowHash, WindowRow, index_by_hash, window_rows-from .tokenizer import tokenize_file_rows+from .tokenizer import decision_lines, tokenize_file_rowslog = structlog.get_logger(__name__)@@ -309,7 +311,13 @@ def detect_clones(# can be reused inside this phase rather than growing the process again.del per_file_streams- final = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)+ final = _finalize_pairs(+ _merge_adjacent_pairs(raw_pairs),+ min_lines,+ meta_map,+ {pf.file_info.path: pf for pf in parsed_list},+ source_reader,+ )pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)return DuplicationReport(@@ -788,7 +796,9 @@ def _detect_clones_incremental(]if not persist:- final = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)+ final = _finalize_pairs(+ _merge_adjacent_pairs(raw_pairs), min_lines, meta_map, current, read_source+ )pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)return DuplicationReport(pairs=final,@@ -830,7 +840,9 @@ def _detect_clones_incremental(pairs=len(raw_pairs),)- final = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)+ final = _finalize_pairs(+ _merge_adjacent_pairs(raw_pairs), min_lines, meta_map, current, read_source+ )pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)diagnostics = diag.as_log_fields()@@ -931,15 +943,69 @@ def _persist_pair_index(# ---------------------------------------------------------------------------+class _SiblingSkeleton:+ """Recognizes a clone between two files of one directory that holds no+ branch and no lambda: the skeleton siblings share by contract (a handler's+ signatures, a keybinding table, a migration's columns, a constructor+ chain), not copied logic.++ Measured on 165 hand-labelled same-directory clone pairs from four+ repositories: it drops 67 of 95 skeleton pairs and keeps 59 of 61 copied+ logic pairs. Test files keep every pair, since duplicated assertion blocks+ read them. Only the side whose file was read is parsed; both sides have the+ same token kinds, so either answers.+ """++ def __init__(self, files: dict[str, Any], read_source: Any | None) -> None:+ self._files = files+ self._read_source = read_source+ self._lines: dict[str, frozenset[int] | None] = {}++ def matches(self, p: ClonePair) -> bool:+ if p.is_intra_file or posixpath.dirname(p.file_a) != posixpath.dirname(p.file_b):+ return False+ if self._is_test(p.file_a) or self._is_test(p.file_b):+ return False+ if p.file_a in self._files:+ path, start, end = p.file_a, p.a_start_line, p.a_end_line+ elif p.file_b in self._files:+ path, start, end = p.file_b, p.b_start_line, p.b_end_line+ else:+ return False+ lines = self._decision_lines(path)+ return lines is not None and not any(start <= line <= end for line in lines)++ def _is_test(self, path: str) -> bool:+ pf = self._files.get(path)+ stored = getattr(pf.file_info, "is_test", None) if pf is not None else None+ return code_origin(path, is_test=stored) == "test"++ def _decision_lines(self, path: str) -> frozenset[int] | None:+ if path not in self._lines:+ info = self._files[path].file_info+ source = _read_source(info.abs_path, self._read_source)+ self._lines[path] = (+ None if source is None else decision_lines(info.language, source, path)+ )+ return self._lines[path]++def _finalize_pairs(merged: list[ClonePair],min_lines: int,meta_map: dict[str, dict[str, Any]],+ files: dict[str, Any] | None = None,+ read_source: Any | None = None,) -> list[ClonePair]:- """Drop sub-threshold pairs and attach co-change weight."""+ """Drop sub-threshold pairs and sibling skeletons, attach co-change weight.++ *files* maps a path to its parsed file; a pair neither of whose files is+ in it is kept as found.+ """+ skeleton = _SiblingSkeleton(files or {}, read_source)final: list[ClonePair] = []for p in merged:- if min(p.a_line_count, p.b_line_count) < min_lines:+ if min(p.a_line_count, p.b_line_count) < min_lines or skeleton.matches(p):continuescore = _co_change_score(p.file_a, p.file_b, meta_map)if score:diff --git a/packages/core/src/repowise/core/analysis/health/duplication/isolation.py b/packages/core/src/repowise/core/analysis/health/duplication/isolation.pyindex 63ec8ab2f..40d20da88 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/isolation.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/isolation.py@@ -36,6 +36,7 @@ class _FileInfo:path: strabs_path: strlanguage: str+ is_test: bool | None = None@dataclass(frozen=True, slots=True)@@ -45,7 +46,7 @@ class _ParsedFile:def _worker(sender: Any,- files: list[tuple[str, str, str]],+ files: list[tuple[str, str, str, bool | None]],git_meta_map: dict[str, dict[str, Any]],window_tokens: int,min_lines: int,@@ -89,7 +90,7 @@ def detect_clones_with_isolation() -> DuplicationReport:"""Detect clones, isolating repository-scale transient allocations.- Only the three file-info strings used by the detector cross the process+ Only the file-info fields the detector reads cross the processboundary. The full parsed AST/model graph remains in the parent, and thechild returns the comparatively small final report.@@ -119,7 +120,12 @@ def detect_clones_with_isolation()files = [- (pf.file_info.path, str(pf.file_info.abs_path), pf.file_info.language)+ (+ pf.file_info.path,+ str(pf.file_info.abs_path),+ pf.file_info.language,+ getattr(pf.file_info, "is_test", None),+ )for pf in parsed_files]# Clone weighting only reads this field. Avoid serializing the much largerdiff --git a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.pyindex efff679a5..6d56b57fb 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py@@ -219,16 +219,72 @@ def tokenize_file_rows(language: str, source: bytes, path: str | None = None) ->(a ``.tsx`` file is tagged ``typescript`` and needs the JSX grammar) andgates Pascal's project-file sanitizer. Omitting it costs both."""+ parsed = _parse(language, source, path)+ if parsed is None:+ return []+ root, source = parsed+ return token_rows(root, source, import_node_kinds(language))+++# Leaf tokens that branch, and nodes that pass code as a value. A clone with+# none of either is declaration: signatures, tables, constructor chains.+_DECISION_TOKENS = frozenset(+ {+ "if", "else", "elif", "for", "foreach", "while", "switch", "case", "select",+ "match", "when", "try", "catch", "except", "and", "or", "&&", "||", "?", "??", "?.",+ }+) # fmt: skip+_CALLBACK_KINDS = frozenset(+ {+ "lambda",+ "lambda_expression",+ "arrow_function",+ "func_literal",+ "closure_expression",+ "anonymous_function",+ "function_expression",+ "anonymous_function_expression",+ "anonymous_method_expression",+ }+)+++def decision_lines(language: str, source: bytes, path: str | None = None) -> frozenset[int] | None:+ """The 1-indexed lines holding a branch token or the start of a lambda.++ ``None`` when the file cannot be parsed, so a caller can tell "no+ decisions" from "not known".+ """+ parsed = _parse(language, source, path)+ if parsed is None:+ return None+ root, _source = parsed+ lines: set[int] = set()+ cursor = root.walk()+ while True:+ node = cursor.node+ ntype = node.type+ if ntype in _CALLBACK_KINDS or (node.child_count == 0 and ntype in _DECISION_TOKENS):+ lines.add(node.start_point[0] + 1)+ if cursor.goto_first_child():+ continue+ while not cursor.goto_next_sibling():+ if not cursor.goto_parent():+ return frozenset(lines)+++def _parse(language: str, source: bytes, path: str | None) -> tuple[Node, bytes] | None:+ """The tree root and the buffer it was parsed from, or ``None``."""try:from tree_sitter import Parserfrom repowise.core.ingestion.parser import _get_language, grammar_tag_forexcept Exception:- return []+ return Nonegrammar = _get_language(grammar_tag_for(language, path or ""))if grammar is None:- return []+ return Nonetry:from repowise.core.ingestion.sfc_source import prepare_source@@ -238,5 +294,5 @@ def tokenize_file_rows(language: str, source: bytes, path: str | None = None) ->source = prepare_source(language, source, path=path)tree = parser.parse(source)except Exception:- return []- return token_rows(tree.root_node, source, import_node_kinds(language))+ return None+ return tree.root_node, sourcediff --git a/tests/unit/health/test_duplication.py b/tests/unit/health/test_duplication.pyindex 74597738b..db7080965 100644--- a/tests/unit/health/test_duplication.py+++ b/tests/unit/health/test_duplication.py@@ -176,6 +176,79 @@ def test_detect_clones_attaches_co_change_count(tmp_path: Path):assert report.pairs[0].co_change_count == 7+_HANDLER = '''class _{cls}Handler:+ """Adds the edges one framework implies."""++ def detect(self, ctx: Context) -> bool:+ return True++ def add_edges(+ self,+ graph: Graph,+ parsed_files: dict[str, Any],+ ctx: Context,+ path_set: set[str],+ ) -> int:+ return _add_{name}_edges(graph, parsed_files, ctx, path_set)+++HANDLERS: list[Handler] = [_{cls}Handler()]+'''+++def _handler_pair(tmp_path: Path, path_a: str, path_b: str, extra: str = "") -> list:+ parsed = []+ for path, name in ((path_a, "alpha"), (path_b, "beta")):+ src = _HANDLER.format(cls=name.title(), name=name).replace("return True", extra or "return True")+ target = tmp_path / path+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(src)+ parsed.append(_pf(path, str(target)))+ return parsed+++def test_sibling_skeleton_in_one_directory_is_not_a_clone(tmp_path: Path):+ # Two handlers of one registry share signatures and a registration line,+ # with no branch or callback: the contract, not copied logic.+ parsed = _handler_pair(tmp_path, "edges/alpha.py", "edges/beta.py")+ assert detect_clones(parsed, window_tokens=20, min_lines=4).pairs == []+++def test_the_same_skeleton_across_directories_stays_a_clone(tmp_path: Path):+ parsed = _handler_pair(tmp_path, "one/alpha.py", "two/beta.py")+ assert detect_clones(parsed, window_tokens=20, min_lines=4).pairs+++ "extra",+ [+ "return bool(ctx) if ctx.ready else False",+ "return any(map(lambda tok: tok in ctx.stack, ctx.names))",+ ],+)+def test_a_sibling_clone_with_a_branch_or_lambda_stays_a_clone(tmp_path: Path, extra: str):+ parsed = _handler_pair(tmp_path, "edges/alpha.py", "edges/beta.py", extra)+ assert detect_clones(parsed, window_tokens=20, min_lines=4).pairs+++def test_sibling_test_files_keep_their_skeleton_clones(tmp_path: Path):+ # Duplicated assertion blocks read test clones; they stay.+ parsed = _handler_pair(tmp_path, "tests/test_alpha.py", "tests/test_beta.py")+ assert detect_clones(parsed, window_tokens=20, min_lines=4).pairs+ # Ingestion's stored flag decides where the path alone would not.+ parsed = _handler_pair(tmp_path, "helpers/alpha.py", "helpers/beta.py")+ parsed[0].file_info.is_test = True+ assert detect_clones(parsed, window_tokens=20, min_lines=4).pairs+++def test_decision_lines_marks_branches_and_lambdas_only():+ from repowise.core.analysis.health.duplication.tokenizer import decision_lines++ source = b"def f(x: int) -> int:\n y = x\n if y:\n g = lambda: y\n return y\n"+ assert decision_lines("python", source, "f.py") == {3, 4}+ assert decision_lines("not-a-language", source) is None++def test_detect_clones_skips_files_without_duplicates(tmp_path: Path):a = _write(tmp_path, "a.py", "def f():\n return 1\n")b = _write(tmp_path, "b.py", "def g():\n return 2\n")