Thoroughly explore the review system in this codebase. I need to understand:
desloppify/review.py - the full review module: what it does, its data structures, how review_cache works, content hashes, staleness tracking
desloppify/commands/review_cmd.py - the CLI command, what subcommands exist (prepare, evaluate, import, etc.)
tests/test_review.py - existing tests
For each file, read the FULL contents. I need to understand:
What data structures does review use (ReviewFinding, review_cache schema, etc.)
How does prepare work — file selection, priority, staleness
How does finding import work — how do review findings get into the state
What dimensions does the review evaluate
How is review_cache stored and structured in state
Be very thorough — read every file completely.
Assistant
I'll thoroughly explore the review system in this codebase. Let me start by reading the key files you've mentioned.
User
Thoroughly explore the scan pipeline and scoring system. I need to understand:
desloppify/commands/scan.py - the full scan command: what phases run, how findings are collected, how narrative is computed, how score is reported
desloppify/scoring.py - the scoring system: dimensions, how scores are computed, what dimensions exist, how findings map to dimensions
desloppify/registry.py - the detector registry: how detectors are registered, what metadata they carry
desloppify/plan.py - how the scan plan is built, what phases exist
desloppify/narrative/core.py and desloppify/narrative/strategy.py - how narrative suggests next actions
Read each file FULLY. I need to understand:
The complete list of scoring dimensions and how they work
How a new detector/dimension gets wired into the pipeline
How the scan command orchestrates phases
How narrative/strategy decides what to suggest next
The DetectorMeta structure in registry.py
Assistant
I'll thoroughly explore the scan pipeline and scoring system. Let me start by reading these key files in parallel.
Assistant
Let me also read the narrative package constants and a few more files to complete the picture:
User
Explore the state management and language base infrastructure:
desloppify/state.py - full state management: how findings are stored, upserted, the Finding TypedDict, how review_cache is stored in state
desloppify/lang/base.py - LangConfig base class: what methods exist, how phases are defined (phase_smells, phase_security, etc.), FixerConfig, FixResult
desloppify/enums.py - all enums (Confidence, Status, Tier)
desloppify/narrative/actions.py - how next actions are computed
Read each file FULLY. I need to understand:
How review_cache is stored in state (is it a top-level key? what's the schema?)
The Finding TypedDict structure
How _upsert_findings works
How DETECTOR_TOOLS maps detectors to tool suggestions
What phases exist on LangConfig
Assistant
I'll explore the state management and language base infrastructure by reading each file fully.
Assistant
Now let me read the narrative constants file:
Assistant
Assistant
Assistant
User
Assistant
I'll explore the codebase to understand the existing patterns and then design a detailed implementation plan.
Assistant
Now let me look at how the TypeScript and Python plugins register their phases, and the narrative actions module.
Assistant
Now let me check the TS plugin's phase registration to see the pattern for adding a new phase.
Assistant
Now let me check the existing review command and the narrative headline module.
Assistant
Now I have a thorough understanding of the codebase. Let me look at one more thing -- how _find_suspect_detectors handles the review detector to understand the auto-resolve risk.
Assistant
Perfect! I've now read all five files. Let me provide you with a comprehensive summary of the infrastructure:
Summary: State Management and Language Base Infrastructure
1. Finding TypedDict (state.py, lines 18-36)
The Finding TypedDict is the central data structure:
python
class Finding(TypedDict):
"""The central data structure — a normalized finding from any detector."""
id: str # e.g., "detector::file::name"
detector: str # detector that found it
file: str # relative file path
tier: int # 1-4 (AUTO_FIX, QUICK_FIX, JUDGMENT, MAJOR_REFACTOR)
confidence: str # "high" | "medium" | "low"
summary: str # user-facing title
detail: dict # detector-specific metadata
status: str # "open" | "resolved" | "wontfix" | "false_positive"
note: str | None # manual user note
first_seen: str # ISO timestamp
last_seen: str # ISO timestamp
resolved_at: str | None # when marked non-open
reopen_count: int # times bounced between resolved/open
# Stamped post-creation (in plan.py):
lang: NotRequired[str] # language (python/typescript)
zone: NotRequired[str] # file zone (production/test/config/generated/script/vendor)
Key insight: lang and zone are stamped AFTER creation in plan.py, not during detection.
2. Review Cache Storage
Important: I did NOT find review_cache in state.py. The state structure only contains:
version: schema version
created: when state file first created
last_scan: timestamp of most recent scan
scan_count: total scans run
config: user ignore patterns
score / strict_score: weighted progress scores
stats: counters by status/tier
findings: dict[id, Finding]
potentials: per-lang detector potential discovery data
codebase_metrics: per-lang metrics
scan_completeness: per-lang "full" or "fast"
scan_history: last 20 scan entries for trajectory tracking
dimension_scores: objective health scores per dimension
objective_score / objective_strict: rolled-up health scores
No review_cache key exists in the base state. If it's being stored somewhere, it must be either:
In a separate file (like .desloppify/review.json)
In a memory-only structure
Not yet implemented
3. _upsert_findings Function (state.py, lines 316-350)
Iterates current findings and applies ignore patterns
For EXISTING findings: updates last_seen, tier, confidence, summary, detail; optionally stamps zone if present; reopens if it was "fixed"/"auto_resolved"
For NEW findings: inserts with initial status "open"
Zone stamping: If f["zone"] is present in current finding, updates existing old["zone"] (line 338). This is how zones propagate from plan.py into the persisted state.
4. DETECTOR_TOOLS Mapping (narrative/init.py imports from _constants)
The DETECTOR_TOOLS dict maps detector names to tool metadata. Based on actions.py usage (lines 31-90), the structure is:
python
DETECTOR_TOOLS = {
"detector_name": {
"action_type": "auto_fix" | "reorganize" | "refactor" | "manual_fix",
"fixers": ["fixer_name_1", ...], # for auto_fix type
"guidance": "user-facing description", # for refactor/reorganize
},
...
}
Calls merge_scan() to merge findings into state (deduplicates, auto-resolves if detector appears in potentials)
Calls _update_review_cache() to update cache with reviewed files
Review Cache Update (lines 704-719):
Iterates reviewed files
Computes content_hash of current file
Stores: content_hash, reviewed_at (ISO timestamp), finding_count
2. desloppify/commands/review_cmd.py — The CLI Command
Command Structure:
Main entry (cmd_review, lines 10-28):
Loads state and resolves language
Routes to _do_prepare() or _do_import() based on --import-file flag
Prepare Mode (_do_prepare, lines 31-62):
Reads args:
path: scan path
max_files: default 50
max_age: default 30 days
refresh: force-refresh flag (bool)
dimensions: comma-separated list or None
Flow:
Calls _setup_lang() to build zone map and dep graph
Calls prepare_review() with selected options
Writes result via _write_query(data) to .desloppify/query.json
Prints summary: file count, cache status, dimensions
Output to user:
code
Review prepared: N files to review
Cache: X fresh, Y stale, Z new
Dimensions: naming_quality, comment_quality, ...
→ query.json updated. Review files, then: desloppify review --import findings.json
Zone Map Construction — If language has zone_rules, builds a FileZoneMap that classifies each file into zones (production/test/config/generated/script/vendor)
Phase Execution — Iterates through all detector phases from lang.phases:
Each phase has: label, slow (bool), run() method
run() returns (findings, potentials) tuple
Findings Normalization:
Each finding is a dict with: id, detector, file, tier, confidence, summary, detail, status
Detector stamps language and zone onto each finding post-detection
Zone policy confidence downgrades applied (e.g., test zone downgrades certain detectors to "low")
Dimension must exist in scoring.py DIMENSIONS list
Detector name added to that dimension's detectors list
Implement detector in lang plugin (e.g., lang/typescript/detectors/my_detector.py):
Return (findings, potentials) tuple
Each finding dict with: id, detector, file, tier, confidence, summary, detail, status
Create phase wrapper in lang/base.py:
python
class DetectorPhase:
label = "My detector..."
slow = False # or True if CPU-intensive
def run(self, path, lang):
# Call detect_my_detector() or similar
# Return (findings, {"my_detector": potential_count})
All 23 detectors map uniquely to 14 dimensions. One detector can't be in two dimensions, but multiple detectors in one dimension scale the dimension's weight.
Example: "Code quality" dimension has 3 detectors (smells, react, dict_keys), so issues in any of them impact the same dimension score.
This completes the comprehensive exploration. The system is highly modular: detectors are pluggable, dimensions are composable, and the narrative system is pure and extensible.
Design an implementation plan for integrating review coverage tracking into the desloppify scan pipeline.
Context
The desloppify project has an existing review system (review.py, commands/review_cmd.py) that does subjective code review via an external LLM. It produces findings with detector="review" that are imported manually. These map to the "Design quality" scoring dimension (tier 4).
The problem: the review system is completely disconnected from the scan pipeline. A codebase can score 100/100 without ever running a review. The user wants review coverage/staleness tracking to be part of every scan.
Current Architecture
Scan pipeline (plan.py):
generate_findings() builds zone map on lang._zone_map, then iterates lang.phases (list of DetectorPhase)
Each phase's run(path, lang) returns (findings, potentials)
Findings are stamped with lang/zone post-phase
Cross-lang phases like phase_test_coverage and phase_security are in lang/base.py
Scoring (scoring.py):
14 dimensions, each with detectors list. "Design quality" = ["review"]
desloppify/state.py — protect review detector from auto-resolve
desloppify/narrative/actions.py — suggest review --prepare for review_coverage findings
Tests — comprehensive tests
Please design the detailed implementation plan with specific code changes for each file.
I now have a complete picture. Here is the detailed implementation plan.
Implementation Plan: Review Coverage Tracking in the Scan Pipeline
Overview
Introduce a review_coverage detector that runs during every scan to track which production files have never been reviewed or have stale reviews. This creates a continuous feedback loop where the "Design quality" scoring dimension reflects both imported review findings AND review coverage gaps.
Architecture Decision: Separate review_coverage Detector
The key design insight: review_coverage is a scan-time detector (like test_coverage) while review is an import-time detector (external LLM findings). They both contribute to the "Design quality" dimension but have completely independent lifecycles. This separation means:
Scan never touches review findings (no auto-resolve risk)
Purpose: Core detection logic, following the pattern of detectors/test_coverage.py.
Function signature:
python
def detect_review_coverage(
files: list[str],
zone_map, # FileZoneMap | None
review_cache: dict, # state["review_cache"]["files"]
lang_name: str,
*,
max_age_days: int = 30,
) -> tuple[list[dict], int]:
"""Detect unreviewed and stale-reviewed production files.
Returns (entries, potential) where potential = number of reviewable production files.
"""
Logic:
Filter files to production zone only (skip test/generated/vendor), using zone_map.get(f).value
Apply the same filtering as review.py's _compute_review_priority: skip files < _MIN_REVIEW_LOC (20 LOC), skip _LOW_VALUE_NAMES pattern matches
Count remaining files as potential (total reviewable files)
For each reviewable file, check review_cache:
Never reviewed: file not in cache at all -- emit entry with sub_type="unreviewed", confidence "low", tier 4
Stale review: file in cache but reviewed_at is older than max_age_days -- emit entry with sub_type="stale", confidence "low", tier 4
Content changed: file in cache, age is fresh, but content_hash doesn't match current _hash_file() -- emit entry with sub_type="changed", confidence "medium", tier 4
Fresh: skip (no finding)
Return (entries, potential)
Entry format (matches existing detector conventions):
Confidence calibration: All review_coverage findings use "low" confidence except "changed" (content changed since last review) which gets "medium". This keeps the score impact modest -- review coverage is a gentle nudge, not a blocker. With CONFIDENCE_WEIGHTS["low"] = 0.3, even a large number of unreviewed files won't dominate the score.
Import the _hash_file, _LOW_VALUE_NAMES, and _MIN_REVIEW_LOC from review.py to share the exact same filtering logic (DRY).
This is critical. Since review_coverage emits per-file findings and potential = file count, per-file weighted failures must be capped at 1.0 like the other file-based detectors.
Change: Protect review detector from auto-resolve by adding it to suspect detectors unconditionally when it has findings.
In _find_suspect_detectors, add special handling for review:
python
def _find_suspect_detectors(
existing: dict, current_by_detector: dict[str, int], force_resolve: bool,
ran_detectors: set[str] | None = None,
) -> set[str]:
if force_resolve:
return set()
prev: dict[str, int] = {}
for f in existing.values():
if f["status"] == "open":
det = f.get("detector", "unknown")
prev[det] = prev.get(det, 0) + 1
# Always protect "review" — it's imported externally, never produced by scan
_IMPORT_ONLY_DETECTORS = {"review"}
suspect = set()
for det, n in prev.items():
# Import-only detectors are always suspect (scan never produces them)
if det in _IMPORT_ONLY_DETECTORS:
suspect.add(det)
continue
if current_by_detector.get(det, 0) > 0:
continue
if ran_detectors is not None and det in ran_detectors:
continue
if n >= 3:
suspect.add(det)
return suspect
This is the most important safety fix. Currently, review findings with fewer than 3 entries would be auto-resolved when a scan runs (because review is never in ran_detectors and n < 3). The _IMPORT_ONLY_DETECTORS set makes this explicit and unconditional.
This is needed because the default action loop would generate desloppify show review_coverage --status open, which is informational but not actionable. The correct action is to run a review.
Note: We should also ensure the review_coverage entry in DETECTOR_TOOLS (derived from registry) has action_type="manual_fix" -- this is already handled by the registry entry in step 2.
Change: Add review coverage callout similar to the security callout.
In _compute_headline, add a review coverage prefix when there are many unreviewed files:
python
# Review coverage callout — when >50% of files are unreviewed
review_cov_count = (open_by_detector or {}).get("review_coverage", 0)
review_cov_suffix = ""
if review_cov_count > 20: # Only call out when significant
review_cov_suffix = f" Run `desloppify review --prepare` to start a design review."
Append this to the headline where appropriate (only in certain phases like first_scan, early_momentum, middle_grind).
test_review_not_auto_resolved: review findings survive a scan without being auto-resolved (test the _IMPORT_ONLY_DETECTORS fix)
test_file_based_detector_cap: Multiple review_coverage findings per file have their weighted failures capped at 1.0
Key Design Decisions and Rationale
Why confidence="low" for most findings: Review coverage gaps are informational nudges, not bugs. With CONFIDENCE_WEIGHTS["low"] = 0.3, even 50 unreviewed files out of 100 potential would only reduce the dimension score by about 15% (50 * 0.3 / 100 = 15% weighted failures). This keeps the "Design quality" dimension from being dominated by coverage gaps -- imported review findings (which are "medium" or "high" confidence) should have more weight.
Why tier=4: Review coverage is a "major refactor" tier item. It requires external LLM review, which is a heavyweight operation. Tier 4 keeps these findings at the bottom of the priority list in desloppify next.
Why file-based detector: Potential = reviewable file count. A single file can have at most one review_coverage finding (unreviewed OR stale OR changed, not all three). This matches the _FILE_BASED_DETECTORS cap pattern.
Why protect review unconditionally: The current _find_suspect_detectors has a n >= 3 threshold. If a user imports 1-2 review findings and then runs a scan, those findings would be auto-resolved because review is not in ran_detectors and count is below 3. This is a pre-existing bug that this change fixes.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/detectors/review_coverage.py - New file: core detection logic for review coverage gaps
/Users/user_c042661f/Documents/desloppify/desloppify/state.py - Critical safety fix: protect review findings from auto-resolve
/Users/user_c042661f/Documents/desloppify/desloppify/lang/base.py - Shared phase runner + LangConfig field addition
/Users/user_c042661f/Documents/desloppify/desloppify/scoring.py - Wire review_coverage into "Design quality" dimension
/Users/user_c042661f/Documents/desloppify/desloppify/registry.py - Register detector metadata (single source of truth)