Explore the desloppify codebase at /Users/user_c042661f/Documents/desloppify/desloppify/ for code duplication and repetitive patterns. Look for:
Functions or blocks of logic that are near-duplicates across files
Repeated boilerplate patterns (e.g., similar file-reading/error-handling patterns, similar detector structures)
Copy-paste code that could be abstracted
Similar data structures defined in multiple places
Focus on the detector files, lang plugins, and command files. Give specific examples with file paths and line numbers. Be thorough.
Assistant
I'll conduct a thorough exploration of the desloppify codebase to identify code duplication and repetitive patterns. Let me start with a systematic search.
User
Explore the desloppify codebase at /Users/user_c042661f/Documents/desloppify/desloppify/ for naming inconsistencies and convention drift. Look for:
Mixed naming conventions (snake_case vs camelCase, inconsistent prefixes like _ vs no _)
Similar concepts with different names across files (e.g., "findings" vs "entries" vs "results" vs "matches")
Inconsistent function signatures for similar operations
Module organization issues — files that seem misplaced or oddly named
Inconsistent import patterns
Give specific examples with file paths and line numbers. Be thorough.
Assistant
I'll conduct a thorough analysis of the desloppify codebase to identify naming inconsistencies and convention drift. Let me start by exploring the structure and then diving into specific issues.
Assistant
Now let me search for specific patterns of duplication. Let me check detector structures first:
Assistant
Now let me search for naming patterns and inconsistencies across the codebase.
User
Explore the desloppify codebase at /Users/user_c042661f/Documents/desloppify/desloppify/ for complexity issues. Look for:
The largest files by line count — list the top 10 with their line counts
Functions that are very long (>50 lines) — list them with file:line and approximate length
Deeply nested code (3+ levels of indentation in logic)
Complex conditional chains or long if/elif blocks
Files with too many responsibilities (doing multiple unrelated things)
Give specific examples with file paths and line numbers. Be thorough.
Assistant
Let me fix that:
Assistant
I'll conduct a thorough exploration of the desloppify codebase to identify complexity issues. Let me start by gathering information about the largest files and then dig deeper into code structure.
Assistant
Let me search for more specific naming inconsistencies:
Assistant
Good! Now let me check the actual function definitions across different detectors:
Assistant
Let me continue examining key files to identify inconsistencies:
Assistant
Now let me read the top 10 largest files and analyze them for complexity:
User
Explore the desloppify codebase at /Users/user_c042661f/Documents/desloppify/desloppify/ for architectural issues. Look for:
Circular or tangled imports — trace import chains that seem circular or overly complex
Files that import from too many other internal modules (high fan-in)
God modules that everything depends on
Layer violations — does the import direction (lang/ -> detectors/, never reverse) hold?
Modules that mix concerns (e.g., I/O mixed with pure logic, display mixed with computation)
Global mutable state
Check the actual import statements. Give specific examples with file paths and line numbers. Be thorough.
Assistant
Now let me check the test coverage detector and other detectors for patterns:
Assistant
I'll explore the desloppify codebase to identify architectural issues. Let me start with a systematic analysis of the import structure.
Assistant
Now let me search for specific patterns to identify naming inconsistencies:
Assistant
Now let me analyze code structure for long functions and nested complexity:
Assistant
Let me get all Python files and start analyzing imports systematically.
Assistant
Let me check for more duplication patterns - looking at extractors and how they're called:
User
Explore the desloppify codebase for test coverage patterns. The source is at /Users/user_c042661f/Documents/desloppify/desloppify/ and tests at /Users/user_c042661f/Documents/desloppify/tests/.
List all test files and what they cover
Find source modules that have NO corresponding test file or test coverage
Look at the test files — are they thorough? Do they test edge cases or just happy paths?
Are there any detector modules without tests?
Check if the newer detectors (security, dict_keys, mutable_state, private_imports, facade, layer_violation) have tests
Give specific examples. Be thorough.
Assistant
Now let me analyze imports by extracting all import statements:
Assistant
Let me check for deeply nested code and complex conditional chains:
Assistant
Now let me check command files for duplication:
Assistant
I'll conduct a thorough exploration of the test coverage patterns in the desloppify codebase. Let me start by mapping out the structure and then analyze the test coverage.
Assistant
Let me check the _helpers file and look at how state is loaded/saved:
Assistant
Let me try a different approach:
User
Explore the desloppify codebase at /Users/user_c042661f/Documents/desloppify/desloppify/ for error handling quality. Look for:
Inconsistent error handling strategies across modules — do some raise, some return None, some log?
Missing error handling on I/O operations (file reads, subprocess calls)
Error messages that are unhelpful or missing context
Any use of assert for runtime validation (not just tests)
Give specific examples with file paths and line numbers. Be thorough.
Assistant
Now let me get a comprehensive view of all source files and map them to test coverage:
Assistant
I'll conduct a thorough exploration of the desloppify codebase to assess error handling quality. Let me search for various error handling patterns systematically.
Assistant
Now let me check for specific naming inconsistencies by examining critical files:
Assistant
Let me search for more patterns - checking how detectors are wrapped in different places:
Assistant
Let me use the Grep tool more effectively:
Assistant
Now let me search for various error handling anti-patterns across the codebase:
Assistant
Let me search for more inconsistencies systematically:
Assistant
Good! Now let me check for tests of the newer detectors and analyze test coverage comprehensively:
Assistant
Let me search for imports more broadly:
Assistant
Now let me check the plan.py and commands to see how things are structured:
Assistant
Now let me search for functions longer than 50 lines:
Assistant
Let me search with a simpler pattern:
Assistant
Now let me search for silent error patterns (pass, continue, etc.):
Assistant
Now let me look at specific test files to analyze their quality:
Assistant
Good! Now let me read several key files to understand the import structure:
Assistant
Let me search for actual except blocks with pass/continue:
Assistant
Let me check the utils.py to see file-reading patterns and also look at the smell detectors in both languages:
Assistant
Excellent! Now let me check the test for facade and see if there are tests for private_imports and layer_violation:
Assistant
Now let me search for specific naming issues across modules:
Assistant
Let me look at specific files with complex error handling:
Assistant
Now let me look at the TS smells detector and check for comparison:
Assistant
Now let me search for more circular import patterns and examine key dependency files:
Assistant
Excellent! Now let me look at some specific examples of complex conditional chains and multiple responsibilities:
Assistant
Let me continue examining more critical error handling areas:
Assistant
Let me examine the state and registry to identify more inconsistencies:
Assistant
Now let me check if there are dedicated test files for these detectors and look at their implementation:
Assistant
Let me check for circular dependencies and deeply-dependent files:
Assistant
Let me look at more of the TS smells and check for finding creation patterns:
Assistant
Now let me examine files with too many responsibilities:
Assistant
Let me continue examining more files for error handling issues:
Assistant
Perfect! Now let me check the coverage of individual test files more systematically:
Assistant
Let me check for inconsistencies in naming patterns more systematically:
Assistant
Let me check the finding_factories and scan.py to see how findings are created:
Assistant
Let me search for subprocess calls and other I/O operations:
Assistant
Let me get more details and read some key files:
Assistant
Let me now check for more patterns - looking at how different detectors handle file reading and entry creation:
Assistant
Now let me look at specific subprocess and I/O handling:
Assistant
Now let me look for some critical inconsistencies:
Assistant
Now let me look at specific detector modules to see if they're tested in different files:
Assistant
Now let me check the fixers to see if there are duplication patterns:
Assistant
Perfect! Now let me check for conditional complexity:
Assistant
Now let me analyze the registry and check for high fan-in modules:
Assistant
Let me search for more error handling issues:
Assistant
Let me check for more duplication across the lang plugins and narrative module:
Assistant
Let me check for more dependencies and analyze specific problematic patterns:
Assistant
Let me search for except blocks more carefully by looking at multi-line patterns:
Assistant
Now let me check some untested modules and analyze edge case coverage:
Assistant
Let me look at more files with potential error handling issues:
Assistant
Now let me check for circular dependencies and mixed concerns:
Assistant
Perfect! Now let me do a final check on error handling patterns and check for duplicate zone/finding patterns:
Assistant
Now let me check how comprehensive the tests are and look for potential edge cases:
Assistant
Let me check for issues with JSON parsing and other critical operations:
Assistant
Now let me examine some critical dependency paths and check for issues in narrative and review modules:
Assistant
Let me now check a few specific files for detailed duplication analysis:
Assistant
Now let me check for more inconsistencies in naming patterns:
Assistant
Perfect! Now let me check for specific complex patterns and create a final comprehensive report:
Assistant
Now let me check those JSON parsing contexts more carefully:
Assistant
Let me check for more complex import patterns and global mutable state:
Assistant
Let me check for more error handling patterns and look at specific problem areas:
Assistant
Let me check for more specific inconsistencies in the codebase:
Assistant
Now let me look at some edge cases in the tests and check if critical modules have adequate coverage:
Assistant
Now let me check for issues related to silent swallowing and incomplete error handling:
Assistant
Let me check for mixed concerns in key modules and examine command implementations:
Assistant
Now let me create a comprehensive analysis by checking for import/export inconsistencies:
Assistant
Perfect! Now let me search for more specific inconsistencies in the codebase:
Assistant
Now let me create a comprehensive analysis. Let me check a few more critical areas:
Assistant
Let me look more carefully at specific error handling issues found:
Assistant
Perfect! Now let me check if there are edge cases missing and look at the untested command modules:
Assistant
Now let me look at the narrative reminders module:
Assistant
Excellent! Now let me look at critical inconsistencies in the detector naming and underscore prefixes:
Assistant
Now let me create a comprehensive summary report:
Assistant
Now let me compile the findings with more detail:
Assistant
Let me finalize my analysis with a comprehensive review:
Assistant
Excellent! I now have a comprehensive understanding of the codebase. Let me generate my final report:
Code Duplication and Repetitive Patterns Analysis - Desloppify Codebase
I've conducted a thorough exploration of the desloppify codebase and identified significant duplication and repetitive patterns. Here are my findings:
Recommendation: The _read_file_text() function already exists in utils.py:88-99 with optional caching support. This should be the single source of truth. The duplication creates maintenance burden and misses optimization opportunity (caching).
Perfect! Now I have a thorough understanding of the codebase's error handling. Let me compile my findings:
Error Handling Quality Analysis for Desloppify Codebase
Based on my thorough exploration of the codebase at /Users/user_c042661f/Documents/desloppify/desloppify/, here are specific findings across all five categories:
1. BARE EXCEPT & OVERLY BROAD EXCEPT CLAUSES
Issue 1: Broad Exception in review_cmd.py (line 203)
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/commands/review_cmd.py:200-204
if lang.build_dep_graph and lang._dep_graph is None:
try:
lang._dep_graph = lang.build_dep_graph(path)
except Exception: # ← OVERLY BROAD
pass # Non-fatal — context will just lack dep graph info
Problem: Catches all Exception types without discrimination. Could hide AttributeError, ImportError, or other unexpected failures. The comment says "non-fatal" but swallows everything silently.
Problem: Using BaseException (the parent of all exceptions including SystemExit, KeyboardInterrupt) for cleanup. While it re-raises, it's still catching things that shouldn't be caught (system signals). Should be Exception instead.
Problem: Same as above — BaseException is too broad for cleanup code.
Assistant
Perfect. Let me compile my findings into a comprehensive report.
Architectural Issues in desloppify Codebase
I've completed a thorough analysis of the desloppify codebase at /Users/user_c042661f/Documents/desloppify/desloppify/. Here are the key architectural issues I found:
The codebase relies heavily on ... (3-level) relative imports, particularly from language plugins importing detectors:
desloppify/lang/python/detectors/deps.py:34: from ....detectors.graph import finalize_graph
desloppify/lang/python/detectors/security.py:27: from ....detectors.security import _make_entry
desloppify/lang/python/extractors.py:3: from ...detectors.base import ClassInfo, FunctionInfo
desloppify/lang/python/extractors.py:4: from ...detectors.passthrough import _classify_params, classify_passthrough_tier
This depth suggests weak layering. Detectors at desloppify/detectors/ should be independent of language-specific plugins, but language plugins are reaching back into the detectors layer, violating clean architecture.
2. High Fan-In Modules (God Modules)
Issue: Utilities and state modules imported by nearly every subsystem
smells_ast.py (1,102 LOC) — Major refactoring candidate
_detect_hardcoded_path_sep() @ line 653: 64 LOC - Complex path validation with 2+ levels of nested ifs
_detect_annotation_quality() @ line 1039: 64 LOC - Multiple annotation checks with deeply nested conditions
_detect_optional_param_sprawl() @ line 968: 62 LOC - Parameter analysis with complex dataclass detection
_detect_regex_backtrack() @ line 405: 61 LOC - Regex pattern analysis with 3+ nesting levels
Assistant
Perfect! Now I have enough information to compile a comprehensive report. Let me create the final analysis:
Naming Inconsistencies and Convention Drift in Desloppify Codebase
Based on my thorough exploration of /Users/user_c042661f/Documents/desloppify/desloppify/, I've identified significant naming inconsistencies and convention drift patterns. Here's a comprehensive report:
The codebase uses multiple terms for the same concepts, creating confusion:
Issue: Similar concepts named differently across files:
"findings" (state.py): Primary type Finding(TypedDict) at line 17
"entries" (lang/typescript/fixers/common.py:89, logs.py:12): Raw detector output, e.g., entries: list[dict]
"results" (lang/typescript/fixers/common.py:103): Output of fixers, e.g., results = []
"matches" (commands/show.py): Search results in _build_show_payload(matches: list[dict])
Examples:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/finding_factories.py:12-27: All functions use entries parameter but return list[Finding] after transformation via make_finding() factory
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/fixers/common.py:89-131: apply_fixer() takes entries, internally groups them as file_entries, but returns results
/Users/user_c042661f/Documents/desloppify/desloppify/plan.py:26-74: Uses both findings: list[dict] (line 67) and phase_findings, phase_potentials (line 72)
2. Underscore Prefix Inconsistency in Phase Functions
Issue: Private functions have inconsistent underscore naming:
Examples:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/python/__init__.py: All phase runners use _phase_* prefix (e.g., _phase_unused, _phase_structural, _phase_coupling, _phase_smells)
/Users/user_c042661f/Documents/desloppify/desloppify/lang/base.py:170-192: Public-facing phase runners use NO underscore prefix: , ,
Assistant
Excellent! Now let me compile the comprehensive report:
Test Coverage Analysis Report for Desloppify
Executive Summary
The desloppify codebase has 2,212 test items across 72 test files, with 26,851 total lines of test code. The test suite runs successfully with 2,209 passing tests and 1 failing test (unrelated to detector coverage). Test coverage is extensive for most detectors, though several newer and utility modules lack dedicated tests.
Recommendation: Create a decorator or context manager safe_file_read() to encapsulate this pattern.
3. "Group by File" Dictionary Pattern Duplication
Pattern Found: Nearly identical defaultdict(list) grouping logic across 22+ files:
python
by_file: dict[str, list[dict]] = defaultdict(list)
for e in entries:
by_file[e["file"]].append(e)
for filepath, file_entries in sorted(by_file.items()):
# process
def detect_*_security(files, zone_map) -> tuple[list[dict], int]:
entries = []
scanned = 0
for filepath in files:
if zone_map and zone in (GENERATED, VENDOR):
continue
try:
content = Path(filepath).read_text(errors="replace")
except OSError:
continue
scanned += 1
lines = content.splitlines()
# detector-specific logic
return entries, scanned
The boilerplate iteration + zone checking + file reading is repeated 3 times with slight variations.
Recommendation: Extract a common security_detector_wrapper() function that handles file iteration, zone filtering, and error handling, passing a checker function.
5. Finding Entry Creation Duplication
Finding creation pattern repeated across multiple detectors:
/Users/user_c042661f/Documents/desloppify/desloppify/detectors/security.py:226-247 - _make_entry() function creates normalized finding dicts
Same pattern in /Users/user_c042661f/Documents/desloppify/desloppify/lang/python/detectors/security.py:29-34 (imports and calls _make_entry())
Same pattern in /Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/detectors/security.py:55 (imports and calls _make_entry())
The _make_entry() function is defined once but the pattern of building finding dicts appears in 10+ other files with slight variations.
Recommendation: Consolidate finding factories further. Perhaps create make_detector_finding(detector_name, **kwargs) in a central location.
6. Detector Registry Boilerplate (Python vs TypeScript)
This pattern appears 8+ times across both language configs.
Recommendation: Create a phase_runner() decorator/factory that accepts detector function, finding factory, and name.
7. Extractors Duplication (Python vs TypeScript)
Similar structure, different implementations:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/python/extractors.py:12-19 - _read_file() function
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/extractors.py - No _read_file(), uses inline Path().read_text()
Both implement similar parameter extraction logic:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/python/extractors.py:47-150 - extract_py_functions() with multi-line signature handling
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/extractors.py:1-150 - extract_ts_functions() with similar logic but for TS syntax
The signature parsing, parameter extraction, and function body detection are language-specific but share common algorithmic patterns.
Recommendation: Extract common logic into lang/base.py or lang/extractor_base.py for shared patterns, keeping only syntax-specific code in language plugins.
8. Smell Detection Registry Duplication
Python smells definition:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/python/detectors/smells.py:16-73 - _smell() helper + SMELL_CHECKS list (35 smell types)
TypeScript smells definition:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/detectors/smells.py:27-180 - Dict list with same info (25 smell types)
Duplication:
Both define "magic_number", "todo_fixme", "hardcoded_url", "debug_tag", "workaround_tag" (5 overlapping smells)
Same structure repeated in Python (using _smell() helper) and TypeScript (using dicts)
Both files have similar line-by-line processing patterns (76-120 lines are nearly identical)
Both define overlapping patterns (e.g., generated files, test dirs, config files) with language-specific variations. Common patterns:
Zone.GENERATED - could be unified
Zone.TEST - both define variations of test directory patterns
Zone.CONFIG - both define config file patterns
Summary of Duplication Metrics
Category
Files Affected
Severity
Abstraction Opportunity
File I/O with error handling
36+
High
Centralize in utils.py
Exception handling (OSError)
36+
High
Decorator/context manager
Group-by-file logic
22+
Medium
Utility function
Security detector structure
3
Medium
Common wrapper function
Finding creation
10+
Medium
Factory consolidation
Phase runners
8+
Medium
Decorator factory
State load/save
10+
Low
Decorator/context manager
Smell registry
2
Medium
Unified registry in base
Zone classification
2
Low
COMMON_ZONE_RULES expansion
Signature parsing
2
Low
Shared helper module
The most impactful refactoring would be consolidating file I/O patterns (items 1-2), which affects 36+ files and have a unified solution already in utils.py.
Issue 4: Broad Exception in typescript fixers/common.py (line 125)
Problem: Backup file load and corruption rename both silently swallow errors. While they provide context in the outer except block, these inner exceptions are masked completely. If rename fails, no error is logged.
Problem: Dep graph build failures are completely silent. Users have no indication that this critical feature failed.
Issue 3: config.py (lines 187, 195)
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/config.py:186-195
except OSError:
pass # ← SILENT SWALLOW during migration
...
except OSError:
pass # ← SILENT SWALLOW during config save
Problem: Config migration and save failures are silently ignored. If config can't be saved, users won't know — state could be corrupted without warning.
Issue 4: narrative/core.py (lines 54-58)
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/narrative/core.py:54-57
if readme_path.exists():
try:
in_readme = "scorecard.png" in readme_path.read_text()
except OSError:
pass # ← SILENT SWALLOW
Problem: README read failure is silently ignored. Badge status will incorrectly show as "not in README" when the error was the read failure.
Problem: Date parsing errors are silently skipped with a vague comment. No diagnostic info about which finding or field had the malformed date.
3. INCONSISTENT ERROR HANDLING STRATEGIES
Pattern A: Silent Pass (found in multiple files)
state.py: backup load, rename failures
config.py: migration and save
narrative/core.py: README reads
visualize.py: file reads, ImportError
Pattern B: Return None/Empty (found in detector code)
python/detectors/unused.py: Returns None on ruff/pyflakes failure (lines 48-49, 102)
python/detectors/deps.py: Returns on parse errors (lines 31-32)
typescript/detectors/unused.py: Catches OSError/ValueError but defaults to "imports" (lines 61-62, 94)
Pattern C: Continue/Skip (found in loops)
config.py:160: Continue on JSON parse error during migration
issues.py:88: Continue on parse error in loop
python/detectors/security.py:237: Continue on OSError in file read loop
Pattern D: Log and Continue
python/detectors/unused.py: Returns None to indicate failure (caller handles)
typescript/detectors/deps.py: Returns fallback on JSON parse (lines 48-49, 61)
Inconsistency: Some failures are silent (state.py), some return None (unused.py), some default/fallback (deps.py). No unified strategy — makes debugging hard.
Problem: Template HTML file read has NO error handling. If file is missing/corrupted, users get unhandled OSError traceback instead of helpful message.
Issue 2: Unhandled read_text() in finding_factories.py
python
# Multiple detector files call .read_text() with no exception handling:
# - lang/python/detectors/smells_ast.py:543
# - lang/typescript/detectors/unused.py:73
# - lang/python/detectors/dict_keys.py:98
Problem: File content retrieval during detection can fail but is unguarded. Could crash mid-scan without context.
Issue 3: Subprocess calls have timeout but no CalledProcessError in some cases
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/unused.py:31-36
result = subprocess.run(
["npx", "tsc", ...],
capture_output=True, text=True, cwd=PROJECT_ROOT,
timeout=120,
shell=(sys.platform == "win32"),
)
# ← No exception handling — tsc compile errors won't be caught
Problem: tsc is run with shell=True on Windows but subprocess exceptions aren't caught. Non-zero exit codes are ignored.
Issue 4: JSON parsing without full error context
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/lang/python/detectors/unused.py:54-57
try:
diagnostics = json.loads(result.stdout)
except json.JSONDecodeError:
return None # ← No context about what failed
Problem: JSON decode failure returns None silently. If ruff output was truncated or corrupted, users get no diagnostic info — just "unused detection failed."
Issue 5: Package.json reads in TypeScript deps.py
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/detectors/deps.py:47
data = json.loads(config_path.read_text(errors="replace"))
# ← Uses errors="replace" which silently corrupts data, then JSONDecodeError
Problem: Reading with errors="replace" masks encoding issues. JSON parse failure will return fallback without telling user that config was corrupted.
# File: /Users/user_c042661f/Documents/desloppify/desloppify/lang/typescript/detectors/unused.py:70-94
except (OSError, UnicodeDecodeError):
pass
return "imports" # ← Default to imports with NO indication it was a fallback
Problem: If file read fails, the categorization silently defaults to "imports" (line 94). Next round of fixing could wrongly categorize unused vars as imports, then fail to remove them.
Issue 4: config.py - Migrated without user knowledge
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/config.py:185-195
try:
safe_write_text(sf, json.dumps(state_data, indent=2) + "\n")
except OSError:
pass # ← Silent failure to strip config from old state file
Problem: If state file can't be updated, config.json is written but the old state files still have duplicated config. No warning to user about inconsistency.
# File: /Users/user_c042661f/Documents/desloppify/desloppify/output/scorecard.py:104-118, 122-143
except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
pass # ← Silent fallback to directory name
Problem: If gh CLI or git command fails, badge generation uses directory name instead of repo name. No indication to user that they got a default, not the real project name. Makes badge useless without explanation.
6. RUNTIME ASSERTS (NOT FOR TESTS)
Issue 1: Python security detector uses assert for validation checks
python
# File: /Users/user_c042661f/Documents/desloppify/desloppify/lang/python/detectors/security.py:169-183
def _check_assert_security(self, node: ast.Assert):
"""Flag assert statements used for security checks (disabled in -O mode)."""
Note: This is a DETECTOR that flags problematic asserts in user code — not a runtime assertion in desloppify itself. This is correct usage.
Result: No improper runtime asserts found in the codebase. The codebase correctly avoids using assert for input validation.
Key Recommendation: Implement a centralized error handling strategy with specific exception types, consistent logging for failures, and meaningful error messages. Many failures silently degrade functionality without user visibility.
from ..review import _MIN_REVIEW_LOC, _LOW_VALUE_NAMES, _hash_file
from ..utils import rel, _read_file_text, resolve_path
Detectors layer imports from review module (higher-level orchestration)
desloppify/lang/base.py:176,182,228: Phase runners import specific detectors:
python
from ..detectors.dupes import detect_duplicates # line 176
from ..detectors.security import detect_security_issues # line 227
from ..detectors.test_coverage import detect_test_coverage # line 263
Clean in isolation, but these are inside shared phase functions, creating tight coupling.
5. Mixed Concerns — Logic + I/O + Display
Issue: Output formatting mixed with computation in multiple modules
desloppify/commands/scan.py (667 lines):
Lines 70-82: Display logic (_show_diff_summary)
Lines 95-127: Score computation and formatting (_show_score_delta)
Lines 300: Terminal output via colorize
Lines 320-331: State serialization (_write_query)
Lines 337-362: Image generation (scorecard badge)
Expected: Separate computation module + command-specific display layer
desloppify/commands/show.py:
Lines 57-120+: Filtering + matching logic mixed with terminal printing
_format_detail() (lines 37-54) mixes data transformation with display formatting
desloppify/output/scorecard.py (300+ lines):
Lines 15-33: Color computation (pure)
Lines 36-81: Font loading and image generation (I/O)
Lines 96-200: Project name resolution (system I/O + API calls)
All mixed in a single module without clear separation
desloppify/narrative/core.py:
Lines 42-69: _compute_badge_status() performs file I/O and README parsing
Should be in a separate I/O layer
6. Narrative Package Structure Issues
Issue: Large re-export facade in desloppify/narrative/__init__.py
Lines 11-39 import from 7 submodules, then lines 41-66 re-export everything. This creates tight coupling:
python
from ._constants import (...) # 5 items
from .core import (...) # 3 items
from .phase import (...) # 2 items
from .dimensions import (...) # 3 items
from .actions import (...) # 2 items
from .headline import (...) # 1 item
from .reminders import (...) # 2 items
from .strategy import (...) # 6 items
Problem: 24+ re-exported names mean consumers don't know which submodule is responsible. Testing/refactoring becomes complex. The comment "avoid import cycles" (line 9) signals the real issue: circular dependencies were resolved via this facade.
7. Review Module Complexity
Issue: Heavy aggregation of concerns in desloppify/review/__init__.py
Lines 10-63 orchestrate 6 separate submodules in a single facade:
dimensions.py - prompt + dimension templates
context.py - context building (23 helper functions)
context_holistic.py - holistic context
selection.py - file selection heuristics
prepare.py - preparation for AI evaluation
import_findings.py - finding import + storage
remediation.py - plan generation
Impact:desloppify/detectors/review_coverage.py:3 imports from this high-level module, creating upward layer violation.
8. Dependency Graph Module Anti-Pattern
desloppify/detectors/graph.py:18-19:
python
from .. import utils as _utils_mod
_extra_exclusions = _utils_mod._extra_exclusions
Issue: This is a workaround for Python's import binding problem:
from ..utils import _extra_exclusions would bind to the initial value
Module-level reassignment via set_exclusions() wouldn't propagate
The module-import pattern forces late lookup every time
Root cause: Global mutable state without proper initialization/injection pattern.
9. Configuration Leakage Across Layers
Issue: Runtime config passed through LangConfig object
desloppify/lang/base.py:100-105 shows config bleeding into the language layer:
python
_review_cache: dict = field(default_factory=dict, repr=False)
_review_max_age_days: int = field(default=30, repr=False)
_props_threshold: int = field(default=0, repr=False)
_complexity_map: dict = field(default_factory=dict, repr=False)
Problem: These fields are mutated at scan time (desloppify/commands/scan.py:229-237). The LangConfig becomes both a configuration object AND a state-carrying object, violating single responsibility.
10. Finding Factories Import Awkwardness
desloppify/lang/base.py:108-112:
python
from .finding_factories import (
make_unused_findings, make_dupe_findings, ...
)
This import happens AFTER the LangConfig dataclass definition. The module is small enough to live in lang/base.py directly, but separation creates an extra import edge.
11. Scoring Module Duplication
desloppify/scoring.py and desloppify/state.py both define tier weights:
_merge_and_persist(state, findings, diff) → returns updated state
_present_results(state, diff, lang, badge_path) → pure printing
move.py:_cmd_move_dir() (199 LOC) — Complex state machine
Issues:
Five nested loops (lines 325-367):
python
for src_file, dst_file in file_moves:
for filepath, replacements in importer_changes.items():
if filepath in moving_files:
if filepath in intra_pkg_changes:
if lang_name == "python":
for old_str, new_str in self_changes:
Indentation reaches 5 levels at lines 354-361
Two-phase apply (lines 417-462):
Phase 1: Compute all new contents (lines 418-422)
Phase 2: Execute with rollback (lines 425-462)
But rollback is deeply nested (try/except/for inside exception handler)
Duplication with cmd_move() (56 LOC at line 211):
Both functions handle language detection, file finding, replacement computation
5+ detector modules (smells_ast.py, react.py, test_coverage.py, phases.py) with too many responsibilities per file
30+ long functions (>50 LOC) lacking clear single responsibility
Complex conditional chains especially in pattern detection (smells_ast.py: 17 elifs, scan.py: 112 ifs)
Deep nesting (4-5 levels) in AST processing and file move logic
Recommended initial focus: Break up cmd_scan(), _cmd_move_dir(), and utils.py first, as they're high-traffic and block other improvements.
phase_dupes()
phase_security()
phase_test_coverage()
/Users/user_c042661f/Documents/desloppify/desloppify/narrative/phase.py:6-47: Detection functions use underscore: _detect_phase(), _detect_milestone()
/Users/user_c042661f/Documents/desloppify/desloppify/lang/base.py line 198: But then find_external_test_files() is PUBLIC without underscore
Inconsistency: Same architectural role (phase runners), but split between:
Private _phase_* functions in lang-specific modules
Public phase_* functions in base.py (dupes, security, test_coverage)
3. Findings Factory Functions Use "make_*" Prefix
Inconsistency in factory pattern naming:
/Users/user_c042661f/Documents/desloppify/desloppify/lang/finding_factories.py uses make_* prefix for all 8 factory functions:
make_unused_findings() (line 12)
make_dupe_findings() (line 30)
make_single_use_findings() (line 70)
make_cycle_findings() (line 115)
make_orphaned_findings() (line 137)
make_smell_findings() (line 155)
make_passthrough_findings() (line 182)
make_facade_findings() (line 204)
But state.py:247 uses a different name entirely: make_finding() (singular, the builder itself)
4. Module Organization Issues — Naming Mismatch
File Movement Without Name Updates:
/Users/user_c042661f/Documents/desloppify/desloppify/output/scorecard.py and visualize.py were moved from root but functions still have root-like naming
/Users/user_c042661f/Documents/desloppify/desloppify/narrative/ is a package split from former narrative.py but has unclear module boundaries:
by_file: dict[str, list[dict]] = defaultdict(list)
for e in entries: # "e" is shorthand
by_file[e[file_key]].append(e)
for filepath, file_entries in sorted(by_file.items()): # Suddenly "file_entries"
Parameter: entries: list[dict]
Internal loop: e (shorthand, no clear type)
Nested grouping: file_entries (different name, suggests different type but it's the same)
This pattern repeats in ALL fixer functions (imports.py, logs.py, params.py, etc.)
fix_cmd.py needs 5-8 unit tests for fixer dispatch
review_cmd.py needs 4-6 tests for review workflow
Commands are tested indirectly through CLI/integration tests but would benefit from direct unit tests
Test Execution Summary
code
Total Test Items: 2,212
Total Test Files: 72
Total Test Lines: 26,851
Passing Tests: 2,209 (99.9%)
Failing Tests: 1 (test_issues.py deterministic ordering)
Test Execution: 2.13 seconds
The test suite is mature and comprehensive with excellent coverage of detector logic and architectural enforcement, but would benefit from direct unit tests for utility functions and private_imports/layer_violation detectors.