Explore the subjective review system in desloppify. I need to understand the full pipeline:
How review --prepare works — trace from the CLI command through to the query.json output. Look at desloppify/commands/review_cmd.py and how it calls into review.py.
How review --import works — trace from CLI through import_review_findings and import_holistic_findings into state merge.
How review findings flow into scoring — look at desloppify/scoring.py for how review/subjective_review dimension scores and finding weights work. Look for HOLISTIC_MULTIPLIER, HOLISTIC_POTENTIAL, CONFIDENCE_WEIGHTS, and how review_assessments feed into the final score.
How review_coverage detector integrates — desloppify/detectors/review_coverage.py and where it's called from in the scan pipeline.
The issues command — desloppify/commands/issues_cmd.py and desloppify/issues.py.
Be very thorough — read the actual files, trace the code paths, note the exact function signatures and data shapes.
Assistant
I'll thoroughly explore the subjective review system in desloppify. Let me start by examining the key files in parallel.
Assistant
Now let me read the issues files:
Assistant
Now let me check the state.py to understand the Finding TypedDict and merge_scan:
User
Explore the holistic review context-building system in desloppify/review.py in detail. I need to understand:
build_holistic_context() and _build_holistic_context_inner() — what data is gathered for each of the 8 current dimensions, what heuristics are used, what the output shape looks like.
_build_investigation_batches() — how files are selected for each batch, how batches map to dimensions.
HOLISTIC_DIMENSION_PROMPTS — all 8 current dimensions, their descriptions, look_for, and skip lists.
HOLISTIC_REVIEW_SYSTEM_PROMPT — the full system prompt sent to the reviewing agent.
_serialize_context() — what goes into the context dict that the reviewing agent sees.
ReviewContext dataclass — what fields are populated and how.
Also check: what's the relationship between per-file dimensions and holistic dimensions? Some names overlap (cross_module_architecture, convention_outlier, error_consistency). How does that work in scoring?
Assistant
I'll explore the holistic review context-building system in detail. Let me start by reading the review.py file and examining the structure.
Assistant
Let me continue reading state.py to see make_finding and merge_scan:
Assistant
Now let me search for additional context about the holistic dimensions and scoring integration to ensure I have a complete picture:
Assistant
Now let me trace how review findings flow through the scan pipeline. Let me check the scan command:
Assistant
Let me read the scoring.py file to understand the holistic dimensions better:
User
Explore how review findings and assessments feed into the scoring system in desloppify. I need to understand:
desloppify/scoring.py — read the entire file. How do review_assessments work? What is HOLISTIC_MULTIPLIER, HOLISTIC_POTENTIAL, CONFIDENCE_WEIGHTS? How does the review dimension factor into the objective score? What are the scoring dimensions and tiers?
desloppify/state.py — how are review findings stored? What does make_finding() look like? How does merge_scan handle review findings differently from programmatic ones? What's the review_cache structure?
desloppify/narrative/ — how do review findings appear in narrative output? Check core.py, actions.py, dimensions.py for any review-specific logic.
Look for how review_assessments in state feeds back into the score. Is there a separate scoring path for subjective assessments vs. finding-based scoring?
Check what potentials structure looks like for review — how is the "denominator" determined for review scoring?
Be very thorough. I need to understand the math.
Assistant
Perfect! Let me now check the issues.py to understand how holistic findings are integrated with the issues command:
Assistant
I'll help you understand how review findings and assessments feed into the scoring system. Let me start by exploring the key files.
Assistant
Now let me check how review_coverage is called in the plan.py:
Assistant
Now let me check the test files to understand how the holistic system is tested:
Assistant
Now let me read the narrative files to understand how review findings appear in narrative output:
Assistant
Let me search in the scan phase implementation:
Assistant
Now let me check the narrative init.py to see constants, and look for more details on how review_assessments work:
Assistant
Perfect! Now let me check one more file to see how the per-file dimensions map to holistic dimensions:
Assistant
Perfect! Let me check the phase implementation in base.py:
Assistant
Let me now look at review.py and related files to understand the assessment mechanism:
Assistant
Now let me check how this phase is called in plan.py:
Assistant
Now let me search for more specific information about how review_assessments flow through the scoring:
Assistant
Now let me check the lang config's phase setup:
Assistant
Let me check the TypeScript and Python lang configs to see how phases are defined:
Assistant
Perfect! Now let me look at the state recomputation to see how review assessments flow through to scoring:
Assistant
Perfect! Now I have a comprehensive understanding. Let me create a final summary document by reading a few more key files to understand the complete picture:
Assistant
Assistant
Assistant
User
Assistant
I'll start by thoroughly exploring the codebase to understand the current review system architecture, then design a comprehensive plan.
Assistant
Now let me examine the remaining key files to understand the full picture.
Assistant
Now let me explore the test files and remaining key files to understand patterns for testing and the existing helpers.
Assistant
Let me continue reading the lang/base.py for the shared phase runners and look at how the security detectors and existing context gathering works to understand the full pattern.
Assistant
Now let me look at a few more things -- the security detector patterns (for auth/RLS context-gathering reference), the narrative module, and the existing unstaged changes to understand what's already in progress.
Assistant
Let me see the unstaged changes to review.py to understand what's already been done.
Assistant
Good - review.py is not a package, it's a single file. Let me now look at the TS security detectors for auth pattern reference, and the narrative module for integration points.
Assistant
Now let me look at the narrative headline module to understand how security headlines were added, as a pattern for review-dimension-driven headlines.
Assistant
Now I have a thorough understanding of the entire system. Let me look at the existing holistic_findings.json test file to understand the output format.
Assistant
Be thorough — read every prompt, every dimension definition.
Perfect! Now I have a comprehensive understanding. Let me create a detailed analysis document.
Summary: Review Findings & Assessment Scoring in Desloppify
I've thoroughly explored the codebase and can now provide you with a complete understanding of how review findings and assessments feed into the scoring system. Here's the comprehensive breakdown:
1. Scoring Fundamentals (scoring.py)
Dimensions and Tiers
The system defines 14 scoring dimensions with tier weights:
Precedence: Holistic scores overwrite per-file scores for the same dimension; per-file scores never overwrite holistic
How Assessments Become Scoring Dimensions
In compute_dimension_scores() (lines 217-246 in scoring.py):
python
def compute_dimension_scores(
findings: dict,
potentials: dict[str, int],
*,
strict: bool = False,
review_assessments: dict | None = None, # <- ENTRY POINT
) -> dict[str, dict]:
"""Each assessment becomes a first-class tier-4 dimension."""
results = {} # First process all detector-based dimensions normally
# THEN append assessment dimensions
if review_assessments:
for dim_name, assessment in review_assessments.items():
display = dim_name.replace("_", " ").title()
# Extract the score (clamped 0-100)
score = max(0, min(100, assessment.get("score", 0)))
pass_rate = score / 100.0
# Count open review findings for this dimension
issue_count = sum(
1 for f in findings.values()
if f.get("detector") == "review"
and f["status"] in failure_set
and f.get("detail", {}).get("dimension") == dim_name
)
# Create a tier-4 dimension with ASSESSMENT_CHECKS (10) potential
results[display] = {
"score": round(float(score), 1),
"tier": 4, # <- Tier 4!
"checks": ASSESSMENT_CHECKS, # <- Always 10
"issues": issue_count,
"detectors": {"review_assessment": {
"potential": ASSESSMENT_CHECKS,
"pass_rate": round(pass_rate, 4),
"issues": issue_count,
"weighted_failures": round(
ASSESSMENT_CHECKS * (1 - pass_rate), 4
),
}},
}
Key insight: Each assessment dimension pretends it has 10 potential checks. If the assessment score is 75, that's 7.5 "passes" and 2.5 "failures" out of 10.
3. Pass Rate & Weighted Failure Math
For Regular Detectors
_detector_pass_rate() (lines 84-161 in scoring.py) computes:
Assessment dimensions are tier-4 with ASSESSMENT_CHECKS=10 potential
If review_assessments = {"naming_quality": 75}:
checks = 10 (fixed)
pass_rate = 0.75
weighted_failures = 10 * (1 - 0.75) = 2.5
The weight factor = 4 * (10 / 200) = 0.2x
So a lone assessment dimension contributes only 20% of a tier-1 dimension
with full sample weight.
8. Security Handling & Zone Exclusion
Security findings (and by extension, review findings in test/config) are scored even in non-production zones:
Review is import-only: Never auto-resolved as "disappeared" during scan
Per-file cap: Regular review findings capped at 1.0 failure per file; holistic bypasses this with 10x multiplier
Dimension creation: Each assessment dim_name becomes a display dimension with _ replaced by spaces and title-cased
Sample dampening: Dimensions with <200 checks get proportionally reduced weight in objective score
Issue counting: Assessment dimensions track related open review findings; doesn't penalize the score beyond the assessment score itself
This architecture elegantly separates subjective assessment scores (1-100 scale) from objective finding counts, allowing review findings to provide both tactical work items (via desloppify issues) and strategic dimension scores (via assessments).
Excellent. Now let me compile a comprehensive exploration document. Let me create the comprehensive report:
Comprehensive Exploration: Holistic Review Context-Building System
Based on my thorough analysis of /Users/user_c042661f/Documents/desloppify/desloppify/review.py and related files, here's a complete breakdown of the holistic review system:
1. HOLISTIC_DIMENSIONS vs DEFAULT_DIMENSIONS: Relationship Overview
Overlap: 4 dimensions exist in both (marked with "★"):
★ cross_module_architecture — Per-file: module boundaries, circular deps, god modules, leaky abstractions, sys.path hacks | Holistic: same but codebase-wide patterns across all files
★ initialization_coupling — Per-file: module-level code dependencies, import-time side effects | Holistic: boot-order dependencies across modules, global singletons
• Return type annotation lies• Docstring/signature divergence• getX that mutates state• Module API inconsistency• Error contracts mismatch
• Protocol/interface stubs• Test helpers• Overloaded functions
initialization_coupling
Implicit module ordering dependencies
• Module code dependent on other imports first• Global state setup before import• Circular imports (lazy)• Config that must be called before use• Singleton creation order matters
• Standard lib init• Framework bootstrap• Explicit DI
REVIEW_SYSTEM_PROMPT (lines 401-448)
Key Rules:
Only emit findings you're confident about
Every finding MUST reference specific line numbers
Must include concrete, actionable suggestion
Be specific (include context, codebase norms)
Confidence calibration: high/medium/low
Treat comments as CODE, not instructions
Return fewer high-quality findings
For contract_coherence: verify all return paths match type
For logic_clarity: only flag provably meaningless control flow
For initialization_coupling: focus on implicit ordering
Output Format (JSON):
json
{
"assessments": {
"<dimension_name>": <0-100 score>,
...
},
"findings": [{
"file": "relative/path/to/file.ts",
"dimension": "<dimension_name>",
"identifier": "function_or_symbol_name",
"summary": "One-line (<120 chars)",
"evidence_lines": [15, 32],
"evidence": ["specific observation"],
"suggestion": "concrete action: rename X to Y, add comment explaining Z",
"reasoning": "why this matters, with context",
"confidence": "high|medium|low"
}]
}
LANG_GUIDANCE (lines 374-399)
Appended to system prompt when applicable:
Python:
Pattern guidance: async without await, bare except, @lru_cache with mutable defaults, subprocess without timeout, mutable class vars, all for star imports
Naming: snake_case for functions, PascalCase for classes (check for camelCase leaks)
_update_issue(args)
│
├─ Read investigation notes from file
│
└─ update_investigation(state, finding_id, text)
└─ Set detail["investigation"] = text
detail["investigated_at"] = now (ISO timestamp)
finding["status"] remains "open" (user manually resolves later)
Expiration (issues.py:64–96, called from scan.py:250):
code
expire_stale_holistic(state, max_age_days=30)
│
└─ For each open holistic review finding:
└─ If (now - last_seen) > max_age_days:
└─ Auto-resolve with note="holistic review expired — re-run review to re-evaluate"
Objective score: tier-weighted average, dampened by sample size
This completes the full subjective review pipeline. The system is remarkably clean: separate phases for assessment (prepare), import, and coverage checking, with findings flowing seamlessly into the scoring engine.
Design a comprehensive plan to hugely improve desloppify's cross-codebase subjective review system. The user specifically wants:
Better investigation batches — expand from 4 fixed to up to 6, incorporating new dimensions
Better prompts — calibration examples in system prompt, per-dimension evidence anchors, tighter "skip" guidance
Pre-computed heuristic signals — semi-automated metrics that feed into the context dict, so the reviewing agent has concrete numbers to work with (not just file lists)
Constraints
Everything in review.py is pure Python — no LLM calls
New context gathering must not dramatically slow down prepare (file cache is already used)
Keep review.py maintainable — consider if it should be split further
All new dimensions must have corresponding tests
Don't break existing import format — the agent output JSON schema should be additive only
Assessment dimensions auto-create tier-4 scoring dims, so new dimension names automatically work in scoring
Plan Structure
Think about:
Which dimensions to add and how they group into batches
What context data to gather for each new dimension
What pre-computed heuristic signals to add
How to improve prompts for all dimensions (not just new ones)
How to keep review.py from becoming unmanageable (it's already 1676 lines)
Testing strategy
Implementation order (what to do first for maximum impact)
Now I have a comprehensive picture of the full system. Let me design the plan.
Based on my thorough exploration of the codebase, here is the detailed plan.
1. File Structure: Split review.py Before Adding New Dimensions
Current problem: review.py is already 1724 lines and is monolithic. Adding 3 new holistic dimensions, 2 new per-file dimensions, richer context gathering, and improved prompts will push it past 2500 lines. The file already has 7 distinct sections (holistic dimensions/prompts, per-file dimensions/prompts, context builder, file selection, prepare/import, holistic review, remediation plan).
Proposed split -- convert desloppify/review.py into a desloppify/review/ package:
Module
Contents
Approx LOC
review/__init__.py
Re-exports for backward compat
~40
review/dimensions.py
All dimension lists + prompt dicts (both holistic and per-file), LANG_GUIDANCE, system prompts
~500
review/context.py
ReviewContext, build_review_context(), build_holistic_context(), all heuristic signal functions
This mirrors the existing pattern of narrative/ being split from narrative.py (documented in MEMORY.md Phase 7).
The __init__.py re-exports all public names so external imports (from desloppify.review import prepare_review) continue to work without any changes to callers. This is exactly the pattern used in desloppify/narrative/__init__.py.
2. New Dimensions
2a. New Holistic Dimensions (3)
Add to HOLISTIC_DIMENSIONS and HOLISTIC_DIMENSION_PROMPTS:
authorization_consistency
python
"authorization_consistency": {
"description": "RLS gaps, auth middleware inconsistency, permission model drift",
"look_for": [
"Tables with database access but no RLS policies (context shows table→policy mapping)",
"Sibling API routes/endpoints where some have auth middleware and others don't",
"Permission granularity mismatch: coarse RBAC in one area, fine-grained in another",
"Mixed trust boundaries: some routes trust client data, siblings validate server-side",
"Auth checks duplicated in handlers instead of centralized in middleware",
"Service role key usage that could use anon key + RLS instead",
],
"skip": [
"Public routes (health checks, login, static assets) intentionally without auth",
"Internal service-to-service calls with pre-validated tokens",
"Development-only endpoints behind feature flags",
],
}
ai_generated_debt
python
"ai_generated_debt": {
"description": "LLM-generated code hallmarks: restating comments, defensive overengineering, boilerplate bloat",
"look_for": [
"Restating comments that echo the code verbatim (// increment counter above counter++)",
"Excessive defensive null/type checks where the type system already guarantees safety",
"Wrapper functions that add no logic — just pass args through with a renamed interface",
"Docstring bloat: multi-paragraph docstrings on trivial 3-line functions",
"Debug logging that dumps entire objects or state at every function boundary",
"Generic variable names (data, result, item, temp, value) in domain-specific code",
"Try-catch around every operation including pure functions that cannot throw",
"Structural tells: functions split into tiny helpers that are called exactly once",
"Unused variables assigned but never read (often from destructuring templates)",
"Identical boilerplate error handling copied across many files verbatim",
],
"skip": [
"Comments explaining WHY or documenting business rules (not WHAT)",
"Defensive checks at API boundaries where input is genuinely untrusted",
"Generated code that is supposed to look mechanical (migrations, scaffolding)",
"Wrapper functions that add logging, auth, or error normalization",
],
}
incomplete_migration
python
"incomplete_migration": {
"description": "Stalled pattern migrations: old+new coexisting, deprecated-but-called, leftover shims",
"look_for": [
"Old API and new API patterns used side-by-side (context shows pattern pairs)",
"Deprecated functions/classes still actively called by non-deprecated code",
"Compatibility shims wrapping old interfaces that no caller still needs",
"Partial TypeScript migration: .js files coexisting with .ts files doing the same job",
"Migration TODOs older than 3 months (context provides TODO age analysis)",
"Mixed framework versions: React class components alongside functional in the same feature",
"Configuration files referencing removed features or old paths",
],
"skip": [
"Active, intentional migrations with tracked progress",
"Backward-compatible APIs maintained for external consumers",
"Gradual rollouts behind feature flags (intentional dual-path)",
],
}
2b. New Per-File Dimensions (2)
Add to DEFAULT_DIMENSIONS and DIMENSION_PROMPTS:
ai_generated_debt (per-file version)
python
"ai_generated_debt": {
"description": "Code with AI-generation hallmarks: restating comments, overengineering, boilerplate",
"look_for": [
"Comments that restate the code on the line below or above verbatim",
"Multi-paragraph docstrings on trivial one-liner functions",
"Try-catch wrapping pure functions or expressions that cannot throw",
"Wrapper functions with no added logic — pure pass-through",
"Sequential console.log/debug calls that should be a single structured log",
"Generic names (data, result, item, response) where domain names would be clearer",
"Defensive null checks on values the type system already guarantees non-null",
],
"skip": [
"Comments explaining business rules, workarounds, or non-obvious behavior",
"Defensive checks at module boundaries or user input sites",
"Thin wrappers that add logging, auth, validation, or error normalization",
],
}
authorization_coherence (per-file version)
python
"authorization_coherence": {
"description": "Auth/validation consistency within a single file or module",
"look_for": [
"Auth check on some handler functions but not sibling handlers in the same file",
"Permission checks that reference roles as magic strings instead of constants",
"Input validation on some parameters but not sibling parameters of the same type",
"Mixed auth strategies: session check in one handler, JWT in another in the same router",
"Service role or admin bypass without audit logging",
],
"skip": [
"Public endpoints explicitly documented as auth-free",
"Internal utility functions that callers already validated for",
"Test files",
],
}
These new context sections feed into build_holistic_context() and build_review_context() so the reviewing agent has concrete numbers. All are computed in pure Python from file contents already read into the file cache.
3a. Auth/RLS Context (for authorization_consistency and authorization_coherence)
Add to build_holistic_context() as section 9: "authorization":
python
def _gather_auth_context(file_contents: dict[str, str], is_ts: bool) -> dict:
"""Gather auth/RLS patterns from file contents."""
auth_ctx = {}
# 1. Auth middleware usage per route file
# TS: detect express/fastify/Next.js middleware patterns
# PY: detect Django/FastAPI/Flask decorator-based auth
route_files = {}
for filepath, content in file_contents.items():
if _is_route_file(filepath, content, is_ts):
handlers = _extract_handlers(content, is_ts)
auth_checks = _count_auth_patterns(content, is_ts)
route_files[rel(filepath)] = {
"handler_count": len(handlers),
"handlers_with_auth": auth_checks,
"handlers_without_auth": len(handlers) - auth_checks,
}
if route_files:
auth_ctx["route_auth_coverage"] = route_files
# 2. RLS/table policy mapping (SQL files)
tables_with_rls = set()
tables_without_rls = set()
for filepath, content in file_contents.items():
if filepath.endswith(".sql") or "migration" in filepath.lower():
_parse_rls_policies(content, tables_with_rls, tables_without_rls)
if tables_with_rls or tables_without_rls:
auth_ctx["rls_coverage"] = {
"tables_with_policies": sorted(tables_with_rls),
"tables_without_policies": sorted(tables_without_rls),
}
# 3. Supabase createClient patterns (service role vs anon)
if is_ts:
service_role_files = []
anon_files = []
for filepath, content in file_contents.items():
if "createClient" in content:
if "SERVICE_ROLE" in content or "service_role" in content:
service_role_files.append(rel(filepath))
else:
anon_files.append(rel(filepath))
if service_role_files:
auth_ctx["service_role_usage"] = service_role_files
if anon_files:
auth_ctx["anon_key_usage"] = anon_files
return auth_ctx
Add to build_review_context() context and build_holistic_context() as section 10: "ai_debt_signals":
python
def _gather_ai_debt_signals(file_contents: dict[str, str]) -> dict:
"""Compute per-file AI-generated-debt heuristic signals."""
file_signals = {}
for filepath, content in file_contents.items():
lines = content.splitlines()
loc = len(lines)
if loc < 10:
continue
# 1. Comment-to-code ratio
comment_lines = sum(1 for l in lines if l.strip().startswith(("#", "//", "*", "/*")))
comment_ratio = comment_lines / loc if loc else 0
# 2. Docstring-to-body ratio for functions
# (high ratio = potential bloat)
# 3. Guard clause density (try/if at start of functions)
guard_count = len(re.findall(r"^\s+(?:if\s+.*(?:is None|== None|=== null|=== undefined)|try\s*[:{])", content, re.MULTILINE))
guard_density = guard_count / max(1, _count_functions(content))
# 4. Log density per function
log_count = len(re.findall(r"\b(?:console\.log|print|logger\.(?:debug|info|warn))\b", content))
log_density = log_count / max(1, _count_functions(content))
# 5. Generic name ratio
generic_names = len(re.findall(r"\b(?:data|result|item|temp|value|response|output|input|obj|arr|val)\b", content))
name_count = len(_FUNC_NAME_RE.findall(content))
signals = {}
if comment_ratio > 0.3:
signals["high_comment_ratio"] = round(comment_ratio, 2)
if log_density > 3.0:
signals["high_log_density"] = round(log_density, 1)
if guard_density > 2.0:
signals["high_guard_density"] = round(guard_density, 1)
if signals:
file_signals[rel(filepath)] = signals
# Aggregate signals
return {
"file_signals": dict(sorted(file_signals.items(), key=lambda x: -len(x[1]))[:20]),
"codebase_avg_comment_ratio": _avg_ratio(file_contents),
}
3c. Migration Context (for incomplete_migration)
Add to build_holistic_context() as section 11: "migration_signals":
python
def _gather_migration_signals(file_contents: dict[str, str], is_ts: bool) -> dict:
"""Detect signs of incomplete migrations."""
signals = {}
# 1. Deprecated marker usage
deprecated_count = 0
deprecated_files = []
for filepath, content in file_contents.items():
count = len(re.findall(r"@deprecated|@Deprecated|\bDEPRECATED\b", content))
if count:
deprecated_count += count
deprecated_files.append({"file": rel(filepath), "count": count})
if deprecated_files:
signals["deprecated_markers"] = {
"total": deprecated_count,
"files": sorted(deprecated_files, key=lambda x: -x["count"])[:15],
}
# 2. Migration TODOs (with age estimation from git blame if fast enough, else just count)
migration_todos = []
for filepath, content in file_contents.items():
for m in re.finditer(r"(?:TODO|FIXME|HACK)\s*:?\s*(.*migrat|.*legacy|.*deprecat|.*old api|.*remove after)", content, re.IGNORECASE):
migration_todos.append({"file": rel(filepath), "text": m.group(0)[:100]})
if migration_todos:
signals["migration_todos"] = migration_todos[:20]
# 3. Pattern pairs (old + new coexisting)
if is_ts:
_detect_ts_pattern_pairs(file_contents, signals)
else:
_detect_py_pattern_pairs(file_contents, signals)
# 4. Mixed file extensions (JS + TS for same module names)
if is_ts:
js_files = {Path(f).stem for f in file_contents if f.endswith(".js") or f.endswith(".jsx")}
ts_files = {Path(f).stem for f in file_contents if f.endswith(".ts") or f.endswith(".tsx")}
overlap = js_files & ts_files
if overlap:
signals["mixed_extensions"] = sorted(overlap)[:20]
return signals
TS pattern pairs to detect:
Class components + functional components in same feature area
axios + fetch usage
moment + dayjs or date-fns
Redux + Context API
var + let/const
Python pattern pairs:
format() + f-strings
os.path + pathlib
unittest + pytest style tests
print + logging
3d. Enriched Existing Context
Module-level IO scan (currently limited to first 50 lines):
Change the coupling detection in _build_holistic_context_inner() to scan all module-level lines (lines before the first def/class at column 0), not just the first 50. This catches import-time side effects that occur after the import block.
Richer error strategy detection:
Add a per-file error strategy classification to build_review_context() in error_conventions:
python
# For each file, classify its primary error strategy
# Returns: {"file": "src/foo.ts", "strategy": "throw", "has_mixed": True}
Per-file ReviewContext addition (ai_debt_signals):
Add ai_debt_signals: dict field to ReviewContext dataclass for per-file AI debt metrics.
4. Investigation Batch Expansion
Expand from 4 fixed batches to up to 6, incorporating new dimensions. In _build_investigation_batches():
python
# Batch 1: Architecture & Coupling (unchanged)
# Batch 2: Conventions & Errors (unchanged)
# Batch 3: Abstractions & Dependencies (unchanged)
# Batch 4: Testing & API (unchanged)
# Batch 5: Authorization & Security (NEW)
# dimensions: ["authorization_consistency"]
# files: route files with auth gaps, SQL files with missing RLS
# Batch 6: AI Debt & Migrations (NEW)
# dimensions: ["ai_generated_debt", "incomplete_migration"]
# files: top files by AI debt signals, files with deprecated markers, migration TODOs
The new batches only appear when their context data is non-empty (same pattern as existing batches), so codebases without routes or migrations won't get empty batches.
5. Prompt Improvements
5a. Calibration Examples in System Prompts
Add a CALIBRATION_EXAMPLES section to both REVIEW_SYSTEM_PROMPT and HOLISTIC_REVIEW_SYSTEM_PROMPT:
python
CALIBRATION_EXAMPLES = """
CALIBRATION — score these examples as reference:
HIGH confidence (any senior eng agrees):
- Function named `getUser` that mutates database state → naming_quality finding
- Identical catch blocks in 4/5 service files → error_consistency finding
- Comment says "validates input" but validation was removed 3 commits ago → comment_quality
MEDIUM confidence (most would agree):
- 8-parameter function that could take an options object → abstraction_fitness
- Mixed snake_case/camelCase in 60% of files in the same directory → convention_outlier
LOW confidence (reasonable disagreement):
- Single-implementation interface used for dependency injection → abstraction_fitness (SKIP — DI is valid)
- Verbose logging in a payment processing module → logging_quality (SKIP — sensitive operations warrant extra logging)
NON-FINDINGS (do NOT emit):
- Framework boilerplate (React hooks, Express middleware signatures)
- Standard patterns that look verbose to unfamiliar readers but are idiomatic
- Style preferences not backed by a concrete risk or maintenance cost
"""
5b. Per-Dimension Evidence Anchors
Add an evidence_anchors key to each dimension prompt (both holistic and per-file):
python
"naming_quality": {
# ... existing fields ...
"evidence_anchors": [
"Function X is called in contexts {A, B, C} — its name should reflect the common use case",
"Codebase convention for this directory uses prefix 'fetch' but this function uses 'get'",
],
}
This gives the reviewing agent concrete sentence templates to fill in, improving finding specificity.
5c. Tighter Skip Guidance
Add explicit quantitative thresholds to skip guidance where possible:
python
"skip": [
"Files in directories with <3 siblings (no convention to diverge from)",
"Functions with <3 lines (naming is less critical for trivial helpers)",
"Modules with <20 LOC (insufficient code to meaningfully evaluate)",
]
Update _serialize_context() to include new fields.
7. Scoring Integration
New assessment dimensions auto-create tier-4 scoring dims via compute_dimension_scores() -- the review_assessments mechanism handles this automatically. No changes needed to scoring.py.
The only change is ensuring the import_review_findings() and import_holistic_findings() validators accept the new dimension names. Currently they validate against DIMENSION_PROMPTS and HOLISTIC_DIMENSION_PROMPTS respectively, so adding the new dimensions to those dicts is sufficient.
8. Testing Strategy
New test file: tests/test_review_context.py
Tests for the new context gathering functions:
_gather_auth_context() with mock route files, SQL files, Supabase patterns
_gather_ai_debt_signals() with mock files having varying comment ratios, log densities
_gather_migration_signals() with deprecated markers, TODO patterns, mixed extensions
Integration test: build_holistic_context() returns new sections when data exists
Integration test: build_review_context() returns new fields
Updates to tests/test_review.py
Update TestHolisticConstants.test_eight_dimensions to expect 11 dimensions
Add TestNewDimensions tests for ai_generated_debt, authorization_coherence
Add TestImportReviewFindings tests for new dimension validation
Add TestAssessmentImport tests with new dimension names
Updates to tests/test_holistic_review.py
Update dimension count assertion
Add tests for new investigation batches (batch 5, batch 6)
Add tests for authorization_consistency, ai_generated_debt, incomplete_migration import validation
New test file: tests/test_review_split.py
Verify __init__.py re-exports all public names
Verify backward compatibility of from desloppify.review import X for all existing public names
Verify no circular imports in the new package structure
9. Implementation Order
Phase 1: Split review.py into review/ package (highest risk, do first)
Create desloppify/review/ directory
Move code into 7 modules as described above
Create __init__.py with full re-exports
Run full test suite to verify no regressions
Add tests/test_review_split.py for import compatibility
Phase 2: New holistic dimensions + prompts (additive, low risk)
Add 3 new holistic dimensions to review/dimensions.py
Add corresponding prompts with evidence anchors
Update tests for dimension count and validation
Phase 3: New per-file dimensions + prompts (additive, low risk)
Add 2 new per-file dimensions
Add corresponding prompts with evidence anchors
Update tests
Phase 4: Pre-computed heuristic signals (medium risk, pure Python)
Implement _gather_auth_context() in review/context.py
Implement _gather_ai_debt_signals() in review/context.py
Implement _gather_migration_signals() in review/context.py
Wire into build_holistic_context() and build_review_context()
Update ReviewContext dataclass
Add comprehensive tests in tests/test_review_context.py
Phase 5: Investigation batch expansion (depends on Phase 4)
Add batch 5 (Authorization) and batch 6 (AI Debt & Migrations) to _build_investigation_batches()
Update tests for batch count and content
Phase 6: Prompt improvements (independent, can be done in parallel)
Add calibration examples to system prompts
Add evidence anchors to all dimension prompts (existing + new)
Tighten skip guidance with quantitative thresholds
Update LANG_GUIDANCE with auth-related patterns
Phase 7: Enriched existing context (independent)
Fix module-level IO scan to go beyond first 50 lines
Add per-file error strategy classification
Update tests
10. Risks and Mitigations
Risk: Performance regression from new context gathering.
Mitigation: All new context functions iterate over file_contents dict (already loaded). No additional filesystem reads. The file cache is already enabled during prepare. Regex patterns are pre-compiled. The auth/RLS context only processes files matching route/SQL patterns (filtered early).
Risk: Breaking existing import paths when splitting review.py.
Mitigation: The __init__.py re-exports every public name. Test suite has 1543 tests that will catch import failures. Add explicit import compatibility test.
Risk: New dimensions being low-value noise.
Mitigation: All new dimensions have tight skip guidance. The ai_generated_debt dimension is the highest-value addition since it catches a class of issues (LLM-generated code debt) that no other tool detects. The authorization_consistency dimension is critical for security-sensitive codebases. The incomplete_migration dimension catches a common source of tech debt. All three are configurable via --dimensions and can be excluded.
Risk: Query.json growing too large for agent context windows.
Mitigation: Context sections have explicit caps (20 files max per section, 15 files per batch). The holistic context is a summary dict with numbers, not raw file contents. Per-file review sends file contents (unavoidable) but the new context sections add only metadata (~2-5KB).
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/review.py - Must be split into review/ package; contains all 1724 lines of context gathering, prompts, import/export, and preparation logic
/Users/user_c042661f/Documents/desloppify/desloppify/scoring.py - Assessment dimension scoring integration; verify new dimensions auto-create properly via review_assessments mechanism
/Users/user_c042661f/Documents/desloppify/tests/test_review.py - Primary test file (1676 lines); must update dimension counts, add new dimension validation tests, verify split compatibility
/Users/user_c042661f/Documents/desloppify/tests/test_holistic_review.py - Holistic review tests (1051 lines); must update for 11 dimensions, new batches, new import validation
/Users/user_c042661f/Documents/desloppify/desloppify/narrative/headline.py - Headline computation that already handles security prefix and review suffix; pattern to follow for any new dimension-specific narrative logic
• Inconsistent parameter ordering/naming• Mixed sync/async in same module• Overloaded interfaces• Missing error contracts• Functions with >5 params
• Excessive sequential debug logs• Missing context• Inconsistent log levels• Sensitive data in logs• Print in production
• Log verbosity in test/debug• Intentional minimalism in hot paths
type_safety
Type annotations match runtime
• Return types not covering all paths• Params typed X, called with Y• Union types that could narrow• Missing annotations on public API• Type: ignore without explanation
• Untyped private helpers• Dynamic framework code• Test code