Explore how the scoring and narrative systems work in desloppify, specifically:
Scoring pipeline: How do detector names map to scoring dimensions? Look at desloppify/core/registry.py (DetectorMeta), desloppify/engine/state_internal/scoring.py, and any dimension mapping. How would an unknown detector ID (like "golangci_lint" from a generic plugin) be handled? Would it crash, be ignored, or get a default?
Narrative system: How does desloppify/narrative/ use detector names? Look at DETECTOR_TOOLS in narrative/__init__.py, how _count_open_by_detector works in narrative/core.py, and how actions/strategy reference specific detectors. What happens when a detector isn't in these mappings?
Scoring dimensions: What are the current dimensions, their tiers, and how they're defined? Look for the dimension definitions and how findings get scored into dimensions.
Post-scan analysis: Look at desloppify/app/commands/scan/ to understand what happens after findings are generated — the coaching output, strategy, headline computation. Trace the path from findings → score → narrative → output.
Be thorough — include file paths, function names, and relevant code snippets.
Assistant
I'll conduct a thorough exploration of the scoring and narrative systems in desloppify. Let me start by examining the key files mentioned.
Assistant
Let me continue reading the narrative module and scoring system:
User
Explore how fixers, move, and review work in desloppify, specifically:
Fixer system: Look at desloppify/languages/framework/base/types.py FixerConfig, desloppify/app/commands/fix/cmd.py, and an example fixer (e.g., in desloppify/languages/typescript/fixers/). How are fixers registered, discovered, and executed? What's the minimum viable fixer? Could we create a generic "run shell command" fixer?
Move system: Look at desloppify/app/commands/move/move.py and language-specific move implementations. What language-specific knowledge does move need? Is there a way to provide a basic move (rename file, update state) without import rewriting?
Review system: Look at desloppify/app/commands/review/cmd.py and the review flow. What does review --prepare need from a language? Look at review_module_patterns_fn, review_api_surface_fn, review_guidance, holistic_review_dimensions. What happens when these are None?
Detect commands: Look at how desloppify/app/commands/detect.py uses cfg.detect_commands. Are these independent of the scoring pipeline?
Be thorough — include file paths, function names, and key code patterns.
Assistant
Now I see—the narrative module is in desloppify/intelligence/narrative/. Let me read the key files:
Assistant
I'll systematically explore the fixer, move, review, and detect systems in desloppify. Let me start by mapping the file structure and understanding the key components.
Assistant
Now let me examine the narrative constants and other related files:
Assistant
Now let me read the key files to understand the fixer, move, review, and detect systems:
Assistant
Let me continue exploring the scoring system and scan command flow:
User
Explore how dependency graphs, duplicate detection, and test coverage work in desloppify, and investigate tree-sitter as a potential generic solution:
Dep graph: Look at desloppify/languages/python/detectors/deps.py and/or any TypeScript dep graph builder. What format does build_dep_graph return? What's the dict structure? How is it used downstream (orphaned detection, coupling, test coverage)?
Function extraction: Look at desloppify/languages/python/extractors.py and desloppify/languages/typescript/extractors.py. What does FunctionInfo look like? What fields are required? How are extracted functions used in duplicate detection?
Test coverage: Look at desloppify/engine/detectors/test_coverage/detector.py and desloppify/languages/framework/base/shared_phases.py phase_test_coverage. What does test coverage need from a language? (dep graph, test file discovery, import mapping)
Tree-sitter feasibility: Search for any existing tree-sitter usage or dependencies in the codebase. Check if py-tree-sitter or tree-sitter-languages is in pyproject.toml. Think about what a minimal tree-sitter integration would look like — just enough to extract: (a) import statements, (b) function definitions with their bodies, (c) export declarations.
Orphaned detection: How does orphaned file detection work? What does it need from the dep graph?
Be thorough — include file paths, data structures, and the specific interfaces each system requires.
Assistant
Good start. Now let me dive deeper into the fix system, move implementations, and review flow:
Assistant
Let me read the actual scoring policy and dimension definitions:
Assistant
I'll conduct a thorough exploration of these systems. Let me start by gathering information on all the key components.
Assistant
Now let me explore example fixers and the move system in more detail:
Assistant
Let me continue exploring the scan flow and how it generates narrative output:
Assistant
Let me look at the test coverage detector and related files:
Assistant
Now let me look at the review system in more detail:
Assistant
Let me also check the action engine more fully and narrative headline computation:
Assistant
Let me read the move implementations and look at the review module:
Assistant
Excellent! Now let me explore how unknown detectors would be handled and look at the action tools:
Assistant
Excellent. Now let me examine the review preparation and holistic review functions:
Assistant
Good! Now let me check the test files to understand how unknown detectors are handled:
Assistant
Now let me look at the review hook definitions and how they're used:
Assistant
Now let me look at the TypeScript dep graph and other key files:
Assistant
Perfect! Now let me also check the scanning workflow and policy/dimension definitions more:
Assistant
Now let me examine how these review hook functions are actually used in the context building:
Assistant
Perfect! Now let me look at the scan workflow to see the complete flow from findings to narrative:
Assistant
Let me search for where those functions are called in context building:
Assistant
Now let me gather more details on the test coverage mapping and look at coverage/mapping.py:
Assistant
Let me check the full scan command to see how narrative is computed:
Assistant
Let me check the holistic context selection file:
Assistant
Now let me check the post-scan analysis function:
Assistant
Let me find the actual usage of review_api_surface_fn:
Assistant
Let me continue exploring this file and find where narrative is computed:
Assistant
Perfect! Now I have a comprehensive view. Let me create one more check for how unknown detectors are handled in action generation:
Assistant
Perfect! Now let me look at an example implementation of these hooks:
Assistant
Excellent! Now let me look at how languages define their interfaces and look for tree-sitter:
Assistant
Perfect! Now I have all the information I need to provide a comprehensive answer. Let me compile my findings:
Comprehensive Exploration: Scoring and Narrative Systems in Desloppify
Based on my thorough exploration of the codebase, here's how the scoring and narrative systems work:
1. SCORING PIPELINE: How Detector Names Map to Dimensions
{
"resolved_absolute_path": {
"imports": set[str], # Set of files THIS file imports
"importers": set[str], # Set of files that import THIS file
"deferred_imports": set[str], # Imports inside functions (can't cause cycles)
"import_count": int, # len(imports) — calculated by finalize_graph()
"importer_count": int # len(importers) — calculated by finalize_graph()
},
...
}
Key implementation details:
Uses AST parsing (ast.parse()) for reliable multi-line import extraction
Distinguishes import X from from X import Y statements
Handles relative imports (., ..) by path resolution
These are tracked separately because they can't cause circular import errors at module load time
Logic: collects top-level function/class (start_lineno, end_lineno) ranges, then checks if import statement falls within any range
Resolves paths to absolute strings (via )
User
Design a thorough implementation plan to make generic language plugins fully functional in desloppify. The user wants ALL features working, not just scan-and-dump.
Current State
22 generic language plugins exist (go, rust, ruby, etc.) using generic_lang() in desloppify/languages/framework/generic.py
Each plugin specifies external tools (e.g., golangci-lint, rubocop) with {label, cmd, fmt, id, tier} specs
These tools run at scan time, parse output into findings
But most features beyond basic scanning don't work:
Scoring: unknown detector IDs aren't in DETECTOR_SCORING_POLICIES → findings have no scoring impact
Narrative: detectors not in DETECTOR_TOOLS → no actions/guidance generated
Fixers: none registered
Move: stubs return empty (no import rewriting)
Review: hooks are None (review_module_patterns_fn, etc.)
Dep graph: stub returns {} → orphaned/coupling/cycles/test coverage all broken
Function extraction: noop → duplicate detection broken
Architecture Details from Exploration
Scoring Pipeline
DETECTOR_SCORING_POLICIES in desloppify/engine/scoring_internal/policy/core.py maps detector→dimension
_DIMENSION_SPECS defines dimensions: File health (T3), Code quality (T3), Duplication (T3), Test health (T4), Security (T4)
Unknown detectors get dimension=None → zero score impact (graceful but useless)
detector_policy() returns safe default for unknown detectors
Narrative System
DETECTOR_TOOLS in desloppify/intelligence/narrative/_constants.py built from core/registry.py
compute_actions() in action_engine.py iterates DETECTOR_TOOLS → unknown detectors generate zero actions
_dimension_name() returns "Unknown" for unmapped detectors
Registry
desloppify/core/registry.py has DETECTORS dict of DetectorMeta dataclass instances
Each has: name, dimension, action_type, guidance, fixers tuple
detector_tools() builds DETECTOR_TOOLS from DETECTORS
Fixers
FixerConfig in types.py: needs detect callable + callable + detector name
Assistant
I'll start by thoroughly exploring the codebase to understand the current architecture before designing the implementation plan.
Assistant
Now let me explore the narrative system, the existing language plugins, and the type definitions.
Assistant
Let me look at some of the generic language plugins to see their tool specs, and the existing full plugins for reference patterns.
Assistant
Now let me look at the full Python and TypeScript plugins to understand how they wire things differently, and examine the scan pipeline.
Assistant
Now let me look at the scan pipeline, the fixer infrastructure, the move command, and the review system.
Assistant
Now let me look at the move command and how fixers integrate with the fix command.
Assistant
Now let me look at how the fix command loads fixers, the scan pipeline, and a few more generic plugins.
Assistant
Now let me look at the scan pipeline to see how phases are run, and check how the existing tools declare fix_cmd or similar.
Assistant
Now let me check how scanning invokes phases, how the review pipeline works for generic plugins, and the scan plan to understand the dep graph flow.
Assistant
Let me look at generate_findings and the plan module to see how dep graph/zone map are wired.
Assistant
Now let me examine the LangRun runtime wrapper and the contract validation.
Assistant
Now let me look at the move apply module to understand how move dispatches to the language module, and also the review module to see how review defaults work.
Assistant
Now let me look at the remaining generic plugins to understand which tools support --fix modes and see the full list.
Assistant
Let me also check how lang_capabilities is used and look at the scoring module for get_dimension_for_detector.
Assistant
Let me also check the move.py main file to see how it dispatches to language modules, and look at all generic plugins.
Assistant
Now let me look at the remaining generic plugins and the registry_order for display_order.
Assistant
Let me see the remaining generic plugins and how the move_planning module dispatches to language-specific modules.
Assistant
Now let me check how the narrative system uses detector_tools() more closely and how the state file handles unknown detectors.
Assistant
Let me examine the narrative action_tools.py and the test_coverage detector to understand the hook system.
Assistant
Now let me look at the test_coverage detector to understand what hooks it expects from languages.
Assistant
Let me check the remaining generic plugins (yaml, sql, perl, markdown) and then the gdscript plugin (which is a full plugin, a good reference).
Assistant
Now I have a thorough understanding of the codebase. Let me check a couple more details: the GDScript plugin (mid-tier full plugin) and see how shared_subjective_duplicates_tail is used by generic plugins.
Assistant
Now I have a comprehensive understanding of the entire architecture. Let me compile the full list of all generic plugins and their IDs, then design the implementation plan.
Assistant
I now have comprehensive understanding. Let me verify one more thing -- how the DETECTOR_TOOLS constant is built at module load time and if it can be dynamically extended.
Assistant
Now I have a thorough understanding of the entire system. Let me synthesize the implementation plan.
Implementation Plan: Generic Language Plugins -- Full Feature Support
1. Problem Summary
There are 22 generic language plugins (go, rust, ruby, java, kotlin, swift, php, elixir, haskell, clojure, terraform, docker, sql, cxx, bash, yaml, scala, nim, zig, perl, lua, powershell, markdown) registered via generic_lang() in /Users/user_c042661f/Documents/desloppify/desloppify/languages/framework/generic.py. They produce findings at scan time, but those findings have no downstream impact because:
Their detector IDs (e.g. golangci_lint, rubocop_offense) are not in DETECTOR_SCORING_POLICIES -- findings get dimension=None, zero score impact
Their detector IDs are not in DETECTORS registry -- DETECTOR_TOOLS has no entry for them, so narrative generates no actions/guidance
No fixers are registered -- desloppify fix fails immediately
No move module exists -- load_lang_move_module() calls sys.exit(1)
No dep graph/function extraction -- orphaned/coupling/cycles/dupes/test_coverage all produce nothing
No shared phases (security, test coverage, subjective review, duplicates) are wired up
2. Implementation Strategy
The key insight is that generic_lang() is the single choke point for all 22 plugins. All changes should flow through this function, auto-wiring everything based on the tool specs provided. No changes to individual plugin __init__.py files should be needed except to add optional new fields (fix_cmd, dimension).
The approach follows five tiers ordered by impact-to-effort ratio.
Tier 1: Pipeline Wiring (Scoring + Narrative)
Goal: Make existing generic findings actually count in scoring and narrative.
Key Insight: Both DETECTORS and DETECTOR_SCORING_POLICIES are module-level dicts. generic_lang() runs at import time. We can insert entries into both dicts from generic_lang() after building the tool specs.
Files to modify:
A. desloppify/core/registry.py -- Add dynamic registration function
Add a function register_generic_detector(detector_id, *, dimension, tier, guidance) that inserts a DetectorMeta into :
Assistant
Good -- FunctionInfo needs name, file, line, end_line, loc, body, plus optional normalized, body_hash, params. The generic extractor needs to populate these properly.
Now let me check how the structural analysis shared phase works and whether it can work without a full language plugin.
Assistant
Good -- run_structural_phase needs complexity_signals (language-specific) and lang.file_finder + lang.large_threshold. Let me check what run_coupling_phase needs.
Assistant
Now I have a full picture. Let me now construct the complete plan.
Assistant
Now I have everything I need. Let me compile the comprehensive plan.
Here is the complete implementation plan for making generic language plugins fully functional in desloppify.
Architecture Overview
There are 22 generic language plugins all registered via generic_lang() in /Users/user_c042661f/Documents/desloppify/desloppify/languages/framework/generic.py. The central insight is that all wiring changes should happen inside generic_lang() itself -- the individual plugin __init__.py files should only need minimal additions (like fix_cmd keys). This keeps the architecture clean and ensures all 22 plugins benefit automatically.
Implementation Tiers
Tier 1: Scoring and Narrative Wiring
This is the highest-impact, lowest-effort change. Currently, generic detector IDs like golangci_lint and rubocop_offense exist nowhere in DETECTORS (the canonical registry) or DETECTOR_SCORING_POLICIES (the scoring pipeline), so findings produce zero score impact and zero narrative actions.
Step 1A: Add dynamic detector registration to the canonical registry
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 Plan: User provided a detailed plan for a "Generic Language Plugin System" for desloppify - a Python CLI tool for codebase health tracking. The plan included creating a generic plugin framework, output parsers, 22 language plugins, a langs command, and modifications to existing framework files.
Phase 1 - Reading Framework Files: I read key files to understand the codebase:
desloppify/languages/__init__.py - registration system
desloppify/engine/state_internal/filtering.py - make_finding function
desloppify/languages/gdscript/__init__.py - example full plugin
desloppify/engine/policy/zones.py - zone classification
Various CLI parser files
Implementation Phase:
Created desloppify/languages/framework/generic.py with parsers, make_tool_phase, stubs, generic_lang
Modified types.py to add integration_depth field
Modified resolution.py for instance passthrough in get_lang/auto_detect_lang
Modified __init__.py to add register_generic_lang
Modified discovery.py for user plugin discovery
Created all 22 plugin files as plugin_*.py files initially
User Feedback #1: "why don't we have them in folders like the main languages?" - User wanted consistency with full plugins
User Feedback #2: "why are we splitting up different kinds of implementations?" - User wanted ALL plugins organized the same way regardless of implementation type
Reorganization: Deleted all plugin_*.py files and recreated them as packages under languages/<name>/__init__.py
Created langs command: , registered in command registry, added parser group
User
I need to understand how detectors get wired into scoring and narrative for the desloppify generic plugin system. Find and summarize:
desloppify/core/registry.py — how DETECTORS dict works, DetectorMeta structure, how detector_tools() derives DETECTOR_TOOLS
desloppify/engine/scoring_internal/policy/core.py — how DETECTOR_SCORING_POLICIES maps detector IDs to dimensions, what dimensions exist
desloppify/intelligence/narrative/action_engine.py — how compute_actions() uses DETECTOR_TOOLS
desloppify/languages/framework/generic.py — current state of the generic plugin framework, what tool specs look like
desloppify/languages/framework/contract_validation.py — what contract validation requires
For each file, give me the key data structures, their formats, and how they connect. I need to understand what needs to change to make generic plugin detectors participate in scoring and narrative.
Assistant
I'll help you understand the detector wiring system. Let me search for and examine these files.
Assistant
Now let me read the key files:
Assistant
Now let me search for any related files that show how these pieces connect:
Assistant
Let me check how the registry and policies are used in scoring and narrative:
Assistant
Let me check how detect_commands relate to the registry and what tool specs look like:
Assistant
Let me look for examples of how tool specs are used and what smell_id means:
Assistant
Let me look at a concrete example of how a generic language is configured:
Assistant
Perfect! Now let me check how get_detect_commands works:
Assistant
Let me also check the Finding schema to understand what findings look like:
Assistant
Excellent. Now I have all the information needed. Let me create a comprehensive summary:
Summary: Detector Wiring for Scoring and Narrative in Desloppify
I've mapped the complete detector wiring system. Here's how the pieces connect:
I need to understand what shared detector phases exist and how fixers work, to plan extending them to generic language plugins. Find and summarize:
desloppify/languages/framework/base/shared_phases.py — what shared phases exist (security, test coverage, duplicates, etc.), how they work, what they require from lang
desloppify/engine/detectors/test_coverage/detector.py — what it needs from lang (dep_graph, file_finder, etc.)
desloppify/engine/detectors/dupes.py — what it needs from lang (extract_functions)
desloppify/app/commands/fix/cmd.py — how fixers are looked up and executed, what FixerConfig needs
How does a full language plugin (e.g., Python or C#) wire up its shared phases? Check desloppify/languages/python/__init__.py or desloppify/languages/csharp/__init__.py for the phase list
desloppify/engine/detectors/security.py — the cross-language security detector
I need to understand what each shared phase requires from the language config so I can determine which ones can work with generic plugins (which have empty dep graphs and noop function extractors).
Assistant
I'll help you understand the shared detector phases and how fixers work. Let me start by exploring the key files you mentioned.
Assistant
Now let me get the remaining files:
Assistant
Now let me read the security and test coverage detectors:
Assistant
Now let me check the fixer loading mechanism and look for any C# plugin:
Assistant
Let me read the C# plugin to see how it's structured:
Assistant
Now let me check the phase builders to understand how shared phases are constructed:
Assistant
Perfect. Now let me check one more thing - the registry to understand detector metadata:
Assistant
Perfect! Now I have all the information I need. Let me provide a comprehensive summary:
Summary: Shared Detector Phases, Fixers, and Language Plugin Architecture
def get_dimension_for_detector(detector: str):
"""Look up which dimension a detector belongs to."""
policy = DETECTOR_SCORING_POLICIES.get(detector)
if not policy or policy.dimension is None:
return None
return DIMENSIONS_BY_NAME.get(policy.dimension)
Handling Unknown Detectors
Query 1: What happens with an unknown detector like "golangci_lint"?
The system has safe fallback handling:
In detector_policy() function (line 182):
python
def detector_policy(detector: str) -> DetectorScoringPolicy:
"""Get scoring policy for a detector, with a safe default fallback."""
return DETECTOR_SCORING_POLICIES.get(
detector,
DetectorScoringPolicy(detector=detector, dimension=None, tier=None),
)
→ Returns a policy with dimension=None (no scoring impact)
In get_dimension_for_detector():
If detector not in DETECTOR_SCORING_POLICIES, returns None
Test confirms: get_dimension_for_detector("nonexistent_detector") returns None
In dimension scoring (compute_dimension_scores_by_mode()):
Detectors with dimension None are skipped entirely from scoring
Finding data for unknown detectors is still persisted but doesn't affect scores
In compute_score_impact() test (test_scoring.py line 734):
from desloppify.core.registry import detector_tools as _detector_tools
DETECTOR_TOOLS = _detector_tools() # Built from registry.py
STRUCTURAL_MERGE = {"large", "complexity", "gods", "concerns"}
def compute_fixer_leverage(...) -> dict[str, float | int | str]:
"""Estimate how much value automated fixers would deliver."""
auto_fixable = sum(
action.get("count", 0)
for action in actions
if action.get("type") == "auto_fix"
)
# ... compute coverage and impact ratio
@dataclass
class FixResult:
"""Return type for fixer wrappers that need to carry metadata."""
entries: list[dict]
skip_reasons: dict[str, int] = field(default_factory=dict)
Example skip reason labels (from apply_flow.py, lines 251-259):
Example: A "remove // FIXME comments" fixer would:
python
def detect_fixme(path: Path) -> list[dict]:
entries = []
for f in path.rglob("*.ts"):
for i, line in enumerate(f.read_text().splitlines(), 1):
if "// FIXME" in line:
entries.append({"file": str(f), "line": i})
return entries
def fix_fixme(entries, dry_run=False) -> list[dict]:
by_file = defaultdict(list)
for e in entries:
by_file[e["file"]].append(e)
results = []
for path, file_entries in by_file.items():
lines = Path(path).read_text().splitlines(keepends=True)
remove_lines = {e["line"] - 1 for e in file_entries}
new_lines = [l for i, l in enumerate(lines) if i not in remove_lines]
if not dry_run:
Path(path).write_text("".join(new_lines))
results.append({
"file": path,
"removed": [f"FIXME comment at line {e['line']}" for e in file_entries],
"lines_removed": len(file_entries),
})
return results
Generic "Run Shell Command" Fixer
Could be possible, but limited value:
Detect phase would need to know what to find (language-specific)
Fix phase would execute command, but parsing output is language-specific
Skip reasons, state resolution, cascading cleanup all become generic/unreliable
Called in: desloppify/intelligence/review/context_holistic/selection.py (lines 229-234)
Purpose: Compute language-specific API surface consistency signals.
Example:
python
# TypeScript: flags files with mixed sync/async exports
def api_surface(file_contents: dict[str, str]) -> dict[str, list[str]]:
sync_async_mix: list[str] = []
for filepath, content in file_contents.items():
has_sync = bool(re.search(r"\bexport\s+function\s+\w+", content))
has_async = bool(re.search(r"\bexport\s+async\s+function\s+\w+", content))
if has_sync and has_async:
sync_async_mix.append(rel(filepath))
return {"sync_async_mix": sync_async_mix[:20]} if sync_async_mix else {}
# Python: empty (no mixed-pattern API concerns)
def api_surface(_file_contents: dict[str, str]) -> dict:
return {}
If None: Returns {}
3. review_guidance: dict
Hardcoded patterns, auth checks, naming conventions for agent to review.
Example:
python
REVIEW_GUIDANCE = {
"patterns": [
"Check for `async def` functions that never `await`",
"Look for bare `except:` clauses",
"Verify `@lru_cache` isn't on methods with mutable defaults",
],
"auth": [
"Check `@login_required` consistency",
"Flag unvalidated `request.data` in ORM queries",
],
"naming": "Python uses snake_case for functions, PascalCase for classes",
}
If empty dict: No language-specific guidance provided (agent uses generic defaults)
4. review_low_value_pattern: object (regex)
Files matching this pattern are excluded from review (e.g., type stubs, index files).
cmd_detect(args)
→ resolve_lang(args) — from --lang or auto-detect
→ _resolve_detector_key(detector_input, lang.detect_commands) — validate detector name
→ Set default thresholds (large, dupes)
→ make_lang_run(lang_cfg, ...) — create LangRun with settings/options
→ lang.detect_commands[detector](args) — run detector function
Independent from scoring pipeline. Keys serve as valid detector name list.
Example (Python):desloppify/languages/python/commands.py has:
large — files >threshold LOC
dupes — duplicate functions
coupling — import cycles
etc.
Each detector is a callable: detect_<name>(args) that:
Reads from args.path
Parses args.threshold (if applicable)
Prints or outputs JSON
Can be completely independent of the scoring system
Key property: Detect commands run standalone, bypassing state tracking and narrative coaching. They're for one-off analysis or integration with external tools.
@dataclass
class FunctionInfo:
name: str # Function/method name
file: str # File path (can be relative or absolute)
line: int # Start line number (1-indexed)
end_line: int # End line number
loc: int # Lines of code (end_line - start_line)
body: str # Raw function body (including signature)
normalized: str = "" # Normalized body (comments/prints stripped)
body_hash: str = "" # MD5 hash of normalized body
params: list[str] = field(...) # Parameter names extracted from signature
return_annotation: str | None = None
Python Function Extraction (/Users/user_c042661f/Documents/desloppify/desloppify/languages/python/extractors.py)
Approach: Regex + indentation-based line boundaries
Regex: r"^(\s*)(?:async\s+)?def\s+(\w+)\s*\(" (matches def and async def)
Signature parsing: finds the line where signature closes (presence of ) and : after it)
Body extraction: all lines indented past the function's indent level, trimmed of trailing blanks
Used to filter which files to consider for coverage scoring
zone_map.include_only(all_files, Zone.PRODUCTION, Zone.SCRIPT) gets scorable production files
External test discovery (find_external_test_files() in shared_phases.py)
python
def find_external_test_files(path: Path, lang: LangConfig) -> set[str]:
"""Find test files in standard locations outside the scanned path."""
extra = set()
path_root = path.resolve()
test_dirs = lang.external_test_dirs or ["tests", "test"]
exts = tuple(lang.test_file_extensions or lang.extensions)
for test_dir in test_dirs:
d = PROJECT_ROOT / test_dir
if not d.is_dir():
continue
if d.resolve().is_relative_to(path_root):
continue # already inside scanned path
for root, _, files in os.walk(d):
for filename in files:
if any(filename.endswith(ext) for ext in exts):
extra.add(os.path.join(root, filename))
return extra
Import extraction and function extraction are not bottlenecks
Maintenance burden: need to learn tree-sitter query syntax, debug byte-offset issues
If problems arise (e.g., multi-line import failures, function boundary misdetection), consider tree-sitter for just Python imports (using ast which is already solid) or TS imports (only regex-based extraction).
6. Key Interface Contracts
LangConfig requirements for test coverage (/Users/user_c042661f/Documents/desloppify/desloppify/languages/framework/base/types.py)
python
@dataclass
class LangConfig:
build_dep_graph: Callable[[Path], dict] # Required
zone_map: object | None = field(...) # Set at scan time
dep_graph: dict | None = field(...) # Set at scan time
# Optional:
extract_functions: Callable[[Path], list] | None = None
file_finder: Callable | None = None
complexity_map: dict[str, float] | None = field(...) # Set at scan time
external_test_dirs: list[str] = ["tests", "test"]
test_file_extensions: list[str] = []
What test coverage detector requires from language:
build_dep_graph(path) → dict with imports/importers sets
zone_map populated at scan time (for zone classification)
Language-specific test coverage module at languages/{lang}/test_coverage.py with:
Auto-register generic detectors into scoring system when generic_lang() is called
Auto-register into DETECTOR_TOOLS for narrative actions
These should go into a "Lint" or "Code quality" dimension
Tier 2: Fixers (many linters support --fix)
Add optional fix_cmd to tool specs
Generate FixerConfig that runs the fix command and re-detects
Tier 3: Generic Dep Graph + Function Extraction (regex-based, best-effort)
Simple regex-based import extraction for common patterns (import/require/use/include)
Simple regex-based function extraction for common patterns (def/fn/func/function)
These feed into orphaned detection, coupling, duplicate detection
Tier 4: Test Coverage (naming-convention based)
Generic test_coverage module that uses naming conventions only
No dep graph needed — just match test_X → X patterns per language
Tier 5: Review + Move (minimal defaults)
Generic review guidance and module patterns
Move with file rename but no import rewriting (with helpful message)
Please produce a detailed implementation plan with specific files to create/modify, function signatures, and the order of implementation. Think about what can be reused vs what needs to be new.
DETECTORS
python
def register_generic_detector(
detector_id: str,
*,
dimension: str = "Code quality",
tier: int = 3,
guidance: str = "",
label: str = "",
action_type: str = "manual_fix",
fixers: tuple[str, ...] = (),
) -> None:
"""Register a generic detector at runtime.
Called from generic_lang() to wire tool findings into scoring + narrative.
"""
if detector_id in DETECTORS:
return # Already registered (e.g. re-import)
DETECTORS[detector_id] = DetectorMeta(
name=detector_id,
display=label or detector_id.replace("_", " "),
dimension=dimension,
action_type=action_type,
guidance=guidance or f"review and fix {label or detector_id} findings",
fixers=fixers,
)
Important: Since DETECTOR_TOOLS in _constants.py is computed once at import time via _detector_tools(), we need to ensure it stays in sync. Two options:
Option A (preferred): Make DETECTOR_TOOLS lazy -- change _constants.py to call _detector_tools() on first access rather than at module load. This is the cleanest approach since generic plugins register after the narrative module initializes.
Option B: Have register_generic_detector() also update DETECTOR_TOOLS directly. This creates a second write path and risks going stale.
Recommended: Option A -- change DETECTOR_TOOLS in _constants.py to a lazy property:
python
# _constants.py
_DETECTOR_TOOLS_CACHE: dict | None = None
def get_detector_tools() -> dict:
global _DETECTOR_TOOLS_CACHE
if _DETECTOR_TOOLS_CACHE is None:
_DETECTOR_TOOLS_CACHE = _detector_tools()
return _DETECTOR_TOOLS_CACHE
def invalidate_detector_tools_cache() -> None:
global _DETECTOR_TOOLS_CACHE
_DETECTOR_TOOLS_CACHE = None
Then update all DETECTOR_TOOLS references (in action_engine.py, action_tools.py, __init__.py) to use get_detector_tools() instead. The register_generic_detector() function calls invalidate_detector_tools_cache() to force rebuild.
B. desloppify/engine/scoring_internal/policy/core.py -- Add dynamic scoring registration
Add a function register_generic_scoring_policy(detector_id, dimension, tier):
python
def register_generic_scoring_policy(
detector_id: str,
dimension: str = "Code quality",
tier: int = 3,
*,
file_based: bool = True,
) -> None:
"""Register scoring policy for a generic detector at runtime."""
if detector_id in DETECTOR_SCORING_POLICIES:
return
DETECTOR_SCORING_POLICIES[detector_id] = DetectorScoringPolicy(
detector=detector_id,
dimension=dimension,
tier=tier,
file_based=file_based,
)
if file_based:
FILE_BASED_DETECTORS.add(detector_id)
# Rebuild DIMENSIONS to include the new detector
_rebuild_dimensions()
Also add _rebuild_dimensions():
python
def _rebuild_dimensions() -> None:
global DIMENSIONS, DIMENSIONS_BY_NAME
DIMENSIONS = _build_dimensions()
DIMENSIONS_BY_NAME = {d.name: d for d in DIMENSIONS}
C. desloppify/languages/framework/generic.py -- Wire auto-registration into generic_lang()
At the end of generic_lang(), after building the LangConfig, call both registration functions:
python
from desloppify.core.registry import register_generic_detector
from desloppify.engine.scoring_internal.policy.core import register_generic_scoring_policy
for tool in tools:
register_generic_detector(
tool["id"],
dimension="Code quality",
tier=tool["tier"],
guidance=f"review and fix {tool['label']} findings",
label=tool["label"],
action_type="auto_fix" if tool.get("fix_cmd") else "manual_fix",
fixers=(f"{tool['id']}-fix",) if tool.get("fix_cmd") else (),
)
register_generic_scoring_policy(
tool["id"],
dimension="Code quality",
tier=tool["tier"],
file_based=True,
)
Impact: After this tier, scanning a Go project will produce findings that affect the score, appear in dimension breakdowns, and generate narrative actions like "5 golangci_lint findings -- review and fix golangci-lint findings".
Tier 2: Fixers (--fix mode for linters)
Goal: When a linter supports --fix, auto-generate a fixer that runs it.
A. Extend tool spec format
Add an optional fix_cmd key to tool dicts. Example for Ruby:
B. desloppify/languages/framework/generic.py -- Add generic fixer factory
Create make_generic_fixer() that builds a FixerConfig:
python
def make_generic_fixer(
tool_id: str,
label: str,
detect_cmd: str,
detect_fmt: str,
fix_cmd: str,
) -> FixerConfig:
"""Build a FixerConfig that runs an external fix command."""
parser = _PARSERS[detect_fmt]
def detect(path):
try:
result = subprocess.run(
detect_cmd, shell=True, cwd=str(path),
capture_output=True, text=True, timeout=120,
)
except (FileNotFoundError, subprocess.TimeoutExpired):
return []
output = (result.stdout or "") + (result.stderr or "")
return parser(output, path)
def fix(entries, *, dry_run=False):
if dry_run:
return [
{"file": e["file"], "removed": [e["message"]], "lines_removed": 1}
for e in entries
]
path = Path(entries[0]["file"]).parent if entries else Path(".")
# Find scan root (common ancestor)
files = {e["file"] for e in entries}
scan_root = Path(os.path.commonpath(list(files))) if files else path
if not scan_root.is_dir():
scan_root = scan_root.parent
try:
subprocess.run(
fix_cmd, shell=True, cwd=str(scan_root),
capture_output=True, text=True, timeout=120,
)
except (FileNotFoundError, subprocess.TimeoutExpired):
return []
# Re-detect to see what was fixed
remaining = set()
post_entries = detect(scan_root)
for e in post_entries:
remaining.add((e["file"], e["message"]))
results = []
for e in entries:
key = (e["file"], e["message"])
if key not in remaining:
results.append({
"file": e["file"],
"removed": [e["message"]],
"lines_removed": 0,
})
return results
return FixerConfig(
label=f"{label} auto-fix",
detect=detect,
fix=fix,
detector=tool_id,
verb="Fixed",
dry_verb="Would fix",
)
C. Wire fixers into generic_lang()
In generic_lang(), build the fixers dict:
python
fixers = {}
for t in tools:
if t.get("fix_cmd"):
fixer_name = f"{t['id']}-fix"
fixers[fixer_name] = make_generic_fixer(
t["id"], t["label"], t["cmd"], t["fmt"], t["fix_cmd"]
)
Pass fixers=fixers to LangConfig(...).
D. Update individual plugins with fix_cmd
Known tools with fix modes:
rubocop: "rubocop --auto-correct"
golangci-lint: "golangci-lint run --fix"
ktlint: "ktlint --format"
sqlfluff: "sqlfluff fix ."
cargo clippy: "cargo clippy --fix --allow-dirty"
hlint: "hlint --refactor ." (requires refactor)
swiftlint: "swiftlint lint --fix"
phpstan: no fix mode
cppcheck: no fix mode
Add fix_cmd to those plugins' tool dicts (update their __init__.py files).
Impact: desloppify fix rubocop_offense-fix --dry-run will work out of the box.
Tier 3: Shared Phases (Security, Test Coverage, Subjective Review, Duplicates)
Goal: Generic plugins should run the same shared phases that full plugins use.
A. desloppify/languages/framework/generic.py -- Add shared phases to the phase list
Currently, generic_lang() only creates phases for the external tools. Add the shared phases:
python
from desloppify.languages.framework.base.phase_builders import (
detector_phase_security,
detector_phase_test_coverage,
shared_subjective_duplicates_tail,
)
phases = [
make_tool_phase(t["label"], t["cmd"], t["fmt"], t["id"], t["tier"])
for t in tools
]
# Append shared detector phases (security, test coverage, review, dupes)
phases.append(detector_phase_security())
phases.append(detector_phase_test_coverage())
phases.extend(shared_subjective_duplicates_tail())
Security: The cross-language security detector (detectors/security.py) already works with any file list. It detects hardcoded secrets, insecure random, weak crypto, etc. This will "just work" since it only needs lang.file_finder and lang.zone_map, both of which generic plugins already provide.
Test Coverage: Requires a dep graph. With an empty dep graph (the current stub), it will produce zero results because _discover_scorable_and_tests() finds no production files. However, we can make this work at a basic level in Tier 3B.
Subjective Review: Already works with empty review_cache. The detect_review_coverage() function needs files, zone_map, per_file_cache, and lang_name -- all available. This will flag files as needing design review.
Duplicates: Requires extract_functions. With the noop stub, detect_duplicates([]) returns empty. Can work after Tier 4 adds generic function extraction.
B. Generic test coverage via naming convention only
The test coverage detector already does naming-based mapping via _naming_based_mapping() in desloppify/engine/detectors/coverage/mapping.py. The issue is that without a dep graph, _discover_scorable_and_tests() has no files to work with.
Solution: Make the generic dep graph builder return a minimal graph from the file finder:
python
def minimal_dep_graph(path: Path, file_finder, zone_map=None) -> dict:
"""Build a minimal dep graph with file entries but no import edges.
Sufficient for test coverage naming-convention mapping and orphaned count.
"""
files = file_finder(path) if file_finder else []
graph = {}
for f in files:
graph[f] = {"imports": set(), "importers": set()}
return graph
Then in generic_lang(), replace empty_dep_graph with a closure that calls minimal_dep_graph:
This gives test coverage something to work with: it will find production files (via zone map), find test files (via zone map + external test dirs), and do naming-convention matching (test_X.py -> X.py, etc.).
Impact: Security findings, test coverage gaps (naming-based), and subjective review flagging will all work for generic plugins.
Tier 4: Generic Function Extraction + Structural Analysis
Goal: Enable duplicate detection and structural analysis for generic plugins using simple regex.
A. desloppify/languages/framework/generic.py -- Add generic function extractor
Create a regex-based function extractor that handles common function declaration patterns:
python
import re
from desloppify.languages.framework.base.types import FunctionInfo # may need to import
# Common function patterns across languages
_FUNCTION_PATTERNS = {
# Go: func Name(params) return {
".go": re.compile(r"^\s*func\s+(?:\([^)]*\)\s+)?(\w+)\s*\("),
# Rust: fn name(params) -> Type {
".rs": re.compile(r"^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)\s*[<(]"),
# Ruby: def name(params)
".rb": re.compile(r"^\s*def\s+(\w+)"),
# Java/Kotlin/C#/Scala: <modifiers> Type name(params) {
".java": re.compile(r"^\s*(?:public|private|protected|static|final|abstract|\s)+\s+\w+\s+(\w+)\s*\("),
".kt": re.compile(r"^\s*(?:fun|suspend\s+fun)\s+(\w+)\s*[<(]"),
".scala": re.compile(r"^\s*def\s+(\w+)"),
# Swift: func name(params)
".swift": re.compile(r"^\s*(?:func|static\s+func|class\s+func)\s+(\w+)\s*[<(]"),
# PHP: function name(params)
".php": re.compile(r"^\s*(?:public|private|protected|static|\s)*function\s+(\w+)\s*\("),
# Elixir: def name(params)
".ex": re.compile(r"^\s*(?:def|defp)\s+(\w+)"),
".exs": re.compile(r"^\s*(?:def|defp)\s+(\w+)"),
# Haskell: name :: Type or name params =
".hs": re.compile(r"^(\w+)\s+.*="),
# C/C++: Type name(params) {
".c": re.compile(r"^\s*(?:\w+\s+)+(\w+)\s*\([^;]*$"),
".cpp": re.compile(r"^\s*(?:\w+\s+)+(\w+)\s*\([^;]*$"),
".h": re.compile(r"^\s*(?:\w+\s+)+(\w+)\s*\([^;]*$"),
".hpp": re.compile(r"^\s*(?:\w+\s+)+(\w+)\s*\([^;]*$"),
# Lua: function name(params) or local function name(params)
".lua": re.compile(r"^\s*(?:local\s+)?function\s+(\w+)"),
# Perl: sub name {
".pl": re.compile(r"^\s*sub\s+(\w+)"),
".pm": re.compile(r"^\s*sub\s+(\w+)"),
# Nim: proc name(params)
".nim": re.compile(r"^\s*proc\s+(\w+)"),
# Zig: fn name(params) Type {
".zig": re.compile(r"^\s*(?:pub\s+)?fn\s+(\w+)"),
# Shell: function name() or name()
".sh": re.compile(r"^\s*(?:function\s+)?(\w+)\s*\(\)"),
".bash": re.compile(r"^\s*(?:function\s+)?(\w+)\s*\(\)"),
# PowerShell: function Name {
".ps1": re.compile(r"^\s*function\s+(\w[\w-]*)"),
".psm1": re.compile(r"^\s*function\s+(\w[\w-]*)"),
# Clojure: (defn name ...)
".clj": re.compile(r"^\s*\(defn-?\s+(\w+)"),
".cljs": re.compile(r"^\s*\(defn-?\s+(\w+)"),
".cljc": re.compile(r"^\s*\(defn-?\s+(\w+)"),
}
The extractor function:
python
def make_generic_function_extractor(extensions: list[str]) -> callable:
"""Build a function extractor using regex patterns for the given extensions."""
# Collect applicable patterns
patterns = {}
for ext in extensions:
if ext in _FUNCTION_PATTERNS:
patterns[ext] = _FUNCTION_PATTERNS[ext]
if not patterns:
return noop_extract_functions # No patterns for this language
def extract(path: Path) -> list:
from desloppify.languages.framework.base.types import FunctionInfo
functions = []
file_finder_fn = make_file_finder(extensions)
for filepath in file_finder_fn(path):
ext = Path(filepath).suffix
pattern = patterns.get(ext)
if not pattern:
continue
try:
content = Path(filepath).read_text(errors="replace")
except OSError:
continue
lines = content.splitlines()
for i, line in enumerate(lines):
m = pattern.match(line)
if m:
name = m.group(1)
# Collect body (simple: next N lines or until matching indent)
body_lines = lines[i:min(i + 50, len(lines))]
body = "\n".join(body_lines)
functions.append(FunctionInfo(
name=name,
file=filepath,
line=i + 1,
body=body,
params="",
))
return functions
return extract
Check what FunctionInfo looks like:
We need to verify the FunctionInfo dataclass definition.
This inserts into DETECTOR_SCORING_POLICIES, updates FILE_BASED_DETECTORS, and calls _rebuild_dimensions() to refresh DIMENSIONS and DIMENSIONS_BY_NAME.
Step 1C: Make DETECTOR_TOOLS lazy in the narrative system
The current code computes DETECTOR_TOOLS = _detector_tools() at module load time. This happens before generic_lang() runs, so generic detectors are never included. Change to a lazy pattern:
python
_DETECTOR_TOOLS_CACHE: dict | None = None
def get_detector_tools() -> dict:
global _DETECTOR_TOOLS_CACHE
if _DETECTOR_TOOLS_CACHE is None:
_DETECTOR_TOOLS_CACHE = _detector_tools()
return _DETECTOR_TOOLS_CACHE
def invalidate_detector_tools_cache() -> None:
global _DETECTOR_TOOLS_CACHE
_DETECTOR_TOOLS_CACHE = None
Files to update (change DETECTOR_TOOLS to get_detector_tools()):
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/action_engine.py -- 3 references in _append_auto_fix_actions, _append_reorganize_actions, _append_refactor_actions
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/action_tools.py -- 1 reference in _build_fixers
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/__init__.py -- re-export get_detector_tools instead of or alongside DETECTOR_TOOLS
The register_generic_detector() function in registry.py should call invalidate_detector_tools_cache() to force rebuild on next access.
Step 1D: Wire auto-registration into generic_lang()
At the end of generic_lang(), after building the LangConfig, iterate the tools and register each:
python
for tool in tools:
register_generic_detector(
tool["id"],
dimension="Code quality",
tier=tool["tier"],
guidance=f"review and fix {tool['label']} findings",
label=tool["label"],
action_type="auto_fix" if tool.get("fix_cmd") else "manual_fix",
fixers=(f"{tool['id']}-fix",) if tool.get("fix_cmd") else (),
)
register_generic_scoring_policy(
tool["id"],
dimension="Code quality",
tier=tool["tier"],
file_based=True,
)
Result: After scanning a Go project, golangci_lint findings will contribute to the "Code quality" dimension score, and narrative will generate actions like "5 golangci_lint findings -- review and fix golangci-lint findings".
Tier 2: Shared Detector Phases
Currently, generic plugins only run their external tools as phases. Full plugins also run shared phases for security, test coverage, structural analysis, subjective review, and duplicate detection. These phases are language-agnostic and should work with generic plugins.
from desloppify.languages.framework.base.phase_builders import (
detector_phase_security,
detector_phase_test_coverage,
shared_subjective_duplicates_tail,
)
from desloppify.languages._shared.phases_common import (
run_structural_phase,
run_coupling_phase,
)
Build phases list with shared phases appended:
python
phases = [make_tool_phase(...) for t in tools]
# Add structural analysis (large files, complexity, flat dirs)
phases.append(DetectorPhase("Structural analysis", _make_structural_phase(extensions)))
# Security (cross-language: secrets, weak crypto, etc.)
phases.append(detector_phase_security())
# Test coverage (naming-convention based when dep graph is minimal)
phases.append(detector_phase_test_coverage())
# Subjective review + duplicate detection tail
phases.extend(shared_subjective_duplicates_tail())
The structural phase needs a wrapper because run_structural_phase requires complexity_signals. For generic plugins, pass an empty list (no language-specific signals; still runs large file + flat dir detection):
Replace empty_dep_graph with minimal_dep_graph that creates entries for all source files (no import edges, but files are present in the graph):
python
def minimal_dep_graph(path: Path, file_finder_fn) -> dict:
"""Build a minimal dep graph with file entries but no import edges."""
files = file_finder_fn(path) if file_finder_fn else []
graph = {}
for f in files:
graph[f] = {"imports": set(), "importers": set()}
return graph
Result: Test coverage detection will find production files (via zone map) and match them against test files using naming conventions. Orphaned detection will see all files but report none orphaned (since there are no import edges to determine what is used/unused -- which is correct behavior for a minimal graph). Coupling and cycles will be empty (no edges).
Step 2C: Add coupling phase (optional, only when dep graph has data)
The coupling phase (run_coupling_phase) runs single-use, cycles, and orphaned detectors. With a minimal dep graph (no edges), it will report everything as "0 importers" which would create false positives for orphaned detection. The OrphanedDetectionOptions has a corroboration_min_signals parameter that prevents this, but we should be explicit.
Create a wrapper that skips coupling when the dep graph has no edges:
python
def _make_coupling_phase(file_finder_fn):
def phase_fn(path, lang):
from desloppify.utils import log
graph = lang.dep_graph or lang.build_dep_graph(path)
lang.dep_graph = graph
# Skip coupling analysis when graph has no edges (generic plugins)
has_edges = any(
entry.get("imports") or entry.get("importers")
for entry in graph.values()
)
if not has_edges:
return [], {}
return run_coupling_phase(
path, lang, build_dep_graph_fn=lang.build_dep_graph, log_fn=log
)
return DetectorPhase("Coupling + cycles + orphaned", phase_fn)
This is conservative -- no false positives. Coupling/cycles/orphaned will remain empty for generic plugins until they get import parsing (if ever).
Add a _FUNCTION_PATTERNS dict mapping file extensions to compiled regex patterns that match function declarations. Cover all 22 generic plugin extensions. Each regex should capture the function name as group 1.
Step 4B: Create generic function extractor factory
python
def make_generic_function_extractor(
extensions: list[str],
file_finder_fn,
) -> callable:
"""Build a regex-based function extractor for duplicate detection."""
patterns = {ext: _FUNCTION_PATTERNS[ext] for ext in extensions if ext in _FUNCTION_PATTERNS}
if not patterns:
return noop_extract_functions
def extract(path: Path) -> list:
from desloppify.engine.detectors.base import FunctionInfo
functions = []
for filepath in file_finder_fn(path):
ext = Path(filepath).suffix
pattern = patterns.get(ext)
if not pattern:
continue
try:
content = Path(filepath).read_text(errors="replace")
except OSError:
continue
lines = content.splitlines()
for i, line in enumerate(lines):
m = pattern.match(line)
if m:
name = m.group(1)
# Estimate body: next 50 lines or until dedent
end = min(i + 50, len(lines))
body = "\n".join(lines[i:end])
loc = end - i
functions.append(FunctionInfo(
name=name,
file=filepath,
line=i + 1,
end_line=end,
loc=loc,
body=body,
))
return functions
return extract
Then modify load_lang_move_module() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/move/move_language.py to fall back to the generic module instead of calling sys.exit(1):
python
def load_lang_move_module(lang_name: str) -> ModuleType:
module_name = f"desloppify.languages.{lang_name}.move"
try:
return importlib.import_module(module_name)
except ImportError:
# Fall back to generic move (file rename only, no import rewriting)
return importlib.import_module("desloppify.languages.framework.generic_move")
Step 5B: Review defaults (already mostly work)
The review system already has robust fallbacks:
review_module_patterns_fn=None falls back to default_review_module_patterns() in /Users/user_c042661f/Documents/desloppify/desloppify/intelligence/review/context.py (line 140-142)
No changes needed for basic review functionality. For better quality, we could add generic review guidance, but that is optional and out of scope for this plan.
Implementation Order and Dependencies
code
Tier 1A: registry.py (register_generic_detector)
Tier 1B: scoring policy/core.py (register_generic_scoring_policy)
Tier 1C: narrative/_constants.py (lazy DETECTOR_TOOLS)
+ action_engine.py, action_tools.py, __init__.py (use getter)
Tier 1D: generic.py (call registration in generic_lang)
All of Tier 1 can be done as a single commit.
Tier 2A: generic.py (add shared phases)
Tier 2B: generic.py (minimal dep graph)
Tier 2C: generic.py (coupling phase guard)
Tier 2 depends on Tier 1 (shared phases produce findings for
detectors like "structural", "security", "test_coverage" which
are already in the registry).
Tier 3A: generic.py (make_generic_fixer)
Tier 3B: generic.py (wire fixers)
Tier 3C: individual plugin __init__.py files (add fix_cmd)
Tier 3 depends on Tier 1 (fixers reference detector IDs that
must be registered in DETECTORS).
Tier 4A-C: generic.py (function extraction)
Independent of other tiers but best done after Tier 2
(shared phases provide the duplicate detection phase).
Tier 5A: generic_move.py + move_language.py (generic move fallback)
Tier 5B: No changes needed.
Independent of other tiers.
Tier 1 tests: Add tests in desloppify/tests/ verifying:
register_generic_detector() adds to DETECTORS and DETECTOR_TOOLS is rebuilt
register_generic_scoring_policy() adds to DETECTOR_SCORING_POLICIES and rebuilds dimensions
Scanning a Go project produces findings that appear in dimension scores
Narrative generates actions for generic detector findings
Tier 2 tests: Verify shared phases produce findings:
Security detector finds hardcoded secrets in .go files
Structural detector flags large .go files
Test coverage detector uses naming convention (test_X_test.go -> X.go)
Tier 3 tests: Mock subprocess to verify:
make_generic_fixer creates working detect/fix callables
Fix command re-detects and computes delta
Dry run returns preview without running fix_cmd
Tier 4 tests: Verify function extraction:
Go: func Name( extracted
Rust: fn name( extracted
Ruby: def name extracted
Duplicate detection finds similar functions across files
Tier 5 tests: Verify:
Move command falls back to generic module
File is renamed but no import rewriting
Verify hint warns user about manual import updates
Potential Challenges
Import ordering: generic_lang() runs at import time when language modules are loaded. The registration functions in registry.py and policy/core.py must be importable without circular dependencies. This should be fine since generic.py already imports from state.py and utils.py.
Module load order: DETECTOR_TOOLS is used by the narrative system at query time, not at import time. Making it lazy resolves any ordering concerns.
Test isolation: Tests that check DETECTORS or DETECTOR_SCORING_POLICIES must account for generic detectors being registered. Consider adding cleanup fixtures.
Idempotency: Since generic_lang() may be called multiple times (e.g., in tests or during module reloads), all registration functions must be idempotent.
Display order: The DISPLAY_ORDER in registry_order.py does not include generic detector IDs. Generic detectors should appear after the canonical ones in display output. The display_order() function returns list(_DISPLAY_ORDER) which only has canonical detectors. Generic detectors will appear when iterating DETECTORS.keys() but not in the display order. This is acceptable -- they will show up in dimension breakdowns and narrative but not in the fixed display table.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/languages/framework/generic.py - Central hub: all wiring for scoring, narrative, fixers, shared phases, function extraction happens here
/Users/user_c042661f/Documents/desloppify/desloppify/core/registry.py - Add register_generic_detector() for dynamic detector metadata registration
/Users/user_c042661f/Documents/desloppify/desloppify/engine/scoring_internal/policy/core.py - Add register_generic_scoring_policy() for dynamic scoring policy registration
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/_constants.py - Make DETECTOR_TOOLS lazy so generic detectors are included
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/move/move_language.py - Add generic fallback instead of sys.exit(1) for unsupported languages
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.
desloppify/app/commands/langs.py
Created tests: desloppify/tests/lang/common/test_generic_plugin.py
Test Fixing Phase: Multiple test failures:
importlib.util shadow bug in discovery.py
test_unknown_ext - .rb now recognized (changed to .xyz)
test_no_source_files - .md and .yml now recognized (changed to .txt/.toml)
Updated all standardization tests to use _full_langs() helper that filters by integration_depth == "full"
Fixed test_all_builtin_langs_discoverable to not reset registry
User Feedback #3: "and are they all plugged in in the same way? Where's python" - User noticed two different registration paths
Unification: Changed register_lang to store instances (not classes), simplified get_lang(), updated test_get_lang_returns_fresh_instances → test_get_lang_returns_same_instance
Quality Message: Added quality_message property to LangConfig, added display in scan output after zones line
User Feedback #4: "so there's no difference between them and full languages other than that? And will all the other languages fundamentally work?" - I honestly listed what doesn't work
User Feedback #5: "how could we get them all working?" - I outlined the path (scoring, narrative, fixers, tree-sitter for dep graphs)
User Feedback #6: "can you make a plan for how to get them all working? be extremely thorough" - Entered plan mode
Plan Mode Exploration: Launched 3 Explore agents to investigate:
Scoring & narrative systems
Fixers, move, review systems
Dep graph, dupes, test coverage, tree-sitter feasibility
Plan Design: Launched Plan agent that produced 5-tier implementation plan
Now I need to capture all the current state precisely, including what files exist, what's been modified, and what the plan entails.
After initial implementation, the user gave critical feedback:
Plugins should be in folders (packages) like full languages, not as plugin_*.py files
Registration should be unified — no two different mechanisms for full vs generic plugins
A quality message should appear during scan for non-full plugins
Most recently: the user wants a thorough plan for making ALL features work for generic plugins (scoring, narrative, fixers, move, review, dep graph, function extraction, test coverage, duplicate detection) — not just basic scanning
Key Technical Concepts:
LangConfig dataclass: Central configuration for each language plugin (desloppify/languages/framework/base/types.py)
DetectorPhase: Scan pipeline phase that runs detectors and returns (findings, signals) tuples
Registry pattern: All plugins store LangConfig instances in registry_state._registry dict
quality = getattr(lang, "quality_message", None)
if quality:
_stderr(
f" Note: our {lang.name} integration is {quality}."
f" Consider improving based on gaps you see."
)
22 Language Plugin Packages (CREATED as languages/<name>/__init__.py):
desloppify/engine/detectors/test_coverage/detector.py — Test coverage
Errors and Fixes:
importlib.util shadow bug: Adding import importlib.util inside a function in discovery.py shadowed the module-level importlib import, causing UnboundLocalError. Fixed by moving import importlib.util to the top of the file.
test_unknown_ext failure: Ruby (.rb) was now a registered extension. Fixed by changing test to use .xyz.
test_no_source_files failure: Markdown (.md) and YAML (.yml) were now registered. Fixed by changing to .txt/.toml.
Structure validation failures: 12 tests failed because they iterated available_langs() and expected all languages to have full package structure (commands.py, extractors.py, etc.). Fixed by adding _full_langs() helpers that filter by integration_depth == "full".
test_all_builtin_langs_discoverable failure: Clearing registry and calling load_all() didn't re-register because Python caches imported modules. Fixed by simplifying test to check current state instead of reset+rediscover.
User feedback on organization: Initially created plugin_*.py files. User asked "why don't we have them in folders?" and "why are we splitting up different kinds of implementations?" — reorganized to languages/<name>/__init__.py packages.
User feedback on registration: User asked "are they all plugged in in the same way? Where's python?" — unified registration so register_lang stores instances, not classes.
Problem Solving:
Solved the organizational inconsistency between full and generic plugins (packages vs single files)
Solved the dual registration mechanism (class-based vs instance-based) by unifying to instance storage
Identified the fundamental gaps in generic plugins: scoring (zero impact), narrative (no actions), fixers (none), move (stubs), review (defaults work partially), dep graph (empty), function extraction (noop), test coverage (broken without dep graph)
Designed a 5-tier plan to address all gaps, prioritized by impact and complexity
All User Messages:
"Implement the following plan: [detailed Generic Language Plugin System plan]"
"continue please" (after interruption)
"sorry, why don't we have them in folders like the main languages?"
"why are we splitting up different kinds of implementations?"
"yes please" (confirming packages instead of single files)
"and are they all plugged in in the same way? Where's python"
"yes please, keep it as simple as possible, we should also have a language quality metric that we store like this for each language and we include in the scan message 'Our current Elixir implementation is [STATUS]. Please consider making improvements based on gaps that you see'"
"so there's no difference between them and full languages other than that? And will all the other languages fundamentally work?"
"how could we get them all working?"
"can you make a plan for how to get them all working? be extremely thorough"
Pending Tasks:
Write the final plan file at /Users/user_c042661f/.claude/plans/humble-riding-scroll.md and call ExitPlanMode
The plan covers 5 tiers of work to make generic plugins fully functional:
Tier 1: Scoring + narrative wiring (register generic detectors into scoring dimensions and DETECTOR_TOOLS)
Tier 3: Generic fixers (add fix_cmd to tool specs for linters that support --fix)
Tier 4: Generic function extraction (regex-based for duplicate detection)
Tier 5: Move fallback + review defaults
Current Work:
I am in plan mode, having completed Phase 1 (exploration via 3 parallel Explore agents) and Phase 2 (design via Plan agent). The Plan agent returned a comprehensive 5-tier implementation plan. I now need to:
Write the final plan to the plan file
Call ExitPlanMode for user approval
The user's most recent request was: "can you make a plan for how to get them all working? be extremely thorough"
All implementation is complete for the basic generic plugin system (2778 tests passing, langs command works, scan works for generic plugins with quality messages). The plan for making ALL features work has been designed but not yet written to the plan file or approved.
Optional Next Step:
Write the comprehensive 5-tier plan to /Users/user_c042661f/.claude/plans/humble-riding-scroll.md and call ExitPlanMode. This directly fulfills the user's request: "can you make a plan for how to get them all working? be extremely thorough"
def detector_tools() -> dict[str, dict]:
"""Build detector tool metadata keyed by detector name."""
result = {}
for name, d in DETECTORS.items():
entry: dict = {
"fixers": list(d.fixers),
"action_type": d.action_type,
}
if d.tool:
entry["tool"] = d.tool
if d.guidance:
entry["guidance"] = d.guidance
result[name] = entry
return result
findings = [
make_finding(
smell_id, # Tool ID (e.g., "golangci_lint")
e["file"],
f"{smell_id}::{e['line']}", # Unique ID
tier=tier,
confidence="medium",
summary=e["message"], # Message from tool
)
for e in entries
]
Key Limitation: Generic plugins don't contribute to scoring or narrative by default because:
Tool IDs ("golangci_lint", "vet_error") are NOT registered in DETECTORS dict
Without DETECTORS entry → no DETECTOR_SCORING_POLICIES entry
Without scoring policy → detector doesn't contribute to dimensions
Without dimension → doesn't appear in narrative actions