I need you to critically analyze the refactoring of the desloppify/app/commands/review/ module.
The following files were DELETED:
assessment_integrity.py
batch_core.py
batch_prompt_template.py
batch_scoring.py
helpers.py
import_helpers.py
runner_helpers.py
runtime.py
And these NEW directories were created:
review/importing/
review/normalization/
review/orchestration/
review/payload/
review/quality/
review/runtime/
Please:
Read the new directories (list files in each, read key files) to understand what they contain
Look at the git diff for the deleted files to understand what was removed vs moved
Assess: Is the code being genuinely decomposed into better abstractions, or is it just being spread across more files with the same coupling? Look for signs of:
Actual separation of concerns
Reduced coupling between modules
Clear, cohesive interfaces per module
Or alternatively: circular imports, re-exports that just add indirection, files that are too small to justify existing
Be blunt and specific in your assessment. Give concrete examples.
Assistant
I'll systematically analyze this refactoring. Let me start by understanding the new directory structure and the deleted files.
User
I need you to critically analyze the refactoring of the desloppify/core/ module.
New files/directories added:
core/_internal/path_proxy.py
core/coercions_api.py
core/discovery/ (new directory)
core/exception_sets.py
core/io/ (new directory)
core/nonfatal.py
core/pathing/ (new directory)
core/score_targets.py
core/text_api.py
Existing files modified:
core/init.py
core/_internal/text_utils.py
core/config.py
core/discovery_api.py
core/enums.py
core/fallbacks.py
core/file_paths.py
core/grep.py
core/output.py
core/output_api.py
core/paths_api.py
core/query.py
core/query_paths.py
core/registry.py
core/signal_patterns.py
core/skill_docs.py
core/source_discovery.py
Please:
List files in the new directories (core/discovery/, core/io/, core/pathing/) and read their contents
Read the new standalone files (coercions_api.py, exception_sets.py, nonfatal.py, score_targets.py, text_api.py, path_proxy.py)
Look at the diff for core/init.py to understand how the public API surface changed
Assess critically:
Are these new modules genuinely cohesive units, or are they tiny fragments that should stay together?
Is the _api.py suffix pattern (coercions_api, text_api, paths_api, output_api, discovery_api) creating unnecessary indirection?
Is there a clear layering/dependency direction, or is this creating a web of imports?
Do any of the new files contain trivially small amounts of code that don't justify a separate module?
Be specific and blunt.
Assistant
I'll start by reading all the new files and directories, plus the key diffs.
Assistant
Now let me read the __init__.py files to understand the re-export patterns, and get the git diffs for the deleted files.
User
I need to critically analyze two areas of a refactoring:
The new desloppify/compat/ directory — list and read its files. Understand what it provides. Is there a genuine need for a compatibility layer, or is this premature abstraction?
The new helper files in desloppify/app/commands/helpers/:
Read the new contracts.py files, phase_policies.py, and list the syntax/ directory
Check the git diff for a sample of heavily-modified files (e.g., framework/generic.py, framework/runtime.py, ts/phases.py) to understand what kind of changes are being made
Assess:
Are the "contracts" files introducing meaningful interface definitions or just type aliases?
Is phase_policies.py a genuine policy extraction or a trivial split?
What's in syntax/ — real parsing logic or just constants?
In the heavily modified files, is the refactoring improving modularity or just changing import paths?
Look for whether functions are actually being restructured or just moved
Be blunt and specific with examples.
Assistant
Now let me read the compat files and the existing modified helpers.
Assistant
Now let me read the core/init.py diff and the existing files that were modified to understand the full picture.
Assistant
I'll systematically analyze these changes. Let me start by reading the new files and examining the diffs.
User
Critically analyze the test and utility changes in this refactoring.
New test files:
test_direct_coverage_additional_modules.py
test_direct_coverage_helpers.py
test_api_surfaces_direct.py
test_compat_utils_direct.py
test_file_paths_output_api_direct.py
test_review_batch_core.py
test_review_batches_nonfatal.py
test_review_merge.py
test_runtime_policy_direct.py
Modified test files (many)
Also: desloppify/utils.py has 139 lines changed.
Please:
Read several of the new test files to understand their pattern. Are they:
Genuine behavioral tests that validate real functionality?
Or superficial "coverage padding" tests that just import modules and assert they exist?
Do they test actual logic with meaningful assertions?
Look at the utils.py diff to understand what changed there
Check if existing test modifications are just updating import paths (suggesting the tests just follow renames) vs testing new behavior
Look at the naming pattern "test_direct_coverage_" and "test__direct" — these names suggest they might be mechanical coverage tests rather than behavior tests
Be honest about whether the test additions represent real quality improvement or just number-padding.
Assistant
Now let me read the new files to compare with the deleted ones.
Assistant
Now let me check who actually imports from these new modules, and what the original files look like.
Assistant
Now let me check what the original modules looked like (before the compat shims were introduced), plus understand the new core/discovery/, core/pathing/, and core/io/ directories that compat is proxying to.
Assistant
I'll systematically analyze the test files and utility changes. Let me start by reading the new test files and the utils.py diff.
Assistant
Now let me look at the diffs for the heavily modified framework files and the deleted file.
Assistant
Now let me read the orchestration directory and the remaining small files to complete the picture.
Assistant
Now let me check what the original files looked like and what the compat/ directory contains, plus check for internal _coercions module.
Assistant
Now let me check the deleted common.py file and the original locations of what was moved.
Assistant
Now let me check for the actual differences using diff. Let me compare the old and new versions of the largest files.
Assistant
Now let me look at the utils.py diff and some modified test files.
Assistant
Now let me check the existing modified helpers for context and see how many callers actually use the new files.
Assistant
Let me check a few more diffs to understand the pattern of changes in the TS detector files and the treesitter files.
Assistant
Let me also count the total lines of code in these new files and check the import chain depth.
Assistant
Now let me check some additional usage patterns and the actual original locations where these new modules' content lived before.
Assistant
Now let me look at a few of the modified test files to see if changes are just import path updates.
Assistant
Interesting. The files mostly grew rather than being decomposed. Let me check for cross-package imports and what was actually extracted vs just moved.
Assistant
Let me check where the original types lived before contracts.py was created, and examine the _coerce_value refactoring more closely.
Assistant
Let me also check what the core/discovery/, core/pathing/, and core/io/__init__.py files look like, and check the original modules these new api files are wrapping.
Assistant
batch_scoring.py is identical. Now let me check the others.
Assistant
Now let me check one more thing -- how many callers still use the old import paths vs. the new ones.
Assistant
Now let me check the generic.py diff continuation and the registry_state.py changes for the context-switching logic.
Assistant
Now let me look at the compat module to understand the utils.py refactoring more completely, and check a couple more modified test files.
Assistant
Let me also check the contract_validation module that's being imported in generic.py and look at what happened to the existing TS fixer files.
Assistant
Let me count the total file and line overhead introduced by the entire compat layer and all its intermediaries.
Assistant
Let me check one more modified test file and the existing test_direct_coverage_modules.py diff to see what changed there.
Assistant
Now let me count the import-path-only changes versus substantive changes across the TS detector files.
Assistant
Now let me check cross-directory imports and understand the new runtime/ init's lazy-loading mechanism, and what external.py imports.
Assistant
Now let me count the different categories of test quality to get a complete picture.
Assistant
Now let me check the contract_validation.py file to see how substantive it is.
Assistant
Now let me check whether scan_reporting_subjective.py was deleted and its content moved to subjective_reporting.py.
Assistant
Now let me check the runner_helpers diff and look at new code in it.
Assistant
Let me now look at the updated __init__.py for the review module and check for the external.py import path.
Assistant
Now let me check the _smell_effects.py file to see where the functions moved from smells.py.
Assistant
Now let me check for circular imports and understand how existing files (entrypoint.py, batch.py, batches.py, etc.) reference the moved modules.
Assistant
Now I have enough data for a thorough assessment. Let me also quickly check what react.py got -- it had the largest diff.
Assistant
Let me also look at what the entrypoint/batch files import to understand the full dependency graph.
Assistant
Let me check the runtime/init.py cross-dependency - it imports from orchestration.
Assistant
There it is -- runtime/policy.py imports from orchestration/runtime_defaults.py. Let me summarize the full file inventory.
Assistant
I now have a comprehensive picture. Here is my analysis.
Critical Analysis of the desloppify/core/ Refactoring
Summary of What Was Done
The refactoring introduced 19 new files (800 lines total) that wrap 5 existing implementation files (664 lines total). The core structural change is:
Three new sub-packages (discovery/, io/, pathing/) each with a cookie-cutter __init__.py + api.py + impl.py structure
Four new standalone shim modules (coercions_api.py, text_api.py, exception_sets.py, score_targets.py)
One genuine new feature module (nonfatal.py -- 74 lines)
One utility class (_internal/path_proxy.py -- DynamicPathProxy)
A compat/ package with facades for the old top-level imports (utils.py, file_discovery.py, scoring.py)
The three existing *_api.py files (discovery_api.py, paths_api.py, output_api.py) converted to deprecation-warning shims that forward to the new sub-packages
Verdict: This is Mostly Harmful Indirection
1. The discovery/, io/, pathing/ Sub-Packages Are Pure Forwarding Layers
Every one of these follows the same pattern:
__init__.py: 9 lines, imports api and impl, exports them. Contains a sentinel variable _DISCOVERY_NAMESPACE_SHIM that nothing uses.
api.py: Imports every function from the real implementation module and re-exports it by calling through. Zero logic added.
impl.py: from desloppify.core.{real_module} import * -- a star-import shim. Zero logic added.
Take core/discovery/api.py (88 lines). It imports source_discovery and then writes out 14 wrapper functions like:
/Users/user_c042661f/Documents/desloppify/desloppify/compat/file_discovery.py -- 51 lines (pure re-exports from core.discovery.api and core.pathing.api)
/Users/user_c042661f/Documents/desloppify/desloppify/compat/scoring.py -- 84 lines (pure re-exports from engine._scoring.*)
/Users/user_c042661f/Documents/desloppify/desloppify/compat/utils.py -- 134 lines (re-exports from core.io.api, core.pathing.api, core.discovery.api, core.skill_docs, core.tooling, plus 2 thin wrappers)
What it does: The compat layer sits between the old top-level modules (desloppify/file_discovery.py, desloppify/utils.py, desloppify/scoring.py) and new sub-packages (core/discovery/, core/pathing/, core/io/). The import chain is now:
That is four layers of re-export before you reach the implementation. Meanwhile, core/discovery/impl.py (10 lines), core/pathing/impl.py (14 lines), and core/io/impl.py (10 lines) are nothing but from desloppify.core.source_discovery import * style star-imports. They exist purely to mirror an api/impl structural pattern that adds zero semantic value.
Actual caller count for the old import paths: Only 8 total imports across 2 files use or directly (mostly tests). Only 6 files use . The compat layer protects almost nobody.
Assistant
Now I have a thorough picture. Here is my analysis.
Critical Analysis: Test and Utility Changes
1. The New Test Files: A Spectrum from Padding to Genuine
The 9 new test files (1,107 lines total) fall into three distinct tiers of quality:
Tier A: Genuine behavioral tests (good)
These files test real logic with meaningful inputs and validate specific behavioral contracts:
test_review_merge.py (126 lines, 7 assertions, 0 callable-checks): The best of the bunch. It constructs realistic finding dicts and validates the _same_issue_concept merge logic across 5 scenarios: identifier matching, root-cause-cluster matching, strict-mode rejection, related-file-overlap requirements, and transitive chain collapse in _build_merge_groups. Every assertion tests an actual algorithmic decision.
test_runtime_policy_direct.py (63 lines, 21 assertions, 0 callable-checks): Legitimately validates resolve_batch_run_policy -- providing CLI args and verifying the policy object has correct values. The second test validates fallback/clamping behavior for invalid inputs. These are real unit tests for real logic.
test_review_batch_core.py (32 lines, 7 assertions, 0 callable-checks): Tests extract_json_payload with a multi-candidate raw string, verifying it picks the richer JSON candidate. Tests the failure path too. Small but genuine.
test_review_batches_nonfatal.py (19 lines, 5 assertions, 0 callable-checks): Tests that _scored_dimensions_for_lang degrades gracefully when a dependency throws, capturing a structured warning. Tests a real error-handling contract.
test_direct_coverage_helpers.py (127 lines, 21 assertions, only 2 callable-checks): Mostly genuine. Tests resolve_matching_findings with actual state dicts and status filters; tests agent_env_mod.is_agent_environment() and detect_agent_interface() with monkeypatched env vars; tests _resolve_all_patterns for finding resolution; tests attestation validation with keyword matching. Only the final 2-line test is a callable smoke check.
Tier B: API surface / compat-layer tests (defensible but shallow)
test_api_surfaces_direct.py (108 lines, 20 assertions, 0 callable-checks): A mix. The DynamicPathProxy test is genuinely behavioral (validates lazy resolution on each access). The creates temp files and validates actual file discovery. The validates that deprecation warnings fire on legacy wrappers. These are legitimate -- they guard the new / / facades introduced by the refactoring.
Assistant
Here is my assessment.
Critical Analysis of the review/ Module Refactoring
Summary
This refactoring takes 8 flat files from desloppify/app/commands/review/ and redistributes them into 6 new sub-packages. The result is mostly a directory reorganization with minimal structural improvement. The code was not genuinely decomposed -- it was shuffled into subdirectories, often byte-for-byte identical or even larger than the originals, with the subdirectory names providing a veneer of "separation of concerns" that doesn't reflect actual decoupling.
The Mapping: What Went Where
Deleted file
New location
Change?
batch_scoring.py (176 lines)
payload/batch_scoring.py (176 lines)
Identical -- zero changes
helpers.py (11 lines)
orchestration/helpers.py (11 lines)
Identical -- zero changes
batch_prompt_template.py (402 lines)
payload/batch_prompt_template.py (414 lines)
Minor refactoring of one rendering function
assessment_integrity.py (57 lines)
quality/assessment_integrity.py (77 lines)
Signature change to bind_scorecard_subjective_at_target
runtime.py (69 lines)
runtime/setup.py (68 lines)
Moved deferred imports to module-level
import_helpers.py (981 lines)
importing/import_helpers.py (1301 lines)
Grew by 320 lines -- new features added
batch_core.py (757 lines)
normalization/batch_core.py (887 lines)
Grew by 130 lines -- extracted helper functions
runner_helpers.py (1487 lines)
runtime/runner_helpers.py (1640 lines)
Grew by 153 lines -- new dataclasses/helpers
Total before: ~3,940 lines across 8 files.
Total after: ~4,771 lines across 8 core files + 7 new tiny files (constants, __init__.pys).
The code grew by ~830 lines. None of the big files shrank. No file was split into smaller, more cohesive pieces.
Assistant
I now have a thorough picture of the changes. Here is my critical analysis.
Critical Analysis: Language Framework and TypeScript Plugin Refactoring
1. _framework/base/contracts.py -- Dataclass Relocation, Not an Interface Definition
This is a verbatim copy of the four dataclasses (FunctionInfo, ClassInfo, ComplexitySignal, GodRule) from engine/detectors/base.py. The original file was gutted and turned into a re-export shim:
Verdict: Despite the name "contracts," this file contains zero protocols, zero ABCs, and zero interface definitions. It is four plain dataclasses that previously lived in engine/detectors/base.py. The word "contracts" here is misleading -- it's just "types that got moved to a different module." The docstrings are slightly trimmed (less detail on GodRule and ComplexitySignal) compared to the originals, which is a minor documentation regression.
The move is debatable on its merits. These dataclasses are consumed by both the engine detectors and the language framework, so there's a layering argument for putting them at the framework level rather than in engine/detectors/. But the name contracts.py overpromises.
TreeSitterLangSpec was moved from treesitter/__init__.py into a separate contracts.py. Again, it's a single frozen dataclass, not a protocol or interface. The __init__.py now imports it from the submodule.
Verdict: Same pattern. A dataclass that previously lived at the top of its package was moved to a separate file called "contracts." The original __init__.py was ~100 lines and the dataclass was ~30 of those, so this is a small file split. Not harmful, but calling it is grandiose for what it is.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 1: "Architecture & Coupling"
Dimensions to assess: cross_module_architecture, high_level_elegance
Seed files to start from (read ALL of these):
desloppify/core/pathing/api.py, desloppify/core/io/api.py, desloppify/state.py, desloppify/core/discovery/api.py, desloppify/languages/_framework/base/types.py, desloppify/init.py, desloppify/core/fallbacks.py, desloppify/engine/policy/zones.py, desloppify/languages/_framework/treesitter/init.py, desloppify/languages/init.py, desloppify/app/commands/helpers/state_access.py, desloppify/app/commands/next_parts/render.py, desloppify/app/commands/plan/_resolve.py, desloppify/app/commands/resolve/render.py, desloppify/app/commands/review/merge.py, desloppify/app/commands/review/preflight.py, desloppify/app/commands/scan/scan_reporting_text.py, desloppify/app/commands/show/render.py, desloppify/app/commands/status_parts/render.py, desloppify/app/commands/update_skill.py, desloppify/app/output/scorecard_parts/meta.py
Focus: god modules, import-time side effects, boundary violations, deferred import pressure
RULES:
Only emit findings you are confident about. When unsure, skip.
Every finding MUST include at least one related_file as evidence.
Every finding MUST include a concrete, actionable suggestion.
Be specific with examples and line numbers.
FINDINGS MUST BE DEFECTS ONLY — never positive observations.
Score from evidence, not from a target.
Also explore beyond seed files as needed to follow dependency chains.
After reading the files, output your results as a JSON object (no markdown fences) with this structure:
{
"assessments": {
"cross_module_architecture": <0-100>,
"high_level_elegance": <0-100>
},
"findings": [
{
"dimension": "<dimension_key>",
"identifier": "<short_snake_case_id>",
"summary": "<1-2 sentence description of the defect>",
"related_files": ["file1.py", "file2.py"],
"evidence": "",
"suggestion": "",
"confidence": "high|medium|low"
}
]
}
Be thorough but honest. If something is genuinely good, give it a high score. If it's bad, say why specifically.
Assistant
I'll start by reading the blind review packet and all the seed files to understand the codebase structure and review criteria.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 3: "Abstractions & Dependencies"
Dimensions to assess: abstraction_fitness, dependency_health, mid_level_elegance, low_level_elegance
Seed files to start from (read the most important ones — focus on the abstraction/wrapper/facade files):
desloppify/compat/utils.py, desloppify/utils.py, desloppify/compat/file_discovery.py, desloppify/compat/scoring.py, desloppify/core/coercions_api.py, desloppify/core/discovery/init.py, desloppify/core/discovery_api.py, desloppify/core/io/init.py, desloppify/core/pathing/init.py, desloppify/core/source_discovery.py, desloppify/core/_internal/path_proxy.py, desloppify/core/registry.py, desloppify/engine/_work_queue/helpers.py, desloppify/intelligence/review/_prepare/helpers.py, desloppify/intelligence/review/_context/models.py, desloppify/app/commands/helpers/state_access.py, desloppify/app/commands/review/orchestration/helpers.py, desloppify/app/commands/review/normalization/batch_core.py, desloppify/app/commands/review/runtime/runner_helpers.py, desloppify/languages/_framework/runtime.py, desloppify/languages/_framework/generic.py, desloppify/engine/detectors/base.py, desloppify/app/commands/fix/init.py, desloppify/app/commands/plan/init.py, desloppify/app/commands/resolve/init.py, desloppify/app/commands/show/init.py
Focus: abstraction hotspots — wrappers, facades, multi-hop delegation chains, TypedDict violations, param bags, unnecessary indirection layers. Look especially at the compat/ layer, the core/discovery|io|pathing sub-packages, and state_access.py.
RULES:
Only emit findings you are confident about.
Every finding MUST include related_files and concrete evidence.
FINDINGS MUST BE DEFECTS ONLY.
Score from evidence, not from a target.
Be blunt — if abstractions don't earn their existence, say so.
The review packet is too large. Let me read it in chunks and the seed files separately.
Assistant
I'll start by reading the blind review packet to understand the system prompt and dimension definitions, then systematically read the seed files to assess the four dimensions.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 5: "Package Organization"
Dimensions to assess: package_organization, high_level_elegance
Also explore: desloppify/app/commands/review/ (all subdirectories), desloppify/core/discovery/, desloppify/core/io/, desloppify/core/pathing/, desloppify/compat/
Focus: file placement, directory boundaries, architectural layering. Do the directory structures make sense? Are packages justified or over-structured? Are files in the right place?
RULES:
Only emit findings you are confident about.
Every finding MUST include related_files and concrete evidence.
FINDINGS MUST BE DEFECTS ONLY.
Score from evidence, not from a target.
Output as JSON (no markdown fences):
{
"assessments": {
"package_organization": <0-100>,
"high_level_elegance": <0-100>
},
"findings": [...]
}
The review packet is too large. Let me read it in sections and start reading the seed files.
Assistant
I'll start by reading the blind review packet, then systematically examine all the seed files and exploration targets.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 6: "State & Design Integrity"
Dimensions to assess: initialization_coupling, design_coherence
I'll start by reading the blind review packet and the seed files to understand the system and assess the dimensions.
Assistant
Now let me read the remaining seed files.
Assistant
The file is too large, let me read it in parts.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 2: "Conventions & Errors"
Dimensions to assess: convention_outlier, error_consistency, mid_level_elegance
The seed files are mostly init.py files across the codebase. Focus on:
Convention drift: inconsistent naming, file organization, style islands across packages
Error handling: mixed strategies (throw vs return None vs error codes), inconsistent exception handling
Mid-level elegance: quality of handoffs and integration seams across modules
Read a representative sample of init.py files across the codebase to understand patterns:
desloppify/app/commands/review/init.py and its sub-packages (importing/, normalization/, orchestration/, payload/, quality/, runtime/)
desloppify/core/_internal/init.py
desloppify/engine/ init.py files
desloppify/languages/_framework/ init.py files
Also read some production modules to assess error handling patterns:
desloppify/engine/detectors/complexity.py
desloppify/engine/detectors/coupling.py
desloppify/app/output/visualize.py
desloppify/engine/planning/core.py
RULES:
Only emit findings you are confident about.
Every finding MUST include related_files and concrete evidence.
FINDINGS MUST BE DEFECTS ONLY.
Score from evidence, not from a target.
Output as JSON (no markdown fences):
{
"assessments": {
"convention_outlier": <0-100>,
"error_consistency": <0-100>,
"mid_level_elegance": <0-100>
},
"findings": [...]
}
Now let me read the seed files and exploration targets. I'll do this in parallel.
Assistant
I'll start by reading the review packet to understand the full system prompt and dimension definitions, then read the specified files.
Assistant
Now let me read the remaining seed files and start exploring the dependency chains more deeply.
Assistant
The review packet is too large. Let me read it in chunks and the other files.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 4: "AI Debt & Migrations"
Dimensions to assess: ai_generated_debt, incomplete_migration, low_level_elegance
Now let me check for the scan_reporting_text.py file and explore key dependency patterns.
Assistant
Now let me read the key seed files for the dimensions I need to assess. Let me read them in parallel.
Assistant
I'll start by reading the blind review packet to understand the dimension definitions and review system, then systematically examine the codebase.
Assistant
Now let me explore the review subdirectories, core/discovery/, core/io/, core/pathing/, and compat/.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 7: "Governance & Contracts"
Dimensions to assess: cross_module_architecture, high_level_elegance, test_strategy, package_organization
Now let me explore the facade layers more deeply, look for god modules, and check how many callers still use the old paths vs. new API surfaces.
Assistant
Now let me read more key files, particularly the core/io/api.py, core/pathing/api.py, and core/discovery/api.py to understand the full delegation chains.
Assistant
Now let me read the remaining seed files.
Assistant
I'll start by reading the blind review packet and then systematically examine the seed files and related code to assess the four dimensions.
Assistant
Now let me read the actual source files I need to assess. Let me start with the __init__.py files and production modules.
Assistant
Now let me read the seed files and explore the areas of interest.
Assistant
Now let me read the key files in these directories to understand the organization.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 9: "Cross-cutting Sweep"
Dimensions to assess: naming_quality, logic_clarity, type_safety, contract_coherence, api_surface_coherence, authorization_consistency
Read a representative cross-section of the codebase. Start with these key modules:
The review packet is too large. Let me read it in chunks and the seed files separately.
Assistant
Now let me read the remaining seed files.
Assistant
I'll start by reading the blind review packet and then systematically examine the specified files.
Assistant
Now let me read the review sub-package __init__.py files and the production modules for error handling assessment.
Assistant
Now let me check the state.py facade import patterns and look for god modules.
Assistant
Now let me check what imports from the compat layer vs direct imports to assess whether the compat shims have active callers.
Assistant
Now let me read the compat directory and the review subdirectories.
Assistant
Now let me explore the compat/ directory and *_api.py files for migration patterns and deprecated shims.
User
You are a blind code quality reviewer. Read the blind packet at /Users/user_c042661f/Documents/desloppify/.desloppify/review_packet_blind.json to understand the full review system prompt and dimension definitions.
You are responsible for BATCH 8: "Design coherence — Mechanical Concern Signals"
Dimensions to assess: design_coherence, initialization_coupling
This batch focuses on files where mechanical detectors identified structural patterns needing human judgment. Concern types: design_concern, duplication_design, mixed_responsibilities, systemic_pattern, systemic_smell.
Read a representative sample of these high-signal files:
Now let me read the review sub-package init.py files.
Assistant
Let me now check for the key concerns: import-time side effects, boundary violations, and understand the compat layer.
Assistant
I'll start by reading the blind review packet to understand the full system prompt and dimension definitions, then read all the specified files.
Assistant
Now let me read the rest of the review packet and explore the test files and other relevant code.
Assistant
Now let me read the core files specified in the task.
Assistant
Now let me look at some key areas to understand the import chains more deeply, particularly the compat layer calling patterns and the file_discovery.py root shim.
Assistant
The packet is too large. Let me read it in chunks.
Assistant
Now let me examine the test files and other key structural files in depth.
Assistant
Now let me examine more __init__.py files and also look at the core/_internal/ and engine sub-packages for convention patterns.
Assistant
Now let me look for the missing seed file and some additional context about mutable global state and initialization patterns.
Assistant
Now let me check the number of callers of from desloppify.file_discovery import and from desloppify.scoring import (the root-level shims), and also check for the compat/__init__.py.
Assistant
Now let me check the import-time side effects pattern and look at how utils.py works.
Assistant
Now let me check who is still importing from the old/deprecated paths vs the new ones.
Assistant
Now let me check what imports the review subdirectory files and understand if any of these packages are under-justified. Let me also look at the original locations of moved files to confirm the migration pattern.
Assistant
Now let me examine architecture boundaries, the compat layer, cross-module imports, and test coverage patterns more deeply.
Assistant
Now let me look at the compat/ directory structure and the core/io/impl.py to understand if there's an impl module or just the api.
Assistant
Now let me read the actual source files I need to review.
Assistant
Now let me check who actually imports from these shim packages, to understand if the compat layer is actually used or dead weight.
Assistant
Now let me examine some detector files for naming/logic patterns.
Assistant
Now let me look at specific initialization coupling patterns -- the PROJECT_ROOT module-level variable usage and the mutable global state patterns more closely.
Assistant
Now let me check for import-time side effects more specifically and look for the _DEFAULT_PROJECT_ROOT initialization pattern.
Assistant
Now let me look at the engine/planning/core.py and more error handling patterns across the codebase.
Assistant
Now let me check if there are callers still using the compat layer, and examine the core package organization more deeply.
Assistant
Now let me check whether anything actually imports from the impl modules.
Assistant
Now let me read the remaining files.
Assistant
Now let me examine a few more files to round out my cross-section, focusing on areas that might reveal type safety and contract issues.
Assistant
Now let me check who imports from the root-level shims (file_discovery.py, scoring.py, utils.py) to understand how many callers still rely on the legacy imports.
Assistant
Now let me look at more init.py files to understand convention patterns better, plus some more error handling in detector files.
Assistant
The impl modules have zero callers. Let me check the core/output_api.py to see if there's another layer.
Assistant
Let me now look at more files that will reveal cross-cutting patterns for my remaining dimensions.
Assistant
Good - so desloppify.scoring is widely imported (30+ callers) and is a compat shim. Let me now look at the new API files and the io/api.py pass-through pattern.
Assistant
Now let me look at the state_access.py pattern more deeply -- it's a pure pass-through, and check how the command layer accesses engine internals.
Assistant
Now let me read the remaining files.
Assistant
Now let me check who imports from the core/io/api.py, core/discovery/api.py, and core/pathing/api.py to understand if the API shim layer is genuinely needed vs. being pass-through.
Assistant
Now let me look at the root-level shim files to understand the full migration picture.
Assistant
Let me check callers of the deprecated output_api and paths_api modules, and the runtime.py LangRun property boilerplate.
Assistant
Now let me check who imports from these legacy root modules and what the test coverage situation looks like for critical paths.
Assistant
Let me also check for auth patterns and look at a couple more files for the cross-cutting review.
Assistant
Good - the app layer doesn't directly import from engine._* - it goes through facades. Let me now check for hub modules and look at the scoring.py import fan-out.
Assistant
Now let me look at more language plugin init.py files to assess convention consistency across sibling plugins.
Assistant
Now let me check for imports to the old root-level files from actual non-test production code.
Assistant
Let me check how many callers desloppify.state (the root-level facade) has and look at its full content.
Assistant
Let me check the scan_reporting_text.py seed file now.
Assistant
Now let me look at a few more files to check for additional naming/type safety patterns across the codebase.
Assistant
Interesting - production code is still importing from desloppify.scoring (the legacy shim). Let me check the exact nature of these imports to understand the dependency pattern.
Assistant
Now let me check the core/io/api.py and core/discovery/api.py to understand the pass-through pattern more deeply -- are these truly just 1-to-1 forwarding functions with no added logic?
Assistant
Now let me read the runner_helpers.py file more carefully (it was truncated).
Assistant
Now let me look at a few more things to check the depth of delegation chains and dependency health.
Assistant
Now let me look at a few more important areas -- how the core/io, core/pathing, core/discovery packages are structured, and check for the layer violation dimension specifically.
Assistant
Now let me look at the core/pathing/api.py to understand the "canonical" layer, and explore some larger modules for AI-generated code patterns.
Assistant
Let me look at more generic-style language plugins and also at the _NAMESPACE_SHIM pattern and some error handling in more modules.
Assistant
Now let me look at the resolve_findings function more closely for a potential contract issue I noticed, and check a few more specific patterns.
Assistant
Now let me look at the testing structure more carefully to assess test_strategy. Let me check for key untested critical paths.
Assistant
Now let me look at the review subdirectory with only 1 file each, check the orchestration package more deeply, and understand how many of these single-file packages are truly justified.
Assistant
Let me check for requirements.txt or pyproject.toml for dependency health assessment.
Assistant
I have now read sufficient code across all the specified files. Let me also quickly check for initialization coupling patterns -- global mutable state at module scope.
Assistant
Now let me look at error handling patterns more deeply. Let me check how errors are handled across various modules.
Assistant
Now let me check some important boundary violations -- does app directly import from engine._state or engine._scoring or engine._plan?
Assistant
Now let me investigate the test patterns more deeply - checking for import-only smoke tests vs real behavioral testing, and looking for critical untested modules.
Assistant
Now let me look for AI-generated code patterns: restating comments, defensive overengineering, boilerplate. Let me check some larger modules.
Assistant
Now let me check a few more things. Let me look at the SectionPayload dataclass (which implements MutableMapping) to understand if it earns its existence, and check the DynamicPathProxy.
Assistant
Let me look at more error handling patterns to compare across the codebase — particularly checking for bare except: or inconsistent strategies.
Assistant
Now let me look at some additional files for the PROJECT_ROOT module-level mutable override pattern.
Assistant
Now let me check the describe_finding and annotate_finding pattern to confirm the duplication I noticed.
Assistant
Good -- the app layer does respect the engine._* privacy boundary. Let me check the intelligence layer.
Assistant
Now let me look at other important things - the engine package structure, the _internal layer, and how boundary contracts are (or aren't) enforced.
Assistant
Let me check how build_batch_prompt is used -- it just delegates to render_batch_prompt.
Assistant
Let me look more carefully at the resolve_findings function to verify the contract issue I noticed.
Assistant
Now let me check what imports from the normalization package using relative imports.
Assistant
Let me also quickly check some things about the LangRun proxied properties and _config_attr_property usage to verify how many there are.
Assistant
Let me look at the _internal boundary violations to see if engine modules are reaching into core._internal.
Assistant
Now let me check the _resolve_skip_item_options logic for the redundant isinstance checks I noticed.
Assistant
Now let me check how deeply the show_agent_plan duplication exists between status and show renderers.
Assistant
Let me now look at the engine/planning/__init__.py more carefully -- it has a very different pattern (pass-through wrappers with *args, **kwargs) compared to other init files.
Assistant
I now have a thorough picture. Let me also look at the _resolve_generic_lang_options in generic.py for a similar redundancy pattern.
Assistant
Let me check the scan package structure for scan_skill_sync.py.
Assistant
Let me check these more carefully for duplication.
Assistant
Now let me check for patterns around parallel PROJECT_ROOT: Path | None = None overrides in multiple modules.
Assistant
There are engine modules (engine/_plan/persistence.py, engine/_state/schema.py) reaching into core._internal to import DynamicPathProxy. This is a boundary violation since _internal is supposed to be private to core. Let me verify this more carefully.
Assistant
Now let me check who actually imports from these impl shims.
Assistant
Now I have enough data for a thorough assessment. Let me trace the delegation chains one more time before writing my findings. The key chains I need to document:
io/output chain: core.io.api -> core.output (1-hop wrapper, no added value)
pathing chain: core.pathing.api -> core.file_paths (1-hop wrapper, no added value)
discovery chain: core.discovery.api -> core.source_discovery (1-hop wrapper, no added value)
Let me verify one more: how many callers the core/io/__init__.py's from . import api, impl pattern has.
Assistant
I can see there's a real defect here. Let me verify this more carefully.
When status == "open" (reopening a finding), the code:
Sets extra_updates["resolved_at"] = None (correct for reopen)
But the base updates dict on line 145 sets "resolved_at": now
Then updates.update(extra_updates) overwrites with None (correct for the "open" case)
But for the non-wontfix, non-open case (e.g., status == "fixed" or status == "false_positive"), the code sets resolved_at: now in the base updates, which is correct.
Now let me check for the "note" behavior: When status == "open", extra_updates["note"] = next_note, but the base updates["note"] = note. The update() call means extra_updates wins. But when note is None and previous_note exists, next_note = previous_note, so the old note is preserved. This seems intentional.
Let me check on more cross-cutting patterns.
Assistant
Now let me look at the root-level structure of the desloppify package to understand overall organization.
Assistant
Clear duplication confirmed. Now let me look at the _coerce_assessment_score duplication between preflight.py and state_access.py.
Assistant
Let me check how these PROJECT_ROOT overrides are used in the context of the react.py detector.
Assistant
Let me now examine a few more areas for convention patterns and the _NAMESPACE_SHIM usage.
Assistant
Now let me look at the package structure for the core package to understand how many root-level files remain alongside the new structured packages.
Assistant
Now let me check for the detect_boolean_state_explosion function which directly accesses PROJECT_ROOT without using the _resolve_source_path helper.
Assistant
Let me verify the coercions_api.py chain by looking at core/_internal/coercions.py.
Assistant
Now let me look for AI-generated code patterns in some of the larger modules. Let me check for restating-comment patterns and defensive overengineering.
Assistant
Now let me look at some additional files to understand patterns. I want to check the output_api.py and paths_api.py in core -- are these also shims?
Assistant
Let me look at a few of these __getattr__ init files for consistency comparison.
Assistant
Now let me check the _collect_dimension_rows return type -- it returns a 6-tuple but is typed with all 6 elements.
Assistant
Now let me look at the _coerce_assessment_score in preflight.py more closely to confirm the duplication.
Assistant
Now let me check the _apply_registration_bundle pattern -- side effects during module construction.
Assistant
The state_access.py file is a classic pass-through shim. Let me check how many callers it has and verify these are truly just forwarding with no added logic.
Assistant
Let me check how many callers use the deprecated shims output_api.py, paths_api.py, and discovery_api.py.
Assistant
Now let me look at the lazy_exports helper and the typescript fixers init.
Assistant
Now let me check the import-time side effect in text_utils.py more carefully and the globals() pattern in treesitter __init__.py.
Assistant
Now let me look at the _state_lang_capabilities function more carefully -- it writes a key lang_capabilities into StateModel that is not declared in the TypedDict.
Assistant
Now let me check who imports from discovery_api.py.
Assistant
Now let me check if there's a test that verifies _internal isn't imported from outside core:
Assistant
Now let me look at the scoring facade chain - scoring.py -> compat/scoring.py -> actual engine.
Assistant
Now let me look at error handling across a few more important production modules to get a complete picture.
Assistant
Now I have enough information to complete my assessment. Let me check one more pattern - how detect_boolean_state_explosion handles the PROJECT_ROOT variable when it's None.
Assistant
Confirmed: lang_capabilities is used in 9 files but is not declared in the StateModel TypedDict. Let me check for similar undeclared fields.
Assistant
Now let me check how many layers of indirection there are in the facade stack. Check if any core modules import from app.
Assistant
Now let me check how the core._internal.path_proxy fits in and understand the _internal directory.
Assistant
Let me check the core/io/api.py vs core/output.py relationship and look at the impl.py files in the new structured packages.
Assistant
Now let me look at how errors are handled in the scan workflow and state persistence to check for consistency.
Assistant
Now let me look at a broader set of modules for AI-generated code patterns - check some larger files for restating comments.
Assistant
This is a real bug. When PROJECT_ROOT is None (its default), the expression PROJECT_ROOT / filepath on line 384 will raise TypeError: unsupported operand type(s) for /: 'NoneType' and 'str'. This contrasts with _resolve_source_path (line 25-34) which properly handles the None case by falling back to get_project_root().
Now let me check the smells.py file for a similar pattern:
Assistant
Now let me understand the utils.py shim at the root level.
Assistant
Now let me check which of these keys are actually defined in StateModel:
Assistant
Now let me look at how tests are organized and check for more behavioral test files vs. the smoke/callable tests.
Assistant
Now let me verify the depth of the shim chain. utils.py -> compat/utils.py -> core/io/api.py -> core/output.py. Let me trace one specific call.
Assistant
Let me also look at the _RECOVERABLE_LANG_RESOLUTION_ERRORS pattern elsewhere to check for consistency.
Assistant
Let me now look at some more files for AI-generated patterns - particularly the new *_api.py "canonical" surfaces that are pure pass-through wrappers.
Assistant
Now let me check what PROJECT_ROOT is in smells.py and unused.py -- the imports show they use the API module's PROJECT_ROOT, which is the DynamicPathProxy, not None:
Assistant
So lang_capabilities, zone_distribution, reminder_history, scan_path, and review_cache are all used in state but not declared in StateModel. Let me verify scan_path:
Assistant
Let me also check for boundary enforcement tests and look at how many production callers still use desloppify.scoring (the legacy root shim) instead of the canonical engine path.
Assistant
This is an important finding - the engine layer imports from the app layer, which is a clear upward dependency violation.
Let me now check the review packet dimension definitions more thoroughly.
Assistant
Now let me check how many distinct error exception tuples are defined across the codebase.
Assistant
Now let me check the core/io/api.py layer. It forwards every function 1-to-1 to core/output.py. Let me confirm it adds zero logic.
The core/io/api.py file has every function as a pure pass-through: def colorize(text, color): return output_mod.colorize(text, color). No added logic, no type narrowing, no error handling.
Let me now check who imports from core/output.py directly (the implementation) vs. through the API.
Assistant
Now I have a thorough understanding of the codebase structure. Let me check a few more specific patterns before formulating my assessment.
Assistant
Good -- those import PROJECT_ROOT from core.pathing.api (which is the DynamicPathProxy), whereas react.py defines its own PROJECT_ROOT: Path | None = None locally as a "backward-compatible test override hook." That's the inconsistency. The detect_boolean_state_explosion function in react.py uses the local PROJECT_ROOT (which is None by default) without the _resolve_source_path helper, leading to a potential TypeError.
Let me verify the detect_context_nesting function uses _resolve_source_path properly:
Assistant
Let me examine the engine/planning/__init__.py more closely and also check whether core.py is really a pure re-export of the same things.
Assistant
This is a significant type safety issue -- scan_path is accessed via .get() across 18 files but is not part of the StateModel TypedDict. Let me verify how widely zone_distribution and reminder_history are used:
Assistant
Good -- no direct imports from _internal.text_utils. Let me check how the core/text_api.py is structured.
Assistant
Let me now explore the multi-layered indirection more carefully. I want to trace the full chain for io/api.py:
Assistant
So within react.py, there are two path resolution approaches:
_resolve_source_path() (used in detect_state_sync, detect_context_nesting, detect_hook_return_bloat) -- properly handles PROJECT_ROOT is None
Direct PROJECT_ROOT / filepath (used in detect_boolean_state_explosion) -- crashes when PROJECT_ROOT is None
Now let me check for any additional design coherence issues I can identify.
Assistant
Now let me check the gather_auth_context return type:
Assistant
Good. So only the API surface and impl shim use core/output directly. Let me also check core/source_discovery.py and core/file_paths.py.
Assistant
Now let me check who is reading read_code_snippet from core.pathing.api vs core.text_api, looking for scattered access points.
Assistant
Now let me look more broadly for AI-generated patterns - look at some of the newer files.
Assistant
This is significant. 20 production modules still import from desloppify.scoring (the legacy shim) while the actual code lives in desloppify.engine._scoring. Yet there's a compat import guard test but it only checks for utils and file_discovery, not scoring. Let me verify.
Assistant
Now let me look at the scan_workflow.py more to see the error handling patterns around plan sync.
Assistant
Now I have all the evidence I need. Let me compose the assessment.
{
"assessments": {
"design_coherence": 72,
"initialization_coupling": 82
},
"findings": [
{
"dimension": "design_coherence",
"identifier": "operations_describe_annotate_duplication",
"summary": "describe_finding and annotate_finding are structurally identical functions differing only in which key they set on the override dict ('description' vs 'note')",
"related_files": [
"desloppify/engine/_plan/operations.py"
],
"evidence": [
"Lines 320-330 (describe_finding) and 333-343 (annotate_finding) share identical 6-line bodies: ensure_plan_defaults, utc_now, get-or-create override, set one key, set updated_at",
"The only difference is the dictionary key written: 'description' vs 'note'"
],
"suggestion": "Extract a shared _set_override_field(plan, finding_id, field, value) helper. Both public functions become one-liners delegating to it.",
"confidence": "high"
},
{
"dimension": "design_coherence",
"identifier": "resolve_options_noop_isinstance_branches",
"summary": "_resolve_skip_item_options contains isinstance branches where both arms return the same value, making the conditionals dead logic",
"related_files": [
"desloppify/engine/_plan/operations.py"
],
"evidence": [
"Line 69: 'reason=values["reason"] if isinstance(values["reason"], str) else values["reason"]' -- both branches evaluate to values['reason']",
"Line 70: identical pattern for 'note'",
"Lines 71-74: identical pattern for 'attestation' -- 'values["attestation"] if isinstance(values["attestation"], str) else values["attestation"]'"
],
"suggestion": "Remove the no-op conditionals. Assign 'reason=values["reason"]' directly. If type narrowing was intended, add actual coercion logic (e.g. convert non-str to None).",
"confidence": "high"
},
{
"dimension": "design_coherence",
"identifier": "resolve_options_duplicated_pattern",
"summary": "_resolve_generic_lang_options duplicates the full GenericLangOptions construction twice with near-identical field-by-field logic for the 'options is not None' and legacy kwargs paths",
"related_files": [
"desloppify/languages/_framework/generic.py"
],
"evidence": [
"Lines 264-278: constructs GenericLangOptions from options.exclude, options.depth, etc. with list() wrapping",
"Lines 294-308: constructs GenericLangOptions from values['exclude'], values['depth'], etc. with identical list() wrapping",
"Both paths apply the exact same None-check-then-list() coercion for exclude, detect_markers, and zone_rules"
],
"suggestion": "When options is not None and no legacy kwargs exist, return the options object directly (it is already a GenericLangOptions). The defensive re-construction copies identical values from a frozen dataclass into a new frozen dataclass with no transformation.",
"confidence": "high"
},
{
"dimension": "design_coherence",
"identifier": "runner_helpers_mixed_responsibilities",
"summary": "runner_helpers.py is over 700 lines mixing subprocess management, thread orchestration, stall detection, blind packet sanitization, parallel execution, retry logic, and progress event dispatching in a single module",
"related_files": [
"desloppify/app/commands/review/runtime/runner_helpers.py"
],
"evidence": [
"Module defines 10+ dataclasses: CodexBatchRunnerDeps, FollowupScanDeps, BatchResult, BatchProgressEvent, BatchExecutionOptions, _ParallelExecutionContext, _RunnerState, _AttemptContext, _ExecutionResult, plus more",
"Responsibilities span: (1) codex CLI command building, (2) Popen-based process lifecycle, (3) stall detection heuristics, (4) live log streaming, (5) parallel thread pool orchestration, (6) retry/backoff, (7) blind packet preparation, (8) progress callback dispatch",
"Module imports threading, subprocess, concurrent.futures, time, json, hashlib, datetime -- each reflecting a distinct concern"
],
"suggestion": "Extract at least two focused modules: one for subprocess execution/stall detection (the _RunnerState/_AttemptContext/_run_via_popen/_run_via_subprocess cluster) and one for parallel batch orchestration (_ParallelExecutionContext and its workers).",
"confidence": "high"
},
{
"dimension": "design_coherence",
"identifier": "batch_core_parameter_proliferation",
"summary": "merge_batch_results and its internal accumulators pass abstraction_sub_axes and abstraction_component_names through 4 levels of functions as unrelated keyword parameters alongside the primary scoring data",
"related_files": [
"desloppify/app/commands/review/normalization/batch_core.py"
],
"evidence": [
"merge_batch_results (line 781) accepts abstraction_sub_axes and abstraction_component_names as top-level params",
"_accumulate_batch_scores (line 546) also receives abstraction_sub_axes as a param and threads it through",
"_compute_abstraction_components (line 750) receives both abstraction_sub_axes and abstraction_component_names",
"These abstraction-fitness-specific params are threaded through general-purpose scoring functions that otherwise have no awareness of abstraction_fitness as a special dimension"
],
"suggestion": "Group abstraction_sub_axes and abstraction_component_names into a small frozen dataclass (e.g. AbstractionConfig) and pass it as a single optional parameter, or move abstraction component computation into a post-processing step after the general merge.",
"confidence": "medium"
},
{
"dimension": "design_coherence",
"identifier": "ts_phases_repeated_finding_construction",
"summary": "TypeScript phases.py repeats an identical pattern of make_finding calls with manual dict construction for entries across 7+ detector results, each with slightly different field mappings but the same structural shape",
"related_files": [
"desloppify/languages/typescript/phases.py"
],
"evidence": [
"phase_logs (lines 67-79): iterates entries, builds make_finding with detail dict",
"phase_exports (lines 94-107): same pattern, different fields",
"phase_deprecated (lines 117-136): same pattern with conditional tier logic",
"phase_coupling (lines 302-317, 331-346): same make_finding loop twice more",
"phase_smells (lines 421-438, 447-458, 463-476, 483-498, 503-521): five more instances of the same loop-and-make_finding pattern",
"The shared framework already has _entries_to_findings in shared_phases.py (line 192) but TS phases does not use it, duplicating the normalization contract"
],
"suggestion": "Use or extend _entries_to_findings from shared_phases.py. Each detector result should define a mapping spec (detector name, default tier, confidence, summary template) rather than re-implementing the finding-construction loop in each phase.",
"confidence": "medium"
},
{
"dimension": "initialization_coupling",
"identifier": "batch_core_module_level_scorer_instance",
"summary": "_DIMENSION_SCORER = DimensionMergeScorer() is instantiated at module import time, creating a hidden dependency on DimensionMergeScorer's constructor being side-effect-free and stable across all import contexts",
"related_files": [
"desloppify/app/commands/review/normalization/batch_core.py",
"desloppify/app/commands/review/payload/batch_scoring.py"
],
"evidence": [
"Line 25: _DIMENSION_SCORER = DimensionMergeScorer() -- module-level instantiation",
"Used in _finding_pressure_by_dimension (line 540) and _compute_merged_assessments (line 742)",
"If DimensionMergeScorer evolves to carry configuration (weights, thresholds), this module-level singleton prevents per-invocation customization without patching global state"
],
"suggestion": "Accept a scorer parameter in merge_batch_results and use a default-factory pattern rather than a module-level singleton. Alternatively, since DimensionMergeScorer is stateless (frozen dataclass), document that contract explicitly so future maintainers know this is safe.",
"confidence": "low"
},
{
"dimension": "initialization_coupling",
"identifier": "schema_dynamic_path_proxy_at_module_scope",
"summary": "STATE_DIR and STATE_FILE in schema.py use DynamicPathProxy at module scope, creating lambda-captured dependencies on get_project_root() that resolve lazily at access time but bind at import time",
"related_files": [
"desloppify/engine/_state/schema.py"
],
"evidence": [
"Line 200: STATE_DIR = DynamicPathProxy(get_state_dir, label='STATE_DIR')",
"Line 201: STATE_FILE = DynamicPathProxy(get_state_file, label='STATE_FILE')",
"These are module-level constants that delegate to get_project_root() at access time. Any code that imports STATE_DIR/STATE_FILE gets a proxy object whose resolved value depends on runtime state of a different module (text_utils.PROJECT_ROOT)"
],
"suggestion": "The comment on line 199 notes these are legacy exports for import compatibility. Consider deprecating these proxy exports in favor of the function-based get_state_dir()/get_state_file() API, which makes the runtime dependency explicit at the call site.",
"confidence": "medium"
}
]
}
Assistant
Now let me check one more pattern -- the ensure_state_defaults function has an explicit return None annotation but is typed as -> None:
Assistant
Now let me look at the _internal/coercions.py to understand the coercions_api pattern.
Assistant
Now let me check the import in commands.py to see if it's importing from phases.py:
Assistant
Now let me look at how app/commands/scan/ imports align with review/ to see the convention comparisons. Also let me examine the engine/detectors/test_coverage/__init__.py and other detectors init files.
Assistant
Now let me look at the io/api.py pass-through more carefully and explore larger modules for AI-generated code signs.
Assistant
Now let me count the total number of read_code_snippet entry points. Let me also check how _coerce_assessment_score is used in preflight to confirm it's functionally identical to the canonical one.
Assistant
This has an explicit return None which is redundant but not a defect. Let me look for more substantive issues.
Assistant
Wait - commands.py imports TS_COMPLEXITY_SIGNALS, TS_GOD_RULES, TS_SKIP_DIRS, TS_SKIP_NAMES from phases.py, but phases.py itself imports those from phase_policies.py:
Assistant
Now I have a thorough understanding of the codebase. Let me do a final check on the structure.json data from the review packet, specifically looking at directory profiles and coupling matrix if available.
Assistant
Confirmed: the compat import guard test only covers desloppify.utils and desloppify.file_discovery, but not desloppify.scoring. Meanwhile 20 production files actively import from the scoring shim.
Now let me check the _framework/base/contracts.py file mentioned in the seed types.py.
Assistant
Now let me check the nonfatal.py module and the exception_sets.py to understand the error pattern infrastructure.
Assistant
Now let me check for the final pieces: any upward dependency from intelligence to app.
Assistant
Now let me check some naming patterns across the codebase -- I want to look for naming inconsistencies.
Assistant
Now let me check for the _COMPAT_ markers and actually understand the import migration layers properly. Let me also look at the typescript/syntax/ directory and the review subpackages.
Assistant
Let me now investigate the test_direct_coverage files more carefully to understand the proportion of "import-only" vs "behavioral" tests.
Assistant
This is very interesting. There are multiple overlapping exception tuple definitions. Let me check where PLAN_LOAD_EXCEPTIONS is used vs _PLAN_SYNC_EXCEPTIONS.
Assistant
Good. Now let me also look at the core/output.py which is a hub module and the core/file_paths.py which is another hub.
Assistant
Let me now look at the core directory profile more closely.
Assistant
Let me check some public API parameter count/consistency issues.
Assistant
Now I have enough information. Let me also check the core directory profile:
Assistant
Now let me check whether there is a test enforcing the _internal boundary:
Assistant
Now let me count how many things read_code_snippet is accessible through. It's defined once in _internal/text_utils.py, but reexported through: core/text_api.py, core/pathing/api.py, core/paths_api.py, compat/utils.py, and utils.py. That's 5 re-export paths for one function.
Let me check one more thing -- how much of the compat layer is actively used.
Assistant
Now I have a concrete finding: _SHOW_PLAN_LOAD_EXCEPTIONS in show/cmd.py is identical to PLAN_LOAD_EXCEPTIONS in core/exception_sets.py but duplicated locally instead of imported. Let me also check for other places with similar overlapping exception tuples.
Assistant
Let me check for mixed use of dict vs typed return/param patterns.
Assistant
Let me now look at the review subpackages to see if there are migration-related patterns.
Assistant
Let me continue reading to see the imports_from_dirs and imported_by_dirs:
Assistant
Good -- compat is only used by the top-level shims, not actively within the codebase. Now let me verify the globals() pattern for mutation.
Assistant
I now have a thorough understanding of the codebase structure. Let me compile my findings.
Assistant
Now let me look at the output_api.py which I saw earlier is also a facade.
Assistant
Now I have enough to understand the architecture deeply. Let me also look at a few more critical paths to check for test coverage.
Assistant
Now let me look at the _PLAN_SYNC_EXCEPTIONS vs PLAN_LOAD_EXCEPTIONS more carefully:
Let me check _RECOVERABLE_LANG_RESOLUTION_ERRORS too:
Assistant
Multiple functions in the scoring engine accept findings: dict with no type parameters at all. Let me check if there are typed versions elsewhere.
Assistant
Now let me also check the compat directory profile:
Assistant
Now let me check if there's an arch test for core._internal boundary enforcement:
Assistant
So we have:
_RECOVERABLE_LANG_RESOLUTION_ERRORS = (ImportError, ValueError, TypeError, AttributeError, OSError, RuntimeError) -- similar to PLAN_LOAD_EXCEPTIONS but with RuntimeError instead of KeyError
These are all overlapping exception tuple definitions with slightly different compositions. Let me now gather the final data I need.
Let me check the convention for how language plugin init files handle their LangConfig. Some use class-based, some use generic_lang.
Assistant
Now let me check which deleted files from the git status correspond to these new subpackages. The git status shows several deleted files under review/:
Assistant
Good -- output_api and paths_api have zero live callers. They're dead compatibility shims. Let me also now verify discovery_api.py.
Assistant
Now I have enough evidence to produce the assessment. Let me verify one more thing -- the review/orchestration package with just 2 small files.
Assistant
Now I have a thorough understanding of the codebase's abstraction layers. Let me compile my assessment.
{
"assessments": {
"abstraction_fitness": 42,
"dependency_health": 78,
"mid_level_elegance": 48,
"low_level_elegance": 62
},
"findings": [
{
"dimension": "abstraction_fitness",
"identifier": "io_api_pure_passthrough",
"summary": "core/io/api.py is a pure pass-through facade that forwards every function to core/output.py with identical signatures, adding no policy, validation, or translation.",
"related_files": ["desloppify/core/io/api.py", "desloppify/core/output.py"],
"evidence": "colorize() -> output_mod.colorize(text, color), log() -> output_mod.log(msg), print_table() -> output_mod.print_table(headers, rows, widths), display_entries() -> output_mod.display_entries(...all 8 kwargs forwarded identically). Constants also aliased: LOC_COMPACT_THRESHOLD = output_mod.LOC_COMPACT_THRESHOLD. Zero added behavior in the entire 64-line file. 90 files import from this facade.",
"suggestion": "Merge core/io/api.py into core/output.py (rename output.py to core/io/api.py if the namespace matters) and update imports. The facade adds one import hop to every call site with no benefit.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "discovery_api_pure_passthrough",
"summary": "core/discovery/api.py is a pure pass-through facade that forwards every function to core/source_discovery.py with identical signatures, adding no policy or translation.",
"related_files": ["desloppify/core/discovery/api.py", "desloppify/core/source_discovery.py"],
"evidence": "All 14 exports are trivial forwards: set_exclusions() -> source_discovery_mod.set_exclusions(patterns), enable_file_cache() -> source_discovery_mod.enable_file_cache(), find_source_files() coerces Iterable->list but source_discovery already accepts list. 48 importers pay for this indirection.",
"suggestion": "Rename source_discovery.py to discovery/api.py (or merge into it) and update imports. The intermediate module provides no abstraction boundary.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "pathing_api_pure_passthrough",
"summary": "core/pathing/api.py is a pure pass-through facade that forwards every function to core/file_paths.py with identical signatures, adding minimal policy only in read_code_snippet (default project_root).",
"related_files": ["desloppify/core/pathing/api.py", "desloppify/core/file_paths.py"],
"evidence": "matches_exclusion() -> file_paths_mod.matches_exclusion(rel_path, exclusion), rel() -> file_paths_mod.rel(path), safe_write_text() -> file_paths_mod.safe_write_text(filepath, content). Only read_code_snippet adds a project_root default. 126 importers pay for this indirection. Constants PROJECT_ROOT, DEFAULT_PATH, SRC_PATH are the only items that could not be simple re-exports.",
"suggestion": "Consolidate file_paths.py into pathing/api.py. The one piece of added logic (default project_root for read_code_snippet) does not justify a separate module.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "state_access_pure_passthrough",
"summary": "app/commands/helpers/state_access.py is a 7-function module where every function is a trivial 1-line delegation to desloppify.state with zero added logic.",
"related_files": ["desloppify/app/commands/helpers/state_access.py", "desloppify/state.py"],
"evidence": "load_state_file() -> state_mod.load_state(state_file), save_state_file() -> state_mod.save_state(state, state_file), resolve_matching_findings() -> state_mod.match_findings(state, pattern, status_filter=status_filter), snapshot_scores() -> state_mod.score_snapshot(state), remove_ignored_findings() -> state_mod.remove_ignored_findings(state, pattern), coerce_assessment_score() -> state_mod.coerce_assessment_score(value), utc_timestamp() -> state_mod.utc_now(). No parameter renaming, no validation, no error handling.",
"suggestion": "Delete state_access.py and have callers import directly from desloppify.state. The 'narrow accessor' framing does not justify a module that adds nothing.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "impl_modules_zero_callers",
"summary": "core/io/impl.py, core/pathing/impl.py, and core/discovery/impl.py are star-import shims with zero importers anywhere in the codebase.",
"related_files": ["desloppify/core/io/impl.py", "desloppify/core/pathing/impl.py", "desloppify/core/discovery/impl.py"],
"evidence": "Grep for 'from desloppify.core.io.impl import', 'from desloppify.core.pathing.impl import', 'from desloppify.core.discovery.impl import' returns 0 results across the entire codebase. Each file is a ~10-line star-import shim (e.g. 'from desloppify.core.output import , repo_root, packet_path, batch_index, batch) -> str: return render_batch_prompt(repo_root=repo_root, packet_path=packet_path, batch_index=batch_index, batch=batch). Pure arg-forwarding with no added value. Callers could import render_batch_prompt directly.",
"suggestion": "Remove build_batch_prompt and have callers import render_batch_prompt from the payload module directly.",
"confidence": "medium"
},
{
"dimension": "mid_level_elegance",
"identifier": "langrun_property_boilerplate",
"summary": "LangRun in runtime.py manually defines 11 getter/setter property pairs that mechanically proxy to self.state., creating ~100 lines of boilerplate.",
"related_files": ["desloppify/languages/_framework/runtime.py"],
"evidence": "Lines 148-234: zone_map, dep_graph, complexity_map, review_cache, review_max_age_days, runtime_settings, runtime_options, large_threshold_override, props_threshold_override, detector_coverage, coverage_warnings -- each has identical @property that returns self.state. and @.setter that assigns self.state. = value. This is pure structural boilerplate.",
"suggestion": "Use / with a whitelist set (similar to how config attributes use _config_attr_property) or generate properties programmatically from _LANG_RUNTIME_STATE_FIELDS to eliminate the repetition.",
"confidence": "medium"
},
{
"dimension": "mid_level_elegance",
"identifier": "compat_utils_duplicate_tool_hash",
"summary": "Both desloppify/utils.py and desloppify/compat/utils.py define their own compute_tool_hash() and check_tool_staleness() functions that do the same thing but read TOOL_DIR from their own module scope, creating subtle divergence risk.",
"related_files": ["desloppify/utils.py", "desloppify/compat/utils.py"],
"evidence": "utils.py lines 23-30: compute_tool_hash() calls _compat_utils._tooling.compute_tool_hash(tool_dir=Path(TOOL_DIR)) where TOOL_DIR = _compat_utils.TOOL_DIR (line 20). compat/utils.py lines 80-87: compute_tool_hash() calls _tooling.compute_tool_hash(tool_dir=Path(TOOL_DIR)) where TOOL_DIR = _tooling.TOOL_DIR (line 53). Both shadow the TOOL_DIR at module scope, meaning test overrides of utils.TOOL_DIR won't propagate to compat/utils.TOOL_DIR and vice versa.",
"suggestion": "Consolidate to a single function definition. If TOOL_DIR override is needed, use a parameter rather than relying on module-level global mutation.",
"confidence": "high"
},
{
"dimension": "dependency_health",
"identifier": "discovery_api_only_caller_is_shim",
"summary": "core/discovery_api.py (the old flat module) exists solely to serve 3 test files via , but still imports the full discovery and pathing APIs at module scope.",
"related_files": ["desloppify/core/discovery_api.py"],
"evidence": "The module does 'from desloppify.core.discovery.api import *' eagerly (line 7) and defines for legacy path exports. Only 3 files import from it (all tests). The eager star-import means the full discovery API is loaded for these 3 callers.",
"suggestion": "Update the 3 test files to import from core.discovery.api and core.pathing.api directly, then delete core/discovery_api.py.",
"confidence": "high"
},
{
"dimension": "low_level_elegance",
"identifier": "exception_sets_overly_broad",
"summary": "PLAN_LOAD_EXCEPTIONS catches 7 exception types including AttributeError, TypeError, and KeyError, which masks programming bugs as load failures.",
"related_files": ["desloppify/core/exception_sets.py"],
"evidence": "PLAN_LOAD_EXCEPTIONS = (ImportError, AttributeError, OSError, ValueError, TypeError, KeyError). AttributeError, TypeError, and KeyError are typically programming errors (wrong attribute access, wrong arg type, missing dict key), not I/O failures. Catching them silently converts bugs into silent fallback behavior.",
"suggestion": "Narrow to (ImportError, OSError, ValueError) for I/O and parse failures. If specific code paths legitimately raise KeyError/TypeError during load, catch those locally with an explanatory comment.",
"confidence": "medium"
},
{
"dimension": "low_level_elegance",
"identifier": "dynamic_path_proxy_getattr_risk",
"summary": "DynamicPathProxy. silently delegates every unknown attribute to the resolved Path, making the proxy type-invisible and error-masking.",
"related_files": ["desloppify/core/_internal/path_proxy.py"],
"evidence": "Line 34: def (self, name: str) -> object: return getattr(self._value(), name). This means any typo (e.g., proxy.exiss() instead of proxy.exists()) will resolve the lambda, create a real Path, and then raise AttributeError from Path -- not from the proxy. The return type 'object' also defeats type checking for all proxied attributes.",
"suggestion": "Restrict to an explicit allowlist of Path attributes that callers actually use (exists, is_dir, parent, etc.), or document the design tradeoff. Consider using or typing.Protocol to give type checkers visibility.",
"confidence": "medium"
}
]
}
Assistant
Confirmed: there is no test enforcing that core._internal remains private to core. Now let me verify my understanding of the redundant shim layer. Let me look at how core.io.api and core.output are related.
Assistant
Good. Now let me look at the deleted files from git status to understand what was moved vs what still lingers.
Assistant
Now I have enough to form a thorough assessment. Let me look at one last thing -- the NO_COLOR import-time env read pattern.
Assistant
Now I have a comprehensive understanding. Let me also look at one more thing - the LangConfig types contract and whether the large number of fields on it is tested for contract compliance.
Assistant
Now let me also count the number of files in each core namespace package:
Assistant
These deleted files have been moved into subdirectories. Let me check if the old import paths are still used anywhere.
Assistant
Good. Now let me check how the different __init__.py patterns break down across sibling command packages. I have already seen these patterns:
lazy_exports helper pattern: show, resolve, plan, fix (import from lazy_exports.py)
Inline __getattr__ with _LEGACY_MODULE_ALIASES: review (top-level)
Inline __getattr__ with _LAZY_EXPORTS: review/runtime
Inline __getattr__ with direct import: move (inline if/else)
Inline __getattr__ with _EXPORT_MODULES: typescript/fixers
Direct eager import: security, test_coverage
Pure docstring: core/_internal, engine/_state, engine/_work_queue, engine/_plan, engine/_scoring, etc
Let me also check the app/commands/scan/__init__.py to see its pattern.
Assistant
Good. Now let me look at how core.io.api delegates to core.output while being imported 93 times - I want to check how the actual impl module is structured and whether the api module adds value beyond being a pass-through.
Assistant
Let me check if the impl.py files are actually imported by anyone other than the __init__.py.
Assistant
Those are all importing from the NEW paths. Good, the migration seems complete for the review subpackages. Let me now look at what the review __init__.py looks like.
Assistant
That's yet another pattern: direct eager import without lazy loading. So under app/commands/, the sub-command packages use at least 4 different __init__.py patterns:
scan/: direct eager import
show/, resolve/, plan/, fix/: lazy_exports helper
move/: inline __getattr__ with importlib
review/: inline __getattr__ with _LEGACY_MODULE_ALIASES
Now I have enough data to provide a well-evidenced assessment. Let me also quickly check a couple more things for mid-level elegance -- the handoff between engine/planning init and core.
Assistant
I now have enough evidence to produce the assessment. Let me check one more thing - how the state.py facade tests overlap with the deeper state tests.
Assistant
So there are callers going through engine.planning (the __init__.py with *args/**kwargs wrappers) and callers going directly to engine.planning.core. Let me also check one more thing -- the state.py facade at the root.
Assistant
Wait -- the __init__.py files do import impl:
Assistant
Now I have comprehensive evidence. Let me produce the final assessment.
Assistant
There are many callers using the old paths through the __getattr__ shim. Let me now look at some more potential AI-debt patterns. Let me check the core/io/api.py pass-through more carefully - it's pure forwarding with no added logic.
Assistant
Yes, __init__.py imports impl at line 7, but grep missed it because of the relative import pattern. Let me check if anyone actually uses the impl submodule.
Assistant
So commands.py imports these constants through phases.py rather than directly from phase_policies.py. This means importing commands.py forces loading the entire phases.py module (with all its heavy detector imports), even though commands.py only needs the constants. This is an initialization coupling issue -- commands.py could get its constants directly from phase_policies.py.
Now I have enough evidence to produce my assessment. Let me compile the findings.
{
"assessments": {
"initialization_coupling": 72,
"design_coherence": 68
},
"findings": [
{
"dimension": "initialization_coupling",
"identifier": "react_detector_dual_project_root",
"summary": "react.py defines its own PROJECT_ROOT: Path | None = None module-level mutable instead of importing from core.pathing.api. The detect_boolean_state_explosion function uses this local None-valued PROJECT_ROOT directly (PROJECT_ROOT / filepath on line 384) without the _resolve_source_path helper, which will raise TypeError when PROJECT_ROOT is None and the file path is relative.",
"related_files": [
"desloppify/languages/typescript/detectors/react.py"
],
"evidence": "Line 22: PROJECT_ROOT: Path | None = None (local mutable). Line 384: else PROJECT_ROOT / filepath -- crashes when PROJECT_ROOT is None. Contrast with sibling detectors (smells.py, unused.py, concerns.py, props.py) which import the DynamicPathProxy from core.pathing.api and never crash. Also contrast with other functions in the same file (detect_state_sync, detect_context_nesting, detect_hook_return_bloat) which use the _resolve_source_path helper that handles None properly.",
"suggestion": "Replace the local PROJECT_ROOT: Path | None = None with from desloppify.core.pathing.api import PROJECT_ROOT and update detect_boolean_state_explosion to use _resolve_source_path like the other detectors in the same file.",
"confidence": "high"
},
{
"dimension": "initialization_coupling",
"identifier": "scattered_project_root_override_pattern",
"summary": "Seven modules define their own PROJECT_ROOT: Path | None = None as a test override hook, creating a scattered initialization coupling pattern. These shadow the canonical DynamicPathProxy from core.pathing.api which already supports runtime root overrides via RuntimeContext.",
"related_files": [
"desloppify/cli.py",
"desloppify/app/commands/helpers/state.py",
"desloppify/app/commands/review/external.py",
"desloppify/app/commands/review/batch.py",
"desloppify/languages/typescript/detectors/react.py",
"desloppify/intelligence/review/importing/holistic.py",
"desloppify/intelligence/review/importing/per_file.py",
"desloppify/core/_internal/text_utils.py"
],
"evidence": "Each of these files declares at module scope. The canonical system already has (core/_internal/path_proxy.py) backed by (core/runtime_state.py) which supports test overrides via . The local override pattern requires each test to know which module's global to patch, and the react.py bug (detect_boolean_state_explosion crash on None) shows the fragility of this approach.",
"suggestion": "Migrate modules to use the canonical DynamicPathProxy from core.pathing.api, which already supports test overrides via RuntimeContext. This eliminates the scattered mutable globals and the risk of None-dereference bugs.",
"confidence": "medium"
},
{
"dimension": "initialization_coupling",
"identifier": "registry_state_globals_mutation",
"summary": "registry_state.py uses assignments to mutate module-level state for , , and . While this avoids the stale-binding problem, it creates an implicit boot-order dependency: callers must ensure runs before is meaningful, and can silently clear state that other modules depend on.",
"related_files": [
"desloppify/languages/_framework/registry_state.py"
],
"evidence": "Lines 91, 101, 116-121: , , . Line 82-86: clears everything atomically including the registry dict, load flag, context, and errors. Any module that has cached before a reset will have stale knowledge.",
"suggestion": "Consider encapsulating the registry state in a class instance (similar to RuntimeContext) to make the lifecycle and ownership explicit rather than relying on module-level globals mutation.",
"confidence": "low"
},
{
"dimension": "initialization_coupling",
"identifier": "commands_imports_phases_for_constants",
"summary": "commands.py imports TS_COMPLEXITY_SIGNALS, TS_GOD_RULES, TS_SKIP_DIRS, TS_SKIP_NAMES from phases.py, which re-exports them from phase_policies.py. This forces loading the entire phases.py module (with its 14 heavy detector module imports) just to access four constant values.",
"related_files": [
"desloppify/languages/typescript/commands.py",
"desloppify/languages/typescript/phases.py",
"desloppify/languages/typescript/phase_policies.py"
],
"evidence": "commands.py lines 34-39: . phases.py lines 39-44 re-exports these from phase_policies.py. phases.py also imports 14 detector modules (lines 10-38: coupling, naming, orphaned, signature, concerns, deprecated, deps, exports, facade, logs, patterns, props, react, smells, unused). commands.py could import directly from phase_policies.py to avoid triggering this cascade.",
"suggestion": "Import the constants directly from phase_policies.py in commands.py: .",
"confidence": "high"
},
{
"dimension": "design_coherence",
"identifier": "react_detector_inconsistent_path_resolution",
"summary": "Within react.py, four detector functions use two different path resolution strategies. Three functions use the helper (which handles PROJECT_ROOT being None), while uses raw (which crashes on None). This is an internal consistency defect.",
"related_files": [
"desloppify/languages/typescript/detectors/react.py"
],
"evidence": "Functions using : detect_state_sync (via _load_tsx_content, line 39), detect_context_nesting (line 165), detect_hook_return_bloat (via _load_tsx_content, line 247). Function using raw access: detect_boolean_state_explosion (line 384, ). The inconsistency means one function in the same file will crash where three others will not, under identical conditions.",
"suggestion": "Refactor detect_boolean_state_explosion to use or for path resolution, matching the pattern used by the other three detector functions.",
"confidence": "high"
},
{
"dimension": "design_coherence",
"identifier": "smell_detection_structural_repetition",
"summary": "Python smells.py and TypeScript smells.py both implement nearly identical smell-detection pipelines: define SMELL_CHECKS as a list of dicts with id/label/severity/pattern, iterate files, apply regex checks with string-awareness filtering, run multi-line detectors, then build summary entries sorted by severity. This structural duplication across language boundaries indicates a missing shared abstraction.",
"related_files": [
"desloppify/languages/python/detectors/smells.py",
"desloppify/languages/typescript/detectors/smells.py"
],
"evidence": "Python smells.py lines 33-188: list of dicts. Lines 424-434: iterates files, runs pattern matches, builds dict keyed by id, then sorts by severity. TypeScript smells.py lines 35-218: list with identical structure. Lines 430-520: iterates files, runs pattern matches into dict keyed by id, then builds entries sorted by severity with identical sort key . Both use with same shape.",
"suggestion": "Extract the common smell pipeline (check definition, file iteration, regex matching with string filtering, summary building) into a shared framework function, allowing language-specific plugins to provide only their check definitions and multi-line detectors.",
"confidence": "medium"
},
{
"dimension": "design_coherence",
"identifier": "generic_lang_registration_side_effects",
"summary": "The function in generic.py performs global registration side effects (register_detector, register_scoring_policy, registry_state.register) as part of plugin construction. While the code comments note that side effects are deferred until after validation, the function mixes config construction with global state mutation, meaning calling twice with the same name silently overwrites previous registrations.",
"related_files": [
"desloppify/languages/_framework/generic.py"
],
"evidence": "Lines 215-223: calls for each detector, for each policy, and . These are all global mutable state mutations. Line 311-436: calls unconditionally -- there is no guard against double-registration or cleanup of previous registrations for the same name.",
"suggestion": "Add a guard in that checks whether the language is already registered and either raises an error or cleans up the previous registration before applying new side effects.",
"confidence": "medium"
}
]
}
Assistant
So the "canonical" API surface (core/io/api.py, core/pathing/api.py, core/discovery/api.py) is heavily imported (90+, 146, 49 files). These are pure pass-through wrappers around core/output.py, core/file_paths.py, core/source_discovery.py. Let me check if anyone still imports from the original modules directly.
Assistant
So the impl submodules are exported from __init__.py but never actually imported by any code outside their own package. They exist purely as a structural convention.
Now let me verify something about the core/ flat directory -- there are 24 files there. How many are shims?
Assistant
Good. The original modules (core/output.py, core/source_discovery.py, core/file_paths.py) are only imported by their respective API wrappers. No one imports them directly anymore. Now let me look at the _internal/path_proxy.py and check for over-engineering.
Assistant
Now let me look for more specific AI-debt signals. Let me check for docstrings on very short functions.
Assistant
Let me now check how many callers are still importing from the deprecated shims (output_api.py, paths_api.py, discovery_api.py).
Assistant
This is a clear AI-generated pattern: every function is a one-line forwarding call to state_mod, wrapped in a docstring that restates the obvious. Let me also look at the engine/planning/queue_policy.py file and some of the selection_* files.
Assistant
Now let me look for defensive overengineering patterns - isinstance checks on typed values, try/except on pure expressions.
Assistant
Let me now check the _SCORING_SHIM / _COMPAT_SCORING_SHIM pattern to understand the full migration chain depth. I want to count how many layers you go through for a typical from desloppify.scoring import DIMENSIONS.
Assistant
Now I have a comprehensive understanding. Let me compile my assessment.
{
"assessments": {
"cross_module_architecture": 62,
"high_level_elegance": 68
},
"findings": [
{
"dimension": "cross_module_architecture",
"identifier": "engine_imports_app_layer",
"summary": "The engine layer (engine/planning/dimension_rows.py) imports from the app layer (app/output/scorecard_parts/dimensions.py), violating the downward-only dependency rule where lower layers should never depend on higher layers.",
"related_files": [
"desloppify/engine/planning/dimension_rows.py",
"desloppify/app/output/scorecard_parts/dimensions.py"
],
"evidence": "desloppify/engine/planning/dimension_rows.py line 9: from desloppify.app.output.scorecard_parts.dimensions import prepare_scorecard_dimensions. The module docstring (line 3-4) even acknowledges this: 'Provides scorecard_dimension_rows without importing app-layer modules' but then does exactly that.",
"suggestion": "Move prepare_scorecard_dimensions (or its core logic) down into the engine/planning layer or a shared core module. The app/output layer should consume engine outputs, not the other way around.",
"confidence": "high"
},
{
"dimension": "cross_module_architecture",
"identifier": "intelligence_reaches_into_engine_private",
"summary": "The intelligence layer directly imports from engine._scoring private subpackage, bypassing the public scoring facade.",
"related_files": [
"desloppify/intelligence/review/dimensions/metadata.py",
"desloppify/engine/_scoring/subjective/display_names.py",
"desloppify/scoring.py"
],
"evidence": "desloppify/intelligence/review/dimensions/metadata.py line 10: from desloppify.engine._scoring.subjective.display_names import DISPLAY_NAMES. The _scoring prefix marks this as private, but the scoring facade at desloppify/scoring.py already re-exports DISPLAY_NAMES (via compat/scoring.py line 45).",
"suggestion": "Import DISPLAY_NAMES from desloppify.scoring (the public facade) instead of reaching into the engine private module. If the facade doesn't export it, add it there.",
"confidence": "high"
},
{
"dimension": "cross_module_architecture",
"identifier": "facade_indirection_explosion",
"summary": "Core utility functions like read_code_snippet are accessible through 5+ distinct import paths (text_utils -> text_api, pathing/api, paths_api, compat/utils, utils), creating confusion about which path is canonical and making the dependency graph artificially dense.",
"related_files": [
"desloppify/core/_internal/text_utils.py",
"desloppify/core/text_api.py",
"desloppify/core/pathing/api.py",
"desloppify/core/paths_api.py",
"desloppify/compat/utils.py",
"desloppify/utils.py"
],
"evidence": "read_code_snippet defined at core/_internal/text_utils.py:30, re-exported through: core/text_api.py:20, core/pathing/api.py:39, core/paths_api.py:41, compat/utils.py (via pathing/api), and utils.py (via compat). In production code the function is consumed from two different canonical paths: core/pathing/api (show/render.py, next_parts/render.py) and never directly from core/text_api. Zero callers use paths_api, output_api, or discovery_api.",
"suggestion": "Remove the zero-caller compatibility shims (core/paths_api.py, core/output_api.py, core/discovery_api.py) and consolidate the re-export to one canonical path per function. Since all production callers already use core/pathing/api and core/io/api, those are the winners.",
"confidence": "high"
},
{
"dimension": "cross_module_architecture",
"identifier": "dead_compat_shims_persist",
"summary": "Three compatibility facade modules (core/paths_api.py, core/output_api.py, core/discovery_api.py) have zero production callers but add import-surface noise and require maintenance.",
"related_files": [
"desloppify/core/paths_api.py",
"desloppify/core/output_api.py",
"desloppify/core/discovery_api.py"
],
"evidence": "grep for returns 0 results. returns 0 results. has 4 uses, all in test files. These shims were intended for migration but the migration is complete.",
"suggestion": "Delete core/paths_api.py and core/output_api.py immediately (zero callers). For core/discovery_api.py, update the 3 test files to import from core/discovery/api and core/pathing/api directly, then delete.",
"confidence": "high"
},
{
"dimension": "cross_module_architecture",
"identifier": "coerce_assessment_score_duplication",
"summary": "Assessment score coercion logic is duplicated between the engine state layer and the review preflight command, with subtly different implementations that risk drift.",
"related_files": [
"desloppify/engine/_state/resolution.py",
"desloppify/app/commands/review/preflight.py",
"desloppify/app/commands/helpers/state_access.py"
],
"evidence": "engine/_state/resolution.py:24 defines (canonical, handles clamping to 0-100, uses is_numeric guard). preflight.py:108 defines (different implementation, no clamping, accepts bool-as-int, accepts string scores). state_access.py:46 wraps the engine version. The preflight version does not exclude bools (isinstance check uses int|float which includes bool), and does not clamp to 0-100.",
"suggestion": "Delete the private in preflight.py and call (which delegates to the canonical engine version). This eliminates the subtle behavioral divergence.",
"confidence": "high"
},
{
"dimension": "cross_module_architecture",
"identifier": "import_time_cwd_capture",
"summary": "The project root is captured at import time from , which is fragile when the module is imported before the working directory is set (e.g. in test runners, CI, or library usage).",
"related_files": [
"desloppify/core/_internal/text_utils.py"
],
"evidence": "core/_internal/text_utils.py line 11: . This executes at import time. The RuntimeContext system (core/runtime_state.py) was built to override this, but the default still captures cwd eagerly. If this module is imported as a transitive dependency before the CLI sets up the runtime context, the fallback is whatever directory the process happened to start in.",
"suggestion": "Make lazy by computing it on first access rather than at import time. A simple pattern: use a sentinel and resolve in on first call, caching the result.",
"confidence": "medium"
},
{
"dimension": "high_level_elegance",
"identifier": "show_and_status_render_duplication",
"summary": "show/render.py and status_parts/render.py each define their own and with near-identical logic, creating a maintenance-drift risk between two command surfaces.",
"related_files": [
"desloppify/app/commands/show/render.py",
"desloppify/app/commands/status_parts/render.py"
],
"evidence": "show/render.py:206 defines and status_parts/render.py:496 defines . The bodies are nearly identical (both check plan, delegate to print_active_agent_plan, print the same yellow header string, call print_ranked_actions). Similarly is duplicated at show/render.py:253 and status_parts/render.py:474 with identical structure but slightly different parameter shapes.",
"suggestion": "Extract a single helper into app/commands/helpers/rendering.py (which both already import). The show variant's extra parameter can be handled with a kwarg default.",
"confidence": "high"
},
{
"dimension": "high_level_elegance",
"identifier": "three_layer_shim_chain",
"summary": "The top-level facade files (utils.py, scoring.py, file_discovery.py) exist solely to re-export from compat/ which re-exports from core/ packages, creating a 3-layer shim chain with no active external consumers.",
"related_files": [
"desloppify/utils.py",
"desloppify/compat/utils.py",
"desloppify/scoring.py",
"desloppify/compat/scoring.py",
"desloppify/file_discovery.py",
"desloppify/compat/file_discovery.py"
],
"evidence": "utils.py imports from compat/utils.py which imports from core/pathing/api, core/io/api, core/discovery/api, etc. has only 8 occurrences (all in tests or transitive-check tests). has 1 occurrence (a test). has 0 occurrences. The real codebase has migrated to the core/ packages (90 files import from core/io/api, 146 from core/pathing/api).",
"suggestion": "Since the migration to core/ packages is effectively complete, deprecate and schedule removal of the three top-level shims (utils.py, scoring.py, file_discovery.py) and their compat/ intermediaries. Update the remaining 8 test imports to use the canonical paths.",
"confidence": "high"
},
{
"dimension": "high_level_elegance",
"identifier": "pathing_api_mixes_io_and_path_concerns",
"summary": "core/pathing/api.py bundles both path resolution functions and I/O operations (safe_write_text, read_code_snippet), mixing two distinct responsibilities in what should be a pure path-manipulation surface.",
"related_files": [
"desloppify/core/pathing/api.py",
"desloppify/core/_internal/text_utils.py"
],
"evidence": "pathing/api.py exports path-resolution functions (get_project_root, rel, resolve_path, matches_exclusion, safe_relpath) alongside I/O functions (safe_write_text at line 89, read_code_snippet at line 39). The API docstring says 'Canonical path and snippet API surface' but safe_write_text is an atomic-write I/O operation, not path resolution. read_code_snippet involves file I/O and text formatting.",
"suggestion": "Move safe_write_text to core/io/api.py (it's already in the io namespace conceptually). Keep read_code_snippet in pathing/api since it's path-resolved snippet reading and already has 2 callers there. This aligns the API surface with its name.",
"confidence": "medium"
},
{
"dimension": "cross_module_architecture",
"identifier": "globals_mutation_for_module_state",
"summary": "Multiple modules use to mutate module-level state instead of using a proper mutable container, making the state invisible to static analysis and IDE navigation.",
"related_files": [
"desloppify/languages/_framework/registry_state.py",
"desloppify/languages/_framework/treesitter/.py",
"desloppify/core/registry.py"
],
"evidence": "registry_state.py lines 91, 101, 121 use , , . treesitter/.py lines 47-48, 54-55 use . core/registry.py lines 334, 342 use , . This pattern exists to work around Python's global-variable rebinding rules but makes state transitions harder to trace.",
"suggestion": "Replace the globals() pattern with a simple @dataclass or module-level container object. For example in registry_state.py: then and . This is how runtime_state.py already handles its equivalent pattern (RuntimeContext dataclass).",
"confidence": "medium"
}
]
}
Assistant
Good. So for from desloppify.scoring import DIMENSIONS, the import chain is:
desloppify/scoring.py (root shim) -> star-imports from desloppify/compat/scoring.py
desloppify/compat/scoring.py -> imports from desloppify/engine/_scoring/policy/core.py
That's 3 hops. Let me now look for some more patterns to assess. Let me check if deprecated-but-called symbols exist.
Assistant
So there's an inconsistency -- _scoring/detection.py uses dict[str, Finding] while _scoring/results/core.py uses bare dict. These are in the same package.
Now I have enough evidence to produce the assessment. Let me compile my findings.
{
"assessments": {
"naming_quality": 82,
"logic_clarity": 80,
"type_safety": 62,
"contract_coherence": 68,
"api_surface_coherence": 72,
"authorization_consistency": 90
},
"findings": [
{
"dimension": "type_safety",
"identifier": "state-model-undeclared-fields",
"summary": "StateModel TypedDict is missing at least 5 fields that are actively written and read across 30+ callsites: scan_path (18 files), lang_capabilities (9 files), zone_distribution (9 files), reminder_history (7 files), and review_cache. The TypedDict promises a shape the runtime silently exceeds.",
"related_files": [
"desloppify/engine/_state/schema.py",
"desloppify/app/commands/scan/scan_workflow.py",
"desloppify/engine/_state/persistence.py",
"desloppify/engine/_state/resolution.py",
"desloppify/intelligence/narrative/core.py"
],
"evidence": [
"schema.py defines StateModel (lines 151-169) with no scan_path, lang_capabilities, zone_distribution, reminder_history, or review_cache fields",
"scan_workflow.py line 105: state["lang_capabilities"] = normalized -- writes undeclared field",
"scan_workflow.py line 431: runtime.state["zone_distribution"] = runtime.lang.zone_map.counts()",
"scan_workflow.py line 613: runtime.state["reminder_history"] = narrative["reminder_history"]",
"state.get("scan_path") appears in 18 files across the codebase (filtering.py, resolution.py, persistence.py, narrative/core.py, etc.) but scan_path is not declared in StateModel",
"state.get("review_cache", {}) used in scan_workflow.py line 210 -- also undeclared"
],
"suggestion": "Add the missing fields to StateModel as NotRequired entries: scan_path: NotRequired[str | None], lang_capabilities: NotRequired[dict[str, dict[str, object]]], zone_distribution: NotRequired[dict[str, int]], reminder_history: NotRequired[dict[str, int]], review_cache: NotRequired[dict[str, object]]. This makes the TypedDict truthful about the runtime shape.",
"confidence": "high"
},
{
"dimension": "type_safety",
"identifier": "scoring-engine-bare-dict-params",
"summary": "Five public functions in engine/_scoring/results/core.py accept findings as bare 'dict' with no type parameters, while sibling module engine/_scoring/detection.py correctly types the same parameter as dict[str, Finding]. The untyped signatures lose all static checking on the most important data structure in the system.",
"related_files": [
"desloppify/engine/_scoring/results/core.py",
"desloppify/engine/_scoring/detection.py",
"desloppify/engine/_scoring/subjective/core.py"
],
"evidence": [
"results/core.py line 40: findings: dict, -- bare dict on compute_dimension_scores_by_mode",
"results/core.py line 109: findings: dict, -- bare dict on compute_dimension_scores",
"results/core.py line 380: findings: dict, -- bare dict on compute_score_bundle",
"subjective/core.py line 111: findings: dict, -- bare dict on _issue_count_for_dimension",
"subjective/core.py line 220: findings: dict, -- bare dict on append_subjective_dimensions",
"Contrast with detection.py line 37: findings: dict[str, Finding], -- properly typed",
"detection.py line 84, 135, 183: all use dict[str, Finding]"
],
"suggestion": "Replace bare 'dict' with 'dict[str, Finding]' on all five functions in results/core.py and subjective/core.py. The import already exists in detection.py as a pattern to follow.",
"confidence": "high"
},
{
"dimension": "contract_coherence",
"identifier": "resolve-findings-overwrites-then-overrides",
"summary": "resolve_findings() builds a base 'updates' dict (line 142) that unconditionally sets resolved_at=now and a 'manual' resolution_attestation, then immediately overwrites those fields via extra_updates for the 'open' and 'wontfix' branches. The base dict contains semantically wrong values (e.g., resolved_at=now for a reopen) that are silently corrected by the override. If a new status branch is added without also supplying extra_updates, the function will silently stamp a resolved_at timestamp on a non-resolved finding.",
"related_files": [
"desloppify/engine/_state/resolution.py"
],
"evidence": [
"Line 142-155: base updates dict sets resolved_at=now and resolution_attestation with kind='manual'",
"Line 126-140: when status=='open', extra_updates overrides resolved_at=None and resolution_attestation with kind='manual_reopen'",
"Line 116-125: when status=='wontfix', extra_updates adds wontfix_snapshot but does NOT override resolved_at -- so resolved_at=now is applied even though wontfix is not technically a 'resolved' status",
"Line 156: updates.update(extra_updates) applies the overrides, but the base always supplies wrong defaults for at least the 'open' path"
],
"suggestion": "Build the updates dict conditionally per status branch rather than using a 'base plus override' pattern. Each branch (open, wontfix, fixed, false_positive) should construct exactly the fields appropriate for that status, avoiding the fragile override chain.",
"confidence": "high"
},
{
"dimension": "contract_coherence",
"identifier": "wontfix-gets-resolved-at-timestamp",
"summary": "When resolve_findings() is called with status='wontfix', the base updates dict sets resolved_at=now (line 145) and the wontfix branch in extra_updates (lines 116-125) does not override it. This means wontfix findings get a resolved_at timestamp, which is semantically incorrect -- wontfix is a 'dismissed' status, not a 'resolved' one. This conflicts with the schema's implied meaning where resolved_at is set on auto_resolved and fixed findings.",
"related_files": [
"desloppify/engine/_state/resolution.py",
"desloppify/engine/_state/schema.py"
],
"evidence": [
"resolution.py line 142-145: updates dict unconditionally includes resolved_at=now",
"resolution.py lines 116-125: wontfix branch adds wontfix_scan_count and wontfix_snapshot to extra_updates but does NOT set resolved_at",
"schema.py line 65: Finding TypedDict declares resolved_at: str | None, implying None means 'not resolved'",
"merge_findings.py line 46: _mark_auto_resolved sets resolved_at only for truly resolved findings"
],
"suggestion": "Add resolved_at=now only for genuinely resolved statuses (fixed, false_positive, auto_resolved). For wontfix, set resolved_at=None or a separate dismissed_at field.",
"confidence": "high"
},
{
"dimension": "api_surface_coherence",
"identifier": "inconsistent-dict-typing-across-scoring-api",
"summary": "The scoring API surface mixes fully unparameterized 'dict' with 'dict[str, dict]' and 'dict[str, int]' for the same conceptual parameters. compute_dimension_scores_by_mode takes (findings: dict, potentials: dict[str, int]) while compute_health_breakdown takes (dimension_scores: dict). The ScoreBundle dataclass uses (dimension_scores: dict[str, dict]) while its factory function compute_score_bundle takes (findings: dict). These inconsistencies make it impossible for callers to know what shapes are expected without reading implementation.",
"related_files": [
"desloppify/engine/_scoring/results/core.py"
],
"evidence": [
"Line 28-31: ScoreBundle has dimension_scores: dict[str, dict] -- partially typed",
"Line 39-45: compute_dimension_scores_by_mode has findings: dict and potentials: dict[str, int] -- inconsistent precision",
"Line 108-115: compute_dimension_scores has findings: dict, potentials: dict[str, int]",
"Line 319-321: compute_health_breakdown has dimension_scores: dict -- bare dict",
"Line 379-384: compute_score_bundle has findings: dict, potentials: dict[str, int]"
],
"suggestion": "Establish type aliases (e.g. FindingsMap = dict[str, Finding], DimensionScoreMap = dict[str, DimensionScoreEntry]) and use them consistently across the scoring API surface. This is the core scoring engine -- type precision here pays off across all consumers.",
"confidence": "high"
},
{
"dimension": "type_safety",
"identifier": "scan-workflow-potentials-type-mismatch",
"summary": "run_scan_generation declares its return potentials as dict[str, object] (line 379), but line 407 writes potentials['stale_wontfix'] = monitored_wontfix (an int). The actual callers pass potentials to merge_scan which types it as dict[str, int | Any] via MergeScanOptions. The function signature promises dict[str, object] which is too loose and hides the actual dict[str, int] contract.",
"related_files": [
"desloppify/app/commands/scan/scan_workflow.py",
"desloppify/engine/_state/merge.py"
],
"evidence": [
"scan_workflow.py line 379: return type is tuple[list[dict[str, Any]], dict[str, object], dict[str, object] | None]",
"scan_workflow.py line 407: potentials['stale_wontfix'] = monitored_wontfix -- monitored_wontfix is int from _augment_with_stale_wontfix_findings",
"merge_scan_results (line 414) accepts potentials: dict[str, object] then passes to MergeScanOptions",
"compute_dimension_scores_by_mode expects potentials: dict[str, int] -- the actual consumer needs ints, not objects"
],
"suggestion": "Type potentials as dict[str, int] throughout the scan workflow chain, matching the actual runtime values and the scoring engine's expectations.",
"confidence": "high"
},
{
"dimension": "naming_quality",
"identifier": "collect-dimension-rows-opaque-tuple-return",
"summary": "_collect_dimension_rows returns a 6-element tuple (float, float, float, float, list, list) with no named structure. Callers must destructure by position (lines 333-340), making the code fragile and hard to read. The function name 'collect' is also vague -- it computes weighted sums and partitions dimensions into mechanical vs subjective pools.",
"related_files": [
"desloppify/engine/_scoring/results/core.py"
],
"evidence": [
"Lines 161-172: return type is tuple[float, float, float, float, list[dict[str, float | str]], list[dict[str, float | str]]]",
"Lines 333-340: caller destructures as (mech_sum, mech_weight, subj_sum, subj_weight, mechanical_rows, subjective_rows) -- 6 positional bindings",
"Function name 'collect' does not communicate that it computes weighted aggregates and partitions by scoring pool"
],
"suggestion": "Replace the 6-tuple return with a NamedTuple or dataclass (e.g. DimensionPartition with fields mech_sum, mech_weight, subj_sum, subj_weight, mechanical_rows, subjective_rows). Consider renaming to _partition_dimension_pools or _aggregate_dimension_weights.",
"confidence": "high"
},
{
"dimension": "logic_clarity",
"identifier": "resolve-findings-double-attestation-build",
"summary": "resolve_findings() builds a resolution_attestation dict in the base updates (lines 149-154) and then builds a second one in extra_updates for the 'open' branch (lines 134-140). The second one overwrites the first via dict.update(). This means for the 'open' branch, the base attestation is constructed but immediately thrown away -- wasted computation and confusing control flow.",
"related_files": [
"desloppify/engine/*_files",
"source_discovery.py lines 189-198: implementations are one-line calls to find_source_files with hardcoded extension lists",
"The core/discovery/ package is a language-agnostic API surface (its docstring says 'Canonical discovery API surface') yet it exports python and typescript-specific functions"
],
"suggestion": "Move language-specific file finders into the respective language plugins (desloppify/languages/python/ and desloppify/languages/typescript/). Keep the core/discovery API language-agnostic, exposing only find_source_files.",
"confidence": "medium"
},
{
"dimension": "contract_coherence",
"identifier": "gather-auth-context-return-type-lie",
"summary": "gather_auth_context is annotated as returning dict[str, object] (line 87), but it actually constructs an AuthorizationSignals dataclass and calls .as_dict() on it (line 145). The return type should be the as_dict() return type. More importantly, the function constructs a rich typed AuthorizationSignals but immediately discards all type information by converting to dict. Callers lose the ability to use the dataclass interface.",
"related_files": [
"desloppify/intelligence/review/context_signals/auth.py"
],
"evidence": [
"Line 87: return type annotation is -> dict[str, object]",
"Line 137-145: builds AuthorizationSignals dataclass, then returns .as_dict()",
"AuthorizationSignals.as_dict() returns dict[str, object] (line 60)",
"Callers receive an opaque dict instead of the typed AuthorizationSignals"
],
"suggestion": "Return the AuthorizationSignals dataclass directly and let callers call .as_dict() when they need serialization. This preserves type information at boundaries where it is most valuable.",
"confidence": "medium"
}
]
}
Assistant
Let me now look at how many imports use the deprecated desloppify.core.discovery_api path (the one that warns).
Assistant
Let me look at the _internal/text_utils.py to see if text_api.py is also a pure pass-through.
Assistant
Now let me check the selection_dependencies.py file for AI-generated patterns - the heavy isinstance checking.
Assistant
Now I have enough data to produce a thorough, evidence-backed assessment. Let me compile my findings.
{
"assessments": {
"convention_outlier": 62,
"error_consistency": 58,
"mid_level_elegance": 60
},
"findings": [
{
"dimension": "convention_outlier",
"identifier": "init-pattern-inconsistency-across-command-packages",
"summary": "Sibling command sub-packages under app/commands/ use at least four different init.py conventions for lazy/eager export, despite serving the same architectural role.",
"related_files": [
"desloppify/app/commands/scan/init.py",
"desloppify/app/commands/show/init.py",
"desloppify/app/commands/move/init.py",
"desloppify/app/commands/review/init.py",
"desloppify/app/commands/fix/init.py",
"desloppify/app/commands/helpers/lazy_exports.py"
],
"evidence": "scan/ uses direct eager import ('from .scan import cmd_scan'). show/, resolve/, plan/, fix/ use the shared lazy_exports helper (lazy_module_getattr/lazy_module_dir). move/ uses an inline getattr with raw importlib and an 'if name != ...' guard. review/ uses inline getattr with a LEGACY_MODULE_ALIASES dict. All are sibling command packages exporting a single cmd* function, yet each follows a different protocol. A shared helper (lazy_exports.py) exists but only 4 of 7 command packages use it.",
"suggestion": "Converge all command sub-package init.py files onto the lazy_exports helper or direct eager import. The lazy_exports helper already exists and is used by four packages; apply it consistently to move/ and review/ (replacing their inline variants), or simplify all to direct eager imports if lazy loading is not needed.",
"confidence": "high"
},
{
"dimension": "convention_outlier",
"identifier": "review-sub-packages-mixed-init-depth",
"summary": "The six sub-packages under app/commands/review/ have inconsistent init.py depths: some are empty docstrings, one uses lazy exports with getattr, creating an uneven navigation experience.",
"related_files": [
"desloppify/app/commands/review/importing/init.py",
"desloppify/app/commands/review/normalization/init.py",
"desloppify/app/commands/review/orchestration/init.py",
"desloppify/app/commands/review/payload/init.py",
"desloppify/app/commands/review/quality/init.py",
"desloppify/app/commands/review/runtime/init.py"
],
"evidence": "importing/, normalization/, orchestration/, payload/, quality/ have bare docstring-only init.py files (no exports). runtime/ has a fully-developed init.py with lazy getattr, _LAZY_EXPORTS dict, dir, and eager imports of setup_lang/setup_lang_concrete. These six directories are siblings serving the same review command, but the runtime/ sub-package follows a completely different structural protocol than its five siblings.",
"suggestion": "Either give all review sub-packages a consistent init pattern (all with exports or all bare), or document why runtime/ needs a richer init surface while the others do not.",
"confidence": "high"
},
{
"dimension": "error_consistency",
"identifier": "duplicated-exception-tuple-show-cmd",
"summary": "_SHOW_PLAN_LOAD_EXCEPTIONS in show/cmd.py is an exact copy of PLAN_LOAD_EXCEPTIONS from core/exception_sets.py, duplicating the shared exception set rather than importing it.",
"related_files": [
"desloppify/app/commands/show/cmd.py",
"desloppify/core/exception_sets.py"
],
"evidence": "_SHOW_PLAN_LOAD_EXCEPTIONS (show/cmd.py line 35) = (ImportError, AttributeError, OSError, ValueError, TypeError, KeyError). PLAN_LOAD_EXCEPTIONS (core/exception_sets.py line 5) = (ImportError, AttributeError, OSError, ValueError, TypeError, KeyError). They are identical tuples. Other callers (engine/planning/render.py, scan/scan_reporting_llm.py) correctly import from core/exception_sets.py, but show/cmd.py defines its own local copy. This creates a drift risk: if PLAN_LOAD_EXCEPTIONS is updated, _SHOW_PLAN_LOAD_EXCEPTIONS will silently diverge.",
"suggestion": "Replace _SHOW_PLAN_LOAD_EXCEPTIONS with an import of PLAN_LOAD_EXCEPTIONS from desloppify.core.exception_sets.",
"confidence": "high"
},
{
"dimension": "error_consistency",
"identifier": "proliferating-ad-hoc-exception-tuples",
"summary": "Multiple modules define their own near-identical exception tuples for recoverable error handling, with overlapping but subtly different compositions, rather than sharing a common set.",
"related_files": [
"desloppify/core/exception_sets.py",
"desloppify/app/output/visualize.py",
"desloppify/app/commands/scan/scan_workflow.py",
"desloppify/languages/_framework/treesitter/.py"
],
"evidence": "Four distinct exception tuples exist: (1) PLAN_LOAD_EXCEPTIONS = (ImportError, AttributeError, OSError, ValueError, TypeError, KeyError). (2) _RECOVERABLE_LANG_RESOLUTION_ERRORS in visualize.py = (ImportError, ValueError, TypeError, AttributeError, OSError, RuntimeError) -- adds RuntimeError, drops KeyError. (3) _PLAN_SYNC_EXCEPTIONS in scan_workflow.py = (OSError, ValueError, RuntimeError, TypeError, KeyError) -- drops ImportError and AttributeError, adds RuntimeError. (4) PARSE_INIT_ERRORS in treesitter/.py = (ImportError, OSError, ValueError, RuntimeError) -- a 4-member subset. The exception_sets.py module was created to centralize this, but only covers one case; three other ad-hoc tuples remain module-local.",
"suggestion": "Consolidate recoverable-error exception tuples into core/exception_sets.py with named sets for each domain (plan loading, language resolution, tree-sitter init). Modules should import these rather than defining local variants.",
"confidence": "high"
},
{
"dimension": "mid_level_elegance",
"identifier": "planning-init-double-indirection",
"summary": "engine/planning/.py uses *args/**kwargs pass-through wrappers that lazily import engine/planning/core, which itself is a pure re-export facade -- creating a two-layer indirection chain with no added policy or translation at either layer.",
"related_files": [
"desloppify/engine/planning/.py",
"desloppify/engine/planning/core.py"
],
"evidence": "engine/planning/.py defines generate_plan_md(*args, **kwargs) which calls _core_module().generate_plan_md(_NAMESPACE_SHIM variables since they are unused and add no value. If they were intended as import guards or debugging markers, add a comment explaining their purpose, or replace with a more conventional approach.",
"confidence": "high"
},
{
"dimension": "error_consistency",
"identifier": "orphaned-file-loc-silent-zero-on-read-failure",
"summary": "orphaned.py's _file_loc silently returns 0 on read failure, which can cause the caller to skip valid orphaned files without any logging, unlike every other detector in the same package that uses log_best_effort_failure.",
"related_files": [
"desloppify/engine/detectors/orphaned.py",
"desloppify/engine/detectors/large.py",
"desloppify/engine/detectors/complexity.py",
"desloppify/core/fallbacks.py"
],
"evidence": "orphaned.py _file_loc (line 73-78): 'try: return len(Path(filepath).read_text().splitlines()) except (OSError, UnicodeDecodeError): return 0'. No logging, no fallback warning. By contrast, large.py (line 25-31) catches the same exceptions and calls log_best_effort_failure(logger, ..., exc). complexity.py (line 140-146) does the same. coupling.py (line 169-175) does the same. The detect_orphaned_files function then does 'if loc < 10: continue', silently discarding any file that failed to read (since loc=0 < 10), with no indication the file was skipped due to an I/O error rather than genuinely being small.",
"suggestion": "Add log_best_effort_failure to _file_loc (or its caller) consistent with the pattern used by every other detector in the package, so that I/O failures during orphaned-file detection are at least visible in debug logs.",
"confidence": "high"
}
]
}
Assistant
Now I have enough comprehensive evidence. Let me compose the final assessment.
{
"assessments": {
"cross_module_architecture": 62,
"high_level_elegance": 68,
"test_strategy": 58,
"package_organization": 55
},
"findings": [
{
"dimension": "cross_module_architecture",
"identifier": "engine-reaches-into-core-internal",
"summary": "Engine modules violate core._internal boundary by importing DynamicPathProxy directly from desloppify.core._internal.path_proxy",
"related_files": [
"desloppify/engine/_state/schema.py",
"desloppify/engine/_plan/persistence.py",
"desloppify/core/_internal/path_proxy.py"
],
"evidence": "engine/_state/schema.py line 10: from desloppify.core._internal.path_proxy import DynamicPathProxy. engine/_plan/persistence.py line 12: from desloppify.core._internal.path_proxy import DynamicPathProxy. The _internal prefix conventionally marks package-private modules. Two engine subpackages reach across the core boundary into private internals. No architecture test guards this boundary (test_import_boundaries.py and test_architecture_boundaries.py do not check _internal access). DynamicPathProxy is already re-exported via core.pathing.api, so engine modules could import from there.",
"suggestion": "Export DynamicPathProxy through core.pathing.api (or a dedicated core-level public module) and update engine imports to use the public path. Add an architecture guardrail test that prevents non-core modules from importing core._internal.",
"confidence": "high"
},
{
"dimension": "cross_module_architecture",
"identifier": "scoring-shim-still-used-in-production",
"summary": "20 production modules import from desloppify.scoring (a legacy compatibility shim) instead of the canonical desloppify.engine._scoring path, and no import guard test prevents this drift",
"related_files": [
"desloppify/scoring.py",
"desloppify/compat/scoring.py",
"desloppify/engine/_work_queue/helpers.py",
"desloppify/engine/planning/dimension_rows.py",
"desloppify/engine/planning/render.py",
"desloppify/intelligence/narrative/dimensions.py",
"desloppify/intelligence/narrative/action_engine.py",
"desloppify/core/issues_render.py",
"desloppify/languages/_framework/generic.py",
"desloppify/tests/core/test_compat_import_guards.py"
],
"evidence": "desloppify/scoring.py is a shim: from desloppify.compat.scoring import * # noqa: F401,F403. Grep finds 20 production files importing from desloppify.scoring (e.g. engine/_work_queue/helpers.py, engine/planning/dimension_rows.py, intelligence/narrative/dimensions.py, languages/_framework/generic.py). Meanwhile test_compat_import_guards.py only guards against desloppify.utils and desloppify.file_discovery -- the _ALLOWED_COMPAT_MODULES set does not include desloppify/scoring.py and the guard test never checks for it. This means the migration is incomplete and unguarded: engine-layer code imports through a root-level shim that traverses compat before reaching engine._scoring.",
"suggestion": "Either migrate all 20 production callers to import directly from desloppify.engine.*.py files contain primarily import-and-assert-callable smoke tests that verify importability but not behavioral correctness of critical modules",
"related_files": [
"desloppify/tests/commands/test_direct_coverage_modules.py",
"desloppify/tests/commands/test_direct_coverage_additional_modules.py",
"desloppify/tests/commands/test_direct_coverage_split_modules.py",
"desloppify/tests/commands/test_direct_coverage_helpers.py"
],
"evidence": "test_direct_coverage_modules.py has 5 test functions that collectively call on approximately 120 targets and on another 6. The dominant pattern is: import module, assert function is callable, no invocation. test_direct_coverage_additional_modules.py follows the same pattern with 5 more functions. test_direct_coverage_split_modules.py has 16 calls in test_split_module_direct_coverage_smoke_signals. While these guarantee importability (no syntax errors, no circular imports), they verify zero behavioral contracts -- the functions could return wrong results, crash on valid inputs, or violate type contracts, and these tests would still pass.",
"suggestion": "Supplement smoke tests with behavioral tests for the most critical functions. For example, merge_batch_results, build_review_packet, run_scan_generation, and build_open_plan_queue are all asserted callable but never invoked in these files. Even minimal input/output assertions would catch regressions.",
"confidence": "high"
},
{
"dimension": "test_strategy",
"identifier": "no-architecture-guard-for-internal-boundary",
"summary": "The core._internal boundary is not enforced by any architecture test, allowing engine modules to silently depend on private core internals",
"related_files": [
"desloppify/tests/detectors/test_architecture_boundaries.py",
"desloppify/tests/lang/common/test_import_boundaries.py",
"desloppify/tests/core/test_compat_import_guards.py"
],
"evidence": "test_architecture_boundaries.py only checks that engine/detectors don't import language modules. test_import_boundaries.py checks that command/output layers use public facades (not core.file_paths or core.source_discovery), and that detectors don't import lang modules. test_compat_import_guards.py checks that runtime code doesn't import desloppify.utils or desloppify.file_discovery. None of these tests check whether non-core modules import from core._internal. The existing violations in engine/_state/schema.py and engine/_plan/persistence.py demonstrate the gap is actively exploited.",
"suggestion": "Add an architecture test that scans all non-core Python files and asserts none import from desloppify.core._internal. This would parallel the existing test_command_and_output_layers_use_public_core_facades test but for the _internal boundary.",
"confidence": "high"
},
{
"dimension": "package_organization",
"identifier": "core-package-has-parallel-flat-and-structured-namespaces",
"summary": "The core package has 24 root-level .py files alongside 3 structured subpackages (discovery/, pathing/, io/) that duplicate the same functionality through shim layers",
"related_files": [
"desloppify/core/.py",
"desloppify/core/output.py",
"desloppify/core/io/api.py",
"desloppify/core/io/impl.py",
"desloppify/core/file_paths.py",
"desloppify/core/pathing/api.py",
"desloppify/core/pathing/impl.py",
"desloppify/core/source_discovery.py",
"desloppify/core/discovery/api.py",
"desloppify/core/discovery/impl.py",
"desloppify/core/output_api.py",
"desloppify/core/paths_api.py",
"desloppify/core/discovery_api.py"
],
"evidence": "For the output/IO concern alone, there are 5 files: core/output.py (impl), core/io/api.py (pure pass-through to output.py), core/io/impl.py (star-import from output.py), core/output_api.py (deprecated wrapper to io/api.py), and core/io/.py. core/io/api.py's colorize function body is literally -- every function is a 1:1 forwarding delegate. The impl.py files in all three subpackages are star-import shims: e.g. . This creates a 3-layer indirection: caller -> core/io/api.py -> core/output.py. The same duplication exists for pathing (core/file_paths.py + core/pathing/api.py + core/pathing/impl.py + core/paths_api.py) and discovery (core/source_discovery.py + core/discovery/api.py + core/discovery/impl.py + core/discovery_api.py).",
"suggestion": "Complete the migration by making the structured packages (core/io, core/pathing, core/discovery) the canonical locations for both API and implementation, then remove the redundant flat files (core/output.py, core/file_paths.py, core/source_discovery.py) and deprecated wrappers (core/output_api.py, core/paths_api.py, core/discovery_api.py). The impl.py shims can be eliminated if the implementation code is moved into the subpackage directly.",
"confidence": "high"
},
{
"dimension": "package_organization",
"identifier": "triple-layer-compat-shims-for-scoring",
"summary": "Scoring exports traverse three shim layers: desloppify.scoring -> desloppify.compat.scoring -> desloppify.engine._scoring submodules",
"related_files": [
"desloppify/scoring.py",
"desloppify/compat/scoring.py",
"desloppify/engine/_scoring/policy/core.py",
"desloppify/engine/_scoring/results/core.py",
"desloppify/engine/_scoring/detection.py"
],
"evidence": "desloppify/scoring.py: . desloppify/compat/scoring.py: imports from 3 engine._scoring submodules and re-exports ~34 symbols. 20 production files import through the root-level scoring.py shim. The compat layer for file_discovery and utils has import guards preventing production use, but scoring has no such guard, meaning this triple-hop import chain is the active production path for all scoring symbols.",
"suggestion": "Either promote desloppify.compat.scoring as the stable public API (eliminating the root scoring.py shim) or migrate callers directly to engine._scoring submodules. The three-layer chain adds no policy, translation, or value -- each layer is a pure pass-through.",
"confidence": "high"
},
{
"dimension": "high_level_elegance",
"identifier": "api-impl-split-adds-indirection-without-policy",
"summary": "The core/io, core/pathing, and core/discovery subpackages each have an api.py and impl.py, but both are pure pass-through wrappers that add no policy, validation, or translation over the flat implementation files they delegate to",
"related_files": [
"desloppify/core/io/api.py",
"desloppify/core/io/impl.py",
"desloppify/core/pathing/api.py",
"desloppify/core/pathing/impl.py",
"desloppify/core/discovery/api.py",
"desloppify/core/discovery/impl.py",
"desloppify/core/output.py",
"desloppify/core/file_paths.py",
"desloppify/core/source_discovery.py"
],
"evidence": "core/io/api.py has 7 public functions; every single one is a 1-line delegation to core.output with identical signatures: . core/io/impl.py is . core/pathing/api.py similarly delegates every function 1:1 to core.file_paths. core/discovery/api.py delegates to core.source_discovery. The api/impl split implies a boundary with different consumers, but impl.py is never imported by any production code -- it exists only as a structural artifact. The api.py files add no validation, no access control, no type narrowing -- they are identity functions.",
"suggestion": "If the goal is to provide stable import paths (core.io.api, core.pathing.api, core.discovery.api), move the actual implementation into these modules rather than maintaining separate implementation files. Eliminate the impl.py files which serve no purpose.",
"confidence": "high"
},
{
"dimension": "test_strategy",
"identifier": "state-persistence-atomic-write-not-tested-for-crash-safety",
"summary": "State persistence uses atomic temp+rename writes, but no test verifies crash-safety properties (interrupted write, concurrent access, or disk-full scenarios)",
"related_files": [
"desloppify/engine/_state/persistence.py",
"desloppify/tests/state/test_state.py",
"desloppify/core/file_paths.py"
],
"evidence": "state.py facade exports load_state and save_state (71 importers). test_state.py tests finding lifecycle, merge logic, and noise budgets -- it tests save_state/load_state roundtrips but never verifies atomic write semantics (the test never interrupts a write, checks for .bak files, or validates temp file cleanup). The safe_write_text function in core/file_paths.py implements the atomic write pattern. Given that state files are the tool's most critical persistent artifact (corrupted state = lost analysis), the lack of atomicity testing is a coverage gap for a critical path.",
"suggestion": "Add tests that verify: (1) a .bak file is created before overwrite, (2) the written file is valid JSON after save, (3) interrupting save_state mid-write does not corrupt the previous state file. These can use monkeypatching to simulate write failures.",
"confidence": "medium"
}
]
}
Assistant
That file has 8 isinstance checks in a single file that primarily deals with dict-typed state. That's a common defensive-coding AI pattern when the types should be known from the state schema.
Now let me look for the coerce_ pattern which is a classic sign of over-defensive AI code.
Assistant
So output_api.py and paths_api.py are only imported by test files. They exist as deprecated shims with no production callers. Let me now also confirm discovery_api.py callers are test-only.
Already confirmed earlier: discovery_api.py is imported by 3 test files only.
Now I have comprehensive evidence. Let me produce the assessment.
{
"assessments": {
"package_organization": 52,
"high_level_elegance": 58
},
"findings": [
{
"dimension": "package_organization",
"identifier": "core-api-impl-over-structure",
"summary": "core/discovery/, core/io/, and core/pathing/ each contain 3 files (80-130 LOC total) that are pure pass-through wrappers around sibling flat modules, creating a 4-layer forwarding chain with no added logic",
"related_files": [
"desloppify/core/discovery/init.py",
"desloppify/core/discovery/api.py",
"desloppify/core/discovery/impl.py",
"desloppify/core/io/init.py",
"desloppify/core/io/api.py",
"desloppify/core/io/impl.py",
"desloppify/core/pathing/init.py",
"desloppify/core/pathing/api.py",
"desloppify/core/pathing/impl.py",
"desloppify/core/source_discovery.py",
"desloppify/core/output.py",
"desloppify/core/file_paths.py"
],
"evidence": "Each api.py is a 1-to-1 forwarding layer: e.g., core/io/api.py has def colorize(text, color): return output_mod.colorize(text, color) for every function from core/output.py. Each impl.py is from desloppify.core.X import * (10 LOC). The impl modules are exported in init.py but zero callers import them (discovery.impl, io.impl, pathing.impl produce zero grep hits). The real logic stays in the flat modules (source_discovery.py, output.py, file_paths.py). This creates a directory-per-module structure where each package has 80-132 LOC of pure delegation, adding 322 LOC of forwarding code across the three packages.",
"suggestion": "Either move the logic into the package modules (making api.py the real implementation rather than a forwarder), or remove the sub-packages and import directly from the flat modules. The impl.py files can be removed entirely since they have no consumers.",
"confidence": "high"
},
{
"dimension": "package_organization",
"identifier": "review-orchestration-trivial-package",
"summary": "review/orchestration/ is a 3-file package (19 LOC total, excluding init.py) containing a single 11-line function and a single 7-line constant definition",
"related_files": [
"desloppify/app/commands/review/orchestration/init.py",
"desloppify/app/commands/review/orchestration/helpers.py",
"desloppify/app/commands/review/orchestration/runtime_defaults.py"
],
"evidence": "helpers.py contains exactly one function parse_dimensions (11 LOC). runtime_defaults.py contains exactly one constant (7 LOC). Both are imported by files in the parent review/ directory (batch.py, preflight.py, prepare.py, external.py) and by runtime/policy.py. The package overhead (.py + directory) exceeds the content.",
"suggestion": "Merge these into the parent review/ directory -- the constant could live in the existing payload/constants.py module or a shared constants module, and parse_dimensions could live in the parent .py or entrypoint.py.",
"confidence": "high"
},
{
"dimension": "package_organization",
"identifier": "review-quality-single-file-package",
"summary": "review/quality/ is a package containing exactly one 77-line file, imported by exactly one caller",
"related_files": [
"desloppify/app/commands/review/quality/.py",
"desloppify/app/commands/review/quality/assessment_integrity.py",
"desloppify/app/commands/review/import_cmd.py"
],
"evidence": "quality/assessment_integrity.py (77 LOC) is imported only by import_cmd.py. The package has a blank .py (1 line docstring). A single-file package with one consumer adds directory overhead without providing navigability or ownership benefits.",
"suggestion": "Move assessment_integrity.py to the parent review/ directory or co-locate with its sole consumer import_cmd.py.",
"confidence": "high"
},
{
"dimension": "package_organization",
"identifier": "review-importing-single-file-package",
"summary": "review/importing/ is a package wrapping exactly one large file (import_helpers.py, 1301 LOC)",
"related_files": [
"desloppify/app/commands/review/importing/.py",
"desloppify/app/commands/review/importing/import_helpers.py"
],
"evidence": "The importing/ directory contains .py (empty, 1 line) plus import_helpers.py (1301 LOC). The module is imported by import_cmd.py via and by one test file. A large file justified for domain complexity does not benefit from being the sole occupant of a sub-package -- the directory boundary adds no organizational clarity.",
"suggestion": "Flatten import_helpers.py into the parent review/ directory. If the file needs splitting, that split should create the sub-package with multiple focused files.",
"confidence": "high"
},
{
"dimension": "package_organization",
"identifier": "review-normalization-single-file-package",
"summary": "review/normalization/ is a package wrapping exactly one file (batch_core.py, 887 LOC)",
"related_files": [
"desloppify/app/commands/review/normalization/.py",
"desloppify/app/commands/review/normalization/batch_core.py"
],
"evidence": "The normalization/ directory contains .py (empty, 1 line) plus batch_core.py (887 LOC). Imported by batches.py and batch.py via . Same pattern as the importing/ package: a single large file wrapped in a sub-package with no co-located siblings.",
"suggestion": "Flatten batch_core.py into the parent review/ directory, or split it into multiple files to justify the sub-package.",
"confidence": "high"
},
{
"dimension": "high_level_elegance",
"identifier": "multi-layer-compat-forwarding-chain",
"summary": "Four-layer compatibility forwarding chain exists from root shims through compat/ to core/ sub-packages to flat implementation modules, making the canonical import path non-obvious",
"related_files": [
"desloppify/utils.py",
"desloppify/compat/utils.py",
"desloppify/core/io/api.py",
"desloppify/core/output.py",
"desloppify/file_discovery.py",
"desloppify/compat/file_discovery.py",
"desloppify/core/discovery/api.py",
"desloppify/core/source_discovery.py",
"desloppify/scoring.py",
"desloppify/compat/scoring.py",
"desloppify/core/discovery_api.py",
"desloppify/core/output_api.py",
"desloppify/core/paths_api.py"
],
"evidence": "A call to from root utils.py traverses: utils.py -> compat/utils.py -> core/io/api.py -> core/output.py (4 hops). The root shim has 30+ active production callers (), while and have zero production callers (only test files verify they work). The coexistence of (compatibility facade), (canonical), and (another compat layer) for the same surface creates three parallel import paths for identical functionality.",
"suggestion": "Eliminate the layers: (1) Remove output_api.py and paths_api.py since they have no production callers. (2) Migrate the 30+ callers of root scoring.py to import directly from engine._scoring. (3) Consolidate the discovery compat shims into a single redirect.",
"confidence": "high"
},
{
"dimension": "high_level_elegance",
"identifier": "core-flat-directory-mixed-concerns",
"summary": "core/ directory contains 24 files mixing real logic modules, shim/facade modules, and tiny constant-only modules with no organizing principle distinguishing them",
"related_files": [
"desloppify/core/output.py",
"desloppify/core/output_api.py",
"desloppify/core/output_contract.py",
"desloppify/core/paths_api.py",
"desloppify/core/discovery_api.py",
"desloppify/core/file_paths.py",
"desloppify/core/source_discovery.py",
"desloppify/core/coercions_api.py",
"desloppify/core/text_api.py",
"desloppify/core/score_targets.py",
"desloppify/core/exception_sets.py",
"desloppify/core/nonfatal.py",
"desloppify/core/signal_patterns.py"
],
"evidence": "The 24-file directory contains: (a) real implementations (output.py, source_discovery.py, file_paths.py, registry.py, config.py), (b) deprecated shims with zero production callers (output_api.py, paths_api.py), (c) compat facades (discovery_api.py), (d) thin API re-export wrappers (coercions_api.py at 19 LOC, text_api.py at 46 LOC), and (e) tiny constant-only modules (score_targets.py at 13 LOC, exception_sets.py at 14 LOC). A new contributor cannot predict which file is the canonical import target for a given concern without reading documentation.",
"suggestion": "Remove the dead shims (output_api.py, paths_api.py). Consolidate the tiny constant modules (score_targets.py, exception_sets.py) into their nearest consumer or an existing related module.",
"confidence": "medium"
},
{
"dimension": "package_organization",
"identifier": "coercions-api-unnecessary-wrapper",
"summary": "coercions_api.py (19 LOC) is a pure re-export wrapper around core/_internal/coercions.py that adds no logic, typing, or policy",
"related_files": [
"desloppify/core/coercions_api.py",
"desloppify/core/_internal/coercions.py",
"desloppify/app/commands/review/runtime/policy.py"
],
"evidence": "coercions_api.py is entirely followed by an repeating the same names. The _internal/coercions.py module has no import-time side effects and contains pure functions. The api wrapper adds zero type narrowing, no default overrides, and no additional validation. It exists solely to hide the prefix, but callers already use the full path which is not materially simpler than .",
"suggestion": "Either move coercions.py from _internal/ to core/ directly, or have callers import from core._internal.coercions (the underscore prefix is already a convention, not a barrier).",
"confidence": "medium"
}
]
}
Assistant
There are 13 coerce_ functions scattered across the codebase. Let me check if some are duplicated.
Assistant
The coerce_int and coerce_float in scan_coverage.py are nearly identical to coerce_positive_int/coerce_positive_float in core/_internal/coercions.py -- duplicated coercion logic.
Now let me look for the Planned removal dates in compat files and check if any of those dates have passed.
Assistant
Planned removal is 2026-09-30, current date is 2026-03-01. These are still within their stated lifecycle.
Now let me look more broadly for the low_level_elegance dimension. Let me check some files for control flow quality.
Assistant
Note that coerce_target_score checks is_numeric(fallback) but fallback is already typed as float - this is defensive overengineering. The fallback parameter is always a float literal.
Let me also check the coerce_notice_count function for the same pattern.
Assistant
Now let me check whether there's a four-layer indirection for the io/api.py pattern. Let me trace where imports actually come from.
The core/io/api.py is the "canonical" surface, but it just wraps core/output.py. This is a pure forwarding layer. Each function call goes: caller -> core/io/api.py -> core/output.py. That's one extra hop for stable import paths. This is a design choice (facade pattern) and may or may not be considered "debt" depending on perspective. Since the MEMORY.md says "Intentional package facades used to stabilize public import paths" is in the skip list for abstraction_fitness, I should be careful here. But the dimension definitions do say to look for "Pass-through wrapper functions with no added logic" under ai_generated_debt.
Let me now check the engine/_scoring/subjective/display_names.py and other split-out modules.
Assistant
Now let me look at some more modules to build confidence in the AI-generated-debt assessment. Let me read the TypeScript/phase_policies.py new file.
Assistant
Let me now check the _ = lines pattern which is an AI-debt indicator (unused parameter that's just assigned to nothing).
Assistant
The _ = refresh at line 85 and _ = colorize_fn at line 968 are unused parameters just suppressed rather than being removed from the signature.
Now I have a good picture. Let me compile my findings for the assessment. Let me verify one more thing - the depth of indirection for the review module's legacy aliases.
Assistant
Good. Let me also look at the tests/core/test_compat_import_guards.py to understand the expected behavior.
Assistant
This confirms there IS an active migration from desloppify.utils and desloppify.file_discovery to the new API surfaces. The test enforces that runtime code doesn't use the old imports, but tests are still allowed to.
Let me also check the tests that still import from deprecated paths.
Assistant
Now I have enough evidence. Let me compile the final assessment.
Let me do one last check on the core/io/api.py pattern -- is there a core/io/__init__.py?
Assistant
So there are __init__.py namespace shims, api.py surfaces, and impl.py shims -- all for each of io, discovery, and pathing. That's a lot of structural indirection for what amounts to core/output.py, core/source_discovery.py, and core/file_paths.py.
Let me verify one more thing: impl.py files -- does anyone import from them?
Assistant
The impl.py files have zero importers. They're dead code -- namespace shims that nothing uses.
Let me also look at how scoring.py callers could import directly.
Assistant
Good. So only the engine internals and the compat shim import from engine._scoring directly. All external callers go through desloppify.scoring (the root shim).
Now I have a thorough picture. Let me produce the final assessment.
{
"assessments": {
"ai_generated_debt": 38,
"incomplete_migration": 42,
"low_level_elegance": 72
},
"findings": [
{
"dimension": "ai_generated_debt",
"identifier": "state_access_pure_forwarding",
"summary": "state_access.py contains 7 functions that each forward a single call to state_mod with no added logic, policy, or translation. Each has a docstring that merely restates the forwarded call.",
"related_files": [
"desloppify/app/commands/helpers/state_access.py"
],
"evidence": "Every function is a one-liner delegating to state_mod: load_state_file calls state_mod.load_state, save_state_file calls state_mod.save_state, resolve_matching_findings calls state_mod.match_findings, snapshot_scores calls state_mod.score_snapshot, remove_ignored_findings calls state_mod.remove_ignored_findings, coerce_assessment_score calls state_mod.coerce_assessment_score, utc_timestamp calls state_mod.utc_now. Each has a docstring like 'Load state from one explicit state path (or default when None)' that restates the function name. Only 2 callers exist across the codebase.",
"suggestion": "Delete the module and have the 2 callers import directly from desloppify.state.",
"confidence": "high"
},
{
"dimension": "ai_generated_debt",
"identifier": "io_api_pure_forwarding",
"summary": "core/io/api.py is a pure pass-through wrapper around core/output.py, forwarding every function and constant with zero added logic, policy, or type narrowing.",
"related_files": [
"desloppify/core/io/api.py",
"desloppify/core/output.py"
],
"evidence": "Every export in io/api.py delegates directly: colorize calls output_mod.colorize, log calls output_mod.log, print_table calls output_mod.print_table, display_entries calls output_mod.display_entries. Constants are literal aliases: LOC_COMPACT_THRESHOLD = output_mod.LOC_COMPACT_THRESHOLD. There are 90 importers of this module. None of the wrappers add auth, caching, validation, or any other behavior.",
"suggestion": "If the intent is import-path stability, use re-exports (from ... import ... as ...) rather than manually defining wrapper functions that add a runtime call frame.",
"confidence": "high"
},
{
"dimension": "ai_generated_debt",
"identifier": "coerce_target_score_defensive_fallback_check",
"summary": "coerce_target_score validates its own fallback parameter with is_numeric() despite it being typed as float and always called with float literals.",
"related_files": [
"desloppify/app/commands/helpers/score.py"
],
"evidence": "Lines 10-13: . The parameter is . Every call site passes a literal float (95.0, 97.0, 96.0). Checking is_numeric on a known float parameter is pure defensive overengineering.",
"suggestion": "Remove the is_numeric guard on fallback and use directly.",
"confidence": "high"
},
{
"dimension": "ai_generated_debt",
"identifier": "duplicated_coercion_functions",
"summary": "coerce_int/coerce_float in scan_coverage.py duplicate the logic already provided by core/_internal/coercions.py (coerce_positive_int, coerce_non_negative_float, etc.).",
"related_files": [
"desloppify/app/commands/scan/scan_coverage.py",
"desloppify/core/_internal/coercions.py",
"desloppify/core/coercions_api.py"
],
"evidence": "scan_coverage.py defines coerce_int (lines 10-25) and coerce_float (lines 28-41) with the same isinstance-chain pattern (bool -> int -> float -> str -> default) as coerce_positive_int/coerce_non_negative_float in core/_internal/coercions.py. The canonical API is already exported through core/coercions_api.py.",
"suggestion": "Replace local coerce_int/coerce_float with the canonical coerce_non_negative_int/coerce_non_negative_float from core/coercions_api.",
"confidence": "high"
},
{
"dimension": "incomplete_migration",
"identifier": "impl_shims_zero_importers",
"summary": "core/io/impl.py, core/discovery/impl.py, and core/pathing/impl.py are star-import shims with zero importers.",
"related_files": [
"desloppify/core/io/impl.py",
"desloppify/core/discovery/impl.py",
"desloppify/core/pathing/impl.py"
],
"evidence": "Grep for 'from desloppify.core.(io|discovery|pathing).impl' returns zero matches across the entire codebase. These files exist only as structural placeholders from the api/impl namespace split but serve no runtime or test purpose. Each is a 10-line star-import shim (e.g., ).",
"suggestion": "Delete the three impl.py files and remove their imports from the respective .py modules.",
"confidence": "high"
},
{
"dimension": "incomplete_migration",
"identifier": "scoring_three_hop_chain",
"summary": "Importing from desloppify.scoring traverses a 3-module chain (scoring.py -> compat/scoring.py -> engine/_scoring/*) with 30+ active callers still using the root-level path.",
"related_files": [
"desloppify/scoring.py",
"desloppify/compat/scoring.py",
"desloppify/engine/_scoring/policy/core.py",
"desloppify/engine/_scoring/results/core.py"
],
"evidence": "scoring.py is a 'Legacy root shim' that star-imports from compat/scoring.py, which in turn imports from engine/_scoring/policy/core.py and engine/_scoring/results/core.py. There are 30+ production callers (e.g., engine/planning/render.py, app/commands/status_parts/render.py, intelligence/narrative/dimensions.py) that use . Unlike file_discovery and utils, there is no deprecation warning and no compat import guard test preventing new code from using the root shim.",
"suggestion": "Add a deprecation warning to desloppify.scoring and add it to the compat import guard test, then migrate callers to import from desloppify.compat.scoring or directly from engine._scoring submodules.",
"confidence": "high"
},
{
"dimension": "incomplete_migration",
"identifier": "review_legacy_module_aliases_many_callers",
"summary": "review/.py provides _LEGACY_MODULE_ALIASES for runner_helpers and batch_core via , with 20+ test callers still using the old import paths.",
"related_files": [
"desloppify/app/commands/review/.py",
"desloppify/tests/review/test_review_commands.py",
"desloppify/tests/commands/test_review_batch_core_direct.py",
"desloppify/tests/review/test_review_batch_core.py"
],
"evidence": "review/.py declares . Grep shows 18 instances of in test_review_commands.py and 2 instances of in test files. The modules were moved to subdirectories but the old import paths persist through with no deprecation warning or migration plan.",
"suggestion": "Update test imports to use the new paths (runtime.runner_helpers, normalization.batch_core) and remove the legacy aliases from .py.",
"confidence": "high"
},
{
"dimension": "incomplete_migration",
"identifier": "discovery_api_deprecated_still_imported",
"summary": "core/discovery_api.py emits DeprecationWarning for path helpers but 4 test files still import from it.",
"related_files": [
"desloppify/core/discovery_api.py",
"desloppify/tests/core/test_runtime_state.py",
"desloppify/tests/core/test_utils.py",
"desloppify/tests/review/test_review_misc.py"
],
"evidence": "discovery_api.py's emits DeprecationWarning for path helpers and the module is labeled as a 'Compatibility facade.' Four test files still import from it: test_runtime_state.py, test_utils.py (twice), and test_review_misc.py. These should use core.discovery.api or core.pathing.api instead.",
"suggestion": "Update the 4 test files to import from the canonical core.discovery.api and core.pathing.api modules.",
"confidence": "high"
},
{
"dimension": "low_level_elegance",
"identifier": "subjective_rerun_command_unused_refresh_param",
"summary": "subjective_rerun_command accepts a refresh parameter that is immediately discarded with .",
"related_files": [
"desloppify/app/output/subjective_reporting.py"
],
"evidence": "Line 85: immediately after the function signature . The parameter is never used in the function body. This is dead interface surface that adds confusion to callers.",
"suggestion": "Remove the refresh parameter from the function signature and all call sites.",
"confidence": "high"
},
{
"dimension": "low_level_elegance",
"identifier": "selection_dependencies_excessive_isinstance_guards",
"summary": "selection_dependencies.py has 8 isinstance checks guarding dict/list/str/int values that should be structurally guaranteed by the state schema.",
"related_files": [
"desloppify/intelligence/review/context_holistic/selection_dependencies.py"
],
"evidence": "The file processes state findings which follow the Finding TypedDict schema. Despite this, every access is wrapped in isinstance checks: at line 16, at lines 27 and 44, at line 30, at line 34, at line 47, at line 95. The state schema guarantees these types; the guards are defensive sprawl that obscures the actual logic.",
"suggestion": "Trust the state schema types. Replace isinstance guards with direct access and let TypeErrors surface schema violations rather than silently returning empty results.",
"confidence": "medium"
},
{
"dimension": "ai_generated_debt",
"identifier": "compute_ts_inline_types_unused_lines_param",
"summary": "compute_ts_inline_types accepts a lines parameter then immediately discards it with .",
"related_files": [
"desloppify/languages/typescript/phase_policies.py"
],
"evidence": "Line 19-21: followed immediately by . The function only uses . The parameter exists solely to match the ComplexitySignal.compute callback signature , but this is a sign of a rigid callback interface forcing unnecessary parameters.",
"suggestion": "Change the ComplexitySignal.compute callback type to accept **kwargs or make lines optional, so implementations don't need to accept unused parameters.",
"confidence": "medium"
}
]
}
User
I need you to create the final review_result.json file by reading the current template and adding all findings from the 9 review batches.
Read the current file at: /Users/user_c042661f/Documents/desloppify/.desloppify/external_review_sessions/ext_20260228_233656_9ea6b4e8/review_result.json
It already has the assessments. You need to add ALL findings from the 9 batches below into the "findings" array. Each finding must have: dimension, identifier, summary, related_files (as array of strings), evidence (as string), suggestion (as string), confidence (as string).
IMPORTANT: For any finding where "evidence" was returned as an array, concatenate the array items into a single string separated by ". ".
Here are ALL findings from all 9 batches - add every single one:
BATCH 1 findings:
dimension: cross_module_architecture, identifier: engine_imports_app_layer, summary: "The engine layer (engine/planning/dimension_rows.py) imports from the app layer (app/output/scorecard_parts/dimensions.py), violating the downward-only dependency rule.", related_files: ["desloppify/engine/planning/dimension_rows.py", "desloppify/app/output/scorecard_parts/dimensions.py"], evidence: "desloppify/engine/planning/dimension_rows.py line 9 imports from app layer", suggestion: "Move prepare_scorecard_dimensions into engine/planning layer", confidence: high
dimension: cross_module_architecture, identifier: facade_indirection_explosion, summary: "Core utility functions like read_code_snippet are accessible through 5+ distinct import paths, creating confusion about which is canonical.", related_files: ["desloppify/core/_internal/text_utils.py", "desloppify/core/text_api.py", "desloppify/core/pathing/api.py", "desloppify/core/paths_api.py", "desloppify/compat/utils.py", "desloppify/utils.py"], evidence: "read_code_snippet defined at core/_internal/text_utils.py:30, re-exported through 5 different modules", suggestion: "Remove zero-caller shims and consolidate to one canonical path per function", confidence: high
dimension: cross_module_architecture, identifier: dead_compat_shims_persist, summary: "Three compatibility facade modules (core/paths_api.py, core/output_api.py, core/discovery_api.py) have zero production callers.", related_files: ["desloppify/core/paths_api.py", "desloppify/core/output_api.py", "desloppify/core/discovery_api.py"], evidence: "grep for imports from these modules returns 0 production results", suggestion: "Delete all three immediately", confidence: high
dimension: cross_module_architecture, identifier: coerce_assessment_score_duplication, summary: "Assessment score coercion logic is duplicated between engine state layer and review preflight with subtly different implementations.", related_files: ["desloppify/engine/_state/resolution.py", "desloppify/app/commands/review/preflight.py", "desloppify/app/commands/helpers/state_access.py"], evidence: "Two different _coerce_assessment_score implementations with different clamping/bool handling", suggestion: "Delete private version in preflight.py, use canonical engine version", confidence: high
Assistant
Let me start by reading the current file to understand its structure.
Assistant
Now I have the structure. I need to populate the findings array with all 66 findings from the 9 batches. Let me construct the complete JSON.
Assistant
Let me verify the file was written correctly by checking the finding count.
Assistant
The file has been written and validated successfully. Here is the summary:
Session metadata (id + token) preserved from the original
20 assessment dimensions with their scores preserved from the original
66 findings added from all 9 batches (Batches 1-9)
Validation results:
All 66 findings have all required fields: dimension, identifier, summary, related_files, evidence, suggestion, confidence
All evidence values are strings (no arrays)
All related_files values are arrays of strings
The JSON parses cleanly with no syntax errors
Findings by dimension:
design_coherence: 9 findings
abstraction_fitness: 8 findings
cross_module_architecture: 7 findings
package_organization: 6 findings
ai_generated_debt: 5 findings
incomplete_migration: 4 findings
convention_outlier, contract_coherence, error_consistency, high_level_elegance, initialization_coupling, type_safety: 3 each
api_surface_coherence, mid_level_elegance, test_strategy: 2 each
logic_clarity, low_level_elegance, naming_quality: 1 each
User
Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
Before providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
The user's explicit requests and intents
Your approach to addressing the user's requests
Key decisions, technical concepts and code patterns
Specific details like:
file names
full code snippets
function signatures
file edits
Errors that you ran into and how you fixed them
Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Double-check for technical accuracy and completeness, addressing each required element thoroughly.
Your summary should include the following sections:
Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
Assistant
User's initial request: Asked me to critically analyze the large set of uncommitted changes in the desloppify repository to determine if the refactoring is genuinely improving structure or just moving stuff around.
My initial analysis: I launched 5 parallel Task agents to analyze different areas:
review/ module refactoring
core/ module refactoring
compat/ and helpers refactoring
TypeScript plugin + framework refactoring
Test changes and utils.py refactoring
The conclusion was that ~30% was genuine improvement, ~50% was harmful/wasteful, ~20% was neutral. Key finding: the refactoring was mostly "cosmetic reorganization masquerading as structural improvement."
User asked to look at desloppify issues, scan, and plan: Wanted to understand the ROOT CAUSE of why the refactoring went wrong.
I ran desloppify scan, plan, status, show review, show subjective, etc.: Discovered the score was stuck at 76.9 for 10+ scans. Identified the feedback loop: tool flags low package_organization → agent reorganizes files → tool flags the new indirection → score doesn't move. The key insight was "the tool is eating its own tail."
User asked to re-run all subjective analysis from a clean slate: Wanted to clear all existing subjective assessments and review findings, then re-run everything.
User asked about running with Cloud sub-agents: I initially ran with Codex (--runner codex --parallel) because the tool's instructions said "Preferred: codex". The user asked why I wasn't using Claude sub-agents.
User pointed out the meta-problem: I was doing the same thing the refactoring agents did — mechanically following the tool's literal suggestion instead of exercising judgment. The tool said "use codex" so I used codex, just like the tool said "reorganize packages" so the refactoring reorganized packages.
I killed the Codex run and used Claude sub-agents instead: Used --external-start --external-runner claude to create a session, then spawned 9 parallel Task agents (one per batch) to do the review.
Assembling and importing results: Merged results from all 9 agents, fixed schema issues (evidence needed to be arrays, missing findings for dimensions below thresholds), and imported via --external-submit.
Comparison of fresh review vs manual analysis: The fresh review overwhelmingly confirmed my manual findings. Score was 76.1 (slightly worse than pre-reset 76.9). AI debt dropped from 87→38, incomplete migration from 63→42.
User
Very thorough exploration of the plan infrastructure in the desloppify codebase. I need to understand:
Plan schema (desloppify/engine/_plan/schema.py) - What does the plan data model look like? What fields exist? Is there already a concept of "epics" or "clusters"?
Auto-clustering (desloppify/engine/_plan/auto_cluster.py) - How does current clustering work? What does it group by? What's the output structure?
Reconciliation (desloppify/engine/_plan/reconcile.py) - What does reconcile do after scan? When is it triggered?
Plan operations (desloppify/engine/_plan/operations.py) - What mutations are available? Can items be moved, grouped, superseded?
Plan persistence (desloppify/engine/_plan/persistence.py) - How is plan.json read/written?
Plan facade - Look for engine/planning/ or any top-level plan module that orchestrates these.
Scan workflow integration (desloppify/app/commands/scan/scan_workflow.py) - Where does reconciliation currently get called? What's the trigger point?
Read all these files thoroughly and report back the full schema, data structures, function signatures, and integration points.
Assistant
I'll conduct a thorough exploration of the plan infrastructure in the desloppify codebase. Let me start by reading all the relevant files.
Assistant
Now let me read the persistence and facade files:
User
Very thorough exploration of the review import and subjective assessment flow in desloppify. I need to understand:
Review import command (desloppify/app/commands/review/import_cmd.py) - How are external review results imported? What does it do to state?
Intelligence review importing (desloppify/intelligence/review/importing/) - Read all files in this directory. How are findings processed during import?
State schema (desloppify/engine/_state/schema.py) - What does the state model look like? How are subjective assessments stored? How are findings stored?
State merge/filtering (desloppify/engine/_state/merge_findings.py, desloppify/engine/_state/filtering.py) - How are findings merged into state?
Subjective scoring (desloppify/engine/_scoring/subjective/core.py) - How are subjective dimension scores computed?
Review entrypoint (desloppify/app/commands/review/entrypoint.py) - The main review command flow.
Review batches (desloppify/app/commands/review/batches.py) - How batches are managed.
Read all these files thoroughly and report back the complete flow from "review results arrive" to "state is updated with new findings and assessments".
Assistant
Now let me read the plan.py facade file:
Assistant
Now let me read the stale_dimensions file:
Assistant
I'll conduct a thorough exploration of the review import and subjective assessment flow. Let me start by reading all the key files.
Assistant
Now let me read the intelligence review importing files:
User
Very thorough exploration of how desloppify uses LLM calls. I need to understand the patterns for making LLM API calls so the epic synthesis feature can follow the same patterns.
Scan reporting LLM (desloppify/app/commands/scan/scan_reporting_llm.py) - How does the scan LLM narrative work? What API is used? What model? How is the prompt structured?
Review prepare (desloppify/intelligence/review/prepare.py) - How are review prompts prepared?
Review prepare batches (desloppify/intelligence/review/prepare_batches.py) - How are batch prompts built?
Context holistic (desloppify/intelligence/review/context_holistic/) - Read all files. How is holistic context gathered for LLM review?
Narrative core (desloppify/intelligence/narrative/core.py) - How does compute_narrative work?
Selection (desloppify/intelligence/review/selection.py) - How are files selected for review?
Look for any LLM client/wrapper module - search for patterns like openai, anthropic, litellm, llm_call, chat_completion, etc. How does the codebase actually call LLMs?
Work queue (desloppify/engine/_work_queue/core.py, ranking.py, helpers.py) - How does the current work queue get built and ordered? This is the queue the synthesis would restructure.
Report the complete LLM integration pattern, including: client setup, prompt construction, response parsing, error handling, and how results flow into state.
Assistant
I'll conduct a thorough exploration of the LLM integration patterns in desloppify. Let me start by searching for LLM-related files and patterns.
Assistant
Now let me check the batches.py file more carefully and look for the import_helpers module referenced in import_cmd.py:
Assistant
Let me search more specifically for LLM and API patterns:
Assistant
Let me read the import_helpers file:
Assistant
Let me search for how the scan reporting LLM actually works:
Assistant
Let me continue reading import_helpers and also look for where findings are actually merged:
Assistant
Now let me check the review-related files for actual LLM integration:
Assistant
Now let me look at merge.py to understand how findings are merged into state:
Assistant
Now let me look at the context holistic files to understand how context is gathered:
Assistant
Let me read these files in parallel:
Assistant
Now let me search for actual LLM calls, and check the selection file:
Assistant
Now let me look for the work queue implementation:
Assistant
Let me search for actual API calls being made to external services:
Assistant
Let me look at the review runtime and batches files more closely:
Assistant
Let me look at the batch prompting structure and read the runner code:
Assistant
Let me search for where the actual subprocess commands are invoked to understand how review agents are called:
Assistant
Perfect! Now let me look for what the actual command is that gets executed (the Claude command):
Assistant
Now let me look at the actual codex command construction:
Assistant
Now let me find the codex_batch_command function:
Assistant
Perfect! Now I have all the information needed. Let me compile a comprehensive report on the plan infrastructure:
Comprehensive Plan Infrastructure Report
I've thoroughly explored the desloppify plan infrastructure. Here's the complete breakdown:
1. Plan Data Model (desloppify/engine/_plan/schema.py)
The plan is a versioned JSON document with these TypedDict structures:
Perfect! Now let me check a few more critical pieces - let me look for how prompts are built and what the data flow is:
Assistant
Perfect! Now I have enough information. Let me compile a comprehensive report on the review import and subjective assessment flow.
Complete Flow Report: Review Import to State Update
I've thoroughly explored the review import and subjective assessment flow in desloppify. Here's the complete end-to-end process from "review results arrive" to "state is updated with findings and assessments":
HIGH-LEVEL ARCHITECTURE
The review import system has three main entry points:
Holistic imports - codebase-wide review findings via import_holistic_findings()
Per-file imports - targeted per-file review findings via import_review_findings()
Builds HolisticContext from code analysis (architecture, coupling, conventions, errors, abstractions, testing, API surface, structure, auth, AI debt, migrations)
Creates investigation batches via build_investigation_batches()
Appends design-coherence batch from mechanical concern signals
Includes optional issue history context
User
Design an implementation plan for adding an "epic synthesis" feature to the desloppify CLI tool. This is an LLM-driven step that runs after subjective review findings are imported, clustering findings by root cause into "epics" with coherent theses, resolving contradictions, and ordering by dependency.
Context / Problem
The tool has a gap between "review findings land" and "agent executes work items." Currently:
Review produces independent observations across 20 dimensions (68 findings last run)
Auto-clustering groups by dimension/detector mechanically: auto/review-abstraction_fitness, auto/review-design_coherence, etc.
The work queue is a flat list — items that contradict each other coexist (e.g., "add tests for compat layer" alongside "delete compat layer")
Executing agents pick items one-by-one without understanding the coherent strategy
The result: agents do mechanical reorganization that doesn't move the score. They follow literal suggestions instead of understanding root causes.
What Epic Synthesis Does
After review findings land, an LLM step:
Reads ALL open findings (review, concerns, mechanical) + current plan state
Clusters by ROOT CAUSE, not dimension (e.g., "unnecessary compat layer" groups findings from abstraction_fitness, package_organization, ai_generated_debt)
Assigns a THESIS per epic (one-line directive like "Delete the compat/ layer — all callers should import from core directly")
Assigns a DIRECTION per epic (enum: delete, merge, flatten, enforce, simplify, decompose)
Identifies CONTRADICTIONS and marks one side as superseded
Orders epics by dependency (which must come first for others to make sense)
Tags epics as agent_safe (boolean) — can an LLM agent execute this without human judgment?
Groups findings by grouping key: review::dimension, file::detector::path, typed::detector::subtype, etc.
Auto-generates clusters with auto/ prefix
Preserves user-modified clusters
Entry: auto_cluster_findings(plan, state) -> int
Assistant
I'll start by thoroughly exploring the existing codebase to understand the current architecture, patterns, and integration points before designing the implementation plan.
Assistant
Now let me explore the LLM integration patterns, the review import flow, and the work queue to understand how synthesis should integrate.
Assistant
Now let me explore the LLM subprocess integration pattern, the CLI parser groups, and the plan init.py to understand subcommand registration.
Assistant
Let me now examine the subprocess/runner pattern more closely and look at how findings are structured in state.
Assistant
Now let me look at the existing engine/plan.py facade to understand the public API surface, and the _resolve.py module in plan to understand how plan/state interaction works.
Assistant
Let me look at how the codex exec subprocess is actually called and the prompt construction pattern.
Assistant
Let me now look at how the review prepare/packet building constructs prompts, and check the existing finding data structure for review findings.
Assistant
Let me look at how the scan reporting LLM block is built (to understand the prompt construction pattern) and the rendering of clusters in the queue.
Assistant
Now let me check the existing render_batch_prompt to understand the prompt construction pattern more deeply.
Assistant
Now I have a thorough understanding of the codebase. Let me examine one more area: how the _plan module is structured (its __init__.py) and how tests are organized.
Assistant
I now have a comprehensive understanding of the codebase architecture. Let me compile the detailed implementation plan.
Epic Synthesis Implementation Plan
1. Overview
The epic synthesis feature introduces an LLM-driven clustering step that runs after review findings are imported. It groups findings by root cause (not dimension/detector), assigns coherent theses and action directions, resolves contradictions, and orders by dependency. This plan details the exact files to create and modify, data structures, function signatures, and integration points.
2. Data Structures
2.1 New Epic TypedDict in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py
The Epic type extends the Cluster concept with strategic metadata. It should be defined alongside the existing Cluster TypedDict:
python
# Valid direction enum values
VALID_EPIC_DIRECTIONS = frozenset({
"delete", "merge", "flatten", "enforce",
"simplify", "decompose", "extract", "inline",
})
class Epic(TypedDict, total=False):
name: Required[str] # e.g. "epic/delete-compat-layer"
thesis: Required[str] # One-line directive
direction: Required[str] # One of VALID_EPIC_DIRECTIONS
root_cause: str # Root cause description
finding_ids: list[str] # All findings belonging to this epic
supersedes: list[str] # Finding IDs this epic's thesis contradicts
agent_safe: bool # Can an agent execute without human judgment?
dependency_order: int # Lower = must come first
action_steps: list[str] # Ordered concrete steps
source_clusters: list[str] # auto/ clusters this epic absorbed
created_at: str
updated_at: str
synthesis_version: int # For re-synthesis idempotency
auto: bool # Always True (LLM-generated)
This is not an API boundary -- it is a passthrough. The real module source_discovery.py (216 lines) already has well-defined functions with clear signatures. Wrapping them in another module adds no type safety, no validation, no abstraction. The sole behavioral change is converting Iterable[str] to list[str] in one call, which could be a one-line fix in the original.
The impl.py files are even worse -- they are literally from X import * re-exports. The docstring says "New code should prefer api" -- so what is impl.py for? It provides "access to implementation internals," but it exports the exact same __all__ as the original module. There is no split between public API and internals.
Cost: 9 new files, ~200 lines of boilerplate, to replace what was previously done by 3 files (discovery_api.py, paths_api.py, output_api.py) that were themselves already thin wrappers.
2. The _api.py Suffix Pattern Creates a Confusing Dual-Layer System
Before this refactoring, the import path to get colorize was:
python
from desloppify.core.output_api import colorize # or from output directly
After, callers have been migrated to:
python
from desloppify.core.io.api import colorize
Meanwhile, output_api.py still exists as a deprecation-warning shim that forwards to io.api, which forwards to output. That is three layers of indirection for a function call:
code
caller -> core.io.api.colorize -> core.output.colorize (the real function)
Used in exactly 2 files. This is a constant that belongs wherever it is consumed, or in the plan module itself. A 14-line file for a single tuple of standard exception types is absurd.
score_targets.py -- 13 lines. Three integer constants:
Used in exactly 2 files (config.py and narrative/core.py). These belong in config.py or the scoring module.
coercions_api.py -- 19 lines. A pure re-export of 5 functions from core._internal.coercions. No logic, no transformation. The original module is already only 73 lines. This "API surface" adds nothing that from desloppify.core._internal.coercions import coerce_confidence wouldn't provide.
text_api.py -- 46 lines. Re-exports 4 functions from _internal.text_utils with identical signatures and zero logic changes. The docstring says "Public text utility boundary for cross-module callers" but there is no boundary -- it is a forwarding layer.
4. The impl.py / api.py Split Is Cargo-Culted Architecture
The api.py vs impl.py split pattern is borrowed from codebases where:
The API module defines abstract interfaces or protocols
The impl module provides concrete implementations that can be swapped
Here, both api.py and impl.py in each sub-package import from the same underlying module and expose the same functions. There is no interface/implementation distinction. There is no dependency inversion. It is structural overhead with no architectural purpose.
5. The DynamicPathProxy Is the One Genuinely Useful Addition
path_proxy.py (38 lines) introduces DynamicPathProxy, which replaces the old sentinel-comparison pattern in paths_api.py:
python
# Old: clunky sentinel pattern
if PROJECT_ROOT is not _PROJECT_ROOT_SENTINEL and isinstance(PROJECT_ROOT, Path | str):
return Path(PROJECT_ROOT).resolve()
return _get_project_root()
This is a real improvement. The proxy correctly delegates __fspath__, __truediv__, and __getattr__ to the resolved path. It is used in 5 places and solves a real problem (module-level path constants that need to track runtime root changes). This belongs in _internal/ and is correctly placed there.
6. nonfatal.py Is a Reasonable New Module
At 74 lines with a dataclass, a report function, and a summary renderer, this has enough cohesion to justify a separate file. It is used in 2 places currently but defines a clear pattern (structured error collection) that other modules could adopt.
7. The compat/ Package Is Premature
The compat/ package contains:
utils.py (134 lines) -- a "deprecated compatibility facade" with a removal date of 2026-09-30
file_discovery.py (51 lines) -- another compat facade
scoring.py (84 lines) -- yet another compat facade
These exist to support top-level imports like from desloppify.utils import colorize. But this is an internal tool, not a published library with external consumers. There is no need for a formal deprecation cycle with dated removal targets. If you are moving imports, just move them and fix the callers. The codebase has full control over all consumers.
core.{discovery_api,paths_api,output_api} -> core.{discovery,io,pathing}.api -> (same as above)
There is no circular dependency issue, so credit for that. But the layering is purely additive -- every new layer is a forwarding shim, not an abstraction boundary. You can trace any call through 2-3 modules of pure delegation before hitting real code.
Quantitative Summary
Category
New Files
New Lines
Logic Lines (non-boilerplate)
Sub-package scaffolding (__init__, impl)
6
61
0
API forwarding layers (api.py x3)
3
261
~5 (one type coercion)
Standalone shim modules
4
93
~3 (constants)
Compat facades
4
274
0
Genuine new code
2
112
~100
Total
19
800
~108
So roughly 86% of the new code is boilerplate -- re-exports, forwarding functions, deprecation warnings, __all__ lists, and docstrings that say "use the other module instead."
Recommendations
Delete the discovery/, io/, pathing/ sub-packages entirely. The existing source_discovery.py, output.py, and file_paths.py are perfectly good modules. If you want a cleaner public API, add __all__ to them directly.
Delete coercions_api.py and text_api.py. Have callers import from core._internal.coercions and core._internal.text_utils directly, or move those functions out of _internal if they are truly public.
Delete exception_sets.py and score_targets.py. Inline those constants into their 2 consumers, or put them in the modules they logically belong to (engine/_plan/ and core/config.py respectively).
Delete the compat/ package. Update the 7 call sites that use desloppify.utils, desloppify.file_discovery, and desloppify.scoring to import from their actual sources. This is a private codebase.
Keep nonfatal.py and _internal/path_proxy.py. These are the only additions that contain genuine logic.
Keep the old discovery_api.py, paths_api.py, output_api.py as they were (simple re-export aggregations from their underlying modules), since they served as a thin convenience layer with zero indirection cost. Or delete them too if you prefer callers importing directly from source_discovery, file_paths, and output.
The net effect of the entire refactoring (minus the two good files) is that it replaces ~150 lines of simple re-exports with ~690 lines of structured re-exports organized into more files. That is not a refactoring. That is accretion.
from desloppify.utils import
from desloppify.file_discovery import
from desloppify import scoring
Actual caller count for the new "canonical" paths: 54 occurrences across 49 files import from core.discovery, 149 occurrences across 125 files import from core.pathing, and 91 files import from core.io. The refactoring has already aggressively rewritten callers to the new paths, making the compat shims even less necessary.
Verdict: This is premature and over-engineered. The codebase has no external consumers (no published API, no third-party plugins). There is nobody to maintain backward compatibility for. The compat layer adds 660 lines across 16 files, introduces a 4-deep import delegation chain, and solves a problem that does not exist. The impl.py files (3 files totaling 34 lines) are structurally gratuitous -- they just star-import from the actual implementation modules to create a fake api/impl split in packages where only one implementation exists.
2. New Helper Files in desloppify/app/commands/helpers/
state_access.py (64 lines) -- Pure Delegation, No Value
All 7 functions do nothing except rename state_mod.X to a slightly different name. load_state_file calls load_state. save_state_file calls save_state. utc_timestamp calls utc_now. There is no transformation, no error handling, no extra logic. Only 2 files import from this module (resolve/render.py and plan/_resolve.py).
Verdict: This file is pure indirection. Callers should import desloppify.state directly. It adds cognitive overhead ("is load_state_file different from load_state?") and makes the codebase harder to grep.
This provides lazy_module_getattr() and lazy_module_dir() -- helpers for implementing __getattr__/__dir__ in __init__.py modules to defer imports until attribute access. Used by 4 __init__.py files (show, resolve, plan, fix).
Verdict: This is the most defensible of the new helpers. It deduplicates a real pattern that would otherwise be copy-pasted. 33 lines is appropriately small. The name "lazy_exports" is slightly misleading -- it is really "lazy __init__ re-export helpers" -- but functional.
finding_payloads.py (77 lines) -- Marginal Type Safety Layer
Provides a FindingDetail TypedDict and 5 accessor functions like finding_detail(), detail_dimension(), detail_lines(), detail_target_line(). Used by 3 files. The accessors are thin wrappers over .get() with type coercion.
Verdict: Borderline. The FindingDetail TypedDict and detail_target_line() helper provide mild type-safety value. But state_findings() is just a 3-line function that calls state.get("findings") and casts it. The file earns marginal existence from the TypedDict definition; the rest is over-extraction.
3. Other New Files
score_bars.py (20 lines) -- One Function, One File
Contains exactly one function, dimension_bar(), which renders a terminal progress bar. 20 lines total including docstring and __all__. Used by 2 files.
Verdict: This should be inlined into one of the existing output modules or the 2 callers directly. A 20-line file containing a single function does not earn its own module. The function itself is 8 lines of logic.
subjective_reporting.py (439 lines) -- Relocated Module With Minor Additions
This is almost exactly scan_reporting_subjective.py (401 lines in the committed version) relocated from app/commands/scan/ to app/output/ with ~40 lines of new helper functions added (_subjective_summary_parts, _should_render_subjective_paths, show_subjective_paths). The docstring was changed from "Subjective scan reporting" to "Shared subjective reporting helpers for scan/status/show/next output flows." Used by 5 files.
Verdict: This is a reasonable move if the reporting is genuinely shared across scan/status/show/next flows, which the 5-caller usage suggests. The old location under scan/ was misleading if non-scan commands use it. This one earns its existence, though the delta is small.
display_names.py (31 lines) -- One Constant, One File
Contains a single DISPLAY_NAMES dictionary mapping dimension keys to short display strings. 31 lines. Used by 3 files.
Verdict: This is a data constant that was likely extracted from scoring.py or subjective/core.py. 31 lines for a single dict is defensible if it prevents a circular import or if it needs to be shared across scoring modules. But it is the kind of extraction that fragments the codebase -- developers must now know to look in engine/_scoring/subjective/display_names.py for what was previously a simple dict in the scoring module.
Provides OpenPlanQueuePolicy dataclass and build_open_plan_queue() function that wraps build_work_queue() with consistent defaults. Used by 2 files (planning/render.py and planning/select.py).
Verdict: This one earns its existence. The OpenPlanQueuePolicy dataclass captures a real concept (the default queue-building configuration for planning views), and the wrapper centralizes the parameter assembly logic that would otherwise be duplicated in 2+ callers with complex parameter threading.
Summary Assessment
File
Lines
Callers
Verdict
compat/ (entire directory)
274
3 legacy shims
Unnecessary. No external consumers exist.
core/discovery/, core/pathing/, core/io/
313
49-125 files
Over-structured. The impl.py files are pointless. The api.py files are thin wrappers over existing core modules.
state_access.py
64
2
Pure indirection. Delete and import state directly.
lazy_exports.py
33
4
Defensible. Real pattern dedup.
finding_payloads.py
77
3
Marginal. TypedDict has some value; accessors are over-extracted.
score_bars.py
20
2
Unnecessary. One 8-line function should be inlined.
subjective_reporting.py
439
5
Reasonable relocation from scan-specific to shared output.
display_names.py
31
3
Marginal. Single dict extracted into its own file.
queue_policy.py
62
2
Defensible. Captures real shared configuration concept.
The overall pattern is one of premature architectural layering: introducing api/impl splits, compatibility facades, and thin delegation wrappers in a codebase with no external consumers and no versioning boundary. The compat layer alone adds ~660 lines of pure re-export code across 16 files. Combined with state_access.py and score_bars.py, approximately 750 lines of the refactoring are pure overhead that makes the codebase harder to navigate (more files to open, deeper import chains) without making it more correct or maintainable.
test_file_paths_output_api_direct.py (59 lines, 14 assertions, 0 callable-checks): Tests matches_exclusion, normalize_path_separators, resolve_scan_file, safe_write_text, colorize, log, print_table, and display_entries with actual inputs and output validation. These are shallow integration checks but they validate real behavior (path matching, file I/O, terminal output capture).
test_compat_utils_direct.py (45 lines, 9 assertions, 3 callable-checks): Tests that the desloppify.compat.utils compatibility shim correctly delegates compute_tool_hash/check_tool_staleness through to the underlying _tooling module, honoring TOOL_DIR overrides. The __getattr__ error-raising test is useful. 3 of 9 assertions are callable-checks.
Tier C: Pure coverage padding (problematic)
test_direct_coverage_additional_modules.py (121 lines, 13 assertions, all 13 are callable-checks): This is the worst offender. Every single test function just imports a module and asserts callable(some_function). It tests that Python can import modules, which Python already guarantees if the imports at the top of the file succeed. The assertions add zero value beyond the import statement. Names like test_plan_review_helpers_smoke, test_scan_core_engine_go_smoke, test_fixer_import_rewrite_smoke are honest about what they are -- but "smoke" is generous. These are import-existence checks.
2. The test_direct_coverage_modules.py Modification
The existing file (407 lines, already the main coverage-padding file) was expanded significantly. Looking at the diff:
Added ~30 more imports tracking renamed module paths (e.g. review.batch_core to review.normalization.batch_core, review.runtime to review.runtime.setup)
Added ~20 more _assert_all_callables(...) entries for newly-extracted modules
But also added some genuinely behavioral tests at the bottom: test_noise_budget_defaults, test_noise_budget_from_config, test_noise_settings_invalid_config, test_serialize_item_minimal, test_build_query_payload_structure, test_private_imports_is_dunder, test_command_registry_has_core_commands. These test actual return values with real inputs.
The file is a hybrid: ~60% callable-check padding and ~40% genuine behavioral assertions. The behavioral tests at the bottom are good and could stand on their own in a properly-named file.
3. The utils.py Change
The 139-line diff is a net deletion -- the file goes from 134 lines to 35 lines. It:
Removes all explicit re-exports (the long list of from desloppify.core.discovery_api import ...)
Replaces them with from desloppify.compat.utils import * plus a __getattr__ fallback
desloppify/utils.py becomes a thin shim that delegates everything to desloppify/compat/utils.py
The compat/utils.py module is essentially the old utils.py content, but it now imports from the new canonical locations (desloppify.core.discovery.api instead of desloppify.core.discovery_api, desloppify.core.pathing.api instead of desloppify.core.paths_api). This is a standard "introduce a compat layer while moving to new module paths" pattern. The chain is now:
This is architecturally fine but adds one indirection layer. The __getattr__ on both utils.py and compat/utils.py means attribute access for legacy discovery names goes through two __getattr__ calls at runtime, which is mildly wasteful but functionally harmless.
4. Modified Test Files: Import Path Updates
The majority of changes in modified test files are mechanical import path updates:
File
Nature of changes
test_scorecard.py
core._internal.text_utils.PROJECT_ROOT to core.pathing.api.PROJECT_ROOT
test_review_coverage.py
core.discovery_api.rel to core.pathing.api.rel
test_review_batch_core_direct.py
review.batch_scoring to review.payload.batch_scoring
test_review_split.py
review.remediation to review._prepare.remediation_engine
test_cmd_scan.py
Moved several imports from scan.scan to scan.scan_helpers and scan.scan_reporting_summary
However, test_review_commands.py and test_work_queue.py also add new test methods -- not just import fixes:
test_review_commands.py adds test_do_import_blocks_when_review_backlog_open and test_do_import_force_review_import_bypasses_backlog_gate -- these test a real new gating feature.
test_work_queue.py adds test_subjective_slot_injection_interleaves_low_subjective_items and test_subjective_slot_injection_skipped_when_specific_tier_requested -- genuine behavioral tests for a new queue interleaving feature.
test_cmd_scan.py adds TestScanQueryPayloadPlanStatus -- tests plan error handling in scan payloads.
5. Honest Assessment
The naming pattern is telling. The _direct and _direct_coverage suffixes are self-documenting admissions. They exist to provide direct import coverage for modules that are otherwise only covered transitively. This is a common tactic to inflate code coverage metrics without writing tests that would catch regressions.
By the numbers:
Category
Files
Lines
Real behavioral assertions
Pure padding (all callable-checks)
1
121
0
Mostly padding (>50% callable-checks)
1 (modified)
407
~20
Hybrid (real + padding)
2
172
~24
Genuine behavioral tests
5
267
~61
Total new test code
9
1,107
~105
Approximately 500-600 lines of the new test code is genuine quality improvement. The remaining 400-500 lines are coverage padding -- import-and-assert-callable patterns that would pass even if the functions returned wrong results, had broken logic, or silently dropped arguments.
The good news: The review merge, runtime policy, batch core, batch nonfatal, and coverage helpers tests are real. The modified existing tests (review_commands, work_queue, cmd_scan) add genuine new feature coverage. The API surface tests for the new core module layout are defensible as regression guards for the compat layer.
The bad news:test_direct_coverage_additional_modules.py is 121 lines of pure coverage theater. The _assert_all_callables pattern, which accounts for hundreds of lines across multiple files, provides the illusion of test coverage without testing any behavior. If a function signature changed but its body broke completely, these tests would still pass.
Specific Problems
1. Subdirectories That Don't Justify Their Existence
orchestration/ contains exactly 3 files totaling 19 lines of actual code:
__init__.py -- 1 line (docstring)
helpers.py -- 11 lines (a single function parse_dimensions)
runtime_defaults.py -- 7 lines (a single constant DEFAULT_BATCH_STALL_KILL_SECONDS = 120)
An 11-line function and a single constant do not warrant their own package. This is the kind of decomposition that makes grep harder without making anything else easier.
quality/ contains a single 77-line file (assessment_integrity.py). One file does not need a package.
importing/ contains a single 1301-line file (import_helpers.py). One file does not need a package. The package adds nothing -- the __init__.py doesn't even re-export anything.
normalization/ contains a single 887-line file (batch_core.py). Same story.
2. Cross-Package Coupling Undermines the Directory Structure
The new directories are not self-contained. The dependency graph between them:
runtime/policy.py imports from orchestration/runtime_defaults.py (line 21: from ..orchestration.runtime_defaults import DEFAULT_BATCH_STALL_KILL_SECONDS)
normalization/batch_core.py imports from payload/batch_scoring.py and payload/batch_prompt_template.py
batch.py (top-level) imports from normalization/, payload/, orchestration/, runtime/, and importing/ -- touching all 5 new packages
The directory boundaries do not correspond to actual abstraction boundaries. If runtime/policy.py needs a constant from orchestration/, those two packages are not truly separated.
3. Legacy Compatibility Layer Adds Pure Indirection
The review/__init__.py sets up lazy module aliases:
These exist solely to preserve old import paths. That is technical debt carried forward, not reduced.
4. No Interfaces Were Introduced
The biggest files (runner_helpers.py at 1640 lines, import_helpers.py at 1301 lines, batch_core.py at 887 lines) were moved without being split. If the goal was to improve modularity, these are the files that needed decomposition. Instead they were placed into new directories and grew.
For example, runner_helpers.py gained new dataclasses (BatchExecutionOptions, _ParallelExecutionContext), a new _coerce_execution_options function, and a _report_progress_error helper -- all of which were added inline to the same file. This is new functionality, not decomposition.
import_helpers.py gained ReviewImportOptions (a 90-line dataclass with a from_raw factory method), plus helper functions like _normalize_optional_mapping_field, _validate_manual_override_attestation, etc. Again, new features were added to the same monolithic file; the directory move didn't reduce its cohesion problems.
5. The Naming is Misleading
normalization/batch_core.py does batch payload parsing, finding validation, and JSON extraction. "Normalization" is a stretch.
orchestration/ contains a dimension-parsing helper and a timeout constant. "Orchestration" suggests something much more substantive.
payload/ contains prompt templates, scoring math, a constants file, and a packet builder. These are four different concerns (prompt rendering, scoring algorithms, configuration, and data assembly) lumped under "payload."
What Would Genuine Decomposition Look Like
If the goal is to improve the review/ package:
Split the 1640-line runner_helpers.py into actual concern-based modules: process management (subprocess/Popen wrangling), blind packet sanitization, batch result dataclasses, and the parallel execution orchestrator.
Split the 1301-line import_helpers.py into: payload validation/normalization, provenance verification, assessment policy resolution, and the import orchestration flow.
Eliminate single-file packages. If quality/ only has assessment_integrity.py, just keep it as review/assessment_integrity.py. The directory adds nothing.
Define actual package interfaces. Currently every sub-package's __init__.py is either empty or a lazy re-export shim. A well-decomposed package would have __init__.py exposing a small, documented public API while keeping internals private.
Verdict
This refactoring is cosmetic reorganization masquerading as structural improvement. The code was moved into directories named after architectural concepts (payload, orchestration, runtime, quality, normalization, importing), but the actual code within each directory was not redesigned to match those concepts. No coupling was reduced. No interfaces were introduced. The largest files grew rather than being broken apart. Four of the six new packages contain exactly one substantive file. The result is harder to navigate (deeper paths, more __init__.py files, lazy-loading indirection) without being easier to reason about.
Two small regex-based functions (compute_ts_destructure_props, compute_ts_inline_types)
Three constant lists/sets (TS_COMPLEXITY_SIGNALS, TS_GOD_RULES, TS_SKIP_NAMES, TS_SKIP_DIRS)
All were previously inline in typescript/phases.py.
Verdict: This is a straightforward "extract constants to their own file" refactoring. The name phase_policies is again inflated -- these are configuration constants, not policies in any design-pattern sense. But the split itself is reasonable: these constants were cluttering the top of a file whose main job is running phase functions. The functions compute_ts_destructure_props and compute_ts_inline_types gained proper docstrings in the move (previously they were prefixed with _ and undocumented), which is a genuine improvement.
4. typescript/syntax/ -- Single Function Extraction
Files:/Users/user_c042661f/Documents/desloppify/desloppify/languages/typescript/syntax/__init__.py and scanner.py
scan_code (a 25-line generator that yields character positions with string-tracking) was extracted from _smell_helpers.py into its own package. The function is byte-for-byte identical to the original.
Verdict: This is a defensible extraction. scan_code was used by both _smell_helpers.py and the fixers (if_chain.py, syntax_scan.py). Previously, fixers imported it from detectors, creating a cross-concern dependency. Now they both import from syntax/, which is cleaner.
However, the new __init__.py has a puzzling dead assignment: _TS_SYNTAX_SHIM = __name__. This appears to be a leftover from some compatibility pattern and serves no purpose.
5. Deleted: typescript/fixers/common.py
This was already a re-export shim (it imported from fixer_io, import_rewrite, syntax_scan and re-exported). The deletion means callers now import directly from the real modules. This is a clean removal of an unnecessary indirection layer.
6. The Heavily Modified Files -- What Actually Changed
_framework/generic.py: Substantial but Verbose Restructuring
The core generic_lang() function was genuinely restructured:
Registration decoupled from construction: _build_tool_registration_bundle() now builds detector/scoring payloads without side effects, and _apply_registration_bundle() commits them only after validation. Previously, detectors were registered in a loop inline. This is a real improvement -- if config validation fails, you don't leave half-registered detectors in global state.
Options normalized into a dataclass: GenericLangOptions replaces loose keyword args. But the implementation is excessive: _resolve_generic_lang_options() is 40+ lines that manually copies every field from the dataclass... into a new instance of the same dataclass. The method literally does GenericLangOptions(exclude=list(options.exclude) if options.exclude is not None else None, ...) for every field. This is defensive-copy boilerplate that a copy.deepcopy() would handle in one line.
Lazy imports replaced with top-level imports: All the conditional from ... import ... blocks inside functions were hoisted to module level. The _shared_phase_runner() helper uses importlib.import_module to break a circular import, which is strictly worse than the previous lazy import pattern -- it loses type checking and IDE navigation for the exact same runtime behavior.
validate_lang_contract() added: This is the one genuinely new piece of logic in the framework. It validates that a LangConfig has non-empty phases, callable detectors, valid scan profile, etc. This is useful -- it catches misconfigured plugins at registration time rather than at scan time.
_framework/runtime.py: __getattr__ Replaced with Explicit Properties
The LangRun class previously used __getattr__ with a forwarding set to proxy config attributes. Now it uses 30+ explicit property definitions via _config_attr_property(). Additionally, several methods (normalize_settings, normalize_runtime_options, set_runtime_context, detect_lang_security, detect_lang_security_detailed, detect_private_imports, scan_coverage_prerequisites) were given explicit delegation wrappers.
Verdict: This is a mixed bag. Explicit properties are more IDE-friendly and type-checker-friendly than __getattr__. But the LangRuntimeContract Protocol class was gutted in the process -- it went from having ~15 explicit attributes to just config: LangConfig. This means the Protocol no longer actually documents the runtime interface; it just says "you have a config." The old Protocol was more useful as documentation.
Also, the sorted renaming of _FORWARDED_CONFIG_ATTRS to _LANGRUN_CONFIG_SURFACE (just alphabetically reordering the same set of strings) is pure churn.
typescript/phases.py: Genuine Delegation to Shared Phases
phase_structural and phase_coupling were substantially refactored to delegate to run_structural_phase() and run_coupling_phase() from shared_phases.py. The TS-specific logic (mixed concerns detection, props bloat, boundary candidates, cross-tool imports, facades) stays in phases.py, while the generic structural/coupling flow (large files, complexity, gods, flat dirs, single-use, cycles, orphaned) moves to shared code.
Verdict: This is the most clearly beneficial change. The TS phase_structural went from ~80 lines of detector orchestration down to ~30, delegating the repetitive parts. The extra_signal_entries_fn callback lets TS inject its mixed-concerns detection without reimplementing the structural pipeline. Similarly, phase_coupling delegates single-use/cycles/orphaned detection while keeping TS-specific boundary and facade logic.
However, the _make_boundary_findings signature change is a subtle API break: it now receives the full shared results list instead of the raw single-use entries, and filters by finding.get("detector") == "single_use". This is less efficient (iterating all findings to find single-use ones) and more fragile (string matching on detector names).
run_structural_phase() gained extra_signal_entries_fn parameter and a try/except fallback for the min_loc parameter on detect_complexity. run_coupling_phase() gained single_use_skip_dir_names and orphaned_options parameters.
The try/except backward-compatibility fallback for min_loc is concerning:
This silently swallows TypeError from any cause, not just a missing parameter. A duck-typing inspect.signature check or **kwargs approach would be safer.
_framework/registry_state.py: Over-Engineering Mutable State
_RegistryMap and _LoadErrorMap are dict subclasses with empty bodies, created "to avoid module-level mutable-literal state." This is cargo-cult: a dict() call would achieve the same thing. The globals()["_load_attempted"] = bool(value) pattern for setting module globals is unusual and unnecessary -- the original global _load_attempted; _load_attempted = value was clearer.
The set_load_errors function now does:
python
current = globals().get("_load_errors")
if isinstance(current, dict):
current.clear()
current.update(dict(errors))
return
globals()["_load_errors"] = dict(errors)
This is a convoluted way to mutate a module-level dict in place, apparently to avoid breaking references. But the old code (global _load_errors; _load_errors = errors) was fine since get_load_errors() returns the value each time.
The _load_context / get_load_context() / set_load_context() additions plus _should_skip_load() in discovery.py add a mechanism for detecting when the project root changes between loads. This is genuine new functionality addressing a real edge case (running in different project roots within one process).
Across concerns.py, deprecated.py, deps.py, exports.py, knip_adapter.py, logs.py, patterns.py, props.py, security.py, unused.py, the changes are almost entirely:
desloppify.core._internal.text_utils -> desloppify.core.text_api or desloppify.core.pathing.api
These are ripple effects from a broader refactoring of the core module structure (splitting monolithic API modules into sub-packages). There is virtually no logic change in these files.
Two exceptions with real changes:
react.py (487-line diff): Inline logic was extracted into 8 small helper functions (_resolve_source_path, _load_tsx_content, _collect_state_setters, _effect_body_end, _effect_statements, _matched_setters, _state_sync_entry). This is genuine decomposition making the state-sync detection more testable.
smells.py: _detect_empty_if_chains (80 lines) and _detect_dead_useeffects (60 lines) were moved to _smell_effects.py, with the if-chain logic refactored into smaller predicate functions (_is_if_head, _is_single_line_empty_if, etc.). This is a real improvement in readability.
_smell_detectors.py: Two dead helper functions (_line_no_and_preview, _extract_returned_object_body) were removed, and an inline brace-tracking loop was replaced with a call to the existing _find_block_end. Good cleanup.
deprecated.py: The legacy detect_deprecated() wrapper was removed (callers now use detect_deprecated_result().as_tuple()). Clean API simplification.
Summary Assessment
Change
Verdict
contracts.py files (both)
Dataclass relocation, not interfaces. "Contracts" is a misnomer. Harmless but overpromises.
phase_policies.py
Reasonable constant extraction. Name is inflated.
syntax/ package
Good: resolves cross-concern import dependency for scan_code.
fixers/common.py deletion
Good: removes unnecessary re-export shim.
generic_lang() restructure
Mixed: registration-before-validation fix is valuable; GenericLangOptions is verbose boilerplate; importlib.import_module is a regression vs. lazy imports.
contract_validation.py
Genuinely new and useful: fail-fast validation for plugin configs.
runtime.py property expansion
Mixed: IDE-friendlier, but gutted the Protocol class that documented the interface.
shared_phases.py extensibility
Good: TS phases delegate properly. try/except TypeError is fragile.
registry_state.py
Over-engineered: empty dict subclasses and globals()[] pattern add complexity for no benefit. Load-context tracking is the one useful addition.
react.py decomposition
Good: monolithic function split into testable helpers.
smells.py -> _smell_effects.py
Good: large detection functions split into smaller predicates.
TS detector import rewrites
Pure churn from core module restructuring. No logic changes.
Overall: Roughly 30% of the line changes in this area are substantive improvements (phase delegation, contract validation, function decomposition in react/smells). About 20% is defensible but arguable restructuring (dataclass moves, property expansion). The remaining 50% is import path churn from the core module split, with a sprinkling of unnecessary over-engineering (empty dict subclasses, globals() patterns, the GenericLangOptions copy-every-field constructor).
').",
"suggestion": "Delete these three dead modules. The init.py files that import them (from . import api, impl) should drop the impl import.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "four_hop_compat_chain",
"summary": "The legacy compat layer creates a 4-hop delegation chain (utils.py -> compat/utils.py -> core/discovery/api.py -> source_discovery.py) with no active first-party callers of the root-level shims.",
"related_files": ["desloppify/utils.py", "desloppify/compat/utils.py", "desloppify/file_discovery.py", "desloppify/compat/file_discovery.py"],
"evidence": "desloppify/utils.py delegates via getattr to compat/utils.py which delegates via getattr to core/discovery/api.py which delegates to source_discovery.py. Grep for 'from desloppify.file_discovery import' returns 0 results. Grep for 'from desloppify import utils' shows only 3 test files. The root-level shims (utils.py, file_discovery.py, scoring.py) have almost no first-party callers yet impose a multi-hop chain on any remaining caller.",
"suggestion": "Delete desloppify/file_discovery.py (0 callers) immediately. Migrate the 3 test files off desloppify/utils.py to direct core imports, then delete the root shim. The compat/ layer can remain with a sunset date since it documents the migration.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "output_api_paths_api_deprecated_zero_callers",
"summary": "core/output_api.py and core/paths_api.py are deprecated compatibility facades with zero first-party callers.",
"related_files": ["desloppify/core/output_api.py", "desloppify/core/paths_api.py"],
"evidence": "Grep for 'from desloppify.core.output_api import' returns 0 results. Grep for 'from desloppify.core.paths_api import' returns 0 results. These files each wrap the api.py module with added deprecation warnings per call, but nobody calls them.",
"suggestion": "Delete both dead modules. They were part of a migration that has completed.",
"confidence": "high"
},
{
"dimension": "abstraction_fitness",
"identifier": "coercions_api_trivial_reexport",
"summary": "core/coercions_api.py is a 19-line re-export module that adds no logic over core/_internal/coercions.py.",
"related_files": ["desloppify/core/coercions_api.py", "desloppify/core/_internal/coercions.py"],
"evidence": "The entire file is: from desloppify.core._internal.coercions import (coerce_confidence, coerce_non_negative_float, coerce_non_negative_int, coerce_positive_float, coerce_positive_int) plus all. 6 files import from it. The _internal prefix convention is the sole justification, but the coercions module has no internal-only implementation details worth hiding.",
"suggestion": "Either rename _internal/coercions.py to core/coercions.py (dropping the _internal prefix) or make coercions_api.py's callers import directly. The re-export adds a hop with no boundary value.",
"confidence": "medium"
},
{
"dimension": "abstraction_fitness",
"identifier": "text_api_trivial_reexport",
"summary": "core/text_api.py is a pure pass-through that forwards 4 functions to core/_internal/text_utils.py with identical signatures.",
"related_files": ["desloppify/core/text_api.py", "desloppify/core/_internal/text_utils.py"],
"evidence": "get_area() -> _text_utils.get_area(filepath, min_depth=min_depth), is_numeric() -> _text_utils.is_numeric(value), read_code_snippet() -> _text_utils.read_code_snippet(...), strip_c_style_comments() -> _text_utils.strip_c_style_comments(text). No transformation, no validation, no error handling added.",
"suggestion": "Same as coercions_api: either promote text_utils out of _internal or have callers import directly.",
"confidence": "medium"
},
{
"dimension": "mid_level_elegance",
"identifier": "build_batch_prompt_passthrough",
"summary": "build_batch_prompt() in batch_core.py is a public API function that is a 1:1 delegation to render_batch_prompt() with identical keyword arguments.",
"related_files": ["desloppify/app/commands/review/normalization/batch_core.py", "desloppify/app/commands/review/payload/batch_prompt_template.py"],
"evidence": "Lines 864-877: def build_batch_prompt(
getattr
setattr
getattr
getattr
getattr
getattr
getattr
class_getitem
PROJECT_ROOT: Path | None = None
DynamicPathProxy
RuntimeContext
current_runtime_context().project_root
globals()[]
_load_attempted
_load_context
_load_errors
set_load_attempted(True)
was_load_attempted()
reset_registry_state()
globals()['_load_attempted'] = bool(value)
globals()['_load_context'] = ...
globals()['_load_errors'] = ...
reset_registry_state()
was_load_attempted() == True
from desloppify.languages.typescript.phases import (TS_COMPLEXITY_SIGNALS, TS_GOD_RULES, TS_SKIP_DIRS, TS_SKIP_NAMES)
from desloppify.languages.typescript.phase_policies import TS_COMPLEXITY_SIGNALS, TS_GOD_RULES, TS_SKIP_DIRS, TS_SKIP_NAMES
class _State: load_attempted = False; load_context = None; ...
_state = _State()
_state.load_attempted = True
state/resolution.py"
],
"evidence": [
"Line 149-154: base updates builds resolution_attestation = {kind: 'manual', text: attestation, ...}",
"Line 134-140: extra_updates for status=='open' builds resolution_attestation = {kind: 'manual_reopen', text: attestation or note, ...}",
"Line 156: updates.update(extra_updates) overwrites the base attestation with the 'open' version",
"For status=='wontfix', the base 'manual' attestation is used even though the resolution is not manual in the traditional sense"
],
"suggestion": "Factor the function into per-status branches that each build exactly the correct updates dict. Eliminate the 'base plus override' pattern that constructs throwaway values.",
"confidence": "high"
},
{
"dimension": "api_surface_coherence",
"identifier": "discovery-api-language-specific-finders",
"summary": "discovery/api.py exports language-specific convenience functions find_ts_files, find_tsx_files, and find_py_files alongside the generic find_source_files. These hardcode language extensions in what is otherwise a language-agnostic discovery API surface. The three language-specific functions are thin wrappers that call find_source_files with fixed extension lists.",
"related_files": [
"desloppify/core/discovery/api.py",
"desloppify/core/source_discovery.py"
],
"evidence": [
"discovery/api.py lines 61-71: find_ts_files, find_tsx_files, find_py_files each just call source_discovery_mod.find
init
init
init
init
init
args, **kwargs), where _core_module() does importlib.import_module('desloppify.engine.planning.core'). But core.py itself is just re-exports: 'from desloppify.engine.planning.render import generate_plan_md' etc. So a call through init goes: init.py -> importlib -> core.py -> render.py/scan.py/select.py. The init.py wrappers erase all type information (everything is args: Any, **kwargs: Any), and core.py adds no logic. Meanwhile, some callers bypass this entirely and import directly from core.py (e.g., tests/core/test_plan.py, tests/lang/csharp/test_csharp_scan.py).",
"suggestion": "Collapse the two layers: either make init.py do the direct re-exports that core.py currently does (eliminating core.py), or use getattr-based lazy loading in init.py to preserve type signatures without the pass-through wrappers.",
"confidence": "high"
},
{
"dimension": "mid_level_elegance",
"identifier": "visualize-repeated-warn-guard-pattern",
"summary": "visualize.py repeats the same warned-once guard pattern (local bool flag + conditional warning) in three separate functions, creating glue-code entropy at the integration boundary.",
"related_files": [
"desloppify/app/output/visualize.py"
],
"evidence": "Three functions contain nearly identical warned-once patterns: (1) _resolve_visualization_lang (line 48: 'warned = False', line 58: 'if not warned: warned = True; warn_best_effort(...)'), (2) _fallback_source_files (line 87: 'warned = False', line 98: 'if not warned: warned = True; warn_best_effort(...)'), (3) _collect_file_data (line 118: 'warned_read_failure = False', line 135: 'if not warned_read_failure: warned_read_failure = True; warn_best_effort(...)'). Each catches _RECOVERABLE_LANG_RESOLUTION_ERRORS or (OSError, UnicodeDecodeError), logs via log_best_effort_failure, then conditionally warns the user once. This is the same pattern three times with minor string changes.",
"suggestion": "Extract a small context manager or helper that combines the log_best_effort_failure call with a warn-once guard, reducing the repeated boilerplate in each function to a single call.",
"confidence": "medium"
},
{
"dimension": "convention_outlier",
"identifier": "namespace-shim-unused-sentinels",
"summary": "Three core sub-package init.py files define unused __NAMESPACE_SHIM module-level variables that serve no runtime purpose and follow no convention used elsewhere.",
"related_files": [
"desloppify/core/discovery/init.py",
"desloppify/core/io/init.py",
"desloppify/core/pathing/init.py"
],
"evidence": "Each of the three structured namespace init.py files (discovery, io, pathing) defines a module-level variable of the form _DISCOVERY_NAMESPACE_SHIM = name (discovery/init.py line 5), _IO_NAMESPACE_SHIM = name (io/init.py line 5), _PATHING_NAMESPACE_SHIM = name (pathing/init.py line 5). These variables are never referenced anywhere else in the codebase (grep for _NAMESPACE_SHIM yields only these three definition sites). No other init.py in the project follows this pattern.",
"suggestion": "Remove the _
scoring submodules (or from desloppify.compat.scoring if compat stability is needed), and add 'desloppify.scoring' to the import guard test's banned list. Or explicitly define desloppify.scoring as the stable public facade and document it as non-deprecated.",
"confidence": "high"
},
{
"dimension": "test_strategy",
"identifier": "smoke-callable-tests-inflate-coverage-without-verification",
"summary": "The test_direct_coverage
_assert_all_callables()
assert callable()
assert callable()
init
init
return output_mod.colorize(text, color)
from desloppify.core.output import * # noqa: F401,F403
from desloppify.compat.scoring import * # noqa: F401,F403
dimension: high_level_elegance, identifier: show_and_status_render_duplication, summary: "show/render.py and status_parts/render.py each define their own show_agent_plan() and show_subjective_followup() with near-identical logic.", related_files: ["desloppify/app/commands/show/render.py", "desloppify/app/commands/status_parts/render.py"], evidence: "Both files define show_agent_plan and show_subjective_followup with nearly identical bodies", suggestion: "Extract a single render_agent_plan() helper into app/commands/helpers/rendering.py", confidence: high
dimension: high_level_elegance, identifier: three_layer_shim_chain, summary: "Top-level facade files exist solely to re-export from compat/ which re-exports from core/ packages, creating a 3-layer chain with no active external consumers.", related_files: ["desloppify/utils.py", "desloppify/compat/utils.py", "desloppify/scoring.py", "desloppify/compat/scoring.py", "desloppify/file_discovery.py", "desloppify/compat/file_discovery.py"], evidence: "utils.py imports from compat/utils.py which imports from core packages. Only 8 test occurrences use the old paths.", suggestion: "Deprecate and schedule removal of the three top-level shims and their compat intermediaries", confidence: high
dimension: cross_module_architecture, identifier: globals_mutation_for_module_state, summary: "Multiple modules use globals()[name] = value to mutate module-level state, making it invisible to static analysis.", related_files: ["desloppify/languages/_framework/registry_state.py", "desloppify/languages/_framework/treesitter/init.py", "desloppify/core/registry.py"], evidence: "registry_state.py uses globals()[] pattern for _load_attempted, _load_context, _load_errors", suggestion: "Replace with a dataclass container object", confidence: medium
BATCH 3 findings:
8. dimension: abstraction_fitness, identifier: io_api_pure_passthrough, summary: "core/io/api.py is a pure pass-through facade forwarding every function to core/output.py with identical signatures, adding no policy or translation.", related_files: ["desloppify/core/io/api.py", "desloppify/core/output.py"], evidence: "Every function in io/api.py is a 1-line delegation. 90 files import from this facade.", suggestion: "Merge core/io/api.py into core/output.py", confidence: high
9. dimension: abstraction_fitness, identifier: discovery_api_pure_passthrough, summary: "core/discovery/api.py is a pure pass-through facade forwarding every function to core/source_discovery.py.", related_files: ["desloppify/core/discovery/api.py", "desloppify/core/source_discovery.py"], evidence: "All 14 exports are trivial forwards. 48 importers pay for indirection.", suggestion: "Rename source_discovery.py to discovery/api.py or merge", confidence: high
10. dimension: abstraction_fitness, identifier: pathing_api_pure_passthrough, summary: "core/pathing/api.py is a pure pass-through facade forwarding to core/file_paths.py.", related_files: ["desloppify/core/pathing/api.py", "desloppify/core/file_paths.py"], evidence: "Only read_code_snippet adds a project_root default. 126 importers pay for indirection.", suggestion: "Consolidate file_paths.py into pathing/api.py", confidence: high
11. dimension: abstraction_fitness, identifier: state_access_pure_passthrough, summary: "state_access.py is a 7-function module where every function is a trivial 1-line delegation to desloppify.state.", related_files: ["desloppify/app/commands/helpers/state_access.py", "desloppify/state.py"], evidence: "load_state_file -> state_mod.load_state, save_state_file -> state_mod.save_state, etc. All 7 are pure forwards.", suggestion: "Delete state_access.py and import directly from desloppify.state", confidence: high
12. dimension: abstraction_fitness, identifier: impl_modules_zero_callers, summary: "core/io/impl.py, core/pathing/impl.py, and core/discovery/impl.py are star-import shims with zero importers.", related_files: ["desloppify/core/io/impl.py", "desloppify/core/pathing/impl.py", "desloppify/core/discovery/impl.py"], evidence: "Grep returns 0 results for any import from these modules.", suggestion: "Delete all three dead modules", confidence: high
13. dimension: abstraction_fitness, identifier: four_hop_compat_chain, summary: "Legacy compat layer creates a 4-hop delegation chain with no active first-party callers of root-level shims.", related_files: ["desloppify/utils.py", "desloppify/compat/utils.py", "desloppify/file_discovery.py", "desloppify/compat/file_discovery.py"], evidence: "utils.py -> compat/utils.py -> core/discovery/api.py -> source_discovery.py. file_discovery.py has 0 callers.", suggestion: "Delete file_discovery.py immediately, migrate 3 test files off utils.py", confidence: high
14. dimension: abstraction_fitness, identifier: output_api_paths_api_deprecated_zero_callers, summary: "core/output_api.py and core/paths_api.py are deprecated facades with zero first-party callers.", related_files: ["desloppify/core/output_api.py", "desloppify/core/paths_api.py"], evidence: "Grep returns 0 results for imports from either module.", suggestion: "Delete both dead modules", confidence: high
15. dimension: abstraction_fitness, identifier: coercions_api_trivial_reexport, summary: "core/coercions_api.py is a 19-line re-export adding no logic over core/_internal/coercions.py.", related_files: ["desloppify/core/coercions_api.py", "desloppify/core/_internal/coercions.py"], evidence: "Entire file is re-exports plus all. 6 files import from it.", suggestion: "Rename _internal/coercions.py to core/coercions.py", confidence: medium
16. dimension: mid_level_elegance, identifier: compat_utils_duplicate_tool_hash, summary: "Both utils.py and compat/utils.py define their own compute_tool_hash() with divergence risk from separate TOOL_DIR module-level shadows.", related_files: ["desloppify/utils.py", "desloppify/compat/utils.py"], evidence: "Both shadow TOOL_DIR at module scope. Test overrides of one won't propagate to the other.", suggestion: "Consolidate to a single function definition with parameter instead of global", confidence: high
17. dimension: low_level_elegance, identifier: exception_sets_overly_broad, summary: "PLAN_LOAD_EXCEPTIONS catches 7 exception types including AttributeError, TypeError, KeyError which masks programming bugs.", related_files: ["desloppify/core/exception_sets.py"], evidence: "AttributeError, TypeError, KeyError are typically programming errors, not I/O failures.", suggestion: "Narrow to (ImportError, OSError, ValueError)", confidence: medium
BATCH 5 findings:
18. dimension: package_organization, identifier: core-api-impl-over-structure, summary: "core/discovery/, core/io/, and core/pathing/ each contain 3 files that are pure pass-through wrappers, creating 322 LOC of forwarding code.", related_files: ["desloppify/core/discovery/init.py", "desloppify/core/discovery/api.py", "desloppify/core/discovery/impl.py", "desloppify/core/io/init.py", "desloppify/core/io/api.py", "desloppify/core/io/impl.py", "desloppify/core/pathing/init.py", "desloppify/core/pathing/api.py", "desloppify/core/pathing/impl.py"], evidence: "Each api.py is 1-to-1 forwarding. Each impl.py is star-import shim with 0 callers. 322 LOC of pure delegation.", suggestion: "Move logic into package modules or remove sub-packages", confidence: high
19. dimension: package_organization, identifier: review-orchestration-trivial-package, summary: "review/orchestration/ is a 3-file package with 19 LOC total: one 11-line function and one constant.", related_files: ["desloppify/app/commands/review/orchestration/init.py", "desloppify/app/commands/review/orchestration/helpers.py", "desloppify/app/commands/review/orchestration/runtime_defaults.py"], evidence: "helpers.py has one function (11 LOC), runtime_defaults.py has one constant (7 LOC).", suggestion: "Merge into parent review/ directory", confidence: high
20. dimension: package_organization, identifier: review-quality-single-file-package, summary: "review/quality/ is a package containing exactly one 77-line file, imported by one caller.", related_files: ["desloppify/app/commands/review/quality/init.py", "desloppify/app/commands/review/quality/assessment_integrity.py"], evidence: "Single-file package with one consumer.", suggestion: "Move to parent review/ directory", confidence: high
21. dimension: package_organization, identifier: review-importing-single-file-package, summary: "review/importing/ wraps exactly one large file (1301 LOC).", related_files: ["desloppify/app/commands/review/importing/init.py", "desloppify/app/commands/review/importing/import_helpers.py"], evidence: "Single large file in a sub-package with empty init.py.", suggestion: "Flatten into parent or split the file to justify the sub-package", confidence: high
22. dimension: package_organization, identifier: review-normalization-single-file-package, summary: "review/normalization/ wraps exactly one file (887 LOC).", related_files: ["desloppify/app/commands/review/normalization/init.py", "desloppify/app/commands/review/normalization/batch_core.py"], evidence: "Single file in sub-package with empty init.py.", suggestion: "Flatten into parent or split the file", confidence: high
23. dimension: high_level_elegance, identifier: multi-layer-compat-forwarding-chain, summary: "Four-layer compat forwarding chain makes canonical import path non-obvious.", related_files: ["desloppify/utils.py", "desloppify/compat/utils.py", "desloppify/core/io/api.py", "desloppify/core/output.py", "desloppify/scoring.py", "desloppify/compat/scoring.py"], evidence: "colorize traverses utils.py -> compat/utils.py -> core/io/api.py -> core/output.py (4 hops). scoring.py has 30+ active callers.", suggestion: "Eliminate layers, migrate callers to canonical paths", confidence: high
BATCH 6 findings:
24. dimension: initialization_coupling, identifier: react_detector_dual_project_root, summary: "react.py defines its own PROJECT_ROOT: Path | None = None instead of importing from core.pathing.api. detect_boolean_state_explosion uses it directly and will crash when None.", related_files: ["desloppify/languages/typescript/detectors/react.py"], evidence: "Line 22: local mutable PROJECT_ROOT. Line 384: PROJECT_ROOT / filepath crashes when None.", suggestion: "Import from core.pathing.api and use _resolve_source_path like other functions in the same file", confidence: high
25. dimension: initialization_coupling, identifier: scattered_project_root_override_pattern, summary: "Seven modules define their own PROJECT_ROOT: Path | None = None as test override hooks, shadowing the canonical DynamicPathProxy.", related_files: ["desloppify/cli.py", "desloppify/app/commands/helpers/state.py", "desloppify/languages/typescript/detectors/react.py", "desloppify/intelligence/review/importing/holistic.py", "desloppify/core/_internal/text_utils.py"], evidence: "Each declares PROJECT_ROOT: Path | None = None at module scope. The canonical system already supports runtime overrides.", suggestion: "Migrate to canonical DynamicPathProxy from core.pathing.api", confidence: medium
26. dimension: initialization_coupling, identifier: commands_imports_phases_for_constants, summary: "commands.py imports constants from phases.py which re-exports from phase_policies.py, forcing loading 14 detector modules just for four constants.", related_files: ["desloppify/languages/typescript/commands.py", "desloppify/languages/typescript/phases.py", "desloppify/languages/typescript/phase_policies.py"], evidence: "commands.py imports TS_COMPLEXITY_SIGNALS etc from phases.py. phases.py imports 14 detector modules.", suggestion: "Import directly from phase_policies.py", confidence: high
27. dimension: design_coherence, identifier: react_detector_inconsistent_path_resolution, summary: "Within react.py, three functions use _resolve_source_path helper but detect_boolean_state_explosion uses raw PROJECT_ROOT / filepath.", related_files: ["desloppify/languages/typescript/detectors/react.py"], evidence: "Three functions safe, one function crashes on None -- internal consistency defect.", suggestion: "Refactor to use _resolve_source_path consistently", confidence: high
28. dimension: design_coherence, identifier: smell_detection_structural_repetition, summary: "Python and TypeScript smells.py both implement nearly identical smell-detection pipelines, indicating a missing shared abstraction.", related_files: ["desloppify/languages/python/detectors/smells.py", "desloppify/languages/typescript/detectors/smells.py"], evidence: "Both define SMELL_CHECKS list, iterate files, run regex matches, build entries with identical sort key pattern.", suggestion: "Extract common smell pipeline into shared framework function", confidence: medium
29. dimension: design_coherence, identifier: generic_lang_registration_side_effects, summary: "generic_lang() performs global registration side effects during construction with no guard against double-registration.", related_files: ["desloppify/languages/_framework/generic.py"], evidence: "Lines 215-223 call register_detector, register_scoring_policy. No guard against double-registration.", suggestion: "Add guard checking for existing registration", confidence: medium
BATCH 2 findings:
30. dimension: convention_outlier, identifier: init-pattern-inconsistency-across-command-packages, summary: "Sibling command sub-packages use at least four different init.py conventions for lazy/eager export.", related_files: ["desloppify/app/commands/scan/init.py", "desloppify/app/commands/show/init.py", "desloppify/app/commands/review/init.py", "desloppify/app/commands/fix/init.py", "desloppify/app/commands/helpers/lazy_exports.py"], evidence: "scan/ uses eager import, show/resolve/plan/fix use lazy_exports helper, move/ uses inline getattr, review/ uses _LEGACY_MODULE_ALIASES.", suggestion: "Converge all onto lazy_exports helper or direct eager imports", confidence: high
31. dimension: convention_outlier, identifier: review-sub-packages-mixed-init-depth, summary: "Six sub-packages under review/ have inconsistent init.py depths.", related_files: ["desloppify/app/commands/review/importing/init.py", "desloppify/app/commands/review/runtime/init.py"], evidence: "Five have bare docstring-only init.py. runtime/ has fully-developed lazy loading.", suggestion: "Give all review sub-packages a consistent init pattern", confidence: high
32. dimension: error_consistency, identifier: duplicated-exception-tuple-show-cmd, summary: "_SHOW_PLAN_LOAD_EXCEPTIONS in show/cmd.py is an exact copy of PLAN_LOAD_EXCEPTIONS from core/exception_sets.py.", related_files: ["desloppify/app/commands/show/cmd.py", "desloppify/core/exception_sets.py"], evidence: "Identical tuples defined in two places.", suggestion: "Import from core/exception_sets.py", confidence: high
33. dimension: error_consistency, identifier: proliferating-ad-hoc-exception-tuples, summary: "Multiple modules define near-identical exception tuples with overlapping but subtly different compositions.", related_files: ["desloppify/core/exception_sets.py", "desloppify/app/output/visualize.py", "desloppify/app/commands/scan/scan_workflow.py", "desloppify/languages/_framework/treesitter/init.py"], evidence: "Four distinct tuples with overlapping but different exception types.", suggestion: "Consolidate into core/exception_sets.py with named sets per domain", confidence: high
34. dimension: mid_level_elegance, identifier: planning-init-double-indirection, summary: "engine/planning/init.py uses args/**kwargs pass-through wrappers that lazily import core.py, which itself is a pure re-export facade.", related_files: ["desloppify/engine/planning/init.py", "desloppify/engine/planning/core.py"], evidence: "Two-layer indirection erasing all type information. Some callers bypass entirely.", suggestion: "Collapse to direct re-exports in init.py", confidence: high
35. dimension: convention_outlier, identifier: namespace-shim-unused-sentinels, summary: "Three core sub-package init.py files define unused __NAMESPACE_SHIM variables.", related_files: ["desloppify/core/discovery/init.py", "desloppify/core/io/init.py", "desloppify/core/pathing/init.py"], evidence: "Variables never referenced. No other init.py follows this pattern.", suggestion: "Remove the unused variables", confidence: high
36. dimension: error_consistency, identifier: orphaned-file-loc-silent-zero-on-read-failure, summary: "orphaned.py _file_loc silently returns 0 on read failure unlike every other detector that uses log_best_effort_failure.", related_files: ["desloppify/engine/detectors/orphaned.py", "desloppify/engine/detectors/large.py"], evidence: "Silent return 0 causes files to be skipped as 'small' instead of 'failed to read'.", suggestion: "Add log_best_effort_failure consistent with other detectors", confidence: high
BATCH 4 findings:
37. dimension: ai_generated_debt, identifier: state_access_pure_forwarding, summary: "state_access.py contains 7 pure forwarding functions with docstrings that merely restate the call.", related_files: ["desloppify/app/commands/helpers/state_access.py"], evidence: "Every function is a one-liner delegating to state_mod. Only 2 callers exist.", suggestion: "Delete and have callers import directly from desloppify.state", confidence: high
38. dimension: ai_generated_debt, identifier: io_api_pure_forwarding, summary: "core/io/api.py forwards every function and constant from core/output.py with zero added logic.", related_files: ["desloppify/core/io/api.py", "desloppify/core/output.py"], evidence: "Every export delegates directly. 90 importers pay for this indirection.", suggestion: "Use re-exports instead of manually defining wrapper functions", confidence: high
39. dimension: ai_generated_debt, identifier: coerce_target_score_defensive_fallback_check, summary: "coerce_target_score validates its own fallback parameter with is_numeric() despite being typed as float.", related_files: ["desloppify/app/commands/helpers/score.py"], evidence: "Lines 10-13: checks is_numeric on a known float parameter. Every call site passes a literal float.", suggestion: "Remove the is_numeric guard", confidence: high
40. dimension: ai_generated_debt, identifier: duplicated_coercion_functions, summary: "coerce_int/coerce_float in scan_coverage.py duplicate logic from core/_internal/coercions.py.", related_files: ["desloppify/app/commands/scan/scan_coverage.py", "desloppify/core/_internal/coercions.py"], evidence: "Same isinstance-chain pattern duplicated.", suggestion: "Replace with canonical coerce functions from coercions_api", confidence: high
41. dimension: incomplete_migration, identifier: impl_shims_zero_importers, summary: "core/io/impl.py, core/discovery/impl.py, core/pathing/impl.py have zero importers.", related_files: ["desloppify/core/io/impl.py", "desloppify/core/discovery/impl.py", "desloppify/core/pathing/impl.py"], evidence: "Grep returns zero matches. Pure dead code.", suggestion: "Delete all three", confidence: high
42. dimension: incomplete_migration, identifier: scoring_three_hop_chain, summary: "Importing from desloppify.scoring traverses a 3-module chain with 30+ active callers still using the root path.", related_files: ["desloppify/scoring.py", "desloppify/compat/scoring.py"], evidence: "30+ production callers. No deprecation warning and no import guard test.", suggestion: "Add deprecation warning, migrate callers, add to import guard test", confidence: high
43. dimension: incomplete_migration, identifier: review_legacy_module_aliases_many_callers, summary: "review/init.py provides legacy aliases with 20+ test callers still using old import paths.", related_files: ["desloppify/app/commands/review/init.py"], evidence: "18 instances of old import paths in test files. No deprecation warning.", suggestion: "Update test imports to new paths and remove aliases", confidence: high
44. dimension: incomplete_migration, identifier: discovery_api_deprecated_still_imported, summary: "core/discovery_api.py emits DeprecationWarning but 4 test files still import from it.", related_files: ["desloppify/core/discovery_api.py"], evidence: "4 test files still use deprecated path.", suggestion: "Update test files to canonical imports", confidence: high
45. dimension: ai_generated_debt, identifier: compute_ts_inline_types_unused_lines_param, summary: "compute_ts_inline_types accepts a lines parameter then immediately discards it with _ = lines.", related_files: ["desloppify/languages/typescript/phase_policies.py"], evidence: "Line 19-21: parameter accepted and discarded.", suggestion: "Change callback type to make lines optional", confidence: medium
BATCH 7 findings:
46. dimension: cross_module_architecture, identifier: engine-reaches-into-core-internal, summary: "Engine modules violate core._internal boundary by importing DynamicPathProxy directly.", related_files: ["desloppify/engine/_state/schema.py", "desloppify/engine/_plan/persistence.py", "desloppify/core/_internal/path_proxy.py"], evidence: "Both engine modules import from core._internal.path_proxy. No architecture test guards this.", suggestion: "Export DynamicPathProxy through core.pathing.api and add boundary test", confidence: high
47. dimension: cross_module_architecture, identifier: scoring-shim-still-used-in-production, summary: "20 production modules import from desloppify.scoring (legacy shim) with no import guard preventing drift.", related_files: ["desloppify/scoring.py", "desloppify/compat/scoring.py", "desloppify/engine/work_queue/helpers.py"], evidence: "20 production files use root-level shim. Not in import guard test.", suggestion: "Add to import guard test and migrate callers", confidence: high
48. dimension: test_strategy, identifier: smoke-callable-tests-inflate-coverage, summary: "test_direct_coverage*.py files contain primarily import-and-assert-callable tests that verify importability but not behavior.", related_files: ["desloppify/tests/commands/test_direct_coverage_modules.py", "desloppify/tests/commands/test_direct_coverage_additional_modules.py"], evidence: "Dominant pattern: import module, assert callable, no invocation. Zero behavioral contracts tested.", suggestion: "Supplement with behavioral tests for critical functions", confidence: high
49. dimension: test_strategy, identifier: no-architecture-guard-for-internal-boundary, summary: "core._internal boundary is not enforced by any architecture test.", related_files: ["desloppify/tests/detectors/test_architecture_boundaries.py", "desloppify/tests/lang/common/test_import_boundaries.py"], evidence: "Existing tests check other boundaries but not _internal. Active violations exist.", suggestion: "Add architecture test scanning for non-core imports from core._internal", confidence: high
50. dimension: package_organization, identifier: core-package-has-parallel-flat-and-structured-namespaces, summary: "core/ has 24 files alongside 3 subpackages that duplicate the same functionality through shim layers.", related_files: ["desloppify/core/output.py", "desloppify/core/io/api.py", "desloppify/core/file_paths.py", "desloppify/core/pathing/api.py"], evidence: "For output/IO: 5 files (output.py, io/api.py, io/impl.py, output_api.py, io/init.py). All for one concern.", suggestion: "Make structured packages canonical and remove redundant flat files", confidence: high
BATCH 9 findings:
51. dimension: type_safety, identifier: state-model-undeclared-fields, summary: "StateModel TypedDict is missing at least 5 fields actively written and read across 30+ callsites.", related_files: ["desloppify/engine/_state/schema.py", "desloppify/app/commands/scan/scan_workflow.py"], evidence: "scan_path (18 files), lang_capabilities (9 files), zone_distribution (9 files), reminder_history (7 files), review_cache -- all undeclared in StateModel but actively used.", suggestion: "Add missing fields as NotRequired entries to StateModel", confidence: high
52. dimension: type_safety, identifier: scoring-engine-bare-dict-params, summary: "Five public functions in engine/_scoring/results/core.py accept findings as bare dict with no type parameters.", related_files: ["desloppify/engine/_scoring/results/core.py", "desloppify/engine/_scoring/detection.py"], evidence: "results/core.py uses bare dict. Sibling detection.py correctly uses dict[str, Finding].", suggestion: "Replace bare dict with dict[str, Finding]", confidence: high
53. dimension: contract_coherence, identifier: resolve-findings-overwrites-then-overrides, summary: "resolve_findings() builds a base updates dict with semantically wrong defaults that are silently corrected by per-status overrides.", related_files: ["desloppify/engine/_state/resolution.py"], evidence: "Base dict sets resolved_at=now for all statuses including 'open'. Open branch overrides to None.", suggestion: "Build updates dict conditionally per status branch", confidence: high
54. dimension: contract_coherence, identifier: wontfix-gets-resolved-at-timestamp, summary: "wontfix findings get a resolved_at timestamp, which is semantically incorrect.", related_files: ["desloppify/engine/_state/resolution.py", "desloppify/engine/_state/schema.py"], evidence: "Base updates sets resolved_at=now, wontfix branch doesn't override it.", suggestion: "Set resolved_at only for genuinely resolved statuses", confidence: high
55. dimension: api_surface_coherence, identifier: inconsistent-dict-typing-across-scoring-api, summary: "Scoring API mixes unparameterized dict with typed dict variants for the same conceptual parameters.", related_files: ["desloppify/engine/_scoring/results/core.py"], evidence: "compute_dimension_scores_by_mode takes dict, ScoreBundle uses dict[str, dict], compute_health_breakdown takes dict.", suggestion: "Establish type aliases and use consistently", confidence: high
56. dimension: type_safety, identifier: scan-workflow-potentials-type-mismatch, summary: "run_scan_generation declares potentials as dict[str, object] but actual values are ints.", related_files: ["desloppify/app/commands/scan/scan_workflow.py"], evidence: "Return type dict[str, object] but writes int values. Consumer expects dict[str, int].", suggestion: "Type potentials as dict[str, int] throughout", confidence: high
57. dimension: naming_quality, identifier: collect-dimension-rows-opaque-tuple-return, summary: "_collect_dimension_rows returns a 6-element tuple with no named structure.", related_files: ["desloppify/engine/_scoring/results/core.py"], evidence: "Returns (float, float, float, float, list, list). Callers destructure by position.", suggestion: "Replace with NamedTuple or dataclass", confidence: high
58. dimension: logic_clarity, identifier: resolve-findings-double-attestation-build, summary: "resolve_findings() builds attestation dict in base then builds a second one for 'open' branch that overwrites it.", related_files: ["desloppify/engine/_state/resolution.py"], evidence: "Base attestation constructed but immediately thrown away for 'open' status.", suggestion: "Factor into per-status branches", confidence: high
59. dimension: api_surface_coherence, identifier: discovery-api-language-specific-finders, summary: "discovery/api.py exports language-specific find_ts_files, find_tsx_files, find_py_files in a language-agnostic API surface.", related_files: ["desloppify/core/discovery/api.py", "desloppify/core/source_discovery.py"], evidence: "Language-specific wrappers in core/discovery which should be language-agnostic.", suggestion: "Move language-specific finders into respective language plugins", confidence: medium
60. dimension: contract_coherence, identifier: gather-auth-context-return-type-lie, summary: "gather_auth_context constructs a rich typed AuthorizationSignals but immediately discards type information by converting to dict.", related_files: ["desloppify/intelligence/review/context_signals/auth.py"], evidence: "Builds dataclass, returns .as_dict(). Callers lose typed access.", suggestion: "Return the dataclass directly", confidence: medium
BATCH 8 findings:
61. dimension: design_coherence, identifier: operations_describe_annotate_duplication, summary: "describe_finding and annotate_finding are structurally identical functions differing only in which dict key they set.", related_files: ["desloppify/engine/_plan/operations.py"], evidence: "Lines 320-330 and 333-343 share identical 6-line bodies, differing only in 'description' vs 'note'.", suggestion: "Extract shared _set_override_field helper", confidence: high
62. dimension: design_coherence, identifier: resolve_options_noop_isinstance_branches, summary: "_resolve_skip_item_options contains isinstance branches where both arms return the same value.", related_files: ["desloppify/engine/_plan/operations.py"], evidence: "Line 69: both branches evaluate to values['reason']. Dead conditionals.", suggestion: "Remove the no-op conditionals", confidence: high
63. dimension: design_coherence, identifier: resolve_options_duplicated_pattern, summary: "_resolve_generic_lang_options duplicates full GenericLangOptions construction twice with identical field-by-field logic.", related_files: ["desloppify/languages/_framework/generic.py"], evidence: "Lines 264-278 and 294-308: identical list() wrapping and None checks.", suggestion: "Return options directly when no legacy kwargs exist", confidence: high
64. dimension: design_coherence, identifier: runner_helpers_mixed_responsibilities, summary: "runner_helpers.py is over 700 lines mixing subprocess management, thread orchestration, stall detection, blind packet sanitization, parallel execution, retry logic, and progress dispatch.", related_files: ["desloppify/app/commands/review/runtime/runner_helpers.py"], evidence: "10+ dataclasses, imports threading/subprocess/concurrent.futures/time/json/hashlib.", suggestion: "Extract subprocess execution/stall detection and parallel orchestration into separate modules", confidence: high
65. dimension: design_coherence, identifier: batch_core_parameter_proliferation, summary: "merge_batch_results passes abstraction-specific parameters through 4 levels of general scoring functions.", related_files: ["desloppify/app/commands/review/normalization/batch_core.py"], evidence: "abstraction_sub_axes and abstraction_component_names threaded through general-purpose functions.", suggestion: "Group into dataclass or move to post-processing", confidence: medium
66. dimension: design_coherence, identifier: ts_phases_repeated_finding_construction, summary: "phases.py repeats identical make_finding loops across 7+ detector results.", related_files: ["desloppify/languages/typescript/phases.py"], evidence: "Same loop-and-make_finding pattern in phase_logs, phase_exports, phase_deprecated, etc. Shared framework already has _entries_to_findings.", suggestion: "Use or extend _entries_to_findings from shared_phases.py", confidence: medium
Write the complete JSON to /Users/user_c042661f/Documents/desloppify/.desloppify/external_review_sessions/ext_20260228_233656_9ea6b4e8/review_result.json
Make sure all findings have string evidence (not arrays), string related_files arrays, and all required fields.
Here's an example of how your output should be structured:
Key Technical Concepts:
[Concept 1]
[Concept 2]
[...]
Files and Code Sections:
[File Name 1]
[Summary of why this file is important]
[Summary of the changes made to this file, if any]
[Important Code Snippet]
[File Name 2]
[Important Code Snippet]
[...]
Errors and fixes:
[Detailed description of error 1]:
[How you fixed the error]
[User feedback on the error if any]
[...]
Problem Solving:
[Description of solved problems and ongoing troubleshooting]
All user messages:
[Detailed non tool use user message]
[...]
Pending Tasks:
[Task 1]
[Task 2]
[...]
Current Work:
[Precise description of current work]
Optional Next Step:
[Optional Next step to take]
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
Compact Instructions
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
IMPORTANT: Do NOT use any tools. You MUST respond with ONLY the ... block as your text output.
User asked if working through the queue would fix things: I said no — the queue is a flat list of independent observations, not a coherent plan. Some suggestions contradict each other.
User asked if insufficient detail was the problem: I said no — the detail is good. The problem is lack of coherence and thesis per group, and some suggestions pointing in contradictory directions.
User proposed a synthesis step: After subjective review findings land, an LLM step would read all findings together, cluster by root cause, assign a thesis per cluster, resolve contradictions, and build an ordered execution plan with "epics."
User asked me to make a plan for this: This is the most recent request before the summary request.
Key files and paths:
.desloppify/state-python.json - state file that was backed up and modified
Initially ran Codex sub-agents instead of Claude sub-agents
Evidence field needed to be array not string
Missing findings for dimensions below thresholds (dependency_health, authorization_consistency)
The user's final request before the summary was "Can you make a plan for this?" referring to the epic synthesis step.
Phase 1: Critically review ~349 changed files (18K insertions, 15K deletions) to determine if the refactoring genuinely improves structure or just moves code around.
Phase 2: Diagnose the ROOT CAUSE of why the refactoring went wrong by examining desloppify's own scan/plan/review output.
Phase 3: Clear all subjective assessments and re-run the full subjective review from a clean slate to see what the tool finds fresh.
Phase 4: Compare fresh review findings against the manual analysis to validate whether the tool points in the right direction.
Phase 5: Design a new "epic synthesis" step in the desloppify pipeline — an LLM-driven plan reconciliation that runs after subjective review findings are imported, grouping findings into root-cause-based epics with theses and contradiction resolution.
The user's final explicit request was: "Can you make a plan for this?" — referring to implementing the epic synthesis step in the desloppify codebase.
Key Technical Concepts:
Desloppify architecture: Python CLI, language plugins, state persistence in .desloppify/state-{lang}.json, dimension-based scoring (mechanical + subjective)
Two scoring tracks: Mechanical (96.4%, concrete/measurable) and Subjective (62.4%, LLM-assessed across 20 dimensions)
The feedback loop problem: Tool flags low scores → agent reorganizes files → tool flags new problems → score plateaus
desloppify/engine/_scoring/results/core.py - Uses bare dict instead of dict[str, Finding]
Existing plan infrastructure (relevant to proposed epic synthesis):
desloppify/engine/_plan/auto_cluster.py - Current mechanical clustering (588 LOC)
desloppify/engine/_plan/reconcile.py - Runs after scan to align plan with findings
desloppify/engine/_plan/operations.py - Plan mutations (move, describe, skip, etc.)
desloppify/engine/_plan/schema.py - Plan data model
desloppify/engine/_plan/persistence.py - Plan JSON I/O
desloppify/app/commands/scan/scan_workflow.py - Where reconciliation is triggered (best-effort after scan save)
Errors and fixes:
Used Codex sub-agents instead of Claude sub-agents:
Tool's prepare output said "Preferred: codex" and I followed literally
User pointed out this was the same failure mode as the refactoring — mechanically following tool suggestions
Fixed by killing Codex run (TaskStop) and using --external-start --external-runner claude + Task tool sub-agents
Evidence field format error: Schema expected evidence as array of strings, not single string
Fixed by converting all evidence strings to single-element arrays: f["evidence"] = [f["evidence"]]
Missing findings for dimensions below threshold: dependency_health (78.0) required at least one finding; authorization_consistency (90.0) required finding for any score below 100
Fixed by adding findings for those dimensions
Subjective_review findings blocking review prepare: After clearing state and running scan, the scan recreated 319 subjective_review "unreviewed" marker findings that blocked --prepare
Fixed by clearing them from state again via Python script, then using --force-review-rerun
Problem Solving:
Diagnosed the plateau problem: Score stuck at 76.9 for 10+ scans because refactoring addressed symptoms (flat dirs, scattered imports) with structural moves, while underlying diseases (loose typing, duplicated logic, unnecessary abstraction) require semantic changes
Identified the feedback loop: Tool flags problem → agent does mechanical fix → tool flags the fix as a new problem → score doesn't move
Validated tool's diagnostic capability: Fresh review from 9 Claude sub-agents produced 68 findings that overwhelmingly confirmed manual analysis. AI debt dropped 87→38, incomplete migration 63→42
Identified the pipeline gap: Between review findings and execution, there's no synthesis step to compose independent observations into coherent epics with theses
All user messages:
"Can you look at all the, there's a lot of changes in the local branch and I'm trying to do a refactoring work, but can you look very critically at the work and try to understand if we're genuinely improving the structure or if we're just moving stuff around. Basically I'm trying to push it up to engineering best practices and try to understand if I'm doing a good job."
"can you look at the desloppify issues and scan and plan and try to understand why this is? Look, try to get to the root of the actual issue."
"Can you re-run all of the subjective analysis? And let me know if it fixes those problems, if it flags all these problems. Try to just re-run it across every dimension and maybe even remove all the current open subjective issues, just so we start from a clean slate. You might need a new way to do actually no, don't let's just, just rerun them all actually just clear all the current ones or mark them all no fix and then rerun them all and get a view of what's happening."
"And try to understand if first of all if it points you towards running them with sub agents one sub agent per dimension and then if it gets or if it kind of points in the right direction of the flag issues that you just flagged"
"So why aren't you running it using Cloud Subagents? Is there a confusion in your instruction?"
"Claude subagents i mean"
"Can you try to understand why you got confused about this as well um try to think meta about this"
"Like why were you misdirected? You know claude should just run your instructions to tell you that you should run it with claude"
[Included my earlier analysis about the real issues and meta-problem as context for comparison]
"So if you worked through all the open queue, do you think it would be in a good state?"
"Is there insufficient detail on the task for them to execute correctly? Is that the problem?"
"So do you think we need a step after we find new subjective items that would make them into a coherent meta plan?"
"What if we have a step whenever a new subjective issue appears that we have to make a plan on how to integrate it into the overall plan and then basically what we do is we each plan has a kind of meta focus and then we kind of clean up and prioritize move around and remove things based on it so basically we take this kind of like meta run through the plan using all the various planning tools after there's any kind of subjective step that changed and we um basically reprioritize it and give it kind of a kind of i don't know like an epic focus or something like that and even clean it and remove stuff um but try to make it kind of like really ambitious but coherent so it's kind of like another step for an llm who basically looks at all the stuff in the queue and actually makes a plan on how to do and tries to spot all these contradictory things that make sense and just builds the actual queue"
Pending Tasks:
Make a plan for implementing the epic synthesis step in desloppify — this is the user's final explicit request before the summary was requested. The plan should cover adding an LLM-driven reconciliation step that runs after subjective review findings are imported, clustering findings into root-cause-based epics with theses, resolving contradictions, and producing an ordered execution queue.
Current Work:
The most recent substantive work was designing the epic synthesis feature at a high level. I described:
The epic schema: thesis, direction (enum), findings list, actions, supersedes, agent_safe
The trigger: runs after any subjective finding change
The LLM call: reads all open findings + current plan state, outputs epic definitions
Where it fits in existing code: after auto_cluster.py, alongside reconcile.py
The user then asked "Can you make a plan for this?" — meaning create a detailed implementation plan for this feature in the desloppify codebase.
Optional Next Step:
Create a detailed implementation plan for the "epic synthesis" feature. This should examine the existing plan infrastructure (engine/_plan/auto_cluster.py, reconcile.py, operations.py, schema.py, persistence.py), the review import flow (app/commands/review/import_cmd.py, intelligence/review/importing/), and the scan workflow trigger point (app/commands/scan/scan_workflow.py) to design where the synthesis step plugs in, what the schema looks like, and how the LLM call is structured.
User's exact request: "Can you make a plan for this?" — referring to the epic synthesis step described in the immediately preceding messages.
Key invariants:
No finding ID can appear in both queue_order and skipped
skip_kind must be in {"temporary", "permanent", "false_positive"}
Error handling: Wrapped in try/except for _PLAN_SYNC_EXCEPTIONS and _PLAN_SYNC_UNEXPECTED_EXCEPTIONS:
Sets state.plan_sync_failed = True
Logs warnings
Records scan warning but doesn't fail the scan
Prints user-facing colorized status updates
Status messages printed:
code
Plan: N skipped item(s) re-surfaced after review period.
Plan: N unscored subjective dimension(s) queued for initial review.
Plan: N refreshed subjective dimension(s) removed from queue.
Plan: N stale subjective dimension(s) queued for refresh.
Subjective dimensions are synthetic findings: Stored as subjective::<slug> IDs in queue
Front-injected for initial scoring
Stale ones interleaved on bounded cadence to prevent starvation
Managed separately from objective findings
Superseded entries track context: When findings disappear, the plan records
Original detector/file/summary for audit trail
Up to 5 candidate replacement findings
User notes are preserved
90-day TTL before cleanup
Atomic writes with backup: All plan saves are atomic with .json.bak backups
Corruption handling returns empty plan gracefully
Validation happens on load and save
Scan integration is best-effort: Plan reconciliation errors don't fail the scan
Errors logged, state marked with plan_sync_failed flag
User sees colored status messages
This is the complete infrastructure. The plan is a sophisticated living document that manages both objective findings and subjective dimensions, with smart clustering, skip tracking, and bounded interleaving to prevent queue inversion.
Evidence-first subjective scoring: Open review findings override assessment scores — the import only stores metadata, actual pass-rate is computed from findings.
Provisional vs. durable: Manual overrides are temporary (provisional until next scan); trusted internal/attested external are durable.
Holistic staleness: Auto-resolves findings not re-imported, respects dimension scope (full sweep vs. partial).
Mechanical → subjective linkage: When detectors change, dependent subjective dimensions marked stale for human re-review.
State Integration: Store synthesis results similarly to review findings (new detector="epic_synthesis" perhaps)
Work Queue: Synthesis findings appear as high-tier items reflecting epic decomposition
The entire system is built around subprocess delegation to Claude Code agents via the codex tool, with sophisticated prompt construction, parallel execution, result merging, and state integration.
Reconciliation (engine/_plan/reconcile.py)
reconcile_plan_after_scan(plan, state) — supersedes disappeared findings, resurfaces stale skips
Called in scan_workflow.py's _reconcile_plan_best_effort()
Plan Operations (engine/_plan/operations.py)
move_items, skip_items, create_cluster, add_to_cluster, move_cluster, purge_ids, etc.
Clusters are created via create_cluster() and populated via add_to_cluster()
Plan Persistence (engine/_plan/persistence.py)
load_plan / save_plan — atomic JSON writes with backup
Epics should coexist with auto-clusters (different prefix, different purpose)
Don't break existing plan operations (move, skip, focus work with epics too)
The LLM call must be subprocess-based (codex exec or claude CLI) following existing patterns
Synthesis should be idempotent — re-running updates existing epics rather than duplicating
Must work without LLM (degrade gracefully if synthesis fails/skipped)
Please produce a detailed implementation plan with specific files to create/modify, function signatures, data structures, and integration points.
2.2 Extend PlanModel with epics field
In the same schema.py file, add to PlanModel:
python
class PlanModel(TypedDict, total=False):
# ... existing fields ...
epics: dict[str, Epic] # keyed by epic name
epic_synthesis_meta: dict # synthesis run metadata
Update empty_plan() to include "epics": {} and "epic_synthesis_meta": {}.
Update _ensure_plan_container_types() to ensure epics is a dict.
Update validate_plan() to validate epic directions and ensure no finding appears in both an epic's supersedes list and queue_order.
2.3 Naming Convention
Epic names use the epic/ prefix (distinct from auto/ for auto-clusters), e.g.:
epic/delete-compat-layer
epic/consolidate-path-utilities
epic/enforce-registry-pattern
This prefix must be rejected by create_cluster() (manual user clusters) in the same way auto/ is already rejected:
python
if name.startswith("auto/") or name.startswith("epic/"):
raise ValueError(...)
3. Core Synthesis Module
New file:/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/epic_synthesis.py
This module contains all synthesis logic: prompt building, result parsing, plan mutation.
3.1 Input Collection
python
@dataclass(frozen=True)
class SynthesisInput:
"""All data needed for the LLM synthesis call."""
open_findings: list[dict] # All open findings (review + mechanical)
existing_clusters: dict[str, dict] # Current auto-clusters
existing_epics: dict[str, dict] # Previous synthesis results (for idempotency)
plan_queue_order: list[str] # Current queue ordering
superseded: dict[str, dict] # Already-superseded items
dimension_scores: dict # Current scorecard for context
def collect_synthesis_input(
plan: PlanModel,
state: StateModel,
) -> SynthesisInput:
"""Gather all inputs needed for epic synthesis."""
This function reads all open findings from state["findings"], the current clusters and epics from the plan, and dimension scores from state. It filters to only open, non-suppressed findings.
3.2 Prompt Construction
python
EPIC_PREFIX = "epic/"
def build_synthesis_prompt(
synthesis_input: SynthesisInput,
) -> str:
"""Build the structured prompt for the LLM synthesis call."""
The prompt follows the existing pattern from batch_prompt_template.py: structured text sections with a JSON output schema. Key prompt sections:
Context block -- All open findings as a JSON list with id, detector, file, tier, summary, detail.dimension, detail.kind. Truncated summaries to control token count.
Existing cluster block -- Current auto-clusters showing what mechanical grouping has already done, so the LLM knows what it is replacing.
Previous epics block (for re-synthesis) -- Any existing epics from prior runs, so the LLM can update rather than recreate.
Dimension scores block -- Current scorecard to give the LLM context on what areas are already strong vs weak.
Task requirements block -- Explicit instructions:
Group by ROOT CAUSE, not detector/dimension
Each epic must have: name, thesis (one-line imperative), direction (enum), root_cause, finding_ids, supersedes, agent_safe, dependency_order, action_steps
Identify contradictions: if two findings suggest opposite actions, mark the weaker one in supersedes
Order by dependency: lower dependency_order means "do this first"
agent_safe = true only for mechanical changes with clear scope
Output schema block -- JSON schema for the response:
@dataclass(frozen=True)
class SynthesisRunnerDeps:
"""Injectable dependencies for the subprocess call."""
subprocess_run: object # subprocess.run or mock
timeout_seconds: int = 10 * 60 # 10 minutes default
timeout_error: type[BaseException] = TimeoutError
repo_root: Path | None = None
output_dir: Path | None = None
def run_synthesis_llm(
prompt: str,
deps: SynthesisRunnerDeps,
) -> dict | None:
"""Execute LLM synthesis via subprocess. Returns parsed JSON or None on failure."""
This follows the existing codex_batch_command pattern from runner_helpers.py:
Write the prompt to a temp file (or pass inline)
Build the codex exec command with --ephemeral, workspace-write sandbox
Direct output to a JSON file via -o
Parse the output JSON on success
Return None on timeout/failure (graceful degradation)
The function should also support a claude runner path (for claude CLI) following the existing _EXTERNAL_SUPPORTED_RUNNERS pattern in external.py.
3.4 Result Parsing and Validation
python
@dataclass
class SynthesisResult:
"""Parsed and validated LLM synthesis output."""
epics: list[dict]
unassigned_findings: list[str]
contradiction_notes: list[dict]
parse_errors: list[str]
def parse_synthesis_result(
raw: dict,
valid_finding_ids: set[str],
) -> SynthesisResult:
"""Validate and normalize LLM synthesis output against known finding IDs."""
Validation rules:
Each finding_id must exist in valid_finding_ids
Direction must be in VALID_EPIC_DIRECTIONS
No finding can appear in multiple epics
Superseded finding_ids must exist
Epic names are slugified with epic/ prefix
Dependency order is normalized to integers 1..N
3.5 Plan Mutation
python
@dataclass
class SynthesisMutationResult:
"""Summary of changes made during epic synthesis."""
epics_created: int
epics_updated: int
findings_superseded: int
findings_reordered: int
errors: list[str]
def apply_synthesis_to_plan(
plan: PlanModel,
state: StateModel,
synthesis: SynthesisResult,
) -> SynthesisMutationResult:
"""Apply validated synthesis results to the plan.
1. Create/update epic entries in plan["epics"]
2. Mark contradicted findings as superseded
3. Reorder queue_order by epic dependency_order
4. Update override metadata for epic membership
"""
This function:
Clears previous auto-generated epics (those with auto=True)
Creates new Epic entries in plan["epics"]
For each superseded finding_id, calls _supersede_id() from reconcile.py or adds a SupersededEntry
Reorders queue_order so that epic members are grouped together and ordered by dependency_order
Updates plan["overrides"] to track epic membership (similar to how auto-clusters track cluster membership)
Records synthesis metadata in plan["epic_synthesis_meta"]:
def _epic_membership(epics: dict) -> dict[str, str]:
"""Build mapping of finding id to epic name."""
finding_to_epic: dict[str, str] = {}
for epic_name, epic in epics.items():
for finding_id in epic.get("finding_ids", []):
finding_to_epic[finding_id] = epic_name
return finding_to_epic
When epics exist, they take precedence over auto-clusters for grouping. Epics render as a cluster-like meta-item with additional metadata:
Consider adding a plan epics subcommand (or plan synthesize show) to display the current epic state:
code
Epic: epic/delete-compat-layer (dependency_order: 1, agent_safe: true)
Direction: delete
Thesis: Delete the compat/ layer -- all callers should import from core directly
Root cause: Unnecessary compatibility shim created during migration
Findings: 5
Steps:
1. Remove compat/ directory
2. Update all imports to point to core
3. Run scan to verify
Existing operations in operations.py work on finding IDs. Since epic finding_ids are the same finding IDs already in the plan, move/skip/focus continue to work. However, we need:
move_cluster should also accept epic names (prefixed with epic/)
set_focus should accept epic names
delete_cluster should handle epic deletion (clear from plan["epics"])
These require small additions to the existing operation functions to check plan["epics"] when a name starts with epic/.
9.2 Auto-Clustering Coexistence
Auto-clusters (prefix auto/) and epics (prefix epic/) coexist. When epics exist:
Auto-clusters are still generated on scan (they are the input to synthesis)
In the work queue, when collapse_clusters=True, epics take precedence: findings assigned to both an auto-cluster AND an epic appear under the epic
Auto-clusters with ALL findings absorbed by epics can be hidden from display
reconcile_plan_after_scan() must also check epics:
If a finding in an epic is no longer alive, remove it from the epic's finding_ids
If an epic has zero remaining findings, delete it
Track epic references in referenced_ids collection
10. Schema Version
Bump PLAN_VERSION from 2 to 3 in schema.py. Add migration logic in ensure_plan_defaults():
python
if "epics" not in plan or not isinstance(plan.get("epics"), dict):
plan["epics"] = {}
if "epic_synthesis_meta" not in plan or not isinstance(plan.get("epic_synthesis_meta"), dict):
plan["epic_synthesis_meta"] = {}
This is backward-compatible: old plans without epics simply get empty dicts.
11. Testing Strategy
New file:/Users/user_c042661f/Documents/desloppify/desloppify/tests/plan/test_epic_synthesis.py
Key test cases:
Schema tests: Epic TypedDict validation, plan version migration, epic container defaults
Input collection: collect_synthesis_input correctly gathers open findings, filters suppressed, includes clusters
Prompt construction: build_synthesis_prompt produces expected sections with finding data
Result parsing: Valid/invalid LLM outputs, unknown finding IDs rejected, direction enum validation, deduplication
Plan mutation:
Epics created in plan["epics"]
Superseded findings added to plan["superseded"] and removed from queue_order
Queue reordered by dependency
Idempotency: re-running replaces existing epics
Graceful degradation: None LLM result produces empty mutation result, no plan corruption
Reconciliation: Dead findings pruned from epics, empty epics deleted
Work queue: Epic collapse, dependency ordering, interaction with auto-clusters
Operations: move/skip/focus work with epic names
Tests should follow the pattern from test_auto_cluster.py using the _finding() and _state_with() helpers.
12. Implementation Sequence
The work should be done in this order to ensure each step is independently testable:
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/epic_synthesis.py - New file: entire synthesis pipeline (prompt, LLM call, parsing, plan mutation)
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py - Queue integration: epic-aware collapse and dependency ordering
/Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups_admin.py - CLI wiring: plan synthesize subcommand and --synthesize import flag
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/cmd.py - Dispatch: route "synthesize" action to handler