Very thoroughly explore the dead_function detector implementation. I need to understand:
Where is it defined? Look in desloppify/lang/typescript/ and desloppify/detectors/ and similar paths
How does it detect dead functions? Does it do cross-file analysis or just single-file?
How does it check for references/usages?
What patterns could cause the 97% false positive rate described in the issue (functions called within same file, exported functions, callback references)
Search for "dead_function", "dead function", "unused function" across the codebase. Also look at how TypeScript smell detection works in general.
Assistant
I'll conduct a thorough exploration of the dead_function detector implementation. Let me start with comprehensive searches across the codebase.
User
Very thoroughly explore the async_no_await detector implementation. I need to understand:
Where is it defined? Look in desloppify/lang/typescript/ and desloppify/detectors/ and similar paths
How does it detect async functions without await? Does it parse the full function body or use regex?
What could cause it to miss await in multi-line functions (70% false positive rate)?
Search for "async_no_await", "async.*await", "no_await" across the codebase. Look at the TypeScript smell detection helpers too.
Assistant
Let me check the lang structure first:
Assistant
I'll thoroughly explore the async_no_await detector implementation. Let me start by searching for relevant files and code.
User
Very thoroughly explore the console_error_no_throw detector implementation. I need to understand:
Where is it defined? Look in desloppify/lang/typescript/ and desloppify/detectors/ and similar paths
How does it detect console.error without throw? What scope does it check?
Does it have any exclusion logic for error boundaries, logger files, toast patterns, etc.?
Search for "console_error_no_throw", "console_error", "no_throw" across the codebase.
Assistant
I see the repo structure is different from the memory file. Let me search more broadly:
Assistant
I'll thoroughly explore the console_error_no_throw detector implementation across the codebase.
Assistant
Now let me look at the key files that appeared in the grep results:
Assistant
Let me search with broader patterns to find the TypeScript detector structure:
Assistant
Now let me look at the TypeScript smell detector files:
Assistant
Now let me look at the helper functions and understand how the detection works more deeply:
Assistant
Now let me read the main detector files:
Assistant
Now let me look at the Python uncalled functions detector to see if there's a similar implementation that might be more comprehensive:
Assistant
Now let me look at the actual helper function implementation more closely:
Assistant
Perfect! Let me read the smell detectors files:
Assistant
Now let me look at the TypeScript unused detector:
Assistant
Let me search more specifically for how the detector is imported and used:
Assistant
Excellent! Now let me look for the test files to understand better how this detector works and what the false positives might be:
Assistant
Now let me look at the tests for dead_function to understand what it actually flags:
Assistant
Perfect! Now let me search for any exclusion patterns or special handling for this detector:
Assistant
Let me continue reading the test file to find dead_function tests:
Assistant
Now let me look at the actual invocation in the main smells.py file to see how it's called:
Assistant
Perfect! Now let me search for any issues or discussions about dead_function to understand the false positive problem better:
Assistant
Now let me search for more specific test cases and edge cases:
Assistant
Great! Now let me check the patterns file to understand error handling context:
Assistant
Let me check the git log and issues for any mention of dead_function:
Assistant
Now let me look at the scan_code function to understand how it works:
Assistant
Perfect! Now let me check if there are any reviewer patterns for console_error_no_throw:
Assistant
Let me look at that commit:
Assistant
Now let me look at the _smell_effects.py to understand the actual implementations being used:
Assistant
Now let me check if there's a GitHub issue about this:
Assistant
Let me check the test for smell helpers to get more details:
Assistant
Let me search for any actual issues or discussions about dead_function false positives in the codebase or documentation:
Assistant
Let me search for documentation or code comments about the 97% false positive rate:
Assistant
Let me check if there are any existing issues or discussions in the repository files:
Assistant
Now let me look at what functions actually call _detect_dead_functions to understand the detection flow more:
Assistant
Now let me create a comprehensive summary by looking at what the actual dead_function detection does:
Assistant
Perfect! Now let me compile my comprehensive findings. Let me create one final check to look at how the Python dead_function detector works for comparison:
Assistant
Perfect! Now I have a comprehensive understanding. Let me create a summary document:
Based on my thorough exploration of the codebase, here's a complete analysis of the console_error_no_throw detector:
Console Error No Throw Detector - Comprehensive Analysis
1. Location
The detector is defined in multiple connected locations:
Registration: /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/smells.py (lines 91-95 in TS_SMELL_CHECKS, called at line 612)
Tests: /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/test_ts_smells.py (lines 289-324) and /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/smells/test_ts_smell_helpers.py (lines 225-248)
2. How It Detects console.error Without Throw
The detection algorithm is straightforward and line-based:
python
def detect_error_no_throw(
filepath: str,
lines: list[str],
smell_counts: dict[str, list[dict]],
) -> None:
"""Find console.error calls not followed by throw or return."""
for index, line in enumerate(lines):
if "console.error" in line:
# Look ahead up to 3 lines after the console.error call
following = "\n".join(lines[index + 1 : index + 4])
# Check if throw or return appears in those 3 lines
if not re.search(r"\b(?:throw|return)\b", following):
# Flag it as a smell
smell_counts["console_error_no_throw"].append({
"file": filepath,
"line": index + 1,
"content": line.strip()[:100],
})
Assistant
Perfect! Now I have a comprehensive view. Let me create a detailed report on my findings:
Comprehensive Analysis of async_no_await Detector
1. Location & Definition
The async_no_await detector is defined in two places:
The detector uses a line-by-line scanning approach with brace-depth tracking. Here's the exact flow from _smell_helpers.py lines 79-123:
python
def _detect_async_no_await(
filepath: str, content: str, lines: list[str], smell_counts: dict[str, list[dict]]
):
"""Find async functions that don't use await.
Algorithm: for each async declaration, track brace depth to find the function
body extent (up to 200 lines). Scan each line for 'await' within those braces.
If the opening brace closes (depth returns to 0) without seeing await, flag it.
"""
async_re = re.compile(r"(?:async\s+function\s+(\w+)|(\w+)\s*=\s*async)")
for i, line in enumerate(lines):
m = async_re.search(line)
if not m:
continue
name = m.group(1) or m.group(2)
brace_depth = 0
found_open = False
has_await = False
for j in range(i, min(i + 200, len(lines))):
body_line = lines[j]
prev_code_ch = ""
for _, ch, in_s in scan_code(body_line):
if in_s:
continue
if ch == "/" and prev_code_ch == "/":
break # Rest of line is comment
elif ch == "{":
brace_depth += 1
found_open = True
elif ch == "}":
brace_depth -= 1
prev_code_ch = ch
if "await " in body_line or "await\n" in body_line:
has_await = True
if found_open and brace_depth <= 0:
break
if found_open and not has_await:
smell_counts["async_no_await"].append({...})
Assistant
Excellent! Now let me gather all the information I've found. Let me create a comprehensive report:
Comprehensive Exploration of the dead_function Detector Implementation
Based on my thorough exploration of the codebase, here's what I found:
1. Location and Definition
The dead_function detector is defined in two places (one for each language):
The detector is registered in the canonical registry at /Users/user_c042661f/Documents/desloppify/desloppify/core/registry.py (not shown as a separate detector entry, but implied through "smells" category).
2. How the TypeScript Dead Function Detector Works
The _detect_dead_functions() function in TypeScript:
python
def _detect_dead_functions(
filepath: str, lines: list[str], smell_counts: dict[str, list[dict]]
):
"""Find functions with empty body or only return/return null."""
Detection Algorithm (lines 110-150):
Iterate through each line in the file
Skip decorated functions (lines starting with @)
Match function declarations using _find_function_start(), which recognizes:
function name() { ... } declarations
const|let|var name = () => { ... } arrow functions
const|let|var name = function { ... } function expressions
Both exported and non-exported variants
Find opening brace within a 5-line window
Track braces to find the matching closing brace (with max scan of 30 characters)
Extract body between the braces
Strip C-style comments ( and )
User
Very thoroughly explore how the "subjective review" system works in the desloppify codebase. I need to understand:
How are findings classified as "subjective" vs "objective"? Look for confidence levels, review types, subjective flags, etc.
How does the review flow work? Look at desloppify/app/commands/fix/review_flow.py and related files
What is the "evidence-only filtering" mentioned in recent commits?
How are detector findings routed — which go to auto-fix vs subjective review?
Look at the Confidence enum and how it's used
Look at how the work queue orders/prioritizes items — desloppify/engine/_work_queue/
Look at the registry (desloppify/core/registry.py) for how detectors declare their confidence levels and whether they're flagged for subjective review
Search broadly: "subjective", "objective", "confidence", "review", "evidence", "mechanical", "Confidence.LOW", "Confidence.MEDIUM", "Confidence.HIGH" across the codebase.
Assistant
I'll conduct a thorough exploration of the subjective review system in the desloppify codebase. Let me start with broad searches and then dive into the key files.
Assistant
Let me read the key files identified:
User
Very thoroughly explore the detector registry and dimension system in desloppify. I need to understand:
Read desloppify/core/registry.py fully — how are detectors registered? What metadata do they have (confidence, dimension, severity, etc.)?
How do dimensions work? What dimensions exist? Look for dimension definitions.
How are smell detectors (like async_no_await, dead_function, console_error_no_throw) registered vs. other detectors?
What is the relationship between detectors, dimensions, tiers, and confidence?
How does the fix command decide what to auto-fix vs what needs review?
Look at desloppify/app/commands/fix/apply_flow.py for the fix application logic
Look at how findings flow from detection → classification → queue → fix
Search for: "DetectorMeta", "detector_meta", "dimension", "tier", "DETECTORS", "smell", "register" in the codebase.
Assistant
Now let me look at the core registry to understand detector confidence declarations:
Assistant
I'll conduct a thorough exploration of the detector registry and dimension system. Let me start by reading the core registry and then searching for related patterns throughout the codebase.
User
Thoroughly explore the TypeScript smell detection system. I need to understand:
Read desloppify/languages/typescript/detectors/smells.py fully — the main detect_smells() function and TS_SMELL_CHECKS
Read desloppify/languages/typescript/detectors/_smell_helpers.py fully — the async_no_await implementation
Read desloppify/languages/typescript/detectors/_smell_effects.py fully — the console_error_no_throw implementation
Read desloppify/languages/typescript/detectors/_smell_detectors.py fully — the dead_function implementation
What is scan_code() and how does it work? Look in _smell_helpers.py
How do smell findings get their confidence level assigned?
Are there any existing exclusion mechanisms in the smell detection pipeline?
I need the full code of these files to understand what needs to change.
Assistant
Let me now search for more details on evidence-only filtering and work queue logic:
Assistant
Now let me read the enums and dimensions files to understand the dimension and confidence/tier systems:
Assistant
Now let me check the work queue test cases to understand the evidence-only filtering better:
Assistant
Now let me search for the scoring system and fix flow logic:
Assistant
I'll thoroughly explore the TypeScript smell detection system for you. Let me read all the relevant files in parallel.
Assistant
Let me search for how findings are built and routed:
Assistant
Let me search for more about how findings are classified into tiers and how the review/fix decision is made:
Assistant
Now let me check the scan_code() function in the scanner module:
Assistant
Now let me check the helpers file:
Assistant
Now let me look at the state schema and how findings are structured:
Assistant
Let me also check how the apply_flow handles findings:
Assistant
Let me search for where smell findings get their confidence assigned:
Assistant
Now let me read the phases.py file to understand how confidence is assigned in smell detection:
Assistant
Let me check test cases and how findings are scored:
Assistant
Let me search for more about how detectors are classified and the classification logic:
Assistant
Let me continue reading the phases.py file to find the smell detection phase:
Assistant
Let me look at the build_subjective_items function:
Assistant
Excellent! Now let me search for the work queue and how items are prioritized for auto-fix vs review:
Assistant
Now let me check the make_smell_findings function to see how confidence is assigned:
Assistant
Perfect! Now let me search for information about smells and how they're registered as detectors:
Assistant
Now let me check scoring and how findings contribute to scores:
Assistant
Now let me check if there are any existing exclusion mechanisms in the smell detection:
Assistant
Let me look at how smells are defined in the language plugins:
Assistant
Let me check narrative action_engine to understand how subjective/objective findings are handled:
Assistant
Let me also check for any utility files that might have general exclusion logic:
Assistant
Let me check the utils module to see if there are utility functions for exclusions:
Assistant
Let me check the state.py to understand Finding structure better:
Assistant
Now let me read the discovery API to understand the exclusion mechanism:
Assistant
Let me look at one more critical piece - how the system distinguishes review/subjective vs regular findings:
Assistant
Perfect! Now let me search for the scoring system to understand dimensions:
Assistant
Perfect! Now let me look at one more key file about how findings flow through the system:
Assistant
Perfect! Now let me check the SMELL_TIER_MAP:
Assistant
Perfect! Now I have all the information needed. Let me create a comprehensive summary of the TypeScript smell detection system.
Comprehensive Analysis: TypeScript Smell Detection System
1. Main Smell Detection Flow (smells.py)
The detect_smells(path: Path) function (lines 553-643) is the entry point. It:
Collects all TypeScript files via find_ts_files(path)
For each file:
Reads the content and splits into lines
Builds line state map via _build_ts_line_state() (tracks block comments and template literals)
Applies regex-based checks for simple smells
Calls multi-line helper functions for complex smells
Returns (entries, total_files_checked) where entries are grouped by smell ID with severity
Key finding structure from regex matches:
python
{
"file": filepath,
"line": i + 1,
"content": line.strip()[:100],
}
2. TS_SMELL_CHECKS Registry (lines 35-218)
A 32-item registry of all smell patterns with metadata:
orphaned, uncalled_functions, flat_dirs, naming, single_use, coupling, cycles, facade - all mark
User
I need a detailed implementation plan for fixing three TypeScript smell detectors with high false positive rates, plus a holistic improvement to how questionable findings are routed.
Context
The desloppify tool has a smells detector registered in desloppify/core/registry.py with:
standalone_threshold="medium" — findings with confidence < medium become "evidence-only" (stay in state for scoring but don't appear in the work queue)
The detector uses raw substring matching "await " in body_line instead of using the existing scan_code() function to find await tokens in code positions. This means:
Comments with "await" trigger false positives
Strings with "await" trigger false negatives
It has a hard 200-line cap that causes misses in long functions
Fix: Replace the raw substring check with proper token scanning using scan_code(). The brace-tracking loop already uses scan_code() — we just need to also detect await tokens within it (look for 'a' followed by 'w','a','i','t' not inside strings). OR more practically: after extracting the function body text between braces, use scan_code() to find await as a word token in non-string positions.
Actually the simplest fix: within the existing for j in range(...) loop that scans lines, instead of "await " in body_line, we should use scan_code on each body_line and look for await as a keyword token outside strings/comments. We already have scan_code imported. We can collect the non-string/non-comment text from each line and check for \bawait\b in that.
Also remove the 200-line cap — scan until braces close (the existing pattern in _track_brace_body scans up to 2000 lines).
I'll thoroughly explore the codebase to understand the current implementation before designing the plan. Let me start by reading all the relevant files.
Assistant
Now let me look at the scanner module to understand how scan_code works and the existing test files.
Assistant
Now let me check for any other references to dead_function in the state files and scoring/narrative code, and also look at how severity maps to confidence.
Assistant
Let me check how smells severity maps to confidence, and look at the ranking code.
Assistant
Now let me find make_smell_findings to understand how severity maps to tier/confidence.
Assistant
This confirms the critical mapping at line 204: conf = "medium" if e["severity"] != "low" else "low". Now let me check the Python dead_function smell to see if it also needs renaming (since it's a separate language plugin).
Assistant
Let me also check if there are any Python smell detector references in state files or plan files that reference dead_function, and look at the _detect_dead_functions in the Python detector for comparison.
Assistant
Now let me check the CONFIDENCE_ORDER constant that's used in evidence-only filtering.
Assistant
Excellent. I now have a thorough understanding of the complete code flow. Let me now check if the _scan_code helper from the requirement docs exists and understand the text scanning patterns used in other detection functions.
Assistant
I have all the information needed to create the detailed implementation plan. Let me now compile the complete plan.
Here is the detailed implementation plan:
Implementation Plan: Fix Three TypeScript Smell Detectors + Holistic Routing
Overview
Three TypeScript smell detectors have high false positive rates and need targeted fixes. The changes span 4 production files and 2 test files, plus awareness of downstream impacts in state data and Python-side parallel detectors.
Key Architecture Understanding
The severity-to-queue routing pipeline works as follows:
Each smell in TS_SMELL_CHECKS (in smells.py) has a severity field: "high", "medium", or "low"
make_smell_findings() in /Users/user_c042661f/Documents/desloppify/desloppify/languages/_framework/finding_factories.py:204 maps severity to confidence: conf = "medium" if e["severity"] != "low" else "low"
The smells detector in registry.py has standalone_threshold="medium"
The work queue builder in ranking.py:117-121 checks: if finding_rank > threshold_rank, skip (evidence-only)
CONFIDENCE_ORDER = {"high": 0, "medium": 1, "low": 2} so "low" (rank 2) > "medium" (rank 1) -- low confidence findings are filtered out
Therefore: lowering a smell's severity from "medium" to "low" automatically makes it evidence-only.
Problem (lines 79-123): The function uses raw substring matching "await " in body_line at line 111, which matches await inside comments and string literals. It also has a hard 200-line cap at line 97.
Current code at the bug site (lines 97-114):
python
Key aspects:
Lookahead scope: Checks the next 3 lines following the console.error call
Pattern match: Looks for word boundaries (\b) around throw or return keywords
Simple substring match: First checks if "console.error" appears anywhere in the line (no validation that it's in code, not a string)
One-line detection: Flags on the line where console.error appears
3. Exclusion Logic and Limitations
No built-in exclusions for:
Error boundaries (React ErrorBoundary components)
Logger files (utils/logger.ts files)
Toast/notification patterns (toast.error calls)
Centralized error handlers
Current filtering only applies at file level:
Skips files in node_modules/
Skips .d.ts declaration files
Potential False Positives:
console.error inside string literals (e.g., "console.error('msg')") is NOT filtered
The main detect_smells() function does call _ts_match_is_in_string() for regex-based checks, but console_error_no_throw uses the wrapper that only checks for substring presence
This is a limitation in the current implementation
Comments in strings don't prevent detection:
typescript
const doc = "console.error('fail'); doOtherStuff();"; // Not a real call
Would be flagged.
Multi-line console.error calls with throw on line N+4 or beyond are missed:
typescript
console.error(
'long message'
);
doSomething();
doMore();
throw new Error('bad'); // On line +5, won't be detected
4. Related Patterns in the Codebase
The detector is part of a complementary error-handling pattern family:
From /desloppify/languages/typescript/detectors/patterns.py:
Important note: The tool treats these three as complementary layers, not competing approaches. Having console.error, toast.error, and handleError all present in a codebase is considered healthy — they represent different layers of error handling (logging, UI notification, centralized handling).
5. Test Coverage
Positive test cases (should be flagged):
typescript
function handle() {
console.error('something went wrong');
doOtherStuff();
moreStuff();
evenMoreStuff();
}
Negative test cases (should NOT be flagged):
typescript
function handle() {
console.error('fail');
throw new Error('fail');
}
Test location: Lines 289-324 of test_ts_smells.py
6. Configuration
From TS_SMELL_CHECKS in smells.py:
python
{
"id": "console_error_no_throw",
"label": "console.error without throw/return",
"pattern": None, # multi-line analysis (but uses simple line scanning)
"severity": "medium",
}
Severity: Medium
Execution: Called for every TypeScript file during detect_smells()
Entry in output: Included in results if matches found
Summary
The console_error_no_throw detector is a simple, line-forward heuristic that:
Scans each line for the substring console.error
Checks the next 3 lines for throw or return keywords
Flags cases where neither keyword is found
Has no exclusion logic for error boundaries, logger files, or toast patterns
Can produce false positives for console.error in strings or comments
Works well for straightforward cases but has clear limitations for complex control flow
The algorithm scans body_line (a single line) for await AFTER processing braces on that line. This means:
Await on a different line than opening brace: If async function foo() { is on line 1, and await first appears on line 50, it will eventually be found, but...
Await in intermediate lines never reached: If the function body spans lines 1-150, but braces close before checking all intermediate lines, awaits in those lines are missed
Example:
typescript
async function getData() {
const x = 1;
const y = 2;
// ... 180 more lines ...
const result = await fetch('/api'); // Line 185
return result; // Line 186
}
If the brace closes at line 186, but the function is declared at line 1, the detector scans 200 lines from line 1 (0-200). However, the scan logic breaks when brace_depth <= 0 AFTER processing line j, so it would check lines 0-200, theoretically finding the await.
for j in range(i, min(i + 200, len(lines))):
body_line = lines[j]
# ... brace tracking loop ...
for _, ch, in_s in scan_code(body_line):
if in_s:
continue
# ... update brace_depth ...
if "await " in body_line or "await\n" in body_line:
has_await = True
if found_open and brace_depth <= 0:
break
The await check happens on the same line as the brace check. If a line contains both the closing } AND await, the detector will:
Process the closing brace → brace_depth becomes 0
Check for await on that line
Then check if found_open and brace_depth <= 0 → TRUE, so it breaks
This means the await check on the closing brace line might still work, BUT if the closing brace comes BEFORE the await text on the same line, the string search will still find it.
Issue #5: String and Comment Literal Detection is Broken for Await
The scan_code() function is used ONLY for brace tracking (lines 100-110). The await detection (line 111) uses a raw substring search with NO awareness of strings or comments.
Example false positives:
typescript
async function foo() {
// TODO: add await here
return 42;
}
// "await" appears in comment → flags as false POSITIVE
async function bar() {
const msg = 'don\'t forget to await';
return fetch('/api'); // Missing actual await → false POSITIVE
}
// "await" in string literal → flags as false POSITIVE
Issue #6: Brace Depth Tracking Ignores String Context Until the Await Check
While scan_code() does handle strings for brace tracking, once a line is identified as containing an await, it's flagged regardless of whether that await is in a string or comment.
4. Why 70% False Positive Rate
The combination of these issues creates a perfect storm:
Too aggressive string/comment matching — any line with "await" (even in strings/comments) triggers the flag
But also misses real awaits in:
Very long functions (>200 lines) where await appears after the break condition
Awaits on continuation lines like: const x =\n await fetch()
Awaits in nested closures if the outer function's braces close first
Line-based detection is fundamentally broken for JavaScript/TypeScript where:
Code is often spread across multiple lines
String literals can span lines
Comments can reference await
5. Test Cases That Pass But Reveal Issues
From /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/test_ts_smells.py:
Line 258-268: Tests basic case (single line)
Line 271-286: Tests with actual await (passes because "await " string is found)
Line 217-222: Arrow function case
All tests are SHORT functions with await on a single line or simple multi-line structure.
6. Why It Fails on Real Codebases
Real-world TypeScript functions have:
Multiline await statements:
typescript
async function fetch() {
const data = await Promise.all([
fetch('/a'),
fetch('/b'),
fetch('/c'),
]);
}
The "await" keyword is on a different line than the actual awaited expression.
Await in closures/callbacks:
typescript
async function wrapper() {
items.forEach(async (item) => {
await processItem(item);
});
return 'done'; // No await in outer function body!
}
Detector would find "await" in the forEach callback and mark the wrapper as having await.
Comments/strings with await:
typescript
async function stub() {
// This function should await something
return null;
}
False positive from the comment.
Summary
The async_no_await detector is fundamentally broken because it:
Uses raw substring search for await instead of proper AST parsing
Doesn't properly scope the await to the function being analyzed
Has a hard-coded 200-line limit that causes missed detections
Doesn't account for multi-line statements
Doesn't properly handle strings/comments in the await detection phase
Uses per-line processing rather than full-function-body analysis
Recommended fix: Implement proper AST parsing (using a TypeScript parser in Python, or calling Node.js tooling) to identify:
The exact function boundaries
Whether any await expression exists in the direct function body (not in nested closures)
Proper handling of async/await keywords regardless of formatting
//
/* */
Check if body is in one of these patterns:
Empty string ""
"return"
"return null"
"return undefined"
Flag as dead_function if any of the above patterns match
3. No Cross-File Analysis
Critical Finding: The detector is purely single-file. It:
Does NOT check if functions are exported
Does NOT check if functions are imported elsewhere
Does NOT check if functions are called within the same file
Does NOT track callbacks or function references
Does NOT perform any multi-file dependency analysis
This is fundamentally different from the Python uncalled_functions detector (at /Users/user_c042661f/Documents/desloppify/desloppify/languages/python/detectors/uncalled.py) which DOES:
Walk the entire codebase
Track all references across files
Build a reference index
Filter candidates against the reference set
4. Reference/Usage Checking
The TypeScript dead_function detector does NOT check for references at all. It only looks at the function body syntax. There is no mechanism to:
Search for identifier occurrences (unlike Python's _identifier_occurrences())
Check imports or exports
Verify if a function is actually called
Detect callback references, event listeners, or dynamic calls
5. Root Causes of 97% False Positive Rate
Based on the code inspection, here are the exact patterns that would cause false positives:
A. Exported Functions (NOT CHECKED)
typescript
// FLAGGED AS DEAD (false positive)
export function validateInput() {
return;
}
// This is exported and used elsewhere, but detector doesn't know
B. Functions Called Within Same File (NOT CHECKED)
typescript
function helper() {
return;
}
function caller() {
helper(); // Called here, but detector only looks at body syntax
doWork();
}
C. Callback References (NOT CHECKED)
typescript
// FLAGGED AS DEAD (false positive)
function onClick() {
return;
}
// Used as callback:
element.addEventListener('click', onClick);
// Detector doesn't track reference to 'onClick'
D. Event Handlers and Lifecycle Methods (NOT CHECKED)
typescript
// React component
function useInitialize() {
return; // Intentional early return or stub
}
useEffect(useInitialize, []); // Referenced dynamically
E. Stub/Placeholder Functions (VALID DETECTION)
typescript
// This SHOULD be flagged - genuinely empty
function notImplementedYet() {
}
F. Functions with Only Comments (WILL BE FLAGGED)
typescript
// FLAGGED AS DEAD (false positive)
function TODO() {
// TODO: implement this
return;
}
// Comment is stripped, leaving just "return"
G. Async Stubs
typescript
// FLAGGED AS DEAD
async function asyncStub() {
return;
}
// But might be intentionally a placeholder
await asyncStub(); // Still called despite being "dead"
6. Why It's Different from Python
Python has a separate uncalled_functions detector that:
Only flags underscore-prefixed functions (_private)
Actual unused function → Not detected at all (would need cross-file analysis like uncalled_functions)
7. Key Code Locations
Main detector: /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_detectors.py:102-150
Function pattern matching: _find_function_start() at lines 30-63
Comment stripping: Uses _strip_ts_comments() which delegates to strip_c_style_comments()
Brace tracking: Uses _track_brace_body() to find function boundaries
Invocation: Called at /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/smells.py:617
Test coverage: /Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/test_ts_smells.py:377-389
8. Pattern Matching Details
The _find_function_start() function (lines 30-63) matches:
Declaration pattern: function name(...)
Arrow function pattern: const name = (...) => ... or const name = async (...) => ...
Function expression: const name = function(...)
All with optional export and async modifiers
However, it does NOT match:
Methods inside classes/objects
Functions inside nested scopes
Dynamically created functions
Summary
The TypeScript dead_function detector is a syntax-only, single-file analyzer that flags functions with trivial bodies (empty, return-only). It has zero awareness of:
Function exports
Function references or calls (even in the same file)
Callbacks, event listeners, or dynamic invocations
Entry points or special function purposes
This design is fundamentally incapable of distinguishing between genuinely dead code and legitimate stub functions, exported utilities, or callbacks, leading to the ~97% false positive rate mentioned in your issue.
/* ... */
Template literals (backtick strings with ${} nesting awareness)
Returns {line_index: reason} map. Lines not in map are safe for regex checks. This prevents false positives in comments/strings.
Handles:
Escape sequences (\.)
Template ${} nesting depth tracking
Block comment closing detection
4. Multi-line Smell Helpers (_smell_helpers.py)
All delegate to implementations in _smell_effects.py and use the scan_code() function.
Key functions:
_detect_async_no_await() - Finds async functions without await using brace depth tracking
_detect_error_no_throw() - Finds console.error without throw/return in next 3 lines
Function decorator skip: Dead/monster function detectors skip @decorated functions (line 112 in _smell_detectors.py)
NO general exclusion mechanism like the memory describes (matches_exclusion(), _extra_exclusions) is currently applied in smell detection. This is available in discovery_api.py but not used by the smell detection pipeline.
matches_exclusion(rel_path, exclusion) exists in core/file_paths.py (lines 13-32) and supports:
Component matching: "node_modules" in path_parts
Glob patterns: fnmatch on path parts
Full-path globs: "dir/**" style patterns
Summary
The TS smell detection system is comprehensive and modular:
Regex-based smells for simple patterns (strings, comments safe-guarded)
Multi-line analysis with string-aware character scanning (via scan_code())
Brace/paren depth tracking for function boundaries and block extraction
Three-tier confidence based on smell severity (high=medium conf, low=low conf)
Limited exclusion (file/line state/string filtering only, no config-based exclusions)
All files and code are now fully understood and ready for modification planning.
Key logic in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/subjective_policy.py (lines 64-76):
python
def _is_evidence_only(finding: dict) -> bool:
"""Return True if the finding is below its detector's standalone threshold."""
detector = finding.get("detector", "")
meta = DETECTORS.get(detector)
if meta and meta.standalone_threshold:
threshold_rank = CONFIDENCE_ORDER.get(meta.standalone_threshold, 9)
finding_rank = CONFIDENCE_ORDER.get(finding.get("confidence", "low"), 9)
if finding_rank > threshold_rank: # "low"=2 > "medium"=1
return True
return False
Evidence-only findings:
Remain in state and contribute to dimension scores
Are filtered out from work queue (not surfaced as standalone items)
Still affect subjective visibility policy
Useful for review evidence without forcing immediate action
def should_surface(self, item: dict) -> bool:
"""Unscored (initial_review) -> always. All others -> only when drained."""
if item.get("initial_review"):
return True # Always surface unscored dimensions
return not self.has_objective_backlog # Surface other subjective only when objective work is done
6. Work Queue Ordering and Priority
Item Sort Order (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/ranking.py, lines 153-200):
MIN_STANDALONE_IMPACT = 0.05
all_items = [
item for item in all_items
if item.get("kind") != "finding"
or item.get("is_review")
or item.get("is_subjective")
or not item.get("estimated_impact")
or item["estimated_impact"] >= MIN_STANDALONE_IMPACT
]
Mechanical findings with negligible score impact are dropped even if confidence is high
is_review and is_subjective items always included (not subject to impact floor)
Reason: Fixing 1 finding in a dimension at 99.99% score has near-zero impact
9. Test Cases Demonstrating Evidence-Only Filtering
From /Users/user_c042661f/Documents/desloppify/desloppify/tests/review/work_queue_cases.py:
if meta.action_type == "auto_fix" and meta.fixers:
# Check if fixers are available for the language
if fixer in supported_fixers:
return f"desloppify autofix {fixer} --dry-run"
else:
return "desloppify plan done ..." # Manual resolution command
Selects candidates where status == "open" AND not yet reviewed
Produces .desloppify/query.json with file content, prompts, dimension contexts
Feeds into external review runners (Codex, Claude cloud)
8. DETECTOR-TO-DIMENSION MAPPING
Built dynamically from DETECTOR_SCORING_POLICIES:
code
Detector → DetectorScoringPolicy(dimension="...", tier=...)
↓
DIMENSIONS (computed list of Dimension objects)
↓
dimension_scores in state (dict[str, DimensionScore])
The detector flags functions with empty/trivial bodies (empty, return, return null, return undefined). The name "dead_function" is misleading — it's really detecting stub functions. At 97% FP rate, almost all flagged functions are intentional stubs.
Fix:
Rename smell ID from dead_function to stub_function
Lower severity from "medium" to "low"
Update the label to "Stub/empty function body"
This automatically makes it evidence-only (below standalone_threshold="medium") — it still affects scoring but doesn't appear as a standalone queue item
Problem 4: Holistic routing improvement
The existing standalone_threshold mechanism works well at the detector level. But within the smells detector, individual smell types have different reliability levels. The current system already handles this via severity→confidence→threshold:
HIGH severity → medium confidence → in queue (tier 2)
MEDIUM severity → medium confidence → in queue (tier 3)
LOW severity → low confidence → evidence-only
For smells that are inherently ambiguous and often intentional, lowering their severity to "low" routes them to evidence-only automatically. The dead_function→stub_function rename is the main one that needs this.
For console_error_no_throw, we fix the detection logic to reduce FPs rather than lowering severity, because genuine silent error swallowing IS worth catching.
For async_no_await, same — fix the logic, keep severity medium.
Various test files that may reference dead_function by name
Please design a step-by-step implementation plan with specific code changes for each file.
for j in range(i, min(i + 200, len(lines))):
body_line = lines[j]
prev_code_ch = ""
for _, ch, in_s in scan_code(body_line):
if in_s:
continue
if ch == "/" and prev_code_ch == "/":
break # Rest of line is comment
elif ch == "{":
brace_depth += 1
found_open = True
elif ch == "}":
brace_depth -= 1
prev_code_ch = ch
if "await " in body_line or "await\n" in body_line:
has_await = True
if found_open and brace_depth <= 0:
break
Fix -- two changes:
Change A: Replace the 200-line cap with 2000 (matching _track_brace_body's default):
python
for j in range(i, min(i + 2000, len(lines))):
Change B: Replace the raw substring check with a scan_code-based await detection. The await keyword detection should be integrated INTO the existing scan_code loop, collecting non-string characters and then checking for the await word boundary. The simplest approach is to accumulate non-string text per line and do a regex check:
Replace lines 97-114 with:
python
for j in range(i, min(i + 2000, len(lines))):
body_line = lines[j]
prev_code_ch = ""
code_chars: list[str] = []
for _, ch, in_s in scan_code(body_line):
if in_s:
code_chars.append(" ") # placeholder to preserve positions
continue
if ch == "/" and prev_code_ch == "/":
break # Rest of line is comment
elif ch == "{":
brace_depth += 1
found_open = True
elif ch == "}":
brace_depth -= 1
code_chars.append(ch)
prev_code_ch = ch
code_text = "".join(code_chars)
if re.search(r"\bawait\b", code_text):
has_await = True
if found_open and brace_depth <= 0:
break
Note: re is already imported at line 10 of the file.
This correctly skips await inside string literals and comments while preserving the existing brace-tracking logic.
def detect_error_no_throw(
filepath: str,
lines: list[str],
smell_counts: dict[str, list[dict]],
) -> None:
"""Find console.error calls not followed by throw or return."""
for index, line in enumerate(lines):
if "console.error" in line:
following = "\n".join(lines[index + 1 : index + 4])
if not re.search(r"\b(?:throw|return)\b", following):
smell_counts["console_error_no_throw"].append(
{
"file": filepath,
"line": index + 1,
"content": line.strip()[:100],
}
)
Fix -- four additions:
Addition 1: Expand the "handled" regex to include common error-handling patterns in the lookahead. Change line 17 from:
python
if not re.search(r"\b(?:throw|return)\b", following):
to:
python
if not re.search(r"\b(?:throw|return|rethrow)\b|(?:toast|normalizeAndPresentError|presentError)\s*\(", following):
Addition 2: Skip files that are logger/error utility modules by filename. Add a check at the start of the function:
python
import os
def detect_error_no_throw(
filepath: str,
lines: list[str],
smell_counts: dict[str, list[dict]],
) -> None:
"""Find console.error calls not followed by throw or return."""
basename = os.path.basename(filepath).lower()
if any(kw in basename for kw in ("logger", "errorpresentation", "errorhandler", "errorreporting")):
return
os needs to be imported at the top of _smell_effects.py.
Addition 3: Skip if inside componentDidCatch. Check preceding lines (up to 10 back) for the method name:
python
if "console.error" in line:
# Skip if inside componentDidCatch
preceding = "\n".join(lines[max(0, index - 10) : index])
if "componentDidCatch" in preceding:
continue
Addition 4: Skip if inside dev-only blocks. Check preceding lines for dev-only guards:
python
if re.search(r"import\.meta\.env\.DEV|process\.env\.NODE_ENV", preceding):
continue
Combined replacement for the function body:
python
def detect_error_no_throw(
filepath: str,
lines: list[str],
smell_counts: dict[str, list[dict]],
) -> None:
"""Find console.error calls not followed by throw or return."""
basename = os.path.basename(filepath).lower()
if any(kw in basename for kw in (
"logger", "errorpresentation", "errorhandler", "errorreporting",
)):
return
for index, line in enumerate(lines):
if "console.error" not in line:
continue
# Skip if inside componentDidCatch or dev-only block
preceding = "\n".join(lines[max(0, index - 10) : index])
if "componentDidCatch" in preceding:
continue
if re.search(r"import\.meta\.env\.DEV|process\.env\.NODE_ENV", preceding):
continue
following = "\n".join(lines[index + 1 : index + 4])
if re.search(
r"\b(?:throw|return|rethrow)\b"
r"|(?:toast|normalizeAndPresentError|presentError)\s*\(",
following,
):
continue
smell_counts["console_error_no_throw"].append(
{
"file": filepath,
"line": index + 1,
"content": line.strip()[:100],
}
)
Also add import os at the top of _smell_effects.py (after the existing import re on line 6).
Step 3: Rename dead_function to stub_function + lower severity
This is a multi-file rename. The TS-specific rename does NOT affect the Python dead_function smell (that is a separate detector in a separate language plugin).
In function _detect_dead_functions at line 144, change the dict key:
python
# FROM:
smell_counts["dead_function"].append(
# TO:
smell_counts["stub_function"].append(
Also update the content string at line 148 for clarity:
python
# FROM:
"content": f"{name}() — body is {label}",
# TO:
"content": f"{name}() — stub ({label})",
Consider renaming the function itself from _detect_dead_functions to _detect_stub_functions for clarity. This requires updating:
The import in smells.py line 16: _detect_dead_functions -> _detect_stub_functions
The call site in smells.py line 617: _detect_dead_functions(...) -> _detect_stub_functions(...)
The import in test_ts_smell_helpers.py line 5: same rename
All test references
However, the function rename is optional. The critical part is the smell ID rename (dead_function -> stub_function) and severity change ("medium" -> "low").
Decision: Rename the function too, for consistency. The grep shows all references are contained within the TS detector tree and its tests.
# Rename test and update assertions:
def test_detect_stub_function(tmp_path):
"""Detects functions with empty body or only return null."""
_write(
tmp_path,
"bad.ts",
("function emptyFunc() {\n}\nfunction nullFunc() {\n return null;\n}\n"),
)
entries, _ = detect_smells(tmp_path)
ids = {e["id"] for e in entries}
assert "stub_function" in ids
stub = next(e for e in entries if e["id"] == "stub_function")
assert stub["count"] == 2
assert stub["severity"] == "low" # new: verify it's low severity
Add new tests for async_no_await improvements:
python
def test_async_no_await_ignores_await_in_comment(tmp_path):
"""Await in comments should not suppress the async_no_await finding."""
_write(
tmp_path,
"bad.ts",
"async function fetchData() {\n // await fetch('/api');\n return 1;\n}\n",
)
entries, _ = detect_smells(tmp_path)
ids = {e["id"] for e in entries}
assert "async_no_await" in ids
def test_async_no_await_ignores_await_in_string(tmp_path):
"""Await in strings should not suppress the async_no_await finding."""
_write(
tmp_path,
"bad.ts",
"async function fetchData() {\n const s = 'await something';\n return 1;\n}\n",
)
entries, _ = detect_smells(tmp_path)
ids = {e["id"] for e in entries}
assert "async_no_await" in ids
Add new tests for console_error_no_throw improvements:
python
def test_console_error_with_toast_not_flagged(tmp_path):
"""console.error followed by toast() should not be flagged."""
_write(
tmp_path,
"bad.ts",
"function handle() {\n console.error('fail');\n toast('Error occurred');\n}\n",
)
entries, _ = detect_smells(tmp_path)
ids = {e["id"] for e in entries}
assert "console_error_no_throw" not in ids
def test_console_error_in_logger_file_not_flagged(tmp_path):
"""console.error in logger utility files should be skipped entirely."""
_write(
tmp_path,
"src/utils/logger.ts",
"function logError(msg: string) {\n console.error(msg);\n // no throw needed\n doSomething();\n doMore();\n}\n",
)
entries, _ = detect_smells(tmp_path)
error_entries = [e for e in entries if e["id"] == "console_error_no_throw"]
assert len(error_entries) == 0
The test test_registry_standalone_threshold_count at line 822 asserts exactly 7 detectors have standalone_threshold="medium". This test does NOT need to change because the smells detector's standalone_threshold is not being modified -- only the individual smell's severity is changing within the smells detector.
Step 5: Verify No State Migration Needed
The dead_function -> stub_function rename changes the smell ID used in finding keys. Finding IDs in state are constructed as smells::<file>::dead_function. After the rename, new scans will produce smells::<file>::stub_function.
The existing reconciliation logic in the scan pipeline handles "vanished" findings (old dead_function findings will be marked as resolved when they no longer appear in new scan results). New stub_function findings will appear as new findings. No explicit state migration is needed -- the next scan naturally transitions.
Step 6: Verify Python-side dead_function Is Unaffected
The Python language plugin has its own dead_function smell at /Users/user_c042661f/Documents/desloppify/desloppify/languages/python/detectors/smells.py:66. This is an entirely separate detector and is NOT being changed in this plan. The rename is TypeScript-only. The Python dead_function has "medium" severity, which is appropriate for Python where stub functions (bare pass) are more commonly indicative of unfinished work than in TypeScript.
Step 2 second (console_error_no_throw fix) -- self-contained in _smell_effects.py
Step 1 third (async_no_await fix) -- slightly more complex logic change
Step 4 last (tests) -- after all production code changes are in place
Run python -m pytest desloppify/languages/typescript/tests/ -q to verify
Run python -m pytest desloppify/tests/review/work_queue_cases.py -q to verify the threshold count test still passes
Risk Assessment
Low risk: The dead_function -> stub_function rename. All references are contained within the TS detector tree. State reconciliation handles it naturally.
Low risk: The console_error_no_throw exclusions. They only suppress findings (reduce FPs), never create new ones.
Medium risk: The async_no_await scan_code integration. The logic change replaces raw substring matching with regex on filtered code text. The key correctness requirement is that the code_chars list correctly excludes string content. The scan_code function is well-tested and yields in_s=True for string content, so appending " " (space) for in-string characters preserves word boundaries while preventing false matches. However, there is a subtle consideration: scan_code treats the quote characters themselves as in_s=True on the opening quote and in_s=False on the closing quote (checking line 26-27 of scanner.py shows the closing quote yields in_s is not None which evaluates to False when in_str was just set to None). Actually, re-reading scanner.py:24-26 more carefully:
python
if ch == in_str:
in_str = None
yield (i, ch, in_str is not None) # in_str is None here, so yields False
So closing quote characters yield in_s=False. This means the closing quote ' or " or ` would appear in code_chars. This is fine -- a closing quote character cannot form part of \bawait\b.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_helpers.py - Contains _detect_async_no_await -- the main logic fix for token-aware await detection
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_effects.py - Contains detect_error_no_throw -- needs exclusion logic for logger files, componentDidCatch, dev blocks, and expanded handled patterns
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/_smell_detectors.py - Contains _detect_dead_functions -- rename to _detect_stub_functions and change dict key from dead_function to stub_function
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/detectors/smells.py - Central smell registry (TS_SMELL_CHECKS) -- rename ID, update label, lower severity; update imports and call sites
/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/tests/smells/test_ts_smell_helpers.py - Primary unit test file for direct detector testing -- needs rename updates and new test cases for string/comment awareness