| name | more-code-less-reuse |
| description | Analyze AI-generated code for redundancy and missed reuse opportunities using semantic clone detection, then refactor to eliminate technical debt. Triggers: 'check for code duplication', 'review AI-generated PR', 'find redundant code', 'reuse audit', 'detect code clones', 'reduce AI code redundancy' |
More Code, Less Reuse: AI Code Redundancy Auditor
This skill enables Claude to detect and eliminate the characteristic redundancy patterns that LLM-generated code introduces into codebases. Based on research showing AI-generated pull requests contain 1.87x more semantic redundancy than human-written code (p<0.001), this skill applies a systematic audit workflow: scan new or AI-generated code for semantic clones against the existing codebase, identify missed reuse opportunities, and refactor duplicated logic into shared abstractions. The core insight is that AI code often passes tests and looks plausible on the surface, but silently accumulates technical debt by reimplementing functionality that already exists nearby.
When to Use
- When reviewing a pull request that was generated by an AI coding agent (Copilot, Cursor, Claude, etc.)
- When the user asks to "check for duplicated code" or "find redundancy" in recent changes
- When integrating AI-generated code into an existing codebase and wanting to ensure it reuses existing utilities
- When a codebase has grown through heavy AI assistance and needs a reuse audit
- When preparing a code review checklist specifically for AI-authored contributions
- When refactoring after noticing repeated patterns across recently added files
Key Technique
The paper (Huang et al., MSR 2026) reveals that while traditional metrics like cyclomatic complexity and lines of code show minimal differences between AI and human PRs, a semantic redundancy metric exposes a critical gap. The authors define the Max Redundancy Score (MRS) for each new function f added in a PR: compute the cosine similarity between f's code embedding and every existing function g in the codebase, then take the maximum. A high MRS means the new function is semantically near-identical to something already present -- a missed reuse opportunity. Across their dataset, AI-generated code averaged an MRS of 0.2867 vs. 0.1532 for humans, meaning AI code is nearly twice as likely to duplicate existing logic.
The dangerous part is that reviewers don't catch this. The paper's emotion analysis (using DistilRoBERTa across 7 emotion categories) found that reviewers express more positive and neutral sentiment toward AI PRs than human ones, while showing less disgust, anger, and surprise. This means AI-generated redundancy passes review more easily than human redundancy -- the surface-level correctness and clean formatting of AI code masks poor design choices, creating what the authors call "silent technical debt."
The actionable takeaway: any code review of AI-generated contributions must include an explicit redundancy check. Don't trust that the code "looks good." Instead, systematically compare each new function or class against the existing codebase for semantic overlap, and refactor duplicates into shared utilities before merging.
Step-by-Step Workflow
-
Identify the scope of new code. Collect all new functions, classes, and methods introduced in the PR or recent changes. Use git diff --name-only against the base branch to enumerate changed files, then extract added function/method definitions from those files.
-
Build an inventory of existing utilities. For each changed file, identify its module and scan sibling modules, shared utility files, and base classes in the same package. List every existing function signature with a one-line description of its purpose. Pay special attention to utils/, helpers/, common/, and base modules.
-
Perform semantic comparison for each new function. For every new function, ask: does an existing function already do this or something very close? Compare by:
- Name similarity: same verb+noun pattern (e.g.,
validate_input vs check_input)
- Parameter overlap: similar parameter names and types
- Logic overlap: same control flow, API calls, or data transformations
- Return value equivalence: produces the same kind of output from the same kind of input
-
Flag high-redundancy candidates. Mark any new function that shares >70% of its logic with an existing function. Categorize each match:
- Type-1 clone: Exact or near-exact copy (rename and delete)
- Type-2 clone: Same structure with different variable names or literals (parameterize and merge)
- Type-4 semantic clone: Different syntax but equivalent purpose (refactor to call existing function)
-
Check for inlined logic that belongs in a utility. AI agents often inline operations that the codebase already wraps in helpers. Look for patterns like: raw os.path manipulation when a paths.py utility exists, manual JSON parsing when a serializers.py helper handles it, or reimplemented error handling that a decorator already provides.
-
Propose specific refactorings. For each flagged redundancy, write a concrete refactoring:
- Replace the duplicate with a call to the existing function
- If the existing function needs slight generalization (e.g., an extra parameter), extend it rather than duplicating
Concrete Examples
Example 1: AI agent reimplements an existing validation helper
User: "Review this AI-generated PR for redundancy"
New code in services/user_service.py:
def validate_email_format(email: str) -> bool:
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not isinstance(email, str):
return False
return bool(re.match(pattern, email))
Existing code found in utils/validators.py:
def is_valid_email(email: str) -> bool:
"""Validate email format using RFC 5322 simplified pattern."""
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return isinstance(email, str) and bool(re.match(pattern, email))
Audit finding:
REDUNDANCY DETECTED (Type-1 clone)
- New: services/user_service.py::validate_email_format
- Existing: utils/validators.py::is_valid_email
- Overlap: identical regex pattern, identical logic
- Action: Delete validate_email_format, replace call sites with:
from utils.validators import is_valid_email
Example 2: AI agent creates a new data transformation instead of using existing one
User: "Check if this new code duplicates anything we already have"
New code in api/handlers.py:
def format_user_response(user_obj):
return {
"id": str(user_obj.id),
"name": f"{user_obj.first_name} {user_obj.last_name}",
"email": user_obj.email,
"created": user_obj.created_at.isoformat(),
}
Existing code in serializers/user.py:
class UserSerializer:
@staticmethod
def to_dict(user) -> dict:
return {
"id": str(user.id),
"name": user.full_name,
"email": user.email,
"created": user.created_at.isoformat(),
}
Audit finding:
REDUNDANCY DETECTED (Type-4 semantic clone)
- New: api/handlers.py::format_user_response
- Existing: serializers/user.py::UserSerializer.to_dict
- Overlap: same fields, same transformations, different access pattern for name
- Action: Replace with UserSerializer.to_dict(user_obj)
- Note: f"{first_name} {last_name}" duplicates user.full_name property
Example 3: Multiple AI-generated functions share extractable logic
User: "Audit this module for code reuse opportunities"
Three new functions in processors/data_pipeline.py all contain:
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
data = response.json()
except requests.RequestException as e:
logger.error(f"Failed to fetch {url}: {e}")
return None
Audit finding:
REDUNDANCY DETECTED (repeated inline pattern, 3 occurrences)
- Locations: lines 45-51, 78-84, 112-118
- Existing utility: None found
- Action: Extract to shared helper:
def fetch_json(url: str) -> dict | None:
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
logger.error(f"Failed to fetch {url}: {e}")
return None
- Place in: utils/http.py (or the nearest shared utilities module)
- Then replace all 3 inline blocks with: data = fetch_json(url)
Best Practices
- Do: Always scan
utils/, helpers/, common/, and base modules before accepting any new utility function from AI -- these are where reusable code lives and where AI most often fails to look.
- Do: Compare by purpose, not just by syntax. AI agents produce Type-4 semantic clones (same behavior, different code) that grep-based duplicate detection misses.
- Do: Check the git history of the base branch for recently added utilities. AI agents often work from stale context and miss functions added in parallel PRs.
- Do: Extend existing functions with optional parameters rather than creating near-duplicates with slightly different behavior.
- Avoid: Trusting that "the tests pass" means the code is well-integrated. Pass rates measure correctness, not maintainability or reuse.
- Avoid: Over-abstracting in response to redundancy findings. If two functions share 30% of their logic, they may be legitimately distinct. The threshold for refactoring is when the core purpose is the same and differences can be captured by parameters.
Error Handling
- False positives on intentional duplication: Some codebases deliberately duplicate code across service boundaries (e.g., microservices that shouldn't share imports). Check module boundaries and architecture docs before flagging cross-service duplicates.
- Utilities that are similar but not equivalent: Two functions may look alike but handle edge cases differently (e.g., one is null-safe, one isn't). Always verify behavioral equivalence before recommending a replacement. Run existing tests after refactoring.
- Missing test coverage for the existing function: If the existing utility lacks tests for the exact use case the AI code addresses, add tests for that case before replacing the duplicate. Don't reduce coverage.
- Refactoring introduces circular imports: When consolidating duplicates into a shared module, check that the new import path doesn't create dependency cycles. Resolve by moving the shared function to a lower-level module.
Limitations
- This workflow is most effective for Python and languages with clear function/method boundaries. Languages with heavy metaprogramming or macro systems may produce harder-to-detect semantic clones.
- Semantic comparison relies on Claude reading and understanding both functions. For very large codebases (thousands of modules), a full manual scan is impractical -- focus the audit on the package tree containing the changed files and explicitly designated utility modules.
- The paper's findings are based on open-source Python repositories with >500 stars. Redundancy patterns in proprietary, enterprise, or non-Python codebases may differ.
- Reviewer sentiment analysis findings suggest a bias toward accepting AI code uncritically. This skill cannot fix organizational review culture, but it can provide concrete evidence of redundancy to make reviews more rigorous.
- The 1.87x redundancy multiplier is an average across the studied dataset. Individual PRs may show more or less redundancy depending on the AI agent used and the task complexity.
Reference
Huang, H., Jaisri, P., Shimizu, S., Chen, L., & Nakashima, S. (2026). More Code, Less Reuse: Investigating Code Quality and Reviewer Sentiment towards AI-generated Pull Requests. MSR 2026. arXiv:2601.21276 -- Focus on Section 4 (redundancy metric MRS definition), Table 3 (AI vs human redundancy scores), and Section 5 (the sentiment disconnect finding).