I need to understand what each detector in scripts/decruftify/detectors/ actually does at a fundamental level — what does it extract from source files, and what analysis does it perform on that extraction?
For each top-level detector file in scripts/decruftify/detectors/ (NOT the py/ subdirectory), read the main detect_* function and tell me:
What it extracts from files (e.g. "function signatures", "import statements", "regex matches")
What analysis it does on the extracted data (e.g. "counts properties", "builds a graph and finds cycles")
Whether the extraction is inherently TS-specific or could work for any language
Also do the same for each file in scripts/decruftify/detectors/py/ — tell me how the Python version differs from the TS version.
Be thorough — read every detect_* function. I need the actual details, not summaries from filenames.
Assistant
I'll systematically read each detector file to understand their extraction and analysis methods.
Assistant
Now I'll read each detector file systematically. Let me start with the top-level detectors directory.
Assistant
Now let me read the Python-specific detectors in the py/ subdirectory.
Assistant
Perfect. I've now read all detector files systematically. Let me compile a comprehensive analysis for each detector.
Complete Detector Analysis
I've systematically read every detector file. Here's what each one extracts and analyzes:
Uses dependency graph from deps.py (imports/importers sets)
File path prefixes to classify shared/ vs tools/
Analysis:
Violations: Finds shared/ files that import from tools/ (backward dependency)
User
I need to understand the extraction patterns across all detectors to design a shared extractor layer. For each of these files, I need to know EXACTLY what regex/parsing they use to extract structures from source code:
scripts/decruftify/detectors/complexity.py - what signals does it extract and how?
scripts/decruftify/detectors/gods.py - how does it extract component/hook info?
scripts/decruftify/detectors/dupes.py - how does it extract and normalize function bodies?
scripts/decruftify/detectors/smells.py - what's the pattern/rule structure?
scripts/decruftify/detectors/large.py - what does it extract beyond LOC?
scripts/decruftify/detectors/concerns.py - what patterns does it look for?
scripts/decruftify/detectors/props.py - how does it extract interfaces?
scripts/decruftify/detectors/passthrough.py - the new one, how does it extract components?
Then do the same for the Python equivalents:
9. scripts/decruftify/detectors/py/complexity.py
10. scripts/decruftify/detectors/py/gods.py
11. scripts/decruftify/detectors/py/dupes.py
12. scripts/decruftify/detectors/py/smells.py
For each file, I specifically need:
The exact regex patterns used to find functions/classes/components
How body extent is determined (brace tracking? indentation? something else?)
What normalization is done before analysis
What the output structure looks like
Be very thorough - read every file completely. I need the raw details to design shared extractors.
Assistant
I'll analyze each detector's extraction patterns systematically. Let me read all the files to understand their exact parsing approaches.
User
I need to understand the "already generic" detectors and where they have language-specific leaks. Read these files thoroughly:
scripts/decruftify/detectors/graph.py - the graph algorithms
scripts/decruftify/detectors/orphaned.py - especially look for hardcoded TS patterns like --include=*.ts, index.ts, entry point patterns
scripts/decruftify/detectors/single_use.py - especially look for hardcoded TS patterns like index.ts, types.ts
scripts/decruftify/detectors/coupling.py - boundary rules, any TS-specific assumptions
scripts/decruftify/detectors/naming.py - any TS assumptions
scripts/decruftify/detectors/deps.py - the TS import graph builder
scripts/decruftify/detectors/py/imports.py - the Python import graph builder
For deps.py and py/imports.py, I need to understand:
What graph structure they return (same format? different?)
What keys/fields the graph dict has
Whether the downstream consumers (graph.py, orphaned.py, single_use.py, coupling.py) would work with either graph format
For orphaned.py and single_use.py:
List every hardcoded string that's TS-specific
What parameters they already accept for language-specific config vs what's hardcoded
Also read:
8. scripts/decruftify/lang/base.py - the LangConfig base class, what it already parameterizes
Assistant
I'll read through all these files to understand the language-specific leaks in the "already generic" detectors.
User
I need to understand the detectors that are inherently framework-specific (React, TS) and how the lang configs currently wire everything together.
Read these files:
scripts/decruftify/detectors/react.py - what does it detect, is any of it generalizable?
scripts/decruftify/detectors/logs.py - console.log detection, any general pattern?
scripts/decruftify/detectors/exports.py - dead export detection
scripts/decruftify/detectors/deprecated.py - deprecated symbol detection
scripts/decruftify/detectors/unused.py - the TS unused detector (tsc-based)
scripts/decruftify/detectors/py/unused.py - the Python unused detector (ruff-based)
Then read the full lang configs to understand orchestration:
8. scripts/decruftify/lang/typescript.py - full file, how phases are structured
9. scripts/decruftify/lang/python.py - full file, how phases are structured
10. scripts/decruftify/lang/__init__.py - registration mechanism
11. scripts/decruftify/lang/base.py - the base class
I need to understand:
What the phase runner pattern looks like
How findings are created from detector output
What LangConfig already parameterizes vs what it should
The registration mechanism
Also check: scripts/decruftify/commands/detect.py - how the CLI dispatch works for decruftify detect <name>, since this has its own hardcoded detector list.
Assistant
Now let me check if naming.py exists.
Assistant
I'll read through all these files to understand the framework-specific detectors and language configuration system.
Assistant
Now let me check the utils.py to understand what find_ts_files does.
Assistant
Perfect. Now I have all the information needed. Let me compile a comprehensive analysis.
Analysis: Language-Specific Leaks in "Already Generic" Detectors
1. Graph Algorithms (graph.py)
Status: Fully language-agnostic
Works with any graph structure conforming to: {resolved_path: {"imports": set, "importers": set, "import_count": int, "importer_count": int}}
No hardcoded patterns or language-specific logic
Optional deferred_imports field for cycle detection (used by Python, ignored if missing)
lang/typescript.py and lang/python.py — phase runners that wire detectors to findings
lang/base.py — LangConfig base class
commands/detect.py — CLI dispatch with hardcoded detector map
Key Problems
TS leaks in "generic" detectors: orphaned.py hardcodes --include=*.ts and TS entry patterns; single_use.py hardcodes ("index.ts", "index.tsx", "types.ts"); naming.py hardcodes TS skip patterns and uses find_ts_files()
Duplicated implementations: complexity, gods, dupes, smells all have separate TS and Python versions with the same analysis logic but different syntax extraction
Confusing structure: No way to tell from directory layout which detectors are generic vs TS-specific
Adding a language requires rewriting 6+ detectors
Detailed Audit Findings
Detectors that should be generic (same algorithm, different extraction):
complexity.py (TS) vs py/complexity.py:
Both count file-level signals and compute weighted scores
PY signals: import count, max function params, indentation depth, long functions, class count, nested comprehensions, TODOs
Same scoring approach, different regex patterns and weights
gods.py (TS) vs py/gods.py:
TS: counts React hooks (context, effect, state, ref, custom) at file level. Flags ≥3 context hooks OR ≥4 effects OR ≥5 states OR ≥8 custom OR ≥15 total OR ≥2 reasons
PY: counts methods, attributes, base classes within class bodies. Uses indentation tracking. Flags ≥15 methods OR ≥10 attributes OR >2 bases OR long methods OR score ≥25
Different extraction (TS=file-level hooks, PY=class-level methods/attrs) but both are "too many responsibilities" detection with threshold rules
Assistant
I'll start by thoroughly exploring the current codebase to understand every file, its structure, and dependencies before designing the plan.
Assistant
Now let me read all the key files in detail.
Assistant
Now let me read all the individual detectors to understand their internals.
Assistant
Now let me read the remaining key detectors - smells, orphaned, single_use, naming, large, and the utility functions.
Assistant
Now let me read the remaining files I need - the utils, passthrough detector, and the remaining framework-specific detectors.
Assistant
Let me also read the remaining detectors and the CLI for full context.
Assistant
Let me also check the remaining detectors I haven't read, plus the fixers and scan command.
Assistant
Now let me read plan.py and the state module to understand how findings flow through the system.
Assistant
Now let me check the fixers directory to understand any cross-references.
Assistant
Now I have a thorough understanding of the entire codebase. Let me check one more thing -- the STRUCTURE.md file and the existing plan files for context on what's already been considered.
Assistant
Now I have a comprehensive understanding of the entire system. Let me compile the detailed phased implementation plan.
Multi-Language Detector Refactoring: Detailed Phased Implementation Plan
Current State Summary
The codebase spans 5,051 lines across detectors, lang configs, and supporting infrastructure. The existing multi-language architecture (LangConfig, phase runners, language registry) is solid -- the problem is that the detectors themselves have language-specific code baked in, and the four detectors that exist in both TS and Python versions (complexity, gods, dupes, smells) duplicate their core algorithms.
Here is the precise inventory:
Total detector files: 21 (in detectors/) + 6 (in detectors/py/) = 27 files, ~4,100 LOC
Files that call find_ts_files() or find_tsx_files() directly (hardcoded TS):
complexity.py (line 13: find_ts_files)
gods.py (line 7: find_tsx_files)
dupes.py (line 100: find_ts_files)
smells.py (line 95: find_ts_files)
large.py (line 13: find_ts_files)
naming.py (line 69: find_ts_files)
concerns.py (line 17: find_tsx_files)
react.py (line 22: find_tsx_files)
props.py (line 16: find_ts_files)
passthrough.py (line 116: find_tsx_files)
Files that hardcode TS-specific barrel/skip names:
single_use.py line 22: ("index.ts", "index.tsx", "types.ts")
orphaned.py lines 45-46: --include=*.ts --include=*.tsx in subprocess calls
Phase 0: Bug Fixes (no architecture changes)
Goal: Fix the 4 known bugs immediately, before any refactoring. Each fix is trivial and surgically targeted.
0a: Fix orphaned.py hardcoded extensions
User
Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
Before providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
The user's explicit requests and intents
Your approach to addressing the user's requests
Key decisions, technical concepts and code patterns
Specific details like:
file names
full code snippets
function signatures
file edits
Errors that you ran into and how you fixed them
Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Double-check for technical accuracy and completeness, addressing each required element thoroughly.
Your summary should include the following sections:
Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
Assistant
Initial task: User asked to implement a plan for adding a Passthrough Detector to Decruftify. The plan was already written in the plan file.
Implementation of passthrough detector: I read existing files (props.py, lang/typescript.py, lang/python.py, commands/detect.py, cli.py, state.py, utils.py) to understand patterns, then:
Created scripts/decruftify/detectors/passthrough.py (~220 LOC)
Modified lang/typescript.py to wire passthrough into _phase_structural
Modified lang/python.py to wire passthrough into _phase_structural
Modified commands/detect.py to add passthrough to detector_cmds
Modified cli.py to add passthrough to DETECTOR_NAMES
Testing: TSX detector found 8 passthrough components. Python detector found 0 (expected). Full scan integrated cleanly. No false positives on settings forms or VideoEditPanel.
Error: Python CLI test failed with wrong arg order (--lang python after detect subcommand). Fixed by putting --lang before detect.
User asked about language differentiation: I explained the three patterns: shared core, separate implementations, and generic detectors.
User asked about scaling: I launched explore agents to audit all detectors, then presented a comprehensive analysis of current patterns and proposed architecture.
User asked for a holistic plan: I entered plan mode, launched 3 explore agents in parallel for deep analysis, then a Plan agent. The initial plan had 10 phases.
User feedback - known bugs: User provided 4 known issues (orphaned.py TS bias, PY_ENTRY_PATTERNS missing /lang/, Python complexity threshold, single_use.py hardcoded names).
User asked about lazy spots/awkward differentiations: I identified 7 issues:
TS as privileged default
Plan doesn't fix confusing directory structure
Inconsistent smell helper locations
passthrough.py with both languages in one file
Phase 4 as mechanical busywork
Ignoring existing LangConfig fields
Hand-wavy cmd_* story
for file layout question.
Dataset releases
Not yet included in a published release.
Boundary candidates: Finds shared/ files whose importers ALL come from a single tool
Cross-tool: Finds tools/A files importing from tools/B
Language-specific: No (path-based analysis, language-agnostic graph)
deprecated.py (detect_deprecated)
Extracts:
Lines containing @deprecated via grep
Symbol names following the annotation (reads file to parse context)
Symbol kind (top-level vs property)
Analysis:
For top-level symbols: counts external importers via grep
Flags symbols with zero importers as safe to remove
Language-specific: Partially (uses TypeScript JSDoc conventions but concept applies to any language)
deps.py (build_dep_graph)
Extracts:
Import statements via grep from\s+['\"]
Module paths from from 'module' patterns
Resolves relative imports (./../) and alias imports (@/)
The architecture is modular and language-aware: core graph algorithms are shared, language-specific parsers are isolated, and most detectors implement a generic concept that could be applied to any language with appropriate extraction logic.
Line 22: if basename in ("index.ts", "index.tsx", "types.ts"): - hardcoded barrel/types pattern
Parameters accepted:
None - function signature is detect_single_use_abstractions(path: Path, graph: dict)
What's missing from parameters:
Barrel file names to skip
Types file patterns to skip
LOC thresholds (currently 20-300, hardcoded lines 25-26)
4. Coupling Detector (coupling.py)
Status: Project-specific architecture, not language leaks
Hardcoded project structure (lines 16-18, 44-46):
SRC_PATH constant
shared_prefix = f"{src}/shared/"
tools_prefix = f"{src}/tools/"
Line 55: if f"{src}/shared/components/ui/" in filepath: - project-specific shadcn path
Analysis: This detector is fundamentally project-specific (reigh's shared/tools architecture). The "leaks" here are actually the detector's purpose - enforcing reigh's specific boundaries. However, the boundary logic itself is generic.
What LangConfig already provides:
boundaries: list[BoundaryRule] (lines 39-43 in base.py) - defines protected/forbidden pairs
Status: Already parameterized via LangConfig.boundaries, but the detector implementation hardcodes reigh paths instead of using the boundaries config.
Python graph includes an additional deferred_imports: set field, which is:
Only used by graph.py's detect_cycles() (lines 34-39) when skip_deferred=True
Safely ignored by all other consumers (orphaned, single_use, coupling) - they only read imports/importers/import_count/importer_count
Conclusion: The graph structure is already effectively language-agnostic. Python's deferred_imports is an optional extension that doesn't break compatibility.
def _load_all():
import importlib
lang_dir = Path(__file__).parent
for f in sorted(lang_dir.glob("*.py")):
if f.name in ("__init__.py", "base.py"):
continue
module_name = f.stem
importlib.import_module(f".{module_name}", __package__)
What it extracts: Complete function/component bodies
Regex patterns (function declaration):
python
fn_re = re.compile(
r"^(?:export\s+)?(?:"
r"(?:function\s+(\w+))|" # function Name
r"(?:const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*(?:\([^)]*\)|[^=])*=>)|" # const Name = (...) =>
r"(?:const\s+(\w+)\s*(?::\s*[^=]+)?\s*=\s*function)" # const Name = function
r")"
)
Body extraction method:
Brace tracking: Starts at function declaration line
Walks forward character-by-character tracking { and } depth
Stops when found_open == True and brace_depth <= 0
Returns lines[start_line:end_line+1]
Normalization (_normalize_body):
Strip lines that:
Are empty or whitespace-only
Start with // or /* or * (comments)
Contain console. (logging)
Join remaining lines with \n
Compute MD5 hash of normalized body
Output structure:
python
{
"file": str,
"name": str,
"line": int,
"end_line": int,
"loc": int,
"body": str, # raw body
"normalized": str, # cleaned for comparison
"hash": str # MD5 of normalized
}
Duplicate detection:
Phase 1: Exact duplicates via hash match
Phase 2: Near-duplicates via difflib.SequenceMatcher on normalized bodies (threshold 0.8)
Only compares functions within 50% size of each other
Change: Accept extensions parameter, default to [".ts", ".tsx"]. The calling function detect_orphaned_files already receives extra_entry_patterns and extra_barrel_names -- add an extensions parameter the same way.
python
def _build_dynamic_import_targets(path: Path, extensions: list[str] | None = None) -> set[str]:
if extensions is None:
extensions = [".ts", ".tsx"]
include_args = [f"--include=*{ext}" for ext in extensions]
# ... use include_args in both subprocess calls
Currently PY_ENTRY_PATTERNS (lines 110-118) is missing the /lang/ pattern. Lang config files get flagged as orphaned because they're loaded dynamically via importlib.
Currently line 85: if signals and score >= 15:. Python scoring uses different weights that produce higher scores for equivalent complexity. The threshold should be 25.
Change:
python
if signals and score >= 25: # Python weights produce higher scores; 25 ≈ TS's 15
Currently line 22: if basename in ("index.ts", "index.tsx", "types.ts"):. This should come from LangConfig.
Change: Add barrel_names parameter:
python
def detect_single_use_abstractions(path: Path, graph: dict, *, barrel_names: set[str] | None = None) -> list[dict]:
_barrel_names = barrel_names or {"index.ts", "index.tsx", "types.ts"}
# ...
if basename in _barrel_names:
continue
Update Python lang caller:
python
single_entries = detect_single_use_abstractions(
path, graph,
barrel_names=lang.barrel_names | {"types.py"}, # or just lang.barrel_names
)
TS lang caller already passes through without barrel_names (gets the TS default).
LOC delta: ~+6 lines modified
Phase 0 total: ~16 LOC changed. Test: Run both decruftify scan --lang python and decruftify scan --lang typescript, compare finding counts against pre-fix baseline. Python should have fewer false-positive orphans (lang/ files no longer flagged) and a different complexity threshold.
Phase 1: Extend LangConfig with Missing Configuration
Goal: Add all configuration fields to LangConfig that detectors currently hardcode, so detectors can receive config instead of hardcoding. No detector changes yet -- just the config plumbing.
Phase 1 total: ~42 LOC added. Test: No behavior change expected. All new fields have defaults matching current hardcoded values. Run both scans, verify identical results.
Phase 2: Create Extractors Module
Goal: Create extractors/ with dataclasses and language-specific extraction functions. This pulls body-extraction logic OUT of the TS and Python duplicate detectors into reusable extractors.
New file:/Users/user_c042661f/Documents/reigh/scripts/decruftify/extractors/python.py
This extracts logic from:
detectors/py/dupes.pyextract_functions() (lines 11-112) and _normalize_body() (lines 115-169)
detectors/py/gods.py_analyze_classes() (lines 25-117) and _find_long_methods() (lines 120-152)
python
"""Python extraction functions."""
import hashlib
import re
from pathlib import Path
from ..utils import PROJECT_ROOT
from .base import FunctionInfo, ClassInfo
def extract_py_functions(filepath: str) -> list[FunctionInfo]:
"""Extract function bodies from a Python file.
Moved from detectors/py/dupes.py extract_functions().
Uses indentation to determine function extent.
"""
# ... exact logic from py/dupes.py lines 11-112, returning FunctionInfo objects
def normalize_py_body(body: str) -> str:
"""Normalize a Python function body for comparison.
Moved from detectors/py/dupes.py _normalize_body().
Strips: #, docstrings, print(), logging.*, blank lines.
"""
# ... exact logic from py/dupes.py lines 115-169
def extract_py_classes(filepath: str) -> list[ClassInfo]:
"""Extract class info from a Python file.
Moved from detectors/py/gods.py _analyze_classes().
Uses indentation tracking for class body extent.
Returns ClassInfo with method counts, attributes, base classes.
"""
# ... logic from py/gods.py lines 25-117, returning ClassInfo objects
LOC: ~220 (moved from existing files)
Phase 2 total: ~400 LOC in new files, but most is moved code, not new logic. Net new logic ~60 lines (dataclasses). Test: The extractors module exists but is not yet wired into any detectors. No behavior change. Write unit tests for extractors that verify they produce identical output to the existing inline functions.
Phase 3: Unify Duplicate Detection (dupes.py)
Goal: Make detectors/dupes.py generic. The analysis algorithm (hash grouping + SequenceMatcher) is identical; only the extraction differs.
3a: Rewrite detectors/dupes.py to accept FunctionInfo objects
Current signature: detect_duplicates(path: Path, threshold: float = 0.8) -> list[dict]
New signature: detect_duplicates(functions: list[FunctionInfo], threshold: float = 0.8) -> list[dict]
The new function receives pre-extracted functions (from extractors). The algorithm (lines 97-166) is unchanged -- just reads from FunctionInfo attributes instead of dict keys.
Also keep a thin wrapper for backward compatibility with cmd_dupes:
python
def detect_duplicates(functions: list, threshold: float = 0.8) -> list[dict]:
"""Find duplicate/near-duplicate functions.
Accepts either FunctionInfo objects or legacy dicts.
"""
# Phase 1: exact dupes by hash
# Phase 2: near-dupes by SequenceMatcher
# ... same algorithm, but accessing .body_hash/.normalized/.file/.name/.line/.loc
# with fallback to dict access for backward compat during migration
LOC delta: ~+15 (wrapper), -20 (removed _extract_functions, _normalize_body, find_ts_files import)
def _phase_dupes(path: Path, lang: LangConfig) -> list[dict]:
from ..extractors.typescript import extract_ts_functions
from ..detectors.dupes import detect_duplicates
from .base import make_dupe_findings
all_functions = []
for filepath in lang.find_files(path):
if "node_modules" in filepath or ".d.ts" in filepath:
continue
all_functions.extend(extract_ts_functions(filepath))
return make_dupe_findings(detect_duplicates(all_functions), _stderr)
LOC delta: ~+5 (extraction loop), -0 (was already a thin wrapper)
def _phase_dupes(path: Path, lang: LangConfig) -> list[dict]:
from ..extractors.python import extract_py_functions
from ..detectors.dupes import detect_duplicates
from .base import make_dupe_findings
all_functions = []
for filepath in lang.find_files(path):
all_functions.extend(extract_py_functions(filepath))
return make_dupe_findings(detect_duplicates(all_functions), _stderr)
LOC delta: ~+5
3d: Delete detectors/py/dupes.py
The Python dupes detector is now replaced by extractors/python.py + the generic detectors/dupes.py. Delete the file entirely.
LOC delta: -254
Phase 3 total: ~-230 net LOC (major dedup). Test: Run decruftify detect dupes --lang typescript and decruftify detect dupes --lang python. Compare exact finding output (IDs, similarity scores, function names) against pre-refactor baseline. Must be identical.
Phase 4: Unify God Object Detection (gods.py)
Goal: Make detectors/gods.py generic. Both versions answer "does this unit have too many responsibilities?" but extract different metrics (hook counts vs method/attribute counts).
4a: Rewrite detectors/gods.py to accept ClassInfo objects + rules
New approach: the detector receives a list of ClassInfo objects (already extracted) and a list of threshold rules. It evaluates rules against metrics and returns flagged entries.
python
"""God object detection: units with too many responsibilities."""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Callable
from ..utils import c, print_table, rel
@dataclass
class GodRule:
"""A single god-object threshold rule."""
name: str
description: str
extract: Callable # (ClassInfo) -> int
threshold: int
def detect_gods(classes: list, rules: list[GodRule], *, min_reasons: int = 2,
total_metric: str = "hook_total", total_threshold: int = 15) -> list[dict]:
"""Flag classes/components exceeding responsibility thresholds.
Args:
classes: ClassInfo objects (or legacy dicts with metrics).
rules: Threshold rules to evaluate.
min_reasons: Minimum rule violations to flag (default 2).
total_metric: Metric key for absolute total threshold.
total_threshold: If total_metric exceeds this, flag regardless of min_reasons.
"""
entries = []
for cls in classes:
reasons = []
for rule in rules:
value = rule.extract(cls)
if value >= rule.threshold:
reasons.append(f"{value} {rule.description}")
total = cls.metrics.get(total_metric, 0) if hasattr(cls, 'metrics') else 0
if len(reasons) >= min_reasons or total >= total_threshold:
entries.append({
"file": cls.file,
"loc": cls.loc,
"name": cls.name,
"total": total,
"reasons": reasons,
# Preserve backward-compat fields for TS
**{k: v for k, v in cls.metrics.items()},
})
return sorted(entries, key=lambda e: -e["total"])
LOC delta: ~+50 (new), -52 (removed TS-specific version) = -2 net
4b: Define TS god rules in lang/typescript.py
python
# In _phase_structural:
from ..detectors.gods import detect_gods, GodRule
from ..extractors.typescript import extract_ts_component_metrics
TS_GOD_RULES = [
GodRule("context_hooks", "context hooks", lambda c: c.metrics.get("context_hooks", 0), 3),
GodRule("use_effects", "useEffects", lambda c: c.metrics.get("use_effects", 0), 4),
GodRule("use_states", "useStates", lambda c: c.metrics.get("use_states", 0), 5),
GodRule("custom_hooks", "custom hooks", lambda c: c.metrics.get("custom_hooks", 0), 8),
]
# In _phase_structural():
components = []
for filepath in find_tsx_files(path):
info = extract_ts_component_metrics(filepath)
if info:
components.append(info)
for e in detect_gods(components, TS_GOD_RULES,
total_metric="hook_total", total_threshold=15):
# ... same finding normalization as before
4c: Define Python god rules in lang/python.py
python
from ..detectors.gods import detect_gods, GodRule
from ..extractors.python import extract_py_classes
PY_GOD_RULES = [
GodRule("methods", "methods", lambda c: len(c.methods), 15),
GodRule("attributes", "attributes", lambda c: len(c.attributes), 10),
GodRule("base_classes", "base classes", lambda c: len(c.base_classes), 3),
GodRule("long_methods", "long methods (>50 LOC)",
lambda c: sum(1 for m in c.methods if m.loc > 50), 1),
]
# In _phase_structural():
classes = []
for filepath in lang.find_files(path):
classes.extend(extract_py_classes(filepath))
for e in detect_gods(classes, PY_GOD_RULES,
total_metric="total_score", total_threshold=25):
# ... finding normalization
4d: Delete detectors/py/gods.py
LOC delta: -152
Phase 4 total: ~-100 net LOC. Test: Run structural detection for both languages, compare god-object findings against baseline. TS findings should show identical hook counts and reason strings. Python findings should show identical class/method/attribute counts.
PY_COMPLEXITY_SIGNALS = [
ComplexitySignal("imports", r"^(?:import |from )", weight=1, threshold=20),
ComplexitySignal("TODOs", r"#\s*(?:TODO|FIXME|HACK|XXX)", weight=2, threshold=0),
# ... long functions, deep nesting, many classes use compute= lambdas
]
5d: Delete detectors/py/complexity.py
LOC delta: -127
Phase 5 total: ~-50 net LOC. Test: Compare complexity scores file-by-file for both languages against baseline. Scores must match exactly.
Note: Some TS complexity signals (prop destructuring, nested ternaries, inline types) and Python signals (long functions, deep nesting, many classes) require compute= lambdas since they need multi-step logic beyond a single regex. These lambdas live in the lang config file, keeping the detector generic.
Phase 6: Unify Smells Detection (smells.py)
Goal: Make the single-line smell detection generic. Multi-line detection stays language-specific.
This is the most complex unification because smells.py has both:
The core loop (lines 91-116) is identical in both TS and Python:
python
for filepath in file_finder(path):
content = p.read_text()
lines = content.splitlines()
for check in SMELL_CHECKS:
if check["pattern"] is None:
continue
for i, line in enumerate(lines):
if re.search(check["pattern"], line):
smell_counts[check["id"]].append({...})
Add a generic function:
python
def detect_line_smells(path: Path, rules: list[SmellRule], file_finder: Callable,
string_checker: Callable | None = None) -> dict[str, list[dict]]:
"""Run single-line smell patterns across files.
Args:
rules: SmellRule definitions with regex patterns.
file_finder: Returns list of file paths to scan.
string_checker: Optional (line, match_start) -> bool to skip matches inside strings.
Returns:
Dict mapping rule.id to list of match dicts.
"""
6b: Keep multi-line detectors in language-specific locations
The TS multi-line detectors (_detect_async_no_await, _detect_error_no_throw, _detect_empty_if_chains, _detect_dead_useeffects, _detect_swallowed_errors) stay in detectors/smells.py since they use brace tracking.
The Python multi-line detectors (_detect_empty_except, _detect_swallowed_errors, _walk_except_blocks) stay in detectors/py/smells.py since they use indentation tracking.
6c: Wire from lang configs
Each lang calls detect_line_smells(path, RULES, lang.find_files) then adds multi-line results. This means detectors/py/smells.py shrinks to just the multi-line helpers (~80 lines), and detectors/smells.py gains the generic function.
Phase 6 total: ~-80 net LOC. Test: Compare smell findings per file. Line-by-line matches must be identical. The Python _match_is_in_string checker is passed as the string_checker parameter.
Phase 7: Parameterize Graph-Based Detectors
Goal: Remove hardcoded TS patterns from orphaned.py, single_use.py, naming.py, and large.py so they work with any language through LangConfig.
for e in detect_large_files(path, threshold=lang.large_threshold, file_finder=lang.find_files):
Phase 7 total: ~+30 LOC. Test: Run full scans for both languages. TS results must be identical to pre-refactor. Python results should now include naming analysis if enabled.
Phase 8: Wire find_files Through All Remaining Detectors
Goal: Replace all remaining find_ts_files() / find_tsx_files() calls in framework-specific detectors so they go through LangConfig.
This phase handles detectors that are inherently TS-specific but still shouldn't call find_ts_files directly -- they should use lang.find_files or a dedicated finder passed as a parameter.
Detectors to update:
concerns.py -- calls find_tsx_files(path). Since this is React-specific, it stays TS-only but should accept a file_finder param:
Currently has a 20-entry hardcoded detector_cmds dict (lines 30-51) that maps names to TS-specific module/function pairs. Replace with:
python
def cmd_detect(args):
from ..cli import _resolve_lang
lang = _resolve_lang(args)
if lang is None:
# Auto-detect
from ..lang import auto_detect_lang
from ..utils import PROJECT_ROOT
detected = auto_detect_lang(PROJECT_ROOT)
if detected:
from ..lang import get_lang
lang = get_lang(detected)
detector = args.detector
# Validate detector name
if lang and lang.detector_names and detector not in lang.detector_names:
print(c(f"Unknown detector for {lang.name}: {detector}", "red"))
print(f" Available: {', '.join(sorted(lang.detector_names))}")
sys.exit(1)
# Check for language-specific command override
if lang and hasattr(lang, 'detect_commands') and detector in lang.detect_commands:
lang.detect_commands[detector](args)
return
# Fall through to generic dispatch (shared detectors that work for any language)
_generic_dispatch(args, detector, lang)
9b: Move TS-specific cmd_* functions into lang/typescript.py as detect_commands
Already partially done. Extend PythonConfig with commands that route through the generic detectors with Python config.
Phase 9 total: ~+60 LOC, -30 LOC = +30 net. Test: Run every detect <name> command for both languages. Verify output matches.
Phase 10: Delete Redundant Files and Update Docs
Goal: Remove the now-empty detectors/py/ files that have been replaced, update STRUCTURE.md.
Files to delete:
detectors/py/complexity.py -- replaced in Phase 5
detectors/py/gods.py -- replaced in Phase 4
detectors/py/dupes.py -- replaced in Phase 3
detectors/py/smells.py -- reduced to multi-line helpers only (keep if still >0 LOC after Phase 6; delete if fully absorbed)
Files to keep in detectors/py/:
detectors/py/imports.py -- Python dep graph builder (syntax-specific, no TS equivalent sharing possible)
detectors/py/unused.py -- ruff-based (tool-specific, no sharing possible)
detectors/py/__init__.py
Update STRUCTURE.md
Reflect new extractors/ directory and reduced py/ directory.
Phase 10 total: ~-530 LOC deleted. Test: Full scan for both languages must produce identical results to Phase 9.
Summary Table
Phase
Description
Files Created
Files Modified
Files Deleted
Net LOC
Bug Fixes
0
Bug fixes
0
4
0
+16
All 4
1
LangConfig extension
0
3
0
+42
-
2
Extractors module
4
0
0
+400*
-
3
Unify dupes
0
3
1
-230
-
4
Unify gods
0
3
1
-100
-
5
Unify complexity
0
3
1
-50
-
6
Unify smells
0
3
0**
-80
-
7
Parameterize graph detectors
0
4
0
+30
-
8
Wire find_files everywhere
0
6
0
+40
-
9
Clean up detect command
0
3
0
+30
-
10
Delete + docs
0
1
3-4
-530
-
* Phase 2 is ~400 LOC but ~340 is moved code, only ~60 is new (dataclasses)
** Phase 6 may reduce py/smells.py to ~80 lines (multi-line helpers only) rather than deleting it
Net LOC change across all phases: approximately -430 lines (the codebase gets smaller)
Dependency Graph Between Phases
code
Phase 0 (bugs) -- standalone, do first
Phase 1 (LangConfig) -- standalone
Phase 2 (extractors) -- standalone
Phase 3 (dupes) -- depends on Phase 2
Phase 4 (gods) -- depends on Phase 2
Phase 5 (complexity) -- depends on Phase 1 (threshold config)
Phase 6 (smells) -- depends on Phase 1 (find_files config)
Phase 7 (graph) -- depends on Phase 0 + Phase 1
Phase 8 (find_files) -- depends on Phase 1
Phase 9 (detect cmd) -- depends on Phases 3-8
Phase 10 (cleanup) -- depends on Phases 3-6
Phases 0, 1, 2 can be done in parallel. Phases 3, 4, 5, 6, 7, 8 can be done in any order after their deps. Phase 9 and 10 come last.
Key Design Decisions
Why not a single extract_all() function per language? Because not all detectors need all extractions. Complexity doesn't need function bodies. Gods doesn't need normalized hashes. Running all extractors upfront would be wasteful for detect <single-detector> invocations. Instead, each phase calls the extractors it needs.
Why file_finder parameter instead of always going through LangConfig? Because detectors also have cmd_* CLI handlers that don't receive a LangConfig. The file_finder parameter with a default fallback to find_ts_files maintains backward compatibility for standalone detect usage while enabling generic use when called through the phase pipeline.
Why keep multi-line smell detection language-specific? Brace tracking (TS) and indentation tracking (Python) are fundamentally different parsing strategies. Abstracting them into a shared interface would create an awkward lowest-common-denominator API. It's cleaner to share the single-line loop (identical) and keep multi-line analysis per-language.
Why not introduce an AST? This tool scans large codebases quickly using regex + simple structural tracking. An AST (tree-sitter, etc.) would be more accurate but much slower. The current approach is the right trade-off for a CLI health scanner.
Critical Files for Implementation
/Users/user_c042661f/Documents/reigh/scripts/decruftify/lang/base.py - Core LangConfig dataclass to extend with new fields (find_files, thresholds, naming config)
/Users/user_c042661f/Documents/reigh/scripts/decruftify/detectors/dupes.py - Most impactful unification target: extract-then-analyze pattern template for all other detectors
/Users/user_c042661f/Documents/reigh/scripts/decruftify/detectors/orphaned.py - Has the most hardcoded TS assumptions to parameterize (subprocess calls, entry patterns, barrel names)
/Users/user_c042661f/Documents/reigh/scripts/decruftify/lang/typescript.py - Largest phase runner file (408 LOC); all phase functions must be updated to pass config to detectors
/Users/user_c042661f/Documents/reigh/scripts/decruftify/lang/python.py - Second phase runner (268 LOC); will gain signal/rule definitions as detectors become generic
Here's an example of how your output should be structured:
Key Technical Concepts:
[Concept 1]
[Concept 2]
[...]
Files and Code Sections:
[File Name 1]
[Summary of why this file is important]
[Summary of the changes made to this file, if any]
[Important Code Snippet]
[File Name 2]
[Important Code Snippet]
[...]
Errors and fixes:
[Detailed description of error 1]:
[How you fixed the error]
[User feedback on the error if any]
[...]
Problem Solving:
[Description of solved problems and ongoing troubleshooting]
All user messages:
[Detailed non tool use user message]
[...]
Pending Tasks:
[Task 1]
[Task 2]
[...]
Current Work:
[Precise description of current work]
Optional Next Step:
[Optional Next step to take]
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
Compact Instructions
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
IMPORTANT: Do NOT use any tools. You MUST respond with ONLY the ... block as your text output.
User chose "Move to detectors/ts/"
User pushed back again: "Is this a beautiful or even elegant structure? Think this through"
Final architecture insight: Extractors are part of the language, not the detector system. This led to the elegant structure where lang/X/ contains everything language-specific (config, extractors, detectors) and detectors/ is purely generic.
Key files I need to track:
The passthrough detector I already created and wired
The plan file at /Users/user_c042661f/.claude/plans/snug-whistling-crescent.md
All the existing detector files I read during exploration
The conversation ended with me writing the final plan and calling ExitPlanMode, but the user rejected it asking "Is this a beautiful or even elegant structure?" I then redesigned the architecture to the lang-package approach and rewrote the plan. The user hasn't yet approved the final plan.
Key Technical Concepts:
Decruftify: A Python-based codebase health scanner in scripts/decruftify/ that scans TypeScript and Python codebases
LangConfig system: Language configs in lang/ define phases, each phase runs detectors and normalizes output to findings via make_finding()
Three detector patterns identified: (1) Generic graph-based (graph.py, orphaned.py, single_use.py), (2) Separate implementations (complexity, gods, dupes, smells have TS + Python versions), (3) Shared core + lang functions (passthrough)
Strategy pattern for detectors: Generic algorithms accept normalized data + config (signals, rules, thresholds), languages provide extractors + config
Key data types proposed: FunctionInfo, ClassInfo, ComplexitySignal, GodRule, SmellRule
One-way import rule: lang/ imports from detectors/, never the reverse
Plan file: /Users/user_c042661f/.claude/plans/snug-whistling-crescent.md (WRITTEN - latest version)
Contains the full refactoring plan with 4 phases
Errors and fixes:
Python CLI arg order: python3 -m scripts.decruftify detect passthrough --lang python --path scripts/ failed because --lang is a global arg that must come before the subcommand. Fixed with python3 -m scripts.decruftify --lang python detect passthrough --path scripts/
Plan feedback iteration 1: User said plan was lazy — identified TS defaults, confusing directory structure not fixed, inconsistent smell helper locations, hand-wavy CLI story
Plan feedback iteration 2: User chose "Move to detectors/ts/" for file layout
Plan feedback iteration 3: User said "Is this a beautiful or even elegant structure?" — led to fundamental redesign from detectors/ts/ + extractors/ (3 directories) to lang/X/ packages (everything language-specific under one directory)
Problem Solving:
Passthrough detector implementation: COMPLETED and tested
Architecture refactoring plan: Iterated through 3 revisions based on user feedback, arriving at the lang/X/ package approach
Known bugs identified: 4 specific issues documented in the plan (orphaned.py extensions, PY_ENTRY_PATTERNS, complexity threshold, single_use barrel names)
All user messages:
"Implement the following plan: [passthrough detector plan]"
"Before you begin, how will we deal with the differences between Python and TypeScript?"
"Can you describe how we differentiate between different languages now? And how we have language specific detector adapters?"
"And will this scale well? For all the textures so far do we have something that's applied generically and that's something that works only for TypeScript and something that works only for Python? How does it all work currently?"
"Can you think through what a fundamentally better approach would be that would scale to many languages and be easy for a developer to understand and implement?"
"Yes, make a plan for how to tackle this holistically, don't be lazy."
"For context, here are some more problems we encountered - no need to fix, just consider: 1. orphaned.py — still has TS bias... 2. Python entry patterns... 3. Python complexity threshold... 4. single_use.py line 22..."
"Is there anything here where we're being lazy or that will create awkward differentiations between different languages?"
(Selected "Move to detectors/ts/" for file layout question)
"Is this a beautiful or even elegant structure? Think this through"
"Your task is to create a detailed summary..."
Pending Tasks:
The architecture refactoring plan has been written to the plan file but NOT yet approved by the user (ExitPlanMode was not called after the final revision)
The plan itself has 4 phases of implementation work that hasn't started
Current Work:
The plan file at /Users/user_c042661f/.claude/plans/snug-whistling-crescent.md has been written with the final elegant architecture:
lang/typescript/ = ALL TypeScript support (config + extractors + TS-only detectors like react, logs, exports, deprecated, concerns, patterns, props, smells multi-line helpers)
lang/python/ = ALL Python support (config + extractors + PY-only detectors)
One-way imports: lang/ → detectors/, never reverse
No language defaults, no TS-privileged fallbacks
I was still in plan mode and had just rewritten the plan file after the user's "Is this a beautiful or even elegant structure?" feedback. I had NOT yet called ExitPlanMode for this final version.
Optional Next Step:
Call ExitPlanMode to present the final plan for user approval. The user's most recent request before the summary was: "Is this a beautiful or even elegant structure? Think this through" — I responded by redesigning the architecture and rewriting the plan, but hadn't yet submitted it for approval.